blob: a4d7242086bf82c772cfb9570358d81abeedba83 [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
Paul Jensene0988542015-06-25 15:30:08 -040019import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
20
Paul Jensenca8f16a2014-05-09 12:47:55 -040021import android.content.Context;
Robert Greenwalt7b816022014-04-18 15:25:25 -070022import android.net.LinkProperties;
23import android.net.Network;
24import android.net.NetworkCapabilities;
25import android.net.NetworkInfo;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070026import android.net.NetworkMisc;
Robert Greenwalt7b816022014-04-18 15:25:25 -070027import android.net.NetworkRequest;
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -060028import android.net.NetworkState;
Paul Jensenca8f16a2014-05-09 12:47:55 -040029import android.os.Handler;
Hugo Benichief502882017-09-01 01:23:32 +000030import android.os.INetworkManagementService;
Robert Greenwalt7b816022014-04-18 15:25:25 -070031import android.os.Messenger;
Hugo Benichief502882017-09-01 01:23:32 +000032import android.os.RemoteException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090033import android.os.SystemClock;
34import android.util.Log;
Robert Greenwalt7b816022014-04-18 15:25:25 -070035import android.util.SparseArray;
36
37import com.android.internal.util.AsyncChannel;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090038import com.android.internal.util.WakeupMessage;
Paul Jensencf4c2c62015-07-01 14:16:32 -040039import com.android.server.ConnectivityService;
Paul Jensenca8f16a2014-05-09 12:47:55 -040040import com.android.server.connectivity.NetworkMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -070041
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090042import java.io.PrintWriter;
Robert Greenwalt7b816022014-04-18 15:25:25 -070043import java.util.ArrayList;
Paul Jensen85cf78e2015-06-25 13:25:07 -040044import java.util.Comparator;
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
Robert Greenwalt7b816022014-04-18 15:25:25 -0700121 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;
Paul Jensen1c7ba022015-06-16 14:27:36 -0400127 // This should only be modified via ConnectivityService.updateCapabilities().
Robert Greenwalt7b816022014-04-18 15:25:25 -0700128 public NetworkCapabilities networkCapabilities;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400129 public final NetworkMonitor networkMonitor;
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
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900160 // Networks are lingered when they become unneeded as a result of their NetworkRequests being
161 // satisfied by a higher-scoring network. so as to allow communication to wrap up before the
162 // network is taken down. This usually only happens to the default network. Lingering ends with
163 // either the linger timeout expiring and the network being taken down, or the network
164 // satisfying a request again.
165 public static class LingerTimer implements Comparable<LingerTimer> {
166 public final NetworkRequest request;
167 public final long expiryMs;
168
169 public LingerTimer(NetworkRequest request, long expiryMs) {
170 this.request = request;
171 this.expiryMs = expiryMs;
172 }
173 public boolean equals(Object o) {
174 if (!(o instanceof LingerTimer)) return false;
175 LingerTimer other = (LingerTimer) o;
176 return (request.requestId == other.request.requestId) && (expiryMs == other.expiryMs);
177 }
178 public int hashCode() {
179 return Objects.hash(request.requestId, expiryMs);
180 }
181 public int compareTo(LingerTimer other) {
182 return (expiryMs != other.expiryMs) ?
183 Long.compare(expiryMs, other.expiryMs) :
184 Integer.compare(request.requestId, other.request.requestId);
185 }
186 public String toString() {
187 return String.format("%s, expires %dms", request.toString(),
188 expiryMs - SystemClock.elapsedRealtime());
189 }
190 }
191
192 /**
193 * Inform ConnectivityService that the network LINGER period has
194 * expired.
195 * obj = this NetworkAgentInfo
196 */
197 public static final int EVENT_NETWORK_LINGER_COMPLETE = 1001;
198
199 // All linger timers for this network, sorted by expiry time. A linger timer is added whenever
200 // a request is moved to a network with a better score, regardless of whether the network is or
201 // was lingering or not.
202 // TODO: determine if we can replace this with a smaller or unsorted data structure. (e.g.,
203 // SparseLongArray) combined with the timestamp of when the last timer is scheduled to fire.
204 private final SortedSet<LingerTimer> mLingerTimers = new TreeSet<>();
205
206 // For fast lookups. Indexes into mLingerTimers by request ID.
207 private final SparseArray<LingerTimer> mLingerTimerForRequest = new SparseArray<>();
208
209 // Linger expiry timer. Armed whenever mLingerTimers is non-empty, regardless of whether the
210 // network is lingering or not. Always set to the expiry of the LingerTimer that expires last.
211 // When the timer fires, all linger state is cleared, and if the network has no requests, it is
212 // torn down.
213 private WakeupMessage mLingerMessage;
214
215 // Linger expiry. Holds the expiry time of the linger timer, or 0 if the timer is not armed.
216 private long mLingerExpiryMs;
217
218 // Whether the network is lingering or not. Must be maintained separately from the above because
219 // it depends on the state of other networks and requests, which only ConnectivityService knows.
220 // (Example: we don't linger a network if it would become the best for a NetworkRequest if it
221 // validated).
222 private boolean mLingering;
Paul Jensen85cf78e2015-06-25 13:25:07 -0400223
Paul Jensen2161a8e2014-09-11 11:00:39 -0400224 // This represents the last score received from the NetworkAgent.
225 private int currentScore;
226 // Penalty applied to scores of Networks that have not been validated.
227 private static final int UNVALIDATED_SCORE_PENALTY = 40;
228
Robert Greenwalte73cc462014-09-07 16:50:01 -0700229 // Score for explicitly connected network.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900230 //
231 // This ensures that a) the explicitly selected network is never trumped by anything else, and
232 // b) the explicitly selected network is never torn down.
233 private static final int MAXIMUM_NETWORK_SCORE = 100;
Robert Greenwalte73cc462014-09-07 16:50:01 -0700234
Robert Greenwalt7b816022014-04-18 15:25:25 -0700235 // The list of NetworkRequests being satisfied by this Network.
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900236 private final SparseArray<NetworkRequest> mNetworkRequests = new SparseArray<>();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900237
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900238 // How many of the satisfied requests are actual requests and not listens.
239 private int mNumRequestNetworkRequests = 0;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700240
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900241 // How many of the satisfied requests are of type BACKGROUND_REQUEST.
242 private int mNumBackgroundNetworkRequests = 0;
243
Robert Greenwalt7b816022014-04-18 15:25:25 -0700244 public final Messenger messenger;
245 public final AsyncChannel asyncChannel;
246
Lorenzo Colitti95439462014-10-09 13:44:48 +0900247 // Used by ConnectivityService to keep track of 464xlat.
248 public Nat464Xlat clatd;
249
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900250 private static final String TAG = ConnectivityService.class.getSimpleName();
251 private static final boolean VDBG = false;
Hugo Benichi50d46a42017-08-31 14:29:51 +0000252 private final ConnectivityService mConnService;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900253 private final Context mContext;
Hugo Benichi50d46a42017-08-31 14:29:51 +0000254 private final Handler mHandler;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900255
Paul Jensen31a94f42015-02-13 14:18:39 -0500256 public NetworkAgentInfo(Messenger messenger, AsyncChannel ac, Network net, NetworkInfo info,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700257 LinkProperties lp, NetworkCapabilities nc, int score, Context context, Handler handler,
Paul Jensencf4c2c62015-07-01 14:16:32 -0400258 NetworkMisc misc, NetworkRequest defaultRequest, ConnectivityService connService) {
Robert Greenwalt7b816022014-04-18 15:25:25 -0700259 this.messenger = messenger;
260 asyncChannel = ac;
Paul Jensen31a94f42015-02-13 14:18:39 -0500261 network = net;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700262 networkInfo = info;
263 linkProperties = lp;
264 networkCapabilities = nc;
265 currentScore = score;
Hugo Benichi50d46a42017-08-31 14:29:51 +0000266 mConnService = connService;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900267 mContext = context;
Hugo Benichi50d46a42017-08-31 14:29:51 +0000268 mHandler = handler;
269 networkMonitor = mConnService.createNetworkMonitor(context, handler, this, defaultRequest);
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -0700270 networkMisc = misc;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700271 }
272
Hugo Benichief502882017-09-01 01:23:32 +0000273 public ConnectivityService connService() {
274 return mConnService;
275 }
276
277 public Handler handler() {
278 return mHandler;
279 }
280
Hugo Benichic894b122017-07-31 12:58:20 +0900281 public Network network() {
282 return network;
283 }
284
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900285 // Functions for manipulating the requests satisfied by this network.
286 //
287 // These functions must only called on ConnectivityService's main thread.
288
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900289 private static final boolean ADD = true;
290 private static final boolean REMOVE = false;
291
292 private void updateRequestCounts(boolean add, NetworkRequest request) {
293 int delta = add ? +1 : -1;
294 switch (request.type) {
295 case REQUEST:
296 case TRACK_DEFAULT:
297 mNumRequestNetworkRequests += delta;
298 break;
299
300 case BACKGROUND_REQUEST:
301 mNumRequestNetworkRequests += delta;
302 mNumBackgroundNetworkRequests += delta;
303 break;
304
305 case LISTEN:
306 break;
307
308 case NONE:
309 default:
310 Log.wtf(TAG, "Unhandled request type " + request.type);
311 break;
312 }
313 }
314
Paul Jensen3d911462015-06-12 06:40:24 -0400315 /**
316 * Add {@code networkRequest} to this network as it's satisfied by this network.
Paul Jensen3d911462015-06-12 06:40:24 -0400317 * @return true if {@code networkRequest} was added or false if {@code networkRequest} was
318 * already present.
319 */
320 public boolean addRequest(NetworkRequest networkRequest) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900321 NetworkRequest existing = mNetworkRequests.get(networkRequest.requestId);
322 if (existing == networkRequest) return false;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900323 if (existing != null) {
324 // Should only happen if the requestId wraps. If that happens lots of other things will
325 // be broken as well.
326 Log.wtf(TAG, String.format("Duplicate requestId for %s and %s on %s",
327 networkRequest, existing, name()));
328 updateRequestCounts(REMOVE, existing);
329 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900330 mNetworkRequests.put(networkRequest.requestId, networkRequest);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900331 updateRequestCounts(ADD, networkRequest);
Paul Jensen3d911462015-06-12 06:40:24 -0400332 return true;
Robert Greenwalt71bf33a2014-05-15 18:07:26 -0700333 }
334
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900335 /**
336 * Remove the specified request from this network.
337 */
338 public void removeRequest(int requestId) {
339 NetworkRequest existing = mNetworkRequests.get(requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900340 if (existing == null) return;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900341 updateRequestCounts(REMOVE, existing);
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900342 mNetworkRequests.remove(requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900343 if (existing.isRequest()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900344 unlingerRequest(existing);
345 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900346 }
347
348 /**
349 * Returns whether this network is currently satisfying the request with the specified ID.
350 */
351 public boolean isSatisfyingRequest(int id) {
352 return mNetworkRequests.get(id) != null;
353 }
354
355 /**
356 * Returns the request at the specified position in the list of requests satisfied by this
357 * network.
358 */
359 public NetworkRequest requestAt(int index) {
360 return mNetworkRequests.valueAt(index);
361 }
362
363 /**
364 * Returns the number of requests currently satisfied by this network for which
365 * {@link android.net.NetworkRequest#isRequest} returns {@code true}.
366 */
367 public int numRequestNetworkRequests() {
368 return mNumRequestNetworkRequests;
369 }
370
371 /**
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900372 * Returns the number of requests currently satisfied by this network of type
373 * {@link android.net.NetworkRequest.Type.BACKGROUND_REQUEST}.
374 */
375 public int numBackgroundNetworkRequests() {
376 return mNumBackgroundNetworkRequests;
377 }
378
379 /**
380 * Returns the number of foreground requests currently satisfied by this network.
381 */
382 public int numForegroundNetworkRequests() {
383 return mNumRequestNetworkRequests - mNumBackgroundNetworkRequests;
384 }
385
386 /**
Lorenzo Colitti767708d2016-07-01 01:37:11 +0900387 * Returns the number of requests of any type currently satisfied by this network.
388 */
389 public int numNetworkRequests() {
390 return mNetworkRequests.size();
391 }
392
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900393 /**
394 * Returns whether the network is a background network. A network is a background network if it
395 * is satisfying no foreground requests and at least one background request. (If it did not have
396 * a background request, it would be a speculative network that is only being kept up because
397 * it might satisfy a request if it validated).
398 */
399 public boolean isBackgroundNetwork() {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +0900400 return !isVPN() && numForegroundNetworkRequests() == 0 && mNumBackgroundNetworkRequests > 0;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900401 }
402
Paul Jensen0cc17322014-11-25 15:26:53 -0500403 // Does this network satisfy request?
404 public boolean satisfies(NetworkRequest request) {
405 return created &&
406 request.networkCapabilities.satisfiedByNetworkCapabilities(networkCapabilities);
407 }
408
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900409 public boolean satisfiesImmutableCapabilitiesOf(NetworkRequest request) {
410 return created &&
411 request.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
412 networkCapabilities);
413 }
414
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400415 public boolean isVPN() {
416 return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN);
417 }
418
Paul Jensenb10e37f2014-11-25 12:33:08 -0500419 private int getCurrentScore(boolean pretendValidated) {
Paul Jensen2161a8e2014-09-11 11:00:39 -0400420 // TODO: We may want to refactor this into a NetworkScore class that takes a base score from
421 // the NetworkAgent and signals from the NetworkAgent and uses those signals to modify the
422 // score. The NetworkScore class would provide a nice place to centralize score constants
423 // so they are not scattered about the transports.
424
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900425 // If this network is explicitly selected and the user has decided to use it even if it's
426 // unvalidated, give it the maximum score. Also give it the maximum score if it's explicitly
427 // selected and we're trying to see what its score could be. This ensures that we don't tear
428 // down an explicitly selected network before the user gets a chance to prefer it when
429 // a higher-scoring network (e.g., Ethernet) is available.
430 if (networkMisc.explicitlySelected && (networkMisc.acceptUnvalidated || pretendValidated)) {
431 return MAXIMUM_NETWORK_SCORE;
432 }
Paul Jensen2161a8e2014-09-11 11:00:39 -0400433
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900434 int score = currentScore;
Hugo Benichic8e9e122016-09-14 23:23:08 +0000435 if (!lastValidated && !pretendValidated && !ignoreWifiUnvalidationPenalty()) {
Paul Jensene0988542015-06-25 15:30:08 -0400436 score -= UNVALIDATED_SCORE_PENALTY;
437 }
Paul Jensen2161a8e2014-09-11 11:00:39 -0400438 if (score < 0) score = 0;
Paul Jensen2161a8e2014-09-11 11:00:39 -0400439 return score;
440 }
441
Hugo Benichic8e9e122016-09-14 23:23:08 +0000442 // Return true on devices configured to ignore score penalty for wifi networks
443 // that become unvalidated (b/31075769).
444 private boolean ignoreWifiUnvalidationPenalty() {
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900445 boolean isWifi = networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
446 networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
Hugo Benichi50d46a42017-08-31 14:29:51 +0000447 boolean avoidBadWifi = mConnService.avoidBadWifi() || avoidUnvalidated;
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900448 return isWifi && !avoidBadWifi && everValidated;
Hugo Benichic8e9e122016-09-14 23:23:08 +0000449 }
450
Paul Jensenb10e37f2014-11-25 12:33:08 -0500451 // Get the current score for this Network. This may be modified from what the
452 // NetworkAgent sent, as it has modifiers applied to it.
453 public int getCurrentScore() {
454 return getCurrentScore(false);
455 }
456
457 // Get the current score for this Network as if it was validated. This may be modified from
458 // what the NetworkAgent sent, as it has modifiers applied to it.
459 public int getCurrentScoreAsValidated() {
460 return getCurrentScore(true);
461 }
462
Paul Jensen2161a8e2014-09-11 11:00:39 -0400463 public void setCurrentScore(int newScore) {
464 currentScore = newScore;
465 }
466
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600467 public NetworkState getNetworkState() {
468 synchronized (this) {
469 // Network objects are outwardly immutable so there is no point to duplicating.
470 // Duplicating also precludes sharing socket factories and connection pools.
471 final String subscriberId = (networkMisc != null) ? networkMisc.subscriberId : null;
472 return new NetworkState(new NetworkInfo(networkInfo),
473 new LinkProperties(linkProperties),
474 new NetworkCapabilities(networkCapabilities), network, subscriberId, null);
475 }
476 }
477
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900478 /**
479 * Sets the specified request to linger on this network for the specified time. Called by
480 * ConnectivityService when the request is moved to another network with a higher score.
481 */
482 public void lingerRequest(NetworkRequest request, long now, long duration) {
483 if (mLingerTimerForRequest.get(request.requestId) != null) {
484 // Cannot happen. Once a request is lingering on a particular network, we cannot
485 // re-linger it unless that network becomes the best for that request again, in which
486 // case we should have unlingered it.
487 Log.wtf(TAG, this.name() + ": request " + request.requestId + " already lingered");
488 }
489 final long expiryMs = now + duration;
490 LingerTimer timer = new LingerTimer(request, expiryMs);
491 if (VDBG) Log.d(TAG, "Adding LingerTimer " + timer + " to " + this.name());
492 mLingerTimers.add(timer);
493 mLingerTimerForRequest.put(request.requestId, timer);
494 }
495
496 /**
497 * Cancel lingering. Called by ConnectivityService when a request is added to this network.
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900498 * Returns true if the given request was lingering on this network, false otherwise.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900499 */
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900500 public boolean unlingerRequest(NetworkRequest request) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900501 LingerTimer timer = mLingerTimerForRequest.get(request.requestId);
502 if (timer != null) {
503 if (VDBG) Log.d(TAG, "Removing LingerTimer " + timer + " from " + this.name());
504 mLingerTimers.remove(timer);
505 mLingerTimerForRequest.remove(request.requestId);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900506 return true;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900507 }
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900508 return false;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900509 }
510
511 public long getLingerExpiry() {
512 return mLingerExpiryMs;
513 }
514
515 public void updateLingerTimer() {
516 long newExpiry = mLingerTimers.isEmpty() ? 0 : mLingerTimers.last().expiryMs;
517 if (newExpiry == mLingerExpiryMs) return;
518
519 // Even if we're going to reschedule the timer, cancel it first. This is because the
520 // semantics of WakeupMessage guarantee that if cancel is called then the alarm will
521 // never call its callback (handleLingerComplete), even if it has already fired.
522 // WakeupMessage makes no such guarantees about rescheduling a message, so if mLingerMessage
523 // has already been dispatched, rescheduling to some time in the future it won't stop it
524 // from calling its callback immediately.
525 if (mLingerMessage != null) {
526 mLingerMessage.cancel();
527 mLingerMessage = null;
528 }
529
530 if (newExpiry > 0) {
Hugo Benichi50d46a42017-08-31 14:29:51 +0000531 mLingerMessage = mConnService.makeWakeupMessage(
532 mContext, mHandler,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900533 "NETWORK_LINGER_COMPLETE." + network.netId,
534 EVENT_NETWORK_LINGER_COMPLETE, this);
535 mLingerMessage.schedule(newExpiry);
536 }
537
538 mLingerExpiryMs = newExpiry;
539 }
540
541 public void linger() {
542 mLingering = true;
543 }
544
545 public void unlinger() {
546 mLingering = false;
547 }
548
549 public boolean isLingering() {
550 return mLingering;
551 }
552
553 public void clearLingerState() {
554 if (mLingerMessage != null) {
555 mLingerMessage.cancel();
556 mLingerMessage = null;
557 }
558 mLingerTimers.clear();
559 mLingerTimerForRequest.clear();
560 updateLingerTimer(); // Sets mLingerExpiryMs, cancels and nulls out mLingerMessage.
561 mLingering = false;
562 }
563
564 public void dumpLingerTimers(PrintWriter pw) {
565 for (LingerTimer timer : mLingerTimers) { pw.println(timer); }
566 }
567
Hugo Benichief502882017-09-01 01:23:32 +0000568 public void updateClat(INetworkManagementService netd) {
569 if (Nat464Xlat.requiresClat(this)) {
570 maybeStartClat(netd);
571 } else {
572 maybeStopClat();
573 }
574 }
575
576 /** Ensure clat has started for this network. */
577 public void maybeStartClat(INetworkManagementService netd) {
578 if (clatd != null && clatd.isStarted()) {
579 return;
580 }
581 clatd = new Nat464Xlat(netd, this);
582 clatd.start();
583 }
584
585 /** Ensure clat has stopped for this network. */
586 public void maybeStopClat() {
587 if (clatd == null) {
588 return;
589 }
590 clatd.stop();
591 clatd = null;
592 }
593
Robert Greenwalt7b816022014-04-18 15:25:25 -0700594 public String toString() {
Erik Kline230d5ca2016-01-25 17:44:42 +0900595 return "NetworkAgentInfo{ ni{" + networkInfo + "} " +
596 "network{" + network + "} nethandle{" + network.getNetworkHandle() + "} " +
597 "lp{" + linkProperties + "} " +
598 "nc{" + networkCapabilities + "} Score{" + getCurrentScore() + "} " +
Lorenzo Colitti7b42f392014-12-17 11:26:49 +0900599 "everValidated{" + everValidated + "} lastValidated{" + lastValidated + "} " +
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900600 "created{" + created + "} lingering{" + isLingering() + "} " +
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900601 "explicitlySelected{" + networkMisc.explicitlySelected + "} " +
602 "acceptUnvalidated{" + networkMisc.acceptUnvalidated + "} " +
Paul Jensen3d194ea2015-06-16 14:27:36 -0400603 "everCaptivePortalDetected{" + everCaptivePortalDetected + "} " +
604 "lastCaptivePortalDetected{" + lastCaptivePortalDetected + "} " +
Hugo Benichib577d652017-06-27 15:13:20 +0900605 "clat{" + clatd + "} " +
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900606 "}";
Robert Greenwalt7b816022014-04-18 15:25:25 -0700607 }
608
609 public String name() {
610 return "NetworkAgentInfo [" + networkInfo.getTypeName() + " (" +
Hugo Benichib577d652017-06-27 15:13:20 +0900611 networkInfo.getSubtypeName() + ") - " + Objects.toString(network) + "]";
Robert Greenwalt7b816022014-04-18 15:25:25 -0700612 }
Paul Jensen85cf78e2015-06-25 13:25:07 -0400613
614 // Enables sorting in descending order of score.
615 @Override
616 public int compareTo(NetworkAgentInfo other) {
617 return other.getCurrentScore() - getCurrentScore();
618 }
Robert Greenwalt7b816022014-04-18 15:25:25 -0700619}