1
2
3
4
5
6
7
8
9
10
11
12
13
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
60
61
62
63
64
65
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
113
114
115
116 public long gracefulShutdownTimeoutMillis() {
117 return gracefulShutdownTimeoutMillis;
118 }
119
120
121
122
123
124
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
152
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
160
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
168 connection().local().createStream(HTTP_UPGRADE_STREAM_ID, true);
169 }
170
171
172
173
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
181
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
189 encoder.remoteSettings(settings);
190
191
192 connection().remote().createStream(HTTP_UPGRADE_STREAM_ID, true);
193 }
194
195 @Override
196 public void flush(ChannelHandlerContext ctx) {
197 if (inFlush) {
198
199
200 flushAgain = true;
201 return;
202 }
203 inFlush = true;
204 try {
205 do {
206 flushAgain = false;
207
208 encoder.flowController().writePendingBytes();
209 ctx.flush();
210
211
212
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
227
228 return connection().forEachActiveStream(stream -> !flowController.hasFlowControlled(stream)) != null;
229 } catch (Http2Exception e) {
230 return false;
231 }
232 }
233
234 private abstract class BaseDecoder {
235 public abstract void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception;
236 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { }
237 public void channelActive(ChannelHandlerContext ctx) throws Exception { }
238
239 public void channelInactive(ChannelHandlerContext ctx) throws Exception {
240
241 encoder().close();
242 decoder().close();
243
244
245
246 connection().close(ctx.voidPromise());
247 }
248
249
250
251
252 public boolean prefaceSent() {
253 return true;
254 }
255
256
257
258
259
260
261
262 public void sendPrefaceIfNeeded(ChannelHandlerContext ctx) throws Exception {
263
264 }
265 }
266
267 private final class PrefaceDecoder extends BaseDecoder {
268 private ByteBuf clientPrefaceString;
269 private boolean prefaceSent;
270
271 PrefaceDecoder(ChannelHandlerContext ctx) throws Exception {
272 clientPrefaceString = clientPrefaceString(encoder.connection());
273
274
275 sendPrefaceIfNeeded(ctx);
276 }
277
278 @Override
279 public boolean prefaceSent() {
280 return prefaceSent;
281 }
282
283 @Override
284 public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
285 try {
286 if (ctx.channel().isActive() && readClientPrefaceString(in) && verifyFirstFrameIsSettings(in)) {
287
288 byteDecoder = new FrameDecoder();
289 byteDecoder.decode(ctx, in, out);
290 }
291 } catch (Throwable e) {
292 if (byteDecoder != null) {
293
294 in.skipBytes(in.readableBytes());
295 }
296 onError(ctx, false, e);
297 }
298 }
299
300 @Override
301 public void channelActive(ChannelHandlerContext ctx) throws Exception {
302
303 sendPrefaceIfNeeded(ctx);
304 }
305
306 @Override
307 public void channelInactive(ChannelHandlerContext ctx) throws Exception {
308 cleanup();
309 super.channelInactive(ctx);
310 }
311
312
313
314
315 @Override
316 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
317 cleanup();
318 }
319
320
321
322
323 private void cleanup() {
324 if (clientPrefaceString != null) {
325 clientPrefaceString.release();
326 clientPrefaceString = null;
327 }
328 }
329
330
331
332
333
334
335
336 private boolean readClientPrefaceString(ByteBuf in) throws Http2Exception {
337 if (clientPrefaceString == null) {
338 return true;
339 }
340
341 int prefaceRemaining = clientPrefaceString.readableBytes();
342 int bytesRead = min(in.readableBytes(), prefaceRemaining);
343
344
345 if (bytesRead == 0 || !ByteBufUtil.equals(in, in.readerIndex(),
346 clientPrefaceString, clientPrefaceString.readerIndex(),
347 bytesRead)) {
348 int maxSearch = 1024;
349 int http1Index =
350 ByteBufUtil.indexOf(HTTP_1_X_BUF, in.slice(in.readerIndex(), min(in.readableBytes(), maxSearch)));
351 if (http1Index != -1) {
352 String chunk = in.toString(in.readerIndex(), http1Index - in.readerIndex(), CharsetUtil.US_ASCII);
353 throw connectionError(PROTOCOL_ERROR, "Unexpected HTTP/1.x request: %s", chunk);
354 }
355 String receivedBytes = hexDump(in, in.readerIndex(),
356 min(in.readableBytes(), clientPrefaceString.readableBytes()));
357 throw connectionError(PROTOCOL_ERROR, "HTTP/2 client preface string missing or corrupt. " +
358 "Hex dump for received bytes: %s", receivedBytes);
359 }
360 in.skipBytes(bytesRead);
361 clientPrefaceString.skipBytes(bytesRead);
362
363 if (!clientPrefaceString.isReadable()) {
364
365 clientPrefaceString.release();
366 clientPrefaceString = null;
367 return true;
368 }
369 return false;
370 }
371
372
373
374
375
376
377
378
379
380 private boolean verifyFirstFrameIsSettings(ByteBuf in) throws Http2Exception {
381 if (in.readableBytes() < 5) {
382
383 return false;
384 }
385
386 short frameType = in.getUnsignedByte(in.readerIndex() + 3);
387 if (frameType != SETTINGS) {
388 throw connectionError(PROTOCOL_ERROR, "First received frame was not SETTINGS. " +
389 "Hex dump for first 5 bytes: %s",
390 hexDump(in, in.readerIndex(), 5));
391 }
392 short flags = in.getUnsignedByte(in.readerIndex() + 4);
393 if ((flags & Http2Flags.ACK) != 0) {
394 throw connectionError(PROTOCOL_ERROR, "First received frame was SETTINGS frame but had ACK flag set. " +
395 "Hex dump for first 5 bytes: %s",
396 hexDump(in, in.readerIndex(), 5));
397 }
398 return true;
399 }
400
401
402
403
404 @Override
405 public void sendPrefaceIfNeeded(ChannelHandlerContext ctx) throws Exception {
406 if (prefaceSent || !ctx.channel().isActive()) {
407 return;
408 }
409
410 prefaceSent = true;
411
412 final boolean isClient = !connection().isServer();
413 if (isClient) {
414
415 ctx.write(connectionPrefaceBuf()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
416 }
417
418
419 encoder.writeSettings(ctx, initialSettings, ctx.newPromise()).addListener(
420 ChannelFutureListener.CLOSE_ON_FAILURE);
421
422 try {
423 if (isClient) {
424
425
426
427 userEventTriggered(ctx, Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE);
428 }
429 } finally {
430 if (flushPreface) {
431
432
433
434 ctx.flush();
435 }
436 }
437 }
438 }
439
440 private final class FrameDecoder extends BaseDecoder {
441 @Override
442 public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
443 try {
444 decoder.decodeFrame(ctx, in, out);
445 } catch (Throwable e) {
446 onError(ctx, false, e);
447 }
448 }
449 }
450
451 @Override
452 public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
453
454 encoder.lifecycleManager(this);
455 decoder.lifecycleManager(this);
456 encoder.flowController().channelHandlerContext(ctx);
457 decoder.flowController().channelHandlerContext(ctx);
458 byteDecoder = new PrefaceDecoder(ctx);
459
460
461
462 connection().addListener(new Http2ConnectionAdapter() {
463 @Override
464 public void onStreamClosed(Http2Stream stream) {
465 checkCloseConnection(ctx.newSucceededFuture());
466 }
467 });
468 }
469
470 @Override
471 protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception {
472 if (byteDecoder != null) {
473 byteDecoder.handlerRemoved(ctx);
474 byteDecoder = null;
475 }
476 }
477
478 @Override
479 public void channelActive(ChannelHandlerContext ctx) throws Exception {
480 if (byteDecoder == null) {
481 byteDecoder = new PrefaceDecoder(ctx);
482 }
483 byteDecoder.channelActive(ctx);
484 super.channelActive(ctx);
485 }
486
487 @Override
488 public void channelInactive(ChannelHandlerContext ctx) throws Exception {
489
490 super.channelInactive(ctx);
491 if (byteDecoder != null) {
492 byteDecoder.channelInactive(ctx);
493 byteDecoder = null;
494 }
495 }
496
497 @Override
498 public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
499 try {
500
501
502
503 if (ctx.channel().isWritable() && hasPendingData()) {
504 flush(ctx);
505 }
506 encoder.flowController().channelWritabilityChanged();
507 } finally {
508 super.channelWritabilityChanged(ctx);
509 }
510 }
511
512 @Override
513 protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
514 byteDecoder.decode(ctx, in, out);
515 }
516
517 @Override
518 public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception {
519
520
521
522 ctx.bind(localAddress, ctx.newPromise()).addListener(new PrefaceSendListener(ctx, promise));
523 }
524
525 @Override
526 public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress,
527 ChannelPromise promise) throws Exception {
528
529
530
531 ctx.connect(remoteAddress, localAddress, ctx.newPromise()).addListener(new PrefaceSendListener(ctx, promise));
532 }
533
534 @Override
535 public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
536 ctx.disconnect(promise);
537 }
538
539 @Override
540 public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
541 if (decoupleCloseAndGoAway) {
542 ctx.close(promise);
543 return;
544 }
545 promise = promise.unvoid();
546
547 if (!ctx.channel().isActive() || !prefaceSent()) {
548 ctx.close(promise);
549 return;
550 }
551
552
553
554
555
556
557 ChannelFuture f = connection().goAwaySent() ? ctx.write(EMPTY_BUFFER) : goAway(ctx, null, ctx.newPromise());
558 ctx.flush();
559 doGracefulShutdown(ctx, f, promise);
560 }
561
562 private ChannelFutureListener newClosingChannelFutureListener(
563 ChannelHandlerContext ctx, ChannelPromise promise) {
564 long gracefulShutdownTimeoutMillis = this.gracefulShutdownTimeoutMillis;
565 return gracefulShutdownTimeoutMillis < 0 ?
566 new ClosingChannelFutureListener(ctx, promise) :
567 new ClosingChannelFutureListener(ctx, promise, gracefulShutdownTimeoutMillis, MILLISECONDS);
568 }
569
570 private void doGracefulShutdown(ChannelHandlerContext ctx, ChannelFuture future, final ChannelPromise promise) {
571 final ChannelFutureListener listener = newClosingChannelFutureListener(ctx, promise);
572 if (isGracefulShutdownComplete()) {
573
574
575 future.addListener(listener);
576 } else {
577
578
579
580
581 if (closeListener == null) {
582 closeListener = listener;
583 } else if (promise != null) {
584 final ChannelFutureListener oldCloseListener = closeListener;
585 closeListener = future1 -> {
586 try {
587 oldCloseListener.operationComplete(future1);
588 } finally {
589 listener.operationComplete(future1);
590 }
591 };
592 }
593 }
594 }
595
596 @Override
597 public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
598 ctx.deregister(promise);
599 }
600
601 @Override
602 public void read(ChannelHandlerContext ctx) throws Exception {
603 ctx.read();
604 }
605
606 @Override
607 public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
608 ctx.write(msg, promise);
609 }
610
611 @Override
612 public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
613
614
615 try {
616
617 channelReadComplete0(ctx);
618 } finally {
619 flush(ctx);
620 }
621 }
622
623 final void channelReadComplete0(ChannelHandlerContext ctx) {
624
625 discardSomeReadBytes();
626
627
628
629
630 if (!ctx.channel().config().isAutoRead()) {
631 ctx.read();
632 }
633
634 ctx.fireChannelReadComplete();
635 }
636
637
638
639
640 @Override
641 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
642 if (getEmbeddedHttp2Exception(cause) != null) {
643
644 onError(ctx, false, cause);
645 } else {
646 super.exceptionCaught(ctx, cause);
647 }
648 }
649
650
651
652
653
654
655
656
657 @Override
658 public void closeStreamLocal(Http2Stream stream, ChannelFuture future) {
659 switch (stream.state()) {
660 case HALF_CLOSED_LOCAL:
661 case OPEN:
662 stream.closeLocalSide();
663 break;
664 default:
665 closeStream(stream, future);
666 break;
667 }
668 }
669
670
671
672
673
674
675
676
677 @Override
678 public void closeStreamRemote(Http2Stream stream, ChannelFuture future) {
679 switch (stream.state()) {
680 case HALF_CLOSED_REMOTE:
681 case OPEN:
682 stream.closeRemoteSide();
683 break;
684 default:
685 closeStream(stream, future);
686 break;
687 }
688 }
689
690 @Override
691 public void closeStream(final Http2Stream stream, ChannelFuture future) {
692 if (future.isDone()) {
693 doCloseStream(stream, future);
694 } else {
695 future.addListener((ChannelFutureListener) future1 -> doCloseStream(stream, future1));
696 }
697 }
698
699
700
701
702 @Override
703 public void onError(ChannelHandlerContext ctx, boolean outbound, Throwable cause) {
704 Http2Exception embedded = getEmbeddedHttp2Exception(cause);
705 if (isStreamError(embedded)) {
706 onStreamError(ctx, outbound, cause, (StreamException) embedded);
707 } else if (embedded instanceof CompositeStreamException) {
708 CompositeStreamException compositException = (CompositeStreamException) embedded;
709
710
711
712
713
714
715 Set<Integer> handledStreamIds = new HashSet<Integer>();
716 for (StreamException streamException : compositException) {
717 if (handledStreamIds.add(streamException.streamId())) {
718 onStreamError(ctx, outbound, cause, streamException);
719 }
720 }
721 } else {
722 onConnectionError(ctx, outbound, cause, embedded);
723 }
724 ctx.flush();
725 }
726
727
728
729
730
731
732 protected boolean isGracefulShutdownComplete() {
733 return connection().numActiveStreams() == 0;
734 }
735
736
737
738
739
740
741
742
743
744
745
746 protected void onConnectionError(ChannelHandlerContext ctx, boolean outbound,
747 Throwable cause, Http2Exception http2Ex) {
748 if (http2Ex == null) {
749 http2Ex = new Http2Exception(INTERNAL_ERROR, cause.getMessage(), cause);
750 }
751
752 ChannelPromise promise = ctx.newPromise();
753 ChannelFuture future = goAway(ctx, http2Ex, ctx.newPromise());
754 if (http2Ex.shutdownHint() == Http2Exception.ShutdownHint.GRACEFUL_SHUTDOWN) {
755 doGracefulShutdown(ctx, future, promise);
756 } else {
757 future.addListener(newClosingChannelFutureListener(ctx, promise));
758 }
759 }
760
761
762
763
764
765
766
767
768
769
770 protected void onStreamError(ChannelHandlerContext ctx, boolean outbound,
771 @SuppressWarnings("unused") Throwable cause, StreamException http2Ex) {
772 final int streamId = http2Ex.streamId();
773 Http2Stream stream = connection().stream(streamId);
774
775
776 if (http2Ex instanceof Http2Exception.HeaderListSizeException &&
777 ((Http2Exception.HeaderListSizeException) http2Ex).duringDecode() &&
778 connection().isServer()) {
779
780
781
782
783
784
785
786 if (stream == null) {
787 try {
788 stream = encoder.connection().remote().createStream(streamId, true);
789 } catch (Http2Exception e) {
790 encoder().writeRstStream(ctx, streamId, http2Ex.error().code(), ctx.newPromise());
791 return;
792 }
793 }
794
795
796 if (stream != null && !stream.isHeadersSent()) {
797 try {
798 handleServerHeaderDecodeSizeError(ctx, stream);
799 } catch (Throwable cause2) {
800 onError(ctx, outbound, connectionError(INTERNAL_ERROR, cause2, "Error DecodeSizeError"));
801 }
802 }
803 }
804
805 if (stream == null) {
806 if (!outbound || connection().local().mayHaveCreatedStream(streamId)) {
807 encoder().writeRstStream(ctx, streamId, http2Ex.error().code(), ctx.newPromise());
808 }
809 } else {
810 encoder().writeRstStream(ctx, streamId, http2Ex.error().code(), ctx.newPromise());
811 }
812 }
813
814
815
816
817
818
819
820
821 protected void handleServerHeaderDecodeSizeError(ChannelHandlerContext ctx, Http2Stream stream) {
822 encoder().writeHeaders(ctx, stream.id(), HEADERS_TOO_LARGE_HEADERS, 0, true, ctx.newPromise());
823 }
824
825 protected Http2FrameWriter frameWriter() {
826 return encoder().frameWriter();
827 }
828
829
830
831
832
833
834 private ChannelFuture resetUnknownStream(final ChannelHandlerContext ctx, int streamId, long errorCode,
835 ChannelPromise promise) {
836 ChannelFuture future = frameWriter().writeRstStream(ctx, streamId, errorCode, promise);
837 if (future.isDone()) {
838 closeConnectionOnError(ctx, future);
839 } else {
840 future.addListener((ChannelFutureListener) f -> closeConnectionOnError(ctx, f));
841 }
842 return future;
843 }
844
845 @Override
846 public ChannelFuture resetStream(final ChannelHandlerContext ctx, int streamId, long errorCode,
847 ChannelPromise promise) {
848 final Http2Stream stream = connection().stream(streamId);
849 if (stream == null) {
850 return resetUnknownStream(ctx, streamId, errorCode, promise.unvoid());
851 }
852
853 return resetStream(ctx, stream, errorCode, promise);
854 }
855
856 private ChannelFuture resetStream(final ChannelHandlerContext ctx, final Http2Stream stream,
857 long errorCode, ChannelPromise promise) {
858 promise = promise.unvoid();
859 if (stream.isResetSent()) {
860
861 return promise.setSuccess();
862 }
863
864
865
866
867
868 stream.resetSent();
869
870 final ChannelFuture future;
871
872
873 if (stream.state() == IDLE ||
874 connection().local().created(stream) && !stream.isHeadersSent() && !stream.isPushPromiseSent()) {
875 future = promise.setSuccess();
876 } else {
877 future = frameWriter().writeRstStream(ctx, stream.id(), errorCode, promise);
878 }
879 if (future.isDone()) {
880 processRstStreamWriteResult(ctx, stream, future);
881 } else {
882 future.addListener((ChannelFutureListener) f -> processRstStreamWriteResult(ctx, stream, f));
883 }
884
885 return future;
886 }
887
888 @Override
889 public ChannelFuture goAway(final ChannelHandlerContext ctx, final int lastStreamId, final long errorCode,
890 final ByteBuf debugData, ChannelPromise promise) {
891 promise = promise.unvoid();
892 final Http2Connection connection = connection();
893 try {
894 if (!connection.goAwaySent(lastStreamId, errorCode, debugData)) {
895 debugData.release();
896 promise.trySuccess();
897 return promise;
898 }
899 } catch (Throwable cause) {
900 debugData.release();
901 promise.tryFailure(cause);
902 return promise;
903 }
904
905
906
907 debugData.retain();
908 ChannelFuture future = frameWriter().writeGoAway(ctx, lastStreamId, errorCode, debugData, promise);
909
910 if (future.isDone()) {
911 processGoAwayWriteResult(ctx, lastStreamId, errorCode, debugData, future);
912 } else {
913 future.addListener((ChannelFutureListener) f ->
914 processGoAwayWriteResult(ctx, lastStreamId, errorCode, debugData, f));
915 }
916
917 return future;
918 }
919
920
921
922
923
924 private void checkCloseConnection(ChannelFuture future) {
925
926
927 if (closeListener != null && isGracefulShutdownComplete()) {
928 ChannelFutureListener closeListener = this.closeListener;
929
930
931 this.closeListener = null;
932 try {
933 closeListener.operationComplete(future);
934 } catch (Exception e) {
935 throw new IllegalStateException("Close listener threw an unexpected exception", e);
936 }
937 }
938 }
939
940
941
942
943
944 private ChannelFuture goAway(ChannelHandlerContext ctx, Http2Exception cause, ChannelPromise promise) {
945 long errorCode = cause != null ? cause.error().code() : NO_ERROR.code();
946 int lastKnownStream;
947 if (cause != null && cause.shutdownHint() == Http2Exception.ShutdownHint.HARD_SHUTDOWN) {
948
949
950
951
952 lastKnownStream = Integer.MAX_VALUE;
953 } else {
954 lastKnownStream = connection().remote().lastStreamCreated();
955 }
956 return goAway(ctx, lastKnownStream, errorCode, Http2CodecUtil.toByteBuf(ctx, cause), promise);
957 }
958
959 private void processRstStreamWriteResult(ChannelHandlerContext ctx, Http2Stream stream, ChannelFuture future) {
960 if (future.isSuccess()) {
961 closeStream(stream, future);
962 } else {
963
964 onConnectionError(ctx, true, future.cause(), null);
965 }
966 }
967
968 private void closeConnectionOnError(ChannelHandlerContext ctx, ChannelFuture future) {
969 if (!future.isSuccess()) {
970 onConnectionError(ctx, true, future.cause(), null);
971 }
972 }
973
974 private void doCloseStream(final Http2Stream stream, ChannelFuture future) {
975 stream.close();
976 checkCloseConnection(future);
977 }
978
979
980
981
982 private static ByteBuf clientPrefaceString(Http2Connection connection) {
983 return connection.isServer() ? connectionPrefaceBuf() : null;
984 }
985
986 private static void processGoAwayWriteResult(final ChannelHandlerContext ctx, final int lastStreamId,
987 final long errorCode, final ByteBuf debugData, ChannelFuture future) {
988 try {
989 if (future.isSuccess()) {
990 if (errorCode != NO_ERROR.code()) {
991 if (logger.isDebugEnabled()) {
992 logger.debug("{} Sent GOAWAY: lastStreamId '{}', errorCode '{}', " +
993 "debugData '{}'. Forcing shutdown of the connection.",
994 ctx.channel(), lastStreamId, errorCode, debugData.toString(UTF_8));
995 }
996 ctx.close();
997 }
998 } else {
999 if (logger.isDebugEnabled()) {
1000 logger.debug("{} Sending GOAWAY failed: lastStreamId '{}', errorCode '{}', " +
1001 "debugData '{}'. Forcing shutdown of the connection.",
1002 ctx.channel(), lastStreamId, errorCode, debugData.toString(UTF_8), future.cause());
1003 }
1004 ctx.close();
1005 }
1006 } finally {
1007
1008 debugData.release();
1009 }
1010 }
1011
1012
1013
1014
1015 private static final class ClosingChannelFutureListener implements ChannelFutureListener {
1016 private final ChannelHandlerContext ctx;
1017 private final ChannelPromise promise;
1018 private final Future<?> timeoutTask;
1019 private boolean closed;
1020
1021 ClosingChannelFutureListener(ChannelHandlerContext ctx, ChannelPromise promise) {
1022 this.ctx = ctx;
1023 this.promise = promise;
1024 timeoutTask = null;
1025 }
1026
1027 ClosingChannelFutureListener(final ChannelHandlerContext ctx, final ChannelPromise promise,
1028 long timeout, TimeUnit unit) {
1029 this.ctx = ctx;
1030 this.promise = promise;
1031 timeoutTask = ctx.executor().schedule(new Runnable() {
1032 @Override
1033 public void run() {
1034 doClose();
1035 }
1036 }, timeout, unit);
1037 }
1038
1039 @Override
1040 public void operationComplete(ChannelFuture sentGoAwayFuture) {
1041 if (timeoutTask != null) {
1042 timeoutTask.cancel(false);
1043 }
1044 doClose();
1045 }
1046
1047 private void doClose() {
1048
1049
1050 if (closed) {
1051
1052 assert timeoutTask != null;
1053 return;
1054 }
1055 closed = true;
1056 if (promise == null) {
1057 ctx.close();
1058 } else {
1059
1060
1061 ctx.close(PromiseNotifier.cascade(false, ctx.newPromise(), promise));
1062 }
1063 }
1064 }
1065
1066 private final class PrefaceSendListener implements ChannelFutureListener {
1067 private final ChannelHandlerContext ctx;
1068 private final ChannelPromise promise;
1069
1070 PrefaceSendListener(ChannelHandlerContext ctx, ChannelPromise promise) {
1071 this.ctx = ctx;
1072 this.promise = promise;
1073 }
1074
1075 @Override
1076 public void operationComplete(ChannelFuture f) {
1077 if (f.isSuccess()) {
1078 try {
1079 if (byteDecoder != null) {
1080 byteDecoder.sendPrefaceIfNeeded(ctx);
1081 }
1082 } catch (Throwable e) {
1083 promise.setFailure(e);
1084 return;
1085 }
1086 promise.setSuccess();
1087 } else {
1088 promise.setFailure(f.cause());
1089 }
1090 }
1091 }
1092 }