blob: d577b5a8460dfdbe8105ea606de582db99feaa4f [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;
lucaslin783f2212019-10-22 18:27:33 +080053import android.provider.Settings;
Jason Monk6980d122015-06-15 10:07:55 -040054import android.text.TextUtils;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -080055import android.util.ArraySet;
Jason Monkd52356a2015-01-28 10:40:41 -050056import android.util.Log;
Quang Luong7cfa5272019-03-08 12:37:15 -080057import android.util.Pair;
Jason Monkd52356a2015-01-28 10:40:41 -050058
Quang Luong9574a1b2019-06-06 16:51:53 -070059import androidx.annotation.GuardedBy;
Fan Zhangf7802ea2018-08-28 15:15:19 -070060import androidx.annotation.NonNull;
61
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -080062import com.android.internal.annotations.VisibleForTesting;
Quang Luong8123f772019-02-08 16:30:12 -080063import com.android.internal.util.CollectionUtils;
Jason Monkd52356a2015-01-28 10:40:41 -050064import com.android.settingslib.R;
Sundeep Ghumanbb399912018-01-29 18:31:15 -080065import com.android.settingslib.utils.ThreadUtils;
Jason Monkd52356a2015-01-28 10:40:41 -050066
Sundeep Ghuman53200ed2017-06-21 16:54:36 -070067import java.lang.annotation.Retention;
68import java.lang.annotation.RetentionPolicy;
Vinit Deshpandefcd46122015-06-11 18:22:23 -070069import java.util.ArrayList;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -080070import java.util.Collection;
Quang Luong7cfa5272019-03-08 12:37:15 -080071import java.util.Collections;
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -070072import java.util.HashMap;
Mitchell Wills18af4932016-08-10 13:49:21 -070073import java.util.Iterator;
Quang Luong7cfa5272019-03-08 12:37:15 -080074import java.util.List;
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -070075import java.util.Map;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -080076import java.util.Set;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -070077import java.util.concurrent.atomic.AtomicInteger;
Jason Monkd52356a2015-01-28 10:40:41 -050078
Sundeep Ghumanbb399912018-01-29 18:31:15 -080079/**
80 * Represents a selectable Wifi Network for use in various wifi selection menus backed by
81 * {@link WifiTracker}.
82 *
83 * <p>An AccessPoint, which would be more fittingly named "WifiNetwork", is an aggregation of
84 * {@link ScanResult ScanResults} along with pertinent metadata (e.g. current connection info,
85 * network scores) required to successfully render the network to the user.
86 */
Jason Monkd52356a2015-01-28 10:40:41 -050087public class AccessPoint implements Comparable<AccessPoint> {
88 static final String TAG = "SettingsLib.AccessPoint";
89
90 /**
91 * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels
92 */
93 public static final int LOWER_FREQ_24GHZ = 2400;
94
95 /**
96 * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels
97 */
98 public static final int HIGHER_FREQ_24GHZ = 2500;
99
100 /**
101 * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
102 */
103 public static final int LOWER_FREQ_5GHZ = 4900;
104
105 /**
106 * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
107 */
108 public static final int HIGHER_FREQ_5GHZ = 5900;
109
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800110 /** The key which identifies this AccessPoint grouping. */
111 private String mKey;
112
Quang Luong9574a1b2019-06-06 16:51:53 -0700113 /**
114 * Synchronization lock for managing concurrency between main and worker threads.
115 *
116 * <p>This lock should be held for all modifications to {@link #mScanResults} and
117 * {@link #mExtraScanResults}.
118 */
119 private final Object mLock = new Object();
120
Sundeep Ghuman53200ed2017-06-21 16:54:36 -0700121 @IntDef({Speed.NONE, Speed.SLOW, Speed.MODERATE, Speed.FAST, Speed.VERY_FAST})
122 @Retention(RetentionPolicy.SOURCE)
123 public @interface Speed {
124 /**
125 * Constant value representing an unlabeled / unscored network.
126 */
127 int NONE = 0;
128 /**
129 * Constant value representing a slow speed network connection.
130 */
131 int SLOW = 5;
132 /**
133 * Constant value representing a medium speed network connection.
134 */
135 int MODERATE = 10;
136 /**
137 * Constant value representing a fast speed network connection.
138 */
139 int FAST = 20;
140 /**
141 * Constant value representing a very fast speed network connection.
142 */
143 int VERY_FAST = 30;
144 }
Jason Monkd52356a2015-01-28 10:40:41 -0500145
Arc Wange706be82019-10-16 15:25:56 +0800146 @IntDef({PasspointConfigurationVersion.INVALID,
147 PasspointConfigurationVersion.NO_OSU_PROVISIONED,
148 PasspointConfigurationVersion.OSU_PROVISIONED})
149 @Retention(RetentionPolicy.SOURCE)
150 public @interface PasspointConfigurationVersion {
151 int INVALID = 0;
152 int NO_OSU_PROVISIONED = 1; // R1.
153 int OSU_PROVISIONED = 2; // R2 or R3.
154 }
155
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800156 /** The underlying set of scan results comprising this AccessPoint. */
Quang Luong9574a1b2019-06-06 16:51:53 -0700157 @GuardedBy("mLock")
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800158 private final ArraySet<ScanResult> mScanResults = new ArraySet<>();
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700159
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700160 /**
Quang Luong8123f772019-02-08 16:30:12 -0800161 * Extra set of unused scan results corresponding to this AccessPoint for verbose logging
162 * purposes, such as a set of Passpoint roaming scan results when home scans are available.
163 */
Quang Luong9574a1b2019-06-06 16:51:53 -0700164 @GuardedBy("mLock")
Quang Luong8123f772019-02-08 16:30:12 -0800165 private final ArraySet<ScanResult> mExtraScanResults = new ArraySet<>();
166
167 /**
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700168 * Map of BSSIDs to scored networks for individual bssids.
169 *
170 * <p>This cache should not be evicted with scan results, as the values here are used to
171 * generate a fallback in the absence of scores for the visible APs.
172 */
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700173 private final Map<String, TimestampedScoredNetwork> mScoredNetworkCache = new HashMap<>();
174
Dave Schaefer98537432017-02-08 11:26:08 -0800175 static final String KEY_NETWORKINFO = "key_networkinfo";
176 static final String KEY_WIFIINFO = "key_wifiinfo";
Dave Schaefer98537432017-02-08 11:26:08 -0800177 static final String KEY_SSID = "key_ssid";
178 static final String KEY_SECURITY = "key_security";
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700179 static final String KEY_SPEED = "key_speed";
Dave Schaefer98537432017-02-08 11:26:08 -0800180 static final String KEY_PSKTYPE = "key_psktype";
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800181 static final String KEY_SCANRESULTS = "key_scanresults";
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700182 static final String KEY_SCOREDNETWORKCACHE = "key_scorednetworkcache";
Dave Schaefer98537432017-02-08 11:26:08 -0800183 static final String KEY_CONFIG = "key_config";
Peter Qiuced37db2017-03-14 15:51:22 -0700184 static final String KEY_FQDN = "key_fqdn";
185 static final String KEY_PROVIDER_FRIENDLY_NAME = "key_provider_friendly_name";
Peter Qiu280581b2017-07-24 14:18:56 -0700186 static final String KEY_IS_CARRIER_AP = "key_is_carrier_ap";
187 static final String KEY_CARRIER_AP_EAP_TYPE = "key_carrier_ap_eap_type";
188 static final String KEY_CARRIER_NAME = "key_carrier_name";
Hai Shalom5daf0ce2019-04-22 17:50:48 -0700189 static final String KEY_EAPTYPE = "eap_psktype";
Arc Wange706be82019-10-16 15:25:56 +0800190 static final String KEY_SUBSCRIPTION_EXPIRATION_TIME_IN_MILLIS =
191 "key_subscription_expiration_time_in_millis";
192 static final String KEY_PASSPOINT_CONFIGURATION_VERSION = "key_passpoint_configuration_version";
Dave Schaefer98537432017-02-08 11:26:08 -0800193 static final AtomicInteger sLastId = new AtomicInteger(0);
Jason Monkd52356a2015-01-28 10:40:41 -0500194
Maurice Lam7cdbe192018-11-13 13:52:50 -0800195 /*
196 * NOTE: These constants for security and PSK types are saved to the bundle in saveWifiState,
197 * and sent across IPC. The numeric values should remain stable, otherwise the changes will need
198 * to be synced with other unbundled users of this library.
Jason Monkd52356a2015-01-28 10:40:41 -0500199 */
200 public static final int SECURITY_NONE = 0;
Hai Shalom9effa642018-11-12 11:43:52 -0800201 public static final int SECURITY_WEP = 1;
202 public static final int SECURITY_PSK = 2;
203 public static final int SECURITY_EAP = 3;
204 public static final int SECURITY_OWE = 4;
205 public static final int SECURITY_SAE = 5;
Hai Shalomaa6f9202018-10-16 14:30:02 -0700206 public static final int SECURITY_EAP_SUITE_B = 6;
Hai Shalom1c937182019-05-08 14:39:50 -0700207 public static final int SECURITY_PSK_SAE_TRANSITION = 7;
Hai Shalom2195d1f2019-05-13 15:31:41 -0700208 public static final int SECURITY_OWE_TRANSITION = 8;
209 public static final int SECURITY_MAX_VAL = 9; // Has to be the last
Jason Monkd52356a2015-01-28 10:40:41 -0500210
211 private static final int PSK_UNKNOWN = 0;
212 private static final int PSK_WPA = 1;
213 private static final int PSK_WPA2 = 2;
214 private static final int PSK_WPA_WPA2 = 3;
Hai Shalomc03fc882019-04-08 15:08:19 -0700215 private static final int PSK_SAE = 4;
Jason Monkd52356a2015-01-28 10:40:41 -0500216
Hai Shalom5daf0ce2019-04-22 17:50:48 -0700217 private static final int EAP_UNKNOWN = 0;
218 private static final int EAP_WPA = 1; // WPA-EAP
219 private static final int EAP_WPA2_WPA3 = 2; // RSN-EAP
220
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700221 /**
222 * The number of distinct wifi levels.
223 *
224 * <p>Must keep in sync with {@link R.array.wifi_signal} and {@link WifiManager#RSSI_LEVELS}.
225 */
226 public static final int SIGNAL_LEVELS = 5;
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800227
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700228 public static final int UNREACHABLE_RSSI = Integer.MIN_VALUE;
Dave Schaefer98537432017-02-08 11:26:08 -0800229
Quang Luong9051dfd2018-12-12 12:49:24 -0800230 public static final String KEY_PREFIX_AP = "AP:";
231 public static final String KEY_PREFIX_FQDN = "FQDN:";
232 public static final String KEY_PREFIX_OSU = "OSU:";
233
Jason Monkd52356a2015-01-28 10:40:41 -0500234 private final Context mContext;
235
Quang Luong7cfa5272019-03-08 12:37:15 -0800236 private WifiManager mWifiManager;
237 private WifiManager.ActionListener mConnectListener;
238
Jason Monkd52356a2015-01-28 10:40:41 -0500239 private String ssid;
Jason Monk60a82ff2016-02-25 13:55:03 -0500240 private String bssid;
Jason Monkd52356a2015-01-28 10:40:41 -0500241 private int security;
242 private int networkId = WifiConfiguration.INVALID_NETWORK_ID;
243
244 private int pskType = PSK_UNKNOWN;
Hai Shalom5daf0ce2019-04-22 17:50:48 -0700245 private int mEapType = EAP_UNKNOWN;
Jason Monkd52356a2015-01-28 10:40:41 -0500246
247 private WifiConfiguration mConfig;
Jason Monkd52356a2015-01-28 10:40:41 -0500248
Dave Schaefer98537432017-02-08 11:26:08 -0800249 private int mRssi = UNREACHABLE_RSSI;
Jason Monkd52356a2015-01-28 10:40:41 -0500250
251 private WifiInfo mInfo;
252 private NetworkInfo mNetworkInfo;
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700253 AccessPointListener mAccessPointListener;
Jason Monkd52356a2015-01-28 10:40:41 -0500254
255 private Object mTag;
256
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700257 @Speed private int mSpeed = Speed.NONE;
Stephen Chen21f68682017-04-04 13:23:31 -0700258 private boolean mIsScoredNetworkMetered = false;
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800259
Peter Qiuced37db2017-03-14 15:51:22 -0700260 /**
261 * Information associated with the {@link PasspointConfiguration}. Only maintaining
262 * the relevant info to preserve spaces.
263 */
264 private String mFqdn;
265 private String mProviderFriendlyName;
Quang Luong8123f772019-02-08 16:30:12 -0800266 private boolean mIsRoaming = false;
Arc Wange706be82019-10-16 15:25:56 +0800267 private long mSubscriptionExpirationTimeInMillis;
268 @PasspointConfigurationVersion private int mPasspointConfigurationVersion =
269 PasspointConfigurationVersion.INVALID;
Peter Qiuced37db2017-03-14 15:51:22 -0700270
Peter Qiu280581b2017-07-24 14:18:56 -0700271 private boolean mIsCarrierAp = false;
Quang Luong9051dfd2018-12-12 12:49:24 -0800272
273 private OsuProvider mOsuProvider;
Quang Luong8d40a8e2019-01-02 16:25:38 -0800274
275 private String mOsuStatus;
276 private String mOsuFailure;
277 private boolean mOsuProvisioningComplete = false;
278
Peter Qiu280581b2017-07-24 14:18:56 -0700279 /**
280 * The EAP type {@link WifiEnterpriseConfig.Eap} associated with this AP if it is a carrier AP.
281 */
282 private int mCarrierApEapType = WifiEnterpriseConfig.Eap.NONE;
283 private String mCarrierName = null;
284
Jason Monkd52356a2015-01-28 10:40:41 -0500285 public AccessPoint(Context context, Bundle savedState) {
286 mContext = context;
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800287
288 if (savedState.containsKey(KEY_CONFIG)) {
289 mConfig = savedState.getParcelable(KEY_CONFIG);
290 }
Jason Monkd52356a2015-01-28 10:40:41 -0500291 if (mConfig != null) {
292 loadConfig(mConfig);
293 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700294 if (savedState.containsKey(KEY_SSID)) {
295 ssid = savedState.getString(KEY_SSID);
296 }
297 if (savedState.containsKey(KEY_SECURITY)) {
298 security = savedState.getInt(KEY_SECURITY);
299 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700300 if (savedState.containsKey(KEY_SPEED)) {
301 mSpeed = savedState.getInt(KEY_SPEED);
302 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700303 if (savedState.containsKey(KEY_PSKTYPE)) {
304 pskType = savedState.getInt(KEY_PSKTYPE);
Jason Monkd52356a2015-01-28 10:40:41 -0500305 }
Hai Shalom5daf0ce2019-04-22 17:50:48 -0700306 if (savedState.containsKey(KEY_EAPTYPE)) {
307 mEapType = savedState.getInt(KEY_EAPTYPE);
308 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700309 mInfo = savedState.getParcelable(KEY_WIFIINFO);
Jason Monkd52356a2015-01-28 10:40:41 -0500310 if (savedState.containsKey(KEY_NETWORKINFO)) {
311 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
312 }
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800313 if (savedState.containsKey(KEY_SCANRESULTS)) {
314 Parcelable[] scanResults = savedState.getParcelableArray(KEY_SCANRESULTS);
315 mScanResults.clear();
316 for (Parcelable result : scanResults) {
317 mScanResults.add((ScanResult) result);
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700318 }
319 }
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700320 if (savedState.containsKey(KEY_SCOREDNETWORKCACHE)) {
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700321 ArrayList<TimestampedScoredNetwork> scoredNetworkArrayList =
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700322 savedState.getParcelableArrayList(KEY_SCOREDNETWORKCACHE);
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700323 for (TimestampedScoredNetwork timedScore : scoredNetworkArrayList) {
324 mScoredNetworkCache.put(timedScore.getScore().networkKey.wifiKey.bssid, timedScore);
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700325 }
326 }
Peter Qiuced37db2017-03-14 15:51:22 -0700327 if (savedState.containsKey(KEY_FQDN)) {
328 mFqdn = savedState.getString(KEY_FQDN);
329 }
330 if (savedState.containsKey(KEY_PROVIDER_FRIENDLY_NAME)) {
331 mProviderFriendlyName = savedState.getString(KEY_PROVIDER_FRIENDLY_NAME);
332 }
Peter Qiu280581b2017-07-24 14:18:56 -0700333 if (savedState.containsKey(KEY_IS_CARRIER_AP)) {
334 mIsCarrierAp = savedState.getBoolean(KEY_IS_CARRIER_AP);
335 }
336 if (savedState.containsKey(KEY_CARRIER_AP_EAP_TYPE)) {
337 mCarrierApEapType = savedState.getInt(KEY_CARRIER_AP_EAP_TYPE);
338 }
339 if (savedState.containsKey(KEY_CARRIER_NAME)) {
340 mCarrierName = savedState.getString(KEY_CARRIER_NAME);
341 }
Arc Wange706be82019-10-16 15:25:56 +0800342 if (savedState.containsKey(KEY_SUBSCRIPTION_EXPIRATION_TIME_IN_MILLIS)) {
343 mSubscriptionExpirationTimeInMillis =
344 savedState.getLong(KEY_SUBSCRIPTION_EXPIRATION_TIME_IN_MILLIS);
345 }
346 if (savedState.containsKey(KEY_PASSPOINT_CONFIGURATION_VERSION)) {
347 mPasspointConfigurationVersion = savedState.getInt(KEY_PASSPOINT_CONFIGURATION_VERSION);
348 }
Mitchell Wills5a42db22015-08-03 09:46:08 -0700349 update(mConfig, mInfo, mNetworkInfo);
Sundeep Ghumand1e44922017-08-07 11:21:38 -0700350
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800351 // Calculate required fields
352 updateKey();
Quang Luong8123f772019-02-08 16:30:12 -0800353 updateBestRssiInfo();
Jason Monkd52356a2015-01-28 10:40:41 -0500354 }
355
Quang Luong9051dfd2018-12-12 12:49:24 -0800356 /**
357 * Creates an AccessPoint with only a WifiConfiguration. This is used for the saved networks
358 * page.
Quang Luong9051dfd2018-12-12 12:49:24 -0800359 */
Peter Qiuced37db2017-03-14 15:51:22 -0700360 public AccessPoint(Context context, WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500361 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700362 loadConfig(config);
Quang Luong6e711c82019-03-07 14:52:55 -0800363 updateKey();
Jason Monkd52356a2015-01-28 10:40:41 -0500364 }
365
Peter Qiuced37db2017-03-14 15:51:22 -0700366 /**
367 * Initialize an AccessPoint object for a {@link PasspointConfiguration}. This is mainly
368 * used by "Saved Networks" page for managing the saved {@link PasspointConfiguration}.
369 */
370 public AccessPoint(Context context, PasspointConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500371 mContext = context;
Peter Qiuced37db2017-03-14 15:51:22 -0700372 mFqdn = config.getHomeSp().getFqdn();
373 mProviderFriendlyName = config.getHomeSp().getFriendlyName();
Arc Wange706be82019-10-16 15:25:56 +0800374 mSubscriptionExpirationTimeInMillis = config.getSubscriptionExpirationTimeInMillis();
375 if (config.isOsuProvisioned()) {
376 mPasspointConfigurationVersion = PasspointConfigurationVersion.OSU_PROVISIONED;
377 } else {
378 mPasspointConfigurationVersion = PasspointConfigurationVersion.NO_OSU_PROVISIONED;
379 }
Quang Luong6e711c82019-03-07 14:52:55 -0800380 updateKey();
Quang Luong9051dfd2018-12-12 12:49:24 -0800381 }
382
383 /**
Quang Luong8123f772019-02-08 16:30:12 -0800384 * Initialize an AccessPoint object for a Passpoint network.
Quang Luong9051dfd2018-12-12 12:49:24 -0800385 */
Quang Luong8123f772019-02-08 16:30:12 -0800386 public AccessPoint(@NonNull Context context, @NonNull WifiConfiguration config,
387 @Nullable Collection<ScanResult> homeScans,
388 @Nullable Collection<ScanResult> roamingScans) {
389 mContext = context;
390 networkId = config.networkId;
391 mConfig = config;
Quang Luongeafca1b2019-04-15 14:15:25 -0700392 mFqdn = config.FQDN;
Quang Luong8123f772019-02-08 16:30:12 -0800393 setScanResultsPasspoint(homeScans, roamingScans);
394 updateKey();
395 }
396
397 /**
398 * Initialize an AccessPoint object for a Passpoint OSU Provider.
399 */
400 public AccessPoint(@NonNull Context context, @NonNull OsuProvider provider,
401 @NonNull Collection<ScanResult> results) {
Quang Luong9051dfd2018-12-12 12:49:24 -0800402 mContext = context;
403 mOsuProvider = provider;
Quang Luong8123f772019-02-08 16:30:12 -0800404 setScanResults(results);
Quang Luong9051dfd2018-12-12 12:49:24 -0800405 updateKey();
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700406 }
407
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800408 AccessPoint(Context context, Collection<ScanResult> results) {
Peter Qiuced37db2017-03-14 15:51:22 -0700409 mContext = context;
Quang Luong8123f772019-02-08 16:30:12 -0800410 setScanResults(results);
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800411 updateKey();
Peter Qiuced37db2017-03-14 15:51:22 -0700412 }
413
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800414 @VisibleForTesting void loadConfig(WifiConfiguration config) {
415 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
416 bssid = config.BSSID;
417 security = getSecurity(config);
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800418 networkId = config.networkId;
419 mConfig = config;
420 }
421
422 /** Updates {@link #mKey} and should only called upon object creation/initialization. */
423 private void updateKey() {
424 // TODO(sghuman): Consolidate Key logic on ScanResultMatchInfo
Quang Luong7054e922018-12-07 16:44:18 -0800425 if (isPasspoint()) {
Quang Luongac1026e2019-01-02 17:37:01 -0800426 mKey = getKey(mConfig);
Quang Luong6e711c82019-03-07 14:52:55 -0800427 } else if (isPasspointConfig()) {
428 mKey = getKey(mFqdn);
Quang Luong9051dfd2018-12-12 12:49:24 -0800429 } else if (isOsuProvider()) {
Quang Luongac1026e2019-01-02 17:37:01 -0800430 mKey = getKey(mOsuProvider);
Quang Luong9051dfd2018-12-12 12:49:24 -0800431 } else { // Non-Passpoint AP
Quang Luongac1026e2019-01-02 17:37:01 -0800432 mKey = getKey(getSsidStr(), getBssid(), getSecurity());
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800433 }
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800434 }
435
Ajay Nadathurd7b689a2016-08-31 15:07:56 -0700436 /**
Dave Schaefer98537432017-02-08 11:26:08 -0800437 * Returns a negative integer, zero, or a positive integer if this AccessPoint is less than,
438 * equal to, or greater than the other AccessPoint.
439 *
440 * Sort order rules for AccessPoints:
441 * 1. Active before inactive
442 * 2. Reachable before unreachable
443 * 3. Saved before unsaved
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700444 * 4. Network speed value
Dave Schaefer98537432017-02-08 11:26:08 -0800445 * 5. Stronger signal before weaker signal
446 * 6. SSID alphabetically
447 *
448 * Note that AccessPoints with a signal are usually also Reachable,
449 * and will thus appear before unreachable saved AccessPoints.
450 */
Jason Monkd52356a2015-01-28 10:40:41 -0500451 @Override
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800452 public int compareTo(@NonNull AccessPoint other) {
Jason Monkd52356a2015-01-28 10:40:41 -0500453 // Active one goes first.
454 if (isActive() && !other.isActive()) return -1;
455 if (!isActive() && other.isActive()) return 1;
456
457 // Reachable one goes before unreachable one.
Dave Schaefer98537432017-02-08 11:26:08 -0800458 if (isReachable() && !other.isReachable()) return -1;
459 if (!isReachable() && other.isReachable()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500460
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800461 // Configured (saved) one goes before unconfigured one.
Dave Schaefer98537432017-02-08 11:26:08 -0800462 if (isSaved() && !other.isSaved()) return -1;
463 if (!isSaved() && other.isSaved()) return 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500464
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700465 // Faster speeds go before slower speeds - but only if visible change in speed label
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -0700466 if (getSpeed() != other.getSpeed()) {
467 return other.getSpeed() - getSpeed();
Sundeep Ghuman05c41e22017-02-01 13:27:56 -0800468 }
469
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800470 // Sort by signal strength, bucketed by level
471 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS)
472 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500473 if (difference != 0) {
474 return difference;
475 }
Sundeep Ghumand44b8e42017-06-21 21:40:06 -0700476
Quang Luong9051dfd2018-12-12 12:49:24 -0800477 // Sort by title.
478 difference = getTitle().compareToIgnoreCase(other.getTitle());
Sundeep Ghumand44b8e42017-06-21 21:40:06 -0700479 if (difference != 0) {
480 return difference;
481 }
482
483 // Do a case sensitive comparison to distinguish SSIDs that differ in case only
484 return getSsidStr().compareTo(other.getSsidStr());
Jason Monkd52356a2015-01-28 10:40:41 -0500485 }
486
487 @Override
488 public boolean equals(Object other) {
489 if (!(other instanceof AccessPoint)) return false;
490 return (this.compareTo((AccessPoint) other) == 0);
491 }
492
493 @Override
494 public int hashCode() {
495 int result = 0;
496 if (mInfo != null) result += 13 * mInfo.hashCode();
497 result += 19 * mRssi;
498 result += 23 * networkId;
499 result += 29 * ssid.hashCode();
500 return result;
501 }
502
503 @Override
504 public String toString() {
505 StringBuilder builder = new StringBuilder().append("AccessPoint(")
506 .append(ssid);
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800507 if (bssid != null) {
508 builder.append(":").append(bssid);
509 }
Jason Monkd52356a2015-01-28 10:40:41 -0500510 if (isSaved()) {
511 builder.append(',').append("saved");
512 }
513 if (isActive()) {
514 builder.append(',').append("active");
515 }
516 if (isEphemeral()) {
517 builder.append(',').append("ephemeral");
518 }
519 if (isConnectable()) {
520 builder.append(',').append("connectable");
521 }
Hai Shalomaa6f9202018-10-16 14:30:02 -0700522 if ((security != SECURITY_NONE) && (security != SECURITY_OWE)) {
Jason Monkd52356a2015-01-28 10:40:41 -0500523 builder.append(',').append(securityToString(security, pskType));
524 }
Sundeep Ghuman2b489902017-02-22 18:17:29 -0800525 builder.append(",level=").append(getLevel());
Sundeep Ghuman53200ed2017-06-21 16:54:36 -0700526 if (mSpeed != Speed.NONE) {
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700527 builder.append(",speed=").append(mSpeed);
Sundeep Ghuman8920e9c2017-04-27 16:16:41 -0700528 }
Stephen Chen21f68682017-04-04 13:23:31 -0700529 builder.append(",metered=").append(isMetered());
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800530
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -0800531 if (isVerboseLoggingEnabled()) {
Sundeep Ghumandb9b94c2017-09-06 11:46:21 -0700532 builder.append(",rssi=").append(mRssi);
Quang Luong9574a1b2019-06-06 16:51:53 -0700533 synchronized (mLock) {
534 builder.append(",scan cache size=").append(mScanResults.size()
535 + mExtraScanResults.size());
536 }
Sundeep Ghumandb9b94c2017-09-06 11:46:21 -0700537 }
538
Jason Monkd52356a2015-01-28 10:40:41 -0500539 return builder.append(')').toString();
540 }
541
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800542 /**
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700543 * Updates the AccessPoint rankingScore, metering, and speed, returning true if the data has
Stephen Chen21f68682017-04-04 13:23:31 -0700544 * changed.
545 *
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700546 * @param scoreCache The score cache to use to retrieve scores
547 * @param scoringUiEnabled Whether to show scoring and badging UI
548 * @param maxScoreCacheAgeMillis the maximum age in milliseconds of scores to consider when
549 * generating speed labels
Stephen Chen21f68682017-04-04 13:23:31 -0700550 */
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700551 boolean update(
552 WifiNetworkScoreCache scoreCache,
553 boolean scoringUiEnabled,
554 long maxScoreCacheAgeMillis) {
Stephen Chen21f68682017-04-04 13:23:31 -0700555 boolean scoreChanged = false;
556 if (scoringUiEnabled) {
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700557 scoreChanged = updateScores(scoreCache, maxScoreCacheAgeMillis);
Stephen Chen21f68682017-04-04 13:23:31 -0700558 }
559 return updateMetered(scoreCache) || scoreChanged;
560 }
561
562 /**
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -0700563 * Updates the AccessPoint rankingScore and speed, returning true if the data has changed.
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800564 *
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700565 * <p>Any cached {@link TimestampedScoredNetwork} objects older than the given max age in millis
566 * will be removed when this method is invoked.
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700567 *
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700568 * <p>Precondition: {@link #mRssi} is up to date before invoking this method.
569 *
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700570 * @param scoreCache The score cache to use to retrieve scores
571 * @param maxScoreCacheAgeMillis the maximum age in milliseconds of scores to consider when
572 * generating speed labels
573 *
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700574 * @return true if the set speed has changed
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800575 */
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700576 private boolean updateScores(WifiNetworkScoreCache scoreCache, long maxScoreCacheAgeMillis) {
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700577 long nowMillis = SystemClock.elapsedRealtime();
Quang Luong9574a1b2019-06-06 16:51:53 -0700578 synchronized (mLock) {
579 for (ScanResult result : mScanResults) {
580 ScoredNetwork score = scoreCache.getScoredNetwork(result);
581 if (score == null) {
582 continue;
583 }
584 TimestampedScoredNetwork timedScore = mScoredNetworkCache.get(result.BSSID);
585 if (timedScore == null) {
586 mScoredNetworkCache.put(
587 result.BSSID, new TimestampedScoredNetwork(score, nowMillis));
588 } else {
589 // Update data since the has been seen in the score cache
590 timedScore.update(score, nowMillis);
591 }
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700592 }
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -0700593 }
594
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700595 // Remove old cached networks
Sundeep Ghuman9bb85d32017-08-28 17:04:16 -0700596 long evictionCutoff = nowMillis - maxScoreCacheAgeMillis;
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700597 Iterator<TimestampedScoredNetwork> iterator = mScoredNetworkCache.values().iterator();
598 iterator.forEachRemaining(timestampedScoredNetwork -> {
599 if (timestampedScoredNetwork.getUpdatedTimestampMillis() < evictionCutoff) {
600 iterator.remove();
601 }
602 });
603
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700604 return updateSpeed();
605 }
606
607 /**
608 * Updates the internal speed, returning true if the update resulted in a speed label change.
609 */
610 private boolean updateSpeed() {
611 int oldSpeed = mSpeed;
612 mSpeed = generateAverageSpeedForSsid();
613
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700614 boolean changed = oldSpeed != mSpeed;
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -0800615 if(isVerboseLoggingEnabled() && changed) {
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700616 Log.i(TAG, String.format("%s: Set speed to %d", ssid, mSpeed));
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800617 }
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700618 return changed;
619 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800620
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700621 /** Creates a speed value for the current {@link #mRssi} by averaging all non zero badges. */
622 @Speed private int generateAverageSpeedForSsid() {
623 if (mScoredNetworkCache.isEmpty()) {
624 return Speed.NONE;
625 }
626
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700627 if (Log.isLoggable(TAG, Log.DEBUG)) {
628 Log.d(TAG, String.format("Generating fallbackspeed for %s using cache: %s",
629 getSsidStr(), mScoredNetworkCache));
630 }
631
Sundeep Ghumana7825692017-08-23 15:53:00 -0700632 // TODO(b/63073866): If flickering issues persist, consider mapping using getLevel rather
633 // than specific rssi value so score doesn't change without a visible wifi bar change. This
634 // issue is likely to be more evident for the active AP whose RSSI value is not half-lifed.
635
Sundeep Ghumanfedf4612017-08-15 15:47:18 -0700636 int count = 0;
637 int totalSpeed = 0;
638 for (TimestampedScoredNetwork timedScore : mScoredNetworkCache.values()) {
639 int speed = timedScore.getScore().calculateBadge(mRssi);
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700640 if (speed != Speed.NONE) {
641 count++;
642 totalSpeed += speed;
643 }
644 }
645 int speed = count == 0 ? Speed.NONE : totalSpeed / count;
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -0800646 if (isVerboseLoggingEnabled()) {
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -0700647 Log.i(TAG, String.format("%s generated fallback speed is: %d", getSsidStr(), speed));
648 }
649 return roundToClosestSpeedEnum(speed);
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -0800650 }
651
Stephen Chen21f68682017-04-04 13:23:31 -0700652 /**
653 * Updates the AccessPoint's metering based on {@link ScoredNetwork#meteredHint}, returning
654 * true if the metering changed.
655 */
656 private boolean updateMetered(WifiNetworkScoreCache scoreCache) {
657 boolean oldMetering = mIsScoredNetworkMetered;
658 mIsScoredNetworkMetered = false;
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700659
660 if (isActive() && mInfo != null) {
Eric Schwarzenbach733ea262017-08-08 10:28:21 -0700661 NetworkKey key = NetworkKey.createFromWifiInfo(mInfo);
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700662 ScoredNetwork score = scoreCache.getScoredNetwork(key);
663 if (score != null) {
664 mIsScoredNetworkMetered |= score.meteredHint;
Stephen Chen21f68682017-04-04 13:23:31 -0700665 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700666 } else {
Quang Luong9574a1b2019-06-06 16:51:53 -0700667 synchronized (mLock) {
668 for (ScanResult result : mScanResults) {
669 ScoredNetwork score = scoreCache.getScoredNetwork(result);
670 if (score == null) {
671 continue;
672 }
673 mIsScoredNetworkMetered |= score.meteredHint;
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700674 }
Sundeep Ghumana28050a2017-07-12 22:09:25 -0700675 }
Stephen Chen21f68682017-04-04 13:23:31 -0700676 }
677 return oldMetering == mIsScoredNetworkMetered;
678 }
679
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800680 public static String getKey(ScanResult result) {
Quang Luongac1026e2019-01-02 17:37:01 -0800681 return getKey(result.SSID, result.BSSID, getSecurity(result));
Mitchell Wills18af4932016-08-10 13:49:21 -0700682 }
683
Quang Luongac1026e2019-01-02 17:37:01 -0800684 /**
685 * Returns the AccessPoint key for a WifiConfiguration.
686 * This will return a special Passpoint key if the config is for Passpoint.
687 */
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800688 public static String getKey(WifiConfiguration config) {
Quang Luong7054e922018-12-07 16:44:18 -0800689 if (config.isPasspoint()) {
Quang Luong6e711c82019-03-07 14:52:55 -0800690 return getKey(config.FQDN);
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800691 } else {
Quang Luongc2c947c2019-01-18 12:51:35 -0800692 return getKey(removeDoubleQuotes(config.SSID), config.BSSID, getSecurity(config));
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800693 }
Quang Luongac1026e2019-01-02 17:37:01 -0800694 }
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800695
Quang Luongac1026e2019-01-02 17:37:01 -0800696 /**
Quang Luong6e711c82019-03-07 14:52:55 -0800697 * Returns the AccessPoint key corresponding to a Passpoint network by its FQDN.
698 */
699 public static String getKey(String fqdn) {
700 return new StringBuilder()
701 .append(KEY_PREFIX_FQDN)
702 .append(fqdn).toString();
703 }
704
705 /**
Quang Luongac1026e2019-01-02 17:37:01 -0800706 * Returns the AccessPoint key corresponding to the OsuProvider.
707 */
708 public static String getKey(OsuProvider provider) {
709 return new StringBuilder()
710 .append(KEY_PREFIX_OSU)
Quang Luong1a8fece2019-01-11 14:58:14 -0800711 .append(provider.getFriendlyName())
Quang Luongac1026e2019-01-02 17:37:01 -0800712 .append(',')
713 .append(provider.getServerUri()).toString();
714 }
715
716 /**
717 * Returns the AccessPoint key for a normal non-Passpoint network by ssid/bssid and security.
718 */
719 private static String getKey(String ssid, String bssid, int security) {
720 StringBuilder builder = new StringBuilder();
721 builder.append(KEY_PREFIX_AP);
722 if (TextUtils.isEmpty(ssid)) {
723 builder.append(bssid);
724 } else {
725 builder.append(ssid);
726 }
727 builder.append(',').append(security);
Sundeep Ghuman0d492e82018-01-26 12:45:02 -0800728 return builder.toString();
729 }
730
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800731 public String getKey() {
732 return mKey;
Jason Monkd52356a2015-01-28 10:40:41 -0500733 }
734
Quang Luongeafca1b2019-04-15 14:15:25 -0700735 /**
736 * Determines if the other AccessPoint represents the same network as this AccessPoint
737 */
738 public boolean matches(AccessPoint other) {
739 return getKey().equals(other.getKey());
740 }
741
Jason Monkd52356a2015-01-28 10:40:41 -0500742 public boolean matches(WifiConfiguration config) {
Quang Luong7054e922018-12-07 16:44:18 -0800743 if (config.isPasspoint()) {
744 return (isPasspoint() && config.FQDN.equals(mConfig.FQDN));
Arc Wang04bb4b82019-06-11 11:28:27 +0800745 }
746
747 if (!ssid.equals(removeDoubleQuotes(config.SSID))
748 || (mConfig != null && mConfig.shared != config.shared)) {
749 return false;
750 }
Hai Shalom55796042019-11-21 19:25:52 +0000751
752 final int configSecurity = getSecurity(config);
753 final WifiManager wifiManager = getWifiManager();
754 switch (security) {
755 case SECURITY_PSK_SAE_TRANSITION:
756 return configSecurity == SECURITY_PSK
757 || (wifiManager.isWpa3SaeSupported() && configSecurity == SECURITY_SAE);
758 case SECURITY_OWE_TRANSITION:
759 return configSecurity == SECURITY_NONE
760 || (wifiManager.isEnhancedOpenSupported()
761 && configSecurity == SECURITY_OWE);
762 default:
763 return security == configSecurity;
764 }
Jason Monkd52356a2015-01-28 10:40:41 -0500765 }
766
767 public WifiConfiguration getConfig() {
768 return mConfig;
769 }
770
Peter Qiuced37db2017-03-14 15:51:22 -0700771 public String getPasspointFqdn() {
772 return mFqdn;
773 }
774
Jason Monkd52356a2015-01-28 10:40:41 -0500775 public void clearConfig() {
776 mConfig = null;
777 networkId = WifiConfiguration.INVALID_NETWORK_ID;
778 }
779
780 public WifiInfo getInfo() {
781 return mInfo;
782 }
783
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -0700784 /**
785 * Returns the number of levels to show for a Wifi icon, from 0 to {@link #SIGNAL_LEVELS}-1.
786 *
787 * <p>Use {@#isReachable()} to determine if an AccessPoint is in range, as this method will
788 * always return at least 0.
789 */
Jason Monkd52356a2015-01-28 10:40:41 -0500790 public int getLevel() {
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800791 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500792 }
793
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700794 public int getRssi() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800795 return mRssi;
796 }
797
Sundeep Ghuman04f7f342018-01-23 19:18:31 -0800798 /**
799 * Returns the underlying scan result set.
800 *
801 * <p>Callers should not modify this set.
802 */
Quang Luong8123f772019-02-08 16:30:12 -0800803 public Set<ScanResult> getScanResults() {
804 Set<ScanResult> allScans = new ArraySet<>();
Quang Luong9574a1b2019-06-06 16:51:53 -0700805 synchronized (mLock) {
806 allScans.addAll(mScanResults);
807 allScans.addAll(mExtraScanResults);
808 }
Quang Luong8123f772019-02-08 16:30:12 -0800809 return allScans;
810 }
jackqdyulei9ee9b392017-12-22 11:31:49 -0800811
812 public Map<String, TimestampedScoredNetwork> getScoredNetworkCache() {
813 return mScoredNetworkCache;
814 }
815
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800816 /**
Quang Luong8123f772019-02-08 16:30:12 -0800817 * Updates {@link #mRssi} and sets scan result information to that of the best RSSI scan result.
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800818 *
819 * <p>If the given connection is active, the existing value of {@link #mRssi} will be returned.
820 * If the given AccessPoint is not active, a value will be calculated from previous scan
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700821 * results, returning the best RSSI for all matching AccessPoints averaged with the previous
822 * value. If the access point is not connected and there are no scan results, the rssi will be
823 * set to {@link #UNREACHABLE_RSSI}.
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800824 */
Quang Luong8123f772019-02-08 16:30:12 -0800825 private void updateBestRssiInfo() {
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -0800826 if (this.isActive()) {
827 return;
828 }
829
Quang Luong8123f772019-02-08 16:30:12 -0800830 ScanResult bestResult = null;
831 int bestRssi = UNREACHABLE_RSSI;
Quang Luong9574a1b2019-06-06 16:51:53 -0700832 synchronized (mLock) {
833 for (ScanResult result : mScanResults) {
834 if (result.level > bestRssi) {
835 bestRssi = result.level;
836 bestResult = result;
837 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700838 }
839 }
840
Quang Luong8123f772019-02-08 16:30:12 -0800841 // Set the rssi to the average of the current rssi and the previous rssi.
842 if (bestRssi != UNREACHABLE_RSSI && mRssi != UNREACHABLE_RSSI) {
843 mRssi = (mRssi + bestRssi) / 2;
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700844 } else {
Quang Luong8123f772019-02-08 16:30:12 -0800845 mRssi = bestRssi;
846 }
847
848 if (bestResult != null) {
849 ssid = bestResult.SSID;
850 bssid = bestResult.BSSID;
851 security = getSecurity(bestResult);
Hai Shalom1c937182019-05-08 14:39:50 -0700852 if (security == SECURITY_PSK || security == SECURITY_SAE
853 || security == SECURITY_PSK_SAE_TRANSITION) {
Quang Luong8123f772019-02-08 16:30:12 -0800854 pskType = getPskType(bestResult);
855 }
Hai Shalom5daf0ce2019-04-22 17:50:48 -0700856 if (security == SECURITY_EAP) {
857 mEapType = getEapType(bestResult);
858 }
Quang Luong8123f772019-02-08 16:30:12 -0800859 mIsCarrierAp = bestResult.isCarrierAp;
860 mCarrierApEapType = bestResult.carrierApEapType;
861 mCarrierName = bestResult.carrierName;
862 }
863 // Update the config SSID of a Passpoint network to that of the best RSSI
864 if (isPasspoint()) {
865 mConfig.SSID = convertToQuotedString(ssid);
Sundeep Ghumance78a5f2017-03-15 19:06:14 -0700866 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700867 }
868
Stephen Chen21f68682017-04-04 13:23:31 -0700869 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600870 * Returns if the network should be considered metered.
Stephen Chen21f68682017-04-04 13:23:31 -0700871 */
872 public boolean isMetered() {
873 return mIsScoredNetworkMetered
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600874 || WifiConfiguration.isMetered(mConfig, mInfo);
Stephen Chen21f68682017-04-04 13:23:31 -0700875 }
876
Jason Monkd52356a2015-01-28 10:40:41 -0500877 public NetworkInfo getNetworkInfo() {
878 return mNetworkInfo;
879 }
880
881 public int getSecurity() {
882 return security;
883 }
884
885 public String getSecurityString(boolean concise) {
886 Context context = mContext;
Tomoharu Hatano2bde6e72017-05-30 18:38:56 +0900887 if (isPasspoint() || isPasspointConfig()) {
Sanket Padawe194cce62015-07-10 10:53:31 -0700888 return concise ? context.getString(R.string.wifi_security_short_eap) :
889 context.getString(R.string.wifi_security_eap);
Sanket Padawed1878802015-05-12 10:27:19 -0700890 }
Jason Monkd52356a2015-01-28 10:40:41 -0500891 switch(security) {
892 case SECURITY_EAP:
Hai Shalom5daf0ce2019-04-22 17:50:48 -0700893 switch (mEapType) {
894 case EAP_WPA:
895 return concise ? context.getString(R.string.wifi_security_short_eap_wpa) :
896 context.getString(R.string.wifi_security_eap_wpa);
897 case EAP_WPA2_WPA3:
898 return concise
899 ? context.getString(R.string.wifi_security_short_eap_wpa2_wpa3) :
900 context.getString(R.string.wifi_security_eap_wpa2_wpa3);
901 case EAP_UNKNOWN:
902 default:
903 return concise
904 ? context.getString(R.string.wifi_security_short_eap) :
905 context.getString(R.string.wifi_security_eap);
906 }
Hai Shalomaa6f9202018-10-16 14:30:02 -0700907 case SECURITY_EAP_SUITE_B:
908 return concise ? context.getString(R.string.wifi_security_short_eap_suiteb) :
909 context.getString(R.string.wifi_security_eap_suiteb);
Jason Monkd52356a2015-01-28 10:40:41 -0500910 case SECURITY_PSK:
911 switch (pskType) {
912 case PSK_WPA:
913 return concise ? context.getString(R.string.wifi_security_short_wpa) :
914 context.getString(R.string.wifi_security_wpa);
915 case PSK_WPA2:
916 return concise ? context.getString(R.string.wifi_security_short_wpa2) :
917 context.getString(R.string.wifi_security_wpa2);
918 case PSK_WPA_WPA2:
919 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
920 context.getString(R.string.wifi_security_wpa_wpa2);
921 case PSK_UNKNOWN:
922 default:
923 return concise ? context.getString(R.string.wifi_security_short_psk_generic)
924 : context.getString(R.string.wifi_security_psk_generic);
925 }
926 case SECURITY_WEP:
927 return concise ? context.getString(R.string.wifi_security_short_wep) :
928 context.getString(R.string.wifi_security_wep);
Hai Shalomaa6f9202018-10-16 14:30:02 -0700929 case SECURITY_SAE:
Hai Shalom1c937182019-05-08 14:39:50 -0700930 case SECURITY_PSK_SAE_TRANSITION:
Hai Shalomc03fc882019-04-08 15:08:19 -0700931 if (pskType == PSK_SAE) {
932 return concise ? context.getString(R.string.wifi_security_short_psk_sae) :
933 context.getString(R.string.wifi_security_psk_sae);
934 } else {
935 return concise ? context.getString(R.string.wifi_security_short_sae) :
936 context.getString(R.string.wifi_security_sae);
937 }
Hai Shalom2195d1f2019-05-13 15:31:41 -0700938 case SECURITY_OWE_TRANSITION:
939 if (mConfig != null && getSecurity(mConfig) == SECURITY_OWE) {
940 return concise ? context.getString(R.string.wifi_security_short_owe) :
941 context.getString(R.string.wifi_security_owe);
942 }
943 return concise ? "" : context.getString(R.string.wifi_security_none);
Hai Shalomaa6f9202018-10-16 14:30:02 -0700944 case SECURITY_OWE:
945 return concise ? context.getString(R.string.wifi_security_short_owe) :
946 context.getString(R.string.wifi_security_owe);
Jason Monkd52356a2015-01-28 10:40:41 -0500947 case SECURITY_NONE:
948 default:
949 return concise ? "" : context.getString(R.string.wifi_security_none);
950 }
951 }
952
Jason Monk6980d122015-06-15 10:07:55 -0400953 public String getSsidStr() {
Jason Monkd52356a2015-01-28 10:40:41 -0500954 return ssid;
955 }
956
Jason Monk60a82ff2016-02-25 13:55:03 -0500957 public String getBssid() {
958 return bssid;
959 }
960
Jason Monk6980d122015-06-15 10:07:55 -0400961 public CharSequence getSsid() {
pastychanga2998fc2018-06-26 13:37:34 +0800962 return ssid;
Jason Monk6980d122015-06-15 10:07:55 -0400963 }
964
Quang Luong19429e42019-02-20 17:10:51 -0800965 /**
966 * Returns the name associated with the stored config.
967 * @deprecated Please use {@link #getTitle()} instead to get the display name of an AccessPoint.
968 */
969 @Deprecated
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700970 public String getConfigName() {
971 if (mConfig != null && mConfig.isPasspoint()) {
972 return mConfig.providerFriendlyName;
Peter Qiuced37db2017-03-14 15:51:22 -0700973 } else if (mFqdn != null) {
974 return mProviderFriendlyName;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700975 } else {
976 return ssid;
977 }
978 }
979
Jason Monkd52356a2015-01-28 10:40:41 -0500980 public DetailedState getDetailedState() {
Fan Zhang6acb7662016-10-17 12:40:03 -0700981 if (mNetworkInfo != null) {
982 return mNetworkInfo.getDetailedState();
983 }
984 Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
985 return null;
Jason Monkd52356a2015-01-28 10:40:41 -0500986 }
987
Peter Qiu280581b2017-07-24 14:18:56 -0700988 public boolean isCarrierAp() {
989 return mIsCarrierAp;
990 }
991
992 public int getCarrierApEapType() {
993 return mCarrierApEapType;
994 }
995
996 public String getCarrierName() {
997 return mCarrierName;
998 }
999
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001000 public String getSavedNetworkSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -07001001 WifiConfiguration config = mConfig;
1002 if (config != null) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -07001003 PackageManager pm = mContext.getPackageManager();
1004 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
Fan Zhang51365c32016-09-20 12:22:18 -07001005 int userId = UserHandle.getUserId(config.creatorUid);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -07001006 ApplicationInfo appInfo = null;
Fan Zhang51365c32016-09-20 12:22:18 -07001007 if (config.creatorName != null && config.creatorName.equals(systemName)) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -07001008 appInfo = mContext.getApplicationInfo();
1009 } else {
1010 try {
1011 IPackageManager ipm = AppGlobals.getPackageManager();
Fan Zhang51365c32016-09-20 12:22:18 -07001012 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -07001013 } catch (RemoteException rex) {
1014 }
1015 }
1016 if (appInfo != null &&
1017 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
1018 !appInfo.packageName.equals(
1019 mContext.getString(R.string.certinstaller_package))) {
1020 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
1021 }
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001022 }
Arc Wange706be82019-10-16 15:25:56 +08001023
1024 if (isPasspointConfigurationR1() && isExpired()) {
1025 return mContext.getString(R.string.wifi_passpoint_expired);
1026 }
Sanket Padawe56cfbfb2015-05-05 20:10:46 -07001027 return "";
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001028 }
1029
Quang Luong7054e922018-12-07 16:44:18 -08001030 /**
1031 * Returns the display title for the AccessPoint, such as for an AccessPointPreference's title.
1032 */
1033 public String getTitle() {
1034 if (isPasspoint()) {
1035 return mConfig.providerFriendlyName;
Quang Luong19429e42019-02-20 17:10:51 -08001036 } else if (isPasspointConfig()) {
1037 return mProviderFriendlyName;
Quang Luong9051dfd2018-12-12 12:49:24 -08001038 } else if (isOsuProvider()) {
1039 return mOsuProvider.getFriendlyName();
Quang Luong7054e922018-12-07 16:44:18 -08001040 } else {
1041 return getSsidStr();
1042 }
1043 }
1044
Jason Monkd52356a2015-01-28 10:40:41 -05001045 public String getSummary() {
Quang Luong19bae88c2018-12-14 16:05:05 -08001046 return getSettingsSummary();
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001047 }
1048
1049 public String getSettingsSummary() {
clownshen78be6542019-04-24 19:16:24 +08001050 return getSettingsSummary(false /*convertSavedAsDisconnected*/);
1051 }
1052
1053 /**
1054 * Returns the summary for the AccessPoint.
1055 */
1056 public String getSettingsSummary(boolean convertSavedAsDisconnected) {
Arc Wange706be82019-10-16 15:25:56 +08001057 if (isPasspointConfigurationR1() && isExpired()) {
1058 return mContext.getString(R.string.wifi_passpoint_expired);
1059 }
1060
Jason Monkd52356a2015-01-28 10:40:41 -05001061 // Update to new summary
1062 StringBuilder summary = new StringBuilder();
1063
Quang Luong919d4642019-01-03 14:46:06 -08001064 if (isOsuProvider()) {
1065 if (mOsuProvisioningComplete) {
Quang Luongf005c882019-01-29 16:32:03 -08001066 summary.append(mContext.getString(R.string.osu_sign_up_complete));
Quang Luong919d4642019-01-03 14:46:06 -08001067 } else if (mOsuFailure != null) {
1068 summary.append(mOsuFailure);
1069 } else if (mOsuStatus != null) {
1070 summary.append(mOsuStatus);
1071 } else {
Quang Luongf005c882019-01-29 16:32:03 -08001072 summary.append(mContext.getString(R.string.tap_to_sign_up));
Quang Luong919d4642019-01-03 14:46:06 -08001073 }
1074 } else if (isActive()) {
Quang Luong4c23e8c2019-06-07 11:32:16 -07001075 if (getDetailedState() == DetailedState.CONNECTED && mIsCarrierAp) {
Quang Luong19bae88c2018-12-14 16:05:05 -08001076 // This is the active connection on a carrier AP
1077 summary.append(String.format(mContext.getString(R.string.connected_via_carrier),
1078 mCarrierName));
1079 } else {
Quang Luong98d06bd2019-01-30 13:42:26 -08001080 summary.append(getSummary(mContext, /* ssid */ null, getDetailedState(),
Roshan Piuse9b8e502019-01-23 15:42:44 -08001081 mInfo != null && mInfo.isEphemeral(),
David Sud9bb9a82019-11-13 10:49:01 -08001082 mInfo != null ? mInfo.getAppPackageName() : null));
Jason Monkd52356a2015-01-28 10:40:41 -05001083 }
Quang Luong19bae88c2018-12-14 16:05:05 -08001084 } else { // not active
1085 if (mConfig != null && mConfig.hasNoInternetAccess()) {
1086 int messageID = mConfig.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
1087 ? R.string.wifi_no_internet_no_reconnect
1088 : R.string.wifi_no_internet;
1089 summary.append(mContext.getString(messageID));
1090 } else if (mConfig != null && !mConfig.getNetworkSelectionStatus().isNetworkEnabled()) {
1091 WifiConfiguration.NetworkSelectionStatus networkStatus =
1092 mConfig.getNetworkSelectionStatus();
1093 switch (networkStatus.getNetworkSelectionDisableReason()) {
1094 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
1095 summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
Glen Kuhne446afac2017-06-22 16:02:33 -07001096 break;
Quang Luong19bae88c2018-12-14 16:05:05 -08001097 case WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WRONG_PASSWORD:
1098 summary.append(mContext.getString(R.string.wifi_check_password_try_again));
Glen Kuhne446afac2017-06-22 16:02:33 -07001099 break;
Quang Luong19bae88c2018-12-14 16:05:05 -08001100 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
1101 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
1102 summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
1103 break;
1104 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
1105 summary.append(mContext.getString(R.string.wifi_disabled_generic));
1106 break;
1107 }
1108 } else if (mConfig != null && mConfig.getNetworkSelectionStatus().isNotRecommended()) {
1109 summary.append(mContext.getString(
1110 R.string.wifi_disabled_by_recommendation_provider));
1111 } else if (mIsCarrierAp) {
1112 summary.append(String.format(mContext.getString(
1113 R.string.available_via_carrier), mCarrierName));
1114 } else if (!isReachable()) { // Wifi out of range
1115 summary.append(mContext.getString(R.string.wifi_not_in_range));
1116 } else { // In range, not disabled.
1117 if (mConfig != null) { // Is saved network
1118 // Last attempt to connect to this failed. Show reason why
1119 switch (mConfig.recentFailure.getAssociationStatus()) {
1120 case WifiConfiguration.RecentFailure.STATUS_AP_UNABLE_TO_HANDLE_NEW_STA:
1121 summary.append(mContext.getString(
1122 R.string.wifi_ap_unable_to_handle_new_sta));
1123 break;
1124 default:
clownshen78be6542019-04-24 19:16:24 +08001125 if (convertSavedAsDisconnected) {
1126 // Disconnected
1127 summary.append(mContext.getString(R.string.wifi_disconnected));
1128 } else {
1129 // "Saved"
1130 summary.append(mContext.getString(R.string.wifi_remembered));
1131 }
Quang Luong19bae88c2018-12-14 16:05:05 -08001132 break;
1133 }
Glen Kuhne446afac2017-06-22 16:02:33 -07001134 }
Jason Monkd52356a2015-01-28 10:40:41 -05001135 }
1136 }
1137
Quang Luong19bae88c2018-12-14 16:05:05 -08001138
1139
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -08001140 if (isVerboseLoggingEnabled()) {
Quang Luong19bae88c2018-12-14 16:05:05 -08001141 summary.append(WifiUtils.buildLoggingSummary(this, mConfig));
Jason Monkd52356a2015-01-28 10:40:41 -05001142 }
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001143
Quang Luong19bae88c2018-12-14 16:05:05 -08001144 if (mConfig != null && (WifiUtils.isMeteredOverridden(mConfig) || mConfig.meteredHint)) {
Salvador Martinez6f6fe752018-03-21 16:33:53 -07001145 return mContext.getResources().getString(
1146 R.string.preference_summary_default_combination,
Quang Luong19bae88c2018-12-14 16:05:05 -08001147 WifiUtils.getMeteredLabel(mContext, mConfig),
Salvador Martinez6f6fe752018-03-21 16:33:53 -07001148 summary.toString());
1149 }
1150
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -07001151 // If Speed label and summary are both present, use the preference combination to combine
1152 // the two, else return the non-null one.
1153 if (getSpeedLabel() != null && summary.length() != 0) {
Sundeep Ghumand3171ca2017-07-12 23:02:24 -07001154 return mContext.getResources().getString(
1155 R.string.preference_summary_default_combination,
1156 getSpeedLabel(),
1157 summary.toString());
Eric Schwarzenbachf4f3842b2017-07-17 16:45:04 -07001158 } else if (getSpeedLabel() != null) {
1159 return getSpeedLabel();
Sundeep Ghumand3171ca2017-07-12 23:02:24 -07001160 } else {
1161 return summary.toString();
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001162 }
Jason Monkd52356a2015-01-28 10:40:41 -05001163 }
1164
1165 /**
Jason Monkd52356a2015-01-28 10:40:41 -05001166 * Return whether this is the active connection.
1167 * For ephemeral connections (networkId is invalid), this returns false if the network is
1168 * disconnected.
1169 */
1170 public boolean isActive() {
1171 return mNetworkInfo != null &&
1172 (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
1173 mNetworkInfo.getState() != State.DISCONNECTED);
1174 }
1175
1176 public boolean isConnectable() {
1177 return getLevel() != -1 && getDetailedState() == null;
1178 }
1179
1180 public boolean isEphemeral() {
Shirish Kalelec7a38ef2015-06-25 13:55:33 -07001181 return mInfo != null && mInfo.isEphemeral() &&
1182 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
Jason Monkd52356a2015-01-28 10:40:41 -05001183 }
1184
Peter Qiuced37db2017-03-14 15:51:22 -07001185 /**
1186 * Return true if this AccessPoint represents a Passpoint AP.
1187 */
Vinit Deshpande5b7352c2015-07-09 16:53:12 -07001188 public boolean isPasspoint() {
1189 return mConfig != null && mConfig.isPasspoint();
1190 }
1191
Mitchell Wills5a42db22015-08-03 09:46:08 -07001192 /**
Peter Qiuced37db2017-03-14 15:51:22 -07001193 * Return true if this AccessPoint represents a Passpoint provider configuration.
1194 */
1195 public boolean isPasspointConfig() {
Quang Luonge747f592019-05-02 11:22:33 -07001196 return mFqdn != null && mConfig == null;
Peter Qiuced37db2017-03-14 15:51:22 -07001197 }
1198
1199 /**
Quang Luong9051dfd2018-12-12 12:49:24 -08001200 * Return true if this AccessPoint represents an OSU Provider.
1201 */
1202 public boolean isOsuProvider() {
1203 return mOsuProvider != null;
1204 }
1205
1206 /**
Arc Wange706be82019-10-16 15:25:56 +08001207 * Return true if this AccessPoint is expired.
1208 */
1209 public boolean isExpired() {
1210 if (mSubscriptionExpirationTimeInMillis <= 0) {
1211 // Expiration time not specified.
1212 return false;
1213 } else {
1214 return System.currentTimeMillis() >= mSubscriptionExpirationTimeInMillis;
1215 }
1216 }
1217
1218 public boolean isPasspointConfigurationR1() {
1219 return mPasspointConfigurationVersion == PasspointConfigurationVersion.NO_OSU_PROVISIONED;
1220 }
1221
1222 /**
1223 * Return true if {@link PasspointConfiguration#isOsuProvisioned} is true, this may refer to R2
1224 * or R3.
1225 */
1226 public boolean isPasspointConfigurationOsuProvisioned() {
1227 return mPasspointConfigurationVersion == PasspointConfigurationVersion.OSU_PROVISIONED;
1228 }
1229
1230 /**
Quang Luong4d194842018-12-18 16:59:49 -08001231 * Starts the OSU Provisioning flow.
1232 */
Quang Luong7cfa5272019-03-08 12:37:15 -08001233 public void startOsuProvisioning(@Nullable WifiManager.ActionListener connectListener) {
1234 mConnectListener = connectListener;
1235
1236 getWifiManager().startSubscriptionProvisioning(
Quang Luong4d194842018-12-18 16:59:49 -08001237 mOsuProvider,
Ecco Parke67533e2019-03-01 15:09:35 -08001238 mContext.getMainExecutor(),
1239 new AccessPointProvisioningCallback()
Quang Luong4d194842018-12-18 16:59:49 -08001240 );
1241 }
1242
1243 /**
Mitchell Wills5a42db22015-08-03 09:46:08 -07001244 * Return whether the given {@link WifiInfo} is for this access point.
1245 * If the current AP does not have a network Id then the config is used to
1246 * match based on SSID and security.
1247 */
1248 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
Quang Luong1f1207b2019-02-19 17:35:50 -08001249 if (info.isOsuAp() || mOsuStatus != null) {
1250 return (info.isOsuAp() && mOsuStatus != null);
1251 } else if (info.isPasspointAp() || isPasspoint()) {
1252 return (info.isPasspointAp() && isPasspoint()
Quang Luong2a6cdc52019-03-05 17:35:45 -08001253 && TextUtils.equals(info.getPasspointFqdn(), mConfig.FQDN));
Quang Luong919d4642019-01-03 14:46:06 -08001254 }
1255
Quang Luong1f1207b2019-02-19 17:35:50 -08001256 if (networkId != WifiConfiguration.INVALID_NETWORK_ID) {
Jason Monkd52356a2015-01-28 10:40:41 -05001257 return networkId == info.getNetworkId();
Mitchell Wills5a42db22015-08-03 09:46:08 -07001258 } else if (config != null) {
Hai Shalom1c937182019-05-08 14:39:50 -07001259 return isKeyEqual(getKey(config));
Quang Luong1f1207b2019-02-19 17:35:50 -08001260 } else {
Jason Monkd52356a2015-01-28 10:40:41 -05001261 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
1262 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
1263 // TODO: Handle hex string SSIDs.
Quang Luong1f1207b2019-02-19 17:35:50 -08001264 return TextUtils.equals(removeDoubleQuotes(info.getSSID()), ssid);
Jason Monkd52356a2015-01-28 10:40:41 -05001265 }
1266 }
1267
1268 public boolean isSaved() {
Quang Luong48ad03a2019-02-14 11:51:01 -08001269 return mConfig != null;
Jason Monkd52356a2015-01-28 10:40:41 -05001270 }
1271
1272 public Object getTag() {
1273 return mTag;
1274 }
1275
1276 public void setTag(Object tag) {
1277 mTag = tag;
1278 }
1279
1280 /**
1281 * Generate and save a default wifiConfiguration with common values.
1282 * Can only be called for unsecured networks.
1283 */
1284 public void generateOpenNetworkConfig() {
Cyril Leede476262019-06-03 19:19:43 +08001285 if (!isOpenNetwork()) {
Jason Monkd52356a2015-01-28 10:40:41 -05001286 throw new IllegalStateException();
Hai Shalomaa6f9202018-10-16 14:30:02 -07001287 }
Jason Monkd52356a2015-01-28 10:40:41 -05001288 if (mConfig != null)
1289 return;
1290 mConfig = new WifiConfiguration();
1291 mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
Hai Shalomaa6f9202018-10-16 14:30:02 -07001292
Hai Shalom2195d1f2019-05-13 15:31:41 -07001293 if (security == SECURITY_NONE || !getWifiManager().isEasyConnectSupported()) {
Hai Shalomaa6f9202018-10-16 14:30:02 -07001294 mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
1295 } else {
1296 mConfig.allowedKeyManagement.set(KeyMgmt.OWE);
1297 mConfig.requirePMF = true;
1298 }
Jason Monkd52356a2015-01-28 10:40:41 -05001299 }
1300
Jason Monkd52356a2015-01-28 10:40:41 -05001301 public void saveWifiState(Bundle savedState) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001302 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
1303 savedState.putInt(KEY_SECURITY, security);
Sundeep Ghumana28050a2017-07-12 22:09:25 -07001304 savedState.putInt(KEY_SPEED, mSpeed);
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001305 savedState.putInt(KEY_PSKTYPE, pskType);
Hai Shalom5daf0ce2019-04-22 17:50:48 -07001306 savedState.putInt(KEY_EAPTYPE, mEapType);
Vinit Deshpandefcd46122015-06-11 18:22:23 -07001307 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
Jason Monkd52356a2015-01-28 10:40:41 -05001308 savedState.putParcelable(KEY_WIFIINFO, mInfo);
Quang Luong9574a1b2019-06-06 16:51:53 -07001309 synchronized (mLock) {
1310 savedState.putParcelableArray(KEY_SCANRESULTS,
1311 mScanResults.toArray(new Parcelable[mScanResults.size()
1312 + mExtraScanResults.size()]));
1313 }
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001314 savedState.putParcelableArrayList(KEY_SCOREDNETWORKCACHE,
1315 new ArrayList<>(mScoredNetworkCache.values()));
Jason Monkd52356a2015-01-28 10:40:41 -05001316 if (mNetworkInfo != null) {
1317 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
1318 }
Peter Qiuced37db2017-03-14 15:51:22 -07001319 if (mFqdn != null) {
1320 savedState.putString(KEY_FQDN, mFqdn);
1321 }
1322 if (mProviderFriendlyName != null) {
1323 savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName);
1324 }
Peter Qiu280581b2017-07-24 14:18:56 -07001325 savedState.putBoolean(KEY_IS_CARRIER_AP, mIsCarrierAp);
1326 savedState.putInt(KEY_CARRIER_AP_EAP_TYPE, mCarrierApEapType);
1327 savedState.putString(KEY_CARRIER_NAME, mCarrierName);
Arc Wange706be82019-10-16 15:25:56 +08001328 savedState.putLong(KEY_SUBSCRIPTION_EXPIRATION_TIME_IN_MILLIS,
1329 mSubscriptionExpirationTimeInMillis);
1330 savedState.putInt(KEY_PASSPOINT_CONFIGURATION_VERSION, mPasspointConfigurationVersion);
Jason Monkd52356a2015-01-28 10:40:41 -05001331 }
1332
1333 public void setListener(AccessPointListener listener) {
1334 mAccessPointListener = listener;
1335 }
1336
Hai Shalom55796042019-11-21 19:25:52 +00001337 private static final String sPskSuffix = "," + String.valueOf(SECURITY_PSK);
1338 private static final String sSaeSuffix = "," + String.valueOf(SECURITY_SAE);
1339 private static final String sPskSaeSuffix = "," + String.valueOf(SECURITY_PSK_SAE_TRANSITION);
1340 private static final String sOweSuffix = "," + String.valueOf(SECURITY_OWE);
1341 private static final String sOpenSuffix = "," + String.valueOf(SECURITY_NONE);
1342 private static final String sOweTransSuffix = "," + String.valueOf(SECURITY_OWE_TRANSITION);
1343
Hai Shalom1c937182019-05-08 14:39:50 -07001344 private boolean isKeyEqual(String compareTo) {
1345 if (mKey == null) {
1346 return false;
1347 }
Hai Shalom55796042019-11-21 19:25:52 +00001348
1349 if (compareTo.endsWith(sPskSuffix) || compareTo.endsWith(sSaeSuffix)) {
1350 if (mKey.endsWith(sPskSaeSuffix)) {
1351 // Special handling for PSK-SAE transition mode. If the AP has advertised both,
1352 // we compare the key with both PSK and SAE for a match.
1353 return TextUtils.equals(mKey.substring(0, mKey.lastIndexOf(',')),
1354 compareTo.substring(0, compareTo.lastIndexOf(',')));
1355 }
1356 }
1357 if (compareTo.endsWith(sOpenSuffix) || compareTo.endsWith(sOweSuffix)) {
1358 if (mKey.endsWith(sOweTransSuffix)) {
1359 // Special handling for OWE/Open networks. If AP advertises OWE in transition mode
1360 // and we have an Open network saved, allow this connection to be established.
1361 return TextUtils.equals(mKey.substring(0, mKey.lastIndexOf(',')),
1362 compareTo.substring(0, compareTo.lastIndexOf(',')));
1363 }
1364 }
Hai Shalom1c937182019-05-08 14:39:50 -07001365 return mKey.equals(compareTo);
1366 }
1367
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001368 /**
Quang Luong8123f772019-02-08 16:30:12 -08001369 * Sets {@link #mScanResults} to the given collection and updates info based on the best RSSI
1370 * scan result.
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001371 *
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001372 * @param scanResults a collection of scan results to add to the internal set
Sundeep Ghumand1e44922017-08-07 11:21:38 -07001373 */
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001374 void setScanResults(Collection<ScanResult> scanResults) {
Quang Luong8123f772019-02-08 16:30:12 -08001375 if (CollectionUtils.isEmpty(scanResults)) {
1376 Log.d(TAG, "Cannot set scan results to empty list");
1377 return;
1378 }
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001379
Quang Luong7054e922018-12-07 16:44:18 -08001380 // Validate scan results are for current AP only by matching SSID/BSSID
Quang Luong9051dfd2018-12-12 12:49:24 -08001381 // Passpoint networks are not bound to a specific SSID/BSSID, so skip this for passpoint.
Quang Luong8123f772019-02-08 16:30:12 -08001382 if (mKey != null && !isPasspoint() && !isOsuProvider()) {
Quang Luong7054e922018-12-07 16:44:18 -08001383 for (ScanResult result : scanResults) {
1384 String scanResultKey = AccessPoint.getKey(result);
Hai Shalom1c937182019-05-08 14:39:50 -07001385 if (!isKeyEqual(scanResultKey)) {
Quang Luong8123f772019-02-08 16:30:12 -08001386 Log.d(TAG, String.format(
Quang Luong7054e922018-12-07 16:44:18 -08001387 "ScanResult %s\nkey of %s did not match current AP key %s",
Quang Luong8123f772019-02-08 16:30:12 -08001388 result, scanResultKey, mKey));
1389 return;
Quang Luong7054e922018-12-07 16:44:18 -08001390 }
Jason Monkd52356a2015-01-28 10:40:41 -05001391 }
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001392 }
1393
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001394 int oldLevel = getLevel();
Quang Luong9574a1b2019-06-06 16:51:53 -07001395 synchronized (mLock) {
1396 mScanResults.clear();
1397 mScanResults.addAll(scanResults);
1398 }
Quang Luong8123f772019-02-08 16:30:12 -08001399 updateBestRssiInfo();
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001400 int newLevel = getLevel();
1401
1402 // If newLevel is 0, there will be no displayed Preference since the AP is unreachable
1403 if (newLevel > 0 && newLevel != oldLevel) {
1404 // Only update labels on visible rssi changes
1405 updateSpeed();
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001406 ThreadUtils.postOnMainThread(() -> {
1407 if (mAccessPointListener != null) {
1408 mAccessPointListener.onLevelChanged(this);
1409 }
1410 });
1411
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001412 }
1413
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001414 ThreadUtils.postOnMainThread(() -> {
1415 if (mAccessPointListener != null) {
1416 mAccessPointListener.onAccessPointChanged(this);
1417 }
1418 });
Quang Luong8123f772019-02-08 16:30:12 -08001419 }
Sundeep Ghuman04f7f342018-01-23 19:18:31 -08001420
Quang Luong8123f772019-02-08 16:30:12 -08001421 /**
1422 * Sets the internal scan result cache to the list of home scans.
1423 * If there are no home scans, then the roaming scan list is used, and the AccessPoint is
1424 * marked as roaming.
1425 */
1426 void setScanResultsPasspoint(
1427 @Nullable Collection<ScanResult> homeScans,
1428 @Nullable Collection<ScanResult> roamingScans) {
Quang Luong9574a1b2019-06-06 16:51:53 -07001429 synchronized (mLock) {
1430 mExtraScanResults.clear();
1431 if (!CollectionUtils.isEmpty(homeScans)) {
1432 mIsRoaming = false;
1433 if (!CollectionUtils.isEmpty(roamingScans)) {
1434 mExtraScanResults.addAll(roamingScans);
1435 }
1436 setScanResults(homeScans);
1437 } else if (!CollectionUtils.isEmpty(roamingScans)) {
1438 mIsRoaming = true;
1439 setScanResults(roamingScans);
Jason Monkd52356a2015-01-28 10:40:41 -05001440 }
Jason Monkd52356a2015-01-28 10:40:41 -05001441 }
Jason Monkd52356a2015-01-28 10:40:41 -05001442 }
1443
Quang Luong9051dfd2018-12-12 12:49:24 -08001444 /**
1445 * Attempt to update the AccessPoint with the current connection info.
1446 * This is used to set an AccessPoint to the active one if the connection info matches, or
1447 * conversely to set an AccessPoint to inactive if the connection info does not match. The RSSI
1448 * is also updated upon a match. Listeners will be notified if an update occurred.
1449 *
1450 * This is called in {@link WifiTracker#updateAccessPoints} as well as in callbacks for handling
1451 * NETWORK_STATE_CHANGED_ACTION, RSSI_CHANGED_ACTION, and onCapabilitiesChanged in WifiTracker.
1452 *
1453 * Returns true if an update occurred.
1454 */
Sundeep Ghumand911da32017-07-05 20:06:05 -07001455 public boolean update(
1456 @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001457 boolean updated = false;
1458 final int oldLevel = getLevel();
Mitchell Wills5a42db22015-08-03 09:46:08 -07001459 if (info != null && isInfoForThisAccessPoint(config, info)) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001460 updated = (mInfo == null);
Quang Luong1f1207b2019-02-19 17:35:50 -08001461 if (!isPasspoint() && mConfig != config) {
Sundeep Ghumanf4d33022017-06-05 19:47:36 -07001462 // We do not set updated = true as we do not want to increase the amount of sorting
1463 // and copying performed in WifiTracker at this time. If issues involving refresh
1464 // are still seen, we will investigate further.
1465 update(config); // Notifies the AccessPointListener of the change
1466 }
Glen Kuhned38708c2017-07-19 14:53:34 -07001467 if (mRssi != info.getRssi() && info.getRssi() != WifiInfo.INVALID_RSSI) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001468 mRssi = info.getRssi();
1469 updated = true;
Sundeep Ghuman5c5cd7a2017-05-03 12:45:44 -07001470 } else if (mNetworkInfo != null && networkInfo != null
1471 && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) {
Sundeep Ghuman96a53572017-04-20 21:25:41 -07001472 updated = true;
Jason Monkd52356a2015-01-28 10:40:41 -05001473 }
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001474 mInfo = info;
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001475 mNetworkInfo = networkInfo;
Jason Monkd52356a2015-01-28 10:40:41 -05001476 } else if (mInfo != null) {
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001477 updated = true;
Jason Monkd52356a2015-01-28 10:40:41 -05001478 mInfo = null;
1479 mNetworkInfo = null;
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001480 }
1481 if (updated && mAccessPointListener != null) {
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001482 ThreadUtils.postOnMainThread(() -> {
1483 if (mAccessPointListener != null) {
1484 mAccessPointListener.onAccessPointChanged(this);
1485 }
1486 });
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001487
1488 if (oldLevel != getLevel() /* current level */) {
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001489 ThreadUtils.postOnMainThread(() -> {
1490 if (mAccessPointListener != null) {
1491 mAccessPointListener.onLevelChanged(this);
1492 }
1493 });
Jason Monkd52356a2015-01-28 10:40:41 -05001494 }
1495 }
Sundeep Ghumandb9b94c2017-09-06 11:46:21 -07001496
Sundeep Ghuman8c792882017-04-04 17:23:29 -07001497 return updated;
Jason Monkd52356a2015-01-28 10:40:41 -05001498 }
1499
Sundeep Ghumand911da32017-07-05 20:06:05 -07001500 void update(@Nullable WifiConfiguration config) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001501 mConfig = config;
Quang Luongc825db12019-07-15 18:11:16 -07001502 if (mConfig != null && !isPasspoint()) {
Quang Luong7054e922018-12-07 16:44:18 -08001503 ssid = removeDoubleQuotes(mConfig.SSID);
1504 }
Sundeep Ghumand911da32017-07-05 20:06:05 -07001505 networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID;
Sundeep Ghuman5d14fd72018-02-15 14:49:15 -08001506 ThreadUtils.postOnMainThread(() -> {
1507 if (mAccessPointListener != null) {
1508 mAccessPointListener.onAccessPointChanged(this);
1509 }
1510 });
Vinit Deshpandefc406002015-04-15 18:10:55 -07001511 }
Shirish Kalelec7a38ef2015-06-25 13:55:33 -07001512
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001513 @VisibleForTesting
Sanket Padawe0775a982015-08-19 14:57:46 -07001514 void setRssi(int rssi) {
1515 mRssi = rssi;
1516 }
1517
Sundeep Ghuman54bdcfa2017-03-08 19:52:05 -08001518 /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */
1519 void setUnreachable() {
1520 setRssi(AccessPoint.UNREACHABLE_RSSI);
1521 }
1522
Sundeep Ghuman55adc6b2017-06-05 16:46:59 -07001523 int getSpeed() { return mSpeed;}
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001524
1525 @Nullable
1526 String getSpeedLabel() {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001527 return getSpeedLabel(mSpeed);
1528 }
1529
1530 @Nullable
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001531 @Speed
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001532 private static int roundToClosestSpeedEnum(int speed) {
Sundeep Ghumanbe3a74c2017-08-01 17:50:59 -07001533 if (speed < Speed.SLOW) {
1534 return Speed.NONE;
1535 } else if (speed < (Speed.SLOW + Speed.MODERATE) / 2) {
1536 return Speed.SLOW;
1537 } else if (speed < (Speed.MODERATE + Speed.FAST) / 2) {
1538 return Speed.MODERATE;
1539 } else if (speed < (Speed.FAST + Speed.VERY_FAST) / 2) {
1540 return Speed.FAST;
1541 } else {
1542 return Speed.VERY_FAST;
1543 }
1544 }
1545
1546 @Nullable
jackqdyulei9ee9b392017-12-22 11:31:49 -08001547 String getSpeedLabel(@Speed int speed) {
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001548 return getSpeedLabel(mContext, speed);
1549 }
1550
1551 private static String getSpeedLabel(Context context, int speed) {
Eric Schwarzenbach0b8700f2017-07-25 14:32:21 -07001552 switch (speed) {
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001553 case Speed.VERY_FAST:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001554 return context.getString(R.string.speed_label_very_fast);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001555 case Speed.FAST:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001556 return context.getString(R.string.speed_label_fast);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001557 case Speed.MODERATE:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001558 return context.getString(R.string.speed_label_okay);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001559 case Speed.SLOW:
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001560 return context.getString(R.string.speed_label_slow);
Sundeep Ghuman53200ed2017-06-21 16:54:36 -07001561 case Speed.NONE:
Sundeep Ghuman271e5de2017-05-30 14:11:39 -07001562 default:
1563 return null;
1564 }
Sundeep Ghuman5519b7b2016-12-14 17:53:31 -08001565 }
1566
Amin Shaikhe74dbdd2018-03-09 16:05:30 -05001567 /** Return the speed label for a {@link ScoredNetwork} at the specified {@code rssi} level. */
1568 @Nullable
1569 public static String getSpeedLabel(Context context, ScoredNetwork scoredNetwork, int rssi) {
1570 return getSpeedLabel(context, roundToClosestSpeedEnum(scoredNetwork.calculateBadge(rssi)));
1571 }
1572
Dave Schaefer98537432017-02-08 11:26:08 -08001573 /** Return true if the current RSSI is reachable, and false otherwise. */
Sundeep Ghumanaaa8a1b2017-03-13 14:40:56 -07001574 public boolean isReachable() {
Dave Schaefer98537432017-02-08 11:26:08 -08001575 return mRssi != UNREACHABLE_RSSI;
1576 }
1577
Roshan Piuse9b8e502019-01-23 15:42:44 -08001578 private static CharSequence getAppLabel(String packageName, PackageManager packageManager) {
1579 CharSequence appLabel = "";
1580 ApplicationInfo appInfo = null;
1581 try {
1582 int userId = UserHandle.getUserId(UserHandle.USER_CURRENT);
1583 appInfo = packageManager.getApplicationInfoAsUser(packageName, 0 /* flags */, userId);
1584 } catch (PackageManager.NameNotFoundException e) {
1585 Log.e(TAG, "Failed to get app info", e);
1586 return appLabel;
1587 }
1588 if (appInfo != null) {
1589 appLabel = appInfo.loadLabel(packageManager);
1590 }
1591 return appLabel;
1592 }
1593
Jason Monkd52356a2015-01-28 10:40:41 -05001594 public static String getSummary(Context context, String ssid, DetailedState state,
Quang Luong98d06bd2019-01-30 13:42:26 -08001595 boolean isEphemeral, String suggestionOrSpecifierPackageName) {
Quang Luong0a3edf02018-12-17 14:50:58 -08001596 if (state == DetailedState.CONNECTED) {
Quang Luong98d06bd2019-01-30 13:42:26 -08001597 if (isEphemeral && !TextUtils.isEmpty(suggestionOrSpecifierPackageName)) {
Roshan Piuse9b8e502019-01-23 15:42:44 -08001598 CharSequence appLabel =
1599 getAppLabel(suggestionOrSpecifierPackageName, context.getPackageManager());
1600 return context.getString(R.string.connected_via_app, appLabel);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -07001601 } else if (isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -07001602 // Special case for connected + ephemeral networks.
Stephen Chen36dd5cf12017-03-20 13:27:51 -07001603 final NetworkScoreManager networkScoreManager = context.getSystemService(
1604 NetworkScoreManager.class);
1605 NetworkScorerAppData scorer = networkScoreManager.getActiveScorer();
1606 if (scorer != null && scorer.getRecommendationServiceLabel() != null) {
1607 String format = context.getString(R.string.connected_via_network_scorer);
1608 return String.format(format, scorer.getRecommendationServiceLabel());
1609 } else {
1610 return context.getString(R.string.connected_via_network_scorer_default);
1611 }
Vinit Deshpandefc406002015-04-15 18:10:55 -07001612 }
Jason Monkd52356a2015-01-28 10:40:41 -05001613 }
1614
Sanket Padawe7094d222015-05-01 16:55:00 -07001615 // Case when there is wifi connected without internet connectivity.
1616 final ConnectivityManager cm = (ConnectivityManager)
1617 context.getSystemService(Context.CONNECTIVITY_SERVICE);
1618 if (state == DetailedState.CONNECTED) {
1619 IWifiManager wifiManager = IWifiManager.Stub.asInterface(
1620 ServiceManager.getService(Context.WIFI_SERVICE));
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001621 NetworkCapabilities nc = null;
Sanket Padawe7094d222015-05-01 16:55:00 -07001622
1623 try {
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001624 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
1625 } catch (RemoteException e) {}
1626
1627 if (nc != null) {
1628 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
Maurice Lam7f6fc862017-07-12 16:43:49 -07001629 int id = context.getResources()
1630 .getIdentifier("network_available_sign_in", "string", "android");
1631 return context.getString(id);
lucaslinfc731ab2019-03-12 17:52:15 +08001632 } else if (nc.hasCapability(
1633 NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY)) {
1634 return context.getString(R.string.wifi_limited_connection);
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001635 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
lucaslin783f2212019-10-22 18:27:33 +08001636 final String mode = Settings.Global.getString(context.getContentResolver(),
1637 Settings.Global.PRIVATE_DNS_MODE);
1638 if (nc.isPrivateDnsBroken()) {
1639 return context.getString(R.string.private_dns_broken);
1640 } else {
1641 return context.getString(R.string.wifi_connected_no_internet);
1642 }
Lorenzo Colitti1317e042016-12-13 13:30:07 +09001643 }
Sanket Padawe7094d222015-05-01 16:55:00 -07001644 }
1645 }
Fan Zhang6acb7662016-10-17 12:40:03 -07001646 if (state == null) {
1647 Log.w(TAG, "state is null, returning empty summary");
1648 return "";
1649 }
Jason Monkd52356a2015-01-28 10:40:41 -05001650 String[] formats = context.getResources().getStringArray((ssid == null)
1651 ? R.array.wifi_status : R.array.wifi_status_with_ssid);
1652 int index = state.ordinal();
1653
1654 if (index >= formats.length || formats[index].length() == 0) {
Sanket Padawe3e9e5fa2015-05-28 10:41:14 -07001655 return "";
Jason Monkd52356a2015-01-28 10:40:41 -05001656 }
1657 return String.format(formats[index], ssid);
1658 }
1659
Jason Monkd52356a2015-01-28 10:40:41 -05001660 public static String convertToQuotedString(String string) {
1661 return "\"" + string + "\"";
1662 }
1663
1664 private static int getPskType(ScanResult result) {
1665 boolean wpa = result.capabilities.contains("WPA-PSK");
Hai Shalome6194252019-04-08 14:07:42 -07001666 boolean wpa2 = result.capabilities.contains("RSN-PSK");
Hai Shalomc03fc882019-04-08 15:08:19 -07001667 boolean wpa3TransitionMode = result.capabilities.contains("PSK+SAE");
1668 boolean wpa3 = result.capabilities.contains("RSN-SAE");
1669 if (wpa3TransitionMode) {
1670 return PSK_SAE;
1671 } else if (wpa2 && wpa) {
Jason Monkd52356a2015-01-28 10:40:41 -05001672 return PSK_WPA_WPA2;
1673 } else if (wpa2) {
1674 return PSK_WPA2;
1675 } else if (wpa) {
1676 return PSK_WPA;
1677 } else {
Hai Shalomc03fc882019-04-08 15:08:19 -07001678 if (!wpa3) {
1679 // Suppress warning for WPA3 only networks
1680 Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
1681 }
Jason Monkd52356a2015-01-28 10:40:41 -05001682 return PSK_UNKNOWN;
1683 }
1684 }
1685
Hai Shalom5daf0ce2019-04-22 17:50:48 -07001686 private static int getEapType(ScanResult result) {
1687 // WPA2-Enterprise and WPA3-Enterprise (non 192-bit) advertise RSN-EAP-CCMP
1688 if (result.capabilities.contains("RSN-EAP")) {
1689 return EAP_WPA2_WPA3;
1690 }
1691 // WPA-Enterprise advertises WPA-EAP-TKIP
1692 if (result.capabilities.contains("WPA-EAP")) {
1693 return EAP_WPA;
1694 }
1695 return EAP_UNKNOWN;
1696 }
1697
Jason Monkd52356a2015-01-28 10:40:41 -05001698 private static int getSecurity(ScanResult result) {
1699 if (result.capabilities.contains("WEP")) {
1700 return SECURITY_WEP;
Hai Shalom55796042019-11-21 19:25:52 +00001701 } else if (result.capabilities.contains("PSK+SAE")) {
1702 return SECURITY_PSK_SAE_TRANSITION;
Hai Shalomaa6f9202018-10-16 14:30:02 -07001703 } else if (result.capabilities.contains("SAE")) {
1704 return SECURITY_SAE;
Jason Monkd52356a2015-01-28 10:40:41 -05001705 } else if (result.capabilities.contains("PSK")) {
1706 return SECURITY_PSK;
Hai Shalomaa6f9202018-10-16 14:30:02 -07001707 } else if (result.capabilities.contains("EAP_SUITE_B_192")) {
1708 return SECURITY_EAP_SUITE_B;
Jason Monkd52356a2015-01-28 10:40:41 -05001709 } else if (result.capabilities.contains("EAP")) {
1710 return SECURITY_EAP;
Hai Shalom55796042019-11-21 19:25:52 +00001711 } else if (result.capabilities.contains("OWE_TRANSITION")) {
1712 return SECURITY_OWE_TRANSITION;
Hai Shalomaa6f9202018-10-16 14:30:02 -07001713 } else if (result.capabilities.contains("OWE")) {
1714 return SECURITY_OWE;
Jason Monkd52356a2015-01-28 10:40:41 -05001715 }
1716 return SECURITY_NONE;
1717 }
1718
1719 static int getSecurity(WifiConfiguration config) {
Hai Shalomaa6f9202018-10-16 14:30:02 -07001720 if (config.allowedKeyManagement.get(KeyMgmt.SAE)) {
1721 return SECURITY_SAE;
1722 }
Jason Monkd52356a2015-01-28 10:40:41 -05001723 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
1724 return SECURITY_PSK;
1725 }
Hai Shalomaa6f9202018-10-16 14:30:02 -07001726 if (config.allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
1727 return SECURITY_EAP_SUITE_B;
1728 }
Jason Monkd52356a2015-01-28 10:40:41 -05001729 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
1730 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1731 return SECURITY_EAP;
1732 }
Hai Shalomaa6f9202018-10-16 14:30:02 -07001733 if (config.allowedKeyManagement.get(KeyMgmt.OWE)) {
1734 return SECURITY_OWE;
1735 }
Jason Monkd52356a2015-01-28 10:40:41 -05001736 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
1737 }
1738
1739 public static String securityToString(int security, int pskType) {
1740 if (security == SECURITY_WEP) {
1741 return "WEP";
1742 } else if (security == SECURITY_PSK) {
1743 if (pskType == PSK_WPA) {
1744 return "WPA";
1745 } else if (pskType == PSK_WPA2) {
1746 return "WPA2";
1747 } else if (pskType == PSK_WPA_WPA2) {
1748 return "WPA_WPA2";
1749 }
1750 return "PSK";
1751 } else if (security == SECURITY_EAP) {
1752 return "EAP";
Hai Shalomaa6f9202018-10-16 14:30:02 -07001753 } else if (security == SECURITY_SAE) {
1754 return "SAE";
1755 } else if (security == SECURITY_EAP_SUITE_B) {
1756 return "SUITE_B";
1757 } else if (security == SECURITY_OWE) {
1758 return "OWE";
Hai Shalom55796042019-11-21 19:25:52 +00001759 } else if (security == SECURITY_PSK_SAE_TRANSITION) {
1760 return "PSK+SAE";
1761 } else if (security == SECURITY_OWE_TRANSITION) {
1762 return "OWE_TRANSITION";
Jason Monkd52356a2015-01-28 10:40:41 -05001763 }
1764 return "NONE";
1765 }
1766
1767 static String removeDoubleQuotes(String string) {
Jason Monk2b51cc32015-05-13 11:07:53 -04001768 if (TextUtils.isEmpty(string)) {
1769 return "";
1770 }
Jason Monkd52356a2015-01-28 10:40:41 -05001771 int length = string.length();
1772 if ((length > 1) && (string.charAt(0) == '"')
1773 && (string.charAt(length - 1) == '"')) {
1774 return string.substring(1, length - 1);
1775 }
1776 return string;
1777 }
1778
Quang Luong7cfa5272019-03-08 12:37:15 -08001779 private WifiManager getWifiManager() {
1780 if (mWifiManager == null) {
1781 mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
1782 }
1783 return mWifiManager;
1784 }
1785
Sundeep Ghumanbb399912018-01-29 18:31:15 -08001786 /**
Cyril Leede476262019-06-03 19:19:43 +08001787 * Return true if this is an open network AccessPoint.
1788 */
1789 public boolean isOpenNetwork() {
1790 return security == SECURITY_NONE || security == SECURITY_OWE
1791 || security == SECURITY_OWE_TRANSITION;
1792 }
1793
1794 /**
Sundeep Ghumanbb399912018-01-29 18:31:15 -08001795 * Callbacks relaying changes to the AccessPoint representation.
1796 *
1797 * <p>All methods are invoked on the Main Thread.
1798 */
Jason Monkd52356a2015-01-28 10:40:41 -05001799 public interface AccessPointListener {
Quang Luong7cfa5272019-03-08 12:37:15 -08001800
Sundeep Ghumanbb399912018-01-29 18:31:15 -08001801 /**
1802 * Indicates a change to the externally visible state of the AccessPoint trigger by an
1803 * update of ScanResults, saved configuration state, connection state, or score
1804 * (labels/metered) state.
1805 *
1806 * <p>Clients should refresh their view of the AccessPoint to match the updated state when
1807 * this is invoked. Overall this method is extraneous if clients are listening to
1808 * {@link WifiTracker.WifiListener#onAccessPointsChanged()} callbacks.
1809 *
1810 * <p>Examples of changes include signal strength, connection state, speed label, and
1811 * generally anything that would impact the summary string.
1812 *
1813 * @param accessPoint The accessPoint object the listener was registered on which has
1814 * changed
1815 */
1816 @MainThread void onAccessPointChanged(AccessPoint accessPoint);
Sundeep Ghumanbb399912018-01-29 18:31:15 -08001817 /**
1818 * Indicates the "wifi pie signal level" has changed, retrieved via calls to
1819 * {@link AccessPoint#getLevel()}.
1820 *
1821 * <p>This call is a subset of {@link #onAccessPointChanged(AccessPoint)} , hence is also
1822 * extraneous if the client is already reacting to that or the
1823 * {@link WifiTracker.WifiListener#onAccessPointsChanged()} callbacks.
1824 *
1825 * @param accessPoint The accessPoint object the listener was registered on whose level has
1826 * changed
1827 */
1828 @MainThread void onLevelChanged(AccessPoint accessPoint);
Jason Monkd52356a2015-01-28 10:40:41 -05001829 }
Sundeep Ghumanc0cf8482018-01-26 18:23:34 -08001830
1831 private static boolean isVerboseLoggingEnabled() {
1832 return WifiTracker.sVerboseLogging || Log.isLoggable(TAG, Log.VERBOSE);
1833 }
Quang Luong4d194842018-12-18 16:59:49 -08001834
1835 /**
1836 * Callbacks relaying changes to the OSU provisioning status started in startOsuProvisioning().
1837 *
1838 * All methods are invoked on the Main Thread
1839 */
Quang Luong8123f772019-02-08 16:30:12 -08001840 @VisibleForTesting
1841 class AccessPointProvisioningCallback extends ProvisioningCallback {
Quang Luong4d194842018-12-18 16:59:49 -08001842 @Override
1843 @MainThread public void onProvisioningFailure(int status) {
Quang Luongf005c882019-01-29 16:32:03 -08001844 if (TextUtils.equals(mOsuStatus, mContext.getString(R.string.osu_completing_sign_up))) {
1845 mOsuFailure = mContext.getString(R.string.osu_sign_up_failed);
1846 } else {
1847 mOsuFailure = mContext.getString(R.string.osu_connect_failed);
Quang Luong8d40a8e2019-01-02 16:25:38 -08001848 }
1849 mOsuStatus = null;
1850 mOsuProvisioningComplete = false;
1851 ThreadUtils.postOnMainThread(() -> {
1852 if (mAccessPointListener != null) {
1853 mAccessPointListener.onAccessPointChanged(AccessPoint.this);
1854 }
1855 });
Quang Luong4d194842018-12-18 16:59:49 -08001856 }
1857
1858 @Override
1859 @MainThread public void onProvisioningStatus(int status) {
Quang Luongf005c882019-01-29 16:32:03 -08001860 String newStatus = null;
Quang Luong8d40a8e2019-01-02 16:25:38 -08001861 switch (status) {
1862 case OSU_STATUS_AP_CONNECTING:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001863 case OSU_STATUS_AP_CONNECTED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001864 case OSU_STATUS_SERVER_CONNECTING:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001865 case OSU_STATUS_SERVER_VALIDATED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001866 case OSU_STATUS_SERVER_CONNECTED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001867 case OSU_STATUS_INIT_SOAP_EXCHANGE:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001868 case OSU_STATUS_WAITING_FOR_REDIRECT_RESPONSE:
Quang Luongf005c882019-01-29 16:32:03 -08001869 newStatus = String.format(mContext.getString(R.string.osu_opening_provider),
1870 mOsuProvider.getFriendlyName());
Quang Luong8d40a8e2019-01-02 16:25:38 -08001871 break;
1872 case OSU_STATUS_REDIRECT_RESPONSE_RECEIVED:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001873 case OSU_STATUS_SECOND_SOAP_EXCHANGE:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001874 case OSU_STATUS_THIRD_SOAP_EXCHANGE:
Quang Luong8d40a8e2019-01-02 16:25:38 -08001875 case OSU_STATUS_RETRIEVING_TRUST_ROOT_CERTS:
Quang Luongf005c882019-01-29 16:32:03 -08001876 newStatus = mContext.getString(
1877 R.string.osu_completing_sign_up);
Quang Luong8d40a8e2019-01-02 16:25:38 -08001878 break;
1879 }
Quang Luongf005c882019-01-29 16:32:03 -08001880 boolean updated = !TextUtils.equals(mOsuStatus, newStatus);
1881 mOsuStatus = newStatus;
Quang Luong8d40a8e2019-01-02 16:25:38 -08001882 mOsuFailure = null;
1883 mOsuProvisioningComplete = false;
Quang Luongf005c882019-01-29 16:32:03 -08001884 if (updated) {
1885 ThreadUtils.postOnMainThread(() -> {
1886 if (mAccessPointListener != null) {
1887 mAccessPointListener.onAccessPointChanged(AccessPoint.this);
1888 }
1889 });
1890 }
Quang Luong8d40a8e2019-01-02 16:25:38 -08001891 }
1892
1893 @Override
1894 @MainThread public void onProvisioningComplete() {
1895 mOsuProvisioningComplete = true;
1896 mOsuFailure = null;
1897 mOsuStatus = null;
Quang Luong7cfa5272019-03-08 12:37:15 -08001898
Quang Luong8d40a8e2019-01-02 16:25:38 -08001899 ThreadUtils.postOnMainThread(() -> {
1900 if (mAccessPointListener != null) {
1901 mAccessPointListener.onAccessPointChanged(AccessPoint.this);
1902 }
1903 });
Quang Luong7cfa5272019-03-08 12:37:15 -08001904
1905 // Connect to the freshly provisioned network.
1906 WifiManager wifiManager = getWifiManager();
1907
1908 PasspointConfiguration passpointConfig = wifiManager
1909 .getMatchingPasspointConfigsForOsuProviders(Collections.singleton(mOsuProvider))
1910 .get(mOsuProvider);
1911 if (passpointConfig == null) {
1912 Log.e(TAG, "Missing PasspointConfiguration for newly provisioned network!");
1913 if (mConnectListener != null) {
1914 mConnectListener.onFailure(0);
1915 }
1916 return;
1917 }
1918
1919 String fqdn = passpointConfig.getHomeSp().getFqdn();
1920 for (Pair<WifiConfiguration, Map<Integer, List<ScanResult>>> pairing :
1921 wifiManager.getAllMatchingWifiConfigs(wifiManager.getScanResults())) {
1922 WifiConfiguration config = pairing.first;
1923 if (TextUtils.equals(config.FQDN, fqdn)) {
1924 List<ScanResult> homeScans =
1925 pairing.second.get(WifiManager.PASSPOINT_HOME_NETWORK);
1926 List<ScanResult> roamingScans =
1927 pairing.second.get(WifiManager.PASSPOINT_ROAMING_NETWORK);
1928
1929 AccessPoint connectionAp =
1930 new AccessPoint(mContext, config, homeScans, roamingScans);
1931 wifiManager.connect(connectionAp.getConfig(), mConnectListener);
1932 return;
1933 }
1934 }
1935 if (mConnectListener != null) {
1936 mConnectListener.onFailure(0);
1937 }
Quang Luong4d194842018-12-18 16:59:49 -08001938 }
1939 }
Jason Monkd52356a2015-01-28 10:40:41 -05001940}