1 /* 2 * Copyright (C) 2018 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.net.dns; 18 19 import static android.system.OsConstants.AI_ADDRCONFIG; 20 21 import android.net.Network; 22 import android.net.NetworkUtils; 23 import android.system.GaiException; 24 import android.system.OsConstants; 25 import android.system.StructAddrinfo; 26 27 import libcore.io.Libcore; 28 29 import java.net.InetAddress; 30 import java.net.UnknownHostException; 31 32 33 /** 34 * DNS resolution utility class. 35 * 36 * @hide 37 */ 38 public class ResolvUtil { 39 // Non-portable DNS resolution flag. 40 private static final long NETID_USE_LOCAL_NAMESERVERS = 0x80000000L; 41 42 private ResolvUtil() {} 43 44 public static InetAddress[] blockingResolveAllLocally(Network network, String name) 45 throws UnknownHostException { 46 // Use AI_ADDRCONFIG by default 47 return blockingResolveAllLocally(network, name, AI_ADDRCONFIG); 48 } 49 50 public static InetAddress[] blockingResolveAllLocally( 51 Network network, String name, int aiFlags) throws UnknownHostException { 52 final StructAddrinfo hints = new StructAddrinfo(); 53 hints.ai_flags = aiFlags; 54 // Other hints identical to the default Inet6AddressImpl implementation 55 hints.ai_family = OsConstants.AF_UNSPEC; 56 hints.ai_socktype = OsConstants.SOCK_STREAM; 57 58 final Network networkForResolv = getNetworkWithUseLocalNameserversFlag(network); 59 60 try { 61 return Libcore.os.android_getaddrinfo(name, hints, (int) networkForResolv.netId); 62 } catch (GaiException gai) { 63 gai.rethrowAsUnknownHostException(name + ": TLS-bypass resolution failed"); 64 return null; // keep compiler quiet 65 } 66 } 67 68 public static Network getNetworkWithUseLocalNameserversFlag(Network network) { 69 final long netidForResolv = NETID_USE_LOCAL_NAMESERVERS | (long) network.netId; 70 return new Network((int) netidForResolv); 71 } 72 73 public static Network makeNetworkWithPrivateDnsBypass(Network network) { 74 return new Network(network) { 75 @Override 76 public InetAddress[] getAllByName(String host) throws UnknownHostException { 77 return blockingResolveAllLocally(network, host); 78 } 79 }; 80 } 81 } 82