Skip to content

Commit

Permalink
[ISSUE alibaba#5765] fix localhost not match ip (alibaba#5852)
Browse files Browse the repository at this point in the history
* rename IPUitl to InternetAddressUtil

* move isDomain to InternetAddressUtil

* [ISSUE alibaba#5765] fix localhost not match ip

* fix typo

* delete the verification IP, follow the single responsibility principle
  • Loading branch information
孙继峰 authored May 27, 2021
1 parent 3b3de66 commit 15c7183
Show file tree
Hide file tree
Showing 30 changed files with 160 additions and 172 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.naming.core.Instance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
Expand Down Expand Up @@ -86,8 +86,8 @@ public List<Instance> generateInstancesByIps(String serviceName, String rawProdu
}

private String[] generateIpAndPort(String ip) {
String[] result = IPUtil.splitIPPortStr(ip);
if (result.length != IPUtil.SPLIT_IP_PORT_RESULT_LENGTH) {
String[] result = InternetAddressUtil.splitIPPortStr(ip);
if (result.length != InternetAddressUtil.SPLIT_IP_PORT_RESULT_LENGTH) {
return new String[] {result[0], String.valueOf(AddressServerConstants.DEFAULT_SERVER_PORT)};
}
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import com.alibaba.nacos.address.misc.Loggers;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service;
Expand Down Expand Up @@ -87,8 +87,8 @@ public ResponseEntity<String> postCluster(@RequestParam(required = false) String
clusterObj.setHealthChecker(new AbstractHealthChecker.None());
serviceManager.createServiceIfAbsent(Constants.DEFAULT_NAMESPACE_ID, serviceName, false, clusterObj);
String[] ipArray = addressServerManager.splitIps(ips);
String checkResult = IPUtil.checkIPs(ipArray);
if (IPUtil.checkOK(checkResult)) {
String checkResult = InternetAddressUtil.checkIPs(ipArray);
if (InternetAddressUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray);
for (Instance instance : instanceList) {
Expand Down Expand Up @@ -141,8 +141,8 @@ public ResponseEntity deleteCluster(@RequestParam(required = false) String produ
}
// delete specified ip list
String[] ipArray = addressServerManager.splitIps(ips);
String checkResult = IPUtil.checkIPs(ipArray);
if (IPUtil.checkOK(checkResult)) {
String checkResult = InternetAddressUtil.checkIPs(ipArray);
if (InternetAddressUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray);
serviceManager.removeInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
import com.alibaba.nacos.common.lifecycle.Closeable;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.utils.IoUtils;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.common.utils.ThreadUtils;
import org.slf4j.Logger;
Expand Down Expand Up @@ -89,9 +89,9 @@ public ServerListManager(List<String> fixed, String namespace) {
this.isStarted = true;
List<String> serverAddrs = new ArrayList<String>();
for (String serverAddr : fixed) {
String[] serverAddrArr = IPUtil.splitIPPortStr(serverAddr);
String[] serverAddrArr = InternetAddressUtil.splitIPPortStr(serverAddr);
if (serverAddrArr.length == 1) {
serverAddrs.add(serverAddrArr[0] + IPUtil.IP_PORT_SPLITER + ParamUtil.getDefaultServerPort());
serverAddrs.add(serverAddrArr[0] + InternetAddressUtil.IP_PORT_SPLITER + ParamUtil.getDefaultServerPort());
} else {
serverAddrs.add(serverAddr);
}
Expand Down Expand Up @@ -159,9 +159,9 @@ public ServerListManager(Properties properties) throws NacosException {
if (serverAddr.startsWith(HTTPS) || serverAddr.startsWith(HTTP)) {
serverAddrs.add(serverAddr);
} else {
String[] serverAddrArr = IPUtil.splitIPPortStr(serverAddr);
String[] serverAddrArr = InternetAddressUtil.splitIPPortStr(serverAddr);
if (serverAddrArr.length == 1) {
serverAddrs.add(HTTP + serverAddrArr[0] + IPUtil.IP_PORT_SPLITER + ParamUtil
serverAddrs.add(HTTP + serverAddrArr[0] + InternetAddressUtil.IP_PORT_SPLITER + ParamUtil
.getDefaultServerPort());
} else {
serverAddrs.add(HTTP + serverAddr);
Expand Down Expand Up @@ -358,10 +358,10 @@ private List<String> getApacheServerList(String url, String name) {
List<String> result = new ArrayList<String>(lines.size());
for (String serverAddr : lines) {
if (StringUtils.isNotBlank(serverAddr)) {
String[] ipPort = IPUtil.splitIPPortStr(serverAddr.trim());
String[] ipPort = InternetAddressUtil.splitIPPortStr(serverAddr.trim());
String ip = ipPort[0].trim();
if (ipPort.length == 1) {
result.add(ip + IPUtil.IP_PORT_SPLITER + ParamUtil.getDefaultServerPort());
result.add(ip + InternetAddressUtil.IP_PORT_SPLITER + ParamUtil.getDefaultServerPort());
} else {
result.add(serverAddr);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
package com.alibaba.nacos.client.config.utils;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.common.utils.StringUtils;

import java.util.List;
Expand Down Expand Up @@ -190,7 +190,7 @@ public static void checkBetaIps(String betaIps) throws NacosException {
}
String[] ipsArr = betaIps.split(",");
for (String ip : ipsArr) {
if (!IPUtil.isIP(ip)) {
if (!InternetAddressUtil.isIP(ip)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, "betaIps invalid");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.utils.ConvertUtils;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.InternetAddressUtil;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.fasterxml.jackson.core.type.TypeReference;
Expand Down Expand Up @@ -429,8 +429,8 @@ public String callServer(String api, Map<String, String> params, Map<String, Str
if (curServer.startsWith(UtilAndComs.HTTPS) || curServer.startsWith(UtilAndComs.HTTP)) {
url = curServer + api;
} else {
if (!IPUtil.containsPort(curServer)) {
curServer = curServer + IPUtil.IP_PORT_SPLITER + serverPort;
if (!InternetAddressUtil.containsPort(curServer)) {
curServer = curServer + InternetAddressUtil.IP_PORT_SPLITER + serverPort;
}
url = NamingHttpClientManager.getInstance().getPrefix() + curServer + api;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

package com.alibaba.nacos.common.tls;

import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.InternetAddressUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -38,7 +38,7 @@ public final class SelfHostnameVerifier implements HostnameVerifier {

private static ConcurrentHashMap<String, Boolean> hosts = new ConcurrentHashMap<String, Boolean>();

private static final String[] LOCALHOST_HOSTNAME = new String[] {"localhost", IPUtil.localHostIP()};
private static final String[] LOCALHOST_HOSTNAME = new String[] {"localhost", InternetAddressUtil.localHostIP()};

public SelfHostnameVerifier(HostnameVerifier hv) {
this.hv = hv;
Expand All @@ -64,7 +64,7 @@ private static boolean isIP(String host) {
if (cacheHostVerify != null) {
return cacheHostVerify;
}
boolean isIp = IPUtil.isIP(host);
boolean isIp = InternetAddressUtil.isIP(host);
hosts.putIfAbsent(host, isIp);
return isIp;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package com.alibaba.nacos.common.utils;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Expand All @@ -25,7 +26,7 @@
* @author Nacos
*/
@SuppressWarnings({"checkstyle:AbbreviationAsWordInName", "PMD.ClassNamingShouldBeCamelRule"})
public class IPUtil {
public class InternetAddressUtil {

public static final boolean PREFER_IPV6_ADDRESSES = Boolean.parseBoolean(System.getProperty("java.net.preferIPv6Addresses"));

Expand All @@ -41,6 +42,8 @@ public class IPUtil {

public static final String PERCENT_SIGN_IN_IPV6 = "%";

public static final String LOCAL_HOST = "localhost";

private static final String LOCAL_HOST_IP_V4 = "127.0.0.1";

private static final String LOCAL_HOST_IP_V6 = "[::1]";
Expand Down Expand Up @@ -107,6 +110,7 @@ public static boolean containsPort(String address) {

/**
* Split IP and port strings, support IPv4 and IPv6, IP in IPv6 must be enclosed with [].
* Illegal IP will get abnormal results.
*
* @param str ip and port string
* @return java.lang.String[]
Expand All @@ -125,18 +129,8 @@ public static String[] splitIPPortStr(String str) {
serverAddrArr[0] = str.substring(0, (str.indexOf(IPV6_END_MARK) + 1));
serverAddrArr[1] = str.substring((str.indexOf(IPV6_END_MARK) + 2));
}
if (!isIPv6(serverAddrArr[0])) {
throw new IllegalArgumentException("The IPv6 address(\"" + serverAddrArr[0] + "\") is incorrect.");
}
} else {
serverAddrArr = str.split(":");
if (serverAddrArr.length > SPLIT_IP_PORT_RESULT_LENGTH) {
throw new IllegalArgumentException("The IP address(\"" + str
+ "\") is incorrect. If it is an IPv6 address, please use [] to enclose the IP part!");
}
if (!isIPv4(serverAddrArr[0]) && !DOMAIN_PATTERN.matcher(serverAddrArr[0]).matches()) {
throw new IllegalArgumentException("The IPv4 or Domain address(\"" + serverAddrArr[0] + "\") is incorrect.");
}
}
return serverAddrArr;
}
Expand Down Expand Up @@ -180,7 +174,7 @@ public static String checkIPs(String... ips) {
// illegal response
StringBuilder illegalResponse = new StringBuilder();
for (String ip : ips) {
if (IPUtil.isIP(ip)) {
if (InternetAddressUtil.isIP(ip)) {
continue;
}
illegalResponse.append(ip + ",");
Expand Down Expand Up @@ -215,4 +209,20 @@ public static String removeBrackets(String str) {
return str.replaceAll("[\\[\\]]", "");
}

/**
* judge str is right domain.(Check only rule)
*
* @param str nacosIP
* @return nacosIP is domain
*/
public static boolean isDomain(String str) {
if (StringUtils.isBlank(str)) {
return false;
}
if (Objects.equals(str, LOCAL_HOST)) {
return true;
}
return DOMAIN_PATTERN.matcher(str).matches();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,62 +25,62 @@
* @date 2020/9/3 10:31
*/
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class IPUtilTest {
public class InternetAddressUtilTest {

@Test
public void testIsIPv4() {
Assert.assertTrue(IPUtil.isIPv4("127.0.0.1"));
Assert.assertFalse(IPUtil.isIPv4("[::1]"));
Assert.assertFalse(IPUtil.isIPv4("asdfasf"));
Assert.assertFalse(IPUtil.isIPv4("ffgertert"));
Assert.assertFalse(IPUtil.isIPv4("127.100.19"));
Assert.assertTrue(InternetAddressUtil.isIPv4("127.0.0.1"));
Assert.assertFalse(InternetAddressUtil.isIPv4("[::1]"));
Assert.assertFalse(InternetAddressUtil.isIPv4("asdfasf"));
Assert.assertFalse(InternetAddressUtil.isIPv4("ffgertert"));
Assert.assertFalse(InternetAddressUtil.isIPv4("127.100.19"));
}

@Test
public void testIsIPv6() {
Assert.assertTrue(IPUtil.isIPv6("[::1]"));
Assert.assertFalse(IPUtil.isIPv6("127.0.0.1"));
Assert.assertFalse(IPUtil.isIPv6("er34234"));
Assert.assertTrue(InternetAddressUtil.isIPv6("[::1]"));
Assert.assertFalse(InternetAddressUtil.isIPv6("127.0.0.1"));
Assert.assertFalse(InternetAddressUtil.isIPv6("er34234"));
}

@Test
public void testIsIP() {
Assert.assertTrue(IPUtil.isIP("[::1]"));
Assert.assertTrue(IPUtil.isIP("127.0.0.1"));
Assert.assertFalse(IPUtil.isIP("er34234"));
Assert.assertFalse(IPUtil.isIP("127.100.19"));
Assert.assertTrue(InternetAddressUtil.isIP("[::1]"));
Assert.assertTrue(InternetAddressUtil.isIP("127.0.0.1"));
Assert.assertFalse(InternetAddressUtil.isIP("er34234"));
Assert.assertFalse(InternetAddressUtil.isIP("127.100.19"));
}

@Test
public void testGetIPFromString() {
Assert.assertEquals("[::1]", IPUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("[::1]", IPUtil.getIPFromString(
Assert.assertEquals("[::1]", InternetAddressUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("[::1]", InternetAddressUtil.getIPFromString(
"jdbc:mysql://[::1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("127.0.0.1",
IPUtil.getIPFromString("http://127.0.0.1:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("127.0.0.1", IPUtil.getIPFromString(
InternetAddressUtil.getIPFromString("http://127.0.0.1:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("127.0.0.1", InternetAddressUtil.getIPFromString(
"jdbc:mysql://127.0.0.1:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));

Assert.assertEquals("",
IPUtil.getIPFromString("http://[dddd]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("", IPUtil.getIPFromString(
InternetAddressUtil.getIPFromString("http://[dddd]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
"jdbc:mysql://[127.0.0.1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("", IPUtil.getIPFromString(
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
"jdbc:mysql://666.288.333.444:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("", IPUtil.getIPFromString(
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
"jdbc:mysql://292.168.1.1:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("", IPUtil.getIPFromString(
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
"jdbc:mysql://29.168.1.288:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("", IPUtil.getIPFromString(
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
"jdbc:mysql://29.168.288.28:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("", IPUtil.getIPFromString(
Assert.assertEquals("", InternetAddressUtil.getIPFromString(
"jdbc:mysql://29.288.28.28:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
}
Expand All @@ -99,20 +99,31 @@ public void testSplitIpPort() {
checkSplitIPPortStr("[2001:db8:0:0:1::1]:88", false, "[2001:db8:0:0:1::1]", "88");
checkSplitIPPortStr("[2001:db8:0000:0:1::1]:88", false, "[2001:db8:0000:0:1::1]", "88");
checkSplitIPPortStr("[2001:DB8:0:0:1::1]:88", false, "[2001:DB8:0:0:1::1]", "88");
checkSplitIPPortStr("[fe80::3ce6:7132:808e:707a%19]:88", false, "[fe80::3ce6:7132:808e:707a%19]", "88");
checkSplitIPPortStr("localhost:8848", false, "localhost", "8848");
checkSplitIPPortStr("[dead::beef]:88", false, "[dead::beef]", "88");

checkSplitIPPortStr("::1:88", true);
checkSplitIPPortStr("[::1:88", true);
checkSplitIPPortStr("[127.0.0.1]:88", true);
// illegal ip will get abnormal results
checkSplitIPPortStr("::1:88", false, "", "", "1", "88");
checkSplitIPPortStr("[::1:88", false, "[", "", "1", "88");
checkSplitIPPortStr("[127.0.0.1]:88", false, "[127.0.0.1]", "88");
checkSplitIPPortStr("[dead:beef]:88", false, "[dead:beef]", "88");
checkSplitIPPortStr("[fe80::3ce6:7132:808e:707a%19]:88", false, "[fe80::3ce6:7132:808e:707a%19]", "88");
checkSplitIPPortStr("[fe80::3]e6]:88", false, "[fe80::3]", "6]:88");
checkSplitIPPortStr("", true);
}

@Test
public void testCheckIPs() {
String[] ips = {"127.0.0.1"};
Assert.assertEquals("ok", IPUtil.checkIPs(ips));
Assert.assertEquals("ok", InternetAddressUtil.checkIPs(ips));

String[] illegalIps = {"127.100.19", "127.0.0.1"};
Assert.assertEquals("illegal ip: 127.100.19", IPUtil.checkIPs(illegalIps));
Assert.assertEquals("illegal ip: 127.100.19", InternetAddressUtil.checkIPs(illegalIps));
}

@Test
public void testIsDomain() {
Assert.assertTrue(InternetAddressUtil.isDomain("localhost"));
}

/**
Expand All @@ -124,13 +135,10 @@ public void testCheckIPs() {
*/
public static void checkSplitIPPortStr(String addr, boolean isEx, String... equalsStrs) {
try {
String[] array = IPUtil.splitIPPortStr(addr);
String[] array = InternetAddressUtil.splitIPPortStr(addr);
Assert.assertTrue(array.length == equalsStrs.length);
if (array.length > 1) {
Assert.assertTrue(array[0].equals(equalsStrs[0]));
Assert.assertTrue(array[1].equals(equalsStrs[1]));
} else {
Assert.assertTrue(array[0].equals(equalsStrs[0]));
for (int i = 0; i < array.length; i++) {
Assert.assertEquals(array[i], equalsStrs[i]);
}
} catch (Exception ex) {
if (!isEx) {
Expand Down
Loading

0 comments on commit 15c7183

Please sign in to comment.