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(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
246 encoder().close();
247 decoder().close();
248
249
250
251 connection().close(ctx.voidPromise());
252 }
253
254
255
256
257 public boolean prefaceSent() {
258 return true;
259 }
260
261
262
263
264
265
266
267 public void sendPrefaceIfNeeded(ChannelHandlerContext ctx) throws Exception {
268
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
279
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
293 byteDecoder = new FrameDecoder();
294 byteDecoder.decode(ctx, in, out);
295 }
296 } catch (Throwable e) {
297 if (byteDecoder != null) {
298
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
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
319
320 @Override
321 public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
322 cleanup();
323 }
324
325
326
327
328 private void cleanup() {
329 if (clientPrefaceString != null) {
330 clientPrefaceString.release();
331 clientPrefaceString = null;
332 }
333 }
334
335
336
337
338
339
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
350 if (bytesRead == 0 || !ByteBufUtil.equals(in, in.readerIndex(),
351 clientPrefaceString, clientPrefaceString.readerIndex(),
352 bytesRead)) {
353 int maxSearch = 1024;
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
370 clientPrefaceString.release();
371 clientPrefaceString = null;
372 return true;
373 }
374 return false;
375 }
376
377
378
379
380
381
382
383
384
385 private boolean verifyFirstFrameIsSettings(ByteBuf in) throws Http2Exception {
386 if (in.readableBytes() < 5) {
387
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
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
420 ctx.write(connectionPrefaceBuf()).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
421 }
422
423
424 encoder.writeSettings(ctx, initialSettings, ctx.newPromise()).addListener(
425 ChannelFutureListener.CLOSE_ON_FAILURE);
426
427 try {
428 if (isClient) {
429
430
431
432 userEventTriggered(ctx, Http2ConnectionPrefaceAndSettingsFrameWrittenEvent.INSTANCE);
433 }
434 } finally {
435 if (flushPreface) {
436
437
438
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
459 encoder.lifecycleManager(this);
460 decoder.lifecycleManager(this);
461 encoder.flowController().channelHandlerContext(ctx);
462 decoder.flowController().channelHandlerContext(ctx);
463 byteDecoder = new PrefaceDecoder(ctx);
464
465
466
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
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
506
507
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
525
526
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
534
535
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
552 if (!ctx.channel().isActive() || !prefaceSent()) {
553 ctx.close(promise);
554 return;
555 }
556
557
558
559
560
561
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
579
580 future.addListener(listener);
581 } else {
582
583
584
585
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
622
623 try {
624
625 channelReadComplete0(ctx);
626 } finally {
627 flush(ctx);
628 }
629 }
630
631 final void channelReadComplete0(ChannelHandlerContext ctx) {
632
633 discardSomeReadBytes();
634
635
636
637
638 if (!ctx.channel().config().isAutoRead()) {
639 ctx.read();
640 }
641
642 ctx.fireChannelReadComplete();
643 }
644
645
646
647
648 @Override
649 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
650 if (getEmbeddedHttp2Exception(cause) != null) {
651
652 onError(ctx, false, cause);
653 } else {
654 super.exceptionCaught(ctx, cause);
655 }
656 }
657
658
659
660
661
662
663
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
680
681
682
683
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
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
723
724
725
726
727
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
742
743
744
745 protected boolean isGracefulShutdownComplete() {
746 return connection().numActiveStreams() == 0;
747 }
748
749
750
751
752
753
754
755
756
757
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
776
777
778
779
780
781
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
789 if (http2Ex instanceof Http2Exception.HeaderListSizeException &&
790 ((Http2Exception.HeaderListSizeException) http2Ex).duringDecode() &&
791 connection().isServer()) {
792
793
794
795
796
797
798
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
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
829
830
831
832
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
844
845
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
879 return promise.setSuccess();
880 }
881
882
883
884
885
886 stream.resetSent();
887
888 final ChannelFuture future;
889
890
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
929
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
949
950
951 private void checkCloseConnection(ChannelFuture future) {
952
953
954 if (closeListener != null && isGracefulShutdownComplete()) {
955 ChannelFutureListener closeListener = this.closeListener;
956
957
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
969
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
976
977
978
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
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
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
1035 debugData.release();
1036 }
1037 }
1038
1039
1040
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
1076
1077 if (closed) {
1078
1079 assert timeoutTask != null;
1080 return;
1081 }
1082 closed = true;
1083 if (promise == null) {
1084 ctx.close();
1085 } else {
1086
1087
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 }