View Javadoc
1   /*
2    * Copyright 2023 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec.http2;
17  
18  import io.netty.channel.ChannelHandlerContext;
19  import io.netty.util.internal.logging.InternalLogger;
20  import io.netty.util.internal.logging.InternalLoggerFactory;
21  
22  import java.util.concurrent.TimeUnit;
23  
24  
25  final class Http2MaxRstFrameListener extends Http2FrameListenerDecorator {
26      private static final InternalLogger logger = InternalLoggerFactory.getInstance(Http2MaxRstFrameListener.class);
27      private static final Http2Exception RST_FRAME_RATE_EXCEEDED = Http2Exception.newStatic(Http2Error.ENHANCE_YOUR_CALM,
28              "Maximum number of RST frames reached",
29              Http2Exception.ShutdownHint.HARD_SHUTDOWN, Http2MaxRstFrameListener.class, "onRstStreamRead(..)");
30  
31      private final long nanosPerWindow;
32      private final int maxRstFramesPerWindow;
33      private long lastRstFrameNano = System.nanoTime();
34      private int receivedRstInWindow;
35  
36      Http2MaxRstFrameListener(Http2FrameListener listener, int maxRstFramesPerWindow, int secondsPerWindow) {
37          super(listener);
38          this.maxRstFramesPerWindow = maxRstFramesPerWindow;
39          this.nanosPerWindow = TimeUnit.SECONDS.toNanos(secondsPerWindow);
40      }
41  
42      @Override
43      public void onRstStreamRead(ChannelHandlerContext ctx, int streamId, long errorCode) throws Http2Exception {
44          long currentNano = System.nanoTime();
45          if (currentNano - lastRstFrameNano >= nanosPerWindow) {
46              lastRstFrameNano = currentNano;
47              receivedRstInWindow = 1;
48          } else {
49              receivedRstInWindow++;
50              if (receivedRstInWindow > maxRstFramesPerWindow) {
51                  logger.debug("{} Maximum number {} of RST frames reached within {} seconds, " +
52                                  "closing connection with {} error", ctx.channel(), maxRstFramesPerWindow,
53                          TimeUnit.NANOSECONDS.toSeconds(nanosPerWindow), RST_FRAME_RATE_EXCEEDED.error(),
54                          RST_FRAME_RATE_EXCEEDED);
55                  throw RST_FRAME_RATE_EXCEEDED;
56              }
57          }
58          super.onRstStreamRead(ctx, streamId, errorCode);
59      }
60  }