blob: bb7f86233a402f07516bbf1d737da3638d83640c [file] [log] [blame]
Robert Greenwalt7b816022014-04-18 15:25:25 -07001/*
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
17package com.android.server.connectivity;
18
Yintang Gu1505d0a2019-06-18 14:24:32 +080019import android.annotation.NonNull;
Paul Jensenca8f16a2014-05-09 12:47:55 -040020import android.content.Context;
Luke Huang65914772019-03-16 00:31:46 +080021import android.net.IDnsResolver;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +090022import android.net.INetd;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090023import android.net.INetworkMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -070024import android.net.LinkProperties;
25import android.net.Network;
26import android.net.NetworkCapabilities;
27import android.net.NetworkInfo;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070028import android.net.NetworkMisc;
Lorenzo Colittiac955b32019-05-31 15:41:29 +090029import android.net.NetworkMonitorManager;
Robert Greenwalt7b816022014-04-18 15:25:25 -070030import android.net.NetworkRequest;
lucaslinc2bac512019-11-07 16:47:56 +080031import android.net.NetworkScore;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060032import android.net.NetworkState;
Paul Jensenca8f16a2014-05-09 12:47:55 -040033import android.os.Handler;
Hugo Benichief502882017-09-01 01:23:32 +000034import android.os.INetworkManagementService;
Robert Greenwalt7b816022014-04-18 15:25:25 -070035import android.os.Messenger;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090036import android.os.SystemClock;
37import android.util.Log;
Robert Greenwalt7b816022014-04-18 15:25:25 -070038import android.util.SparseArray;
39
40import com.android.internal.util.AsyncChannel;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090041import com.android.internal.util.WakeupMessage;
Paul Jensencf4c2c62015-07-01 14:16:32 -040042import com.android.server.ConnectivityService;
Robert Greenwalt7b816022014-04-18 15:25:25 -070043
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090044import java.io.PrintWriter;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090045import java.util.Objects;
46import java.util.SortedSet;
47import java.util.TreeSet;
Robert Greenwalt7b816022014-04-18 15:25:25 -070048
49/**
50 * A bag class used by ConnectivityService for holding a collection of most recent
51 * information published by a particular NetworkAgent as well as the
52 * AsyncChannel/messenger for reaching that NetworkAgent and lists of NetworkRequests
Paul Jensen85cf78e2015-06-25 13:25:07 -040053 * interested in using it. Default sort order is descending by score.
Robert Greenwalt7b816022014-04-18 15:25:25 -070054 */
Paul Jensene0988542015-06-25 15:30:08 -040055// States of a network:
56// --------------------
57// 1. registered, uncreated, disconnected, unvalidated
58// This state is entered when a NetworkFactory registers a NetworkAgent in any state except
59// the CONNECTED state.
Robin Lee585e2482016-05-01 23:00:00 +010060// 2. registered, uncreated, connecting, unvalidated
61// This state is entered when a registered NetworkAgent for a VPN network transitions to the
62// CONNECTING state (TODO: go through this state for every network, not just VPNs).
63// ConnectivityService will tell netd to create the network early in order to add extra UID
64// routing rules referencing the netID. These rules need to be in place before the network is
65// connected to avoid racing against client apps trying to connect to a half-setup network.
66// 3. registered, uncreated, connected, unvalidated
67// This state is entered when a registered NetworkAgent transitions to the CONNECTED state.
68// ConnectivityService will tell netd to create the network if it was not already created, and
69// immediately transition to state #4.
70// 4. registered, created, connected, unvalidated
Paul Jensencf4c2c62015-07-01 14:16:32 -040071// If this network can satisfy the default NetworkRequest, then NetworkMonitor will
Paul Jensene0988542015-06-25 15:30:08 -040072// probe for Internet connectivity.
73// If this network cannot satisfy the default NetworkRequest, it will immediately be
Robin Lee585e2482016-05-01 23:00:00 +010074// transitioned to state #5.
Paul Jensene0988542015-06-25 15:30:08 -040075// A network may remain in this state if NetworkMonitor fails to find Internet connectivity,
76// for example:
77// a. a captive portal is present, or
78// b. a WiFi router whose Internet backhaul is down, or
79// c. a wireless connection stops transfering packets temporarily (e.g. device is in elevator
80// or tunnel) but does not disconnect from the AP/cell tower, or
81// d. a stand-alone device offering a WiFi AP without an uplink for configuration purposes.
Robin Lee585e2482016-05-01 23:00:00 +010082// 5. registered, created, connected, validated
Paul Jensene0988542015-06-25 15:30:08 -040083//
84// The device's default network connection:
85// ----------------------------------------
Robin Lee585e2482016-05-01 23:00:00 +010086// Networks in states #4 and #5 may be used as a device's default network connection if they
Paul Jensene0988542015-06-25 15:30:08 -040087// satisfy the default NetworkRequest.
Robin Lee585e2482016-05-01 23:00:00 +010088// A network, that satisfies the default NetworkRequest, in state #5 should always be chosen
89// in favor of a network, that satisfies the default NetworkRequest, in state #4.
Paul Jensene0988542015-06-25 15:30:08 -040090// When deciding between two networks, that both satisfy the default NetworkRequest, to select
91// for the default network connection, the one with the higher score should be chosen.
92//
93// When a network disconnects:
94// ---------------------------
95// If a network's transport disappears, for example:
96// a. WiFi turned off, or
97// b. cellular data turned off, or
98// c. airplane mode is turned on, or
99// d. a wireless connection disconnects from AP/cell tower entirely (e.g. device is out of range
100// of AP for an extended period of time, or switches to another AP without roaming)
Robin Lee585e2482016-05-01 23:00:00 +0100101// then that network can transition from any state (#1-#5) to unregistered. This happens by
Paul Jensene0988542015-06-25 15:30:08 -0400102// the transport disconnecting their NetworkAgent's AsyncChannel with ConnectivityManager.
103// ConnectivityService also tells netd to destroy the network.
104//
105// When ConnectivityService disconnects a network:
106// -----------------------------------------------
107// If a network has no chance of satisfying any requests (even if it were to become validated
Robin Lee585e2482016-05-01 23:00:00 +0100108// and enter state #5), ConnectivityService will disconnect the NetworkAgent's AsyncChannel.
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900109//
110// If the network was satisfying a foreground NetworkRequest (i.e. had been the highest scoring that
111// satisfied the NetworkRequest's constraints), but is no longer the highest scoring network for any
112// foreground NetworkRequest, then there will be a 30s pause to allow network communication to be
113// wrapped up rather than abruptly terminated. During this pause the network is said to be
114// "lingering". During this pause if the network begins satisfying a foreground NetworkRequest,
115// ConnectivityService will cancel the future disconnection of the NetworkAgent's AsyncChannel, and
116// the network is no longer considered "lingering". After the linger timer expires, if the network
117// is satisfying one or more background NetworkRequests it is kept up in the background. If it is
118// not, ConnectivityService disconnects the NetworkAgent's AsyncChannel.
Paul Jensen85cf78e2015-06-25 13:25:07 -0400119public class NetworkAgentInfo implements Comparable<NetworkAgentInfo> {
Hugo Benichic8e9e122016-09-14 23:23:08 +0000120
Yintang Gu1505d0a2019-06-18 14:24:32 +0800121 @NonNull public NetworkInfo networkInfo;
Paul Jensen31a94f42015-02-13 14:18:39 -0500122 // This Network object should always be used if possible, so as to encourage reuse of the
123 // enclosed socket factory and connection pool. Avoid creating other Network objects.
124 // This Network object is always valid.
125 public final Network network;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700126 public LinkProperties linkProperties;
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +0900127 // This should only be modified by ConnectivityService, via setNetworkCapabilities().
128 // TODO: make this private with a getter.
Robert Greenwalt7b816022014-04-18 15:25:25 -0700129 public NetworkCapabilities networkCapabilities;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700130 public final NetworkMisc networkMisc;
Robin Lee585e2482016-05-01 23:00:00 +0100131 // Indicates if netd has been told to create this Network. From this point on the appropriate
132 // routing rules are setup and routes are added so packets can begin flowing over the Network.
Lorenzo Colittid49159f2015-05-14 23:15:10 +0900133 // This is a sticky bit; once set it is never cleared.
Paul Jenseneec75412014-08-04 12:21:19 -0400134 public boolean created;
Robin Lee585e2482016-05-01 23:00:00 +0100135 // Set to true after the first time this network is marked as CONNECTED. Once set, the network
136 // shows up in API calls, is able to satisfy NetworkRequests and can become the default network.
137 // This is a sticky bit; once set it is never cleared.
138 public boolean everConnected;
Paul Jensen71b645f2014-10-13 14:13:07 -0400139 // Set to true if this Network successfully passed validation or if it did not satisfy the
140 // default NetworkRequest in which case validation will not be attempted.
Lorenzo Colittid49159f2015-05-14 23:15:10 +0900141 // This is a sticky bit; once set it is never cleared even if future validation attempts fail.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +0900142 public boolean everValidated;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400143
Lorenzo Colitti7b42f392014-12-17 11:26:49 +0900144 // The result of the last validation attempt on this network (true if validated, false if not).
Lorenzo Colitti7b42f392014-12-17 11:26:49 +0900145 public boolean lastValidated;
146
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900147 // If true, becoming unvalidated will lower the network's score. This is only meaningful if the
148 // system is configured not to do this for certain networks, e.g., if the
149 // config_networkAvoidBadWifi option is set to 0 and the user has not overridden that via
150 // Settings.Global.NETWORK_AVOID_BAD_WIFI.
151 public boolean avoidUnvalidated;
152
Lorenzo Colittid49159f2015-05-14 23:15:10 +0900153 // Whether a captive portal was ever detected on this network.
154 // This is a sticky bit; once set it is never cleared.
Paul Jensen3d194ea2015-06-16 14:27:36 -0400155 public boolean everCaptivePortalDetected;
156
157 // Whether a captive portal was found during the last network validation attempt.
158 public boolean lastCaptivePortalDetected;
Lorenzo Colittid49159f2015-05-14 23:15:10 +0900159
Remi NGUYEN VAN0839a192019-06-17 11:28:27 +0900160 // Indicates the captive portal app was opened to show a login UI to the user, but the network
161 // has not validated yet.
162 public volatile boolean captivePortalValidationPending;
lucaslind2e045e02019-01-24 15:55:30 +0800163
lucasline252a742019-03-12 13:08:03 +0800164 // Set to true when partial connectivity was detected.
165 public boolean partialConnectivity;
166
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900167 // Networks are lingered when they become unneeded as a result of their NetworkRequests being
168 // satisfied by a higher-scoring network. so as to allow communication to wrap up before the
169 // network is taken down. This usually only happens to the default network. Lingering ends with
170 // either the linger timeout expiring and the network being taken down, or the network
171 // satisfying a request again.
172 public static class LingerTimer implements Comparable<LingerTimer> {
173 public final NetworkRequest request;
174 public final long expiryMs;
175
176 public LingerTimer(NetworkRequest request, long expiryMs) {
177 this.request = request;
178 this.expiryMs = expiryMs;
179 }
180 public boolean equals(Object o) {
181 if (!(o instanceof LingerTimer)) return false;
182 LingerTimer other = (LingerTimer) o;
183 return (request.requestId == other.request.requestId) && (expiryMs == other.expiryMs);
184 }
185 public int hashCode() {
186 return Objects.hash(request.requestId, expiryMs);
187 }
188 public int compareTo(LingerTimer other) {
189 return (expiryMs != other.expiryMs) ?
190 Long.compare(expiryMs, other.expiryMs) :
191 Integer.compare(request.requestId, other.request.requestId);
192 }
193 public String toString() {
194 return String.format("%s, expires %dms", request.toString(),
195 expiryMs - SystemClock.elapsedRealtime());
196 }
197 }
198
199 /**
200 * Inform ConnectivityService that the network LINGER period has
201 * expired.
202 * obj = this NetworkAgentInfo
203 */
204 public static final int EVENT_NETWORK_LINGER_COMPLETE = 1001;
205
206 // All linger timers for this network, sorted by expiry time. A linger timer is added whenever
207 // a request is moved to a network with a better score, regardless of whether the network is or
208 // was lingering or not.
209 // TODO: determine if we can replace this with a smaller or unsorted data structure. (e.g.,
210 // SparseLongArray) combined with the timestamp of when the last timer is scheduled to fire.
211 private final SortedSet<LingerTimer> mLingerTimers = new TreeSet<>();
212
213 // For fast lookups. Indexes into mLingerTimers by request ID.
214 private final SparseArray<LingerTimer> mLingerTimerForRequest = new SparseArray<>();
215
216 // Linger expiry timer. Armed whenever mLingerTimers is non-empty, regardless of whether the
217 // network is lingering or not. Always set to the expiry of the LingerTimer that expires last.
218 // When the timer fires, all linger state is cleared, and if the network has no requests, it is
219 // torn down.
220 private WakeupMessage mLingerMessage;
221
222 // Linger expiry. Holds the expiry time of the linger timer, or 0 if the timer is not armed.
223 private long mLingerExpiryMs;
224
225 // Whether the network is lingering or not. Must be maintained separately from the above because
226 // it depends on the state of other networks and requests, which only ConnectivityService knows.
227 // (Example: we don't linger a network if it would become the best for a NetworkRequest if it
228 // validated).
229 private boolean mLingering;
Paul Jensen85cf78e2015-06-25 13:25:07 -0400230
lucaslinc2bac512019-11-07 16:47:56 +0800231 // This represents the characteristics of a network that affects how good the network is
232 // considered for a particular use.
233 @NonNull
234 private NetworkScore mNetworkScore;
Robert Greenwalte73cc462014-09-07 16:50:01 -0700235
Robert Greenwalt7b816022014-04-18 15:25:25 -0700236 // The list of NetworkRequests being satisfied by this Network.
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900237 private final SparseArray<NetworkRequest> mNetworkRequests = new SparseArray<>();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900238
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900239 // How many of the satisfied requests are actual requests and not listens.
240 private int mNumRequestNetworkRequests = 0;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700241
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900242 // How many of the satisfied requests are of type BACKGROUND_REQUEST.
243 private int mNumBackgroundNetworkRequests = 0;
244
Robert Greenwalt7b816022014-04-18 15:25:25 -0700245 public final Messenger messenger;
246 public final AsyncChannel asyncChannel;
247
Chalard Jean05ab6812018-05-02 21:14:54 +0900248 public final int factorySerialNumber;
249
Lorenzo Colitti95439462014-10-09 13:44:48 +0900250 // Used by ConnectivityService to keep track of 464xlat.
Lorenzo Colittidf595632019-01-08 14:43:37 +0900251 public final Nat464Xlat clatd;
Lorenzo Colitti95439462014-10-09 13:44:48 +0900252
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900253 // Set after asynchronous creation of the NetworkMonitor.
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900254 private volatile NetworkMonitorManager mNetworkMonitor;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900255
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900256 private static final String TAG = ConnectivityService.class.getSimpleName();
257 private static final boolean VDBG = false;
Hugo Benichi50d46a42017-08-31 14:29:51 +0000258 private final ConnectivityService mConnService;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900259 private final Context mContext;
Hugo Benichi50d46a42017-08-31 14:29:51 +0000260 private final Handler mHandler;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900261
Paul Jensen31a94f42015-02-13 14:18:39 -0500262 public NetworkAgentInfo(Messenger messenger, AsyncChannel ac, Network net, NetworkInfo info,
lucaslinc2bac512019-11-07 16:47:56 +0800263 LinkProperties lp, NetworkCapabilities nc, @NonNull NetworkScore ns, Context context,
264 Handler handler, NetworkMisc misc, ConnectivityService connService, INetd netd,
Luke Huang65914772019-03-16 00:31:46 +0800265 IDnsResolver dnsResolver, INetworkManagementService nms, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -0700266 this.messenger = messenger;
267 asyncChannel = ac;
Paul Jensen31a94f42015-02-13 14:18:39 -0500268 network = net;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700269 networkInfo = info;
270 linkProperties = lp;
271 networkCapabilities = nc;
lucaslinc2bac512019-11-07 16:47:56 +0800272 mNetworkScore = ns;
Luke Huang65914772019-03-16 00:31:46 +0800273 clatd = new Nat464Xlat(this, netd, dnsResolver, nms);
Hugo Benichi50d46a42017-08-31 14:29:51 +0000274 mConnService = connService;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900275 mContext = context;
Hugo Benichi50d46a42017-08-31 14:29:51 +0000276 mHandler = handler;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700277 networkMisc = misc;
Chalard Jean05ab6812018-05-02 21:14:54 +0900278 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700279 }
280
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900281 /**
282 * Inform NetworkAgentInfo that a new NetworkMonitor was created.
283 */
284 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900285 mNetworkMonitor = new NetworkMonitorManager(networkMonitor);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900286 }
287
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +0900288 /**
289 * Set the NetworkCapabilities on this NetworkAgentInfo. Also attempts to notify NetworkMonitor
290 * of the new capabilities, if NetworkMonitor has been created.
291 *
292 * <p>If {@link NetworkMonitor#notifyNetworkCapabilitiesChanged(NetworkCapabilities)} fails,
293 * the exception is logged but not reported to callers.
294 */
295 public void setNetworkCapabilities(NetworkCapabilities nc) {
296 networkCapabilities = nc;
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900297 final NetworkMonitorManager nm = mNetworkMonitor;
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +0900298 if (nm != null) {
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900299 nm.notifyNetworkCapabilitiesChanged(nc);
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +0900300 }
301 }
302
Hugo Benichief502882017-09-01 01:23:32 +0000303 public ConnectivityService connService() {
304 return mConnService;
305 }
306
soma, kawata88b8f632018-10-23 21:10:02 +0900307 public NetworkMisc netMisc() {
308 return networkMisc;
309 }
310
Hugo Benichief502882017-09-01 01:23:32 +0000311 public Handler handler() {
312 return mHandler;
313 }
314
Hugo Benichic894b122017-07-31 12:58:20 +0900315 public Network network() {
316 return network;
317 }
318
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900319 /**
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900320 * Get the NetworkMonitorManager in this NetworkAgentInfo.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900321 *
322 * <p>This will be null before {@link #onNetworkMonitorCreated(INetworkMonitor)} is called.
323 */
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900324 public NetworkMonitorManager networkMonitor() {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900325 return mNetworkMonitor;
326 }
327
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900328 // Functions for manipulating the requests satisfied by this network.
329 //
330 // These functions must only called on ConnectivityService's main thread.
331
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900332 private static final boolean ADD = true;
333 private static final boolean REMOVE = false;
334
335 private void updateRequestCounts(boolean add, NetworkRequest request) {
336 int delta = add ? +1 : -1;
337 switch (request.type) {
338 case REQUEST:
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900339 mNumRequestNetworkRequests += delta;
340 break;
341
342 case BACKGROUND_REQUEST:
343 mNumRequestNetworkRequests += delta;
344 mNumBackgroundNetworkRequests += delta;
345 break;
346
Chalard Jean715d39b2018-02-16 17:59:29 +0900347 case TRACK_DEFAULT:
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900348 case LISTEN:
349 break;
350
351 case NONE:
352 default:
353 Log.wtf(TAG, "Unhandled request type " + request.type);
354 break;
355 }
356 }
357
Paul Jensen3d911462015-06-12 06:40:24 -0400358 /**
359 * Add {@code networkRequest} to this network as it's satisfied by this network.
Paul Jensen3d911462015-06-12 06:40:24 -0400360 * @return true if {@code networkRequest} was added or false if {@code networkRequest} was
361 * already present.
362 */
363 public boolean addRequest(NetworkRequest networkRequest) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900364 NetworkRequest existing = mNetworkRequests.get(networkRequest.requestId);
365 if (existing == networkRequest) return false;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900366 if (existing != null) {
367 // Should only happen if the requestId wraps. If that happens lots of other things will
368 // be broken as well.
369 Log.wtf(TAG, String.format("Duplicate requestId for %s and %s on %s",
370 networkRequest, existing, name()));
371 updateRequestCounts(REMOVE, existing);
372 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900373 mNetworkRequests.put(networkRequest.requestId, networkRequest);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900374 updateRequestCounts(ADD, networkRequest);
Paul Jensen3d911462015-06-12 06:40:24 -0400375 return true;
Robert Greenwalt71bf33a2014-05-15 18:07:26 -0700376 }
377
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900378 /**
379 * Remove the specified request from this network.
380 */
381 public void removeRequest(int requestId) {
382 NetworkRequest existing = mNetworkRequests.get(requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900383 if (existing == null) return;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900384 updateRequestCounts(REMOVE, existing);
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900385 mNetworkRequests.remove(requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900386 if (existing.isRequest()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900387 unlingerRequest(existing);
388 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900389 }
390
391 /**
392 * Returns whether this network is currently satisfying the request with the specified ID.
393 */
394 public boolean isSatisfyingRequest(int id) {
395 return mNetworkRequests.get(id) != null;
396 }
397
398 /**
399 * Returns the request at the specified position in the list of requests satisfied by this
400 * network.
401 */
402 public NetworkRequest requestAt(int index) {
403 return mNetworkRequests.valueAt(index);
404 }
405
406 /**
407 * Returns the number of requests currently satisfied by this network for which
408 * {@link android.net.NetworkRequest#isRequest} returns {@code true}.
409 */
410 public int numRequestNetworkRequests() {
411 return mNumRequestNetworkRequests;
412 }
413
414 /**
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900415 * Returns the number of requests currently satisfied by this network of type
416 * {@link android.net.NetworkRequest.Type.BACKGROUND_REQUEST}.
417 */
418 public int numBackgroundNetworkRequests() {
419 return mNumBackgroundNetworkRequests;
420 }
421
422 /**
423 * Returns the number of foreground requests currently satisfied by this network.
424 */
425 public int numForegroundNetworkRequests() {
426 return mNumRequestNetworkRequests - mNumBackgroundNetworkRequests;
427 }
428
429 /**
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900430 * Returns the number of requests of any type currently satisfied by this network.
431 */
432 public int numNetworkRequests() {
433 return mNetworkRequests.size();
434 }
435
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900436 /**
437 * Returns whether the network is a background network. A network is a background network if it
Chalard Jeanb72b62d2018-02-16 16:08:35 +0900438 * does not have the NET_CAPABILITY_FOREGROUND capability, which implies it is satisfying no
439 * foreground request, is not lingering (i.e. kept for a while after being outscored), and is
440 * not a speculative network (i.e. kept pending validation when validation would have it
441 * outscore another foreground network). That implies it is being kept up by some background
442 * request (otherwise it would be torn down), maybe the mobile always-on request.
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900443 */
444 public boolean isBackgroundNetwork() {
Chalard Jeanb72b62d2018-02-16 16:08:35 +0900445 return !isVPN() && numForegroundNetworkRequests() == 0 && mNumBackgroundNetworkRequests > 0
446 && !isLingering();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900447 }
448
Chalard Jean804b8fb2018-01-30 22:41:41 +0900449 /**
450 * Returns whether this network is currently suspended. A network is suspended if it is still
451 * connected but data temporarily fails to transfer. See {@link NetworkInfo.State#SUSPENDED}
452 * and {@link NetworkCapabilities#NET_CAPABILITY_NOT_SUSPENDED}.
453 */
454 public boolean isSuspended() {
455 return networkInfo.getState() == NetworkInfo.State.SUSPENDED;
456 }
457
Paul Jensen0cc17322014-11-25 15:26:53 -0500458 // Does this network satisfy request?
459 public boolean satisfies(NetworkRequest request) {
460 return created &&
461 request.networkCapabilities.satisfiedByNetworkCapabilities(networkCapabilities);
462 }
463
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900464 public boolean satisfiesImmutableCapabilitiesOf(NetworkRequest request) {
465 return created &&
466 request.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
467 networkCapabilities);
468 }
469
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400470 public boolean isVPN() {
471 return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN);
472 }
473
Paul Jensenb10e37f2014-11-25 12:33:08 -0500474 private int getCurrentScore(boolean pretendValidated) {
Paul Jensen2161a8e2014-09-11 11:00:39 -0400475 // TODO: We may want to refactor this into a NetworkScore class that takes a base score from
476 // the NetworkAgent and signals from the NetworkAgent and uses those signals to modify the
477 // score. The NetworkScore class would provide a nice place to centralize score constants
478 // so they are not scattered about the transports.
479
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900480 // If this network is explicitly selected and the user has decided to use it even if it's
481 // unvalidated, give it the maximum score. Also give it the maximum score if it's explicitly
482 // selected and we're trying to see what its score could be. This ensures that we don't tear
483 // down an explicitly selected network before the user gets a chance to prefer it when
484 // a higher-scoring network (e.g., Ethernet) is available.
485 if (networkMisc.explicitlySelected && (networkMisc.acceptUnvalidated || pretendValidated)) {
Lorenzo Colitti80986d92019-03-22 00:28:28 +0900486 return ConnectivityConstants.EXPLICITLY_SELECTED_NETWORK_SCORE;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900487 }
Paul Jensen2161a8e2014-09-11 11:00:39 -0400488
lucaslinc2bac512019-11-07 16:47:56 +0800489 int score = mNetworkScore.getIntExtension(NetworkScore.LEGACY_SCORE);
Lorenzo Colitti80986d92019-03-22 00:28:28 +0900490 if (!lastValidated && !pretendValidated && !ignoreWifiUnvalidationPenalty() && !isVPN()) {
Chalard Jean918a68b2018-01-19 17:00:47 +0900491 score -= ConnectivityConstants.UNVALIDATED_SCORE_PENALTY;
Paul Jensene0988542015-06-25 15:30:08 -0400492 }
Paul Jensen2161a8e2014-09-11 11:00:39 -0400493 if (score < 0) score = 0;
Paul Jensen2161a8e2014-09-11 11:00:39 -0400494 return score;
495 }
496
Hugo Benichic8e9e122016-09-14 23:23:08 +0000497 // Return true on devices configured to ignore score penalty for wifi networks
498 // that become unvalidated (b/31075769).
499 private boolean ignoreWifiUnvalidationPenalty() {
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900500 boolean isWifi = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
501 networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
Hugo Benichi50d46a42017-08-31 14:29:51 +0000502 boolean avoidBadWifi = mConnService.avoidBadWifi() || avoidUnvalidated;
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900503 return isWifi && !avoidBadWifi && everValidated;
Hugo Benichic8e9e122016-09-14 23:23:08 +0000504 }
505
Paul Jensenb10e37f2014-11-25 12:33:08 -0500506 // Get the current score for this Network. This may be modified from what the
507 // NetworkAgent sent, as it has modifiers applied to it.
508 public int getCurrentScore() {
509 return getCurrentScore(false);
510 }
511
512 // Get the current score for this Network as if it was validated. This may be modified from
513 // what the NetworkAgent sent, as it has modifiers applied to it.
514 public int getCurrentScoreAsValidated() {
515 return getCurrentScore(true);
516 }
517
lucaslinc2bac512019-11-07 16:47:56 +0800518 public void setNetworkScore(@NonNull NetworkScore ns) {
519 mNetworkScore = ns;
520 }
521
522 @NonNull
523 public NetworkScore getNetworkScore() {
524 return mNetworkScore;
Paul Jensen2161a8e2014-09-11 11:00:39 -0400525 }
526
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600527 public NetworkState getNetworkState() {
528 synchronized (this) {
Chalard Jean804b8fb2018-01-30 22:41:41 +0900529 // Network objects are outwardly immutable so there is no point in duplicating.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600530 // Duplicating also precludes sharing socket factories and connection pools.
531 final String subscriberId = (networkMisc != null) ? networkMisc.subscriberId : null;
532 return new NetworkState(new NetworkInfo(networkInfo),
533 new LinkProperties(linkProperties),
534 new NetworkCapabilities(networkCapabilities), network, subscriberId, null);
535 }
536 }
537
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900538 /**
539 * Sets the specified request to linger on this network for the specified time. Called by
540 * ConnectivityService when the request is moved to another network with a higher score.
541 */
542 public void lingerRequest(NetworkRequest request, long now, long duration) {
543 if (mLingerTimerForRequest.get(request.requestId) != null) {
544 // Cannot happen. Once a request is lingering on a particular network, we cannot
545 // re-linger it unless that network becomes the best for that request again, in which
546 // case we should have unlingered it.
547 Log.wtf(TAG, this.name() + ": request " + request.requestId + " already lingered");
548 }
549 final long expiryMs = now + duration;
550 LingerTimer timer = new LingerTimer(request, expiryMs);
551 if (VDBG) Log.d(TAG, "Adding LingerTimer " + timer + " to " + this.name());
552 mLingerTimers.add(timer);
553 mLingerTimerForRequest.put(request.requestId, timer);
554 }
555
556 /**
557 * Cancel lingering. Called by ConnectivityService when a request is added to this network.
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900558 * Returns true if the given request was lingering on this network, false otherwise.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900559 */
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900560 public boolean unlingerRequest(NetworkRequest request) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900561 LingerTimer timer = mLingerTimerForRequest.get(request.requestId);
562 if (timer != null) {
563 if (VDBG) Log.d(TAG, "Removing LingerTimer " + timer + " from " + this.name());
564 mLingerTimers.remove(timer);
565 mLingerTimerForRequest.remove(request.requestId);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900566 return true;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900567 }
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900568 return false;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900569 }
570
571 public long getLingerExpiry() {
572 return mLingerExpiryMs;
573 }
574
575 public void updateLingerTimer() {
576 long newExpiry = mLingerTimers.isEmpty() ? 0 : mLingerTimers.last().expiryMs;
577 if (newExpiry == mLingerExpiryMs) return;
578
579 // Even if we're going to reschedule the timer, cancel it first. This is because the
580 // semantics of WakeupMessage guarantee that if cancel is called then the alarm will
581 // never call its callback (handleLingerComplete), even if it has already fired.
582 // WakeupMessage makes no such guarantees about rescheduling a message, so if mLingerMessage
Chalard Jeana3984a12019-11-19 20:01:10 +0900583 // has already been dispatched, rescheduling to some time in the future won't stop it
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900584 // from calling its callback immediately.
585 if (mLingerMessage != null) {
586 mLingerMessage.cancel();
587 mLingerMessage = null;
588 }
589
590 if (newExpiry > 0) {
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900591 mLingerMessage = new WakeupMessage(
Hugo Benichi50d46a42017-08-31 14:29:51 +0000592 mContext, mHandler,
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900593 "NETWORK_LINGER_COMPLETE." + network.netId /* cmdName */,
594 EVENT_NETWORK_LINGER_COMPLETE /* cmd */,
595 0 /* arg1 (unused) */, 0 /* arg2 (unused) */,
596 this /* obj (NetworkAgentInfo) */);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900597 mLingerMessage.schedule(newExpiry);
598 }
599
600 mLingerExpiryMs = newExpiry;
601 }
602
603 public void linger() {
604 mLingering = true;
605 }
606
607 public void unlinger() {
608 mLingering = false;
609 }
610
611 public boolean isLingering() {
612 return mLingering;
613 }
614
615 public void clearLingerState() {
616 if (mLingerMessage != null) {
617 mLingerMessage.cancel();
618 mLingerMessage = null;
619 }
620 mLingerTimers.clear();
621 mLingerTimerForRequest.clear();
622 updateLingerTimer(); // Sets mLingerExpiryMs, cancels and nulls out mLingerMessage.
623 mLingering = false;
624 }
625
626 public void dumpLingerTimers(PrintWriter pw) {
627 for (LingerTimer timer : mLingerTimers) { pw.println(timer); }
628 }
629
lucasline252a742019-03-12 13:08:03 +0800630 // TODO: Print shorter members first and only print the boolean variable which value is true
631 // to improve readability.
Robert Greenwalt7b816022014-04-18 15:25:25 -0700632 public String toString() {
lucaslind2e045e02019-01-24 15:55:30 +0800633 return "NetworkAgentInfo{ ni{" + networkInfo + "} "
634 + "network{" + network + "} nethandle{" + network.getNetworkHandle() + "} "
635 + "lp{" + linkProperties + "} "
636 + "nc{" + networkCapabilities + "} Score{" + getCurrentScore() + "} "
637 + "everValidated{" + everValidated + "} lastValidated{" + lastValidated + "} "
638 + "created{" + created + "} lingering{" + isLingering() + "} "
639 + "explicitlySelected{" + networkMisc.explicitlySelected + "} "
640 + "acceptUnvalidated{" + networkMisc.acceptUnvalidated + "} "
641 + "everCaptivePortalDetected{" + everCaptivePortalDetected + "} "
642 + "lastCaptivePortalDetected{" + lastCaptivePortalDetected + "} "
Remi NGUYEN VAN0839a192019-06-17 11:28:27 +0900643 + "captivePortalValidationPending{" + captivePortalValidationPending + "} "
lucasline252a742019-03-12 13:08:03 +0800644 + "partialConnectivity{" + partialConnectivity + "} "
645 + "acceptPartialConnectivity{" + networkMisc.acceptPartialConnectivity + "} "
lucaslind2e045e02019-01-24 15:55:30 +0800646 + "clat{" + clatd + "} "
647 + "}";
Robert Greenwalt7b816022014-04-18 15:25:25 -0700648 }
649
650 public String name() {
651 return "NetworkAgentInfo [" + networkInfo.getTypeName() + " (" +
Hugo Benichib577d652017-06-27 15:13:20 +0900652 networkInfo.getSubtypeName() + ") - " + Objects.toString(network) + "]";
Robert Greenwalt7b816022014-04-18 15:25:25 -0700653 }
Paul Jensen85cf78e2015-06-25 13:25:07 -0400654
655 // Enables sorting in descending order of score.
656 @Override
657 public int compareTo(NetworkAgentInfo other) {
658 return other.getCurrentScore() - getCurrentScore();
659 }
Robert Greenwalt7b816022014-04-18 15:25:25 -0700660}