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.channel.ChannelHandlerContext;
19 import io.netty.handler.codec.http.HttpHeaderNames;
20 import io.netty.handler.codec.http.HttpStatusClass;
21 import io.netty.handler.codec.http.HttpUtil;
22 import io.netty.handler.codec.http2.Http2Connection.Endpoint;
23 import io.netty.util.internal.UnstableApi;
24 import io.netty.util.internal.logging.InternalLogger;
25 import io.netty.util.internal.logging.InternalLoggerFactory;
26
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map.Entry;
30
31 import static io.netty.handler.codec.http.HttpStatusClass.INFORMATIONAL;
32 import static io.netty.handler.codec.http2.Http2CodecUtil.DEFAULT_PRIORITY_WEIGHT;
33 import static io.netty.handler.codec.http2.Http2Error.INTERNAL_ERROR;
34 import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
35 import static io.netty.handler.codec.http2.Http2Error.STREAM_CLOSED;
36 import static io.netty.handler.codec.http2.Http2Exception.connectionError;
37 import static io.netty.handler.codec.http2.Http2Exception.streamError;
38 import static io.netty.handler.codec.http2.Http2PromisedRequestVerifier.ALWAYS_VERIFY;
39 import static io.netty.handler.codec.http2.Http2Stream.State.CLOSED;
40 import static io.netty.handler.codec.http2.Http2Stream.State.HALF_CLOSED_REMOTE;
41 import static io.netty.util.internal.ObjectUtil.checkNotNull;
42 import static java.lang.Integer.MAX_VALUE;
43 import static java.lang.Math.min;
44
45
46
47
48
49
50
51
52
53
54 @UnstableApi
55 public class DefaultHttp2ConnectionDecoder implements Http2ConnectionDecoder {
56 private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultHttp2ConnectionDecoder.class);
57 private Http2FrameListener internalFrameListener = new PrefaceFrameListener();
58 private final Http2Connection connection;
59 private Http2LifecycleManager lifecycleManager;
60 private final Http2ConnectionEncoder encoder;
61 private final Http2FrameReader frameReader;
62 private Http2FrameListener listener;
63 private final Http2PromisedRequestVerifier requestVerifier;
64 private final Http2SettingsReceivedConsumer settingsReceivedConsumer;
65 private final boolean autoAckPing;
66 private final Http2Connection.PropertyKey contentLengthKey;
67 private final boolean validateHeaders;
68
69 public DefaultHttp2ConnectionDecoder(Http2Connection connection,
70 Http2ConnectionEncoder encoder,
71 Http2FrameReader frameReader) {
72 this(connection, encoder, frameReader, ALWAYS_VERIFY);
73 }
74
75 public DefaultHttp2ConnectionDecoder(Http2Connection connection,
76 Http2ConnectionEncoder encoder,
77 Http2FrameReader frameReader,
78 Http2PromisedRequestVerifier requestVerifier) {
79 this(connection, encoder, frameReader, requestVerifier, true);
80 }
81
82
83
84
85
86
87
88
89
90
91
92
93
94 public DefaultHttp2ConnectionDecoder(Http2Connection connection,
95 Http2ConnectionEncoder encoder,
96 Http2FrameReader frameReader,
97 Http2PromisedRequestVerifier requestVerifier,
98 boolean autoAckSettings) {
99 this(connection, encoder, frameReader, requestVerifier, autoAckSettings, true);
100 }
101
102 @Deprecated
103 public DefaultHttp2ConnectionDecoder(Http2Connection connection,
104 Http2ConnectionEncoder encoder,
105 Http2FrameReader frameReader,
106 Http2PromisedRequestVerifier requestVerifier,
107 boolean autoAckSettings,
108 boolean autoAckPing) {
109 this(connection, encoder, frameReader, requestVerifier, autoAckSettings, true, true);
110 }
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127 public DefaultHttp2ConnectionDecoder(Http2Connection connection,
128 Http2ConnectionEncoder encoder,
129 Http2FrameReader frameReader,
130 Http2PromisedRequestVerifier requestVerifier,
131 boolean autoAckSettings,
132 boolean autoAckPing,
133 boolean validateHeaders) {
134 this.validateHeaders = validateHeaders;
135 this.autoAckPing = autoAckPing;
136 if (autoAckSettings) {
137 settingsReceivedConsumer = null;
138 } else {
139 if (!(encoder instanceof Http2SettingsReceivedConsumer)) {
140 throw new IllegalArgumentException("disabling autoAckSettings requires the encoder to be a " +
141 Http2SettingsReceivedConsumer.class);
142 }
143 settingsReceivedConsumer = (Http2SettingsReceivedConsumer) encoder;
144 }
145 this.connection = checkNotNull(connection, "connection");
146 contentLengthKey = this.connection.newKey();
147 this.frameReader = checkNotNull(frameReader, "frameReader");
148 this.encoder = checkNotNull(encoder, "encoder");
149 this.requestVerifier = checkNotNull(requestVerifier, "requestVerifier");
150 if (connection.local().flowController() == null) {
151 connection.local().flowController(new DefaultHttp2LocalFlowController(connection));
152 }
153 connection.local().flowController().frameWriter(encoder.frameWriter());
154 }
155
156 @Override
157 public void lifecycleManager(Http2LifecycleManager lifecycleManager) {
158 this.lifecycleManager = checkNotNull(lifecycleManager, "lifecycleManager");
159 }
160
161 @Override
162 public Http2Connection connection() {
163 return connection;
164 }
165
166 @Override
167 public final Http2LocalFlowController flowController() {
168 return connection.local().flowController();
169 }
170
171 @Override
172 public void frameListener(Http2FrameListener listener) {
173 this.listener = checkNotNull(listener, "listener");
174 }
175
176 @Override
177 public Http2FrameListener frameListener() {
178 return listener;
179 }
180
181 @Override
182 public boolean prefaceReceived() {
183 return FrameReadListener.class == internalFrameListener.getClass();
184 }
185
186 @Override
187 public void decodeFrame(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Http2Exception {
188 frameReader.readFrame(ctx, in, internalFrameListener);
189 }
190
191 @Override
192 public Http2Settings localSettings() {
193 Http2Settings settings = new Http2Settings();
194 Http2FrameReader.Configuration config = frameReader.configuration();
195 Http2HeadersDecoder.Configuration headersConfig = config.headersConfiguration();
196 Http2FrameSizePolicy frameSizePolicy = config.frameSizePolicy();
197 settings.initialWindowSize(flowController().initialWindowSize());
198 settings.maxConcurrentStreams(connection.remote().maxActiveStreams());
199 settings.headerTableSize(headersConfig.maxHeaderTableSize());
200 settings.maxFrameSize(frameSizePolicy.maxFrameSize());
201 settings.maxHeaderListSize(headersConfig.maxHeaderListSize());
202 if (!connection.isServer()) {
203
204 settings.pushEnabled(connection.local().allowPushTo());
205 }
206 return settings;
207 }
208
209 @Override
210 public void close() {
211 frameReader.close();
212 }
213
214
215
216
217
218
219
220
221 protected long calculateMaxHeaderListSizeGoAway(long maxHeaderListSize) {
222 return Http2CodecUtil.calculateMaxHeaderListSizeGoAway(maxHeaderListSize);
223 }
224
225 private int unconsumedBytes(Http2Stream stream) {
226 return flowController().unconsumedBytes(stream);
227 }
228
229 void onGoAwayRead0(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)
230 throws Http2Exception {
231 listener.onGoAwayRead(ctx, lastStreamId, errorCode, debugData);
232 connection.goAwayReceived(lastStreamId, errorCode, debugData);
233 }
234
235 void onUnknownFrame0(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,
236 ByteBuf payload) throws Http2Exception {
237 listener.onUnknownFrame(ctx, frameType, streamId, flags, payload);
238 }
239
240
241 private void verifyContentLength(Http2Stream stream, int data, boolean isEnd) throws Http2Exception {
242 ContentLength contentLength = stream.getProperty(contentLengthKey);
243 if (contentLength != null) {
244 try {
245 contentLength.increaseReceivedBytes(connection.isServer(), stream.id(), data, isEnd);
246 } finally {
247 if (isEnd) {
248 stream.removeProperty(contentLengthKey);
249 }
250 }
251 }
252 }
253
254
255
256
257 private final class FrameReadListener implements Http2FrameListener {
258 @Override
259 public int onDataRead(final ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
260 boolean endOfStream) throws Http2Exception {
261 Http2Stream stream = connection.stream(streamId);
262 Http2LocalFlowController flowController = flowController();
263 int readable = data.readableBytes();
264 int bytesToReturn = readable + padding;
265
266 final boolean shouldIgnore;
267 try {
268 shouldIgnore = shouldIgnoreHeadersOrDataFrame(ctx, streamId, stream, endOfStream, "DATA");
269 } catch (Http2Exception e) {
270
271
272 flowController.receiveFlowControlledFrame(stream, data, padding, endOfStream);
273 flowController.consumeBytes(stream, bytesToReturn);
274 throw e;
275 } catch (Throwable t) {
276 throw connectionError(INTERNAL_ERROR, t, "Unhandled error on data stream id %d", streamId);
277 }
278
279 if (shouldIgnore) {
280
281
282 flowController.receiveFlowControlledFrame(stream, data, padding, endOfStream);
283 flowController.consumeBytes(stream, bytesToReturn);
284
285
286 verifyStreamMayHaveExisted(streamId, endOfStream, "DATA");
287
288
289 return bytesToReturn;
290 }
291 Http2Exception error = null;
292 switch (stream.state()) {
293 case OPEN:
294 case HALF_CLOSED_LOCAL:
295 break;
296 case HALF_CLOSED_REMOTE:
297 case CLOSED:
298 error = streamError(stream.id(), STREAM_CLOSED, "Stream %d in unexpected state: %s",
299 stream.id(), stream.state());
300 break;
301 default:
302 error = streamError(stream.id(), PROTOCOL_ERROR,
303 "Stream %d in unexpected state: %s", stream.id(), stream.state());
304 break;
305 }
306
307 int unconsumedBytes = unconsumedBytes(stream);
308 try {
309 flowController.receiveFlowControlledFrame(stream, data, padding, endOfStream);
310
311 unconsumedBytes = unconsumedBytes(stream);
312
313
314 if (error != null) {
315 throw error;
316 }
317
318 verifyContentLength(stream, readable, endOfStream);
319
320
321
322 bytesToReturn = listener.onDataRead(ctx, streamId, data, padding, endOfStream);
323
324 if (endOfStream) {
325 lifecycleManager.closeStreamRemote(stream, ctx.newSucceededFuture());
326 }
327
328 return bytesToReturn;
329 } catch (Http2Exception e) {
330
331
332
333 int delta = unconsumedBytes - unconsumedBytes(stream);
334 bytesToReturn -= delta;
335 throw e;
336 } catch (RuntimeException e) {
337
338
339
340 int delta = unconsumedBytes - unconsumedBytes(stream);
341 bytesToReturn -= delta;
342 throw e;
343 } finally {
344
345 flowController.consumeBytes(stream, bytesToReturn);
346 }
347 }
348
349 @Override
350 public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
351 boolean endOfStream) throws Http2Exception {
352 onHeadersRead(ctx, streamId, headers, 0, DEFAULT_PRIORITY_WEIGHT, false, padding, endOfStream);
353 }
354
355 @Override
356 public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency,
357 short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception {
358 Http2Stream stream = connection.stream(streamId);
359 boolean allowHalfClosedRemote = false;
360 boolean isTrailers = false;
361 if (stream == null && !connection.streamMayHaveExisted(streamId)) {
362 stream = connection.remote().createStream(streamId, endOfStream);
363
364 allowHalfClosedRemote = stream.state() == HALF_CLOSED_REMOTE;
365 } else if (stream != null) {
366 isTrailers = stream.isHeadersReceived();
367 }
368
369 if (shouldIgnoreHeadersOrDataFrame(ctx, streamId, stream, endOfStream, "HEADERS")) {
370 return;
371 }
372
373 boolean isInformational = !connection.isServer() &&
374 HttpStatusClass.valueOf(headers.status()) == INFORMATIONAL;
375 if ((isInformational || !endOfStream) && stream.isHeadersReceived() || stream.isTrailersReceived()) {
376 throw streamError(streamId, PROTOCOL_ERROR,
377 "Stream %d received too many headers EOS: %s state: %s",
378 streamId, endOfStream, stream.state());
379 }
380
381 switch (stream.state()) {
382 case RESERVED_REMOTE:
383 stream.open(endOfStream);
384 break;
385 case OPEN:
386 case HALF_CLOSED_LOCAL:
387
388 break;
389 case HALF_CLOSED_REMOTE:
390 if (!allowHalfClosedRemote) {
391 throw streamError(stream.id(), STREAM_CLOSED, "Stream %d in unexpected state: %s",
392 stream.id(), stream.state());
393 }
394 break;
395 case CLOSED:
396 throw streamError(stream.id(), STREAM_CLOSED, "Stream %d in unexpected state: %s",
397 stream.id(), stream.state());
398 default:
399
400 throw connectionError(PROTOCOL_ERROR, "Stream %d in unexpected state: %s", stream.id(),
401 stream.state());
402 }
403
404 if (!isTrailers) {
405
406 List<? extends CharSequence> contentLength = headers.getAll(HttpHeaderNames.CONTENT_LENGTH);
407 if (contentLength != null && !contentLength.isEmpty()) {
408 try {
409 long cLength = HttpUtil.normalizeAndGetContentLength(contentLength, false, true);
410 if (cLength != -1) {
411 headers.setLong(HttpHeaderNames.CONTENT_LENGTH, cLength);
412 stream.setProperty(contentLengthKey, new ContentLength(cLength));
413 }
414 } catch (IllegalArgumentException e) {
415 throw streamError(stream.id(), PROTOCOL_ERROR, e,
416 "Multiple content-length headers received");
417 }
418 }
419 } else if (validateHeaders && !headers.isEmpty()) {
420
421
422 for (Iterator<Entry<CharSequence, CharSequence>> iterator =
423 headers.iterator(); iterator.hasNext();) {
424 CharSequence name = iterator.next().getKey();
425 if (Http2Headers.PseudoHeaderName.hasPseudoHeaderFormat(name)) {
426 throw streamError(stream.id(), PROTOCOL_ERROR,
427 "Found invalid Pseudo-Header in trailers: %s", name);
428 }
429 }
430 }
431
432 stream.headersReceived(isInformational);
433 verifyContentLength(stream, 0, endOfStream);
434 encoder.flowController().updateDependencyTree(streamId, streamDependency, weight, exclusive);
435 listener.onHeadersRead(ctx, streamId, headers, streamDependency,
436 weight, exclusive, padding, endOfStream);
437
438 if (endOfStream) {
439 lifecycleManager.closeStreamRemote(stream, ctx.newSucceededFuture());
440 }
441 }
442
443 @Override
444 public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight,
445 boolean exclusive) throws Http2Exception {
446 encoder.flowController().updateDependencyTree(streamId, streamDependency, weight, exclusive);
447
448 listener.onPriorityRead(ctx, streamId, streamDependency, weight, exclusive);
449 }
450
451 @Override
452 public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) throws Http2Exception {
453 Http2Stream stream = connection.stream(streamId);
454 if (stream == null) {
455 verifyStreamMayHaveExisted(streamId, false, "RST_STREAM");
456 return;
457 }
458
459 switch(stream.state()) {
460 case IDLE:
461 throw connectionError(PROTOCOL_ERROR, "RST_STREAM received for IDLE stream %d", streamId);
462 case CLOSED:
463 return;
464 default:
465 break;
466 }
467
468 listener.onRstStreamRead(ctx, streamId, errorCode);
469
470 lifecycleManager.closeStream(stream, ctx.newSucceededFuture());
471 }
472
473 @Override
474 public void onSettingsAckRead(ChannelHandlerContext ctx) throws Http2Exception {
475
476 Http2Settings settings = encoder.pollSentSettings();
477
478 if (settings != null) {
479 applyLocalSettings(settings);
480 }
481
482 listener.onSettingsAckRead(ctx);
483 }
484
485
486
487
488
489
490 private void applyLocalSettings(Http2Settings settings) throws Http2Exception {
491 Boolean pushEnabled = settings.pushEnabled();
492 final Http2FrameReader.Configuration config = frameReader.configuration();
493 final Http2HeadersDecoder.Configuration headerConfig = config.headersConfiguration();
494 final Http2FrameSizePolicy frameSizePolicy = config.frameSizePolicy();
495 if (pushEnabled != null) {
496 if (connection.isServer()) {
497 throw connectionError(PROTOCOL_ERROR, "Server sending SETTINGS frame with ENABLE_PUSH specified");
498 }
499 connection.local().allowPushTo(pushEnabled);
500 }
501
502 Long maxConcurrentStreams = settings.maxConcurrentStreams();
503 if (maxConcurrentStreams != null) {
504 connection.remote().maxActiveStreams((int) min(maxConcurrentStreams, MAX_VALUE));
505 }
506
507 Long headerTableSize = settings.headerTableSize();
508 if (headerTableSize != null) {
509 headerConfig.maxHeaderTableSize(headerTableSize);
510 }
511
512 Long maxHeaderListSize = settings.maxHeaderListSize();
513 if (maxHeaderListSize != null) {
514 headerConfig.maxHeaderListSize(maxHeaderListSize, calculateMaxHeaderListSizeGoAway(maxHeaderListSize));
515 }
516
517 Integer maxFrameSize = settings.maxFrameSize();
518 if (maxFrameSize != null) {
519 frameSizePolicy.maxFrameSize(maxFrameSize);
520 }
521
522 Integer initialWindowSize = settings.initialWindowSize();
523 if (initialWindowSize != null) {
524 flowController().initialWindowSize(initialWindowSize);
525 }
526 }
527
528 @Override
529 public void onSettingsRead(final ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception {
530 if (settingsReceivedConsumer == null) {
531
532
533
534 encoder.writeSettingsAck(ctx, ctx.newPromise());
535
536 encoder.remoteSettings(settings);
537 } else {
538 settingsReceivedConsumer.consumeReceivedSettings(settings);
539 }
540
541 listener.onSettingsRead(ctx, settings);
542 }
543
544 @Override
545 public void onPingRead(ChannelHandlerContext ctx, long data) throws Http2Exception {
546 if (autoAckPing) {
547
548 encoder.writePing(ctx, true, data, ctx.newPromise());
549 }
550 listener.onPingRead(ctx, data);
551 }
552
553 @Override
554 public void onPingAckRead(ChannelHandlerContext ctx, long data) throws Http2Exception {
555 listener.onPingAckRead(ctx, data);
556 }
557
558 @Override
559 public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
560 Http2Headers headers, int padding) throws Http2Exception {
561
562 if (connection().isServer()) {
563 throw connectionError(PROTOCOL_ERROR, "A client cannot push.");
564 }
565
566 Http2Stream parentStream = connection.stream(streamId);
567
568 if (shouldIgnoreHeadersOrDataFrame(ctx, streamId, parentStream, false, "PUSH_PROMISE")) {
569 return;
570 }
571
572 switch (parentStream.state()) {
573 case OPEN:
574 case HALF_CLOSED_LOCAL:
575
576 break;
577 default:
578
579 throw connectionError(PROTOCOL_ERROR,
580 "Stream %d in unexpected state for receiving push promise: %s",
581 parentStream.id(), parentStream.state());
582 }
583
584 if (!requestVerifier.isAuthoritative(ctx, headers)) {
585 throw streamError(promisedStreamId, PROTOCOL_ERROR,
586 "Promised request on stream %d for promised stream %d is not authoritative",
587 streamId, promisedStreamId);
588 }
589 if (!requestVerifier.isCacheable(headers)) {
590 throw streamError(promisedStreamId, PROTOCOL_ERROR,
591 "Promised request on stream %d for promised stream %d is not known to be cacheable",
592 streamId, promisedStreamId);
593 }
594 if (!requestVerifier.isSafe(headers)) {
595 throw streamError(promisedStreamId, PROTOCOL_ERROR,
596 "Promised request on stream %d for promised stream %d is not known to be safe",
597 streamId, promisedStreamId);
598 }
599
600
601 connection.remote().reservePushStream(promisedStreamId, parentStream);
602
603 listener.onPushPromiseRead(ctx, streamId, promisedStreamId, headers, padding);
604 }
605
606 @Override
607 public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)
608 throws Http2Exception {
609 onGoAwayRead0(ctx, lastStreamId, errorCode, debugData);
610 }
611
612 @Override
613 public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement)
614 throws Http2Exception {
615 Http2Stream stream = connection.stream(streamId);
616 if (stream == null || stream.state() == CLOSED || streamCreatedAfterGoAwaySent(streamId)) {
617
618 verifyStreamMayHaveExisted(streamId, false, "WINDOW_UPDATE");
619 return;
620 }
621
622
623 encoder.flowController().incrementWindowSize(stream, windowSizeIncrement);
624
625 listener.onWindowUpdateRead(ctx, streamId, windowSizeIncrement);
626 }
627
628 @Override
629 public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,
630 ByteBuf payload) throws Http2Exception {
631 onUnknownFrame0(ctx, frameType, streamId, flags, payload);
632 }
633
634
635
636
637
638 private boolean shouldIgnoreHeadersOrDataFrame(ChannelHandlerContext ctx, int streamId, Http2Stream stream,
639 boolean endOfStream, String frameName) throws Http2Exception {
640 if (stream == null) {
641 if (streamCreatedAfterGoAwaySent(streamId)) {
642 logger.info("{} ignoring {} frame for stream {}. Stream sent after GOAWAY sent",
643 ctx.channel(), frameName, streamId);
644 return true;
645 }
646
647
648
649 verifyStreamMayHaveExisted(streamId, endOfStream, frameName);
650
651
652
653
654 throw streamError(streamId, STREAM_CLOSED, "Received %s frame for an unknown stream %d",
655 frameName, streamId);
656 }
657 if (stream.isResetSent() || streamCreatedAfterGoAwaySent(streamId)) {
658
659
660
661
662
663 if (logger.isInfoEnabled()) {
664 logger.info("{} ignoring {} frame for stream {}", ctx.channel(), frameName,
665 stream.isResetSent() ? "RST_STREAM sent." :
666 "Stream created after GOAWAY sent. Last known stream by peer " +
667 connection.remote().lastStreamKnownByPeer());
668 }
669
670 return true;
671 }
672 return false;
673 }
674
675
676
677
678
679
680
681
682
683
684
685
686
687 private boolean streamCreatedAfterGoAwaySent(int streamId) {
688 Endpoint<?> remote = connection.remote();
689 return connection.goAwaySent() && remote.isValidStreamId(streamId) &&
690 streamId > remote.lastStreamKnownByPeer();
691 }
692
693 private void verifyStreamMayHaveExisted(int streamId, boolean endOfStream, String frameName)
694 throws Http2Exception {
695 if (!connection.streamMayHaveExisted(streamId)) {
696 throw connectionError(PROTOCOL_ERROR,
697 "Stream %d does not exist for inbound frame %s, endOfStream = %b",
698 streamId, frameName, endOfStream);
699 }
700 }
701 }
702
703 private final class PrefaceFrameListener implements Http2FrameListener {
704
705
706
707
708
709
710 private void verifyPrefaceReceived() throws Http2Exception {
711 if (!prefaceReceived()) {
712 throw connectionError(PROTOCOL_ERROR, "Received non-SETTINGS as first frame.");
713 }
714 }
715
716 @Override
717 public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream)
718 throws Http2Exception {
719 verifyPrefaceReceived();
720 return internalFrameListener.onDataRead(ctx, streamId, data, padding, endOfStream);
721 }
722
723 @Override
724 public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding,
725 boolean endOfStream) throws Http2Exception {
726 verifyPrefaceReceived();
727 internalFrameListener.onHeadersRead(ctx, streamId, headers, padding, endOfStream);
728 }
729
730 @Override
731 public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency,
732 short weight, boolean exclusive, int padding, boolean endOfStream) throws Http2Exception {
733 verifyPrefaceReceived();
734 internalFrameListener.onHeadersRead(ctx, streamId, headers, streamDependency, weight,
735 exclusive, padding, endOfStream);
736 }
737
738 @Override
739 public void onPriorityRead(ChannelHandlerContext ctx, int streamId, int streamDependency, short weight,
740 boolean exclusive) throws Http2Exception {
741 verifyPrefaceReceived();
742 internalFrameListener.onPriorityRead(ctx, streamId, streamDependency, weight, exclusive);
743 }
744
745 @Override
746 public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) throws Http2Exception {
747 verifyPrefaceReceived();
748 internalFrameListener.onRstStreamRead(ctx, streamId, errorCode);
749 }
750
751 @Override
752 public void onSettingsAckRead(ChannelHandlerContext ctx) throws Http2Exception {
753 verifyPrefaceReceived();
754 internalFrameListener.onSettingsAckRead(ctx);
755 }
756
757 @Override
758 public void onSettingsRead(ChannelHandlerContext ctx, Http2Settings settings) throws Http2Exception {
759
760
761 if (!prefaceReceived()) {
762 internalFrameListener = new FrameReadListener();
763 }
764 internalFrameListener.onSettingsRead(ctx, settings);
765 }
766
767 @Override
768 public void onPingRead(ChannelHandlerContext ctx, long data) throws Http2Exception {
769 verifyPrefaceReceived();
770 internalFrameListener.onPingRead(ctx, data);
771 }
772
773 @Override
774 public void onPingAckRead(ChannelHandlerContext ctx, long data) throws Http2Exception {
775 verifyPrefaceReceived();
776 internalFrameListener.onPingAckRead(ctx, data);
777 }
778
779 @Override
780 public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId,
781 Http2Headers headers, int padding) throws Http2Exception {
782 verifyPrefaceReceived();
783 internalFrameListener.onPushPromiseRead(ctx, streamId, promisedStreamId, headers, padding);
784 }
785
786 @Override
787 public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData)
788 throws Http2Exception {
789 onGoAwayRead0(ctx, lastStreamId, errorCode, debugData);
790 }
791
792 @Override
793 public void onWindowUpdateRead(ChannelHandlerContext ctx, int streamId, int windowSizeIncrement)
794 throws Http2Exception {
795 verifyPrefaceReceived();
796 internalFrameListener.onWindowUpdateRead(ctx, streamId, windowSizeIncrement);
797 }
798
799 @Override
800 public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId, Http2Flags flags,
801 ByteBuf payload) throws Http2Exception {
802 onUnknownFrame0(ctx, frameType, streamId, flags, payload);
803 }
804 }
805
806 private static final class ContentLength {
807 private final long expected;
808 private long seen;
809
810 ContentLength(long expected) {
811 this.expected = expected;
812 }
813
814 void increaseReceivedBytes(boolean server, int streamId, int bytes, boolean isEnd) throws Http2Exception {
815 seen += bytes;
816
817 if (seen < 0) {
818 throw streamError(streamId, PROTOCOL_ERROR,
819 "Received amount of data did overflow and so not match content-length header %d", expected);
820 }
821
822 if (seen > expected) {
823 throw streamError(streamId, PROTOCOL_ERROR,
824 "Received amount of data %d does not match content-length header %d", seen, expected);
825 }
826
827 if (isEnd) {
828 if (seen == 0 && !server) {
829
830 return;
831 }
832
833
834 if (expected > seen) {
835 throw streamError(streamId, PROTOCOL_ERROR,
836 "Received amount of data %d does not match content-length header %d", seen, expected);
837 }
838 }
839 }
840 }
841 }