1 /* 2 * Copyright (C) 2020 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 package com.android.networkstack.tethering; 17 18 import static android.net.NetworkCapabilities.TRANSPORT_VPN; 19 import static android.net.TetheringManager.TETHERING_BLUETOOTH; 20 import static android.net.TetheringManager.TETHERING_WIFI_P2P; 21 22 import static com.android.net.module.util.Inet4AddressUtils.inet4AddressToIntHTH; 23 import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH; 24 import static com.android.net.module.util.Inet4AddressUtils.prefixLengthToV4NetmaskIntHTH; 25 import static com.android.networkstack.tethering.util.PrefixUtils.asIpPrefix; 26 27 import static java.util.Arrays.asList; 28 29 import android.content.Context; 30 import android.net.ConnectivityManager; 31 import android.net.IpPrefix; 32 import android.net.LinkAddress; 33 import android.net.Network; 34 import android.net.ip.IpServer; 35 import android.util.ArrayMap; 36 import android.util.ArraySet; 37 import android.util.SparseArray; 38 39 import androidx.annotation.NonNull; 40 import androidx.annotation.Nullable; 41 42 import com.android.internal.annotations.VisibleForTesting; 43 import com.android.internal.util.IndentingPrintWriter; 44 45 import java.net.Inet4Address; 46 import java.net.InetAddress; 47 import java.util.ArrayList; 48 import java.util.Arrays; 49 import java.util.HashSet; 50 import java.util.List; 51 import java.util.Random; 52 import java.util.Set; 53 54 /** 55 * This class coordinate IP addresses conflict problem. 56 * 57 * Tethering downstream IP addresses may conflict with network assigned addresses. This 58 * coordinator is responsible for recording all of network assigned addresses and dispatched 59 * free address to downstream interfaces. 60 * 61 * This class is not thread-safe and should be accessed on the same tethering internal thread. 62 * @hide 63 */ 64 public class PrivateAddressCoordinator { 65 public static final int PREFIX_LENGTH = 24; 66 67 // Upstream monitor would be stopped when tethering is down. When tethering restart, downstream 68 // address may be requested before coordinator get current upstream notification. To ensure 69 // coordinator do not select conflict downstream prefix, mUpstreamPrefixMap would not be cleared 70 // when tethering is down. Instead tethering would remove all deprecated upstreams from 71 // mUpstreamPrefixMap when tethering is starting. See #maybeRemoveDeprecatedUpstreams(). 72 private final ArrayMap<Network, List<IpPrefix>> mUpstreamPrefixMap; 73 private final ArraySet<IpServer> mDownstreams; 74 private static final String LEGACY_WIFI_P2P_IFACE_ADDRESS = "192.168.49.1/24"; 75 private static final String LEGACY_BLUETOOTH_IFACE_ADDRESS = "192.168.44.1/24"; 76 private final List<IpPrefix> mTetheringPrefixes; 77 private final ConnectivityManager mConnectivityMgr; 78 private final TetheringConfiguration mConfig; 79 // keyed by downstream type(TetheringManager.TETHERING_*). 80 private final SparseArray<LinkAddress> mCachedAddresses; 81 PrivateAddressCoordinator(Context context, TetheringConfiguration config)82 public PrivateAddressCoordinator(Context context, TetheringConfiguration config) { 83 mDownstreams = new ArraySet<>(); 84 mUpstreamPrefixMap = new ArrayMap<>(); 85 mConnectivityMgr = (ConnectivityManager) context.getSystemService( 86 Context.CONNECTIVITY_SERVICE); 87 mConfig = config; 88 mCachedAddresses = new SparseArray<>(); 89 // Reserved static addresses for bluetooth and wifi p2p. 90 mCachedAddresses.put(TETHERING_BLUETOOTH, new LinkAddress(LEGACY_BLUETOOTH_IFACE_ADDRESS)); 91 mCachedAddresses.put(TETHERING_WIFI_P2P, new LinkAddress(LEGACY_WIFI_P2P_IFACE_ADDRESS)); 92 93 mTetheringPrefixes = new ArrayList<>(Arrays.asList(new IpPrefix("192.168.0.0/16"), 94 new IpPrefix("172.16.0.0/12"), new IpPrefix("10.0.0.0/8"))); 95 } 96 97 /** 98 * Record a new upstream IpPrefix which may conflict with tethering downstreams. 99 * The downstreams will be notified if a conflict is found. When updateUpstreamPrefix is called, 100 * UpstreamNetworkState must have an already populated LinkProperties. 101 */ updateUpstreamPrefix(final UpstreamNetworkState ns)102 public void updateUpstreamPrefix(final UpstreamNetworkState ns) { 103 // Do not support VPN as upstream. Normally, networkCapabilities is not expected to be null, 104 // but just checking to be sure. 105 if (ns.networkCapabilities != null && ns.networkCapabilities.hasTransport(TRANSPORT_VPN)) { 106 removeUpstreamPrefix(ns.network); 107 return; 108 } 109 110 final ArrayList<IpPrefix> ipv4Prefixes = getIpv4Prefixes( 111 ns.linkProperties.getAllLinkAddresses()); 112 if (ipv4Prefixes.isEmpty()) { 113 removeUpstreamPrefix(ns.network); 114 return; 115 } 116 117 mUpstreamPrefixMap.put(ns.network, ipv4Prefixes); 118 handleMaybePrefixConflict(ipv4Prefixes); 119 } 120 getIpv4Prefixes(final List<LinkAddress> linkAddresses)121 private ArrayList<IpPrefix> getIpv4Prefixes(final List<LinkAddress> linkAddresses) { 122 final ArrayList<IpPrefix> list = new ArrayList<>(); 123 for (LinkAddress address : linkAddresses) { 124 if (!address.isIpv4()) continue; 125 126 list.add(asIpPrefix(address)); 127 } 128 129 return list; 130 } 131 handleMaybePrefixConflict(final List<IpPrefix> prefixes)132 private void handleMaybePrefixConflict(final List<IpPrefix> prefixes) { 133 for (IpServer downstream : mDownstreams) { 134 final IpPrefix target = getDownstreamPrefix(downstream); 135 136 for (IpPrefix source : prefixes) { 137 if (isConflictPrefix(source, target)) { 138 downstream.sendMessage(IpServer.CMD_NOTIFY_PREFIX_CONFLICT); 139 break; 140 } 141 } 142 } 143 } 144 145 /** Remove IpPrefix records corresponding to input network. */ removeUpstreamPrefix(final Network network)146 public void removeUpstreamPrefix(final Network network) { 147 mUpstreamPrefixMap.remove(network); 148 } 149 150 /** 151 * Maybe remove deprecated upstream records, this would be called once tethering started without 152 * any exiting tethered downstream. 153 */ maybeRemoveDeprecatedUpstreams()154 public void maybeRemoveDeprecatedUpstreams() { 155 if (mUpstreamPrefixMap.isEmpty()) return; 156 157 // Remove all upstreams that are no longer valid networks 158 final Set<Network> toBeRemoved = new HashSet<>(mUpstreamPrefixMap.keySet()); 159 toBeRemoved.removeAll(asList(mConnectivityMgr.getAllNetworks())); 160 161 mUpstreamPrefixMap.removeAll(toBeRemoved); 162 } 163 164 /** 165 * Pick a random available address and mark its prefix as in use for the provided IpServer, 166 * returns null if there is no available address. 167 */ 168 @Nullable requestDownstreamAddress(final IpServer ipServer, boolean useLastAddress)169 public LinkAddress requestDownstreamAddress(final IpServer ipServer, boolean useLastAddress) { 170 if (mConfig.shouldEnableWifiP2pDedicatedIp() 171 && ipServer.interfaceType() == TETHERING_WIFI_P2P) { 172 return new LinkAddress(LEGACY_WIFI_P2P_IFACE_ADDRESS); 173 } 174 175 final LinkAddress cachedAddress = mCachedAddresses.get(ipServer.interfaceType()); 176 if (useLastAddress && cachedAddress != null 177 && !isConflictWithUpstream(asIpPrefix(cachedAddress))) { 178 mDownstreams.add(ipServer); 179 return cachedAddress; 180 } 181 182 for (IpPrefix prefixRange : mTetheringPrefixes) { 183 final LinkAddress newAddress = chooseDownstreamAddress(prefixRange); 184 if (newAddress != null) { 185 mDownstreams.add(ipServer); 186 mCachedAddresses.put(ipServer.interfaceType(), newAddress); 187 return newAddress; 188 } 189 } 190 191 // No available address. 192 return null; 193 } 194 getPrefixBaseAddress(final IpPrefix prefix)195 private int getPrefixBaseAddress(final IpPrefix prefix) { 196 return inet4AddressToIntHTH((Inet4Address) prefix.getAddress()); 197 } 198 199 /** 200 * Check whether input prefix conflict with upstream prefixes or in-use downstream prefixes. 201 * If yes, return one of them. 202 */ getConflictPrefix(final IpPrefix prefix)203 private IpPrefix getConflictPrefix(final IpPrefix prefix) { 204 final IpPrefix upstream = getConflictWithUpstream(prefix); 205 if (upstream != null) return upstream; 206 207 return getInUseDownstreamPrefix(prefix); 208 } 209 210 // Get the next non-conflict sub prefix. E.g: To get next sub prefix from 10.0.0.0/8, if the 211 // previously selected prefix is 10.20.42.0/24(subPrefix: 0.20.42.0) and the conflicting prefix 212 // is 10.16.0.0/20 (10.16.0.0 ~ 10.16.15.255), then the max address under subPrefix is 213 // 0.16.15.255 and the next subPrefix is 0.16.16.255/24 (0.16.15.255 + 0.0.1.0). 214 // Note: the sub address 0.0.0.255 here is fine to be any value that it will be replaced as 215 // selected random sub address later. getNextSubPrefix(final IpPrefix conflictPrefix, final int prefixRangeMask)216 private int getNextSubPrefix(final IpPrefix conflictPrefix, final int prefixRangeMask) { 217 final int suffixMask = ~prefixLengthToV4NetmaskIntHTH(conflictPrefix.getPrefixLength()); 218 // The largest offset within the prefix assignment block that still conflicts with 219 // conflictPrefix. 220 final int maxConflict = 221 (getPrefixBaseAddress(conflictPrefix) | suffixMask) & ~prefixRangeMask; 222 223 final int prefixMask = prefixLengthToV4NetmaskIntHTH(PREFIX_LENGTH); 224 // Pick a sub prefix a full prefix (1 << (32 - PREFIX_LENGTH) addresses) greater than 225 // maxConflict. This ensures that the selected prefix never overlaps with conflictPrefix. 226 // There is no need to mask the result with PREFIX_LENGTH bits because this is done by 227 // findAvailablePrefixFromRange when it constructs the prefix. 228 return maxConflict + (1 << (32 - PREFIX_LENGTH)); 229 } 230 chooseDownstreamAddress(final IpPrefix prefixRange)231 private LinkAddress chooseDownstreamAddress(final IpPrefix prefixRange) { 232 // The netmask of the prefix assignment block (e.g., 0xfff00000 for 172.16.0.0/12). 233 final int prefixRangeMask = prefixLengthToV4NetmaskIntHTH(prefixRange.getPrefixLength()); 234 235 // The zero address in the block (e.g., 0xac100000 for 172.16.0.0/12). 236 final int baseAddress = getPrefixBaseAddress(prefixRange); 237 238 // The subnet mask corresponding to PREFIX_LENGTH. 239 final int prefixMask = prefixLengthToV4NetmaskIntHTH(PREFIX_LENGTH); 240 241 // The offset within prefixRange of a randomly-selected prefix of length PREFIX_LENGTH. 242 // This may not be the prefix of the address returned by this method: 243 // - If it is already in use, the method will return an address in another prefix. 244 // - If all prefixes within prefixRange are in use, the method will return null. For 245 // example, for a /24 prefix within 172.26.0.0/12, this will be a multiple of 256 in 246 // [0, 1048576). In other words, a random 32-bit number with mask 0x000fff00. 247 // 248 // prefixRangeMask is required to ensure no wrapping. For example, consider: 249 // - prefixRange 127.0.0.0/8 250 // - randomPrefixStart 127.255.255.0 251 // - A conflicting prefix of 127.255.254.0/23 252 // In this case without prefixRangeMask, getNextSubPrefix would return 128.0.0.0, which 253 // means the "start < end" check in findAvailablePrefixFromRange would not reject the prefix 254 // because Java doesn't have unsigned integers, so 128.0.0.0 = 0x80000000 = -2147483648 255 // is less than 127.0.0.0 = 0x7f000000 = 2130706432. 256 // 257 // Additionally, it makes debug output easier to read by making the numbers smaller. 258 final int randomPrefixStart = getRandomInt() & ~prefixRangeMask & prefixMask; 259 260 // A random offset within the prefix. Used to determine the local address once the prefix 261 // is selected. It does not result in an IPv4 address ending in .0, .1, or .255 262 // For a PREFIX_LENGTH of 255, this is a number between 2 and 254. 263 final int subAddress = getSanitizedSubAddr(~prefixMask); 264 265 // Find a prefix length PREFIX_LENGTH between randomPrefixStart and the end of the block, 266 // such that the prefix does not conflict with any upstream. 267 IpPrefix downstreamPrefix = findAvailablePrefixFromRange( 268 randomPrefixStart, (~prefixRangeMask) + 1, baseAddress, prefixRangeMask); 269 if (downstreamPrefix != null) return getLinkAddress(downstreamPrefix, subAddress); 270 271 // If that failed, do the same, but between 0 and randomPrefixStart. 272 downstreamPrefix = findAvailablePrefixFromRange( 273 0, randomPrefixStart, baseAddress, prefixRangeMask); 274 275 return getLinkAddress(downstreamPrefix, subAddress); 276 } 277 getLinkAddress(final IpPrefix prefix, final int subAddress)278 private LinkAddress getLinkAddress(final IpPrefix prefix, final int subAddress) { 279 if (prefix == null) return null; 280 281 final InetAddress address = intToInet4AddressHTH(getPrefixBaseAddress(prefix) | subAddress); 282 return new LinkAddress(address, PREFIX_LENGTH); 283 } 284 findAvailablePrefixFromRange(final int start, final int end, final int baseAddress, final int prefixRangeMask)285 private IpPrefix findAvailablePrefixFromRange(final int start, final int end, 286 final int baseAddress, final int prefixRangeMask) { 287 int newSubPrefix = start; 288 while (newSubPrefix < end) { 289 final InetAddress address = intToInet4AddressHTH(baseAddress | newSubPrefix); 290 final IpPrefix prefix = new IpPrefix(address, PREFIX_LENGTH); 291 292 final IpPrefix conflictPrefix = getConflictPrefix(prefix); 293 294 if (conflictPrefix == null) return prefix; 295 296 newSubPrefix = getNextSubPrefix(conflictPrefix, prefixRangeMask); 297 } 298 299 return null; 300 } 301 302 /** Get random int which could be used to generate random address. */ 303 @VisibleForTesting getRandomInt()304 public int getRandomInt() { 305 return (new Random()).nextInt(); 306 } 307 308 /** Get random subAddress and avoid selecting x.x.x.0, x.x.x.1 and x.x.x.255 address. */ getSanitizedSubAddr(final int subAddrMask)309 private int getSanitizedSubAddr(final int subAddrMask) { 310 final int randomSubAddr = getRandomInt() & subAddrMask; 311 // If prefix length > 30, the selecting speace would be less than 4 which may be hard to 312 // avoid 3 consecutive address. 313 if (PREFIX_LENGTH > 30) return randomSubAddr; 314 315 // TODO: maybe it is not necessary to avoid .0, .1 and .255 address because tethering 316 // address would not be conflicted. This code only works because PREFIX_LENGTH is not longer 317 // than 24 318 final int candidate = randomSubAddr & 0xff; 319 if (candidate == 0 || candidate == 1 || candidate == 255) { 320 return (randomSubAddr & 0xfffffffc) + 2; 321 } 322 323 return randomSubAddr; 324 } 325 326 /** Release downstream record for IpServer. */ releaseDownstream(final IpServer ipServer)327 public void releaseDownstream(final IpServer ipServer) { 328 mDownstreams.remove(ipServer); 329 } 330 331 /** Clear current upstream prefixes records. */ clearUpstreamPrefixes()332 public void clearUpstreamPrefixes() { 333 mUpstreamPrefixMap.clear(); 334 } 335 getConflictWithUpstream(final IpPrefix prefix)336 private IpPrefix getConflictWithUpstream(final IpPrefix prefix) { 337 for (int i = 0; i < mUpstreamPrefixMap.size(); i++) { 338 final List<IpPrefix> list = mUpstreamPrefixMap.valueAt(i); 339 for (IpPrefix upstream : list) { 340 if (isConflictPrefix(prefix, upstream)) return upstream; 341 } 342 } 343 return null; 344 } 345 isConflictWithUpstream(final IpPrefix prefix)346 private boolean isConflictWithUpstream(final IpPrefix prefix) { 347 return getConflictWithUpstream(prefix) != null; 348 } 349 isConflictPrefix(final IpPrefix prefix1, final IpPrefix prefix2)350 private boolean isConflictPrefix(final IpPrefix prefix1, final IpPrefix prefix2) { 351 if (prefix2.getPrefixLength() < prefix1.getPrefixLength()) { 352 return prefix2.contains(prefix1.getAddress()); 353 } 354 355 return prefix1.contains(prefix2.getAddress()); 356 } 357 358 // InUse Prefixes are prefixes of mCachedAddresses which are active downstream addresses, last 359 // downstream addresses(reserved for next time) and static addresses(e.g. bluetooth, wifi p2p). getInUseDownstreamPrefix(final IpPrefix prefix)360 private IpPrefix getInUseDownstreamPrefix(final IpPrefix prefix) { 361 for (int i = 0; i < mCachedAddresses.size(); i++) { 362 final IpPrefix downstream = asIpPrefix(mCachedAddresses.valueAt(i)); 363 if (isConflictPrefix(prefix, downstream)) return downstream; 364 } 365 366 // IpServer may use manually-defined address (mStaticIpv4ServerAddr) which does not include 367 // in mCachedAddresses. 368 for (IpServer downstream : mDownstreams) { 369 final IpPrefix target = getDownstreamPrefix(downstream); 370 371 if (isConflictPrefix(prefix, target)) return target; 372 } 373 374 return null; 375 } 376 377 @NonNull getDownstreamPrefix(final IpServer downstream)378 private IpPrefix getDownstreamPrefix(final IpServer downstream) { 379 final LinkAddress address = downstream.getAddress(); 380 381 return asIpPrefix(address); 382 } 383 dump(final IndentingPrintWriter pw)384 void dump(final IndentingPrintWriter pw) { 385 pw.println("mTetheringPrefixes:"); 386 pw.increaseIndent(); 387 for (IpPrefix prefix : mTetheringPrefixes) { 388 pw.println(prefix); 389 } 390 pw.decreaseIndent(); 391 392 pw.println("mUpstreamPrefixMap:"); 393 pw.increaseIndent(); 394 for (int i = 0; i < mUpstreamPrefixMap.size(); i++) { 395 pw.println(mUpstreamPrefixMap.keyAt(i) + " - " + mUpstreamPrefixMap.valueAt(i)); 396 } 397 pw.decreaseIndent(); 398 399 pw.println("mDownstreams:"); 400 pw.increaseIndent(); 401 for (IpServer ipServer : mDownstreams) { 402 pw.println(ipServer.interfaceType() + " - " + ipServer.getAddress()); 403 } 404 pw.decreaseIndent(); 405 406 pw.println("mCachedAddresses:"); 407 pw.increaseIndent(); 408 for (int i = 0; i < mCachedAddresses.size(); i++) { 409 pw.println(mCachedAddresses.keyAt(i) + " - " + mCachedAddresses.valueAt(i)); 410 } 411 pw.decreaseIndent(); 412 } 413 } 414