blob: 15628f03bacf9f83378204512c1651a50f901ebf [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
Cody Kesting560eb262020-02-12 14:50:58 -080019import static android.net.ConnectivityDiagnosticsManager.ConnectivityReport;
Chalard Jeanbf1170c2019-12-10 21:07:02 +090020import static android.net.NetworkCapabilities.transportNamesOf;
21
Yintang Gu1505d0a2019-06-18 14:24:32 +080022import android.annotation.NonNull;
Chalard Jeanbf1170c2019-12-10 21:07:02 +090023import android.annotation.Nullable;
Paul Jensenca8f16a2014-05-09 12:47:55 -040024import android.content.Context;
Remi NGUYEN VAN91aa5bc2019-12-12 12:57:11 +090025import android.net.CaptivePortalData;
Luke Huang65914772019-03-16 00:31:46 +080026import android.net.IDnsResolver;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +090027import android.net.INetd;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +090028import android.net.INetworkMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -070029import android.net.LinkProperties;
30import android.net.Network;
Lorenzo Colittid9696562020-01-12 22:28:37 +090031import android.net.NetworkAgentConfig;
Robert Greenwalt7b816022014-04-18 15:25:25 -070032import android.net.NetworkCapabilities;
33import android.net.NetworkInfo;
Lorenzo Colittiac955b32019-05-31 15:41:29 +090034import android.net.NetworkMonitorManager;
Robert Greenwalt7b816022014-04-18 15:25:25 -070035import android.net.NetworkRequest;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060036import android.net.NetworkState;
Paul Jensenca8f16a2014-05-09 12:47:55 -040037import android.os.Handler;
Hugo Benichief502882017-09-01 01:23:32 +000038import android.os.INetworkManagementService;
Robert Greenwalt7b816022014-04-18 15:25:25 -070039import android.os.Messenger;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090040import android.os.SystemClock;
41import android.util.Log;
Robert Greenwalt7b816022014-04-18 15:25:25 -070042import android.util.SparseArray;
43
44import com.android.internal.util.AsyncChannel;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090045import com.android.internal.util.WakeupMessage;
Paul Jensencf4c2c62015-07-01 14:16:32 -040046import com.android.server.ConnectivityService;
Robert Greenwalt7b816022014-04-18 15:25:25 -070047
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090048import java.io.PrintWriter;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090049import java.util.Objects;
50import java.util.SortedSet;
51import java.util.TreeSet;
Robert Greenwalt7b816022014-04-18 15:25:25 -070052
53/**
54 * A bag class used by ConnectivityService for holding a collection of most recent
55 * information published by a particular NetworkAgent as well as the
56 * AsyncChannel/messenger for reaching that NetworkAgent and lists of NetworkRequests
Paul Jensen85cf78e2015-06-25 13:25:07 -040057 * interested in using it. Default sort order is descending by score.
Robert Greenwalt7b816022014-04-18 15:25:25 -070058 */
Paul Jensene0988542015-06-25 15:30:08 -040059// States of a network:
60// --------------------
61// 1. registered, uncreated, disconnected, unvalidated
62// This state is entered when a NetworkFactory registers a NetworkAgent in any state except
63// the CONNECTED state.
Robin Lee585e2482016-05-01 23:00:00 +010064// 2. registered, uncreated, connecting, unvalidated
65// This state is entered when a registered NetworkAgent for a VPN network transitions to the
66// CONNECTING state (TODO: go through this state for every network, not just VPNs).
67// ConnectivityService will tell netd to create the network early in order to add extra UID
68// routing rules referencing the netID. These rules need to be in place before the network is
69// connected to avoid racing against client apps trying to connect to a half-setup network.
70// 3. registered, uncreated, connected, unvalidated
71// This state is entered when a registered NetworkAgent transitions to the CONNECTED state.
72// ConnectivityService will tell netd to create the network if it was not already created, and
73// immediately transition to state #4.
74// 4. registered, created, connected, unvalidated
Paul Jensencf4c2c62015-07-01 14:16:32 -040075// If this network can satisfy the default NetworkRequest, then NetworkMonitor will
Paul Jensene0988542015-06-25 15:30:08 -040076// probe for Internet connectivity.
77// If this network cannot satisfy the default NetworkRequest, it will immediately be
Robin Lee585e2482016-05-01 23:00:00 +010078// transitioned to state #5.
Paul Jensene0988542015-06-25 15:30:08 -040079// A network may remain in this state if NetworkMonitor fails to find Internet connectivity,
80// for example:
81// a. a captive portal is present, or
82// b. a WiFi router whose Internet backhaul is down, or
83// c. a wireless connection stops transfering packets temporarily (e.g. device is in elevator
84// or tunnel) but does not disconnect from the AP/cell tower, or
85// d. a stand-alone device offering a WiFi AP without an uplink for configuration purposes.
Robin Lee585e2482016-05-01 23:00:00 +010086// 5. registered, created, connected, validated
Paul Jensene0988542015-06-25 15:30:08 -040087//
88// The device's default network connection:
89// ----------------------------------------
Robin Lee585e2482016-05-01 23:00:00 +010090// 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 -040091// satisfy the default NetworkRequest.
Robin Lee585e2482016-05-01 23:00:00 +010092// A network, that satisfies the default NetworkRequest, in state #5 should always be chosen
93// in favor of a network, that satisfies the default NetworkRequest, in state #4.
Paul Jensene0988542015-06-25 15:30:08 -040094// When deciding between two networks, that both satisfy the default NetworkRequest, to select
95// for the default network connection, the one with the higher score should be chosen.
96//
97// When a network disconnects:
98// ---------------------------
99// If a network's transport disappears, for example:
100// a. WiFi turned off, or
101// b. cellular data turned off, or
102// c. airplane mode is turned on, or
103// d. a wireless connection disconnects from AP/cell tower entirely (e.g. device is out of range
104// of AP for an extended period of time, or switches to another AP without roaming)
Robin Lee585e2482016-05-01 23:00:00 +0100105// then that network can transition from any state (#1-#5) to unregistered. This happens by
Paul Jensene0988542015-06-25 15:30:08 -0400106// the transport disconnecting their NetworkAgent's AsyncChannel with ConnectivityManager.
107// ConnectivityService also tells netd to destroy the network.
108//
109// When ConnectivityService disconnects a network:
110// -----------------------------------------------
111// If a network has no chance of satisfying any requests (even if it were to become validated
Robin Lee585e2482016-05-01 23:00:00 +0100112// and enter state #5), ConnectivityService will disconnect the NetworkAgent's AsyncChannel.
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900113//
114// If the network was satisfying a foreground NetworkRequest (i.e. had been the highest scoring that
115// satisfied the NetworkRequest's constraints), but is no longer the highest scoring network for any
116// foreground NetworkRequest, then there will be a 30s pause to allow network communication to be
117// wrapped up rather than abruptly terminated. During this pause the network is said to be
118// "lingering". During this pause if the network begins satisfying a foreground NetworkRequest,
119// ConnectivityService will cancel the future disconnection of the NetworkAgent's AsyncChannel, and
120// the network is no longer considered "lingering". After the linger timer expires, if the network
121// is satisfying one or more background NetworkRequests it is kept up in the background. If it is
122// not, ConnectivityService disconnects the NetworkAgent's AsyncChannel.
Paul Jensen85cf78e2015-06-25 13:25:07 -0400123public class NetworkAgentInfo implements Comparable<NetworkAgentInfo> {
Hugo Benichic8e9e122016-09-14 23:23:08 +0000124
Yintang Gu1505d0a2019-06-18 14:24:32 +0800125 @NonNull public NetworkInfo networkInfo;
Paul Jensen31a94f42015-02-13 14:18:39 -0500126 // This Network object should always be used if possible, so as to encourage reuse of the
127 // enclosed socket factory and connection pool. Avoid creating other Network objects.
128 // This Network object is always valid.
129 public final Network network;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700130 public LinkProperties linkProperties;
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +0900131 // This should only be modified by ConnectivityService, via setNetworkCapabilities().
132 // TODO: make this private with a getter.
Robert Greenwalt7b816022014-04-18 15:25:25 -0700133 public NetworkCapabilities networkCapabilities;
Lorenzo Colittid9696562020-01-12 22:28:37 +0900134 public final NetworkAgentConfig networkAgentConfig;
Robin Lee585e2482016-05-01 23:00:00 +0100135 // Indicates if netd has been told to create this Network. From this point on the appropriate
136 // routing rules are setup and routes are added so packets can begin flowing over the Network.
Lorenzo Colittid49159f2015-05-14 23:15:10 +0900137 // This is a sticky bit; once set it is never cleared.
Paul Jenseneec75412014-08-04 12:21:19 -0400138 public boolean created;
Robin Lee585e2482016-05-01 23:00:00 +0100139 // Set to true after the first time this network is marked as CONNECTED. Once set, the network
140 // shows up in API calls, is able to satisfy NetworkRequests and can become the default network.
141 // This is a sticky bit; once set it is never cleared.
142 public boolean everConnected;
Paul Jensen71b645f2014-10-13 14:13:07 -0400143 // Set to true if this Network successfully passed validation or if it did not satisfy the
144 // default NetworkRequest in which case validation will not be attempted.
Lorenzo Colittid49159f2015-05-14 23:15:10 +0900145 // This is a sticky bit; once set it is never cleared even if future validation attempts fail.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +0900146 public boolean everValidated;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400147
Lorenzo Colitti7b42f392014-12-17 11:26:49 +0900148 // The result of the last validation attempt on this network (true if validated, false if not).
Lorenzo Colitti7b42f392014-12-17 11:26:49 +0900149 public boolean lastValidated;
150
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900151 // If true, becoming unvalidated will lower the network's score. This is only meaningful if the
152 // system is configured not to do this for certain networks, e.g., if the
153 // config_networkAvoidBadWifi option is set to 0 and the user has not overridden that via
154 // Settings.Global.NETWORK_AVOID_BAD_WIFI.
155 public boolean avoidUnvalidated;
156
Lorenzo Colittid49159f2015-05-14 23:15:10 +0900157 // Whether a captive portal was ever detected on this network.
158 // This is a sticky bit; once set it is never cleared.
Paul Jensen3d194ea2015-06-16 14:27:36 -0400159 public boolean everCaptivePortalDetected;
160
161 // Whether a captive portal was found during the last network validation attempt.
162 public boolean lastCaptivePortalDetected;
Lorenzo Colittid49159f2015-05-14 23:15:10 +0900163
lucasline252a742019-03-12 13:08:03 +0800164 // Set to true when partial connectivity was detected.
165 public boolean partialConnectivity;
166
Remi NGUYEN VAN91aa5bc2019-12-12 12:57:11 +0900167 // Captive portal info of the network, if any.
168 // Obtained by ConnectivityService and merged into NetworkAgent-provided information.
169 public CaptivePortalData captivePortalData;
170
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900171 // Networks are lingered when they become unneeded as a result of their NetworkRequests being
172 // satisfied by a higher-scoring network. so as to allow communication to wrap up before the
173 // network is taken down. This usually only happens to the default network. Lingering ends with
174 // either the linger timeout expiring and the network being taken down, or the network
175 // satisfying a request again.
176 public static class LingerTimer implements Comparable<LingerTimer> {
177 public final NetworkRequest request;
178 public final long expiryMs;
179
180 public LingerTimer(NetworkRequest request, long expiryMs) {
181 this.request = request;
182 this.expiryMs = expiryMs;
183 }
184 public boolean equals(Object o) {
185 if (!(o instanceof LingerTimer)) return false;
186 LingerTimer other = (LingerTimer) o;
187 return (request.requestId == other.request.requestId) && (expiryMs == other.expiryMs);
188 }
189 public int hashCode() {
190 return Objects.hash(request.requestId, expiryMs);
191 }
192 public int compareTo(LingerTimer other) {
193 return (expiryMs != other.expiryMs) ?
194 Long.compare(expiryMs, other.expiryMs) :
195 Integer.compare(request.requestId, other.request.requestId);
196 }
197 public String toString() {
198 return String.format("%s, expires %dms", request.toString(),
199 expiryMs - SystemClock.elapsedRealtime());
200 }
201 }
202
203 /**
204 * Inform ConnectivityService that the network LINGER period has
205 * expired.
206 * obj = this NetworkAgentInfo
207 */
208 public static final int EVENT_NETWORK_LINGER_COMPLETE = 1001;
209
210 // All linger timers for this network, sorted by expiry time. A linger timer is added whenever
211 // a request is moved to a network with a better score, regardless of whether the network is or
212 // was lingering or not.
213 // TODO: determine if we can replace this with a smaller or unsorted data structure. (e.g.,
214 // SparseLongArray) combined with the timestamp of when the last timer is scheduled to fire.
215 private final SortedSet<LingerTimer> mLingerTimers = new TreeSet<>();
216
217 // For fast lookups. Indexes into mLingerTimers by request ID.
218 private final SparseArray<LingerTimer> mLingerTimerForRequest = new SparseArray<>();
219
220 // Linger expiry timer. Armed whenever mLingerTimers is non-empty, regardless of whether the
221 // network is lingering or not. Always set to the expiry of the LingerTimer that expires last.
222 // When the timer fires, all linger state is cleared, and if the network has no requests, it is
223 // torn down.
224 private WakeupMessage mLingerMessage;
225
226 // Linger expiry. Holds the expiry time of the linger timer, or 0 if the timer is not armed.
227 private long mLingerExpiryMs;
228
229 // Whether the network is lingering or not. Must be maintained separately from the above because
230 // it depends on the state of other networks and requests, which only ConnectivityService knows.
231 // (Example: we don't linger a network if it would become the best for a NetworkRequest if it
232 // validated).
233 private boolean mLingering;
Paul Jensen85cf78e2015-06-25 13:25:07 -0400234
Automerger Merge Worker3d40f5782020-03-08 06:07:47 +0000235 // This represents the quality of the network with no clear scale.
236 private int mScore;
Robert Greenwalte73cc462014-09-07 16:50:01 -0700237
Robert Greenwalt7b816022014-04-18 15:25:25 -0700238 // The list of NetworkRequests being satisfied by this Network.
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900239 private final SparseArray<NetworkRequest> mNetworkRequests = new SparseArray<>();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900240
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900241 // How many of the satisfied requests are actual requests and not listens.
242 private int mNumRequestNetworkRequests = 0;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700243
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900244 // How many of the satisfied requests are of type BACKGROUND_REQUEST.
245 private int mNumBackgroundNetworkRequests = 0;
246
Cody Kesting95a98c22020-03-30 12:03:21 -0700247 // The last ConnectivityReport made available for this network. This value is only null before a
248 // report is generated. Once non-null, it will never be null again.
249 @Nullable private ConnectivityReport mConnectivityReport;
Cody Kesting560eb262020-02-12 14:50:58 -0800250
Robert Greenwalt7b816022014-04-18 15:25:25 -0700251 public final Messenger messenger;
252 public final AsyncChannel asyncChannel;
253
Chalard Jean05ab6812018-05-02 21:14:54 +0900254 public final int factorySerialNumber;
255
Lorenzo Colitti95439462014-10-09 13:44:48 +0900256 // Used by ConnectivityService to keep track of 464xlat.
Lorenzo Colittidf595632019-01-08 14:43:37 +0900257 public final Nat464Xlat clatd;
Lorenzo Colitti95439462014-10-09 13:44:48 +0900258
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900259 // Set after asynchronous creation of the NetworkMonitor.
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900260 private volatile NetworkMonitorManager mNetworkMonitor;
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900261
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900262 private static final String TAG = ConnectivityService.class.getSimpleName();
263 private static final boolean VDBG = false;
Hugo Benichi50d46a42017-08-31 14:29:51 +0000264 private final ConnectivityService mConnService;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900265 private final Context mContext;
Hugo Benichi50d46a42017-08-31 14:29:51 +0000266 private final Handler mHandler;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900267
Paul Jensen31a94f42015-02-13 14:18:39 -0500268 public NetworkAgentInfo(Messenger messenger, AsyncChannel ac, Network net, NetworkInfo info,
Automerger Merge Worker3d40f5782020-03-08 06:07:47 +0000269 LinkProperties lp, NetworkCapabilities nc, int score, Context context,
Lorenzo Colittid9696562020-01-12 22:28:37 +0900270 Handler handler, NetworkAgentConfig config, ConnectivityService connService, INetd netd,
Luke Huang65914772019-03-16 00:31:46 +0800271 IDnsResolver dnsResolver, INetworkManagementService nms, int factorySerialNumber) {
Robert Greenwalt7b816022014-04-18 15:25:25 -0700272 this.messenger = messenger;
273 asyncChannel = ac;
Paul Jensen31a94f42015-02-13 14:18:39 -0500274 network = net;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700275 networkInfo = info;
276 linkProperties = lp;
277 networkCapabilities = nc;
Automerger Merge Worker3d40f5782020-03-08 06:07:47 +0000278 mScore = score;
Luke Huang65914772019-03-16 00:31:46 +0800279 clatd = new Nat464Xlat(this, netd, dnsResolver, nms);
Hugo Benichi50d46a42017-08-31 14:29:51 +0000280 mConnService = connService;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900281 mContext = context;
Hugo Benichi50d46a42017-08-31 14:29:51 +0000282 mHandler = handler;
Lorenzo Colittid9696562020-01-12 22:28:37 +0900283 networkAgentConfig = config;
Chalard Jean05ab6812018-05-02 21:14:54 +0900284 this.factorySerialNumber = factorySerialNumber;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700285 }
286
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900287 /**
288 * Inform NetworkAgentInfo that a new NetworkMonitor was created.
289 */
290 public void onNetworkMonitorCreated(INetworkMonitor networkMonitor) {
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900291 mNetworkMonitor = new NetworkMonitorManager(networkMonitor);
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900292 }
293
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +0900294 /**
295 * Set the NetworkCapabilities on this NetworkAgentInfo. Also attempts to notify NetworkMonitor
296 * of the new capabilities, if NetworkMonitor has been created.
297 *
298 * <p>If {@link NetworkMonitor#notifyNetworkCapabilitiesChanged(NetworkCapabilities)} fails,
299 * the exception is logged but not reported to callers.
Chalard Jean7ec1ff62019-11-22 22:39:56 +0900300 *
301 * @return the old capabilities of this network.
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +0900302 */
Chalard Jean7ec1ff62019-11-22 22:39:56 +0900303 public synchronized NetworkCapabilities getAndSetNetworkCapabilities(
304 @NonNull final NetworkCapabilities nc) {
305 final NetworkCapabilities oldNc = networkCapabilities;
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +0900306 networkCapabilities = nc;
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900307 final NetworkMonitorManager nm = mNetworkMonitor;
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +0900308 if (nm != null) {
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900309 nm.notifyNetworkCapabilitiesChanged(nc);
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +0900310 }
Chalard Jean7ec1ff62019-11-22 22:39:56 +0900311 return oldNc;
Remi NGUYEN VAN3962f672019-03-27 15:42:53 +0900312 }
313
Hugo Benichief502882017-09-01 01:23:32 +0000314 public ConnectivityService connService() {
315 return mConnService;
316 }
317
Lorenzo Colittid9696562020-01-12 22:28:37 +0900318 public NetworkAgentConfig netAgentConfig() {
319 return networkAgentConfig;
soma, kawata88b8f632018-10-23 21:10:02 +0900320 }
321
Hugo Benichief502882017-09-01 01:23:32 +0000322 public Handler handler() {
323 return mHandler;
324 }
325
Hugo Benichic894b122017-07-31 12:58:20 +0900326 public Network network() {
327 return network;
328 }
329
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900330 /**
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900331 * Get the NetworkMonitorManager in this NetworkAgentInfo.
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900332 *
333 * <p>This will be null before {@link #onNetworkMonitorCreated(INetworkMonitor)} is called.
334 */
Lorenzo Colittiac955b32019-05-31 15:41:29 +0900335 public NetworkMonitorManager networkMonitor() {
Remi NGUYEN VANe67b0c32018-12-27 16:43:56 +0900336 return mNetworkMonitor;
337 }
338
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900339 // Functions for manipulating the requests satisfied by this network.
340 //
341 // These functions must only called on ConnectivityService's main thread.
342
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900343 private static final boolean ADD = true;
344 private static final boolean REMOVE = false;
345
346 private void updateRequestCounts(boolean add, NetworkRequest request) {
347 int delta = add ? +1 : -1;
348 switch (request.type) {
349 case REQUEST:
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900350 mNumRequestNetworkRequests += delta;
351 break;
352
353 case BACKGROUND_REQUEST:
354 mNumRequestNetworkRequests += delta;
355 mNumBackgroundNetworkRequests += delta;
356 break;
357
Chalard Jean715d39b2018-02-16 17:59:29 +0900358 case TRACK_DEFAULT:
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900359 case LISTEN:
360 break;
361
362 case NONE:
363 default:
364 Log.wtf(TAG, "Unhandled request type " + request.type);
365 break;
366 }
367 }
368
Paul Jensen3d911462015-06-12 06:40:24 -0400369 /**
370 * Add {@code networkRequest} to this network as it's satisfied by this network.
Paul Jensen3d911462015-06-12 06:40:24 -0400371 * @return true if {@code networkRequest} was added or false if {@code networkRequest} was
372 * already present.
373 */
374 public boolean addRequest(NetworkRequest networkRequest) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900375 NetworkRequest existing = mNetworkRequests.get(networkRequest.requestId);
376 if (existing == networkRequest) return false;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900377 if (existing != null) {
378 // Should only happen if the requestId wraps. If that happens lots of other things will
379 // be broken as well.
380 Log.wtf(TAG, String.format("Duplicate requestId for %s and %s on %s",
Chalard Jeanbf1170c2019-12-10 21:07:02 +0900381 networkRequest, existing, toShortString()));
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900382 updateRequestCounts(REMOVE, existing);
383 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900384 mNetworkRequests.put(networkRequest.requestId, networkRequest);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900385 updateRequestCounts(ADD, networkRequest);
Paul Jensen3d911462015-06-12 06:40:24 -0400386 return true;
Robert Greenwalt71bf33a2014-05-15 18:07:26 -0700387 }
388
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900389 /**
390 * Remove the specified request from this network.
391 */
392 public void removeRequest(int requestId) {
393 NetworkRequest existing = mNetworkRequests.get(requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900394 if (existing == null) return;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900395 updateRequestCounts(REMOVE, existing);
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900396 mNetworkRequests.remove(requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900397 if (existing.isRequest()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900398 unlingerRequest(existing);
399 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900400 }
401
402 /**
403 * Returns whether this network is currently satisfying the request with the specified ID.
404 */
405 public boolean isSatisfyingRequest(int id) {
406 return mNetworkRequests.get(id) != null;
407 }
408
409 /**
410 * Returns the request at the specified position in the list of requests satisfied by this
411 * network.
412 */
413 public NetworkRequest requestAt(int index) {
414 return mNetworkRequests.valueAt(index);
415 }
416
417 /**
418 * Returns the number of requests currently satisfied by this network for which
419 * {@link android.net.NetworkRequest#isRequest} returns {@code true}.
420 */
421 public int numRequestNetworkRequests() {
422 return mNumRequestNetworkRequests;
423 }
424
425 /**
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900426 * Returns the number of requests currently satisfied by this network of type
427 * {@link android.net.NetworkRequest.Type.BACKGROUND_REQUEST}.
428 */
429 public int numBackgroundNetworkRequests() {
430 return mNumBackgroundNetworkRequests;
431 }
432
433 /**
434 * Returns the number of foreground requests currently satisfied by this network.
435 */
436 public int numForegroundNetworkRequests() {
437 return mNumRequestNetworkRequests - mNumBackgroundNetworkRequests;
438 }
439
440 /**
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900441 * Returns the number of requests of any type currently satisfied by this network.
442 */
443 public int numNetworkRequests() {
444 return mNetworkRequests.size();
445 }
446
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900447 /**
448 * Returns whether the network is a background network. A network is a background network if it
Chalard Jeanb72b62d2018-02-16 16:08:35 +0900449 * does not have the NET_CAPABILITY_FOREGROUND capability, which implies it is satisfying no
450 * foreground request, is not lingering (i.e. kept for a while after being outscored), and is
451 * not a speculative network (i.e. kept pending validation when validation would have it
452 * outscore another foreground network). That implies it is being kept up by some background
453 * request (otherwise it would be torn down), maybe the mobile always-on request.
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900454 */
455 public boolean isBackgroundNetwork() {
Chalard Jeanb72b62d2018-02-16 16:08:35 +0900456 return !isVPN() && numForegroundNetworkRequests() == 0 && mNumBackgroundNetworkRequests > 0
457 && !isLingering();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900458 }
459
Paul Jensen0cc17322014-11-25 15:26:53 -0500460 // Does this network satisfy request?
461 public boolean satisfies(NetworkRequest request) {
462 return created &&
463 request.networkCapabilities.satisfiedByNetworkCapabilities(networkCapabilities);
464 }
465
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900466 public boolean satisfiesImmutableCapabilitiesOf(NetworkRequest request) {
467 return created &&
468 request.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
469 networkCapabilities);
470 }
471
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400472 public boolean isVPN() {
473 return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN);
474 }
475
Chalard Jeanfb830762020-02-20 07:32:12 +0000476 private int getCurrentScore(boolean pretendValidated) {
477 // TODO: We may want to refactor this into a NetworkScore class that takes a base score from
478 // the NetworkAgent and signals from the NetworkAgent and uses those signals to modify the
479 // score. The NetworkScore class would provide a nice place to centralize score constants
480 // so they are not scattered about the transports.
481
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900482 // If this network is explicitly selected and the user has decided to use it even if it's
Chalard Jeanfb830762020-02-20 07:32:12 +0000483 // unvalidated, give it the maximum score. Also give it the maximum score if it's explicitly
484 // selected and we're trying to see what its score could be. This ensures that we don't tear
485 // down an explicitly selected network before the user gets a chance to prefer it when
486 // a higher-scoring network (e.g., Ethernet) is available.
487 if (networkAgentConfig.explicitlySelected
488 && (networkAgentConfig.acceptUnvalidated || pretendValidated)) {
Lorenzo Colitti80986d92019-03-22 00:28:28 +0900489 return ConnectivityConstants.EXPLICITLY_SELECTED_NETWORK_SCORE;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900490 }
Paul Jensen2161a8e2014-09-11 11:00:39 -0400491
Automerger Merge Worker3d40f5782020-03-08 06:07:47 +0000492 int score = mScore;
Chalard Jeanfb830762020-02-20 07:32:12 +0000493 if (!lastValidated && !pretendValidated && !ignoreWifiUnvalidationPenalty() && !isVPN()) {
Chalard Jean918a68b2018-01-19 17:00:47 +0900494 score -= ConnectivityConstants.UNVALIDATED_SCORE_PENALTY;
Paul Jensene0988542015-06-25 15:30:08 -0400495 }
Paul Jensen2161a8e2014-09-11 11:00:39 -0400496 if (score < 0) score = 0;
Paul Jensen2161a8e2014-09-11 11:00:39 -0400497 return score;
498 }
499
Hugo Benichic8e9e122016-09-14 23:23:08 +0000500 // Return true on devices configured to ignore score penalty for wifi networks
501 // that become unvalidated (b/31075769).
502 private boolean ignoreWifiUnvalidationPenalty() {
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900503 boolean isWifi = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
504 networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
Hugo Benichi50d46a42017-08-31 14:29:51 +0000505 boolean avoidBadWifi = mConnService.avoidBadWifi() || avoidUnvalidated;
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900506 return isWifi && !avoidBadWifi && everValidated;
Hugo Benichic8e9e122016-09-14 23:23:08 +0000507 }
508
Chalard Jeanfb830762020-02-20 07:32:12 +0000509 // Get the current score for this Network. This may be modified from what the
510 // NetworkAgent sent, as it has modifiers applied to it.
511 public int getCurrentScore() {
512 return getCurrentScore(false);
513 }
514
515 // Get the current score for this Network as if it was validated. This may be modified from
516 // what the NetworkAgent sent, as it has modifiers applied to it.
517 public int getCurrentScoreAsValidated() {
518 return getCurrentScore(true);
519 }
520
Automerger Merge Worker3d40f5782020-03-08 06:07:47 +0000521 public void setScore(final int score) {
522 mScore = score;
Paul Jensen2161a8e2014-09-11 11:00:39 -0400523 }
524
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600525 public NetworkState getNetworkState() {
526 synchronized (this) {
Chalard Jean804b8fb2018-01-30 22:41:41 +0900527 // Network objects are outwardly immutable so there is no point in duplicating.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600528 // Duplicating also precludes sharing socket factories and connection pools.
Lorenzo Colittid9696562020-01-12 22:28:37 +0900529 final String subscriberId = (networkAgentConfig != null)
530 ? networkAgentConfig.subscriberId : null;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600531 return new NetworkState(new NetworkInfo(networkInfo),
532 new LinkProperties(linkProperties),
533 new NetworkCapabilities(networkCapabilities), network, subscriberId, null);
534 }
535 }
536
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900537 /**
538 * Sets the specified request to linger on this network for the specified time. Called by
539 * ConnectivityService when the request is moved to another network with a higher score.
540 */
541 public void lingerRequest(NetworkRequest request, long now, long duration) {
542 if (mLingerTimerForRequest.get(request.requestId) != null) {
543 // Cannot happen. Once a request is lingering on a particular network, we cannot
544 // re-linger it unless that network becomes the best for that request again, in which
545 // case we should have unlingered it.
Chalard Jeanbf1170c2019-12-10 21:07:02 +0900546 Log.wtf(TAG, toShortString() + ": request " + request.requestId + " already lingered");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900547 }
548 final long expiryMs = now + duration;
549 LingerTimer timer = new LingerTimer(request, expiryMs);
Chalard Jeanbf1170c2019-12-10 21:07:02 +0900550 if (VDBG) Log.d(TAG, "Adding LingerTimer " + timer + " to " + toShortString());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900551 mLingerTimers.add(timer);
552 mLingerTimerForRequest.put(request.requestId, timer);
553 }
554
555 /**
556 * Cancel lingering. Called by ConnectivityService when a request is added to this network.
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900557 * Returns true if the given request was lingering on this network, false otherwise.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900558 */
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900559 public boolean unlingerRequest(NetworkRequest request) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900560 LingerTimer timer = mLingerTimerForRequest.get(request.requestId);
561 if (timer != null) {
Chalard Jeanbf1170c2019-12-10 21:07:02 +0900562 if (VDBG) Log.d(TAG, "Removing LingerTimer " + timer + " from " + toShortString());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900563 mLingerTimers.remove(timer);
564 mLingerTimerForRequest.remove(request.requestId);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900565 return true;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900566 }
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900567 return false;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900568 }
569
570 public long getLingerExpiry() {
571 return mLingerExpiryMs;
572 }
573
574 public void updateLingerTimer() {
575 long newExpiry = mLingerTimers.isEmpty() ? 0 : mLingerTimers.last().expiryMs;
576 if (newExpiry == mLingerExpiryMs) return;
577
578 // Even if we're going to reschedule the timer, cancel it first. This is because the
579 // semantics of WakeupMessage guarantee that if cancel is called then the alarm will
580 // never call its callback (handleLingerComplete), even if it has already fired.
581 // WakeupMessage makes no such guarantees about rescheduling a message, so if mLingerMessage
Chalard Jeana3984a12019-11-19 20:01:10 +0900582 // has already been dispatched, rescheduling to some time in the future won't stop it
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900583 // from calling its callback immediately.
584 if (mLingerMessage != null) {
585 mLingerMessage.cancel();
586 mLingerMessage = null;
587 }
588
589 if (newExpiry > 0) {
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900590 mLingerMessage = new WakeupMessage(
Hugo Benichi50d46a42017-08-31 14:29:51 +0000591 mContext, mHandler,
Remi NGUYEN VAN95dc87e2019-06-13 16:12:02 +0900592 "NETWORK_LINGER_COMPLETE." + network.netId /* cmdName */,
593 EVENT_NETWORK_LINGER_COMPLETE /* cmd */,
594 0 /* arg1 (unused) */, 0 /* arg2 (unused) */,
595 this /* obj (NetworkAgentInfo) */);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900596 mLingerMessage.schedule(newExpiry);
597 }
598
599 mLingerExpiryMs = newExpiry;
600 }
601
602 public void linger() {
603 mLingering = true;
604 }
605
606 public void unlinger() {
607 mLingering = false;
608 }
609
610 public boolean isLingering() {
611 return mLingering;
612 }
613
614 public void clearLingerState() {
615 if (mLingerMessage != null) {
616 mLingerMessage.cancel();
617 mLingerMessage = null;
618 }
619 mLingerTimers.clear();
620 mLingerTimerForRequest.clear();
621 updateLingerTimer(); // Sets mLingerExpiryMs, cancels and nulls out mLingerMessage.
622 mLingering = false;
623 }
624
625 public void dumpLingerTimers(PrintWriter pw) {
626 for (LingerTimer timer : mLingerTimers) { pw.println(timer); }
627 }
628
Cody Kesting560eb262020-02-12 14:50:58 -0800629 /**
630 * Sets the most recent ConnectivityReport for this network.
631 *
632 * <p>This should only be called from the ConnectivityService thread.
633 *
634 * @hide
635 */
636 public void setConnectivityReport(@NonNull ConnectivityReport connectivityReport) {
637 mConnectivityReport = connectivityReport;
638 }
639
640 /**
641 * Returns the most recent ConnectivityReport for this network, or null if none have been
642 * reported yet.
643 *
644 * <p>This should only be called from the ConnectivityService thread.
645 *
646 * @hide
647 */
648 @Nullable
649 public ConnectivityReport getConnectivityReport() {
650 return mConnectivityReport;
651 }
652
lucasline252a742019-03-12 13:08:03 +0800653 // TODO: Print shorter members first and only print the boolean variable which value is true
654 // to improve readability.
Robert Greenwalt7b816022014-04-18 15:25:25 -0700655 public String toString() {
lucaslind2e045e02019-01-24 15:55:30 +0800656 return "NetworkAgentInfo{ ni{" + networkInfo + "} "
657 + "network{" + network + "} nethandle{" + network.getNetworkHandle() + "} "
658 + "lp{" + linkProperties + "} "
659 + "nc{" + networkCapabilities + "} Score{" + getCurrentScore() + "} "
660 + "everValidated{" + everValidated + "} lastValidated{" + lastValidated + "} "
661 + "created{" + created + "} lingering{" + isLingering() + "} "
Lorenzo Colittid9696562020-01-12 22:28:37 +0900662 + "explicitlySelected{" + networkAgentConfig.explicitlySelected + "} "
663 + "acceptUnvalidated{" + networkAgentConfig.acceptUnvalidated + "} "
lucaslind2e045e02019-01-24 15:55:30 +0800664 + "everCaptivePortalDetected{" + everCaptivePortalDetected + "} "
665 + "lastCaptivePortalDetected{" + lastCaptivePortalDetected + "} "
lucasline252a742019-03-12 13:08:03 +0800666 + "partialConnectivity{" + partialConnectivity + "} "
Lorenzo Colittid9696562020-01-12 22:28:37 +0900667 + "acceptPartialConnectivity{" + networkAgentConfig.acceptPartialConnectivity + "} "
lucaslind2e045e02019-01-24 15:55:30 +0800668 + "clat{" + clatd + "} "
669 + "}";
Robert Greenwalt7b816022014-04-18 15:25:25 -0700670 }
671
Chalard Jeanbf1170c2019-12-10 21:07:02 +0900672 /**
673 * Show a short string representing a Network.
674 *
675 * This is often not enough for debugging purposes for anything complex, but the full form
676 * is very long and hard to read, so this is useful when there isn't a lot of ambiguity.
677 * This represents the network with something like "[100 WIFI|VPN]" or "[108 MOBILE]".
678 */
679 public String toShortString() {
680 return "[" + network.netId + " "
681 + transportNamesOf(networkCapabilities.getTransportTypes()) + "]";
Robert Greenwalt7b816022014-04-18 15:25:25 -0700682 }
Paul Jensen85cf78e2015-06-25 13:25:07 -0400683
684 // Enables sorting in descending order of score.
685 @Override
686 public int compareTo(NetworkAgentInfo other) {
687 return other.getCurrentScore() - getCurrentScore();
688 }
Chalard Jeanbf1170c2019-12-10 21:07:02 +0900689
690 /**
691 * Null-guarding version of NetworkAgentInfo#toShortString()
692 */
693 @NonNull
694 public static String toShortString(@Nullable final NetworkAgentInfo nai) {
695 return null != nai ? nai.toShortString() : "[null]";
696 }
Robert Greenwalt7b816022014-04-18 15:25:25 -0700697}