From 8016a193b9469f0d918937e674a25a312bd1b057 Mon Sep 17 00:00:00 2001 From: Bruno Studer Date: Mon, 22 Jan 2018 17:04:08 +0100 Subject: [PATCH] Optimize IpAddressMatcher Get rid of byte array allocation in matcher and small optimizations --- .../web/util/matcher/IpAddressMatcher.java | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java b/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java index 86d252d376..98e5885416 100644 --- a/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java +++ b/web/src/main/java/org/springframework/security/web/util/matcher/IpAddressMatcher.java @@ -17,7 +17,6 @@ package org.springframework.security.web.util.matcher; import java.net.InetAddress; import java.net.UnknownHostException; -import java.util.Arrays; import javax.servlet.http.HttpServletRequest; @@ -76,26 +75,21 @@ public final class IpAddressMatcher implements RequestMatcher { byte[] remAddr = remoteAddress.getAddress(); byte[] reqAddr = requiredAddress.getAddress(); - int oddBits = nMaskBits % 8; - int nMaskBytes = nMaskBits / 8 + (oddBits == 0 ? 0 : 1); - byte[] mask = new byte[nMaskBytes]; - - Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte) 0xFF); - - if (oddBits != 0) { - int finalByte = (1 << oddBits) - 1; - finalByte <<= 8 - oddBits; - mask[mask.length - 1] = (byte) finalByte; - } + int nMaskFullBytes = nMaskBits / 8; + byte finalByte = (byte) (0xFF00 >> (nMaskBits & 0x07)); // System.out.println("Mask is " + new sun.misc.HexDumpEncoder().encode(mask)); - for (int i = 0; i < mask.length; i++) { - if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) { + for (int i = 0; i < nMaskFullBytes; i++) { + if (remAddr[i] != reqAddr[i]) { return false; } } + if (finalByte != 0) { + return (remAddr[nMaskFullBytes] & finalByte) == (reqAddr[nMaskFullBytes] & finalByte); + } + return true; }