blob: 43affcdfefe9b484aa9012974930b750d09f920e [file] [log] [blame]
Jason Monkd52356a2015-01-28 10:40:41 -05001/*
2 * Copyright (C) 2015 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.settingslib.wifi;
18
Sundeep Ghuman53200ed2017-06-21 16:54:36 -070019import android.annotation.IntDef;
Sundeep Ghumanbb399912018-01-29 18:31:15 -080020import android.annotation.MainThread;
Sundeep Ghuman271e5de2017-05-30 14:11:39 -070021import android.annotation.Nullable;
Jason Monk6980d122015-06-15 10:07:55 -040022import android.app.AppGlobals;
Jason Monkd52356a2015-01-28 10:40:41 -050023import android.content.Context;
Jason Monk6980d122015-06-15 10:07:55 -040024import android.content.pm.ApplicationInfo;
25import android.content.pm.IPackageManager;
26import android.content.pm.PackageManager;
Sanket Padawe7094d222015-05-01 16:55:00 -070027import android.net.ConnectivityManager;
Sanket Padawe7094d222015-05-01 16:55:00 -070028import android.net.NetworkCapabilities;
Jason Monkd52356a2015-01-28 10:40:41 -050029import android.net.NetworkInfo;
30import android.net.NetworkInfo.DetailedState;
31import android.net.NetworkInfo.State;
Sundeep Ghumana28050a2017-07-12 22:09:25 -070032import android.net.NetworkKey;
Stephen Chen36dd5cf12017-03-20 13:27:51 -070033import android.net.NetworkScoreManager;
34import android.net.NetworkScorerAppData;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -080035import android.net.ScoredNetwork;
Sanket Padawe7094d222015-05-01 16:55:00 -070036import android.net.wifi.IWifiManager;
Jason Monkd52356a2015-01-28 10:40:41 -050037import android.net.wifi.ScanResult;
38import android.net.wifi.WifiConfiguration;
39import android.net.wifi.WifiConfiguration.KeyMgmt;
Peter Qiu280581b2017-07-24 14:18:56 -070040import android.net.wifi.WifiEnterpriseConfig;
Jason Monkd52356a2015-01-28 10:40:41 -050041import android.net.wifi.WifiInfo;
42import android.net.wifi.WifiManager;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -080043import android.net.wifi.WifiNetworkScoreCache;
Quang Luong9051dfd2018-12-12 12:49:24 -080044import android.net.wifi.hotspot2.OsuProvider;
Peter Qiuced37db2017-03-14 15:51:22 -070045import android.net.wifi.hotspot2.PasspointConfiguration;
Quang Luong4d194842018-12-18 16:59:49 -080046import android.net.wifi.hotspot2.ProvisioningCallback;
Jason Monkd52356a2015-01-28 10:40:41 -050047import android.os.Bundle;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -080048import android.os.Parcelable;
Sanket Padawe7094d222015-05-01 16:55:00 -070049import android.os.RemoteException;
50import android.os.ServiceManager;
Mitchell Wills18af4932016-08-10 13:49:21 -070051import android.os.SystemClock;
Jason Monk6980d122015-06-15 10:07:55 -040052import android.os.UserHandle;
Jason Monk6980d122015-06-15 10:07:55 -040053import android.text.TextUtils;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -080054import android.util.ArraySet;
Jason Monkd52356a2015-01-28 10:40:41 -050055import android.util.Log;
Jason Monkd52356a2015-01-28 10:40:41 -050056
Fan Zhangf7802ea2018-08-28 15:15:19 -070057import androidx.annotation.NonNull;
58
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -080059import com.android.internal.annotations.VisibleForTesting;
Jason Monkd52356a2015-01-28 10:40:41 -050060import com.android.settingslib.R;
Sundeep Ghumanbb399912018-01-29 18:31:15 -080061import com.android.settingslib.utils.ThreadUtils;
Jason Monkd52356a2015-01-28 10:40:41 -050062
Sundeep Ghuman53200ed2017-06-21 16:54:36 -070063import java.lang.annotation.Retention;
64import java.lang.annotation.RetentionPolicy;
Vinit Deshpandefcd46122015-06-11 18:22:23 -070065import java.util.ArrayList;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -080066import java.util.Collection;
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -070067import java.util.HashMap;
Mitchell Wills18af4932016-08-10 13:49:21 -070068import java.util.Iterator;
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -070069import java.util.Map;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -080070import java.util.Set;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -070071import java.util.concurrent.atomic.AtomicInteger;
Jason Monkd52356a2015-01-28 10:40:41 -050072
Sundeep Ghumanbb399912018-01-29 18:31:15 -080073/**
74 * Represents a selectable Wifi Network for use in various wifi selection menus backed by
75 * {@link WifiTracker}.
76 *
77 * <p>An AccessPoint, which would be more fittingly named "WifiNetwork", is an aggregation of
78 * {@link ScanResult ScanResults} along with pertinent metadata (e.g. current connection info,
79 * network scores) required to successfully render the network to the user.
80 */
Jason Monkd52356a2015-01-28 10:40:41 -050081public class AccessPoint implements Comparable<AccessPoint> {
82 static final String TAG = "SettingsLib.AccessPoint";
83
84 /**
85 * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels
86 */
87 public static final int LOWER_FREQ_24GHZ = 2400;
88
89 /**
90 * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels
91 */
92 public static final int HIGHER_FREQ_24GHZ = 2500;
93
94 /**
95 * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
96 */
97 public static final int LOWER_FREQ_5GHZ = 4900;
98
99 /**
100 * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
101 */
102 public static final int HIGHER_FREQ_5GHZ = 5900;
103
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800104 /** The key which identifies this AccessPoint grouping. */
105 private String mKey;
106
Sundeep Ghuman53200ed2017-06-21 16:54:36 -0700107 @IntDef({Speed.NONE, Speed.SLOW, Speed.MODERATE, Speed.FAST, Speed.VERY_FAST})
108 @Retention(RetentionPolicy.SOURCE)
109 public @interface Speed {
110 /**
111 * Constant value representing an unlabeled / unscored network.
112 */
113 int NONE = 0;
114 /**
115 * Constant value representing a slow speed network connection.
116 */
117 int SLOW = 5;
118 /**
119 * Constant value representing a medium speed network connection.
120 */
121 int MODERATE = 10;
122 /**
123 * Constant value representing a fast speed network connection.
124 */
125 int FAST = 20;
126 /**
127 * Constant value representing a very fast speed network connection.
128 */
129 int VERY_FAST = 30;
130 }
Jason Monkd52356a2015-01-28 10:40:41 -0500131
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800132 /** The underlying set of scan results comprising this AccessPoint. */
133 private final ArraySet<ScanResult> mScanResults = new ArraySet<>();
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700134
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700135 /**
136 * Map of BSSIDs to scored networks for individual bssids.
137 *
138 * <p>This cache should not be evicted with scan results, as the values here are used to
139 * generate a fallback in the absence of scores for the visible APs.
140 */
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700141 private final Map<String, TimestampedScoredNetwork> mScoredNetworkCache = new HashMap<>();
142
Dave Schaefer98537432017-02-08 11:26:08 -0800143 static final String KEY_NETWORKINFO = "key_networkinfo";
144 static final String KEY_WIFIINFO = "key_wifiinfo";
Dave Schaefer98537432017-02-08 11:26:08 -0800145 static final String KEY_SSID = "key_ssid";
146 static final String KEY_SECURITY = "key_security";
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700147 static final String KEY_SPEED = "key_speed";
Dave Schaefer98537432017-02-08 11:26:08 -0800148 static final String KEY_PSKTYPE = "key_psktype";
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800149 static final String KEY_SCANRESULTS = "key_scanresults";
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700150 static final String KEY_SCOREDNETWORKCACHE = "key_scorednetworkcache";
Dave Schaefer98537432017-02-08 11:26:08 -0800151 static final String KEY_CONFIG = "key_config";
Peter Qiuced37db2017-03-14 15:51:22 -0700152 static final String KEY_FQDN = "key_fqdn";
153 static final String KEY_PROVIDER_FRIENDLY_NAME = "key_provider_friendly_name";
Peter Qiu280581b2017-07-24 14:18:56 -0700154 static final String KEY_IS_CARRIER_AP = "key_is_carrier_ap";
155 static final String KEY_CARRIER_AP_EAP_TYPE = "key_carrier_ap_eap_type";
156 static final String KEY_CARRIER_NAME = "key_carrier_name";
Dave Schaefer98537432017-02-08 11:26:08 -0800157 static final AtomicInteger sLastId = new AtomicInteger(0);
Jason Monkd52356a2015-01-28 10:40:41 -0500158
Maurice Lam7cdbe192018-11-13 13:52:50 -0800159 /*
160 * NOTE: These constants for security and PSK types are saved to the bundle in saveWifiState,
161 * and sent across IPC. The numeric values should remain stable, otherwise the changes will need
162 * to be synced with other unbundled users of this library.
Jason Monkd52356a2015-01-28 10:40:41 -0500163 */
164 public static final int SECURITY_NONE = 0;
Hai Shalom9effa642018-11-12 11:43:52 -0800165 public static final int SECURITY_WEP = 1;
166 public static final int SECURITY_PSK = 2;
167 public static final int SECURITY_EAP = 3;
168 public static final int SECURITY_OWE = 4;
169 public static final int SECURITY_SAE = 5;
Hai Shalomaa6f9202018-10-16 14:30:02 -0700170 public static final int SECURITY_EAP_SUITE_B = 6;
Hai Shalom828b13c2018-11-13 16:43:14 -0800171 public static final int SECURITY_MAX_VAL = 7; // Has to be the last
Jason Monkd52356a2015-01-28 10:40:41 -0500172
173 private static final int PSK_UNKNOWN = 0;
174 private static final int PSK_WPA = 1;
175 private static final int PSK_WPA2 = 2;
176 private static final int PSK_WPA_WPA2 = 3;
177
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700178 /**
179 * The number of distinct wifi levels.
180 *
181 * <p>Must keep in sync with {@link R.array.wifi_signal} and {@link WifiManager#RSSI_LEVELS}.
182 */
183 public static final int SIGNAL_LEVELS = 5;
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800184
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700185 public static final int UNREACHABLE_RSSI = Integer.MIN_VALUE;
Dave Schaefer98537432017-02-08 11:26:08 -0800186
Quang Luong9051dfd2018-12-12 12:49:24 -0800187 public static final String KEY_PREFIX_AP = "AP:";
188 public static final String KEY_PREFIX_FQDN = "FQDN:";
189 public static final String KEY_PREFIX_OSU = "OSU:";
190
Jason Monkd52356a2015-01-28 10:40:41 -0500191 private final Context mContext;
192
193 private String ssid;
Jason Monk60a82ff2016-02-25 13:55:03 -0500194 private String bssid;
Jason Monkd52356a2015-01-28 10:40:41 -0500195 private int security;
196 private int networkId = WifiConfiguration.INVALID_NETWORK_ID;
197
198 private int pskType = PSK_UNKNOWN;
199
200 private WifiConfiguration mConfig;
Jason Monkd52356a2015-01-28 10:40:41 -0500201
Dave Schaefer98537432017-02-08 11:26:08 -0800202 private int mRssi = UNREACHABLE_RSSI;
Jason Monkd52356a2015-01-28 10:40:41 -0500203
204 private WifiInfo mInfo;
205 private NetworkInfo mNetworkInfo;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700206 AccessPointListener mAccessPointListener;
Jason Monkd52356a2015-01-28 10:40:41 -0500207
208 private Object mTag;
209
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700210 @Speed private int mSpeed = Speed.NONE;
Stephen Chen21f68682017-04-04 13:23:31 -0700211 private boolean mIsScoredNetworkMetered = false;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800212
Peter Qiuced37db2017-03-14 15:51:22 -0700213 /**
214 * Information associated with the {@link PasspointConfiguration}. Only maintaining
215 * the relevant info to preserve spaces.
216 */
217 private String mFqdn;
218 private String mProviderFriendlyName;
219
Peter Qiu280581b2017-07-24 14:18:56 -0700220 private boolean mIsCarrierAp = false;
Quang Luong9051dfd2018-12-12 12:49:24 -0800221
222 private OsuProvider mOsuProvider;
Quang Luong8d40a8e2019-01-02 16:25:38 -0800223
224 private String mOsuStatus;
225 private String mOsuFailure;
226 private boolean mOsuProvisioningComplete = false;
227
Peter Qiu280581b2017-07-24 14:18:56 -0700228 /**
229 * The EAP type {@link WifiEnterpriseConfig.Eap} associated with this AP if it is a carrier AP.
230 */
231 private int mCarrierApEapType = WifiEnterpriseConfig.Eap.NONE;
232 private String mCarrierName = null;
233
Jason Monkd52356a2015-01-28 10:40:41 -0500234 public AccessPoint(Context context, Bundle savedState) {
235 mContext = context;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800236
237 if (savedState.containsKey(KEY_CONFIG)) {
238 mConfig = savedState.getParcelable(KEY_CONFIG);
239 }
Jason Monkd52356a2015-01-28 10:40:41 -0500240 if (mConfig != null) {
241 loadConfig(mConfig);
242 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700243 if (savedState.containsKey(KEY_SSID)) {
244 ssid = savedState.getString(KEY_SSID);
245 }
246 if (savedState.containsKey(KEY_SECURITY)) {
247 security = savedState.getInt(KEY_SECURITY);
248 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700249 if (savedState.containsKey(KEY_SPEED)) {
250 mSpeed = savedState.getInt(KEY_SPEED);
251 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700252 if (savedState.containsKey(KEY_PSKTYPE)) {
253 pskType = savedState.getInt(KEY_PSKTYPE);
Jason Monkd52356a2015-01-28 10:40:41 -0500254 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700255 mInfo = savedState.getParcelable(KEY_WIFIINFO);
Jason Monkd52356a2015-01-28 10:40:41 -0500256 if (savedState.containsKey(KEY_NETWORKINFO)) {
257 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
258 }
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800259 if (savedState.containsKey(KEY_SCANRESULTS)) {
260 Parcelable[] scanResults = savedState.getParcelableArray(KEY_SCANRESULTS);
261 mScanResults.clear();
262 for (Parcelable result : scanResults) {
263 mScanResults.add((ScanResult) result);
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700264 }
265 }
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700266 if (savedState.containsKey(KEY_SCOREDNETWORKCACHE)) {
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700267 ArrayList<TimestampedScoredNetwork> scoredNetworkArrayList =
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700268 savedState.getParcelableArrayList(KEY_SCOREDNETWORKCACHE);
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700269 for (TimestampedScoredNetwork timedScore : scoredNetworkArrayList) {
270 mScoredNetworkCache.put(timedScore.getScore().networkKey.wifiKey.bssid, timedScore);
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700271 }
272 }
Peter Qiuced37db2017-03-14 15:51:22 -0700273 if (savedState.containsKey(KEY_FQDN)) {
274 mFqdn = savedState.getString(KEY_FQDN);
275 }
276 if (savedState.containsKey(KEY_PROVIDER_FRIENDLY_NAME)) {
277 mProviderFriendlyName = savedState.getString(KEY_PROVIDER_FRIENDLY_NAME);
278 }
Peter Qiu280581b2017-07-24 14:18:56 -0700279 if (savedState.containsKey(KEY_IS_CARRIER_AP)) {
280 mIsCarrierAp = savedState.getBoolean(KEY_IS_CARRIER_AP);
281 }
282 if (savedState.containsKey(KEY_CARRIER_AP_EAP_TYPE)) {
283 mCarrierApEapType = savedState.getInt(KEY_CARRIER_AP_EAP_TYPE);
284 }
285 if (savedState.containsKey(KEY_CARRIER_NAME)) {
286 mCarrierName = savedState.getString(KEY_CARRIER_NAME);
287 }
Mitchell Wills5a42db22015-08-03 09:46:08 -0700288 update(mConfig, mInfo, mNetworkInfo);
Sundeep Ghumand1e44922017-08-07 11:21:38 -0700289
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800290 // Calculate required fields
291 updateKey();
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800292 updateRssi();
Jason Monkd52356a2015-01-28 10:40:41 -0500293 }
294
Quang Luong9051dfd2018-12-12 12:49:24 -0800295 /**
296 * Creates an AccessPoint with only a WifiConfiguration. This is used for the saved networks
297 * page.
298 *
299 * Passpoint Credential AccessPoints should be created with this.
300 * Make sure to call setScanResults after constructing with this.
301 */
Peter Qiuced37db2017-03-14 15:51:22 -0700302 public AccessPoint(Context context, WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500303 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700304 loadConfig(config);
Jason Monkd52356a2015-01-28 10:40:41 -0500305 }
306
Peter Qiuced37db2017-03-14 15:51:22 -0700307 /**
308 * Initialize an AccessPoint object for a {@link PasspointConfiguration}. This is mainly
309 * used by "Saved Networks" page for managing the saved {@link PasspointConfiguration}.
310 */
311 public AccessPoint(Context context, PasspointConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500312 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700313 mFqdn = config.getHomeSp().getFqdn();
314 mProviderFriendlyName = config.getHomeSp().getFriendlyName();
Quang Luong9051dfd2018-12-12 12:49:24 -0800315 }
316
317 /**
318 * Initialize an AccessPoint object for a Passpoint OSU Provider.
319 * Make sure to call setScanResults after constructing with this.
320 */
321 public AccessPoint(Context context, OsuProvider provider) {
322 mContext = context;
323 mOsuProvider = provider;
Quang Luong550f7d42019-01-09 17:07:19 -0800324 ssid = provider.getFriendlyName();
Quang Luong9051dfd2018-12-12 12:49:24 -0800325 updateKey();
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700326 }
327
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800328 AccessPoint(Context context, Collection<ScanResult> results) {
Peter Qiuced37db2017-03-14 15:51:22 -0700329 mContext = context;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800330
331 if (results.isEmpty()) {
332 throw new IllegalArgumentException("Cannot construct with an empty ScanResult list");
333 }
334 mScanResults.addAll(results);
335
336 // Information derived from scan results
337 ScanResult firstResult = results.iterator().next();
338 ssid = firstResult.SSID;
339 bssid = firstResult.BSSID;
340 security = getSecurity(firstResult);
341 if (security == SECURITY_PSK) {
342 pskType = getPskType(firstResult);
343 }
344 updateKey();
345 updateRssi();
346
347 // Passpoint Info
348 mIsCarrierAp = firstResult.isCarrierAp;
349 mCarrierApEapType = firstResult.carrierApEapType;
350 mCarrierName = firstResult.carrierName;
Peter Qiuced37db2017-03-14 15:51:22 -0700351 }
352
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800353 @VisibleForTesting void loadConfig(WifiConfiguration config) {
354 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
355 bssid = config.BSSID;
356 security = getSecurity(config);
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800357 networkId = config.networkId;
358 mConfig = config;
Quang Luong7054e922018-12-07 16:44:18 -0800359 updateKey();
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800360 }
361
362 /** Updates {@link #mKey} and should only called upon object creation/initialization. */
363 private void updateKey() {
364 // TODO(sghuman): Consolidate Key logic on ScanResultMatchInfo
Quang Luong7054e922018-12-07 16:44:18 -0800365 if (isPasspoint()) {
Quang Luongac1026e2019-01-02 17:37:01 -0800366 mKey = getKey(mConfig);
Quang Luong9051dfd2018-12-12 12:49:24 -0800367 } else if (isOsuProvider()) {
Quang Luongac1026e2019-01-02 17:37:01 -0800368 mKey = getKey(mOsuProvider);
Quang Luong9051dfd2018-12-12 12:49:24 -0800369 } else { // Non-Passpoint AP
Quang Luongac1026e2019-01-02 17:37:01 -0800370 mKey = getKey(getSsidStr(), getBssid(), getSecurity());
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800371 }
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800372 }
373
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700374 /**
Dave Schaefer98537432017-02-08 11:26:08 -0800375 * Returns a negative integer, zero, or a positive integer if this AccessPoint is less than,
376 * equal to, or greater than the other AccessPoint.
377 *
378 * Sort order rules for AccessPoints:
379 * 1. Active before inactive
380 * 2. Reachable before unreachable
381 * 3. Saved before unsaved
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700382 * 4. Network speed value
Dave Schaefer98537432017-02-08 11:26:08 -0800383 * 5. Stronger signal before weaker signal
384 * 6. SSID alphabetically
385 *
386 * Note that AccessPoints with a signal are usually also Reachable,
387 * and will thus appear before unreachable saved AccessPoints.
388 */
Jason Monkd52356a2015-01-28 10:40:41 -0500389 @Override
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800390 public int compareTo(@NonNull AccessPoint other) {
Jason Monkd52356a2015-01-28 10:40:41 -0500391 // Active one goes first.
392 if (isActive() && !other.isActive()) return -1;
393 if (!isActive() && other.isActive()) return 1;
394
395 // Reachable one goes before unreachable one.
Dave Schaefer98537432017-02-08 11:26:08 -0800396 if (isReachable() && !other.isReachable()) return -1;
397 if (!isReachable() && other.isReachable()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500398
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800399 // Configured (saved) one goes before unconfigured one.
Dave Schaefer98537432017-02-08 11:26:08 -0800400 if (isSaved() && !other.isSaved()) return -1;
401 if (!isSaved() && other.isSaved()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500402
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700403 // Faster speeds go before slower speeds - but only if visible change in speed label
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700404 if (getSpeed() != other.getSpeed()) {
405 return other.getSpeed() - getSpeed();
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800406 }
407
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800408 // Sort by signal strength, bucketed by level
409 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS)
410 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500411 if (difference != 0) {
412 return difference;
413 }
Sundeep Ghumand44b8e42017-06-21 21:40:06 -0700414
Quang Luong9051dfd2018-12-12 12:49:24 -0800415 // Sort by title.
416 difference = getTitle().compareToIgnoreCase(other.getTitle());
Sundeep Ghumand44b8e42017-06-21 21:40:06 -0700417 if (difference != 0) {
418 return difference;
419 }
420
421 // Do a case sensitive comparison to distinguish SSIDs that differ in case only
422 return getSsidStr().compareTo(other.getSsidStr());
Jason Monkd52356a2015-01-28 10:40:41 -0500423 }
424
425 @Override
426 public boolean equals(Object other) {
427 if (!(other instanceof AccessPoint)) return false;
428 return (this.compareTo((AccessPoint) other) == 0);
429 }
430
431 @Override
432 public int hashCode() {
433 int result = 0;
434 if (mInfo != null) result += 13 * mInfo.hashCode();
435 result += 19 * mRssi;
436 result += 23 * networkId;
437 result += 29 * ssid.hashCode();
438 return result;
439 }
440
441 @Override
442 public String toString() {
443 StringBuilder builder = new StringBuilder().append("AccessPoint(")
444 .append(ssid);
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800445 if (bssid != null) {
446 builder.append(":").append(bssid);
447 }
Jason Monkd52356a2015-01-28 10:40:41 -0500448 if (isSaved()) {
449 builder.append(',').append("saved");
450 }
451 if (isActive()) {
452 builder.append(',').append("active");
453 }
454 if (isEphemeral()) {
455 builder.append(',').append("ephemeral");
456 }
457 if (isConnectable()) {
458 builder.append(',').append("connectable");
459 }
Hai Shalomaa6f9202018-10-16 14:30:02 -0700460 if ((security != SECURITY_NONE) && (security != SECURITY_OWE)) {
Jason Monkd52356a2015-01-28 10:40:41 -0500461 builder.append(',').append(securityToString(security, pskType));
462 }
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800463 builder.append(",level=").append(getLevel());
Sundeep Ghuman53200ed2017-06-21 16:54:36 -0700464 if (mSpeed != Speed.NONE) {
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700465 builder.append(",speed=").append(mSpeed);
Sundeep Ghuman8920e9c2017-04-27 16:16:41 -0700466 }
Stephen Chen21f68682017-04-04 13:23:31 -0700467 builder.append(",metered=").append(isMetered());
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800468
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -0800469 if (isVerboseLoggingEnabled()) {
Sundeep Ghumandb9b94c2017-09-06 11:46:21 -0700470 builder.append(",rssi=").append(mRssi);
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800471 builder.append(",scan cache size=").append(mScanResults.size());
Sundeep Ghumandb9b94c2017-09-06 11:46:21 -0700472 }
473
Jason Monkd52356a2015-01-28 10:40:41 -0500474 return builder.append(')').toString();
475 }
476
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800477 /**
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700478 * Updates the AccessPoint rankingScore, metering, and speed, returning true if the data has
Stephen Chen21f68682017-04-04 13:23:31 -0700479 * changed.
480 *
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700481 * @param scoreCache The score cache to use to retrieve scores
482 * @param scoringUiEnabled Whether to show scoring and badging UI
483 * @param maxScoreCacheAgeMillis the maximum age in milliseconds of scores to consider when
484 * generating speed labels
Stephen Chen21f68682017-04-04 13:23:31 -0700485 */
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700486 boolean update(
487 WifiNetworkScoreCache scoreCache,
488 boolean scoringUiEnabled,
489 long maxScoreCacheAgeMillis) {
Stephen Chen21f68682017-04-04 13:23:31 -0700490 boolean scoreChanged = false;
491 if (scoringUiEnabled) {
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700492 scoreChanged = updateScores(scoreCache, maxScoreCacheAgeMillis);
Stephen Chen21f68682017-04-04 13:23:31 -0700493 }
494 return updateMetered(scoreCache) || scoreChanged;
495 }
496
497 /**
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700498 * Updates the AccessPoint rankingScore and speed, returning true if the data has changed.
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800499 *
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700500 * <p>Any cached {@link TimestampedScoredNetwork} objects older than the given max age in millis
501 * will be removed when this method is invoked.
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700502 *
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700503 * <p>Precondition: {@link #mRssi} is up to date before invoking this method.
504 *
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700505 * @param scoreCache The score cache to use to retrieve scores
506 * @param maxScoreCacheAgeMillis the maximum age in milliseconds of scores to consider when
507 * generating speed labels
508 *
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700509 * @return true if the set speed has changed
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800510 */
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700511 private boolean updateScores(WifiNetworkScoreCache scoreCache, long maxScoreCacheAgeMillis) {
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700512 long nowMillis = SystemClock.elapsedRealtime();
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800513 for (ScanResult result : mScanResults) {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700514 ScoredNetwork score = scoreCache.getScoredNetwork(result);
515 if (score == null) {
516 continue;
517 }
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700518 TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(result.BSSID);
519 if (timedScore == null) {
520 mScoredNetworkCache.put(
521 result.BSSID, new TimestampedScoredNetwork(score, nowMillis));
522 } else {
523 // Update data since the has been seen in the score cache
524 timedScore.update(score, nowMillis);
525 }
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700526 }
527
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700528 // Remove old cached networks
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700529 long evictionCutoff = nowMillis - maxScoreCacheAgeMillis;
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700530 Iterator<TimestampedScoredNetwork> iterator = mScoredNetworkCache.values().iterator();
531 iterator.forEachRemaining(timestampedScoredNetwork -> {
532 if (timestampedScoredNetwork.getUpdatedTimestampMillis() < evictionCutoff) {
533 iterator.remove();
534 }
535 });
536
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700537 return updateSpeed();
538 }
539
540 /**
541 * Updates the internal speed, returning true if the update resulted in a speed label change.
542 */
543 private boolean updateSpeed() {
544 int oldSpeed = mSpeed;
545 mSpeed = generateAverageSpeedForSsid();
546
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700547 boolean changed = oldSpeed != mSpeed;
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -0800548 if(isVerboseLoggingEnabled() && changed) {
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700549 Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed));
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800550 }
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700551 return changed;
552 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800553
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700554 /** Creates a speed value for the current {@link #mRssi} by averaging all non zero badges. */
555 @Speed private int generateAverageSpeedForSsid() {
556 if (mScoredNetworkCache.isEmpty()) {
557 return Speed.NONE;
558 }
559
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700560 if (Log.isLoggable(TAG, Log.DEBUG)) {
561 Log.d(TAG, String.format("Generating fallbackspeed for %s using cache: %s",
562 getSsidStr(), mScoredNetworkCache));
563 }
564
Sundeep Ghumana7825692017-08-23 15:53:00 -0700565 // TODO(b/63073866): If flickering issues persist, consider mapping using getLevel rather
566 // than specific rssi value so score doesn't change without a visible wifi bar change. This
567 // issue is likely to be more evident for the active AP whose RSSI value is not half-lifed.
568
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700569 int count = 0;
570 int totalSpeed = 0;
571 for (TimestampedScoredNetwork timedScore : mScoredNetworkCache.values()) {
572 int speed = timedScore.getScore().calculateBadge(mRssi);
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700573 if (speed != Speed.NONE) {
574 count++;
575 totalSpeed += speed;
576 }
577 }
578 int speed = count == 0 ? Speed.NONE : totalSpeed / count;
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -0800579 if (isVerboseLoggingEnabled()) {
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700580 Log.i(TAG, String.format("%s generated fallback speed is: %d", getSsidStr(), speed));
581 }
582 return roundToClosestSpeedEnum(speed);
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800583 }
584
Stephen Chen21f68682017-04-04 13:23:31 -0700585 /**
586 * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning
587 * true if the metering changed.
588 */
589 private boolean updateMetered(WifiNetworkScoreCache scoreCache) {
590 boolean oldMetering = mIsScoredNetworkMetered;
591 mIsScoredNetworkMetered = false;
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700592
593 if (isActive() && mInfo != null) {
Eric Schwarzenbach733ea262017-08-08 10:28:21 -0700594 NetworkKey key = NetworkKey.createFromWifiInfo(mInfo);
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700595 ScoredNetwork score = scoreCache.getScoredNetwork(key);
596 if (score != null) {
597 mIsScoredNetworkMetered |= score.meteredHint;
Stephen Chen21f68682017-04-04 13:23:31 -0700598 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700599 } else {
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800600 for (ScanResult result : mScanResults) {
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700601 ScoredNetwork score = scoreCache.getScoredNetwork(result);
602 if (score == null) {
603 continue;
604 }
605 mIsScoredNetworkMetered |= score.meteredHint;
606 }
Stephen Chen21f68682017-04-04 13:23:31 -0700607 }
608 return oldMetering == mIsScoredNetworkMetered;
609 }
610
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800611 public static String getKey(ScanResult result) {
Quang Luongac1026e2019-01-02 17:37:01 -0800612 return getKey(result.SSID, result.BSSID, getSecurity(result));
Mitchell Wills18af4932016-08-10 13:49:21 -0700613 }
614
Quang Luongac1026e2019-01-02 17:37:01 -0800615 /**
616 * Returns the AccessPoint key for a WifiConfiguration.
617 * This will return a special Passpoint key if the config is for Passpoint.
618 */
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800619 public static String getKey(WifiConfiguration config) {
Quang Luong7054e922018-12-07 16:44:18 -0800620 if (config.isPasspoint()) {
Quang Luongac1026e2019-01-02 17:37:01 -0800621 return new StringBuilder()
622 .append(KEY_PREFIX_FQDN)
623 .append(config.FQDN).toString();
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800624 } else {
Quang Luongc2c947c2019-01-18 12:51:35 -0800625 return getKey(removeDoubleQuotes(config.SSID), config.BSSID, getSecurity(config));
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800626 }
Quang Luongac1026e2019-01-02 17:37:01 -0800627 }
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800628
Quang Luongac1026e2019-01-02 17:37:01 -0800629 /**
630 * Returns the AccessPoint key corresponding to the OsuProvider.
631 */
632 public static String getKey(OsuProvider provider) {
633 return new StringBuilder()
634 .append(KEY_PREFIX_OSU)
Quang Luong1a8fece2019-01-11 14:58:14 -0800635 .append(provider.getFriendlyName())
Quang Luongac1026e2019-01-02 17:37:01 -0800636 .append(',')
637 .append(provider.getServerUri()).toString();
638 }
639
640 /**
641 * Returns the AccessPoint key for a normal non-Passpoint network by ssid/bssid and security.
642 */
643 private static String getKey(String ssid, String bssid, int security) {
644 StringBuilder builder = new StringBuilder();
645 builder.append(KEY_PREFIX_AP);
646 if (TextUtils.isEmpty(ssid)) {
647 builder.append(bssid);
648 } else {
649 builder.append(ssid);
650 }
651 builder.append(',').append(security);
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800652 return builder.toString();
653 }
654
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800655 public String getKey() {
656 return mKey;
Jason Monkd52356a2015-01-28 10:40:41 -0500657 }
658
659 public boolean matches(WifiConfiguration config) {
Quang Luong7054e922018-12-07 16:44:18 -0800660 if (config.isPasspoint()) {
661 return (isPasspoint() && config.FQDN.equals(mConfig.FQDN));
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100662 } else {
Quang Luong7054e922018-12-07 16:44:18 -0800663 // Normal non-Passpoint network
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100664 return ssid.equals(removeDoubleQuotes(config.SSID))
665 && security == getSecurity(config)
666 && (mConfig == null || mConfig.shared == config.shared);
667 }
Jason Monkd52356a2015-01-28 10:40:41 -0500668 }
669
670 public WifiConfiguration getConfig() {
671 return mConfig;
672 }
673
Peter Qiuced37db2017-03-14 15:51:22 -0700674 public String getPasspointFqdn() {
675 return mFqdn;
676 }
677
Jason Monkd52356a2015-01-28 10:40:41 -0500678 public void clearConfig() {
679 mConfig = null;
680 networkId = WifiConfiguration.INVALID_NETWORK_ID;
681 }
682
683 public WifiInfo getInfo() {
684 return mInfo;
685 }
686
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700687 /**
688 * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1.
689 *
690 * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will
691 * always return at least 0.
692 */
Jason Monkd52356a2015-01-28 10:40:41 -0500693 public int getLevel() {
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800694 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500695 }
696
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700697 public int getRssi() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800698 return mRssi;
699 }
700
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800701 /**
702 * Returns the underlying scan result set.
703 *
704 * <p>Callers should not modify this set.
705 */
706 public Set<ScanResult> getScanResults() { return mScanResults; }
jackqdyulei9ee9b392017-12-22 11:31:49 -0800707
708 public Map<String, TimestampedScoredNetwork> getScoredNetworkCache() {
709 return mScoredNetworkCache;
710 }
711
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800712 /**
713 * Updates {@link #mRssi}.
714 *
715 * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned.
716 * If the given AccessPoint is not active, a value will be calculated from previous scan
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700717 * results, returning the best RSSI for all matching AccessPoints averaged with the previous
718 * value. If the access point is not connected and there are no scan results, the rssi will be
719 * set to {@link #UNREACHABLE_RSSI}.
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800720 */
721 private void updateRssi() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800722 if (this.isActive()) {
723 return;
724 }
725
726 int rssi = UNREACHABLE_RSSI;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800727 for (ScanResult result : mScanResults) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700728 if (result.level > rssi) {
729 rssi = result.level;
730 }
731 }
732
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700733 if (rssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
734 mRssi = (mRssi + rssi) / 2; // half-life previous value
735 } else {
736 mRssi = rssi;
737 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700738 }
739
Stephen Chen21f68682017-04-04 13:23:31 -0700740 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600741 * Returns if the network should be considered metered.
Stephen Chen21f68682017-04-04 13:23:31 -0700742 */
743 public boolean isMetered() {
744 return mIsScoredNetworkMetered
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600745 || WifiConfiguration.isMetered(mConfig, mInfo);
Stephen Chen21f68682017-04-04 13:23:31 -0700746 }
747
Jason Monkd52356a2015-01-28 10:40:41 -0500748 public NetworkInfo getNetworkInfo() {
749 return mNetworkInfo;
750 }
751
752 public int getSecurity() {
753 return security;
754 }
755
756 public String getSecurityString(boolean concise) {
757 Context context = mContext;
Tomoharu Hatano2bde6e72017-05-30 18:38:56 +0900758 if (isPasspoint() || isPasspointConfig()) {
Sanket Padawe194cce62015-07-10 10:53:31 -0700759 return concise ? context.getString(R.string.wifi_security_short_eap) :
760 context.getString(R.string.wifi_security_eap);
Sanket Padawed1878802015-05-12 10:27:19 -0700761 }
Jason Monkd52356a2015-01-28 10:40:41 -0500762 switch(security) {
763 case SECURITY_EAP:
764 return concise ? context.getString(R.string.wifi_security_short_eap) :
765 context.getString(R.string.wifi_security_eap);
Hai Shalomaa6f9202018-10-16 14:30:02 -0700766 case SECURITY_EAP_SUITE_B:
767 return concise ? context.getString(R.string.wifi_security_short_eap_suiteb) :
768 context.getString(R.string.wifi_security_eap_suiteb);
Jason Monkd52356a2015-01-28 10:40:41 -0500769 case SECURITY_PSK:
770 switch (pskType) {
771 case PSK_WPA:
772 return concise ? context.getString(R.string.wifi_security_short_wpa) :
773 context.getString(R.string.wifi_security_wpa);
774 case PSK_WPA2:
775 return concise ? context.getString(R.string.wifi_security_short_wpa2) :
776 context.getString(R.string.wifi_security_wpa2);
777 case PSK_WPA_WPA2:
778 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
779 context.getString(R.string.wifi_security_wpa_wpa2);
780 case PSK_UNKNOWN:
781 default:
782 return concise ? context.getString(R.string.wifi_security_short_psk_generic)
783 : context.getString(R.string.wifi_security_psk_generic);
784 }
785 case SECURITY_WEP:
786 return concise ? context.getString(R.string.wifi_security_short_wep) :
787 context.getString(R.string.wifi_security_wep);
Hai Shalomaa6f9202018-10-16 14:30:02 -0700788 case SECURITY_SAE:
789 return concise ? context.getString(R.string.wifi_security_short_sae) :
790 context.getString(R.string.wifi_security_sae);
791 case SECURITY_OWE:
792 return concise ? context.getString(R.string.wifi_security_short_owe) :
793 context.getString(R.string.wifi_security_owe);
Jason Monkd52356a2015-01-28 10:40:41 -0500794 case SECURITY_NONE:
795 default:
796 return concise ? "" : context.getString(R.string.wifi_security_none);
797 }
798 }
799
Jason Monk6980d122015-06-15 10:07:55 -0400800 public String getSsidStr() {
Jason Monkd52356a2015-01-28 10:40:41 -0500801 return ssid;
802 }
803
Jason Monk60a82ff2016-02-25 13:55:03 -0500804 public String getBssid() {
805 return bssid;
806 }
807
Jason Monk6980d122015-06-15 10:07:55 -0400808 public CharSequence getSsid() {
pastychanga2998fc2018-06-26 13:37:34 +0800809 return ssid;
Jason Monk6980d122015-06-15 10:07:55 -0400810 }
811
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700812 public String getConfigName() {
813 if (mConfig != null && mConfig.isPasspoint()) {
814 return mConfig.providerFriendlyName;
Peter Qiuced37db2017-03-14 15:51:22 -0700815 } else if (mFqdn != null) {
816 return mProviderFriendlyName;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700817 } else {
818 return ssid;
819 }
820 }
821
Jason Monkd52356a2015-01-28 10:40:41 -0500822 public DetailedState getDetailedState() {
Fan Zhang6acb7662016-10-17 12:40:03 -0700823 if (mNetworkInfo != null) {
824 return mNetworkInfo.getDetailedState();
825 }
826 Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
827 return null;
Jason Monkd52356a2015-01-28 10:40:41 -0500828 }
829
Peter Qiu280581b2017-07-24 14:18:56 -0700830 public boolean isCarrierAp() {
831 return mIsCarrierAp;
832 }
833
834 public int getCarrierApEapType() {
835 return mCarrierApEapType;
836 }
837
838 public String getCarrierName() {
839 return mCarrierName;
840 }
841
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700842 public String getSavedNetworkSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700843 WifiConfiguration config = mConfig;
844 if (config != null) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700845 PackageManager pm = mContext.getPackageManager();
846 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
Fan Zhang51365c32016-09-20 12:22:18 -0700847 int userId = UserHandle.getUserId(config.creatorUid);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700848 ApplicationInfo appInfo = null;
Fan Zhang51365c32016-09-20 12:22:18 -0700849 if (config.creatorName != null && config.creatorName.equals(systemName)) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700850 appInfo = mContext.getApplicationInfo();
851 } else {
852 try {
853 IPackageManager ipm = AppGlobals.getPackageManager();
Fan Zhang51365c32016-09-20 12:22:18 -0700854 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700855 } catch (RemoteException rex) {
856 }
857 }
858 if (appInfo != null &&
859 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
860 !appInfo.packageName.equals(
861 mContext.getString(R.string.certinstaller_package))) {
862 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
863 }
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700864 }
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700865 return "";
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700866 }
867
Quang Luong7054e922018-12-07 16:44:18 -0800868 /**
869 * Returns the display title for the AccessPoint, such as for an AccessPointPreference's title.
870 */
871 public String getTitle() {
872 if (isPasspoint()) {
873 return mConfig.providerFriendlyName;
Quang Luong9051dfd2018-12-12 12:49:24 -0800874 } else if (isOsuProvider()) {
875 return mOsuProvider.getFriendlyName();
Quang Luong7054e922018-12-07 16:44:18 -0800876 } else {
877 return getSsidStr();
878 }
879 }
880
Jason Monkd52356a2015-01-28 10:40:41 -0500881 public String getSummary() {
Quang Luong19bae88c2018-12-14 16:05:05 -0800882 return getSettingsSummary();
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700883 }
884
885 public String getSettingsSummary() {
Jason Monkd52356a2015-01-28 10:40:41 -0500886 // Update to new summary
887 StringBuilder summary = new StringBuilder();
888
Quang Luong919d4642019-01-03 14:46:06 -0800889 if (isOsuProvider()) {
890 if (mOsuProvisioningComplete) {
Quang Luongf005c882019-01-29 16:32:03 -0800891 summary.append(mContext.getString(R.string.osu_sign_up_complete));
Quang Luong919d4642019-01-03 14:46:06 -0800892 } else if (mOsuFailure != null) {
893 summary.append(mOsuFailure);
894 } else if (mOsuStatus != null) {
895 summary.append(mOsuStatus);
896 } else {
Quang Luongf005c882019-01-29 16:32:03 -0800897 summary.append(mContext.getString(R.string.tap_to_sign_up));
Quang Luong919d4642019-01-03 14:46:06 -0800898 }
899 } else if (isActive()) {
Quang Luong19bae88c2018-12-14 16:05:05 -0800900 if (isPasspoint()) {
901 // This is the active connection on passpoint
Quang Luong98d06bd2019-01-30 13:42:26 -0800902 summary.append(getSummary(mContext, /* ssid */ null, getDetailedState(),
903 /* isEphemeral */ false,
904 /* suggestionOrSpecifierPackageName */ null));
Quang Luong19bae88c2018-12-14 16:05:05 -0800905 } else if (mConfig != null && getDetailedState() == DetailedState.CONNECTED
906 && mIsCarrierAp) {
907 // This is the active connection on a carrier AP
908 summary.append(String.format(mContext.getString(R.string.connected_via_carrier),
909 mCarrierName));
910 } else {
911 // This is the active connection on non-passpoint network
Quang Luong98d06bd2019-01-30 13:42:26 -0800912 summary.append(getSummary(mContext, /* ssid */ null, getDetailedState(),
Roshan Piuse9b8e502019-01-23 15:42:44 -0800913 mInfo != null && mInfo.isEphemeral(),
914 mInfo != null ? mInfo.getNetworkSuggestionOrSpecifierPackageName() : null));
Jason Monkd52356a2015-01-28 10:40:41 -0500915 }
Quang Luong19bae88c2018-12-14 16:05:05 -0800916 } else { // not active
917 if (mConfig != null && mConfig.hasNoInternetAccess()) {
918 int messageID = mConfig.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
919 ? R.string.wifi_no_internet_no_reconnect
920 : R.string.wifi_no_internet;
921 summary.append(mContext.getString(messageID));
922 } else if (mConfig != null && !mConfig.getNetworkSelectionStatus().isNetworkEnabled()) {
923 WifiConfiguration.NetworkSelectionStatus networkStatus =
924 mConfig.getNetworkSelectionStatus();
925 switch (networkStatus.getNetworkSelectionDisableReason()) {
926 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
927 summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
Glen Kuhne446afac2017-06-22 16:02:33 -0700928 break;
Quang Luong19bae88c2018-12-14 16:05:05 -0800929 case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD:
930 summary.append(mContext.getString(R.string.wifi_check_password_try_again));
Glen Kuhne446afac2017-06-22 16:02:33 -0700931 break;
Quang Luong19bae88c2018-12-14 16:05:05 -0800932 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
933 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
934 summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
935 break;
936 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
937 summary.append(mContext.getString(R.string.wifi_disabled_generic));
938 break;
939 }
940 } else if (mConfig != null && mConfig.getNetworkSelectionStatus().isNotRecommended()) {
941 summary.append(mContext.getString(
942 R.string.wifi_disabled_by_recommendation_provider));
943 } else if (mIsCarrierAp) {
944 summary.append(String.format(mContext.getString(
945 R.string.available_via_carrier), mCarrierName));
946 } else if (!isReachable()) { // Wifi out of range
947 summary.append(mContext.getString(R.string.wifi_not_in_range));
948 } else { // In range, not disabled.
949 if (mConfig != null) { // Is saved network
950 // Last attempt to connect to this failed. Show reason why
951 switch (mConfig.recentFailure.getAssociationStatus()) {
952 case WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA:
953 summary.append(mContext.getString(
954 R.string.wifi_ap_unable_to_handle_new_sta));
955 break;
956 default:
957 // "Saved"
958 summary.append(mContext.getString(R.string.wifi_remembered));
959 break;
960 }
Glen Kuhne446afac2017-06-22 16:02:33 -0700961 }
Jason Monkd52356a2015-01-28 10:40:41 -0500962 }
963 }
964
Quang Luong19bae88c2018-12-14 16:05:05 -0800965
966
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -0800967 if (isVerboseLoggingEnabled()) {
Quang Luong19bae88c2018-12-14 16:05:05 -0800968 summary.append(WifiUtils.buildLoggingSummary(this, mConfig));
Jason Monkd52356a2015-01-28 10:40:41 -0500969 }
Sundeep Ghuman271e5de2017-05-30 14:11:39 -0700970
Quang Luong19bae88c2018-12-14 16:05:05 -0800971 if (mConfig != null && (WifiUtils.isMeteredOverridden(mConfig) || mConfig.meteredHint)) {
Salvador Martinez6f6fe752018-03-21 16:33:53 -0700972 return mContext.getResources().getString(
973 R.string.preference_summary_default_combination,
Quang Luong19bae88c2018-12-14 16:05:05 -0800974 WifiUtils.getMeteredLabel(mContext, mConfig),
Salvador Martinez6f6fe752018-03-21 16:33:53 -0700975 summary.toString());
976 }
977
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700978 // If Speed label and summary are both present, use the preference combination to combine
979 // the two, else return the non-null one.
980 if (getSpeedLabel() != null && summary.length() != 0) {
Sundeep Ghumand3171ca2017-07-12 23:02:24 -0700981 return mContext.getResources().getString(
982 R.string.preference_summary_default_combination,
983 getSpeedLabel(),
984 summary.toString());
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700985 } else if (getSpeedLabel() != null) {
986 return getSpeedLabel();
Sundeep Ghumand3171ca2017-07-12 23:02:24 -0700987 } else {
988 return summary.toString();
Sundeep Ghuman271e5de2017-05-30 14:11:39 -0700989 }
Jason Monkd52356a2015-01-28 10:40:41 -0500990 }
991
992 /**
Jason Monkd52356a2015-01-28 10:40:41 -0500993 * Return whether this is the active connection.
994 * For ephemeral connections (networkId is invalid), this returns false if the network is
995 * disconnected.
996 */
997 public boolean isActive() {
998 return mNetworkInfo != null &&
999 (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
1000 mNetworkInfo.getState() != State.DISCONNECTED);
1001 }
1002
1003 public boolean isConnectable() {
1004 return getLevel() != -1 && getDetailedState() == null;
1005 }
1006
1007 public boolean isEphemeral() {
Shirish Kalelec7a38ef2015-06-25 13:55:33 -07001008 return mInfo != null && mInfo.isEphemeral() &&
1009 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
Jason Monkd52356a2015-01-28 10:40:41 -05001010 }
1011
Peter Qiuced37db2017-03-14 15:51:22 -07001012 /**
1013 * Return true if this AccessPoint represents a Passpoint AP.
1014 */
Vinit Deshpande5b7352c2015-07-09 16:53:12 -07001015 public boolean isPasspoint() {
1016 return mConfig != null && mConfig.isPasspoint();
1017 }
1018
Mitchell Wills5a42db22015-08-03 09:46:08 -07001019 /**
Peter Qiuced37db2017-03-14 15:51:22 -07001020 * Return true if this AccessPoint represents a Passpoint provider configuration.
1021 */
1022 public boolean isPasspointConfig() {
1023 return mFqdn != null;
1024 }
1025
1026 /**
Quang Luong9051dfd2018-12-12 12:49:24 -08001027 * Return true if this AccessPoint represents an OSU Provider.
1028 */
1029 public boolean isOsuProvider() {
1030 return mOsuProvider != null;
1031 }
1032
1033 /**
Quang Luong4d194842018-12-18 16:59:49 -08001034 * Starts the OSU Provisioning flow.
1035 */
1036 public void startOsuProvisioning() {
1037 mContext.getSystemService(WifiManager.class).startSubscriptionProvisioning(
1038 mOsuProvider,
1039 new AccessPointProvisioningCallback(),
1040 ThreadUtils.getUiThreadHandler()
1041 );
1042 }
1043
1044 /**
Mitchell Wills5a42db22015-08-03 09:46:08 -07001045 * Return whether the given {@link WifiInfo} is for this access point.
1046 * If the current AP does not have a network Id then the config is used to
1047 * match based on SSID and security.
1048 */
1049 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
Quang Luong919d4642019-01-03 14:46:06 -08001050 if (info.isOsuAp()) {
1051 return (mOsuStatus != null);
1052 }
1053
Vinit Deshpande5b7352c2015-07-09 16:53:12 -07001054 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
Jason Monkd52356a2015-01-28 10:40:41 -05001055 return networkId == info.getNetworkId();
Mitchell Wills5a42db22015-08-03 09:46:08 -07001056 } else if (config != null) {
1057 return matches(config);
1058 }
1059 else {
Jason Monkd52356a2015-01-28 10:40:41 -05001060 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
1061 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
1062 // TODO: Handle hex string SSIDs.
1063 return ssid.equals(removeDoubleQuotes(info.getSSID()));
1064 }
1065 }
1066
1067 public boolean isSaved() {
Quang Luong48ad03a2019-02-14 11:51:01 -08001068 return mConfig != null;
Jason Monkd52356a2015-01-28 10:40:41 -05001069 }
1070
1071 public Object getTag() {
1072 return mTag;
1073 }
1074
1075 public void setTag(Object tag) {
1076 mTag = tag;
1077 }
1078
1079 /**
1080 * Generate and save a default wifiConfiguration with common values.
1081 * Can only be called for unsecured networks.
1082 */
1083 public void generateOpenNetworkConfig() {
Hai Shalomaa6f9202018-10-16 14:30:02 -07001084 if ((security != SECURITY_NONE) && (security != SECURITY_OWE)) {
Jason Monkd52356a2015-01-28 10:40:41 -05001085 throw new IllegalStateException();
Hai Shalomaa6f9202018-10-16 14:30:02 -07001086 }
Jason Monkd52356a2015-01-28 10:40:41 -05001087 if (mConfig != null)
1088 return;
1089 mConfig = new WifiConfiguration();
1090 mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
Hai Shalomaa6f9202018-10-16 14:30:02 -07001091
1092 if (security == SECURITY_NONE) {
1093 mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
1094 } else {
1095 mConfig.allowedKeyManagement.set(KeyMgmt.OWE);
1096 mConfig.requirePMF = true;
1097 }
Jason Monkd52356a2015-01-28 10:40:41 -05001098 }
1099
Jason Monkd52356a2015-01-28 10:40:41 -05001100 public void saveWifiState(Bundle savedState) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001101 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
1102 savedState.putInt(KEY_SECURITY, security);
Sundeep Ghumana28050a2017-07-12 22:09:25 -07001103 savedState.putInt(KEY_SPEED, mSpeed);
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001104 savedState.putInt(KEY_PSKTYPE, pskType);
1105 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
Jason Monkd52356a2015-01-28 10:40:41 -05001106 savedState.putParcelable(KEY_WIFIINFO, mInfo);
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001107 savedState.putParcelableArray(KEY_SCANRESULTS,
1108 mScanResults.toArray(new Parcelable[mScanResults.size()]));
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001109 savedState.putParcelableArrayList(KEY_SCOREDNETWORKCACHE,
1110 new ArrayList<>(mScoredNetworkCache.values()));
Jason Monkd52356a2015-01-28 10:40:41 -05001111 if (mNetworkInfo != null) {
1112 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1113 }
Peter Qiuced37db2017-03-14 15:51:22 -07001114 if (mFqdn != null) {
1115 savedState.putString(KEY_FQDN, mFqdn);
1116 }
1117 if (mProviderFriendlyName != null) {
1118 savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1119 }
Peter Qiu280581b2017-07-24 14:18:56 -07001120 savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp);
1121 savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType);
1122 savedState.putString(KEY_CARRIER_NAME, mCarrierName);
Jason Monkd52356a2015-01-28 10:40:41 -05001123 }
1124
1125 public void setListener(AccessPointListener listener) {
1126 mAccessPointListener = listener;
1127 }
1128
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001129 /**
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001130 * Sets {@link #mScanResults} to the given collection.
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001131 *
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001132 * @param scanResults a collection of scan results to add to the internal set
1133 * @throws IllegalArgumentException if any of the given ScanResults did not belong to this AP
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001134 */
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001135 void setScanResults(Collection<ScanResult> scanResults) {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001136
Quang Luong7054e922018-12-07 16:44:18 -08001137 // Validate scan results are for current AP only by matching SSID/BSSID
Quang Luong9051dfd2018-12-12 12:49:24 -08001138 // Passpoint networks are not bound to a specific SSID/BSSID, so skip this for passpoint.
1139 if (!isPasspoint() && !isOsuProvider()) {
Quang Luong7054e922018-12-07 16:44:18 -08001140 String key = getKey();
1141 for (ScanResult result : scanResults) {
1142 String scanResultKey = AccessPoint.getKey(result);
1143 if (!mKey.equals(scanResultKey)) {
1144 throw new IllegalArgumentException(
1145 String.format(
1146 "ScanResult %s\nkey of %s did not match current AP key %s",
1147 result, scanResultKey, key));
1148 }
Jason Monkd52356a2015-01-28 10:40:41 -05001149 }
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001150 }
1151
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001152 int oldLevel = getLevel();
1153 mScanResults.clear();
1154 mScanResults.addAll(scanResults);
1155 updateRssi();
1156 int newLevel = getLevel();
1157
1158 // If newLevel is 0, there will be no displayed Preference since the AP is unreachable
1159 if (newLevel > 0 && newLevel != oldLevel) {
1160 // Only update labels on visible rssi changes
1161 updateSpeed();
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001162 ThreadUtils.postOnMainThread(() -> {
1163 if (mAccessPointListener != null) {
1164 mAccessPointListener.onLevelChanged(this);
1165 }
1166 });
1167
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001168 }
1169
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001170 ThreadUtils.postOnMainThread(() -> {
1171 if (mAccessPointListener != null) {
1172 mAccessPointListener.onAccessPointChanged(this);
1173 }
1174 });
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001175
1176 if (!scanResults.isEmpty()) {
1177 ScanResult result = scanResults.iterator().next();
1178
Jason Monkd52356a2015-01-28 10:40:41 -05001179 // This flag only comes from scans, is not easily saved in config
1180 if (security == SECURITY_PSK) {
1181 pskType = getPskType(result);
1182 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001183
Peter Qiu280581b2017-07-24 14:18:56 -07001184 // The carrier info in the ScanResult is set by the platform based on the SSID and will
1185 // always be the same for all matching scan results.
1186 mIsCarrierAp = result.isCarrierAp;
1187 mCarrierApEapType = result.carrierApEapType;
1188 mCarrierName = result.carrierName;
Jason Monkd52356a2015-01-28 10:40:41 -05001189 }
Jason Monkd52356a2015-01-28 10:40:41 -05001190 }
1191
Quang Luong9051dfd2018-12-12 12:49:24 -08001192 /**
1193 * Attempt to update the AccessPoint with the current connection info.
1194 * This is used to set an AccessPoint to the active one if the connection info matches, or
1195 * conversely to set an AccessPoint to inactive if the connection info does not match. The RSSI
1196 * is also updated upon a match. Listeners will be notified if an update occurred.
1197 *
1198 * This is called in {@link WifiTracker#updateAccessPoints} as well as in callbacks for handling
1199 * NETWORK_STATE_CHANGED_ACTION, RSSI_CHANGED_ACTION, and onCapabilitiesChanged in WifiTracker.
1200 *
1201 * Returns true if an update occurred.
1202 */
Sundeep Ghumand911da32017-07-05 20:06:05 -07001203 public boolean update(
1204 @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
Sundeep Ghumandb9b94c2017-09-06 11:46:21 -07001205
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001206 boolean updated = false;
1207 final int oldLevel = getLevel();
Mitchell Wills5a42db22015-08-03 09:46:08 -07001208 if (info != null && isInfoForThisAccessPoint(config, info)) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001209 updated = (mInfo == null);
Sundeep Ghumanf4d33022017-06-05 19:47:36 -07001210 if (mConfig != config) {
1211 // We do not set updated = true as we do not want to increase the amount of sorting
1212 // and copying performed in WifiTracker at this time. If issues involving refresh
1213 // are still seen, we will investigate further.
1214 update(config); // Notifies the AccessPointListener of the change
1215 }
Glen Kuhned38708c2017-07-19 14:53:34 -07001216 if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001217 mRssi = info.getRssi();
1218 updated = true;
Sundeep Ghuman5c5cd7a2017-05-03 12:45:44 -07001219 } else if (mNetworkInfo != null && networkInfo != null
1220 && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
Sundeep Ghuman96a53572017-04-20 21:25:41 -07001221 updated = true;
Jason Monkd52356a2015-01-28 10:40:41 -05001222 }
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001223 mInfo = info;
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001224 mNetworkInfo = networkInfo;
Jason Monkd52356a2015-01-28 10:40:41 -05001225 } else if (mInfo != null) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001226 updated = true;
Jason Monkd52356a2015-01-28 10:40:41 -05001227 mInfo = null;
1228 mNetworkInfo = null;
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001229 }
1230 if (updated && mAccessPointListener != null) {
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001231 ThreadUtils.postOnMainThread(() -> {
1232 if (mAccessPointListener != null) {
1233 mAccessPointListener.onAccessPointChanged(this);
1234 }
1235 });
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001236
1237 if (oldLevel != getLevel() /* current level */) {
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001238 ThreadUtils.postOnMainThread(() -> {
1239 if (mAccessPointListener != null) {
1240 mAccessPointListener.onLevelChanged(this);
1241 }
1242 });
Jason Monkd52356a2015-01-28 10:40:41 -05001243 }
1244 }
Sundeep Ghumandb9b94c2017-09-06 11:46:21 -07001245
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001246 return updated;
Jason Monkd52356a2015-01-28 10:40:41 -05001247 }
1248
Sundeep Ghumand911da32017-07-05 20:06:05 -07001249 void update(@Nullable WifiConfiguration config) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001250 mConfig = config;
Quang Luong7054e922018-12-07 16:44:18 -08001251 if (mConfig != null) {
1252 ssid = removeDoubleQuotes(mConfig.SSID);
1253 }
Sundeep Ghumand911da32017-07-05 20:06:05 -07001254 networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID;
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001255 ThreadUtils.postOnMainThread(() -> {
1256 if (mAccessPointListener != null) {
1257 mAccessPointListener.onAccessPointChanged(this);
1258 }
1259 });
Vinit Deshpandefc406002015-04-15 18:10:55 -07001260 }
Shirish Kalelec7a38ef2015-06-25 13:55:33 -07001261
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001262 @VisibleForTesting
Sanket Padawe0775a982015-08-19 14:57:46 -07001263 void setRssi(int rssi) {
1264 mRssi = rssi;
1265 }
1266
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001267 /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1268 void setUnreachable() {
1269 setRssi(AccessPoint.UNREACHABLE_RSSI);
1270 }
1271
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -07001272 int getSpeed() { return mSpeed;}
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001273
1274 @Nullable
1275 String getSpeedLabel() {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001276 return getSpeedLabel(mSpeed);
1277 }
1278
1279 @Nullable
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001280 @Speed
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001281 private static int roundToClosestSpeedEnum(int speed) {
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001282 if (speed < Speed.SLOW) {
1283 return Speed.NONE;
1284 } else if (speed < (Speed.SLOW + Speed.MODERATE) / 2) {
1285 return Speed.SLOW;
1286 } else if (speed < (Speed.MODERATE + Speed.FAST) / 2) {
1287 return Speed.MODERATE;
1288 } else if (speed < (Speed.FAST + Speed.VERY_FAST) / 2) {
1289 return Speed.FAST;
1290 } else {
1291 return Speed.VERY_FAST;
1292 }
1293 }
1294
1295 @Nullable
jackqdyulei9ee9b392017-12-22 11:31:49 -08001296 String getSpeedLabel(@Speed int speed) {
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001297 return getSpeedLabel(mContext, speed);
1298 }
1299
1300 private static String getSpeedLabel(Context context, int speed) {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001301 switch (speed) {
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001302 case Speed.VERY_FAST:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001303 return context.getString(R.string.speed_label_very_fast);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001304 case Speed.FAST:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001305 return context.getString(R.string.speed_label_fast);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001306 case Speed.MODERATE:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001307 return context.getString(R.string.speed_label_okay);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001308 case Speed.SLOW:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001309 return context.getString(R.string.speed_label_slow);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001310 case Speed.NONE:
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001311 default:
1312 return null;
1313 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -08001314 }
1315
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001316 /** Return the speed label for a {@link ScoredNetwork} at the specified {@code rssi} level. */
1317 @Nullable
1318 public static String getSpeedLabel(Context context, ScoredNetwork scoredNetwork, int rssi) {
1319 return getSpeedLabel(context, roundToClosestSpeedEnum(scoredNetwork.calculateBadge(rssi)));
1320 }
1321
Dave Schaefer98537432017-02-08 11:26:08 -08001322 /** Return true if the current RSSI is reachable, and false otherwise. */
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -07001323 public boolean isReachable() {
Dave Schaefer98537432017-02-08 11:26:08 -08001324 return mRssi != UNREACHABLE_RSSI;
1325 }
1326
Roshan Piuse9b8e502019-01-23 15:42:44 -08001327 private static CharSequence getAppLabel(String packageName, PackageManager packageManager) {
1328 CharSequence appLabel = "";
1329 ApplicationInfo appInfo = null;
1330 try {
1331 int userId = UserHandle.getUserId(UserHandle.USER_CURRENT);
1332 appInfo = packageManager.getApplicationInfoAsUser(packageName, 0 /* flags */, userId);
1333 } catch (PackageManager.NameNotFoundException e) {
1334 Log.e(TAG, "Failed to get app info", e);
1335 return appLabel;
1336 }
1337 if (appInfo != null) {
1338 appLabel = appInfo.loadLabel(packageManager);
1339 }
1340 return appLabel;
1341 }
1342
Jason Monkd52356a2015-01-28 10:40:41 -05001343 public static String getSummary(Context context, String ssid, DetailedState state,
Quang Luong98d06bd2019-01-30 13:42:26 -08001344 boolean isEphemeral, String suggestionOrSpecifierPackageName) {
Quang Luong0a3edf02018-12-17 14:50:58 -08001345 if (state == DetailedState.CONNECTED) {
Quang Luong98d06bd2019-01-30 13:42:26 -08001346 if (isEphemeral && !TextUtils.isEmpty(suggestionOrSpecifierPackageName)) {
Roshan Piuse9b8e502019-01-23 15:42:44 -08001347 CharSequence appLabel =
1348 getAppLabel(suggestionOrSpecifierPackageName, context.getPackageManager());
1349 return context.getString(R.string.connected_via_app, appLabel);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001350 } else if (isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001351 // Special case for connected + ephemeral networks.
Stephen Chen36dd5cf12017-03-20 13:27:51 -07001352 final NetworkScoreManager networkScoreManager = context.getSystemService(
1353 NetworkScoreManager.class);
1354 NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1355 if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1356 String format = context.getString(R.string.connected_via_network_scorer);
1357 return String.format(format, scorer.getRecommendationServiceLabel());
1358 } else {
1359 return context.getString(R.string.connected_via_network_scorer_default);
1360 }
Vinit Deshpandefc406002015-04-15 18:10:55 -07001361 }
Jason Monkd52356a2015-01-28 10:40:41 -05001362 }
1363
Sanket Padawe7094d222015-05-01 16:55:00 -07001364 // Case when there is wifi connected without internet connectivity.
1365 final ConnectivityManager cm = (ConnectivityManager)
1366 context.getSystemService(Context.CONNECTIVITY_SERVICE);
1367 if (state == DetailedState.CONNECTED) {
1368 IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1369 ServiceManager.getService(Context.WIFI_SERVICE));
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001370 NetworkCapabilities nc = null;
Sanket Padawe7094d222015-05-01 16:55:00 -07001371
1372 try {
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001373 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1374 } catch (RemoteException e) {}
1375
1376 if (nc != null) {
1377 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
Maurice Lam7f6fc862017-07-12 16:43:49 -07001378 int id = context.getResources()
1379 .getIdentifier("network_available_sign_in", "string", "android");
1380 return context.getString(id);
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001381 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
1382 return context.getString(R.string.wifi_connected_no_internet);
1383 }
Sanket Padawe7094d222015-05-01 16:55:00 -07001384 }
1385 }
Fan Zhang6acb7662016-10-17 12:40:03 -07001386 if (state == null) {
1387 Log.w(TAG, "state is null, returning empty summary");
1388 return "";
1389 }
Jason Monkd52356a2015-01-28 10:40:41 -05001390 String[] formats = context.getResources().getStringArray((ssid == null)
1391 ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1392 int index = state.ordinal();
1393
1394 if (index >= formats.length || formats[index].length() == 0) {
Sanket Padawe3e9e5fa2015-05-28 10:41:14 -07001395 return "";
Jason Monkd52356a2015-01-28 10:40:41 -05001396 }
1397 return String.format(formats[index], ssid);
1398 }
1399
Jason Monkd52356a2015-01-28 10:40:41 -05001400 public static String convertToQuotedString(String string) {
1401 return "\"" + string + "\"";
1402 }
1403
1404 private static int getPskType(ScanResult result) {
1405 boolean wpa = result.capabilities.contains("WPA-PSK");
1406 boolean wpa2 = result.capabilities.contains("WPA2-PSK");
1407 if (wpa2 && wpa) {
1408 return PSK_WPA_WPA2;
1409 } else if (wpa2) {
1410 return PSK_WPA2;
1411 } else if (wpa) {
1412 return PSK_WPA;
1413 } else {
1414 Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1415 return PSK_UNKNOWN;
1416 }
1417 }
1418
1419 private static int getSecurity(ScanResult result) {
1420 if (result.capabilities.contains("WEP")) {
1421 return SECURITY_WEP;
Hai Shalomaa6f9202018-10-16 14:30:02 -07001422 } else if (result.capabilities.contains("SAE")) {
1423 return SECURITY_SAE;
Jason Monkd52356a2015-01-28 10:40:41 -05001424 } else if (result.capabilities.contains("PSK")) {
1425 return SECURITY_PSK;
Hai Shalomaa6f9202018-10-16 14:30:02 -07001426 } else if (result.capabilities.contains("EAP_SUITE_B_192")) {
1427 return SECURITY_EAP_SUITE_B;
Jason Monkd52356a2015-01-28 10:40:41 -05001428 } else if (result.capabilities.contains("EAP")) {
1429 return SECURITY_EAP;
Hai Shalomaa6f9202018-10-16 14:30:02 -07001430 } else if (result.capabilities.contains("OWE")) {
1431 return SECURITY_OWE;
Jason Monkd52356a2015-01-28 10:40:41 -05001432 }
Hai Shalomaa6f9202018-10-16 14:30:02 -07001433
Jason Monkd52356a2015-01-28 10:40:41 -05001434 return SECURITY_NONE;
1435 }
1436
1437 static int getSecurity(WifiConfiguration config) {
Hai Shalomaa6f9202018-10-16 14:30:02 -07001438 if (config.allowedKeyManagement.get(KeyMgmt.SAE)) {
1439 return SECURITY_SAE;
1440 }
Jason Monkd52356a2015-01-28 10:40:41 -05001441 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1442 return SECURITY_PSK;
1443 }
Hai Shalomaa6f9202018-10-16 14:30:02 -07001444 if (config.allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
1445 return SECURITY_EAP_SUITE_B;
1446 }
Jason Monkd52356a2015-01-28 10:40:41 -05001447 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1448 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1449 return SECURITY_EAP;
1450 }
Hai Shalomaa6f9202018-10-16 14:30:02 -07001451 if (config.allowedKeyManagement.get(KeyMgmt.OWE)) {
1452 return SECURITY_OWE;
1453 }
Jason Monkd52356a2015-01-28 10:40:41 -05001454 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1455 }
1456
1457 public static String securityToString(int security, int pskType) {
1458 if (security == SECURITY_WEP) {
1459 return "WEP";
1460 } else if (security == SECURITY_PSK) {
1461 if (pskType == PSK_WPA) {
1462 return "WPA";
1463 } else if (pskType == PSK_WPA2) {
1464 return "WPA2";
1465 } else if (pskType == PSK_WPA_WPA2) {
1466 return "WPA_WPA2";
1467 }
1468 return "PSK";
1469 } else if (security == SECURITY_EAP) {
1470 return "EAP";
Hai Shalomaa6f9202018-10-16 14:30:02 -07001471 } else if (security == SECURITY_SAE) {
1472 return "SAE";
1473 } else if (security == SECURITY_EAP_SUITE_B) {
1474 return "SUITE_B";
1475 } else if (security == SECURITY_OWE) {
1476 return "OWE";
Jason Monkd52356a2015-01-28 10:40:41 -05001477 }
1478 return "NONE";
1479 }
1480
1481 static String removeDoubleQuotes(String string) {
Jason Monk2b51cc32015-05-13 11:07:53 -04001482 if (TextUtils.isEmpty(string)) {
1483 return "";
1484 }
Jason Monkd52356a2015-01-28 10:40:41 -05001485 int length = string.length();
1486 if ((length > 1) && (string.charAt(0) == '"')
1487 && (string.charAt(length - 1) == '"')) {
1488 return string.substring(1, length - 1);
1489 }
1490 return string;
1491 }
1492
Sundeep Ghumanbb399912018-01-29 18:31:15 -08001493 /**
1494 * Callbacks relaying changes to the AccessPoint representation.
1495 *
1496 * <p>All methods are invoked on the Main Thread.
1497 */
Jason Monkd52356a2015-01-28 10:40:41 -05001498 public interface AccessPointListener {
Sundeep Ghumanbb399912018-01-29 18:31:15 -08001499 /**
1500 * Indicates a change to the externally visible state of the AccessPoint trigger by an
1501 * update of ScanResults, saved configuration state, connection state, or score
1502 * (labels/metered) state.
1503 *
1504 * <p>Clients should refresh their view of the AccessPoint to match the updated state when
1505 * this is invoked. Overall this method is extraneous if clients are listening to
1506 * {@link WifiTracker.WifiListener#onAccessPointsChanged()} callbacks.
1507 *
1508 * <p>Examples of changes include signal strength, connection state, speed label, and
1509 * generally anything that would impact the summary string.
1510 *
1511 * @param accessPoint The accessPoint object the listener was registered on which has
1512 * changed
1513 */
1514 @MainThread void onAccessPointChanged(AccessPoint accessPoint);
1515
1516 /**
1517 * Indicates the "wifi pie signal level" has changed, retrieved via calls to
1518 * {@link AccessPoint#getLevel()}.
1519 *
1520 * <p>This call is a subset of {@link #onAccessPointChanged(AccessPoint)} , hence is also
1521 * extraneous if the client is already reacting to that or the
1522 * {@link WifiTracker.WifiListener#onAccessPointsChanged()} callbacks.
1523 *
1524 * @param accessPoint The accessPoint object the listener was registered on whose level has
1525 * changed
1526 */
1527 @MainThread void onLevelChanged(AccessPoint accessPoint);
Jason Monkd52356a2015-01-28 10:40:41 -05001528 }
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -08001529
1530 private static boolean isVerboseLoggingEnabled() {
1531 return WifiTracker.sVerboseLogging || Log.isLoggable(TAG, Log.VERBOSE);
1532 }
Quang Luong4d194842018-12-18 16:59:49 -08001533
1534 /**
1535 * Callbacks relaying changes to the OSU provisioning status started in startOsuProvisioning().
1536 *
1537 * All methods are invoked on the Main Thread
1538 */
1539 private class AccessPointProvisioningCallback extends ProvisioningCallback {
Quang Luong4d194842018-12-18 16:59:49 -08001540 @Override
1541 @MainThread public void onProvisioningFailure(int status) {
Quang Luongf005c882019-01-29 16:32:03 -08001542 if (TextUtils.equals(mOsuStatus, mContext.getString(R.string.osu_completing_sign_up))) {
1543 mOsuFailure = mContext.getString(R.string.osu_sign_up_failed);
1544 } else {
1545 mOsuFailure = mContext.getString(R.string.osu_connect_failed);
Quang Luong8d40a8e2019-01-02 16:25:38 -08001546 }
1547 mOsuStatus = null;
1548 mOsuProvisioningComplete = false;
1549 ThreadUtils.postOnMainThread(() -> {
1550 if (mAccessPointListener != null) {
1551 mAccessPointListener.onAccessPointChanged(AccessPoint.this);
1552 }
1553 });
Quang Luong4d194842018-12-18 16:59:49 -08001554 }
1555
1556 @Override
1557 @MainThread public void onProvisioningStatus(int status) {
Quang Luongf005c882019-01-29 16:32:03 -08001558 String newStatus = null;
Quang Luong8d40a8e2019-01-02 16:25:38 -08001559 switch (status) {
1560 case OSU_STATUS_AP_CONNECTING:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001561 case OSU_STATUS_AP_CONNECTED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001562 case OSU_STATUS_SERVER_CONNECTING:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001563 case OSU_STATUS_SERVER_VALIDATED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001564 case OSU_STATUS_SERVER_CONNECTED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001565 case OSU_STATUS_INIT_SOAP_EXCHANGE:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001566 case OSU_STATUS_WAITING_FOR_REDIRECT_RESPONSE:
Quang Luongf005c882019-01-29 16:32:03 -08001567 newStatus = String.format(mContext.getString(R.string.osu_opening_provider),
1568 mOsuProvider.getFriendlyName());
Quang Luong8d40a8e2019-01-02 16:25:38 -08001569 break;
1570 case OSU_STATUS_REDIRECT_RESPONSE_RECEIVED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001571 case OSU_STATUS_SECOND_SOAP_EXCHANGE:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001572 case OSU_STATUS_THIRD_SOAP_EXCHANGE:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001573 case OSU_STATUS_RETRIEVING_TRUST_ROOT_CERTS:
Quang Luongf005c882019-01-29 16:32:03 -08001574 newStatus = mContext.getString(
1575 R.string.osu_completing_sign_up);
Quang Luong8d40a8e2019-01-02 16:25:38 -08001576 break;
1577 }
Quang Luongf005c882019-01-29 16:32:03 -08001578 boolean updated = !TextUtils.equals(mOsuStatus, newStatus);
1579 mOsuStatus = newStatus;
Quang Luong8d40a8e2019-01-02 16:25:38 -08001580 mOsuFailure = null;
1581 mOsuProvisioningComplete = false;
Quang Luongf005c882019-01-29 16:32:03 -08001582 if (updated) {
1583 ThreadUtils.postOnMainThread(() -> {
1584 if (mAccessPointListener != null) {
1585 mAccessPointListener.onAccessPointChanged(AccessPoint.this);
1586 }
1587 });
1588 }
Quang Luong8d40a8e2019-01-02 16:25:38 -08001589 }
1590
1591 @Override
1592 @MainThread public void onProvisioningComplete() {
1593 mOsuProvisioningComplete = true;
1594 mOsuFailure = null;
1595 mOsuStatus = null;
1596 ThreadUtils.postOnMainThread(() -> {
1597 if (mAccessPointListener != null) {
1598 mAccessPointListener.onAccessPointChanged(AccessPoint.this);
1599 }
1600 });
Quang Luong4d194842018-12-18 16:59:49 -08001601 }
1602 }
Jason Monkd52356a2015-01-28 10:40:41 -05001603}