View Javadoc

1   package net.sourceforge.pmd.rules.basic;
2   
3   import java.net.InetAddress;
4   import java.util.regex.Pattern;
5   
6   import net.sourceforge.pmd.AbstractJavaRule;
7   import net.sourceforge.pmd.ast.ASTLiteral;
8   
9   public class AvoidUsingHardCodedIP extends AbstractJavaRule {
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.compile(IPv4_REGEXP);
16      private static final Pattern IPv6_PATTERM = Pattern.compile(IPv6_REGEXP);
17      private static final Pattern IPv4_MAPPED_IPv6_PATTERM = Pattern.compile(IPv4_MAPPED_IPv6_REGEXP);
18  
19      /**
20       * This method checks if the Literal matches the pattern. If it does, a violation is logged.
21       */
22      public Object visit(ASTLiteral node, Object data) {
23          String image = node.getImage();
24          if (image == null || image.length() < 3 || image.charAt(0) != '"' ||
25                  image.charAt(image.length()-1) != '"') {
26              return data;
27          }
28          
29  	/* Tests before calls to matches() ensure that the literal is '"[0-9:].*"' */
30          char c = image.charAt(1);
31          if ((Character.isDigit(c) || c == ':') &&
32                  (IPv4_PATTERM.matcher(image).matches() ||
33                          IPv6_PATTERM.matcher(image).matches() ||
34                          IPv4_MAPPED_IPv6_PATTERM.matcher(image).matches())) {
35              try {
36                  // as patterns are not 100% accurate, test address
37                  InetAddress.getByName(image.substring(1, image.length()-1));
38                  
39                  // no error creating address object, pattern must be valid
40                  addViolation(data, node);
41              } catch (Exception e) {
42  		// ignored: invalid format
43              }
44          }
45          return data;
46      }
47  
48  }