NetworkAgentInfo.java revision 5526f9c78c6fcad500c272ef14b7403e3395525e
17b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt/*
27b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * Copyright (C) 2014 The Android Open Source Project
37b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt *
47b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * Licensed under the Apache License, Version 2.0 (the "License");
57b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * you may not use this file except in compliance with the License.
67b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * You may obtain a copy of the License at
77b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt *
87b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt *      http://www.apache.org/licenses/LICENSE-2.0
97b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt *
107b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * Unless required by applicable law or agreed to in writing, software
117b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * distributed under the License is distributed on an "AS IS" BASIS,
127b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
137b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * See the License for the specific language governing permissions and
147b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * limitations under the License.
157b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt */
167b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt
177b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwaltpackage com.android.server.connectivity;
187b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt
19e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensenimport static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
20e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen
21ca8f16ad14819ba17f5ff3d2e2bf6fbc9bbaa9f7Paul Jensenimport android.content.Context;
227b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwaltimport android.net.LinkProperties;
237b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwaltimport android.net.Network;
247b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwaltimport android.net.NetworkCapabilities;
257b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwaltimport android.net.NetworkInfo;
268cd33ed84e94036a5e1201485af7603dc6fb0d9bSreeram Ramachandranimport android.net.NetworkMisc;
277b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwaltimport android.net.NetworkRequest;
28f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkeyimport android.net.NetworkState;
29ca8f16ad14819ba17f5ff3d2e2bf6fbc9bbaa9f7Paul Jensenimport android.os.Handler;
307b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwaltimport android.os.Messenger;
31b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colittiimport android.os.SystemClock;
32b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colittiimport android.util.Log;
337b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwaltimport android.util.SparseArray;
347b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt
357b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwaltimport com.android.internal.util.AsyncChannel;
36b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colittiimport com.android.internal.util.WakeupMessage;
37cf4c2c637268b1a2979e20a8b5644916777a02a4Paul Jensenimport com.android.server.ConnectivityService;
38ca8f16ad14819ba17f5ff3d2e2bf6fbc9bbaa9f7Paul Jensenimport com.android.server.connectivity.NetworkMonitor;
397b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt
40b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colittiimport java.io.PrintWriter;
417b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwaltimport java.util.ArrayList;
4285cf78edc92b85ec90e91de42b14b84e202260f3Paul Jensenimport java.util.Comparator;
43b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colittiimport java.util.Objects;
44b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colittiimport java.util.SortedSet;
45b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colittiimport java.util.TreeSet;
467b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt
477b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt/**
487b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * A bag class used by ConnectivityService for holding a collection of most recent
497b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * information published by a particular NetworkAgent as well as the
507b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt * AsyncChannel/messenger for reaching that NetworkAgent and lists of NetworkRequests
5185cf78edc92b85ec90e91de42b14b84e202260f3Paul Jensen * interested in using it.  Default sort order is descending by score.
527b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt */
53e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// States of a network:
54e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// --------------------
55e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// 1. registered, uncreated, disconnected, unvalidated
56e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//    This state is entered when a NetworkFactory registers a NetworkAgent in any state except
57e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//    the CONNECTED state.
58585e24889455d1d70d14a9c89a8acef922994898Robin Lee// 2. registered, uncreated, connecting, unvalidated
59585e24889455d1d70d14a9c89a8acef922994898Robin Lee//    This state is entered when a registered NetworkAgent for a VPN network transitions to the
60585e24889455d1d70d14a9c89a8acef922994898Robin Lee//    CONNECTING state (TODO: go through this state for every network, not just VPNs).
61585e24889455d1d70d14a9c89a8acef922994898Robin Lee//    ConnectivityService will tell netd to create the network early in order to add extra UID
62585e24889455d1d70d14a9c89a8acef922994898Robin Lee//    routing rules referencing the netID. These rules need to be in place before the network is
63585e24889455d1d70d14a9c89a8acef922994898Robin Lee//    connected to avoid racing against client apps trying to connect to a half-setup network.
64585e24889455d1d70d14a9c89a8acef922994898Robin Lee// 3. registered, uncreated, connected, unvalidated
65585e24889455d1d70d14a9c89a8acef922994898Robin Lee//    This state is entered when a registered NetworkAgent transitions to the CONNECTED state.
66585e24889455d1d70d14a9c89a8acef922994898Robin Lee//    ConnectivityService will tell netd to create the network if it was not already created, and
67585e24889455d1d70d14a9c89a8acef922994898Robin Lee//    immediately transition to state #4.
68585e24889455d1d70d14a9c89a8acef922994898Robin Lee// 4. registered, created, connected, unvalidated
69cf4c2c637268b1a2979e20a8b5644916777a02a4Paul Jensen//    If this network can satisfy the default NetworkRequest, then NetworkMonitor will
70e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//    probe for Internet connectivity.
71e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//    If this network cannot satisfy the default NetworkRequest, it will immediately be
72585e24889455d1d70d14a9c89a8acef922994898Robin Lee//    transitioned to state #5.
73e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//    A network may remain in this state if NetworkMonitor fails to find Internet connectivity,
74e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//    for example:
75e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//    a. a captive portal is present, or
76e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//    b. a WiFi router whose Internet backhaul is down, or
77e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//    c. a wireless connection stops transfering packets temporarily (e.g. device is in elevator
78e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//       or tunnel) but does not disconnect from the AP/cell tower, or
79e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//    d. a stand-alone device offering a WiFi AP without an uplink for configuration purposes.
80585e24889455d1d70d14a9c89a8acef922994898Robin Lee// 5. registered, created, connected, validated
81e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//
82e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// The device's default network connection:
83e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// ----------------------------------------
84585e24889455d1d70d14a9c89a8acef922994898Robin Lee// Networks in states #4 and #5 may be used as a device's default network connection if they
85e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// satisfy the default NetworkRequest.
86585e24889455d1d70d14a9c89a8acef922994898Robin Lee// A network, that satisfies the default NetworkRequest, in state #5 should always be chosen
87585e24889455d1d70d14a9c89a8acef922994898Robin Lee// in favor of a network, that satisfies the default NetworkRequest, in state #4.
88e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// When deciding between two networks, that both satisfy the default NetworkRequest, to select
89e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// for the default network connection, the one with the higher score should be chosen.
90e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//
91e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// When a network disconnects:
92e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// ---------------------------
93e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// If a network's transport disappears, for example:
94e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// a. WiFi turned off, or
95e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// b. cellular data turned off, or
96e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// c. airplane mode is turned on, or
97e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// d. a wireless connection disconnects from AP/cell tower entirely (e.g. device is out of range
98e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//    of AP for an extended period of time, or switches to another AP without roaming)
99585e24889455d1d70d14a9c89a8acef922994898Robin Lee// then that network can transition from any state (#1-#5) to unregistered.  This happens by
100e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// the transport disconnecting their NetworkAgent's AsyncChannel with ConnectivityManager.
101e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// ConnectivityService also tells netd to destroy the network.
102e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen//
103e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// When ConnectivityService disconnects a network:
104e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// -----------------------------------------------
105e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// If a network has no chance of satisfying any requests (even if it were to become validated
106585e24889455d1d70d14a9c89a8acef922994898Robin Lee// and enter state #5), ConnectivityService will disconnect the NetworkAgent's AsyncChannel.
107e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// If the network ever for any period of time had satisfied a NetworkRequest (i.e. had been
108e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// the highest scoring that satisfied the NetworkRequest's constraints), but is no longer the
109e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// highest scoring network for any NetworkRequest, then there will be a 30s pause before
110e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// ConnectivityService disconnects the NetworkAgent's AsyncChannel.  During this pause the
111e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// network is considered "lingering".  This pause exists to allow network communication to be
112e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// wrapped up rather than abruptly terminated.  During this pause if the network begins satisfying
113e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// a NetworkRequest, ConnectivityService will cancel the future disconnection of the NetworkAgent's
114e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen// AsyncChannel, and the network is no longer considered "lingering".
11585cf78edc92b85ec90e91de42b14b84e202260f3Paul Jensenpublic class NetworkAgentInfo implements Comparable<NetworkAgentInfo> {
1167b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt    public NetworkInfo networkInfo;
11731a94f48bf8014cf6a1127bd23cf9a8541a9abedPaul Jensen    // This Network object should always be used if possible, so as to encourage reuse of the
11831a94f48bf8014cf6a1127bd23cf9a8541a9abedPaul Jensen    // enclosed socket factory and connection pool.  Avoid creating other Network objects.
11931a94f48bf8014cf6a1127bd23cf9a8541a9abedPaul Jensen    // This Network object is always valid.
12031a94f48bf8014cf6a1127bd23cf9a8541a9abedPaul Jensen    public final Network network;
1217b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt    public LinkProperties linkProperties;
1221c7ba0285b3fe8de479d6c09b2ff45572913c2cbPaul Jensen    // This should only be modified via ConnectivityService.updateCapabilities().
1237b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt    public NetworkCapabilities networkCapabilities;
124ca8f16ad14819ba17f5ff3d2e2bf6fbc9bbaa9f7Paul Jensen    public final NetworkMonitor networkMonitor;
1258cd33ed84e94036a5e1201485af7603dc6fb0d9bSreeram Ramachandran    public final NetworkMisc networkMisc;
126585e24889455d1d70d14a9c89a8acef922994898Robin Lee    // Indicates if netd has been told to create this Network. From this point on the appropriate
127585e24889455d1d70d14a9c89a8acef922994898Robin Lee    // routing rules are setup and routes are added so packets can begin flowing over the Network.
128d49159f4e997faae6ef4141b667ad6fef74a6724Lorenzo Colitti    // This is a sticky bit; once set it is never cleared.
129eec75412a971a5ccb769364120c769c331946eb3Paul Jensen    public boolean created;
130585e24889455d1d70d14a9c89a8acef922994898Robin Lee    // Set to true after the first time this network is marked as CONNECTED. Once set, the network
131585e24889455d1d70d14a9c89a8acef922994898Robin Lee    // shows up in API calls, is able to satisfy NetworkRequests and can become the default network.
132585e24889455d1d70d14a9c89a8acef922994898Robin Lee    // This is a sticky bit; once set it is never cleared.
133585e24889455d1d70d14a9c89a8acef922994898Robin Lee    public boolean everConnected;
13471b645fe9cb8106dfcbf025a3fd7f58698c051bbPaul Jensen    // Set to true if this Network successfully passed validation or if it did not satisfy the
13571b645fe9cb8106dfcbf025a3fd7f58698c051bbPaul Jensen    // default NetworkRequest in which case validation will not be attempted.
136d49159f4e997faae6ef4141b667ad6fef74a6724Lorenzo Colitti    // This is a sticky bit; once set it is never cleared even if future validation attempts fail.
137d3b8a3e77696ecd90ce59a869aaadf1e7804a9c8Lorenzo Colitti    public boolean everValidated;
138ca8f16ad14819ba17f5ff3d2e2bf6fbc9bbaa9f7Paul Jensen
1397b42f399430d5d4ace4efbee225bbd3ecd2d4146Lorenzo Colitti    // The result of the last validation attempt on this network (true if validated, false if not).
1407b42f399430d5d4ace4efbee225bbd3ecd2d4146Lorenzo Colitti    // This bit exists only because we never unvalidate a network once it's been validated, and that
1417b42f399430d5d4ace4efbee225bbd3ecd2d4146Lorenzo Colitti    // is because the network scoring and revalidation code does not (may not?) deal properly with
1427b42f399430d5d4ace4efbee225bbd3ecd2d4146Lorenzo Colitti    // networks becoming unvalidated.
1437b42f399430d5d4ace4efbee225bbd3ecd2d4146Lorenzo Colitti    // TODO: Fix the network scoring code, remove this, and rename everValidated to validated.
1447b42f399430d5d4ace4efbee225bbd3ecd2d4146Lorenzo Colitti    public boolean lastValidated;
1457b42f399430d5d4ace4efbee225bbd3ecd2d4146Lorenzo Colitti
146d49159f4e997faae6ef4141b667ad6fef74a6724Lorenzo Colitti    // Whether a captive portal was ever detected on this network.
147d49159f4e997faae6ef4141b667ad6fef74a6724Lorenzo Colitti    // This is a sticky bit; once set it is never cleared.
1483d194eae6f658ed865b2d3b748f8b83834c877abPaul Jensen    public boolean everCaptivePortalDetected;
1493d194eae6f658ed865b2d3b748f8b83834c877abPaul Jensen
1503d194eae6f658ed865b2d3b748f8b83834c877abPaul Jensen    // Whether a captive portal was found during the last network validation attempt.
1513d194eae6f658ed865b2d3b748f8b83834c877abPaul Jensen    public boolean lastCaptivePortalDetected;
152d49159f4e997faae6ef4141b667ad6fef74a6724Lorenzo Colitti
153b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // Networks are lingered when they become unneeded as a result of their NetworkRequests being
154b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // satisfied by a higher-scoring network. so as to allow communication to wrap up before the
155b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // network is taken down.  This usually only happens to the default network. Lingering ends with
156b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // either the linger timeout expiring and the network being taken down, or the network
157b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // satisfying a request again.
158b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    public static class LingerTimer implements Comparable<LingerTimer> {
159b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        public final NetworkRequest request;
160b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        public final long expiryMs;
161b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
162b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        public LingerTimer(NetworkRequest request, long expiryMs) {
163b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            this.request = request;
164b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            this.expiryMs = expiryMs;
165b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        }
166b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        public boolean equals(Object o) {
167b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            if (!(o instanceof LingerTimer)) return false;
168b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            LingerTimer other = (LingerTimer) o;
169b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            return (request.requestId == other.request.requestId) && (expiryMs == other.expiryMs);
170b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        }
171b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        public int hashCode() {
172b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            return Objects.hash(request.requestId, expiryMs);
173b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        }
174b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        public int compareTo(LingerTimer other) {
175b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            return (expiryMs != other.expiryMs) ?
176b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti                    Long.compare(expiryMs, other.expiryMs) :
177b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti                    Integer.compare(request.requestId, other.request.requestId);
178b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        }
179b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        public String toString() {
180b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            return String.format("%s, expires %dms", request.toString(),
181b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti                    expiryMs - SystemClock.elapsedRealtime());
182b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        }
183b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    }
184b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
185b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    /**
186b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti     * Inform ConnectivityService that the network LINGER period has
187b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti     * expired.
188b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti     * obj = this NetworkAgentInfo
189b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti     */
190b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    public static final int EVENT_NETWORK_LINGER_COMPLETE = 1001;
191b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
192b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // All linger timers for this network, sorted by expiry time. A linger timer is added whenever
193b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // a request is moved to a network with a better score, regardless of whether the network is or
194b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // was lingering or not.
195b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // TODO: determine if we can replace this with a smaller or unsorted data structure. (e.g.,
196b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // SparseLongArray) combined with the timestamp of when the last timer is scheduled to fire.
197b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    private final SortedSet<LingerTimer> mLingerTimers = new TreeSet<>();
198b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
199b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // For fast lookups. Indexes into mLingerTimers by request ID.
200b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    private final SparseArray<LingerTimer> mLingerTimerForRequest = new SparseArray<>();
201b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
202b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // Linger expiry timer. Armed whenever mLingerTimers is non-empty, regardless of whether the
203b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // network is lingering or not. Always set to the expiry of the LingerTimer that expires last.
204b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // When the timer fires, all linger state is cleared, and if the network has no requests, it is
205b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // torn down.
206b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    private WakeupMessage mLingerMessage;
207b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
208b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // Linger expiry. Holds the expiry time of the linger timer, or 0 if the timer is not armed.
209b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    private long mLingerExpiryMs;
210b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
211b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // Whether the network is lingering or not. Must be maintained separately from the above because
212b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // it depends on the state of other networks and requests, which only ConnectivityService knows.
213b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // (Example: we don't linger a network if it would become the best for a NetworkRequest if it
214b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    // validated).
215b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    private boolean mLingering;
21685cf78edc92b85ec90e91de42b14b84e202260f3Paul Jensen
2172161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen    // This represents the last score received from the NetworkAgent.
2182161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen    private int currentScore;
2192161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen    // Penalty applied to scores of Networks that have not been validated.
2202161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen    private static final int UNVALIDATED_SCORE_PENALTY = 40;
2212161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen
222e73cc4646bed3926024c9f54ca59e3a82a97b56cRobert Greenwalt    // Score for explicitly connected network.
223e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti    //
224e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti    // This ensures that a) the explicitly selected network is never trumped by anything else, and
225e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti    // b) the explicitly selected network is never torn down.
226e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti    private static final int MAXIMUM_NETWORK_SCORE = 100;
227e73cc4646bed3926024c9f54ca59e3a82a97b56cRobert Greenwalt
2287b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt    // The list of NetworkRequests being satisfied by this Network.
229767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    private final SparseArray<NetworkRequest> mNetworkRequests = new SparseArray<>();
23071b645fe9cb8106dfcbf025a3fd7f58698c051bbPaul Jensen    // The list of NetworkRequests that this Network previously satisfied with the highest
23171b645fe9cb8106dfcbf025a3fd7f58698c051bbPaul Jensen    // score.  A non-empty list indicates that if this Network was validated it is lingered.
232767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    // How many of the satisfied requests are actual requests and not listens.
233767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    private int mNumRequestNetworkRequests = 0;
2347b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt
2357b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt    public final Messenger messenger;
2367b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt    public final AsyncChannel asyncChannel;
2377b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt
238954394653dad05838235f48244a4320893e0f0cfLorenzo Colitti    // Used by ConnectivityService to keep track of 464xlat.
239954394653dad05838235f48244a4320893e0f0cfLorenzo Colitti    public Nat464Xlat clatd;
240954394653dad05838235f48244a4320893e0f0cfLorenzo Colitti
241b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    private static final String TAG = ConnectivityService.class.getSimpleName();
242b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    private static final boolean VDBG = false;
243b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    private final ConnectivityService mConnService;
244b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    private final Context mContext;
245b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    private final Handler mHandler;
246b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
24731a94f48bf8014cf6a1127bd23cf9a8541a9abedPaul Jensen    public NetworkAgentInfo(Messenger messenger, AsyncChannel ac, Network net, NetworkInfo info,
2488cd33ed84e94036a5e1201485af7603dc6fb0d9bSreeram Ramachandran            LinkProperties lp, NetworkCapabilities nc, int score, Context context, Handler handler,
249cf4c2c637268b1a2979e20a8b5644916777a02a4Paul Jensen            NetworkMisc misc, NetworkRequest defaultRequest, ConnectivityService connService) {
2507b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt        this.messenger = messenger;
2517b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt        asyncChannel = ac;
25231a94f48bf8014cf6a1127bd23cf9a8541a9abedPaul Jensen        network = net;
2537b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt        networkInfo = info;
2547b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt        linkProperties = lp;
2557b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt        networkCapabilities = nc;
2567b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt        currentScore = score;
257b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        mConnService = connService;
258b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        mContext = context;
259b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        mHandler = handler;
260b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        networkMonitor = mConnService.createNetworkMonitor(context, handler, this, defaultRequest);
2618cd33ed84e94036a5e1201485af7603dc6fb0d9bSreeram Ramachandran        networkMisc = misc;
2627b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt    }
2637b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt
264767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    // Functions for manipulating the requests satisfied by this network.
265767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    //
266767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    // These functions must only called on ConnectivityService's main thread.
267767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti
2683d911469a190437fe936103e861bfa171841fbd6Paul Jensen    /**
2693d911469a190437fe936103e861bfa171841fbd6Paul Jensen     * Add {@code networkRequest} to this network as it's satisfied by this network.
2703d911469a190437fe936103e861bfa171841fbd6Paul Jensen     * @return true if {@code networkRequest} was added or false if {@code networkRequest} was
2713d911469a190437fe936103e861bfa171841fbd6Paul Jensen     *         already present.
2723d911469a190437fe936103e861bfa171841fbd6Paul Jensen     */
2733d911469a190437fe936103e861bfa171841fbd6Paul Jensen    public boolean addRequest(NetworkRequest networkRequest) {
274767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti        NetworkRequest existing = mNetworkRequests.get(networkRequest.requestId);
275767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti        if (existing == networkRequest) return false;
276767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti        if (existing != null && existing.isRequest()) mNumRequestNetworkRequests--;
277767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti        mNetworkRequests.put(networkRequest.requestId, networkRequest);
278767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti        if (networkRequest.isRequest()) mNumRequestNetworkRequests++;
2793d911469a190437fe936103e861bfa171841fbd6Paul Jensen        return true;
28071bf33a02f49444fbfa35b267c70592f3b07a07dRobert Greenwalt    }
28171bf33a02f49444fbfa35b267c70592f3b07a07dRobert Greenwalt
282767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    /**
283767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     * Remove the specified request from this network.
284767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     */
285767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    public void removeRequest(int requestId) {
286767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti        NetworkRequest existing = mNetworkRequests.get(requestId);
287b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        if (existing == null) return;
288767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti        mNetworkRequests.remove(requestId);
289b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        if (existing.isRequest()) {
290b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            mNumRequestNetworkRequests--;
291b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            unlingerRequest(existing);
292b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        }
293767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    }
294767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti
295767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    /**
296767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     * Returns whether this network is currently satisfying the request with the specified ID.
297767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     */
298767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    public boolean isSatisfyingRequest(int id) {
299767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti        return mNetworkRequests.get(id) != null;
300767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    }
301767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti
302767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    /**
303767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     * Returns the request at the specified position in the list of requests satisfied by this
304767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     * network.
305767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     */
306767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    public NetworkRequest requestAt(int index) {
307767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti        return mNetworkRequests.valueAt(index);
308767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    }
309767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti
310767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    /**
311767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     * Returns the number of requests currently satisfied by this network for which
312767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     * {@link android.net.NetworkRequest#isRequest} returns {@code true}.
313767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     */
314767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    public int numRequestNetworkRequests() {
315767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti        return mNumRequestNetworkRequests;
316767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    }
317767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti
318767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    /**
319767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     * Returns the number of requests of any type currently satisfied by this network.
320767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti     */
321767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    public int numNetworkRequests() {
322767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti        return mNetworkRequests.size();
323767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti    }
324767708db54edbdb26e166157fa05966769a629ccLorenzo Colitti
3250cc1732cfb9d68779449b4c12661b4df6bfc720bPaul Jensen    // Does this network satisfy request?
3260cc1732cfb9d68779449b4c12661b4df6bfc720bPaul Jensen    public boolean satisfies(NetworkRequest request) {
3270cc1732cfb9d68779449b4c12661b4df6bfc720bPaul Jensen        return created &&
3280cc1732cfb9d68779449b4c12661b4df6bfc720bPaul Jensen                request.networkCapabilities.satisfiedByNetworkCapabilities(networkCapabilities);
3290cc1732cfb9d68779449b4c12661b4df6bfc720bPaul Jensen    }
3300cc1732cfb9d68779449b4c12661b4df6bfc720bPaul Jensen
331c3f21f3b8b01508f5dc01b2e5fa4c3d652bb67bbLorenzo Colitti    public boolean satisfiesImmutableCapabilitiesOf(NetworkRequest request) {
332c3f21f3b8b01508f5dc01b2e5fa4c3d652bb67bbLorenzo Colitti        return created &&
333c3f21f3b8b01508f5dc01b2e5fa4c3d652bb67bbLorenzo Colitti                request.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
334c3f21f3b8b01508f5dc01b2e5fa4c3d652bb67bbLorenzo Colitti                        networkCapabilities);
335c3f21f3b8b01508f5dc01b2e5fa4c3d652bb67bbLorenzo Colitti    }
336c3f21f3b8b01508f5dc01b2e5fa4c3d652bb67bbLorenzo Colitti
3376bc2c2c34f2b23eae79ad733c97a691734055c4fPaul Jensen    public boolean isVPN() {
3386bc2c2c34f2b23eae79ad733c97a691734055c4fPaul Jensen        return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN);
3396bc2c2c34f2b23eae79ad733c97a691734055c4fPaul Jensen    }
3406bc2c2c34f2b23eae79ad733c97a691734055c4fPaul Jensen
341b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen    private int getCurrentScore(boolean pretendValidated) {
3422161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen        // TODO: We may want to refactor this into a NetworkScore class that takes a base score from
3432161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen        // the NetworkAgent and signals from the NetworkAgent and uses those signals to modify the
3442161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen        // score.  The NetworkScore class would provide a nice place to centralize score constants
3452161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen        // so they are not scattered about the transports.
3462161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen
347e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti        // If this network is explicitly selected and the user has decided to use it even if it's
348e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti        // unvalidated, give it the maximum score. Also give it the maximum score if it's explicitly
349e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti        // selected and we're trying to see what its score could be. This ensures that we don't tear
350e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti        // down an explicitly selected network before the user gets a chance to prefer it when
351e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti        // a higher-scoring network (e.g., Ethernet) is available.
352e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti        if (networkMisc.explicitlySelected && (networkMisc.acceptUnvalidated || pretendValidated)) {
353e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti            return MAXIMUM_NETWORK_SCORE;
354e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti        }
3552161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen
356e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti        int score = currentScore;
357e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen        // Use NET_CAPABILITY_VALIDATED here instead of lastValidated, this allows
358e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen        // ConnectivityService.updateCapabilities() to compute the old score prior to updating
359e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen        // networkCapabilities (with a potentially different validated state).
360e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen        if (!networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) && !pretendValidated) {
361e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen            score -= UNVALIDATED_SCORE_PENALTY;
362e098854c41a72b22f4174bc623e8e93cde8d7331Paul Jensen        }
3632161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen        if (score < 0) score = 0;
3642161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen        return score;
3652161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen    }
3662161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen
367b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen    // Get the current score for this Network.  This may be modified from what the
368b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen    // NetworkAgent sent, as it has modifiers applied to it.
369b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen    public int getCurrentScore() {
370b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen        return getCurrentScore(false);
371b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen    }
372b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen
373b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen    // Get the current score for this Network as if it was validated.  This may be modified from
374b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen    // what the NetworkAgent sent, as it has modifiers applied to it.
375b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen    public int getCurrentScoreAsValidated() {
376b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen        return getCurrentScore(true);
377b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen    }
378b10e37fd1c3a95f7e621eed234c2491eb71241e2Paul Jensen
3792161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen    public void setCurrentScore(int newScore) {
3802161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen        currentScore = newScore;
3812161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen    }
3822161a8ea123134ee3f9a10c0f8f56aabd8289f69Paul Jensen
383f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkey    public NetworkState getNetworkState() {
384f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkey        synchronized (this) {
385f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkey            // Network objects are outwardly immutable so there is no point to duplicating.
386f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkey            // Duplicating also precludes sharing socket factories and connection pools.
387f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkey            final String subscriberId = (networkMisc != null) ? networkMisc.subscriberId : null;
388f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkey            return new NetworkState(new NetworkInfo(networkInfo),
389f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkey                    new LinkProperties(linkProperties),
390f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkey                    new NetworkCapabilities(networkCapabilities), network, subscriberId, null);
391f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkey        }
392f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkey    }
393f07c7b9fd0a640bff4bf7690373613da217fe69bJeff Sharkey
394b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    /**
395b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti     * Sets the specified request to linger on this network for the specified time. Called by
396b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti     * ConnectivityService when the request is moved to another network with a higher score.
397b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti     */
398b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    public void lingerRequest(NetworkRequest request, long now, long duration) {
399b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        if (mLingerTimerForRequest.get(request.requestId) != null) {
400b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            // Cannot happen. Once a request is lingering on a particular network, we cannot
401b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            // re-linger it unless that network becomes the best for that request again, in which
402b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            // case we should have unlingered it.
403b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            Log.wtf(TAG, this.name() + ": request " + request.requestId + " already lingered");
404b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        }
405b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        final long expiryMs = now + duration;
406b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        LingerTimer timer = new LingerTimer(request, expiryMs);
407b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        if (VDBG) Log.d(TAG, "Adding LingerTimer " + timer + " to " + this.name());
408b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        mLingerTimers.add(timer);
409b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        mLingerTimerForRequest.put(request.requestId, timer);
410b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    }
411b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
412b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    /**
413b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti     * Cancel lingering. Called by ConnectivityService when a request is added to this network.
4145526f9c78c6fcad500c272ef14b7403e3395525eLorenzo Colitti     * Returns true if the given request was lingering on this network, false otherwise.
415b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti     */
4165526f9c78c6fcad500c272ef14b7403e3395525eLorenzo Colitti    public boolean unlingerRequest(NetworkRequest request) {
417b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        LingerTimer timer = mLingerTimerForRequest.get(request.requestId);
418b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        if (timer != null) {
419b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            if (VDBG) Log.d(TAG, "Removing LingerTimer " + timer + " from " + this.name());
420b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            mLingerTimers.remove(timer);
421b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            mLingerTimerForRequest.remove(request.requestId);
4225526f9c78c6fcad500c272ef14b7403e3395525eLorenzo Colitti            return true;
423b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        }
4245526f9c78c6fcad500c272ef14b7403e3395525eLorenzo Colitti        return false;
425b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    }
426b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
427b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    public long getLingerExpiry() {
428b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        return mLingerExpiryMs;
429b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    }
430b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
431b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    public void updateLingerTimer() {
432b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        long newExpiry = mLingerTimers.isEmpty() ? 0 : mLingerTimers.last().expiryMs;
433b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        if (newExpiry == mLingerExpiryMs) return;
434b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
435b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        // Even if we're going to reschedule the timer, cancel it first. This is because the
436b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        // semantics of WakeupMessage guarantee that if cancel is called then the alarm will
437b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        // never call its callback (handleLingerComplete), even if it has already fired.
438b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        // WakeupMessage makes no such guarantees about rescheduling a message, so if mLingerMessage
439b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        // has already been dispatched, rescheduling to some time in the future it won't stop it
440b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        // from calling its callback immediately.
441b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        if (mLingerMessage != null) {
442b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            mLingerMessage.cancel();
443b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            mLingerMessage = null;
444b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        }
445b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
446b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        if (newExpiry > 0) {
447b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            mLingerMessage = mConnService.makeWakeupMessage(
448b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti                    mContext, mHandler,
449b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti                    "NETWORK_LINGER_COMPLETE." + network.netId,
450b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti                    EVENT_NETWORK_LINGER_COMPLETE, this);
451b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            mLingerMessage.schedule(newExpiry);
452b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        }
453b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
454b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        mLingerExpiryMs = newExpiry;
455b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    }
456b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
457b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    public void linger() {
458b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        mLingering = true;
459b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    }
460b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
461b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    public void unlinger() {
462b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        mLingering = false;
463b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    }
464b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
465b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    public boolean isLingering() {
466b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        return mLingering;
467b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    }
468b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
469b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    public void clearLingerState() {
470b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        if (mLingerMessage != null) {
471b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            mLingerMessage.cancel();
472b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti            mLingerMessage = null;
473b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        }
474b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        mLingerTimers.clear();
475b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        mLingerTimerForRequest.clear();
476b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        updateLingerTimer();  // Sets mLingerExpiryMs, cancels and nulls out mLingerMessage.
477b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        mLingering = false;
478b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    }
479b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
480b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    public void dumpLingerTimers(PrintWriter pw) {
481b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti        for (LingerTimer timer : mLingerTimers) { pw.println(timer); }
482b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti    }
483b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti
4847b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt    public String toString() {
485230d5ca49821bd7a10bb1b3e61d10f534f687772Erik Kline        return "NetworkAgentInfo{ ni{" + networkInfo + "}  " +
486230d5ca49821bd7a10bb1b3e61d10f534f687772Erik Kline                "network{" + network + "}  nethandle{" + network.getNetworkHandle() + "}  " +
487230d5ca49821bd7a10bb1b3e61d10f534f687772Erik Kline                "lp{" + linkProperties + "}  " +
488230d5ca49821bd7a10bb1b3e61d10f534f687772Erik Kline                "nc{" + networkCapabilities + "}  Score{" + getCurrentScore() + "}  " +
4897b42f399430d5d4ace4efbee225bbd3ecd2d4146Lorenzo Colitti                "everValidated{" + everValidated + "}  lastValidated{" + lastValidated + "}  " +
490b57578ca4f0fa64406ffad09ad9250391e3bbfa5Lorenzo Colitti                "created{" + created + "} lingering{" + isLingering() + "} " +
491e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti                "explicitlySelected{" + networkMisc.explicitlySelected + "} " +
492e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti                "acceptUnvalidated{" + networkMisc.acceptUnvalidated + "} " +
4933d194eae6f658ed865b2d3b748f8b83834c877abPaul Jensen                "everCaptivePortalDetected{" + everCaptivePortalDetected + "} " +
4943d194eae6f658ed865b2d3b748f8b83834c877abPaul Jensen                "lastCaptivePortalDetected{" + lastCaptivePortalDetected + "} " +
495e03c3c7edf54854ed22adf1e55b27b2408c4c66aLorenzo Colitti                "}";
4967b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt    }
4977b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt
4987b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt    public String name() {
4997b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt        return "NetworkAgentInfo [" + networkInfo.getTypeName() + " (" +
50060061a6ebf4ef758c4a47d210de0e5be2484be5bPaul Jensen                networkInfo.getSubtypeName() + ") - " +
50160061a6ebf4ef758c4a47d210de0e5be2484be5bPaul Jensen                (network == null ? "null" : network.toString()) + "]";
5027b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt    }
50385cf78edc92b85ec90e91de42b14b84e202260f3Paul Jensen
50485cf78edc92b85ec90e91de42b14b84e202260f3Paul Jensen    // Enables sorting in descending order of score.
50585cf78edc92b85ec90e91de42b14b84e202260f3Paul Jensen    @Override
50685cf78edc92b85ec90e91de42b14b84e202260f3Paul Jensen    public int compareTo(NetworkAgentInfo other) {
50785cf78edc92b85ec90e91de42b14b84e202260f3Paul Jensen        return other.getCurrentScore() - getCurrentScore();
50885cf78edc92b85ec90e91de42b14b84e202260f3Paul Jensen    }
5097b81602f3c18df8a4ca0342c514af8f7e394c0d7Robert Greenwalt}
510