blob: 28575a9c6decb3a364d4d5fd3ab49edc2107b111 [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
Jason Monk6980d122015-06-15 10:07:55 -040019import android.app.AppGlobals;
Jason Monkd52356a2015-01-28 10:40:41 -050020import android.content.Context;
Jason Monk6980d122015-06-15 10:07:55 -040021import android.content.pm.ApplicationInfo;
22import android.content.pm.IPackageManager;
23import android.content.pm.PackageManager;
Sanket Padawe7094d222015-05-01 16:55:00 -070024import android.net.ConnectivityManager;
25import android.net.Network;
26import android.net.NetworkCapabilities;
Jason Monkd52356a2015-01-28 10:40:41 -050027import android.net.NetworkInfo;
28import android.net.NetworkInfo.DetailedState;
29import android.net.NetworkInfo.State;
Sanket Padawe7094d222015-05-01 16:55:00 -070030import android.net.wifi.IWifiManager;
Jason Monkd52356a2015-01-28 10:40:41 -050031import android.net.wifi.ScanResult;
32import android.net.wifi.WifiConfiguration;
33import android.net.wifi.WifiConfiguration.KeyMgmt;
34import android.net.wifi.WifiInfo;
35import android.net.wifi.WifiManager;
36import android.os.Bundle;
Sanket Padawe7094d222015-05-01 16:55:00 -070037import android.os.RemoteException;
38import android.os.ServiceManager;
Jason Monk6980d122015-06-15 10:07:55 -040039import android.os.UserHandle;
Tony Mantlera0e03dd2016-01-27 15:57:03 -080040import android.support.annotation.NonNull;
Jason Monk6980d122015-06-15 10:07:55 -040041import android.text.Spannable;
42import android.text.SpannableString;
43import android.text.TextUtils;
44import android.text.style.TtsSpan;
Jason Monkd52356a2015-01-28 10:40:41 -050045import android.util.Log;
46import android.util.LruCache;
47
48import com.android.settingslib.R;
49
Vinit Deshpandefcd46122015-06-11 18:22:23 -070050import java.util.ArrayList;
Jason Monkd52356a2015-01-28 10:40:41 -050051import java.util.Map;
52
53
54public class AccessPoint implements Comparable<AccessPoint> {
55 static final String TAG = "SettingsLib.AccessPoint";
56
57 /**
58 * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels
59 */
60 public static final int LOWER_FREQ_24GHZ = 2400;
61
62 /**
63 * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels
64 */
65 public static final int HIGHER_FREQ_24GHZ = 2500;
66
67 /**
68 * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
69 */
70 public static final int LOWER_FREQ_5GHZ = 4900;
71
72 /**
73 * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels
74 */
75 public static final int HIGHER_FREQ_5GHZ = 5900;
76
77
78 /**
79 * Experimental: we should be able to show the user the list of BSSIDs and bands
80 * for that SSID.
81 * For now this data is used only with Verbose Logging so as to show the band and number
82 * of BSSIDs on which that network is seen.
83 */
Vinit Deshpandefcd46122015-06-11 18:22:23 -070084 public LruCache<String, ScanResult> mScanResultCache = new LruCache<String, ScanResult>(32);
85
Jason Monkd52356a2015-01-28 10:40:41 -050086 private static final String KEY_NETWORKINFO = "key_networkinfo";
87 private static final String KEY_WIFIINFO = "key_wifiinfo";
88 private static final String KEY_SCANRESULT = "key_scanresult";
Vinit Deshpandefcd46122015-06-11 18:22:23 -070089 private static final String KEY_SSID = "key_ssid";
90 private static final String KEY_SECURITY = "key_security";
91 private static final String KEY_PSKTYPE = "key_psktype";
92 private static final String KEY_SCANRESULTCACHE = "key_scanresultcache";
Jason Monkd52356a2015-01-28 10:40:41 -050093 private static final String KEY_CONFIG = "key_config";
94
95 /**
96 * These values are matched in string arrays -- changes must be kept in sync
97 */
98 public static final int SECURITY_NONE = 0;
99 public static final int SECURITY_WEP = 1;
100 public static final int SECURITY_PSK = 2;
101 public static final int SECURITY_EAP = 3;
102
103 private static final int PSK_UNKNOWN = 0;
104 private static final int PSK_WPA = 1;
105 private static final int PSK_WPA2 = 2;
106 private static final int PSK_WPA_WPA2 = 3;
107
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800108 public static final int SIGNAL_LEVELS = 4;
109
Jason Monkd52356a2015-01-28 10:40:41 -0500110 private final Context mContext;
111
112 private String ssid;
Jason Monk60a82ff2016-02-25 13:55:03 -0500113 private String bssid;
Jason Monkd52356a2015-01-28 10:40:41 -0500114 private int security;
115 private int networkId = WifiConfiguration.INVALID_NETWORK_ID;
116
117 private int pskType = PSK_UNKNOWN;
118
119 private WifiConfiguration mConfig;
Jason Monkd52356a2015-01-28 10:40:41 -0500120
121 private int mRssi = Integer.MAX_VALUE;
122 private long mSeen = 0;
123
124 private WifiInfo mInfo;
125 private NetworkInfo mNetworkInfo;
126 private AccessPointListener mAccessPointListener;
127
128 private Object mTag;
129
130 public AccessPoint(Context context, Bundle savedState) {
131 mContext = context;
132 mConfig = savedState.getParcelable(KEY_CONFIG);
133 if (mConfig != null) {
134 loadConfig(mConfig);
135 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700136 if (savedState.containsKey(KEY_SSID)) {
137 ssid = savedState.getString(KEY_SSID);
138 }
139 if (savedState.containsKey(KEY_SECURITY)) {
140 security = savedState.getInt(KEY_SECURITY);
141 }
142 if (savedState.containsKey(KEY_PSKTYPE)) {
143 pskType = savedState.getInt(KEY_PSKTYPE);
Jason Monkd52356a2015-01-28 10:40:41 -0500144 }
145 mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO);
146 if (savedState.containsKey(KEY_NETWORKINFO)) {
147 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO);
148 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700149 if (savedState.containsKey(KEY_SCANRESULTCACHE)) {
150 ArrayList<ScanResult> scanResultArrayList =
151 savedState.getParcelableArrayList(KEY_SCANRESULTCACHE);
152 mScanResultCache.evictAll();
153 for (ScanResult result : scanResultArrayList) {
154 mScanResultCache.put(result.BSSID, result);
155 }
156 }
Mitchell Wills5a42db22015-08-03 09:46:08 -0700157 update(mConfig, mInfo, mNetworkInfo);
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700158 mRssi = getRssi();
159 mSeen = getSeen();
Jason Monkd52356a2015-01-28 10:40:41 -0500160 }
161
162 AccessPoint(Context context, ScanResult result) {
163 mContext = context;
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700164 initWithScanResult(result);
Jason Monkd52356a2015-01-28 10:40:41 -0500165 }
166
167 AccessPoint(Context context, WifiConfiguration config) {
168 mContext = context;
169 loadConfig(config);
170 }
171
172 @Override
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800173 public int compareTo(@NonNull AccessPoint other) {
Jason Monkd52356a2015-01-28 10:40:41 -0500174 // Active one goes first.
175 if (isActive() && !other.isActive()) return -1;
176 if (!isActive() && other.isActive()) return 1;
177
178 // Reachable one goes before unreachable one.
179 if (mRssi != Integer.MAX_VALUE && other.mRssi == Integer.MAX_VALUE) return -1;
180 if (mRssi == Integer.MAX_VALUE && other.mRssi != Integer.MAX_VALUE) return 1;
181
182 // Configured one goes before unconfigured one.
183 if (networkId != WifiConfiguration.INVALID_NETWORK_ID
184 && other.networkId == WifiConfiguration.INVALID_NETWORK_ID) return -1;
185 if (networkId == WifiConfiguration.INVALID_NETWORK_ID
186 && other.networkId != WifiConfiguration.INVALID_NETWORK_ID) return 1;
187
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800188 // Sort by signal strength, bucketed by level
189 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS)
190 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500191 if (difference != 0) {
192 return difference;
193 }
194 // Sort by ssid.
195 return ssid.compareToIgnoreCase(other.ssid);
196 }
197
198 @Override
199 public boolean equals(Object other) {
200 if (!(other instanceof AccessPoint)) return false;
201 return (this.compareTo((AccessPoint) other) == 0);
202 }
203
204 @Override
205 public int hashCode() {
206 int result = 0;
207 if (mInfo != null) result += 13 * mInfo.hashCode();
208 result += 19 * mRssi;
209 result += 23 * networkId;
210 result += 29 * ssid.hashCode();
211 return result;
212 }
213
214 @Override
215 public String toString() {
216 StringBuilder builder = new StringBuilder().append("AccessPoint(")
217 .append(ssid);
218 if (isSaved()) {
219 builder.append(',').append("saved");
220 }
221 if (isActive()) {
222 builder.append(',').append("active");
223 }
224 if (isEphemeral()) {
225 builder.append(',').append("ephemeral");
226 }
227 if (isConnectable()) {
228 builder.append(',').append("connectable");
229 }
230 if (security != SECURITY_NONE) {
231 builder.append(',').append(securityToString(security, pskType));
232 }
233 return builder.append(')').toString();
234 }
235
236 public boolean matches(ScanResult result) {
237 return ssid.equals(result.SSID) && security == getSecurity(result);
238 }
239
240 public boolean matches(WifiConfiguration config) {
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100241 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700242 return config.FQDN.equals(mConfig.providerFriendlyName);
Bartosz Fabianowski6fb07562016-01-12 15:43:19 +0100243 } else {
244 return ssid.equals(removeDoubleQuotes(config.SSID))
245 && security == getSecurity(config)
246 && (mConfig == null || mConfig.shared == config.shared);
247 }
Jason Monkd52356a2015-01-28 10:40:41 -0500248 }
249
250 public WifiConfiguration getConfig() {
251 return mConfig;
252 }
253
254 public void clearConfig() {
255 mConfig = null;
256 networkId = WifiConfiguration.INVALID_NETWORK_ID;
257 }
258
259 public WifiInfo getInfo() {
260 return mInfo;
261 }
262
263 public int getLevel() {
264 if (mRssi == Integer.MAX_VALUE) {
265 return -1;
266 }
Tony Mantlera0e03dd2016-01-27 15:57:03 -0800267 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS);
Jason Monkd52356a2015-01-28 10:40:41 -0500268 }
269
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700270 public int getRssi() {
271 int rssi = Integer.MIN_VALUE;
272 for (ScanResult result : mScanResultCache.snapshot().values()) {
273 if (result.level > rssi) {
274 rssi = result.level;
275 }
276 }
277
278 return rssi;
279 }
280
281 public long getSeen() {
282 long seen = 0;
283 for (ScanResult result : mScanResultCache.snapshot().values()) {
284 if (result.timestamp > seen) {
285 seen = result.timestamp;
286 }
287 }
288
289 return seen;
290 }
291
Jason Monkd52356a2015-01-28 10:40:41 -0500292 public NetworkInfo getNetworkInfo() {
293 return mNetworkInfo;
294 }
295
296 public int getSecurity() {
297 return security;
298 }
299
300 public String getSecurityString(boolean concise) {
301 Context context = mContext;
Sanket Padawed1878802015-05-12 10:27:19 -0700302 if (mConfig != null && mConfig.isPasspoint()) {
Sanket Padawe194cce62015-07-10 10:53:31 -0700303 return concise ? context.getString(R.string.wifi_security_short_eap) :
304 context.getString(R.string.wifi_security_eap);
Sanket Padawed1878802015-05-12 10:27:19 -0700305 }
Jason Monkd52356a2015-01-28 10:40:41 -0500306 switch(security) {
307 case SECURITY_EAP:
308 return concise ? context.getString(R.string.wifi_security_short_eap) :
309 context.getString(R.string.wifi_security_eap);
310 case SECURITY_PSK:
311 switch (pskType) {
312 case PSK_WPA:
313 return concise ? context.getString(R.string.wifi_security_short_wpa) :
314 context.getString(R.string.wifi_security_wpa);
315 case PSK_WPA2:
316 return concise ? context.getString(R.string.wifi_security_short_wpa2) :
317 context.getString(R.string.wifi_security_wpa2);
318 case PSK_WPA_WPA2:
319 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
320 context.getString(R.string.wifi_security_wpa_wpa2);
321 case PSK_UNKNOWN:
322 default:
323 return concise ? context.getString(R.string.wifi_security_short_psk_generic)
324 : context.getString(R.string.wifi_security_psk_generic);
325 }
326 case SECURITY_WEP:
327 return concise ? context.getString(R.string.wifi_security_short_wep) :
328 context.getString(R.string.wifi_security_wep);
329 case SECURITY_NONE:
330 default:
331 return concise ? "" : context.getString(R.string.wifi_security_none);
332 }
333 }
334
Jason Monk6980d122015-06-15 10:07:55 -0400335 public String getSsidStr() {
Jason Monkd52356a2015-01-28 10:40:41 -0500336 return ssid;
337 }
338
Jason Monk60a82ff2016-02-25 13:55:03 -0500339 public String getBssid() {
340 return bssid;
341 }
342
Jason Monk6980d122015-06-15 10:07:55 -0400343 public CharSequence getSsid() {
344 SpannableString str = new SpannableString(ssid);
345 str.setSpan(new TtsSpan.VerbatimBuilder(ssid).build(), 0, ssid.length(),
346 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
347 return str;
348 }
349
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700350 public String getConfigName() {
351 if (mConfig != null && mConfig.isPasspoint()) {
352 return mConfig.providerFriendlyName;
353 } else {
354 return ssid;
355 }
356 }
357
Jason Monkd52356a2015-01-28 10:40:41 -0500358 public DetailedState getDetailedState() {
Fan Zhang6acb7662016-10-17 12:40:03 -0700359 if (mNetworkInfo != null) {
360 return mNetworkInfo.getDetailedState();
361 }
362 Log.w(TAG, "NetworkInfo is null, cannot return detailed state");
363 return null;
Jason Monkd52356a2015-01-28 10:40:41 -0500364 }
365
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700366 public String getSavedNetworkSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700367 WifiConfiguration config = mConfig;
368 if (config != null) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700369 PackageManager pm = mContext.getPackageManager();
370 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID);
Fan Zhang51365c32016-09-20 12:22:18 -0700371 int userId = UserHandle.getUserId(config.creatorUid);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700372 ApplicationInfo appInfo = null;
Fan Zhang51365c32016-09-20 12:22:18 -0700373 if (config.creatorName != null && config.creatorName.equals(systemName)) {
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700374 appInfo = mContext.getApplicationInfo();
375 } else {
376 try {
377 IPackageManager ipm = AppGlobals.getPackageManager();
Fan Zhang51365c32016-09-20 12:22:18 -0700378 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId);
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700379 } catch (RemoteException rex) {
380 }
381 }
382 if (appInfo != null &&
383 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) &&
384 !appInfo.packageName.equals(
385 mContext.getString(R.string.certinstaller_package))) {
386 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm));
387 }
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700388 }
Sanket Padawe56cfbfb2015-05-05 20:10:46 -0700389 return "";
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700390 }
391
Jason Monkd52356a2015-01-28 10:40:41 -0500392 public String getSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700393 return getSettingsSummary(mConfig);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700394 }
395
396 public String getSettingsSummary() {
Fan Zhang51365c32016-09-20 12:22:18 -0700397 return getSettingsSummary(mConfig);
398 }
399
400 private String getSettingsSummary(WifiConfiguration config) {
Jason Monkd52356a2015-01-28 10:40:41 -0500401 // Update to new summary
402 StringBuilder summary = new StringBuilder();
403
Fan Zhang51365c32016-09-20 12:22:18 -0700404 if (isActive() && config != null && config.isPasspoint()) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700405 // This is the active connection on passpoint
Jason Monkd52356a2015-01-28 10:40:41 -0500406 summary.append(getSummary(mContext, getDetailedState(),
Fan Zhang51365c32016-09-20 12:22:18 -0700407 false, config.providerFriendlyName));
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700408 } else if (isActive()) {
409 // This is the active connection on non-passpoint network
410 summary.append(getSummary(mContext, getDetailedState(),
Shirish Kalelec7a38ef2015-06-25 13:55:33 -0700411 mInfo != null && mInfo.isEphemeral()));
Fan Zhang51365c32016-09-20 12:22:18 -0700412 } else if (config != null && config.isPasspoint()) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700413 String format = mContext.getString(R.string.available_via_passpoint);
Fan Zhang51365c32016-09-20 12:22:18 -0700414 summary.append(String.format(format, config.providerFriendlyName));
415 } else if (config != null && config.hasNoInternetAccess()) {
Salvador Martinez5d937fc2016-09-23 08:54:20 -0700416 int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled()
417 ? R.string.wifi_no_internet_no_reconnect
418 : R.string.wifi_no_internet;
419 summary.append(mContext.getString(messageID));
Fan Zhang51365c32016-09-20 12:22:18 -0700420 } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
xinhef7705c32015-12-01 14:44:37 -0800421 WifiConfiguration.NetworkSelectionStatus networkStatus =
Fan Zhang51365c32016-09-20 12:22:18 -0700422 config.getNetworkSelectionStatus();
xinhef7705c32015-12-01 14:44:37 -0800423 switch (networkStatus.getNetworkSelectionDisableReason()) {
424 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE:
Jason Monkd52356a2015-01-28 10:40:41 -0500425 summary.append(mContext.getString(R.string.wifi_disabled_password_failure));
xinhef7705c32015-12-01 14:44:37 -0800426 break;
427 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE:
428 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE:
429 summary.append(mContext.getString(R.string.wifi_disabled_network_failure));
430 break;
431 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION:
432 summary.append(mContext.getString(R.string.wifi_disabled_generic));
433 break;
Jason Monkd52356a2015-01-28 10:40:41 -0500434 }
435 } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range
436 summary.append(mContext.getString(R.string.wifi_not_in_range));
437 } else { // In range, not disabled.
Fan Zhang51365c32016-09-20 12:22:18 -0700438 if (config != null) { // Is saved network
Jason Monkd52356a2015-01-28 10:40:41 -0500439 summary.append(mContext.getString(R.string.wifi_remembered));
440 }
441 }
442
443 if (WifiTracker.sVerboseLogging > 0) {
444 // Add RSSI/band information for this config, what was seen up to 6 seconds ago
445 // verbose WiFi Logging is only turned on thru developers settings
446 if (mInfo != null && mNetworkInfo != null) { // This is the active connection
447 summary.append(" f=" + Integer.toString(mInfo.getFrequency()));
448 }
449 summary.append(" " + getVisibilityStatus());
Fan Zhang51365c32016-09-20 12:22:18 -0700450 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
451 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString());
452 if (config.getNetworkSelectionStatus().getDisableTime() > 0) {
Jason Monkd52356a2015-01-28 10:40:41 -0500453 long now = System.currentTimeMillis();
Fan Zhang51365c32016-09-20 12:22:18 -0700454 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000;
Jason Monkd52356a2015-01-28 10:40:41 -0500455 long sec = diff%60; //seconds
456 long min = (diff/60)%60; //minutes
457 long hour = (min/60)%60; //hours
458 summary.append(", ");
459 if (hour > 0) summary.append(Long.toString(hour) + "h ");
460 summary.append( Long.toString(min) + "m ");
461 summary.append( Long.toString(sec) + "s ");
462 }
463 summary.append(")");
464 }
xinhef7705c32015-12-01 14:44:37 -0800465
Fan Zhang51365c32016-09-20 12:22:18 -0700466 if (config != null) {
xinhef7705c32015-12-01 14:44:37 -0800467 WifiConfiguration.NetworkSelectionStatus networkStatus =
Fan Zhang51365c32016-09-20 12:22:18 -0700468 config.getNetworkSelectionStatus();
xinhef7705c32015-12-01 14:44:37 -0800469 for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE;
470 index < WifiConfiguration.NetworkSelectionStatus
471 .NETWORK_SELECTION_DISABLED_MAX; index++) {
472 if (networkStatus.getDisableReasonCounter(index) != 0) {
473 summary.append(" " + WifiConfiguration.NetworkSelectionStatus
474 .getNetworkDisableReasonString(index) + "="
475 + networkStatus.getDisableReasonCounter(index));
476 }
477 }
Jason Monkd52356a2015-01-28 10:40:41 -0500478 }
479 }
480 return summary.toString();
481 }
482
483 /**
484 * Returns the visibility status of the WifiConfiguration.
485 *
486 * @return autojoin debugging information
487 * TODO: use a string formatter
488 * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"]
489 * For instance [-40,5/-30,2]
490 */
491 private String getVisibilityStatus() {
492 StringBuilder visibility = new StringBuilder();
493 StringBuilder scans24GHz = null;
494 StringBuilder scans5GHz = null;
495 String bssid = null;
496
497 long now = System.currentTimeMillis();
498
499 if (mInfo != null) {
500 bssid = mInfo.getBSSID();
501 if (bssid != null) {
502 visibility.append(" ").append(bssid);
503 }
504 visibility.append(" rssi=").append(mInfo.getRssi());
505 visibility.append(" ");
506 visibility.append(" score=").append(mInfo.score);
507 visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate));
508 visibility.append(String.format("%.1f,", mInfo.txRetriesRate));
509 visibility.append(String.format("%.1f ", mInfo.txBadRate));
510 visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate));
511 }
512
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700513 int rssi5 = WifiConfiguration.INVALID_RSSI;
514 int rssi24 = WifiConfiguration.INVALID_RSSI;
515 int num5 = 0;
516 int num24 = 0;
517 int numBlackListed = 0;
518 int n24 = 0; // Number scan results we included in the string
519 int n5 = 0; // Number scan results we included in the string
520 Map<String, ScanResult> list = mScanResultCache.snapshot();
521 // TODO: sort list by RSSI or age
522 for (ScanResult result : list.values()) {
Jason Monkd52356a2015-01-28 10:40:41 -0500523
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700524 if (result.frequency >= LOWER_FREQ_5GHZ
525 && result.frequency <= HIGHER_FREQ_5GHZ) {
526 // Strictly speaking: [4915, 5825]
527 // number of known BSSID on 5GHz band
528 num5 = num5 + 1;
529 } else if (result.frequency >= LOWER_FREQ_24GHZ
530 && result.frequency <= HIGHER_FREQ_24GHZ) {
531 // Strictly speaking: [2412, 2482]
532 // number of known BSSID on 2.4Ghz band
533 num24 = num24 + 1;
Jason Monkd52356a2015-01-28 10:40:41 -0500534 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700535
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700536
537 if (result.frequency >= LOWER_FREQ_5GHZ
538 && result.frequency <= HIGHER_FREQ_5GHZ) {
539 if (result.level > rssi5) {
540 rssi5 = result.level;
Jason Monkd52356a2015-01-28 10:40:41 -0500541 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700542 if (n5 < 4) {
543 if (scans5GHz == null) scans5GHz = new StringBuilder();
544 scans5GHz.append(" \n{").append(result.BSSID);
545 if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*");
546 scans5GHz.append("=").append(result.frequency);
547 scans5GHz.append(",").append(result.level);
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700548 scans5GHz.append("}");
549 n5++;
Jason Monkd52356a2015-01-28 10:40:41 -0500550 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700551 } else if (result.frequency >= LOWER_FREQ_24GHZ
552 && result.frequency <= HIGHER_FREQ_24GHZ) {
553 if (result.level > rssi24) {
554 rssi24 = result.level;
555 }
556 if (n24 < 4) {
557 if (scans24GHz == null) scans24GHz = new StringBuilder();
558 scans24GHz.append(" \n{").append(result.BSSID);
559 if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*");
560 scans24GHz.append("=").append(result.frequency);
561 scans24GHz.append(",").append(result.level);
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700562 scans24GHz.append("}");
563 n24++;
Jason Monkd52356a2015-01-28 10:40:41 -0500564 }
565 }
566 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700567 visibility.append(" [");
568 if (num24 > 0) {
569 visibility.append("(").append(num24).append(")");
570 if (n24 <= 4) {
571 if (scans24GHz != null) {
572 visibility.append(scans24GHz.toString());
573 }
574 } else {
575 visibility.append("max=").append(rssi24);
576 if (scans24GHz != null) {
577 visibility.append(",").append(scans24GHz.toString());
578 }
579 }
580 }
581 visibility.append(";");
582 if (num5 > 0) {
583 visibility.append("(").append(num5).append(")");
584 if (n5 <= 4) {
585 if (scans5GHz != null) {
586 visibility.append(scans5GHz.toString());
587 }
588 } else {
589 visibility.append("max=").append(rssi5);
590 if (scans5GHz != null) {
591 visibility.append(",").append(scans5GHz.toString());
592 }
593 }
594 }
595 if (numBlackListed > 0)
596 visibility.append("!").append(numBlackListed);
597 visibility.append("]");
Jason Monkd52356a2015-01-28 10:40:41 -0500598
599 return visibility.toString();
600 }
601
602 /**
603 * Return whether this is the active connection.
604 * For ephemeral connections (networkId is invalid), this returns false if the network is
605 * disconnected.
606 */
607 public boolean isActive() {
608 return mNetworkInfo != null &&
609 (networkId != WifiConfiguration.INVALID_NETWORK_ID ||
610 mNetworkInfo.getState() != State.DISCONNECTED);
611 }
612
613 public boolean isConnectable() {
614 return getLevel() != -1 && getDetailedState() == null;
615 }
616
617 public boolean isEphemeral() {
Shirish Kalelec7a38ef2015-06-25 13:55:33 -0700618 return mInfo != null && mInfo.isEphemeral() &&
619 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED;
Jason Monkd52356a2015-01-28 10:40:41 -0500620 }
621
Vinit Deshpande5b7352c2015-07-09 16:53:12 -0700622 public boolean isPasspoint() {
623 return mConfig != null && mConfig.isPasspoint();
624 }
625
Mitchell Wills5a42db22015-08-03 09:46:08 -0700626 /**
627 * Return whether the given {@link WifiInfo} is for this access point.
628 * If the current AP does not have a network Id then the config is used to
629 * match based on SSID and security.
630 */
631 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) {
Vinit Deshpande5b7352c2015-07-09 16:53:12 -0700632 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) {
Jason Monkd52356a2015-01-28 10:40:41 -0500633 return networkId == info.getNetworkId();
Mitchell Wills5a42db22015-08-03 09:46:08 -0700634 } else if (config != null) {
635 return matches(config);
636 }
637 else {
Jason Monkd52356a2015-01-28 10:40:41 -0500638 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID.
639 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID).
640 // TODO: Handle hex string SSIDs.
641 return ssid.equals(removeDoubleQuotes(info.getSSID()));
642 }
643 }
644
645 public boolean isSaved() {
646 return networkId != WifiConfiguration.INVALID_NETWORK_ID;
647 }
648
649 public Object getTag() {
650 return mTag;
651 }
652
653 public void setTag(Object tag) {
654 mTag = tag;
655 }
656
657 /**
658 * Generate and save a default wifiConfiguration with common values.
659 * Can only be called for unsecured networks.
660 */
661 public void generateOpenNetworkConfig() {
662 if (security != SECURITY_NONE)
663 throw new IllegalStateException();
664 if (mConfig != null)
665 return;
666 mConfig = new WifiConfiguration();
667 mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
668 mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
669 }
670
671 void loadConfig(WifiConfiguration config) {
Vinit Deshpandefc406002015-04-15 18:10:55 -0700672 if (config.isPasspoint())
673 ssid = config.providerFriendlyName;
674 else
675 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700676
Jason Monk60a82ff2016-02-25 13:55:03 -0500677 bssid = config.BSSID;
Jason Monkd52356a2015-01-28 10:40:41 -0500678 security = getSecurity(config);
679 networkId = config.networkId;
680 mConfig = config;
681 }
682
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700683 private void initWithScanResult(ScanResult result) {
Jason Monkd52356a2015-01-28 10:40:41 -0500684 ssid = result.SSID;
Jason Monk60a82ff2016-02-25 13:55:03 -0500685 bssid = result.BSSID;
Jason Monkd52356a2015-01-28 10:40:41 -0500686 security = getSecurity(result);
687 if (security == SECURITY_PSK)
688 pskType = getPskType(result);
689 mRssi = result.level;
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700690 mSeen = result.timestamp;
Jason Monkd52356a2015-01-28 10:40:41 -0500691 }
692
693 public void saveWifiState(Bundle savedState) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700694 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr());
695 savedState.putInt(KEY_SECURITY, security);
696 savedState.putInt(KEY_PSKTYPE, pskType);
697 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig);
Jason Monkd52356a2015-01-28 10:40:41 -0500698 savedState.putParcelable(KEY_WIFIINFO, mInfo);
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700699 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE,
700 new ArrayList<ScanResult>(mScanResultCache.snapshot().values()));
Jason Monkd52356a2015-01-28 10:40:41 -0500701 if (mNetworkInfo != null) {
702 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo);
703 }
704 }
705
706 public void setListener(AccessPointListener listener) {
707 mAccessPointListener = listener;
708 }
709
710 boolean update(ScanResult result) {
Mitchell Wills5a42db22015-08-03 09:46:08 -0700711 if (matches(result)) {
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700712 /* Update the LRU timestamp, if BSSID exists */
713 mScanResultCache.get(result.BSSID);
714
715 /* Add or update the scan result for the BSSID */
716 mScanResultCache.put(result.BSSID, result);
717
718 int oldLevel = getLevel();
719 int oldRssi = getRssi();
720 mSeen = getSeen();
721 mRssi = (getRssi() + oldRssi)/2;
722 int newLevel = getLevel();
723
724 if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) {
725 mAccessPointListener.onLevelChanged(this);
Jason Monkd52356a2015-01-28 10:40:41 -0500726 }
727 // This flag only comes from scans, is not easily saved in config
728 if (security == SECURITY_PSK) {
729 pskType = getPskType(result);
730 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700731
Jason Monkd52356a2015-01-28 10:40:41 -0500732 if (mAccessPointListener != null) {
733 mAccessPointListener.onAccessPointChanged(this);
734 }
Vinit Deshpandefcd46122015-06-11 18:22:23 -0700735
Jason Monkd52356a2015-01-28 10:40:41 -0500736 return true;
737 }
738 return false;
739 }
740
Mitchell Wills5a42db22015-08-03 09:46:08 -0700741 boolean update(WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) {
Jason Monkd52356a2015-01-28 10:40:41 -0500742 boolean reorder = false;
Mitchell Wills5a42db22015-08-03 09:46:08 -0700743 if (info != null && isInfoForThisAccessPoint(config, info)) {
Jason Monkd52356a2015-01-28 10:40:41 -0500744 reorder = (mInfo == null);
745 mRssi = info.getRssi();
746 mInfo = info;
747 mNetworkInfo = networkInfo;
748 if (mAccessPointListener != null) {
749 mAccessPointListener.onAccessPointChanged(this);
750 }
751 } else if (mInfo != null) {
752 reorder = true;
753 mInfo = null;
754 mNetworkInfo = null;
755 if (mAccessPointListener != null) {
756 mAccessPointListener.onAccessPointChanged(this);
757 }
758 }
759 return reorder;
760 }
761
Vinit Deshpandefc406002015-04-15 18:10:55 -0700762 void update(WifiConfiguration config) {
763 mConfig = config;
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700764 networkId = config.networkId;
765 if (mAccessPointListener != null) {
766 mAccessPointListener.onAccessPointChanged(this);
767 }
Vinit Deshpandefc406002015-04-15 18:10:55 -0700768 }
Shirish Kalelec7a38ef2015-06-25 13:55:33 -0700769
Sanket Padawe0775a982015-08-19 14:57:46 -0700770 void setRssi(int rssi) {
771 mRssi = rssi;
772 }
773
Jason Monkd52356a2015-01-28 10:40:41 -0500774 public static String getSummary(Context context, String ssid, DetailedState state,
Vinit Deshpandefc406002015-04-15 18:10:55 -0700775 boolean isEphemeral, String passpointProvider) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700776 if (state == DetailedState.CONNECTED && ssid == null) {
Vinit Deshpandefc406002015-04-15 18:10:55 -0700777 if (TextUtils.isEmpty(passpointProvider) == false) {
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700778 // Special case for connected + passpoint networks.
Vinit Deshpandefc406002015-04-15 18:10:55 -0700779 String format = context.getString(R.string.connected_via_passpoint);
780 return String.format(format, passpointProvider);
Vinit Deshpandedcf00c92015-04-15 18:32:09 -0700781 } else if (isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -0700782 // Special case for connected + ephemeral networks.
783 return context.getString(R.string.connected_via_wfa);
784 }
Jason Monkd52356a2015-01-28 10:40:41 -0500785 }
786
Sanket Padawe7094d222015-05-01 16:55:00 -0700787 // Case when there is wifi connected without internet connectivity.
788 final ConnectivityManager cm = (ConnectivityManager)
789 context.getSystemService(Context.CONNECTIVITY_SERVICE);
790 if (state == DetailedState.CONNECTED) {
791 IWifiManager wifiManager = IWifiManager.Stub.asInterface(
792 ServiceManager.getService(Context.WIFI_SERVICE));
Lorenzo Colitti1317e042016-12-13 13:30:07 +0900793 NetworkCapabilities nc = null;
Sanket Padawe7094d222015-05-01 16:55:00 -0700794
795 try {
Lorenzo Colitti1317e042016-12-13 13:30:07 +0900796 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork());
797 } catch (RemoteException e) {}
798
799 if (nc != null) {
800 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) {
801 return context.getString(
802 com.android.internal.R.string.network_available_sign_in);
803 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
804 return context.getString(R.string.wifi_connected_no_internet);
805 }
Sanket Padawe7094d222015-05-01 16:55:00 -0700806 }
807 }
Fan Zhang6acb7662016-10-17 12:40:03 -0700808 if (state == null) {
809 Log.w(TAG, "state is null, returning empty summary");
810 return "";
811 }
Jason Monkd52356a2015-01-28 10:40:41 -0500812 String[] formats = context.getResources().getStringArray((ssid == null)
813 ? R.array.wifi_status : R.array.wifi_status_with_ssid);
814 int index = state.ordinal();
815
816 if (index >= formats.length || formats[index].length() == 0) {
Sanket Padawe3e9e5fa2015-05-28 10:41:14 -0700817 return "";
Jason Monkd52356a2015-01-28 10:40:41 -0500818 }
819 return String.format(formats[index], ssid);
820 }
821
822 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) {
Vinit Deshpandefc406002015-04-15 18:10:55 -0700823 return getSummary(context, null, state, isEphemeral, null);
824 }
825
826 public static String getSummary(Context context, DetailedState state, boolean isEphemeral,
827 String passpointProvider) {
828 return getSummary(context, null, state, isEphemeral, passpointProvider);
Jason Monkd52356a2015-01-28 10:40:41 -0500829 }
830
831 public static String convertToQuotedString(String string) {
832 return "\"" + string + "\"";
833 }
834
835 private static int getPskType(ScanResult result) {
836 boolean wpa = result.capabilities.contains("WPA-PSK");
837 boolean wpa2 = result.capabilities.contains("WPA2-PSK");
838 if (wpa2 && wpa) {
839 return PSK_WPA_WPA2;
840 } else if (wpa2) {
841 return PSK_WPA2;
842 } else if (wpa) {
843 return PSK_WPA;
844 } else {
845 Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
846 return PSK_UNKNOWN;
847 }
848 }
849
850 private static int getSecurity(ScanResult result) {
851 if (result.capabilities.contains("WEP")) {
852 return SECURITY_WEP;
853 } else if (result.capabilities.contains("PSK")) {
854 return SECURITY_PSK;
855 } else if (result.capabilities.contains("EAP")) {
856 return SECURITY_EAP;
857 }
858 return SECURITY_NONE;
859 }
860
861 static int getSecurity(WifiConfiguration config) {
862 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
863 return SECURITY_PSK;
864 }
865 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
866 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
867 return SECURITY_EAP;
868 }
869 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
870 }
871
872 public static String securityToString(int security, int pskType) {
873 if (security == SECURITY_WEP) {
874 return "WEP";
875 } else if (security == SECURITY_PSK) {
876 if (pskType == PSK_WPA) {
877 return "WPA";
878 } else if (pskType == PSK_WPA2) {
879 return "WPA2";
880 } else if (pskType == PSK_WPA_WPA2) {
881 return "WPA_WPA2";
882 }
883 return "PSK";
884 } else if (security == SECURITY_EAP) {
885 return "EAP";
886 }
887 return "NONE";
888 }
889
890 static String removeDoubleQuotes(String string) {
Jason Monk2b51cc32015-05-13 11:07:53 -0400891 if (TextUtils.isEmpty(string)) {
892 return "";
893 }
Jason Monkd52356a2015-01-28 10:40:41 -0500894 int length = string.length();
895 if ((length > 1) && (string.charAt(0) == '"')
896 && (string.charAt(length - 1) == '"')) {
897 return string.substring(1, length - 1);
898 }
899 return string;
900 }
901
902 public interface AccessPointListener {
903 void onAccessPointChanged(AccessPoint accessPoint);
904 void onLevelChanged(AccessPoint accessPoint);
905 }
906}