This is an automated email from the ASF dual-hosted git repository.

chibenwa pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-jspf.git

commit a3b71adb7a47fe3f6587074a18583af02d8b4979
Author: Benoit TELLIER <[email protected]>
AuthorDate: Thu Nov 19 17:36:02 2026 +0100

    [PERF] IPAddr: parse an address text once, without a String per digit
    
    IPAddr.stringToInternal validated an IPv4 text with isValidIPV4Address
    twice, once in isValidIP and again in
    createByteArrayFromIPAddressString, which then tokenized it with a
    StringTokenizer and Integer.parseInt. isValidIPV4Address grew each
    octet with word += c and parsed it with Integer.parseInt. Half of the
    CPU of the hostile mx check (2500 A records per check) and 12-23% of
    the legitimate checks.
    
    parseIPV4Address validates and converts an IPv4 text in one pass,
    reading the digits as Integer.parseInt did. stringToInternal uses it,
    and only for a text that is not IPv4 validates the IPv6 address
    before converting it. isValidIP6Address keeps its word in a reused
    StringBuilder and counts the groups without String.split, and the
    ip4 mechanism checks the leading zeros without split and a stream.
    
    The accepted addresses and their bytes are unchanged: compared with
    the former code on three million random address strings.
---
 .../java/org/apache/james/jspf/core/IPAddr.java    |  19 ++--
 .../java/org/apache/james/jspf/core/Inet6Util.java | 116 ++++++++++++---------
 .../org/apache/james/jspf/terms/IP4Mechanism.java  |  14 ++-
 .../org/apache/james/jspf/core/IPAddrTest.java     |  29 ++++++
 4 files changed, 117 insertions(+), 61 deletions(-)

