1 /*
2 * Copyright 2012 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 org.jboss.netty.handler.ipfilter;
17
18 import org.jboss.netty.logging.InternalLogger;
19 import org.jboss.netty.logging.InternalLoggerFactory;
20 import org.jboss.netty.util.internal.StringUtil;
21
22 import java.net.UnknownHostException;
23 import java.util.ArrayList;
24
25 /**
26 * The Class IpFilterRuleList is a helper class to generate a List of Rules from a string.
27 * In case of parse errors no exceptions are thrown. The error is logged.
28 * <br>
29 * Rule List Syntax:
30 * <br>
31 * <pre>
32 * RuleList ::= Rule[,Rule]*
33 * Rule ::= AllowRule | BlockRule
34 * AllowRule ::= +Filter
35 * BlockRule ::= -Filter
36 * Filter ::= PatternFilter | CIDRFilter
37 * PatternFilter ::= @see PatternRule
38 * CIDRFilter ::= c:CIDRFilter
39 * CIDRFilter ::= @see CIDR.newCIDR(String)
40 * </pre>
41 * <br>
42 * Example: allow only localhost:
43 * <br>
44 * new IPFilterRuleHandler().addAll(new IpFilterRuleList("+n:localhost, -n:*"));
45 * <br>
46 */
47 public class IpFilterRuleList extends ArrayList<IpFilterRule> {
48 private static final long serialVersionUID = -6164162941749588780L;
49
50 private static final InternalLogger logger = InternalLoggerFactory.getInstance(IpFilterRuleList.class);
51
52 /**
53 * Instantiates a new ip filter rule list.
54 *
55 * @param rules the rules
56 */
57 public IpFilterRuleList(String rules) {
58 parseRules(rules);
59 }
60
61 private void parseRules(String rules) {
62 String[] ruless = StringUtil.split(rules, ',');
63 for (String rule : ruless) {
64 parseRule(rule.trim());
65 }
66 }
67
68 private void parseRule(String rule) {
69 if (rule == null || rule.length() == 0) {
70 return;
71 }
72 if (!(rule.startsWith("+") || rule.startsWith("-"))) {
73 if (logger.isErrorEnabled()) {
74 logger.error("syntax error in ip filter rule:" + rule);
75 }
76 return;
77 }
78
79 boolean allow = rule.startsWith("+");
80 if (rule.charAt(1) == 'n' || rule.charAt(1) == 'i') {
81 add(new PatternRule(allow, rule.substring(1)));
82 } else if (rule.charAt(1) == 'c') {
83 try {
84 add(new IpSubnetFilterRule(allow, rule.substring(3)));
85 } catch (UnknownHostException e) {
86 if (logger.isErrorEnabled()) {
87 logger.error("error parsing ip filter " + rule, e);
88 }
89 }
90 } else {
91 if (logger.isErrorEnabled()) {
92 logger.error("syntax error in ip filter rule:" + rule);
93 }
94 }
95 }
96 }