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.connectivity; 18 19 import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED; 20 21 import android.content.Context; 22 import android.net.LinkProperties; 23 import android.net.Network; 24 import android.net.NetworkCapabilities; 25 import android.net.NetworkInfo; 26 import android.net.NetworkMisc; 27 import android.net.NetworkRequest; 28 import android.os.Handler; 29 import android.os.Messenger; 30 import android.util.SparseArray; 31 32 import com.android.internal.util.AsyncChannel; 33 import com.android.server.ConnectivityService; 34 import com.android.server.connectivity.NetworkMonitor; 35 36 import java.util.ArrayList; 37 import java.util.Comparator; 38 39 /** 40 * A bag class used by ConnectivityService for holding a collection of most recent 41 * information published by a particular NetworkAgent as well as the 42 * AsyncChannel/messenger for reaching that NetworkAgent and lists of NetworkRequests 43 * interested in using it. Default sort order is descending by score. 44 */ 45 // States of a network: 46 // -------------------- 47 // 1. registered, uncreated, disconnected, unvalidated 48 // This state is entered when a NetworkFactory registers a NetworkAgent in any state except 49 // the CONNECTED state. 50 // 2. registered, uncreated, connected, unvalidated 51 // This state is entered when a registered NetworkAgent transitions to the CONNECTED state 52 // ConnectivityService will tell netd to create the network and immediately transition to 53 // state #3. 54 // 3. registered, created, connected, unvalidated 55 // If this network can satisfy the default NetworkRequest, then NetworkMonitor will 56 // probe for Internet connectivity. 57 // If this network cannot satisfy the default NetworkRequest, it will immediately be 58 // transitioned to state #4. 59 // A network may remain in this state if NetworkMonitor fails to find Internet connectivity, 60 // for example: 61 // a. a captive portal is present, or 62 // b. a WiFi router whose Internet backhaul is down, or 63 // c. a wireless connection stops transfering packets temporarily (e.g. device is in elevator 64 // or tunnel) but does not disconnect from the AP/cell tower, or 65 // d. a stand-alone device offering a WiFi AP without an uplink for configuration purposes. 66 // 4. registered, created, connected, validated 67 // 68 // The device's default network connection: 69 // ---------------------------------------- 70 // Networks in states #3 and #4 may be used as a device's default network connection if they 71 // satisfy the default NetworkRequest. 72 // A network, that satisfies the default NetworkRequest, in state #4 should always be chosen 73 // in favor of a network, that satisfies the default NetworkRequest, in state #3. 74 // When deciding between two networks, that both satisfy the default NetworkRequest, to select 75 // for the default network connection, the one with the higher score should be chosen. 76 // 77 // When a network disconnects: 78 // --------------------------- 79 // If a network's transport disappears, for example: 80 // a. WiFi turned off, or 81 // b. cellular data turned off, or 82 // c. airplane mode is turned on, or 83 // d. a wireless connection disconnects from AP/cell tower entirely (e.g. device is out of range 84 // of AP for an extended period of time, or switches to another AP without roaming) 85 // then that network can transition from any state (#1-#4) to unregistered. This happens by 86 // the transport disconnecting their NetworkAgent's AsyncChannel with ConnectivityManager. 87 // ConnectivityService also tells netd to destroy the network. 88 // 89 // When ConnectivityService disconnects a network: 90 // ----------------------------------------------- 91 // If a network has no chance of satisfying any requests (even if it were to become validated 92 // and enter state #4), ConnectivityService will disconnect the NetworkAgent's AsyncChannel. 93 // If the network ever for any period of time had satisfied a NetworkRequest (i.e. had been 94 // the highest scoring that satisfied the NetworkRequest's constraints), but is no longer the 95 // highest scoring network for any NetworkRequest, then there will be a 30s pause before 96 // ConnectivityService disconnects the NetworkAgent's AsyncChannel. During this pause the 97 // network is considered "lingering". This pause exists to allow network communication to be 98 // wrapped up rather than abruptly terminated. During this pause if the network begins satisfying 99 // a NetworkRequest, ConnectivityService will cancel the future disconnection of the NetworkAgent's 100 // AsyncChannel, and the network is no longer considered "lingering". 101 public class NetworkAgentInfo implements Comparable<NetworkAgentInfo> { 102 public NetworkInfo networkInfo; 103 // This Network object should always be used if possible, so as to encourage reuse of the 104 // enclosed socket factory and connection pool. Avoid creating other Network objects. 105 // This Network object is always valid. 106 public final Network network; 107 public LinkProperties linkProperties; 108 // This should only be modified via ConnectivityService.updateCapabilities(). 109 public NetworkCapabilities networkCapabilities; 110 public final NetworkMonitor networkMonitor; 111 public final NetworkMisc networkMisc; 112 // Indicates if netd has been told to create this Network. Once created the appropriate routing 113 // rules are setup and routes are added so packets can begin flowing over the Network. 114 // This is a sticky bit; once set it is never cleared. 115 public boolean created; 116 // Set to true if this Network successfully passed validation or if it did not satisfy the 117 // default NetworkRequest in which case validation will not be attempted. 118 // This is a sticky bit; once set it is never cleared even if future validation attempts fail. 119 public boolean everValidated; 120 121 // The result of the last validation attempt on this network (true if validated, false if not). 122 // This bit exists only because we never unvalidate a network once it's been validated, and that 123 // is because the network scoring and revalidation code does not (may not?) deal properly with 124 // networks becoming unvalidated. 125 // TODO: Fix the network scoring code, remove this, and rename everValidated to validated. 126 public boolean lastValidated; 127 128 // Whether a captive portal was ever detected on this network. 129 // This is a sticky bit; once set it is never cleared. 130 public boolean everCaptivePortalDetected; 131 132 // Whether a captive portal was found during the last network validation attempt. 133 public boolean lastCaptivePortalDetected; 134 135 // Indicates whether the network is lingering. Networks are lingered when they become unneeded 136 // as a result of their NetworkRequests being satisfied by a different network, so as to allow 137 // communication to wrap up before the network is taken down. This usually only happens to the 138 // default network. Lingering ends with either the linger timeout expiring and the network 139 // being taken down, or the network satisfying a request again. 140 public boolean lingering; 141 142 // This represents the last score received from the NetworkAgent. 143 private int currentScore; 144 // Penalty applied to scores of Networks that have not been validated. 145 private static final int UNVALIDATED_SCORE_PENALTY = 40; 146 147 // Score for explicitly connected network. 148 // 149 // This ensures that a) the explicitly selected network is never trumped by anything else, and 150 // b) the explicitly selected network is never torn down. 151 private static final int MAXIMUM_NETWORK_SCORE = 100; 152 153 // The list of NetworkRequests being satisfied by this Network. 154 public final SparseArray<NetworkRequest> networkRequests = new SparseArray<NetworkRequest>(); 155 // The list of NetworkRequests that this Network previously satisfied with the highest 156 // score. A non-empty list indicates that if this Network was validated it is lingered. 157 // NOTE: This list is only used for debugging. 158 public final ArrayList<NetworkRequest> networkLingered = new ArrayList<NetworkRequest>(); 159 160 public final Messenger messenger; 161 public final AsyncChannel asyncChannel; 162 163 // Used by ConnectivityService to keep track of 464xlat. 164 public Nat464Xlat clatd; 165 166 public NetworkAgentInfo(Messenger messenger, AsyncChannel ac, Network net, NetworkInfo info, 167 LinkProperties lp, NetworkCapabilities nc, int score, Context context, Handler handler, 168 NetworkMisc misc, NetworkRequest defaultRequest, ConnectivityService connService) { 169 this.messenger = messenger; 170 asyncChannel = ac; 171 network = net; 172 networkInfo = info; 173 linkProperties = lp; 174 networkCapabilities = nc; 175 currentScore = score; 176 networkMonitor = connService.createNetworkMonitor(context, handler, this, defaultRequest); 177 networkMisc = misc; 178 } 179 180 /** 181 * Add {@code networkRequest} to this network as it's satisfied by this network. 182 * NOTE: This function must only be called on ConnectivityService's main thread. 183 * @return true if {@code networkRequest} was added or false if {@code networkRequest} was 184 * already present. 185 */ 186 public boolean addRequest(NetworkRequest networkRequest) { 187 if (networkRequests.get(networkRequest.requestId) == networkRequest) return false; 188 networkRequests.put(networkRequest.requestId, networkRequest); 189 return true; 190 } 191 192 // Does this network satisfy request? 193 public boolean satisfies(NetworkRequest request) { 194 return created && 195 request.networkCapabilities.satisfiedByNetworkCapabilities(networkCapabilities); 196 } 197 198 public boolean isVPN() { 199 return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN); 200 } 201 202 private int getCurrentScore(boolean pretendValidated) { 203 // TODO: We may want to refactor this into a NetworkScore class that takes a base score from 204 // the NetworkAgent and signals from the NetworkAgent and uses those signals to modify the 205 // score. The NetworkScore class would provide a nice place to centralize score constants 206 // so they are not scattered about the transports. 207 208 // If this network is explicitly selected and the user has decided to use it even if it's 209 // unvalidated, give it the maximum score. Also give it the maximum score if it's explicitly 210 // selected and we're trying to see what its score could be. This ensures that we don't tear 211 // down an explicitly selected network before the user gets a chance to prefer it when 212 // a higher-scoring network (e.g., Ethernet) is available. 213 if (networkMisc.explicitlySelected && (networkMisc.acceptUnvalidated || pretendValidated)) { 214 return MAXIMUM_NETWORK_SCORE; 215 } 216 217 int score = currentScore; 218 // Use NET_CAPABILITY_VALIDATED here instead of lastValidated, this allows 219 // ConnectivityService.updateCapabilities() to compute the old score prior to updating 220 // networkCapabilities (with a potentially different validated state). 221 if (!networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) && !pretendValidated) { 222 score -= UNVALIDATED_SCORE_PENALTY; 223 } 224 if (score < 0) score = 0; 225 return score; 226 } 227 228 // Get the current score for this Network. This may be modified from what the 229 // NetworkAgent sent, as it has modifiers applied to it. 230 public int getCurrentScore() { 231 return getCurrentScore(false); 232 } 233 234 // Get the current score for this Network as if it was validated. This may be modified from 235 // what the NetworkAgent sent, as it has modifiers applied to it. 236 public int getCurrentScoreAsValidated() { 237 return getCurrentScore(true); 238 } 239 240 public void setCurrentScore(int newScore) { 241 currentScore = newScore; 242 } 243 244 public String toString() { 245 return "NetworkAgentInfo{ ni{" + networkInfo + "} network{" + 246 network + "} lp{" + 247 linkProperties + "} nc{" + 248 networkCapabilities + "} Score{" + getCurrentScore() + "} " + 249 "everValidated{" + everValidated + "} lastValidated{" + lastValidated + "} " + 250 "created{" + created + "} lingering{" + lingering + "} " + 251 "explicitlySelected{" + networkMisc.explicitlySelected + "} " + 252 "acceptUnvalidated{" + networkMisc.acceptUnvalidated + "} " + 253 "everCaptivePortalDetected{" + everCaptivePortalDetected + "} " + 254 "lastCaptivePortalDetected{" + lastCaptivePortalDetected + "} " + 255 "}"; 256 } 257 258 public String name() { 259 return "NetworkAgentInfo [" + networkInfo.getTypeName() + " (" + 260 networkInfo.getSubtypeName() + ") - " + 261 (network == null ? "null" : network.toString()) + "]"; 262 } 263 264 // Enables sorting in descending order of score. 265 @Override 266 public int compareTo(NetworkAgentInfo other) { 267 return other.getCurrentScore() - getCurrentScore(); 268 } 269 } 270