View Javadoc

1   /*
2    * Copyright 2014 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    *   http://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.ipfilter;
17  
18  import io.netty.channel.Channel;
19  import io.netty.channel.ChannelHandler.Sharable;
20  import io.netty.channel.ChannelHandlerContext;
21  
22  import java.net.InetSocketAddress;
23  import java.net.SocketAddress;
24  
25  /**
26   * This class allows one to filter new {@link Channel}s based on the
27   * {@link IpFilterRule}s passed to its constructor. If no rules are provided, all connections
28   * will be accepted.
29   *
30   * If you would like to explicitly take action on rejected {@link Channel}s, you should override
31   * {@link #channelRejected(ChannelHandlerContext, SocketAddress)}.
32   */
33  @Sharable
34  public class RuleBasedIpFilter extends AbstractRemoteAddressFilter<InetSocketAddress> {
35  
36      private final IpFilterRule[] rules;
37  
38      public RuleBasedIpFilter(IpFilterRule... rules) {
39          if (rules == null) {
40              throw new NullPointerException("rules");
41          }
42  
43          this.rules = rules;
44      }
45  
46      @Override
47      protected boolean accept(ChannelHandlerContext ctx, InetSocketAddress remoteAddress) throws Exception {
48          for (IpFilterRule rule : rules) {
49              if (rule == null) {
50                  break;
51              }
52  
53              if (rule.matches(remoteAddress)) {
54                  return rule.ruleType() == IpFilterRuleType.ACCEPT;
55              }
56          }
57  
58          return true;
59      }
60  }