1/* 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 19import android.app.AppGlobals; 20import android.content.Context; 21import android.content.pm.ApplicationInfo; 22import android.content.pm.IPackageManager; 23import android.content.pm.PackageManager; 24import android.net.ConnectivityManager; 25import android.net.Network; 26import android.net.NetworkCapabilities; 27import android.net.NetworkInfo; 28import android.net.NetworkInfo.DetailedState; 29import android.net.NetworkInfo.State; 30import android.net.wifi.IWifiManager; 31import 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; 37import android.os.RemoteException; 38import android.os.ServiceManager; 39import android.os.UserHandle; 40import android.support.annotation.NonNull; 41import android.text.Spannable; 42import android.text.SpannableString; 43import android.text.TextUtils; 44import android.text.style.TtsSpan; 45import android.util.Log; 46import android.util.LruCache; 47 48import com.android.settingslib.R; 49 50import java.util.ArrayList; 51import 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 */ 84 public LruCache<String, ScanResult> mScanResultCache = new LruCache<String, ScanResult>(32); 85 86 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"; 89 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"; 93 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 108 public static final int SIGNAL_LEVELS = 4; 109 110 private final Context mContext; 111 112 private String ssid; 113 private String bssid; 114 private int security; 115 private int networkId = WifiConfiguration.INVALID_NETWORK_ID; 116 117 private int pskType = PSK_UNKNOWN; 118 119 private WifiConfiguration mConfig; 120 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 } 136 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); 144 } 145 mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO); 146 if (savedState.containsKey(KEY_NETWORKINFO)) { 147 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO); 148 } 149 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 } 157 update(mConfig, mInfo, mNetworkInfo); 158 mRssi = getRssi(); 159 mSeen = getSeen(); 160 } 161 162 AccessPoint(Context context, ScanResult result) { 163 mContext = context; 164 initWithScanResult(result); 165 } 166 167 AccessPoint(Context context, WifiConfiguration config) { 168 mContext = context; 169 loadConfig(config); 170 } 171 172 @Override 173 public int compareTo(@NonNull AccessPoint other) { 174 // 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 188 // Sort by signal strength, bucketed by level 189 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS) 190 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 191 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) { 241 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) { 242 return config.FQDN.equals(mConfig.providerFriendlyName); 243 } else { 244 return ssid.equals(removeDoubleQuotes(config.SSID)) 245 && security == getSecurity(config) 246 && (mConfig == null || mConfig.shared == config.shared); 247 } 248 } 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 } 267 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 268 } 269 270 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 292 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; 302 if (mConfig != null && mConfig.isPasspoint()) { 303 return concise ? context.getString(R.string.wifi_security_short_eap) : 304 context.getString(R.string.wifi_security_eap); 305 } 306 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 335 public String getSsidStr() { 336 return ssid; 337 } 338 339 public String getBssid() { 340 return bssid; 341 } 342 343 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 350 public String getConfigName() { 351 if (mConfig != null && mConfig.isPasspoint()) { 352 return mConfig.providerFriendlyName; 353 } else { 354 return ssid; 355 } 356 } 357 358 public DetailedState getDetailedState() { 359 if (mNetworkInfo != null) { 360 return mNetworkInfo.getDetailedState(); 361 } 362 Log.w(TAG, "NetworkInfo is null, cannot return detailed state"); 363 return null; 364 } 365 366 public String getSavedNetworkSummary() { 367 WifiConfiguration config = mConfig; 368 if (config != null) { 369 PackageManager pm = mContext.getPackageManager(); 370 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID); 371 int userId = UserHandle.getUserId(config.creatorUid); 372 ApplicationInfo appInfo = null; 373 if (config.creatorName != null && config.creatorName.equals(systemName)) { 374 appInfo = mContext.getApplicationInfo(); 375 } else { 376 try { 377 IPackageManager ipm = AppGlobals.getPackageManager(); 378 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId); 379 } 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 } 388 } 389 return ""; 390 } 391 392 public String getSummary() { 393 return getSettingsSummary(mConfig); 394 } 395 396 public String getSettingsSummary() { 397 return getSettingsSummary(mConfig); 398 } 399 400 private String getSettingsSummary(WifiConfiguration config) { 401 // Update to new summary 402 StringBuilder summary = new StringBuilder(); 403 404 if (isActive() && config != null && config.isPasspoint()) { 405 // This is the active connection on passpoint 406 summary.append(getSummary(mContext, getDetailedState(), 407 false, config.providerFriendlyName)); 408 } else if (isActive()) { 409 // This is the active connection on non-passpoint network 410 summary.append(getSummary(mContext, getDetailedState(), 411 mInfo != null && mInfo.isEphemeral())); 412 } else if (config != null && config.isPasspoint()) { 413 String format = mContext.getString(R.string.available_via_passpoint); 414 summary.append(String.format(format, config.providerFriendlyName)); 415 } else if (config != null && config.hasNoInternetAccess()) { 416 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)); 420 } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 421 WifiConfiguration.NetworkSelectionStatus networkStatus = 422 config.getNetworkSelectionStatus(); 423 switch (networkStatus.getNetworkSelectionDisableReason()) { 424 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE: 425 summary.append(mContext.getString(R.string.wifi_disabled_password_failure)); 426 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; 434 } 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. 438 if (config != null) { // Is saved network 439 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()); 450 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 451 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString()); 452 if (config.getNetworkSelectionStatus().getDisableTime() > 0) { 453 long now = System.currentTimeMillis(); 454 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000; 455 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 } 465 466 if (config != null) { 467 WifiConfiguration.NetworkSelectionStatus networkStatus = 468 config.getNetworkSelectionStatus(); 469 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 } 478 } 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 513 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()) { 523 524 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; 534 } 535 536 537 if (result.frequency >= LOWER_FREQ_5GHZ 538 && result.frequency <= HIGHER_FREQ_5GHZ) { 539 if (result.level > rssi5) { 540 rssi5 = result.level; 541 } 542 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); 548 scans5GHz.append("}"); 549 n5++; 550 } 551 } 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); 562 scans24GHz.append("}"); 563 n24++; 564 } 565 } 566 } 567 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("]"); 598 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() { 618 return mInfo != null && mInfo.isEphemeral() && 619 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED; 620 } 621 622 public boolean isPasspoint() { 623 return mConfig != null && mConfig.isPasspoint(); 624 } 625 626 /** 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) { 632 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) { 633 return networkId == info.getNetworkId(); 634 } else if (config != null) { 635 return matches(config); 636 } 637 else { 638 // 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) { 672 if (config.isPasspoint()) 673 ssid = config.providerFriendlyName; 674 else 675 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID)); 676 677 bssid = config.BSSID; 678 security = getSecurity(config); 679 networkId = config.networkId; 680 mConfig = config; 681 } 682 683 private void initWithScanResult(ScanResult result) { 684 ssid = result.SSID; 685 bssid = result.BSSID; 686 security = getSecurity(result); 687 if (security == SECURITY_PSK) 688 pskType = getPskType(result); 689 mRssi = result.level; 690 mSeen = result.timestamp; 691 } 692 693 public void saveWifiState(Bundle savedState) { 694 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); 698 savedState.putParcelable(KEY_WIFIINFO, mInfo); 699 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE, 700 new ArrayList<ScanResult>(mScanResultCache.snapshot().values())); 701 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) { 711 if (matches(result)) { 712 /* 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); 726 } 727 // This flag only comes from scans, is not easily saved in config 728 if (security == SECURITY_PSK) { 729 pskType = getPskType(result); 730 } 731 732 if (mAccessPointListener != null) { 733 mAccessPointListener.onAccessPointChanged(this); 734 } 735 736 return true; 737 } 738 return false; 739 } 740 741 boolean update(WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) { 742 boolean reorder = false; 743 if (info != null && isInfoForThisAccessPoint(config, info)) { 744 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 762 void update(WifiConfiguration config) { 763 mConfig = config; 764 networkId = config.networkId; 765 if (mAccessPointListener != null) { 766 mAccessPointListener.onAccessPointChanged(this); 767 } 768 } 769 770 void setRssi(int rssi) { 771 mRssi = rssi; 772 } 773 774 public static String getSummary(Context context, String ssid, DetailedState state, 775 boolean isEphemeral, String passpointProvider) { 776 if (state == DetailedState.CONNECTED && ssid == null) { 777 if (TextUtils.isEmpty(passpointProvider) == false) { 778 // Special case for connected + passpoint networks. 779 String format = context.getString(R.string.connected_via_passpoint); 780 return String.format(format, passpointProvider); 781 } else if (isEphemeral) { 782 // Special case for connected + ephemeral networks. 783 return context.getString(R.string.connected_via_wfa); 784 } 785 } 786 787 // 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)); 793 Network nw; 794 795 try { 796 nw = wifiManager.getCurrentNetwork(); 797 } catch (RemoteException e) { 798 nw = null; 799 } 800 NetworkCapabilities nc = cm.getNetworkCapabilities(nw); 801 if (nc != null && !nc.hasCapability(nc.NET_CAPABILITY_VALIDATED)) { 802 return context.getString(R.string.wifi_connected_no_internet); 803 } 804 } 805 if (state == null) { 806 Log.w(TAG, "state is null, returning empty summary"); 807 return ""; 808 } 809 String[] formats = context.getResources().getStringArray((ssid == null) 810 ? R.array.wifi_status : R.array.wifi_status_with_ssid); 811 int index = state.ordinal(); 812 813 if (index >= formats.length || formats[index].length() == 0) { 814 return ""; 815 } 816 return String.format(formats[index], ssid); 817 } 818 819 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) { 820 return getSummary(context, null, state, isEphemeral, null); 821 } 822 823 public static String getSummary(Context context, DetailedState state, boolean isEphemeral, 824 String passpointProvider) { 825 return getSummary(context, null, state, isEphemeral, passpointProvider); 826 } 827 828 public static String convertToQuotedString(String string) { 829 return "\"" + string + "\""; 830 } 831 832 private static int getPskType(ScanResult result) { 833 boolean wpa = result.capabilities.contains("WPA-PSK"); 834 boolean wpa2 = result.capabilities.contains("WPA2-PSK"); 835 if (wpa2 && wpa) { 836 return PSK_WPA_WPA2; 837 } else if (wpa2) { 838 return PSK_WPA2; 839 } else if (wpa) { 840 return PSK_WPA; 841 } else { 842 Log.w(TAG, "Received abnormal flag string: " + result.capabilities); 843 return PSK_UNKNOWN; 844 } 845 } 846 847 private static int getSecurity(ScanResult result) { 848 if (result.capabilities.contains("WEP")) { 849 return SECURITY_WEP; 850 } else if (result.capabilities.contains("PSK")) { 851 return SECURITY_PSK; 852 } else if (result.capabilities.contains("EAP")) { 853 return SECURITY_EAP; 854 } 855 return SECURITY_NONE; 856 } 857 858 static int getSecurity(WifiConfiguration config) { 859 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 860 return SECURITY_PSK; 861 } 862 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || 863 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { 864 return SECURITY_EAP; 865 } 866 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE; 867 } 868 869 public static String securityToString(int security, int pskType) { 870 if (security == SECURITY_WEP) { 871 return "WEP"; 872 } else if (security == SECURITY_PSK) { 873 if (pskType == PSK_WPA) { 874 return "WPA"; 875 } else if (pskType == PSK_WPA2) { 876 return "WPA2"; 877 } else if (pskType == PSK_WPA_WPA2) { 878 return "WPA_WPA2"; 879 } 880 return "PSK"; 881 } else if (security == SECURITY_EAP) { 882 return "EAP"; 883 } 884 return "NONE"; 885 } 886 887 static String removeDoubleQuotes(String string) { 888 if (TextUtils.isEmpty(string)) { 889 return ""; 890 } 891 int length = string.length(); 892 if ((length > 1) && (string.charAt(0) == '"') 893 && (string.charAt(length - 1) == '"')) { 894 return string.substring(1, length - 1); 895 } 896 return string; 897 } 898 899 public interface AccessPointListener { 900 void onAccessPointChanged(AccessPoint accessPoint); 901 void onLevelChanged(AccessPoint accessPoint); 902 } 903} 904