Fix errror message when DNS name is invalid. (#4751)

It used to throw NPE, since URI.create creates URI with null hostname. Now it
thorws IllegalArgumentException for invalid DNS name, NPE for null name.
This commit is contained in:
creamsoup 2018-08-13 16:55:20 -07:00 committed by Kun Zhang
parent 6d4841a8c2
commit ba4db45e71
2 changed files with 23 additions and 2 deletions

View File

@ -132,10 +132,11 @@ final class DnsNameResolver extends NameResolver {
this.executorResource = executorResource;
// Must prepend a "//" to the name when constructing a URI, otherwise it will be treated as an
// opaque URI, thus the authority and host of the resulted URI would be null.
URI nameUri = URI.create("//" + name);
URI nameUri = URI.create("//" + checkNotNull(name, "name"));
Preconditions.checkArgument(nameUri.getHost() != null, "Invalid DNS name: %s", name);
authority = Preconditions.checkNotNull(nameUri.getAuthority(),
"nameUri (%s) doesn't have an authority", nameUri);
host = Preconditions.checkNotNull(nameUri.getHost(), "host");
host = nameUri.getHost();
if (nameUri.getPort() == -1) {
Integer defaultPort = params.get(NameResolver.Factory.PARAMS_DEFAULT_PORT);
if (defaultPort != null) {

View File

@ -155,6 +155,26 @@ public class DnsNameResolverTest {
"foo.googleapis.com:456", 456);
}
@Test
public void nullDnsName() {
try {
newResolver(null, DEFAULT_PORT);
fail("Expected NullPointerException");
} catch (NullPointerException e) {
// expected
}
}
@Test
public void invalidDnsName_containsUnderscore() {
try {
newResolver("host_1", DEFAULT_PORT);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// expected
}
}
@Test
public void resolve() throws Exception {
final List<InetAddress> answer1 = createAddressList(2);