diff --git a/resolver/src/main/java/org/apache/james/jspf/core/IPAddr.java 
b/resolver/src/main/java/org/apache/james/jspf/core/IPAddr.java
index e3d49bb..f2ab6d6 100644
--- a/resolver/src/main/java/org/apache/james/jspf/core/IPAddr.java
+++ b/resolver/src/main/java/org/apache/james/jspf/core/IPAddr.java
@@ -205,15 +205,22 @@ public class IPAddr {
      *             on error
      */
     private void stringToInternal(String netAddress) throws PermErrorException 
{
-        // createByteArrayFromIPAddressString expects a valid address: it 
fails on "" or "[", ignores
-        // a group without ":" or "." ("2" read as ::), and writes past its 
array on too many groups
-        if (!isValidIP(netAddress)) {
+        if (netAddress == null) {
             throw new PermErrorException("Not a valid address: " + netAddress);
         }
-
         try {
-            byte[] bytes = 
Inet6Util.createByteArrayFromIPAddressString(netAddress);
-    
+            // an IPv4 address is validated and converted in one pass
+            byte[] bytes = Inet6Util.parseIPV4Address(netAddress);
+            if (bytes == null) {
+                // createByteArrayFromIP6AddressString expects a valid 
address: it fails on "" or "[",
+                // ignores a group without ":" or "." ("2" read as ::), and 
writes past its array on
+                // too many groups
+                if (!Inet6Util.isValidIP6Address(netAddress)) {
+                    throw new PermErrorException("Not a valid address: " + 
netAddress);
+                }
+                bytes = 
Inet6Util.createByteArrayFromIP6AddressString(netAddress);
+            }
+
             if (bytes.length == 4) {
                 for (int i = 0; i < bytes.length; i++) {
                     address[i] = bytes[i];
diff --git a/resolver/src/main/java/org/apache/james/jspf/core/Inet6Util.java 
b/resolver/src/main/java/org/apache/james/jspf/core/Inet6Util.java
index 95853b8..35c7745 100644
--- a/resolver/src/main/java/org/apache/james/jspf/core/Inet6Util.java
+++ b/resolver/src/main/java/org/apache/james/jspf/core/Inet6Util.java
@@ -42,21 +42,18 @@ public class Inet6Util {
     public static byte[] createByteArrayFromIPAddressString(
             String ipAddressString) {
 
-        if (isValidIPV4Address(ipAddressString)) {
-            StringTokenizer tokenizer = new StringTokenizer(ipAddressString,
-                    ".");
-            String token = "";
-            int tempInt = 0;
-            byte[] byteAddress = new byte[4];
-            for (int i = 0; i < 4; i++) {
-                token = tokenizer.nextToken();
-                tempInt = Integer.parseInt(token);
-                byteAddress[i] = (byte) tempInt;
-            }
-
-            return byteAddress;
+        byte[] ipv4Address = parseIPV4Address(ipAddressString);
+        if (ipv4Address != null) {
+            return ipv4Address;
         }
+        return createByteArrayFromIP6AddressString(ipAddressString);
+    }
 
+    /**
+     * Creates an byte[] based on the String of an IPv6 address, which must be 
valid (see
+     * {@link #isValidIP6Address(String)}): 4 bytes for an IPv4-mapped address 
(::ffff:a.b.c.d).
+     */
+    static byte[] createByteArrayFromIP6AddressString(String ipAddressString) {
         if (ipAddressString.charAt(0) == '[') {
             ipAddressString = ipAddressString.substring(1, ipAddressString
                     .length() - 1);
@@ -240,7 +237,8 @@ public class Inet6Util {
         int numberOfColons = 0;
         int numberOfPeriods = 0;
         int numberOfPercent = 0;
-        String word = "";
+        // the characters since the last ":" or ".", reused: a String per 
character was the main cost
+        StringBuilder word = new StringBuilder(4);
         char c = 0;
         char prevChar = 0;
         int offset = 0; // offset for [] ip addresses
@@ -286,7 +284,7 @@ public class Inet6Util {
                 if (numberOfColons == 7 && ipAddress.charAt(0 + offset) != ':'
                         && ipAddress.charAt(1 + offset) != ':')
                     return false;
-                word = "";
+                word.setLength(0);
                 break;
 
             case ':':
@@ -308,7 +306,7 @@ public class Inet6Util {
                         return false;
                     doubleColon = true;
                 }
-                word = "";
+                word.setLength(0);
                 break;
             case '%':
                 if (numberOfColons == 0)
@@ -338,7 +336,7 @@ public class Inet6Util {
                     if (!isValidHexChar(c))
                         return false;
                 }
-                word += c;
+                word.append(c);
             }
         }
 
@@ -357,7 +355,7 @@ public class Inet6Util {
             // a : or a .
             // If we did not end in :: then this is invalid
             if (numberOfPercent == 0) {
-                if (word.isEmpty() && ipAddress.charAt(length - 1 - offset) == 
':'
+                if (word.length() == 0 && ipAddress.charAt(length - 1 - 
offset) == ':'
                         && ipAddress.charAt(length - 2 - offset) != ':') {
                     return false;
                 }
@@ -377,28 +375,38 @@ public class Inet6Util {
      */
     private static boolean hasValidGroupCount(String address, boolean 
doubleColon) {
         int groups = 0;
-        for (String group : address.split(":")) {
-            if (group.indexOf('.') >= 0) {
+        int start = 0;
+        while (start <= address.length()) {
+            int end = address.indexOf(':', start);
+            if (end < 0) {
+                end = address.length();
+            }
+            if (address.lastIndexOf('.', end - 1) >= start) {
                 groups += 2;
-            } else if (!group.isEmpty()) {
+            } else if (end > start) {
                 groups++;
             }
+            start = end + 1;
         }
         return doubleColon ? groups <= 7 : groups == 8;
     }
 
     public static boolean isValidIP4Word(String word) {
+        return isValidIP4Word((CharSequence) word);
+    }
+
+    private static boolean isValidIP4Word(CharSequence word) {
         char c;
         if (word.length() < 1 || word.length() > 3)
             return false;
+        int value = 0;
         for (int i = 0; i < word.length(); i++) {
             c = word.charAt(i);
             if (!(c >= '0' && c <= '9'))
                 return false;
+            value = value * 10 + (c - '0');
         }
-        if (Integer.parseInt(word) > 255)
-            return false;
-        return true;
+        return value <= 255;
     }
 
     static boolean isValidHexChar(char c) {
@@ -414,40 +422,44 @@ public class Inet6Util {
      *         notation, false otherwise
      */
     public static boolean isValidIPV4Address(String value) {
+        return parseIPV4Address(value) != null;
+    }
 
-        int periods = 0;
-        int i = 0;
+    /**
+     * Parses an IPV4 address in dotted notation in one pass: four decimal 
numbers of 1 to 3 digits,
+     * each at most 255. The digits are the ones of Character.isDigit, as 
Integer.parseInt reads
+     * them.
+     *
+     * @return its 4 bytes, or null when the string is not an IPV4 address in 
dotted notation
+     */
+    static byte[] parseIPV4Address(String value) {
         int length = value.length();
-
         if (length > 15)
-            return false;
-        char c = 0;
-        String word = "";
-        for (i = 0; i < length; i++) {
-            c = value.charAt(i);
+            return null;
+        byte[] bytes = new byte[4];
+        int periods = 0;
+        int digits = 0;
+        int word = 0;
+        for (int i = 0; i < length; i++) {
+            char c = value.charAt(i);
             if (c == '.') {
-                periods++;
-                if (periods > 3)
-                    return false;
-                if (word.isEmpty())
-                    return false;
-                if (Integer.parseInt(word) > 255)
-                    return false;
-                word = "";
-            } else if (!(Character.isDigit(c)))
-                return false;
-            else {
-                if (word.length() > 2)
-                    return false;
-                word += c;
+                if (periods == 3 || digits == 0 || word > 255)
+                    return null;
+                bytes[periods++] = (byte) word;
+                digits = 0;
+                word = 0;
+            } else {
+                int digit = Character.digit(c, 10);
+                if (digit < 0 || digits == 3)
+                    return null;
+                word = word * 10 + digit;
+                digits++;
             }
         }
-
-        if (word.isEmpty() || Integer.parseInt(word) > 255)
-            return false;
-        if (periods != 3)
-            return false;
-        return true;
+        if (periods != 3 || digits == 0 || word > 255)
+            return null;
+        bytes[3] = (byte) word;
+        return bytes;
     }
 
 }
diff --git 
a/resolver/src/main/java/org/apache/james/jspf/terms/IP4Mechanism.java 
b/resolver/src/main/java/org/apache/james/jspf/terms/IP4Mechanism.java
index 4c99eb9..e777cdb 100644
--- a/resolver/src/main/java/org/apache/james/jspf/terms/IP4Mechanism.java
+++ b/resolver/src/main/java/org/apache/james/jspf/terms/IP4Mechanism.java
@@ -20,7 +20,6 @@
 
 package org.apache.james.jspf.terms;
 
-import java.util.Arrays;
 
 import org.apache.james.jspf.core.DNSLookupContinuation;
 import org.apache.james.jspf.core.IPAddr;
@@ -98,8 +97,17 @@ public class IP4Mechanism extends GenericMechanism {
      * @see org.apache.james.jspf.core.Inet6Util#isValidIPV4Address(String)
      */
     protected boolean isValidAddress(String ipString) {
-        return Inet6Util.isValidIPV4Address(ipString)
-            && Arrays.stream(ipString.split("\\.")).noneMatch(qnum -> 
qnum.length() > 1 && qnum.charAt(0) == '0');
+        if (!Inet6Util.isValidIPV4Address(ipString)) {
+            return false;
+        }
+        // RFC 7208 12: no leading zero
+        for (int i = 0; i < ipString.length() - 1; i++) {
+            boolean qnumStart = i == 0 || ipString.charAt(i - 1) == '.';
+            if (qnumStart && ipString.charAt(i) == '0' && ipString.charAt(i + 
1) != '.') {
+                return false;
+            }
+        }
+        return true;
     }
 
     /**
diff --git a/resolver/src/test/java/org/apache/james/jspf/core/IPAddrTest.java 
b/resolver/src/test/java/org/apache/james/jspf/core/IPAddrTest.java
index 7ce0199..2cc9b3f 100644
--- a/resolver/src/test/java/org/apache/james/jspf/core/IPAddrTest.java
+++ b/resolver/src/test/java/org/apache/james/jspf/core/IPAddrTest.java
@@ -161,4 +161,33 @@ public class IPAddrTest extends TestCase {
         assertTrue(Inet6Util.isValidIPV4Address("1.2.3.4"));
     }
 
+    public void testIPV4AddressIsParsedInOnePass() {
+        assertTrue(java.util.Arrays.equals(new byte[] {1, 2, (byte) 254, 
(byte) 255},
+            Inet6Util.parseIPV4Address("1.2.254.255")));
+        assertNull(Inet6Util.parseIPV4Address("1.2.3.256"));
+        assertNull(Inet6Util.parseIPV4Address("1.2.3.4.5"));
+        assertNull(Inet6Util.parseIPV4Address("1.2.3"));
+        assertNull(Inet6Util.parseIPV4Address("1.2.3.0001"));
+        assertNull(Inet6Util.parseIPV4Address("1.2.3.a"));
+        assertNull(Inet6Util.parseIPV4Address("::1"));
+    }
+
+    public void testIPv4AndIPv6AddressesAreConverted() throws 
PermErrorException {
+        assertEquals("192.0.2.3", 
IPAddr.getAddress("192.0.2.3").getIPAddress());
+        assertEquals("2001:0DB8:0000:0000:0000:0000:0000:CB01", 
IPAddr.getAddress("2001:db8::cb01").getIPAddress());
+        assertEquals("192.0.2.3", 
IPAddr.getAddress("::ffff:192.0.2.3").getIPAddress());
+    }
+
+    public void testInvalidAddressesAreRejected() {
+        String[] invalid = {null, "", "[", "1.2.3", "1.2.3.256", 
"1:2:3:4:5:6:7:8:9", "2", "a.b.c.d"};
+        for (String address : invalid) {
+            try {
+                IPAddr.getAddress(address);
+                fail(address + " is not an address");
+            } catch (PermErrorException e) {
+                // expected
+            }
+        }
+    }
+
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to