| 1 | /* |
| 2 | * Copyright (C) 2014 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 com.android.server.net; |
| 18 | |
| 19 | import android.compat.annotation.UnsupportedAppUsage; |
| 20 | import android.net.LinkAddress; |
| 21 | import android.net.LinkProperties; |
| 22 | import android.net.RouteInfo; |
| 23 | import android.os.Build; |
| 24 | import android.util.Log; |
| 25 | |
| 26 | import java.net.InetAddress; |
| 27 | import java.util.ArrayList; |
| 28 | import java.util.Arrays; |
| 29 | import java.util.Collections; |
| 30 | import java.util.HashMap; |
| 31 | import java.util.HashSet; |
| 32 | import java.util.Set; |
| 33 | |
| 34 | /** |
| 35 | * Keeps track of link configuration received from Netlink. |
| 36 | * |
| 37 | * Instances of this class are expected to be owned by subsystems such as Wi-Fi |
| 38 | * or Ethernet that manage one or more network interfaces. Each interface to be |
| 39 | * tracked needs its own {@code NetlinkTracker}. |
| 40 | * |
| 41 | * An instance of this class is constructed by passing in an interface name and |
| 42 | * a callback. The owner is then responsible for registering the tracker with |
| 43 | * NetworkManagementService. When the class receives update notifications from |
| 44 | * the NetworkManagementService notification threads, it applies the update to |
| 45 | * its local LinkProperties, and if something has changed, notifies its owner of |
| 46 | * the update via the callback. |
| 47 | * |
| 48 | * The owner can then call {@code getLinkProperties()} in order to find out |
| 49 | * what changed. If in the meantime the LinkProperties stored here have changed, |
| 50 | * this class will return the current LinkProperties. Because each change |
| 51 | * triggers an update callback after the change is made, the owner may get more |
| 52 | * callbacks than strictly necessary (some of which may be no-ops), but will not |
| 53 | * be out of sync once all callbacks have been processed. |
| 54 | * |
| 55 | * Threading model: |
| 56 | * |
| 57 | * - The owner of this class is expected to create it, register it, and call |
| 58 | * getLinkProperties or clearLinkProperties on its thread. |
| 59 | * - Most of the methods in the class are inherited from BaseNetworkObserver |
| 60 | * and are called by NetworkManagementService notification threads. |
| 61 | * - All accesses to mLinkProperties must be synchronized(this). All the other |
| 62 | * member variables are immutable once the object is constructed. |
| 63 | * |
| 64 | * This class currently tracks IPv4 and IPv6 addresses. In the future it will |
| 65 | * track routes and DNS servers. |
| 66 | * |
| 67 | * @hide |
| 68 | */ |
| 69 | public class NetlinkTracker extends BaseNetworkObserver { |
| 70 | |
| 71 | private final String TAG; |
| 72 | |
| 73 | public interface Callback { |
| 74 | public void update(); |
| 75 | } |
| 76 | |
| 77 | private final String mInterfaceName; |
| 78 | private final Callback mCallback; |
| 79 | private final LinkProperties mLinkProperties; |
| 80 | private DnsServerRepository mDnsServerRepository; |
| 81 | |
| 82 | private static final boolean DBG = false; |
| 83 | |
| 84 | @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) |
| 85 | public NetlinkTracker(String iface, Callback callback) { |
| 86 | TAG = "NetlinkTracker/" + iface; |
| 87 | mInterfaceName = iface; |
| 88 | mCallback = callback; |
| 89 | mLinkProperties = new LinkProperties(); |
| 90 | mLinkProperties.setInterfaceName(mInterfaceName); |
| 91 | mDnsServerRepository = new DnsServerRepository(); |
| 92 | } |
| 93 | |
| 94 | private void maybeLog(String operation, String iface, LinkAddress address) { |
| 95 | if (DBG) { |
| 96 | Log.d(TAG, operation + ": " + address + " on " + iface + |
| 97 | " flags " + address.getFlags() + " scope " + address.getScope()); |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | private void maybeLog(String operation, Object o) { |
| 102 | if (DBG) { |
| 103 | Log.d(TAG, operation + ": " + o.toString()); |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | @Override |
| 108 | public void interfaceRemoved(String iface) { |
| 109 | maybeLog("interfaceRemoved", iface); |
| 110 | if (mInterfaceName.equals(iface)) { |
| 111 | // Our interface was removed. Clear our LinkProperties and tell our owner that they are |
| 112 | // now empty. Note that from the moment that the interface is removed, any further |
| 113 | // interface-specific messages (e.g., RTM_DELADDR) will not reach us, because the netd |
| 114 | // code that parses them will not be able to resolve the ifindex to an interface name. |
| 115 | clearLinkProperties(); |
| 116 | mCallback.update(); |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | @Override |
| 121 | public void addressUpdated(String iface, LinkAddress address) { |
| 122 | if (mInterfaceName.equals(iface)) { |
| 123 | maybeLog("addressUpdated", iface, address); |
| 124 | boolean changed; |
| 125 | synchronized (this) { |
| 126 | changed = mLinkProperties.addLinkAddress(address); |
| 127 | } |
| 128 | if (changed) { |
| 129 | mCallback.update(); |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | @Override |
| 135 | public void addressRemoved(String iface, LinkAddress address) { |
| 136 | if (mInterfaceName.equals(iface)) { |
| 137 | maybeLog("addressRemoved", iface, address); |
| 138 | boolean changed; |
| 139 | synchronized (this) { |
| 140 | changed = mLinkProperties.removeLinkAddress(address); |
| 141 | } |
| 142 | if (changed) { |
| 143 | mCallback.update(); |
| 144 | } |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | @Override |
| 149 | public void routeUpdated(RouteInfo route) { |
| 150 | if (mInterfaceName.equals(route.getInterface())) { |
| 151 | maybeLog("routeUpdated", route); |
| 152 | boolean changed; |
| 153 | synchronized (this) { |
| 154 | changed = mLinkProperties.addRoute(route); |
| 155 | } |
| 156 | if (changed) { |
| 157 | mCallback.update(); |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | @Override |
| 163 | public void routeRemoved(RouteInfo route) { |
| 164 | if (mInterfaceName.equals(route.getInterface())) { |
| 165 | maybeLog("routeRemoved", route); |
| 166 | boolean changed; |
| 167 | synchronized (this) { |
| 168 | changed = mLinkProperties.removeRoute(route); |
| 169 | } |
| 170 | if (changed) { |
| 171 | mCallback.update(); |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | @Override |
| 177 | public void interfaceDnsServerInfo(String iface, long lifetime, String[] addresses) { |
| 178 | if (mInterfaceName.equals(iface)) { |
| 179 | maybeLog("interfaceDnsServerInfo", Arrays.toString(addresses)); |
| 180 | boolean changed = mDnsServerRepository.addServers(lifetime, addresses); |
| 181 | if (changed) { |
| 182 | synchronized (this) { |
| 183 | mDnsServerRepository.setDnsServersOn(mLinkProperties); |
| 184 | } |
| 185 | mCallback.update(); |
| 186 | } |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | /** |
| 191 | * Returns a copy of this object's LinkProperties. |
| 192 | */ |
| 193 | @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) |
| 194 | public synchronized LinkProperties getLinkProperties() { |
| 195 | return new LinkProperties(mLinkProperties); |
| 196 | } |
| 197 | |
| 198 | @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) |
| 199 | public synchronized void clearLinkProperties() { |
| 200 | // Clear the repository before clearing mLinkProperties. That way, if a clear() happens |
| 201 | // while interfaceDnsServerInfo() is being called, we'll end up with no DNS servers in |
| 202 | // mLinkProperties, as desired. |
| 203 | mDnsServerRepository = new DnsServerRepository(); |
| 204 | mLinkProperties.clear(); |
| 205 | mLinkProperties.setInterfaceName(mInterfaceName); |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Represents a DNS server entry with an expiry time. |
| 211 | * |
| 212 | * Implements Comparable so DNS server entries can be sorted by lifetime, longest-lived first. |
| 213 | * The ordering of entries with the same lifetime is unspecified, because given two servers with |
| 214 | * identical lifetimes, we don't care which one we use, and only comparing the lifetime is much |
| 215 | * faster than comparing the IP address as well. |
| 216 | * |
| 217 | * Note: this class has a natural ordering that is inconsistent with equals. |
| 218 | */ |
| 219 | class DnsServerEntry implements Comparable<DnsServerEntry> { |
| 220 | /** The IP address of the DNS server. */ |
| 221 | public final InetAddress address; |
| 222 | /** The time until which the DNS server may be used. A Java millisecond time as might be |
| 223 | * returned by currentTimeMillis(). */ |
| 224 | public long expiry; |
| 225 | |
| 226 | public DnsServerEntry(InetAddress address, long expiry) throws IllegalArgumentException { |
| 227 | this.address = address; |
| 228 | this.expiry = expiry; |
| 229 | } |
| 230 | |
| 231 | public int compareTo(DnsServerEntry other) { |
| 232 | return Long.compare(other.expiry, this.expiry); |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | /** |
| 237 | * Tracks DNS server updates received from Netlink. |
| 238 | * |
| 239 | * The network may announce an arbitrary number of DNS servers in Router Advertisements at any |
| 240 | * time. Each announcement has a lifetime; when the lifetime expires, the servers should not be used |
| 241 | * any more. In this way, the network can gracefully migrate clients from one set of DNS servers to |
| 242 | * another. Announcements can both raise and lower the lifetime, and an announcement can expire |
| 243 | * servers by announcing them with a lifetime of zero. |
| 244 | * |
| 245 | * Typically the system will only use a small number (2 or 3; {@code NUM_CURRENT_SERVERS}) of DNS |
| 246 | * servers at any given time. These are referred to as the current servers. In case all the |
| 247 | * current servers expire, the class also keeps track of a larger (but limited) number of servers |
| 248 | * that are promoted to current servers when the current ones expire. In order to minimize updates |
| 249 | * to the rest of the system (and potentially expensive cache flushes) this class attempts to keep |
| 250 | * the list of current servers constant where possible. More specifically, the list of current |
| 251 | * servers is only updated if a new server is learned and there are not yet {@code |
| 252 | * NUM_CURRENT_SERVERS} current servers, or if one or more of the current servers expires or is |
| 253 | * pushed out of the set. Therefore, the current servers will not necessarily be the ones with the |
| 254 | * highest lifetime, but the ones learned first. |
| 255 | * |
| 256 | * This is by design: if instead the class always preferred the servers with the highest lifetime, a |
| 257 | * (misconfigured?) network where two or more routers announce more than {@code NUM_CURRENT_SERVERS} |
| 258 | * unique servers would cause persistent oscillations. |
| 259 | * |
| 260 | * TODO: Currently servers are only expired when a new DNS update is received. |
| 261 | * Update them using timers, or possibly on every notification received by NetlinkTracker. |
| 262 | * |
| 263 | * Threading model: run by NetlinkTracker. Methods are synchronized(this) just in case netlink |
| 264 | * notifications are sent by multiple threads. If future threads use alarms to expire, those |
| 265 | * alarms must also be synchronized(this). |
| 266 | * |
| 267 | */ |
| 268 | class DnsServerRepository { |
| 269 | |
| 270 | /** How many DNS servers we will use. 3 is suggested by RFC 6106. */ |
| 271 | public static final int NUM_CURRENT_SERVERS = 3; |
| 272 | |
| 273 | /** How many DNS servers we'll keep track of, in total. */ |
| 274 | public static final int NUM_SERVERS = 12; |
| 275 | |
| 276 | /** Stores up to {@code NUM_CURRENT_SERVERS} DNS servers we're currently using. */ |
| 277 | private Set<InetAddress> mCurrentServers; |
| 278 | |
| 279 | public static final String TAG = "DnsServerRepository"; |
| 280 | |
| 281 | /** |
| 282 | * Stores all the DNS servers we know about, for use when the current servers expire. |
| 283 | * Always sorted in order of decreasing expiry. The elements in this list are also the values |
| 284 | * of mIndex, and may be elements in mCurrentServers. |
| 285 | */ |
| 286 | private ArrayList<DnsServerEntry> mAllServers; |
| 287 | |
| 288 | /** |
| 289 | * Indexes the servers so we can update their lifetimes more quickly in the common case where |
| 290 | * servers are not being added, but only being refreshed. |
| 291 | */ |
| 292 | private HashMap<InetAddress, DnsServerEntry> mIndex; |
| 293 | |
| 294 | public DnsServerRepository() { |
| 295 | mCurrentServers = new HashSet(); |
| 296 | mAllServers = new ArrayList<DnsServerEntry>(NUM_SERVERS); |
| 297 | mIndex = new HashMap<InetAddress, DnsServerEntry>(NUM_SERVERS); |
| 298 | } |
| 299 | |
| 300 | /** Sets the DNS servers of the provided LinkProperties object to the current servers. */ |
| 301 | public synchronized void setDnsServersOn(LinkProperties lp) { |
| 302 | lp.setDnsServers(mCurrentServers); |
| 303 | } |
| 304 | |
| 305 | /** |
| 306 | * Notifies the class of new DNS server information. |
| 307 | * @param lifetime the time in seconds that the DNS servers are valid. |
| 308 | * @param addresses the string representations of the IP addresses of the DNS servers to use. |
| 309 | */ |
| 310 | public synchronized boolean addServers(long lifetime, String[] addresses) { |
| 311 | // The lifetime is actually an unsigned 32-bit number, but Java doesn't have unsigned. |
| 312 | // Technically 0xffffffff (the maximum) is special and means "forever", but 2^32 seconds |
| 313 | // (136 years) is close enough. |
| 314 | long now = System.currentTimeMillis(); |
| 315 | long expiry = now + 1000 * lifetime; |
| 316 | |
| 317 | // Go through the list of servers. For each one, update the entry if one exists, and |
| 318 | // create one if it doesn't. |
| 319 | for (String addressString : addresses) { |
| 320 | InetAddress address; |
| 321 | try { |
| 322 | address = InetAddress.parseNumericAddress(addressString); |
| 323 | } catch (IllegalArgumentException ex) { |
| 324 | continue; |
| 325 | } |
| 326 | |
| 327 | if (!updateExistingEntry(address, expiry)) { |
| 328 | // There was no entry for this server. Create one, unless it's already expired |
| 329 | // (i.e., if the lifetime is zero; it cannot be < 0 because it's unsigned). |
| 330 | if (expiry > now) { |
| 331 | DnsServerEntry entry = new DnsServerEntry(address, expiry); |
| 332 | mAllServers.add(entry); |
| 333 | mIndex.put(address, entry); |
| 334 | } |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | // Sort the servers by expiry. |
| 339 | Collections.sort(mAllServers); |
| 340 | |
| 341 | // Prune excess entries and update the current server list. |
| 342 | return updateCurrentServers(); |
| 343 | } |
| 344 | |
| 345 | private synchronized boolean updateExistingEntry(InetAddress address, long expiry) { |
| 346 | DnsServerEntry existing = mIndex.get(address); |
| 347 | if (existing != null) { |
| 348 | existing.expiry = expiry; |
| 349 | return true; |
| 350 | } |
| 351 | return false; |
| 352 | } |
| 353 | |
| 354 | private synchronized boolean updateCurrentServers() { |
| 355 | long now = System.currentTimeMillis(); |
| 356 | boolean changed = false; |
| 357 | |
| 358 | // Prune excess or expired entries. |
| 359 | for (int i = mAllServers.size() - 1; i >= 0; i--) { |
| 360 | if (i >= NUM_SERVERS || mAllServers.get(i).expiry < now) { |
| 361 | DnsServerEntry removed = mAllServers.remove(i); |
| 362 | mIndex.remove(removed.address); |
| 363 | changed |= mCurrentServers.remove(removed.address); |
| 364 | } else { |
| 365 | break; |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | // Add servers to the current set, in order of decreasing lifetime, until it has enough. |
| 370 | // Prefer existing servers over new servers in order to minimize updates to the rest of the |
| 371 | // system and avoid persistent oscillations. |
| 372 | for (DnsServerEntry entry : mAllServers) { |
| 373 | if (mCurrentServers.size() < NUM_CURRENT_SERVERS) { |
| 374 | changed |= mCurrentServers.add(entry.address); |
| 375 | } else { |
| 376 | break; |
| 377 | } |
| 378 | } |
| 379 | return changed; |
| 380 | } |
| 381 | } |