The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2008 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; |
| 18 | |
Fedor Kudasov | c064c84 | 2019-07-09 14:13:30 +0000 | [diff] [blame] | 19 | import static android.system.OsConstants.AF_INET; |
| 20 | import static android.system.OsConstants.AF_INET6; |
| 21 | |
| 22 | import android.annotation.NonNull; |
Artur Satayev | 2695800 | 2019-12-10 17:47:52 +0000 | [diff] [blame] | 23 | import android.compat.annotation.UnsupportedAppUsage; |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 24 | import android.net.shared.Inet4AddressUtils; |
Paul Duffin | a2b34f8 | 2018-10-11 15:21:46 +0100 | [diff] [blame] | 25 | import android.os.Build; |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 26 | import android.system.ErrnoException; |
Fedor Kudasov | c064c84 | 2019-07-09 14:13:30 +0000 | [diff] [blame] | 27 | import android.system.Os; |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 28 | import android.util.Log; |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 29 | import android.util.Pair; |
| 30 | |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 31 | import java.io.FileDescriptor; |
Fedor Kudasov | e5cb0a2 | 2019-07-09 09:23:25 +0000 | [diff] [blame] | 32 | import java.math.BigInteger; |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 33 | import java.net.Inet4Address; |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 34 | import java.net.InetAddress; |
| 35 | import java.net.SocketException; |
| 36 | import java.net.UnknownHostException; |
| 37 | import java.util.Collection; |
| 38 | import java.util.Locale; |
Fedor Kudasov | e5cb0a2 | 2019-07-09 09:23:25 +0000 | [diff] [blame] | 39 | import java.util.TreeSet; |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 40 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 41 | /** |
| 42 | * Native methods for managing network interfaces. |
| 43 | * |
| 44 | * {@hide} |
| 45 | */ |
| 46 | public class NetworkUtils { |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 47 | |
| 48 | private static final String TAG = "NetworkUtils"; |
| 49 | |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 50 | /** |
markchien | 150e191 | 2018-12-27 22:49:51 +0800 | [diff] [blame] | 51 | * Attaches a socket filter that drops all of incoming packets. |
| 52 | * @param fd the socket's {@link FileDescriptor}. |
| 53 | */ |
| 54 | public static native void attachDropAllBPFFilter(FileDescriptor fd) throws SocketException; |
| 55 | |
| 56 | /** |
| 57 | * Detaches a socket filter. |
| 58 | * @param fd the socket's {@link FileDescriptor}. |
| 59 | */ |
| 60 | public static native void detachBPFFilter(FileDescriptor fd) throws SocketException; |
| 61 | |
| 62 | /** |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 63 | * Binds the current process to the network designated by {@code netId}. All sockets created |
| 64 | * in the future (and not explicitly bound via a bound {@link SocketFactory} (see |
Paul Jensen | 6d3ff9e | 2014-05-29 10:12:39 -0400 | [diff] [blame] | 65 | * {@link Network#getSocketFactory}) will be bound to this network. Note that if this |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 66 | * {@code Network} ever disconnects all sockets created in this way will cease to work. This |
| 67 | * is by design so an application doesn't accidentally use sockets it thinks are still bound to |
Paul Jensen | bcc76d3 | 2014-07-11 08:17:29 -0400 | [diff] [blame] | 68 | * a particular {@code Network}. Passing NETID_UNSET clears the binding. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 69 | */ |
Paul Jensen | 32a58f0 | 2014-06-20 13:58:14 -0400 | [diff] [blame] | 70 | public native static boolean bindProcessToNetwork(int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 71 | |
| 72 | /** |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 73 | * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if |
| 74 | * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}. |
| 75 | */ |
Paul Jensen | 72db88e | 2015-03-10 10:54:12 -0400 | [diff] [blame] | 76 | public native static int getBoundNetworkForProcess(); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 77 | |
| 78 | /** |
| 79 | * Binds host resolutions performed by this process to the network designated by {@code netId}. |
Paul Jensen | bcc76d3 | 2014-07-11 08:17:29 -0400 | [diff] [blame] | 80 | * {@link #bindProcessToNetwork} takes precedence over this setting. Passing NETID_UNSET clears |
| 81 | * the binding. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 82 | * |
| 83 | * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature(). |
| 84 | */ |
Aurimas Liutikas | 514c5ef | 2016-05-24 15:22:55 -0700 | [diff] [blame] | 85 | @Deprecated |
Paul Jensen | 32a58f0 | 2014-06-20 13:58:14 -0400 | [diff] [blame] | 86 | public native static boolean bindProcessToNetworkForHostResolution(int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 87 | |
| 88 | /** |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 89 | * Explicitly binds {@code socketfd} to the network designated by {@code netId}. This |
| 90 | * overrides any binding via {@link #bindProcessToNetwork}. |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 91 | * @return 0 on success or negative errno on failure. |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 92 | */ |
Lorenzo Colitti | 9f1274b | 2014-08-21 11:45:54 -0700 | [diff] [blame] | 93 | public native static int bindSocketToNetwork(int socketfd, int netId); |
Paul Jensen | 3876495 | 2014-05-20 11:25:35 -0400 | [diff] [blame] | 94 | |
| 95 | /** |
Lorenzo Colitti | 4ff9f0f | 2015-03-17 17:56:10 +0900 | [diff] [blame] | 96 | * Protect {@code fd} from VPN connections. After protecting, data sent through |
| 97 | * this socket will go directly to the underlying network, so its traffic will not be |
| 98 | * forwarded through the VPN. |
| 99 | */ |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame] | 100 | @UnsupportedAppUsage |
Lorenzo Colitti | 4ff9f0f | 2015-03-17 17:56:10 +0900 | [diff] [blame] | 101 | public static boolean protectFromVpn(FileDescriptor fd) { |
| 102 | return protectFromVpn(fd.getInt$()); |
| 103 | } |
| 104 | |
| 105 | /** |
Paul Jensen | 6bc2c2c | 2014-05-07 15:27:40 -0400 | [diff] [blame] | 106 | * Protect {@code socketfd} from VPN connections. After protecting, data sent through |
| 107 | * this socket will go directly to the underlying network, so its traffic will not be |
| 108 | * forwarded through the VPN. |
| 109 | */ |
| 110 | public native static boolean protectFromVpn(int socketfd); |
| 111 | |
| 112 | /** |
Paul Jensen | cee9b51 | 2015-05-06 07:32:40 -0400 | [diff] [blame] | 113 | * Determine if {@code uid} can access network designated by {@code netId}. |
| 114 | * @return {@code true} if {@code uid} can access network, {@code false} otherwise. |
| 115 | */ |
| 116 | public native static boolean queryUserAccess(int uid, int netId); |
| 117 | |
| 118 | /** |
Luke Huang | 92ae35e | 2019-01-04 19:46:47 +0800 | [diff] [blame] | 119 | * DNS resolver series jni method. |
| 120 | * Issue the query {@code msg} on the network designated by {@code netId}. |
| 121 | * {@code flags} is an additional config to control actual querying behavior. |
| 122 | * @return a file descriptor to watch for read events |
| 123 | */ |
| 124 | public static native FileDescriptor resNetworkSend( |
| 125 | int netId, byte[] msg, int msglen, int flags) throws ErrnoException; |
| 126 | |
| 127 | /** |
| 128 | * DNS resolver series jni method. |
| 129 | * Look up the {@code nsClass} {@code nsType} Resource Record (RR) associated |
| 130 | * with Domain Name {@code dname} on the network designated by {@code netId}. |
| 131 | * {@code flags} is an additional config to control actual querying behavior. |
| 132 | * @return a file descriptor to watch for read events |
| 133 | */ |
| 134 | public static native FileDescriptor resNetworkQuery( |
| 135 | int netId, String dname, int nsClass, int nsType, int flags) throws ErrnoException; |
| 136 | |
| 137 | /** |
| 138 | * DNS resolver series jni method. |
| 139 | * Read a result for the query associated with the {@code fd}. |
Luke Huang | 4219ab6 | 2019-04-08 15:16:04 +0800 | [diff] [blame] | 140 | * @return DnsResponse containing blob answer and rcode |
Luke Huang | 92ae35e | 2019-01-04 19:46:47 +0800 | [diff] [blame] | 141 | */ |
Luke Huang | 4219ab6 | 2019-04-08 15:16:04 +0800 | [diff] [blame] | 142 | public static native DnsResolver.DnsResponse resNetworkResult(FileDescriptor fd) |
| 143 | throws ErrnoException; |
Luke Huang | 92ae35e | 2019-01-04 19:46:47 +0800 | [diff] [blame] | 144 | |
| 145 | /** |
Luke Huang | c09f2d6 | 2019-03-08 14:48:59 +0800 | [diff] [blame] | 146 | * DNS resolver series jni method. |
| 147 | * Attempts to cancel the in-progress query associated with the {@code fd}. |
| 148 | */ |
| 149 | public static native void resNetworkCancel(FileDescriptor fd); |
| 150 | |
| 151 | /** |
Luke Huang | 247d83a | 2019-04-17 22:27:56 +0800 | [diff] [blame] | 152 | * DNS resolver series jni method. |
Luke Huang | c211b27 | 2019-05-29 01:30:07 +0800 | [diff] [blame] | 153 | * Attempts to get network which resolver will use if no network is explicitly selected. |
Luke Huang | 247d83a | 2019-04-17 22:27:56 +0800 | [diff] [blame] | 154 | */ |
Luke Huang | c211b27 | 2019-05-29 01:30:07 +0800 | [diff] [blame] | 155 | public static native Network getDnsNetwork() throws ErrnoException; |
Luke Huang | 247d83a | 2019-04-17 22:27:56 +0800 | [diff] [blame] | 156 | |
| 157 | /** |
markchien | 150e191 | 2018-12-27 22:49:51 +0800 | [diff] [blame] | 158 | * Get the tcp repair window associated with the {@code fd}. |
| 159 | * |
| 160 | * @param fd the tcp socket's {@link FileDescriptor}. |
| 161 | * @return a {@link TcpRepairWindow} object indicates tcp window size. |
| 162 | */ |
| 163 | public static native TcpRepairWindow getTcpRepairWindow(FileDescriptor fd) |
| 164 | throws ErrnoException; |
| 165 | |
Remi NGUYEN VAN | 12da4a5 | 2018-07-04 11:15:56 +0900 | [diff] [blame] | 166 | /** |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 167 | * @see Inet4AddressUtils#intToInet4AddressHTL(int) |
| 168 | * @deprecated Use either {@link Inet4AddressUtils#intToInet4AddressHTH(int)} |
| 169 | * or {@link Inet4AddressUtils#intToInet4AddressHTL(int)} |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 170 | */ |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 171 | @Deprecated |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame] | 172 | @UnsupportedAppUsage |
Robert Greenwalt | 585ac0f | 2010-08-27 09:24:29 -0700 | [diff] [blame] | 173 | public static InetAddress intToInetAddress(int hostAddress) { |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 174 | return Inet4AddressUtils.intToInet4AddressHTL(hostAddress); |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 175 | } |
| 176 | |
| 177 | /** |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 178 | * @see Inet4AddressUtils#inet4AddressToIntHTL(Inet4Address) |
| 179 | * @deprecated Use either {@link Inet4AddressUtils#inet4AddressToIntHTH(Inet4Address)} |
| 180 | * or {@link Inet4AddressUtils#inet4AddressToIntHTL(Inet4Address)} |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 181 | */ |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 182 | @Deprecated |
Robert Greenwalt | 4717c26 | 2012-10-31 14:32:53 -0700 | [diff] [blame] | 183 | public static int inetAddressToInt(Inet4Address inetAddr) |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 184 | throws IllegalArgumentException { |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 185 | return Inet4AddressUtils.inet4AddressToIntHTL(inetAddr); |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 186 | } |
| 187 | |
| 188 | /** |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 189 | * @see Inet4AddressUtils#prefixLengthToV4NetmaskIntHTL(int) |
| 190 | * @deprecated Use either {@link Inet4AddressUtils#prefixLengthToV4NetmaskIntHTH(int)} |
| 191 | * or {@link Inet4AddressUtils#prefixLengthToV4NetmaskIntHTL(int)} |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 192 | */ |
| 193 | @Deprecated |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame] | 194 | @UnsupportedAppUsage |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 195 | public static int prefixLengthToNetmaskInt(int prefixLength) |
| 196 | throws IllegalArgumentException { |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 197 | return Inet4AddressUtils.prefixLengthToV4NetmaskIntHTL(prefixLength); |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 198 | } |
| 199 | |
Irfan Sheriff | 96ca917 | 2010-10-05 16:12:25 -0700 | [diff] [blame] | 200 | /** |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 201 | * Convert a IPv4 netmask integer to a prefix length |
Remi NGUYEN VAN | 0066bda | 2018-07-09 10:40:40 +0900 | [diff] [blame] | 202 | * @param netmask as an integer (0xff000000 for a /8 subnet) |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 203 | * @return the network prefix length |
| 204 | */ |
| 205 | public static int netmaskIntToPrefixLength(int netmask) { |
| 206 | return Integer.bitCount(netmask); |
| 207 | } |
| 208 | |
| 209 | /** |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 210 | * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous. |
| 211 | * @param netmask as a {@code Inet4Address}. |
| 212 | * @return the network prefix length |
| 213 | * @throws IllegalArgumentException the specified netmask was not contiguous. |
| 214 | * @hide |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 215 | * @deprecated use {@link Inet4AddressUtils#netmaskToPrefixLength(Inet4Address)} |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 216 | */ |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame] | 217 | @UnsupportedAppUsage |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 218 | @Deprecated |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 219 | public static int netmaskToPrefixLength(Inet4Address netmask) { |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 220 | // This is only here because some apps seem to be using it (@UnsupportedAppUsage). |
| 221 | return Inet4AddressUtils.netmaskToPrefixLength(netmask); |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 222 | } |
| 223 | |
| 224 | |
| 225 | /** |
Robert Greenwalt | 0216e61 | 2011-01-14 16:29:58 -0800 | [diff] [blame] | 226 | * Create an InetAddress from a string where the string must be a standard |
| 227 | * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure |
| 228 | * but it will throw an IllegalArgumentException in that case. |
| 229 | * @param addrString |
| 230 | * @return the InetAddress |
| 231 | * @hide |
Paul Duffin | a2b34f8 | 2018-10-11 15:21:46 +0100 | [diff] [blame] | 232 | * @deprecated Use {@link InetAddresses#parseNumericAddress(String)}, if possible. |
Robert Greenwalt | 0216e61 | 2011-01-14 16:29:58 -0800 | [diff] [blame] | 233 | */ |
Paul Duffin | a2b34f8 | 2018-10-11 15:21:46 +0100 | [diff] [blame] | 234 | @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P) |
| 235 | @Deprecated |
Robert Greenwalt | 0216e61 | 2011-01-14 16:29:58 -0800 | [diff] [blame] | 236 | public static InetAddress numericToInetAddress(String addrString) |
| 237 | throws IllegalArgumentException { |
Elliott Hughes | f5bbb57 | 2011-02-15 17:11:29 -0800 | [diff] [blame] | 238 | return InetAddress.parseNumericAddress(addrString); |
Robert Greenwalt | 0216e61 | 2011-01-14 16:29:58 -0800 | [diff] [blame] | 239 | } |
| 240 | |
| 241 | /** |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 242 | * Masks a raw IP address byte array with the specified prefix length. |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 243 | */ |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 244 | public static void maskRawAddress(byte[] array, int prefixLength) { |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 245 | if (prefixLength < 0 || prefixLength > array.length * 8) { |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 246 | throw new RuntimeException("IP address with " + array.length + |
| 247 | " bytes has invalid prefix length " + prefixLength); |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 248 | } |
| 249 | |
| 250 | int offset = prefixLength / 8; |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 251 | int remainder = prefixLength % 8; |
| 252 | byte mask = (byte)(0xFF << (8 - remainder)); |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 253 | |
| 254 | if (offset < array.length) array[offset] = (byte)(array[offset] & mask); |
| 255 | |
| 256 | offset++; |
| 257 | |
| 258 | for (; offset < array.length; offset++) { |
| 259 | array[offset] = 0; |
| 260 | } |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 261 | } |
| 262 | |
| 263 | /** |
| 264 | * Get InetAddress masked with prefixLength. Will never return null. |
| 265 | * @param address the IP address to mask with |
| 266 | * @param prefixLength the prefixLength used to mask the IP |
| 267 | */ |
| 268 | public static InetAddress getNetworkPart(InetAddress address, int prefixLength) { |
| 269 | byte[] array = address.getAddress(); |
| 270 | maskRawAddress(array, prefixLength); |
Robert Greenwalt | f43396c | 2011-05-06 17:10:53 -0700 | [diff] [blame] | 271 | |
| 272 | InetAddress netPart = null; |
| 273 | try { |
| 274 | netPart = InetAddress.getByAddress(array); |
| 275 | } catch (UnknownHostException e) { |
| 276 | throw new RuntimeException("getNetworkPart error - " + e.toString()); |
| 277 | } |
| 278 | return netPart; |
| 279 | } |
| 280 | |
| 281 | /** |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 282 | * Returns the implicit netmask of an IPv4 address, as was the custom before 1993. |
| 283 | */ |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame] | 284 | @UnsupportedAppUsage |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 285 | public static int getImplicitNetmask(Inet4Address address) { |
Remi NGUYEN VAN | 77dd54d | 2019-01-25 08:54:08 +0900 | [diff] [blame] | 286 | // Only here because it seems to be used by apps |
| 287 | return Inet4AddressUtils.getImplicitNetmask(address); |
Lorenzo Colitti | 475085b | 2015-03-10 01:32:40 +0900 | [diff] [blame] | 288 | } |
| 289 | |
| 290 | /** |
Lorenzo Colitti | 8c6c2c3 | 2014-06-12 13:41:17 +0900 | [diff] [blame] | 291 | * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64". |
| 292 | * @hide |
| 293 | */ |
| 294 | public static Pair<InetAddress, Integer> parseIpAndMask(String ipAndMaskString) { |
| 295 | InetAddress address = null; |
| 296 | int prefixLength = -1; |
| 297 | try { |
| 298 | String[] pieces = ipAndMaskString.split("/", 2); |
| 299 | prefixLength = Integer.parseInt(pieces[1]); |
| 300 | address = InetAddress.parseNumericAddress(pieces[0]); |
| 301 | } catch (NullPointerException e) { // Null string. |
| 302 | } catch (ArrayIndexOutOfBoundsException e) { // No prefix length. |
| 303 | } catch (NumberFormatException e) { // Non-numeric prefix. |
| 304 | } catch (IllegalArgumentException e) { // Invalid IP address. |
| 305 | } |
| 306 | |
| 307 | if (address == null || prefixLength == -1) { |
| 308 | throw new IllegalArgumentException("Invalid IP address and mask " + ipAndMaskString); |
| 309 | } |
| 310 | |
| 311 | return new Pair<InetAddress, Integer>(address, prefixLength); |
| 312 | } |
| 313 | |
| 314 | /** |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 315 | * Convert a 32 char hex string into a Inet6Address. |
| 316 | * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be |
| 317 | * made into an Inet6Address |
| 318 | * @param addrHexString a 32 character hex string representing an IPv6 addr |
| 319 | * @return addr an InetAddress representation for the string |
| 320 | */ |
| 321 | public static InetAddress hexToInet6Address(String addrHexString) |
| 322 | throws IllegalArgumentException { |
| 323 | try { |
Jeff Sharkey | fea17de | 2013-06-11 14:13:09 -0700 | [diff] [blame] | 324 | return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s", |
Robert Greenwalt | 59b1a4e | 2011-05-10 15:05:02 -0700 | [diff] [blame] | 325 | addrHexString.substring(0,4), addrHexString.substring(4,8), |
| 326 | addrHexString.substring(8,12), addrHexString.substring(12,16), |
| 327 | addrHexString.substring(16,20), addrHexString.substring(20,24), |
| 328 | addrHexString.substring(24,28), addrHexString.substring(28,32))); |
| 329 | } catch (Exception e) { |
| 330 | Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e); |
| 331 | throw new IllegalArgumentException(e); |
| 332 | } |
| 333 | } |
Robert Greenwalt | a10b7fd | 2011-07-25 16:06:25 -0700 | [diff] [blame] | 334 | |
| 335 | /** |
| 336 | * Create a string array of host addresses from a collection of InetAddresses |
| 337 | * @param addrs a Collection of InetAddresses |
| 338 | * @return an array of Strings containing their host addresses |
| 339 | */ |
| 340 | public static String[] makeStrings(Collection<InetAddress> addrs) { |
| 341 | String[] result = new String[addrs.size()]; |
| 342 | int i = 0; |
| 343 | for (InetAddress addr : addrs) { |
| 344 | result[i++] = addr.getHostAddress(); |
| 345 | } |
| 346 | return result; |
| 347 | } |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 348 | |
| 349 | /** |
| 350 | * Trim leading zeros from IPv4 address strings |
| 351 | * Our base libraries will interpret that as octel.. |
| 352 | * Must leave non v4 addresses and host names alone. |
| 353 | * For example, 192.168.000.010 -> 192.168.0.10 |
| 354 | * TODO - fix base libraries and remove this function |
| 355 | * @param addr a string representing an ip addr |
| 356 | * @return a string propertly trimmed |
| 357 | */ |
Mathew Inwood | fa3a746 | 2018-08-08 14:52:47 +0100 | [diff] [blame] | 358 | @UnsupportedAppUsage |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 359 | public static String trimV4AddrZeros(String addr) { |
Robert Greenwalt | 0faacf0 | 2011-12-07 16:43:59 -0800 | [diff] [blame] | 360 | if (addr == null) return null; |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 361 | String[] octets = addr.split("\\."); |
| 362 | if (octets.length != 4) return addr; |
| 363 | StringBuilder builder = new StringBuilder(16); |
| 364 | String result = null; |
| 365 | for (int i = 0; i < 4; i++) { |
| 366 | try { |
Robert Greenwalt | 3957b5f | 2011-12-07 13:10:59 -0800 | [diff] [blame] | 367 | if (octets[i].length() > 3) return addr; |
Robert Greenwalt | d4420ab | 2011-12-07 09:58:48 -0800 | [diff] [blame] | 368 | builder.append(Integer.parseInt(octets[i])); |
| 369 | } catch (NumberFormatException e) { |
| 370 | return addr; |
| 371 | } |
| 372 | if (i < 3) builder.append('.'); |
| 373 | } |
| 374 | result = builder.toString(); |
| 375 | return result; |
| 376 | } |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 377 | |
Fedor Kudasov | e5cb0a2 | 2019-07-09 09:23:25 +0000 | [diff] [blame] | 378 | /** |
| 379 | * Returns a prefix set without overlaps. |
| 380 | * |
| 381 | * This expects the src set to be sorted from shorter to longer. Results are undefined |
| 382 | * failing this condition. The returned prefix set is sorted in the same order as the |
| 383 | * passed set, with the same comparator. |
| 384 | */ |
| 385 | private static TreeSet<IpPrefix> deduplicatePrefixSet(final TreeSet<IpPrefix> src) { |
| 386 | final TreeSet<IpPrefix> dst = new TreeSet<>(src.comparator()); |
| 387 | // Prefixes match addresses that share their upper part up to their length, therefore |
| 388 | // the only kind of possible overlap in two prefixes is strict inclusion of the longer |
| 389 | // (more restrictive) in the shorter (including equivalence if they have the same |
| 390 | // length). |
| 391 | // Because prefixes in the src set are sorted from shorter to longer, deduplicating |
| 392 | // is done by simply iterating in order, and not adding any longer prefix that is |
| 393 | // already covered by a shorter one. |
| 394 | newPrefixes: |
| 395 | for (IpPrefix newPrefix : src) { |
| 396 | for (IpPrefix existingPrefix : dst) { |
| 397 | if (existingPrefix.containsPrefix(newPrefix)) { |
| 398 | continue newPrefixes; |
| 399 | } |
| 400 | } |
| 401 | dst.add(newPrefix); |
| 402 | } |
| 403 | return dst; |
| 404 | } |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 405 | |
| 406 | /** |
Fedor Kudasov | e5cb0a2 | 2019-07-09 09:23:25 +0000 | [diff] [blame] | 407 | * Returns how many IPv4 addresses match any of the prefixes in the passed ordered set. |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 408 | * |
Fedor Kudasov | e5cb0a2 | 2019-07-09 09:23:25 +0000 | [diff] [blame] | 409 | * Obviously this returns an integral value between 0 and 2**32. |
| 410 | * The behavior is undefined if any of the prefixes is not an IPv4 prefix or if the |
| 411 | * set is not ordered smallest prefix to longer prefix. |
| 412 | * |
| 413 | * @param prefixes the set of prefixes, ordered by length |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 414 | */ |
Fedor Kudasov | e5cb0a2 | 2019-07-09 09:23:25 +0000 | [diff] [blame] | 415 | public static long routedIPv4AddressCount(final TreeSet<IpPrefix> prefixes) { |
| 416 | long routedIPCount = 0; |
| 417 | for (final IpPrefix prefix : deduplicatePrefixSet(prefixes)) { |
| 418 | if (!prefix.isIPv4()) { |
| 419 | Log.wtf(TAG, "Non-IPv4 prefix in routedIPv4AddressCount"); |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 420 | } |
Fedor Kudasov | e5cb0a2 | 2019-07-09 09:23:25 +0000 | [diff] [blame] | 421 | int rank = 32 - prefix.getPrefixLength(); |
| 422 | routedIPCount += 1L << rank; |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 423 | } |
Fedor Kudasov | e5cb0a2 | 2019-07-09 09:23:25 +0000 | [diff] [blame] | 424 | return routedIPCount; |
| 425 | } |
Chalard Jean | dd16d44 | 2019-07-08 16:50:44 +0900 | [diff] [blame] | 426 | |
Fedor Kudasov | e5cb0a2 | 2019-07-09 09:23:25 +0000 | [diff] [blame] | 427 | /** |
| 428 | * Returns how many IPv6 addresses match any of the prefixes in the passed ordered set. |
| 429 | * |
| 430 | * This returns a BigInteger between 0 and 2**128. |
| 431 | * The behavior is undefined if any of the prefixes is not an IPv6 prefix or if the |
| 432 | * set is not ordered smallest prefix to longer prefix. |
| 433 | */ |
| 434 | public static BigInteger routedIPv6AddressCount(final TreeSet<IpPrefix> prefixes) { |
| 435 | BigInteger routedIPCount = BigInteger.ZERO; |
| 436 | for (final IpPrefix prefix : deduplicatePrefixSet(prefixes)) { |
| 437 | if (!prefix.isIPv6()) { |
| 438 | Log.wtf(TAG, "Non-IPv6 prefix in routedIPv6AddressCount"); |
| 439 | } |
| 440 | int rank = 128 - prefix.getPrefixLength(); |
| 441 | routedIPCount = routedIPCount.add(BigInteger.ONE.shiftLeft(rank)); |
| 442 | } |
| 443 | return routedIPCount; |
Chalard Jean | adbf1d0 | 2018-02-26 11:52:46 +0900 | [diff] [blame] | 444 | } |
Eran Messeri | a2e0ca7 | 2018-09-20 15:15:41 +0100 | [diff] [blame] | 445 | |
| 446 | private static final int[] ADDRESS_FAMILIES = new int[] {AF_INET, AF_INET6}; |
| 447 | |
| 448 | /** |
| 449 | * Returns true if the hostname is weakly validated. |
| 450 | * @param hostname Name of host to validate. |
| 451 | * @return True if it's a valid-ish hostname. |
| 452 | * |
| 453 | * @hide |
| 454 | */ |
| 455 | public static boolean isWeaklyValidatedHostname(@NonNull String hostname) { |
| 456 | // TODO(b/34953048): Use a validation method that permits more accurate, |
| 457 | // but still inexpensive, checking of likely valid DNS hostnames. |
| 458 | final String weakHostnameRegex = "^[a-zA-Z0-9_.-]+$"; |
| 459 | if (!hostname.matches(weakHostnameRegex)) { |
| 460 | return false; |
| 461 | } |
| 462 | |
| 463 | for (int address_family : ADDRESS_FAMILIES) { |
| 464 | if (Os.inet_pton(address_family, hostname) != null) { |
| 465 | return false; |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | return true; |
| 470 | } |
The Android Open Source Project | 9066cfe | 2009-03-03 19:31:44 -0800 | [diff] [blame] | 471 | } |