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  package io.netty.handler.codec.http2;
16  
17  import io.netty.buffer.ByteBuf;
18  import io.netty.buffer.ByteBufUtil;
19  import io.netty.buffer.Unpooled;
20  import io.netty.channel.ChannelFuture;
21  import io.netty.channel.ChannelFutureListener;
22  import io.netty.channel.ChannelHandlerContext;
23  import io.netty.channel.ChannelOutboundHandler;
24  import io.netty.channel.ChannelPromise;
25  import io.netty.handler.codec.ByteToMessageDecoder;
26  import io.netty.handler.codec.http.HttpResponseStatus;
27  import io.netty.handler.codec.http2.Http2Exception.CompositeStreamException;
28  import io.netty.handler.codec.http2.Http2Exception.StreamException;
29  import io.netty.util.CharsetUtil;
30  import io.netty.util.concurrent.Future;
31  import io.netty.util.concurrent.PromiseNotifier;
32  import io.netty.util.internal.logging.InternalLogger;
33  import io.netty.util.internal.logging.InternalLoggerFactory;
34  
35  import java.net.SocketAddress;
36  import java.util.HashSet;
37  import java.util.List;
38  import java.util.Set;
39  import java.util.concurrent.TimeUnit;
40  
41  import static io.netty.buffer.ByteBufUtil.hexDump;
42  import static io.netty.buffer.Unpooled.EMPTY_BUFFER;
43  import static io.netty.handler.codec.http2.Http2CodecUtil.HTTP_UPGRADE_STREAM_ID;
44  import static io.netty.handler.codec.http2.Http2CodecUtil.connectionPrefaceBuf;
45  import static io.netty.handler.codec.http2.Http2CodecUtil.getEmbeddedHttp2Exception;
46  import static io.netty.handler.codec.http2.Http2Error.INTERNAL_ERROR;
47  import static io.netty.handler.codec.http2.Http2Error.NO_ERROR;
48  import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
49  import static io.netty.handler.codec.http2.Http2Exception.connectionError;
50  import static io.netty.handler.codec.http2.Http2Exception.isStreamError;
51  import static io.netty.handler.codec.http2.Http2FrameTypes.SETTINGS;
52  import static io.netty.handler.codec.http2.Http2Stream.State.IDLE;
53  import static io.netty.util.CharsetUtil.UTF_8;
54  import static io.netty.util.internal.ObjectUtil.checkNotNull;
55  import static java.lang.Math.min;
56  import static java.util.concurrent.TimeUnit.MILLISECONDS;
57  
58  /**
59   * Provides the default implementation for processing inbound frame events and delegates to a
60   * {@link Http2FrameListener}
61   * <p>
62   * This class will read HTTP/2 frames and delegate the events to a {@link Http2FrameListener}
63   * <p>
64   * This interface enforces inbound flow control functionality through
65   * {@link Http2LocalFlowController}
66   */
67  public class Http2ConnectionHandler extends ByteToMessageDecoder implements Http2LifecycleManager,
68                                                                              ChannelOutboundHandler {
69  
70      private static final InternalLogger logger = InternalLoggerFactory.getInstance(Http2ConnectionHandler.class);
71  
72      private static final Http2Headers HEADERS_TOO_LARGE_HEADERS = ReadOnlyHttp2Headers.serverHeaders(false,
73              HttpResponseStatus.REQUEST_HEADER_FIELDS_TOO_LARGE.codeAsText());
74      private static final ByteBuf HTTP_1_X_BUF = Unpooled.unreleasableBuffer(
75          Unpooled.wrappedBuffer(new byte[] {'H', 'T', 'T', 'P', '/', '1', '.'})).asReadOnly();
76  
77      private final Http2ConnectionDecoder decoder;
78      private final Http2ConnectionEncoder encoder;
79      private final Http2Settings initialSettings;
80      private final boolean decoupleCloseAndGoAway;
81      private final boolean flushPreface;
82      private ChannelFutureListener closeListener;
83      private BaseDecoder byteDecoder;
84      private long gracefulShutdownTimeoutMillis;
85      private boolean inFlush;
86      private boolean flushAgain;
87  
88      protected Http2ConnectionHandler(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder,
89                                       Http2Settings initialSettings) {
90          this(decoder, encoder, initialSettings, false);
91      }
92  
93      protected Http2ConnectionHandler(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder,
94                                       Http2Settings initialSettings, boolean decoupleCloseAndGoAway) {
95          this(decoder, encoder, initialSettings, decoupleCloseAndGoAway, true);
96      }
97  
98      protected Http2ConnectionHandler(Http2ConnectionDecoder decoder, Http2ConnectionEncoder encoder,
99                                       Http2Settings initialSettings, boolean decoupleCloseAndGoAway,
100                                      boolean flushPreface) {
101         this.initialSettings = checkNotNull(initialSettings, "initialSettings");
102         this.decoder = checkNotNull(decoder, "decoder");
103         this.encoder = checkNotNull(encoder, "encoder");
104         this.decoupleCloseAndGoAway = decoupleCloseAndGoAway;
105         this.flushPreface = flushPreface;
106         if (encoder.connection() != decoder.connection()) {
107             throw new IllegalArgumentException("Encoder and Decoder do not share the same connection object");
108         }
109     }
110 
111     /**
112      * Get the amount of time (in milliseconds) this endpoint will wait for all streams to be closed before closing
113      * the connection during the graceful shutdown process. Returns -1 if this connection is configured to wait
114      * indefinitely for all streams to close.
115      */
116     public long gracefulShutdownTimeoutMillis() {
117         return gracefulShutdownTimeoutMillis;
118     }
119 
120     /**
121      * Set the amount of time (in milliseconds) this endpoint will wait for all streams to be closed before closing
122      * the connection during the graceful shutdown process.
123      * @param gracefulShutdownTimeoutMillis the amount of time (in milliseconds) this endpoint will wait for all
124      * streams to be closed before closing the connection during the graceful shutdown process.
125      */
126     public void gracefulShutdownTimeoutMillis(long gracefulShutdownTimeoutMillis) {
127         if (gracefulShutdownTimeoutMillis < -1) {
128             throw new IllegalArgumentException("gracefulShutdownTimeoutMillis: " + gracefulShutdownTimeoutMillis +
129                                                " (expected: -1 for indefinite or >= 0)");
130         }
131         this.gracefulShutdownTimeoutMillis = gracefulShutdownTimeoutMillis;
132     }
133 
134     public Http2Connection connection() {
135         return encoder.connection();
136     }
137 
138     public Http2ConnectionDecoder decoder() {
139         return decoder;
140     }
141 
142     public Http2ConnectionEncoder encoder() {
143         return encoder;
144     }
145 
146     private boolean prefaceSent() {
147         return byteDecoder != null && byteDecoder.prefaceSent();
148     }
149 
150     /**
151      * Handles the client-side (cleartext) upgrade from HTTP to HTTP/2.
152      * Reserves local stream 1 for the HTTP/2 response.
153      */
154     public void onHttpClientUpgrade() throws Http2Exception {
155         if (connection().isServer()) {
156             throw connectionError(PROTOCOL_ERROR, "Client-side HTTP upgrade requested for a server");
157         }
158         if (!prefaceSent()) {
159             // If the preface was not sent yet it most likely means the handler was not added to the pipeline before
160             // calling this method.
161             throw connectionError(INTERNAL_ERROR, "HTTP upgrade must occur after preface was sent");
162         }
163         if (decoder.prefaceReceived()) {
164             throw connectionError(PROTOCOL_ERROR, "HTTP upgrade must occur before HTTP/2 preface is received");
165         }
166 
167         // Create a local stream used for the HTTP cleartext upgrade.
168         connection().local().createStream(HTTP_UPGRADE_STREAM_ID, true);
169     }
170 
171     /**
172      * Handles the server-side (cleartext) upgrade from HTTP to HTTP/2.
173      * @param settings the settings for the remote endpoint.
174      */
175     public void onHttpServerUpgrade(Http2Settings settings) throws Http2Exception {
176         if (!connection().isServer()) {
177             throw connectionError(PROTOCOL_ERROR, "Server-side HTTP upgrade requested for a client");
178         }
179         if (!prefaceSent()) {
180             // If the preface was not sent yet it most likely means the handler was not added to the pipeline before
181             // calling this method.
182             throw connectionError(INTERNAL_ERROR, "HTTP upgrade must occur after preface was sent");
183         }
184         if (decoder.prefaceReceived()) {
185             throw connectionError(PROTOCOL_ERROR, "HTTP upgrade must occur before HTTP/2 preface is received");
186         }
187 
188         // Apply the settings but no ACK is necessary.
189         encoder.remoteSettings(settings);
190 
191         // Create a stream in the half-closed state.
192         connection().remote().createStream(HTTP_UPGRADE_STREAM_ID, true);
193     }
194 
195     @Override
196     public void flush(ChannelHandlerContext ctx) {
197         if (inFlush) {
198             // Reentrant flush (e.g. from a synchronous writability change) must not recurse — that livelocks
199             // (#17256); the in-progress flush loop picks it up.
200             flushAgain = true;
201             return;
202         }
203         inFlush = true;
204         try {
205             do {
206                 flushAgain = false;
207                 // Trigger pending writes in the remote flow controller.
208                 encoder.flowController().writePendingBytes();
209                 ctx.flush();
210                 // Honor any flush re-requested while we were flushing (a resumed write, or a direct flush from
211                 // elsewhere in the pipeline) regardless of writability — flushing already-written data doesn't
212                 // need a writable channel.
213             } while (flushAgain);
214         } catch (Http2Exception e) {
215             onError(ctx, true, e);
216         } catch (Throwable cause) {
217             onError(ctx, true, connectionError(INTERNAL_ERROR, cause, "Error flushing"));
218         } finally {
219             inFlush = false;
220         }
221     }
222 
223     private boolean hasPendingData() {
224         final Http2RemoteFlowController flowController = encoder.flowController();
225         try {
226             // Stop at the first stream that still has a flow-controlled frame queued. Frame-based, so it counts
227             // zero-length frames (e.g. trailing headers) that carry no flow-control bytes.
228             return connection().forEachActiveStream(new Http2StreamVisitor() {
229                 @Override
230                 public boolean visit(Http2Stream stream) {
231                     return !flowController.hasFlowControlled(stream);
232                 }
233             }) != null;
234         } catch (Http2Exception e) {
235             return false;
236         }
237     }
238 
239     private abstract class BaseDecoder {
240         public abstract void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception;
241         public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { }
242         public void channelActive(ChannelHandlerContext ctx) throws Exception { }
243 
244         public void channelInactive(ChannelHandlerContext ctx) throws Exception {
245             // Connection has terminated, close the encoder and decoder.
246             encoder().close();
247             decoder().close();
248 
249             // We need to remove all streams (not just the active ones).
250             // See https://github.com/netty/netty/issues/4838.
251             connection().close(ctx.voidPromise());
252         }
253 
254         /**
255          * Determine if the HTTP/2 connection preface been sent.
256          */
257         public boolean prefaceSent() {
258             return true;
259         }
260 
261         /**
262          * Send the preface if needed.
263          *
264          * @param ctx           the {@link ChannelHandlerContext} to use.
265          * @throws Exception    thrown on error.
266          */
267         public void sendPrefaceIfNeeded(ChannelHandlerContext ctx) throws Exception {
268             // Noop by default.
269         }
270     }
271 
272     private final class PrefaceDecoder extends BaseDecoder {
273         private ByteBuf clientPrefaceString;
274         private boolean prefaceSent;
275 
276         PrefaceDecoder(ChannelHandlerContext ctx) throws Exception {
277             clientPrefaceString = clientPrefaceString(encoder.connection());
278             // This handler was just added to the context. In case it was handled after
279             // the connection became active, send the connection preface now.
280             sendPrefaceIfNeeded(ctx);
281         }
282 
283         @Override
284         public boolean prefaceSent() {
285             return prefaceSent;
286         }
287 
288         @Override
289         public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
290             try {
291                 if (ctx.channel().isActive() && readClientPrefaceString(in) && verifyFirstFrameIsSettings(in)) {
292                     // After the preface is read, it is time to hand over control to the post initialized decoder.
293                     byteDecoder = new FrameDecoder();
294                     byteDecoder.decode(ctx, in, out);
295                 }
296             } catch (Throwable e) {
297                 if (byteDecoder != null) {
298                     // Skip all bytes before we report the exception as
299                     in.skipBytes(in.readableBytes());
300                 }
301                 onError(ctx, false, e);
302             }
303         }
304 
305         @Override
306         public void channelActive(ChannelHandlerContext ctx) throws Exception {
307             // The channel just became active - send the connection preface to the remote endpoint.
308             sendPrefaceIfNeeded(ctx);
309         }
310 
311         @Override
312         public void channelInactive(ChannelHandlerContext ctx) throws Exception {
313             cleanup();
314             super.channelInactive(ctx);
315         }
316 
317         /**
318          * Releases the {@code clientPrefaceString}. Any active streams will be left in the open.
319          */
320         @Override
321         public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
322             cleanup();
323         }
324 
325         /**
326          * Releases the {@code clientPrefaceString}. Any active streams will be left in the open.
327          */
328         private void cleanup() {
329             if (clientPrefaceString != null) {
330                 clientPrefaceString.release();
331                 clientPrefaceString = null;
332             }
333         }
334 
335         /**
336          * Decodes the client connection preface string from the input buffer.
337          *
338          * @return {@code true} if processing of the client preface string is complete. Since client preface strings can
339          *         only be received by servers, returns true immediately for client endpoints.
340          */
341         private boolean readClientPrefaceString(ByteBuf in) throws Http2Exception {
342             if (clientPrefaceString == null) {
343                 return true;
344             }
345 
346             int prefaceRemaining = clientPrefaceString.readableBytes();
347             int bytesRead = min(in.readableBytes(), prefaceRemaining);
348 
349             // If the input so far doesn't match the preface, break the connection.
350             if (bytesRead == 0 || !ByteBufUtil.equals(in, in.readerIndex(),
351                                                       clientPrefaceString, clientPrefaceString.readerIndex(),
352                                                       bytesRead)) {
353                 int maxSearch = 1024; // picked because 512 is too little, and 2048 too much
354                 int http1Index =
355                     ByteBufUtil.indexOf(HTTP_1_X_BUF, in.slice(in.readerIndex(), min(in.readableBytes(), maxSearch)));
356                 if (http1Index != -1) {
357                     String chunk = in.toString(in.readerIndex(), http1Index - in.readerIndex(), CharsetUtil.US_ASCII);
358                     throw connectionError(PROTOCOL_ERROR, "Unexpected HTTP/1.x request: %s", chunk);
359                 }
360                 String receivedBytes = hexDump(in, in.readerIndex(),
361                                                min(in.readableBytes(), clientPrefaceString.readableBytes()));
362                 throw connectionError(PROTOCOL_ERROR, "HTTP/2 client preface string missing or corrupt. " +
363                                                       "Hex dump for received bytes: %s", receivedBytes);
364             }
365             in.skipBytes(bytesRead);
366             clientPrefaceString.skipBytes(bytesRead);
367 
368             if (!clientPrefaceString.isReadable()) {
369                 // Entire preface has been read.
370                 clientPrefaceString.release();
371                 clientPrefaceString = null;
372                 return true;
373             }
374             return false;
375         }
376 
377         /**
378          * Peeks at that the next frame in the buffer and verifies that it is a non-ack {@code SETTINGS} frame.
379          *
380          * @param in the inbound buffer.
381          * @return {@code true} if the next frame is a non-ack {@code SETTINGS} frame, {@code false} if more
382          * data is required before we can determine the next frame type.
383          * @throws Http2Exception thrown if the next frame is NOT a non-ack {@code SETTINGS} frame.
384          */
385         private boolean verifyFirstFrameIsSettings(ByteBuf in) throws Http2Exception {
386             if (in.readableBytes() < 5) {
387                 // Need more data before we can see the frame type for the first frame.
388                 return false;
389             }
390 
391             short frameType = in.getUnsignedByte(in.readerIndex() + 3);
392             if (frameType != SETTINGS) {
393                 throw connectionError(PROTOCOL_ERROR, "First received frame was not SETTINGS. " +
394                                                       "Hex dump for first 5 bytes: %s",
395                                       hexDump(in, in.readerIndex(), 5));
396             }
397             short flags = in.getUnsignedByte(in.readerIndex() + 4);
398             if ((flags & Http2Flags.ACK) != 0) {
399                 throw connectionError(PROTOCOL_ERROR, "First received frame was SETTINGS frame but had ACK flag set. " +
400                         "Hex dump for first 5 bytes: %s",
401                         hexDump(in, in.readerIndex(), 5));
402             }
403             return true;
404         }
405 
406         /**
407          * Sends the HTTP/2 connection preface upon establishment of the connection, if not already sent.
408          */
409         @Override
410         public void sendPrefaceIfNeeded(ChannelHandlerContext ctx) throws Exception {
411             if (prefaceSent || !ctx.channel().isActive()) {
412                 return;
413             }
414 
415             prefaceSent = true;
416 
417             final boolean isClient = !connection().isServer();
418             if (isClient) {
419                 // Clients must send the preface string as the first bytes on the connection.
420                 ctx.write(connectionPrefaceBuf()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
421             }
422 
423             // Both client and server must send their initial settings.
424             encoder.writeSettings(ctx, initialSettings, ctx.newPromise()).addListener(
425                     ChannelFutureListener.CLOSE_ON_FAILURE);
426 
427             try {
428                 if (isClient) {
429                     // If this handler is extended by the user and we directly fire the userEvent from this context then
430                     // the user will not see the event. We should fire the event starting with this handler so this
431                     // class (and extending classes) have a chance to process the event.
432                     userEventTriggered(ctx, Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE);
433                 }
434             } finally {
435                 if (flushPreface) {
436                     // As we don't know if any channelReadComplete() events will be triggered at all we need to ensure
437                     // we also flush. Otherwise the remote peer might never see the preface / settings frame.
438                     // See https://github.com/netty/netty/issues/12089
439                     ctx.flush();
440                 }
441             }
442         }
443     }
444 
445     private final class FrameDecoder extends BaseDecoder {
446         @Override
447         public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
448             try {
449                 decoder.decodeFrame(ctx, in, out);
450             } catch (Throwable e) {
451                 onError(ctx, false, e);
452             }
453         }
454     }
455 
456     @Override
457     public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
458         // Initialize the encoder, decoder, flow controllers, and internal state.
459         encoder.lifecycleManager(this);
460         decoder.lifecycleManager(this);
461         encoder.flowController().channelHandlerContext(ctx);
462         decoder.flowController().channelHandlerContext(ctx);
463         byteDecoder = new PrefaceDecoder(ctx);
464         // Streams are not only closed via closeStream(...): the connection also closes them itself, for example
465         // when a GOAWAY is received or the channel becomes inactive. Check if a pending graceful shutdown can
466         // complete whenever a stream is closed, whatever the reason.
467         connection().addListener(new Http2ConnectionAdapter() {
468             @Override
469             public void onStreamClosed(Http2Stream stream) {
470                 checkCloseConnection(ctx.newSucceededFuture());
471             }
472         });
473     }
474 
475     @Override
476     protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
477         if (byteDecoder != null) {
478             byteDecoder.handlerRemoved(ctx);
479             byteDecoder = null;
480         }
481     }
482 
483     @Override
484     public void channelActive(ChannelHandlerContext ctx) throws Exception {
485         if (byteDecoder == null) {
486             byteDecoder = new PrefaceDecoder(ctx);
487         }
488         byteDecoder.channelActive(ctx);
489         super.channelActive(ctx);
490     }
491 
492     @Override
493     public void channelInactive(ChannelHandlerContext ctx) throws Exception {
494         // Call super class first, as this may result in decode being called.
495         super.channelInactive(ctx);
496         if (byteDecoder != null) {
497             byteDecoder.channelInactive(ctx);
498             byteDecoder = null;
499         }
500     }
501 
502     @Override
503     public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
504         try {
505             // Only flush on a writability change if the flow controller has frames queued. A toggle with
506             // nothing to write (e.g. SslHandler during setup) must not flush, or the flush -> writability ->
507             // flush cycle livelocks (#17256).
508             if (ctx.channel().isWritable() && hasPendingData()) {
509                 flush(ctx);
510             }
511             encoder.flowController().channelWritabilityChanged();
512         } finally {
513             super.channelWritabilityChanged(ctx);
514         }
515     }
516 
517     @Override
518     protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
519         byteDecoder.decode(ctx, in, out);
520     }
521 
522     @Override
523     public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
524         // Ensure we send the preface before we notify the bind promise as the user might try to write
525         // directly in the listener attached to the promise and we need to ensure the preface is always the first
526         // thing that is written.
527         ctx.bind(localAddress, ctx.newPromise()).addListener(new PrefaceSendListener(ctx, promise));
528     }
529 
530     @Override
531     public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
532                         ChannelPromise promise) throws Exception {
533         // Ensure we send the preface before we notify the connect promise as the user might try to write
534         // directly in the listener attached to the promise and we need to ensure the preface is always the first
535         // thing that is written.
536         ctx.connect(remoteAddress, localAddress, ctx.newPromise()).addListener(new PrefaceSendListener(ctx, promise));
537     }
538 
539     @Override
540     public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
541         ctx.disconnect(promise);
542     }
543 
544     @Override
545     public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
546         if (decoupleCloseAndGoAway) {
547             ctx.close(promise);
548             return;
549         }
550         promise = promise.unvoid();
551         // Avoid NotYetConnectedException and avoid sending before connection preface
552         if (!ctx.channel().isActive() || !prefaceSent()) {
553             ctx.close(promise);
554             return;
555         }
556 
557         // If the user has already sent a GO_AWAY frame they may be attempting to do a graceful shutdown which requires
558         // sending multiple GO_AWAY frames. We should only send a GO_AWAY here if one has not already been sent. If
559         // a GO_AWAY has been sent we send a empty buffer just so we can wait to close until all other data has been
560         // flushed to the OS.
561         // https://github.com/netty/netty/issues/5307
562         ChannelFuture f = connection().goAwaySent() ? ctx.write(EMPTY_BUFFER) : goAway(ctx, null, ctx.newPromise());
563         ctx.flush();
564         doGracefulShutdown(ctx, f, promise);
565     }
566 
567     private ChannelFutureListener newClosingChannelFutureListener(
568             ChannelHandlerContext ctx, ChannelPromise promise) {
569         long gracefulShutdownTimeoutMillis = this.gracefulShutdownTimeoutMillis;
570         return gracefulShutdownTimeoutMillis < 0 ?
571                 new ClosingChannelFutureListener(ctx, promise) :
572                 new ClosingChannelFutureListener(ctx, promise, gracefulShutdownTimeoutMillis, MILLISECONDS);
573     }
574 
575     private void doGracefulShutdown(ChannelHandlerContext ctx, ChannelFuture future, final ChannelPromise promise) {
576         final ChannelFutureListener listener = newClosingChannelFutureListener(ctx, promise);
577         if (isGracefulShutdownComplete()) {
578             // If there are no active streams, close immediately after the GO_AWAY write completes or the timeout
579             // elapsed.
580             future.addListener(listener);
581         } else {
582             // If there are active streams we should wait until they are all closed before closing the connection.
583 
584             // The ClosingChannelFutureListener will cascade promise completion. We need to always notify the
585             // new ClosingChannelFutureListener when the graceful close completes if the promise is not null.
586             if (closeListener == null) {
587                 closeListener = listener;
588             } else if (promise != null) {
589                 final ChannelFutureListener oldCloseListener = closeListener;
590                 closeListener = new ChannelFutureListener() {
591                     @Override
592                     public void operationComplete(ChannelFuture future) throws Exception {
593                         try {
594                             oldCloseListener.operationComplete(future);
595                         } finally {
596                             listener.operationComplete(future);
597                         }
598                     }
599                 };
600             }
601         }
602     }
603 
604     @Override
605     public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
606         ctx.deregister(promise);
607     }
608 
609     @Override
610     public void read(ChannelHandlerContext ctx) throws Exception {
611         ctx.read();
612     }
613 
614     @Override
615     public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
616         ctx.write(msg, promise);
617     }
618 
619     @Override
620     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
621         // Trigger flush after read on the assumption that flush is cheap if there is nothing to write and that
622         // for flow-control the read may release window that causes data to be written that can now be flushed.
623         try {
624             // First call channelReadComplete0(...) as this may produce more data that we want to flush
625             channelReadComplete0(ctx);
626         } finally {
627             flush(ctx);
628         }
629     }
630 
631     final void channelReadComplete0(ChannelHandlerContext ctx) {
632         // Discard bytes of the cumulation buffer if needed.
633         discardSomeReadBytes();
634 
635         // Ensure we never stale the HTTP/2 Channel. Flow-control is enforced by HTTP/2.
636         //
637         // See https://tools.ietf.org/html/rfc7540#section-5.2.2
638         if (!ctx.channel().config().isAutoRead()) {
639             ctx.read();
640         }
641 
642         ctx.fireChannelReadComplete();
643     }
644 
645     /**
646      * Handles {@link Http2Exception} objects that were thrown from other handlers. Ignores all other exceptions.
647      */
648     @Override
649     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
650         if (getEmbeddedHttp2Exception(cause) != null) {
651             // Some exception in the causality chain is an Http2Exception - handle it.
652             onError(ctx, false, cause);
653         } else {
654             super.exceptionCaught(ctx, cause);
655         }
656     }
657 
658     /**
659      * Closes the local side of the given stream. If this causes the stream to be closed, adds a
660      * hook to close the channel after the given future completes.
661      *
662      * @param stream the stream to be half closed.
663      * @param future If closing, the future after which to close the channel.
664      */
665     @Override
666     public void closeStreamLocal(Http2Stream stream, ChannelFuture future) {
667         switch (stream.state()) {
668             case HALF_CLOSED_LOCAL:
669             case OPEN:
670                 stream.closeLocalSide();
671                 break;
672             default:
673                 closeStream(stream, future);
674                 break;
675         }
676     }
677 
678     /**
679      * Closes the remote side of the given stream. If this causes the stream to be closed, adds a
680      * hook to close the channel after the given future completes.
681      *
682      * @param stream the stream to be half closed.
683      * @param future If closing, the future after which to close the channel.
684      */
685     @Override
686     public void closeStreamRemote(Http2Stream stream, ChannelFuture future) {
687         switch (stream.state()) {
688             case HALF_CLOSED_REMOTE:
689             case OPEN:
690                 stream.closeRemoteSide();
691                 break;
692             default:
693                 closeStream(stream, future);
694                 break;
695         }
696     }
697 
698     @Override
699     public void closeStream(final Http2Stream stream, ChannelFuture future) {
700         if (future.isDone()) {
701             doCloseStream(stream, future);
702         } else {
703             future.addListener(new ChannelFutureListener() {
704                 @Override
705                 public void operationComplete(ChannelFuture future) {
706                     doCloseStream(stream, future);
707                 }
708             });
709         }
710     }
711 
712     /**
713      * Central handler for all exceptions caught during HTTP/2 processing.
714      */
715     @Override
716     public void onError(ChannelHandlerContext ctx, boolean outbound, Throwable cause) {
717         Http2Exception embedded = getEmbeddedHttp2Exception(cause);
718         if (isStreamError(embedded)) {
719             onStreamError(ctx, outbound, cause, (StreamException) embedded);
720         } else if (embedded instanceof CompositeStreamException) {
721             CompositeStreamException compositException = (CompositeStreamException) embedded;
722             // Each contained StreamException is generally an independent error for a distinct stream (e.g.
723             // one per active stream that overflowed its flow-control window when SETTINGS_INITIAL_WINDOW_SIZE
724             // changed), so every affected stream must still be reset individually; otherwise it would be left
725             // open with a corrupted flow-control window. Should the composite ever contain more than one
726             // exception for the same stream id, only report the first one, per RFC 9113, Section 5.4's
727             // guidance to report at most one stream error per stream.
728             Set<Integer> handledStreamIds = new HashSet<Integer>();
729             for (StreamException streamException : compositException) {
730                 if (handledStreamIds.add(streamException.streamId())) {
731                     onStreamError(ctx, outbound, cause, streamException);
732                 }
733             }
734         } else {
735             onConnectionError(ctx, outbound, cause, embedded);
736         }
737         ctx.flush();
738     }
739 
740     /**
741      * Called by the graceful shutdown logic to determine when it is safe to close the connection. Returns {@code true}
742      * if the graceful shutdown has completed and the connection can be safely closed. This implementation just
743      * guarantees that there are no active streams. Subclasses may override to provide additional checks.
744      */
745     protected boolean isGracefulShutdownComplete() {
746         return connection().numActiveStreams() == 0;
747     }
748 
749     /**
750      * Handler for a connection error. Sends a GO_AWAY frame to the remote endpoint. Once all
751      * streams are closed, the connection is shut down.
752      *
753      * @param ctx the channel context
754      * @param outbound {@code true} if the error was caused by an outbound operation.
755      * @param cause the exception that was caught
756      * @param http2Ex the {@link Http2Exception} that is embedded in the causality chain. This may
757      *            be {@code null} if it's an unknown exception.
758      */
759     protected void onConnectionError(ChannelHandlerContext ctx, boolean outbound,
760                                      Throwable cause, Http2Exception http2Ex) {
761         if (http2Ex == null) {
762             http2Ex = new Http2Exception(INTERNAL_ERROR, cause.getMessage(), cause);
763         }
764 
765         ChannelPromise promise = ctx.newPromise();
766         ChannelFuture future = goAway(ctx, http2Ex, ctx.newPromise());
767         if (http2Ex.shutdownHint() == Http2Exception.ShutdownHint.GRACEFUL_SHUTDOWN) {
768             doGracefulShutdown(ctx, future, promise);
769         } else {
770             future.addListener(newClosingChannelFutureListener(ctx, promise));
771         }
772     }
773 
774     /**
775      * Handler for a stream error. Sends a {@code RST_STREAM} frame to the remote endpoint and closes the
776      * stream.
777      *
778      * @param ctx the channel context
779      * @param outbound {@code true} if the error was caused by an outbound operation.
780      * @param cause the exception that was caught
781      * @param http2Ex the {@link StreamException} that is embedded in the causality chain.
782      */
783     protected void onStreamError(ChannelHandlerContext ctx, boolean outbound,
784                                  @SuppressWarnings("unused") Throwable cause, StreamException http2Ex) {
785         final int streamId = http2Ex.streamId();
786         Http2Stream stream = connection().stream(streamId);
787 
788         //if this is caused by reading headers that are too large, send a header with status 431
789         if (http2Ex instanceof Http2Exception.HeaderListSizeException &&
790             ((Http2Exception.HeaderListSizeException) http2Ex).duringDecode() &&
791             connection().isServer()) {
792 
793             // NOTE We have to check to make sure that a stream exists before we send our reply.
794             // We likely always create the stream below as the stream isn't created until the
795             // header block is completely processed.
796 
797             // The case of a streamId referring to a stream which was already closed is handled
798             // by createStream and will land us in the catch block below
799             if (stream == null) {
800                 try {
801                     stream = encoder.connection().remote().createStream(streamId, true);
802                 } catch (Http2Exception e) {
803                     encoder().writeRstStream(ctx, streamId, http2Ex.error().code(), ctx.newPromise());
804                     return;
805                 }
806             }
807 
808             // ensure that we have not already sent headers on this stream
809             if (stream != null && !stream.isHeadersSent()) {
810                 try {
811                     handleServerHeaderDecodeSizeError(ctx, stream);
812                 } catch (Throwable cause2) {
813                     onError(ctx, outbound, connectionError(INTERNAL_ERROR, cause2, "Error DecodeSizeError"));
814                 }
815             }
816         }
817 
818         if (stream == null) {
819             if (!outbound || connection().local().mayHaveCreatedStream(streamId)) {
820                 encoder().writeRstStream(ctx, streamId, http2Ex.error().code(), ctx.newPromise());
821             }
822         } else {
823             encoder().writeRstStream(ctx, streamId, http2Ex.error().code(), ctx.newPromise());
824         }
825     }
826 
827     /**
828      * Notifies client that this server has received headers that are larger than what it is
829      * willing to accept. Override to change behavior.
830      *
831      * @param ctx the channel context
832      * @param stream the Http2Stream on which the header was received
833      */
834     protected void handleServerHeaderDecodeSizeError(ChannelHandlerContext ctx, Http2Stream stream) {
835         encoder().writeHeaders(ctx, stream.id(), HEADERS_TOO_LARGE_HEADERS, 0, true, ctx.newPromise());
836     }
837 
838     protected Http2FrameWriter frameWriter() {
839         return encoder().frameWriter();
840     }
841 
842     /**
843      * Sends a {@code RST_STREAM} frame even if we don't know about the stream. This error condition is most likely
844      * triggered by the first frame of a stream being invalid. That is, there was an error reading the frame before
845      * we could create a new stream.
846      */
847     private ChannelFuture resetUnknownStream(final ChannelHandlerContext ctx, int streamId, long errorCode,
848                                              ChannelPromise promise) {
849         ChannelFuture future = frameWriter().writeRstStream(ctx, streamId, errorCode, promise);
850         if (future.isDone()) {
851             closeConnectionOnError(ctx, future);
852         } else {
853             future.addListener(new ChannelFutureListener() {
854                 @Override
855                 public void operationComplete(ChannelFuture future) throws Exception {
856                     closeConnectionOnError(ctx, future);
857                 }
858             });
859         }
860         return future;
861     }
862 
863     @Override
864     public ChannelFuture resetStream(final ChannelHandlerContext ctx, int streamId, long errorCode,
865                                      ChannelPromise promise) {
866         final Http2Stream stream = connection().stream(streamId);
867         if (stream == null) {
868             return resetUnknownStream(ctx, streamId, errorCode, promise.unvoid());
869         }
870 
871        return resetStream(ctx, stream, errorCode, promise);
872     }
873 
874     private ChannelFuture resetStream(final ChannelHandlerContext ctx, final Http2Stream stream,
875                                       long errorCode, ChannelPromise promise) {
876         promise = promise.unvoid();
877         if (stream.isResetSent()) {
878             // Don't write a RST_STREAM frame if we have already written one.
879             return promise.setSuccess();
880         }
881         // Synchronously set the resetSent flag to prevent any subsequent calls
882         // from resulting in multiple reset frames being sent.
883         //
884         // This needs to be done before we notify the promise as the promise may have a listener attached that
885         // call resetStream(...) again.
886         stream.resetSent();
887 
888         final ChannelFuture future;
889         // If the remote peer is not aware of the steam, then we are not allowed to send a RST_STREAM
890         // https://tools.ietf.org/html/rfc7540#section-6.4.
891         if (stream.state() == IDLE ||
892             connection().local().created(stream) && !stream.isHeadersSent() && !stream.isPushPromiseSent()) {
893             future = promise.setSuccess();
894         } else {
895             future = frameWriter().writeRstStream(ctx, stream.id(), errorCode, promise);
896         }
897         if (future.isDone()) {
898             processRstStreamWriteResult(ctx, stream, future);
899         } else {
900             future.addListener(new ChannelFutureListener() {
901                 @Override
902                 public void operationComplete(ChannelFuture future) throws Exception {
903                     processRstStreamWriteResult(ctx, stream, future);
904                 }
905             });
906         }
907 
908         return future;
909     }
910 
911     @Override
912     public ChannelFuture goAway(final ChannelHandlerContext ctx, final int lastStreamId, final long errorCode,
913                                 final ByteBuf debugData, ChannelPromise promise) {
914         promise = promise.unvoid();
915         final Http2Connection connection = connection();
916         try {
917             if (!connection.goAwaySent(lastStreamId, errorCode, debugData)) {
918                 debugData.release();
919                 promise.trySuccess();
920                 return promise;
921             }
922         } catch (Throwable cause) {
923             debugData.release();
924             promise.tryFailure(cause);
925             return promise;
926         }
927 
928         // Need to retain before we write the buffer because if we do it after the refCnt could already be 0 and
929         // result in an IllegalRefCountException.
930         debugData.retain();
931         ChannelFuture future = frameWriter().writeGoAway(ctx, lastStreamId, errorCode, debugData, promise);
932 
933         if (future.isDone()) {
934             processGoAwayWriteResult(ctx, lastStreamId, errorCode, debugData, future);
935         } else {
936             future.addListener(new ChannelFutureListener() {
937                 @Override
938                 public void operationComplete(ChannelFuture future) throws Exception {
939                     processGoAwayWriteResult(ctx, lastStreamId, errorCode, debugData, future);
940                 }
941             });
942         }
943 
944         return future;
945     }
946 
947     /**
948      * Closes the connection if the graceful shutdown process has completed.
949      * @param future Represents the status that will be passed to the {@link #closeListener}.
950      */
951     private void checkCloseConnection(ChannelFuture future) {
952         // If this connection is closing and the graceful shutdown has completed, close the connection
953         // once this operation completes.
954         if (closeListener != null && isGracefulShutdownComplete()) {
955             ChannelFutureListener closeListener = this.closeListener;
956             // This method could be called multiple times
957             // and we don't want to notify the closeListener multiple times.
958             this.closeListener = null;
959             try {
960                 closeListener.operationComplete(future);
961             } catch (Exception e) {
962                 throw new IllegalStateException("Close listener threw an unexpected exception", e);
963             }
964         }
965     }
966 
967     /**
968      * Close the remote endpoint with a {@code GO_AWAY} frame. Does <strong>not</strong> flush
969      * immediately, this is the responsibility of the caller.
970      */
971     private ChannelFuture goAway(ChannelHandlerContext ctx, Http2Exception cause, ChannelPromise promise) {
972         long errorCode = cause != null ? cause.error().code() : NO_ERROR.code();
973         int lastKnownStream;
974         if (cause != null && cause.shutdownHint() == Http2Exception.ShutdownHint.HARD_SHUTDOWN) {
975             // The hard shutdown could have been triggered during header processing, before updating
976             // lastStreamCreated(). Specifically, any connection errors encountered by Http2FrameReader or HPACK
977             // decoding will fail to update the last known stream. So we must be pessimistic.
978             // https://github.com/netty/netty/issues/10670
979             lastKnownStream = Integer.MAX_VALUE;
980         } else {
981             lastKnownStream = connection().remote().lastStreamCreated();
982         }
983         return goAway(ctx, lastKnownStream, errorCode, Http2CodecUtil.toByteBuf(ctx, cause), promise);
984     }
985 
986     private void processRstStreamWriteResult(ChannelHandlerContext ctx, Http2Stream stream, ChannelFuture future) {
987         if (future.isSuccess()) {
988             closeStream(stream, future);
989         } else {
990             // The connection will be closed and so no need to change the resetSent flag to false.
991             onConnectionError(ctx, true, future.cause(), null);
992         }
993     }
994 
995     private void closeConnectionOnError(ChannelHandlerContext ctx, ChannelFuture future) {
996         if (!future.isSuccess()) {
997             onConnectionError(ctx, true, future.cause(), null);
998         }
999     }
1000 
1001     private void doCloseStream(final Http2Stream stream, ChannelFuture future) {
1002         stream.close();
1003         checkCloseConnection(future);
1004     }
1005 
1006     /**
1007      * Returns the client preface string if this is a client connection, otherwise returns {@code null}.
1008      */
1009     private static ByteBuf clientPrefaceString(Http2Connection connection) {
1010         return connection.isServer() ? connectionPrefaceBuf() : null;
1011     }
1012 
1013     private static void processGoAwayWriteResult(final ChannelHandlerContext ctx, final int lastStreamId,
1014                                                  final long errorCode, final ByteBuf debugData, ChannelFuture future) {
1015         try {
1016             if (future.isSuccess()) {
1017                 if (errorCode != NO_ERROR.code()) {
1018                     if (logger.isDebugEnabled()) {
1019                         logger.debug("{} Sent GOAWAY: lastStreamId '{}', errorCode '{}', " +
1020                                      "debugData '{}'. Forcing shutdown of the connection.",
1021                                      ctx.channel(), lastStreamId, errorCode, debugData.toString(UTF_8));
1022                     }
1023                     ctx.close();
1024                 }
1025             } else {
1026                 if (logger.isDebugEnabled()) {
1027                     logger.debug("{} Sending GOAWAY failed: lastStreamId '{}', errorCode '{}', " +
1028                                  "debugData '{}'. Forcing shutdown of the connection.",
1029                                  ctx.channel(), lastStreamId, errorCode, debugData.toString(UTF_8), future.cause());
1030                 }
1031                 ctx.close();
1032             }
1033         } finally {
1034             // We're done with the debug data now.
1035             debugData.release();
1036         }
1037     }
1038 
1039     /**
1040      * Closes the channel when the future completes.
1041      */
1042     private static final class ClosingChannelFutureListener implements ChannelFutureListener {
1043         private final ChannelHandlerContext ctx;
1044         private final ChannelPromise promise;
1045         private final Future<?> timeoutTask;
1046         private boolean closed;
1047 
1048         ClosingChannelFutureListener(ChannelHandlerContext ctx, ChannelPromise promise) {
1049             this.ctx = ctx;
1050             this.promise = promise;
1051             timeoutTask = null;
1052         }
1053 
1054         ClosingChannelFutureListener(final ChannelHandlerContext ctx, final ChannelPromise promise,
1055                                      long timeout, TimeUnit unit) {
1056             this.ctx = ctx;
1057             this.promise = promise;
1058             timeoutTask = ctx.executor().schedule(new Runnable() {
1059                 @Override
1060                 public void run() {
1061                     doClose();
1062                 }
1063             }, timeout, unit);
1064         }
1065 
1066         @Override
1067         public void operationComplete(ChannelFuture sentGoAwayFuture) {
1068             if (timeoutTask != null) {
1069                 timeoutTask.cancel(false);
1070             }
1071             doClose();
1072         }
1073 
1074         private void doClose() {
1075             // We need to guard against multiple calls as the timeout may trigger close() first and then it will be
1076             // triggered again because of operationComplete(...) is called.
1077             if (closed) {
1078                 // This only happens if we also scheduled a timeout task.
1079                 assert timeoutTask != null;
1080                 return;
1081             }
1082             closed = true;
1083             if (promise == null) {
1084                 ctx.close();
1085             } else {
1086                 // The original promise may be completed while we waited for the active streams, so don't pass it to
1087                 // close(...). Notify it without failing if it's already done; a cancellation still prevents the close.
1088                 ctx.close(PromiseNotifier.cascade(false, ctx.newPromise(), promise));
1089             }
1090         }
1091     }
1092 
1093     private final class PrefaceSendListener implements ChannelFutureListener {
1094         private final ChannelHandlerContext ctx;
1095         private final ChannelPromise promise;
1096 
1097         PrefaceSendListener(ChannelHandlerContext ctx, ChannelPromise promise) {
1098             this.ctx = ctx;
1099             this.promise = promise;
1100         }
1101 
1102         @Override
1103         public void operationComplete(ChannelFuture f) {
1104             if (f.isSuccess()) {
1105                 try {
1106                     if (byteDecoder != null) {
1107                         byteDecoder.sendPrefaceIfNeeded(ctx);
1108                     }
1109                 } catch (Throwable e) {
1110                     promise.setFailure(e);
1111                     return;
1112                 }
1113                 promise.setSuccess();
1114             } else {
1115                 promise.setFailure(f.cause());
1116             }
1117         }
1118     }
1119 }