01: package net.sourceforge.pmd.rules.basic;
02:
03: import java.net.InetAddress;
04: import java.util.regex.Pattern;
05:
06: import net.sourceforge.pmd.AbstractRule;
07: import net.sourceforge.pmd.ast.ASTLiteral;
08:
09: public class AvoidUsingHardCodedIP extends AbstractRule {
10:
11: private static final String IPv4_REGEXP = "^\"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\"$";
12: private static final String IPv6_REGEXP = "^\"[0-9a-fA-F:]+:[0-9a-fA-F]+\"$";
13: private static final String IPv4_MAPPED_IPv6_REGEXP = "^\"[0-9a-fA-F:]+:[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\"$";
14:
15: private static final Pattern IPv4_PATTERM = Pattern
16: .compile(IPv4_REGEXP);
17: private static final Pattern IPv6_PATTERM = Pattern
18: .compile(IPv6_REGEXP);
19: private static final Pattern IPv4_MAPPED_IPv6_PATTERM = Pattern
20: .compile(IPv4_MAPPED_IPv6_REGEXP);
21:
22: /**
23: * This method checks if the Literal matches the pattern. If it does, a violation is logged.
24: */
25: public Object visit(ASTLiteral node, Object data) {
26: String image = node.getImage();
27: if (image == null || image.length() < 3
28: || image.charAt(0) != '"'
29: || image.charAt(image.length() - 1) != '"') {
30: return data;
31: }
32:
33: /* Tests before calls to matches() ensure that the literal is '"[0-9:].*"' */
34: char c = image.charAt(1);
35: if ((Character.isDigit(c) || c == ':')
36: && (IPv4_PATTERM.matcher(image).matches()
37: || IPv6_PATTERM.matcher(image).matches() || IPv4_MAPPED_IPv6_PATTERM
38: .matcher(image).matches())) {
39: try {
40: // as patterns are not 100% accurate, test address
41: InetAddress.getByName(image.substring(1,
42: image.length() - 1));
43:
44: // no error creating address object, pattern must be valid
45: addViolation(data, node);
46: } catch (Exception e) {
47: // ignored: invalid format
48: }
49: }
50: return data;
51: }
52:
53: }
|