1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.james.jspf.terms;
22
23 import org.apache.james.jspf.core.DNSLookupContinuation;
24 import org.apache.james.jspf.core.IPAddr;
25 import org.apache.james.jspf.core.Inet6Util;
26 import org.apache.james.jspf.core.SPFSession;
27 import org.apache.james.jspf.core.exceptions.PermErrorException;
28
29
30
31
32
33 public class IP4Mechanism extends GenericMechanism {
34
35
36
37
38 public static final String REGEX = "[iI][pP][4]" + "\\:" + "([0-9.]+)"
39 + "(?:" + IP4_CIDR_LENGTH_REGEX + ")?";
40
41 private IPAddr ip = null;
42
43
44
45
46 public DNSLookupContinuation checkSPF(SPFSession spfData) throws PermErrorException {
47 IPAddr originalIP;
48
49 originalIP = IPAddr.getAddress(spfData.getIpAddress(), getIp()
50 .getMaskLength());
51
52 spfData.setAttribute(Directive.ATTRIBUTE_MECHANISM_RESULT, Boolean.valueOf(getIp().getMaskedIPAddress().equals(originalIP.getMaskedIPAddress())));
53
54 return null;
55 }
56
57
58
59
60 public synchronized void config(Configuration params) throws PermErrorException {
61 if (params.groupCount() == 0) {
62 throw new PermErrorException("Missing ip");
63 }
64 String ipString = params.group(1);
65 if (!isValidAddress(ipString)) {
66 throw new PermErrorException("Invalid Address: " + ipString);
67 }
68 int maskLength = getMaxCidr();
69 if (params.groupCount() >= 2 && params.group(2) != null) {
70 String maskLengthString = params.group(2);
71 maskLength = Integer.parseInt(maskLengthString);
72
73 if (maskLength > getMaxCidr() || (maskLengthString.length() > 1 && maskLengthString.startsWith("0"))) {
74 throw new PermErrorException("Invalid CIDR: " + maskLengthString);
75 }
76 }
77 ip = IPAddr.getAddress(ipString, maskLength);
78 }
79
80
81
82
83 protected boolean isValidAddress(String ipString) {
84 return Inet6Util.isValidIPV4Address(ipString);
85 }
86
87
88
89
90
91
92 protected int getMaxCidr() {
93 return 32;
94 }
95
96
97
98
99 protected synchronized IPAddr getIp() {
100 return ip;
101 }
102
103
104
105
106 public String toString() {
107 if (getIp().getMaskLength() == getMaxCidr()) {
108 return "ip4:"+getIp().getIPAddress();
109 } else {
110 return "ip4:"+getIp().getIPAddress()+"/"+getIp().getMaskLength();
111 }
112 }
113
114 }