AccessPoint.java revision 4896a04013a97a41564b0a68685cc559bc81fcca
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.SystemClock; 40import android.os.UserHandle; 41import android.support.annotation.NonNull; 42import android.text.Spannable; 43import android.text.SpannableString; 44import android.text.TextUtils; 45import android.text.style.TtsSpan; 46import android.util.Log; 47 48import com.android.settingslib.R; 49 50import java.util.ArrayList; 51import java.util.Iterator; 52import java.util.Map; 53import java.util.concurrent.ConcurrentHashMap; 54 55 56public class AccessPoint implements Comparable<AccessPoint> { 57 static final String TAG = "SettingsLib.AccessPoint"; 58 59 /** 60 * Lower bound on the 2.4 GHz (802.11b/g/n) WLAN channels 61 */ 62 public static final int LOWER_FREQ_24GHZ = 2400; 63 64 /** 65 * Upper bound on the 2.4 GHz (802.11b/g/n) WLAN channels 66 */ 67 public static final int HIGHER_FREQ_24GHZ = 2500; 68 69 /** 70 * Lower bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels 71 */ 72 public static final int LOWER_FREQ_5GHZ = 4900; 73 74 /** 75 * Upper bound on the 5.0 GHz (802.11a/h/j/n/ac) WLAN channels 76 */ 77 public static final int HIGHER_FREQ_5GHZ = 5900; 78 79 80 /** 81 * Experimental: we should be able to show the user the list of BSSIDs and bands 82 * for that SSID. 83 * For now this data is used only with Verbose Logging so as to show the band and number 84 * of BSSIDs on which that network is seen. 85 */ 86 private final ConcurrentHashMap<String, ScanResult> mScanResultCache = 87 new ConcurrentHashMap<String, ScanResult>(32); 88 private static final long MAX_SCAN_RESULT_AGE_MS = 15000; 89 90 private static final String KEY_NETWORKINFO = "key_networkinfo"; 91 private static final String KEY_WIFIINFO = "key_wifiinfo"; 92 private static final String KEY_SCANRESULT = "key_scanresult"; 93 private static final String KEY_SSID = "key_ssid"; 94 private static final String KEY_SECURITY = "key_security"; 95 private static final String KEY_PSKTYPE = "key_psktype"; 96 private static final String KEY_SCANRESULTCACHE = "key_scanresultcache"; 97 private static final String KEY_CONFIG = "key_config"; 98 99 /** 100 * These values are matched in string arrays -- changes must be kept in sync 101 */ 102 public static final int SECURITY_NONE = 0; 103 public static final int SECURITY_WEP = 1; 104 public static final int SECURITY_PSK = 2; 105 public static final int SECURITY_EAP = 3; 106 107 private static final int PSK_UNKNOWN = 0; 108 private static final int PSK_WPA = 1; 109 private static final int PSK_WPA2 = 2; 110 private static final int PSK_WPA_WPA2 = 3; 111 112 public static final int SIGNAL_LEVELS = 4; 113 114 private final Context mContext; 115 116 private String ssid; 117 private String bssid; 118 private int security; 119 private int networkId = WifiConfiguration.INVALID_NETWORK_ID; 120 121 private int pskType = PSK_UNKNOWN; 122 123 private WifiConfiguration mConfig; 124 125 private int mRssi = Integer.MAX_VALUE; 126 private long mSeen = 0; 127 128 private WifiInfo mInfo; 129 private NetworkInfo mNetworkInfo; 130 private AccessPointListener mAccessPointListener; 131 132 private Object mTag; 133 134 public AccessPoint(Context context, Bundle savedState) { 135 mContext = context; 136 mConfig = savedState.getParcelable(KEY_CONFIG); 137 if (mConfig != null) { 138 loadConfig(mConfig); 139 } 140 if (savedState.containsKey(KEY_SSID)) { 141 ssid = savedState.getString(KEY_SSID); 142 } 143 if (savedState.containsKey(KEY_SECURITY)) { 144 security = savedState.getInt(KEY_SECURITY); 145 } 146 if (savedState.containsKey(KEY_PSKTYPE)) { 147 pskType = savedState.getInt(KEY_PSKTYPE); 148 } 149 mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO); 150 if (savedState.containsKey(KEY_NETWORKINFO)) { 151 mNetworkInfo = savedState.getParcelable(KEY_NETWORKINFO); 152 } 153 if (savedState.containsKey(KEY_SCANRESULTCACHE)) { 154 ArrayList<ScanResult> scanResultArrayList = 155 savedState.getParcelableArrayList(KEY_SCANRESULTCACHE); 156 mScanResultCache.clear(); 157 for (ScanResult result : scanResultArrayList) { 158 mScanResultCache.put(result.BSSID, result); 159 } 160 } 161 update(mConfig, mInfo, mNetworkInfo); 162 mRssi = getRssi(); 163 mSeen = getSeen(); 164 } 165 166 AccessPoint(Context context, ScanResult result) { 167 mContext = context; 168 initWithScanResult(result); 169 } 170 171 AccessPoint(Context context, WifiConfiguration config) { 172 mContext = context; 173 loadConfig(config); 174 } 175 176 @Override 177 public int compareTo(@NonNull AccessPoint other) { 178 // Active one goes first. 179 if (isActive() && !other.isActive()) return -1; 180 if (!isActive() && other.isActive()) return 1; 181 182 // Reachable one goes before unreachable one. 183 if (mRssi != Integer.MAX_VALUE && other.mRssi == Integer.MAX_VALUE) return -1; 184 if (mRssi == Integer.MAX_VALUE && other.mRssi != Integer.MAX_VALUE) return 1; 185 186 // Configured one goes before unconfigured one. 187 if (networkId != WifiConfiguration.INVALID_NETWORK_ID 188 && other.networkId == WifiConfiguration.INVALID_NETWORK_ID) return -1; 189 if (networkId == WifiConfiguration.INVALID_NETWORK_ID 190 && other.networkId != WifiConfiguration.INVALID_NETWORK_ID) return 1; 191 192 // Sort by signal strength, bucketed by level 193 int difference = WifiManager.calculateSignalLevel(other.mRssi, SIGNAL_LEVELS) 194 - WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 195 if (difference != 0) { 196 return difference; 197 } 198 // Sort by ssid. 199 return ssid.compareToIgnoreCase(other.ssid); 200 } 201 202 @Override 203 public boolean equals(Object other) { 204 if (!(other instanceof AccessPoint)) return false; 205 return (this.compareTo((AccessPoint) other) == 0); 206 } 207 208 @Override 209 public int hashCode() { 210 int result = 0; 211 if (mInfo != null) result += 13 * mInfo.hashCode(); 212 result += 19 * mRssi; 213 result += 23 * networkId; 214 result += 29 * ssid.hashCode(); 215 return result; 216 } 217 218 @Override 219 public String toString() { 220 StringBuilder builder = new StringBuilder().append("AccessPoint(") 221 .append(ssid); 222 if (isSaved()) { 223 builder.append(',').append("saved"); 224 } 225 if (isActive()) { 226 builder.append(',').append("active"); 227 } 228 if (isEphemeral()) { 229 builder.append(',').append("ephemeral"); 230 } 231 if (isConnectable()) { 232 builder.append(',').append("connectable"); 233 } 234 if (security != SECURITY_NONE) { 235 builder.append(',').append(securityToString(security, pskType)); 236 } 237 return builder.append(')').toString(); 238 } 239 240 private void evictOldScanResults() { 241 long nowMs = SystemClock.elapsedRealtime(); 242 for (Iterator<ScanResult> iter = mScanResultCache.values().iterator(); iter.hasNext(); ) { 243 ScanResult result = iter.next(); 244 // result timestamp is in microseconds 245 if (nowMs - result.timestamp / 1000 > MAX_SCAN_RESULT_AGE_MS) { 246 iter.remove(); 247 } 248 } 249 } 250 251 public boolean matches(ScanResult result) { 252 return ssid.equals(result.SSID) && security == getSecurity(result); 253 } 254 255 public boolean matches(WifiConfiguration config) { 256 if (config.isPasspoint() && mConfig != null && mConfig.isPasspoint()) { 257 return ssid.equals(removeDoubleQuotes(config.SSID)) && config.FQDN.equals(mConfig.FQDN); 258 } else { 259 return ssid.equals(removeDoubleQuotes(config.SSID)) 260 && security == getSecurity(config) 261 && (mConfig == null || mConfig.shared == config.shared); 262 } 263 } 264 265 public WifiConfiguration getConfig() { 266 return mConfig; 267 } 268 269 public void clearConfig() { 270 mConfig = null; 271 networkId = WifiConfiguration.INVALID_NETWORK_ID; 272 } 273 274 public WifiInfo getInfo() { 275 return mInfo; 276 } 277 278 public int getLevel() { 279 if (mRssi == Integer.MAX_VALUE) { 280 return -1; 281 } 282 return WifiManager.calculateSignalLevel(mRssi, SIGNAL_LEVELS); 283 } 284 285 public int getRssi() { 286 evictOldScanResults(); 287 int rssi = Integer.MIN_VALUE; 288 for (ScanResult result : mScanResultCache.values()) { 289 if (result.level > rssi) { 290 rssi = result.level; 291 } 292 } 293 294 return rssi; 295 } 296 297 public long getSeen() { 298 evictOldScanResults(); 299 long seen = 0; 300 for (ScanResult result : mScanResultCache.values()) { 301 if (result.timestamp > seen) { 302 seen = result.timestamp; 303 } 304 } 305 306 return seen; 307 } 308 309 public NetworkInfo getNetworkInfo() { 310 return mNetworkInfo; 311 } 312 313 public int getSecurity() { 314 return security; 315 } 316 317 public String getSecurityString(boolean concise) { 318 Context context = mContext; 319 if (mConfig != null && mConfig.isPasspoint()) { 320 return concise ? context.getString(R.string.wifi_security_short_eap) : 321 context.getString(R.string.wifi_security_eap); 322 } 323 switch(security) { 324 case SECURITY_EAP: 325 return concise ? context.getString(R.string.wifi_security_short_eap) : 326 context.getString(R.string.wifi_security_eap); 327 case SECURITY_PSK: 328 switch (pskType) { 329 case PSK_WPA: 330 return concise ? context.getString(R.string.wifi_security_short_wpa) : 331 context.getString(R.string.wifi_security_wpa); 332 case PSK_WPA2: 333 return concise ? context.getString(R.string.wifi_security_short_wpa2) : 334 context.getString(R.string.wifi_security_wpa2); 335 case PSK_WPA_WPA2: 336 return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) : 337 context.getString(R.string.wifi_security_wpa_wpa2); 338 case PSK_UNKNOWN: 339 default: 340 return concise ? context.getString(R.string.wifi_security_short_psk_generic) 341 : context.getString(R.string.wifi_security_psk_generic); 342 } 343 case SECURITY_WEP: 344 return concise ? context.getString(R.string.wifi_security_short_wep) : 345 context.getString(R.string.wifi_security_wep); 346 case SECURITY_NONE: 347 default: 348 return concise ? "" : context.getString(R.string.wifi_security_none); 349 } 350 } 351 352 public String getSsidStr() { 353 return ssid; 354 } 355 356 public String getBssid() { 357 return bssid; 358 } 359 360 public CharSequence getSsid() { 361 SpannableString str = new SpannableString(ssid); 362 str.setSpan(new TtsSpan.VerbatimBuilder(ssid).build(), 0, ssid.length(), 363 Spannable.SPAN_INCLUSIVE_INCLUSIVE); 364 return str; 365 } 366 367 public String getConfigName() { 368 if (mConfig != null && mConfig.isPasspoint()) { 369 return mConfig.providerFriendlyName; 370 } else { 371 return ssid; 372 } 373 } 374 375 public DetailedState getDetailedState() { 376 if (mNetworkInfo != null) { 377 return mNetworkInfo.getDetailedState(); 378 } 379 Log.w(TAG, "NetworkInfo is null, cannot return detailed state"); 380 return null; 381 } 382 383 public String getSavedNetworkSummary() { 384 WifiConfiguration config = mConfig; 385 if (config != null) { 386 PackageManager pm = mContext.getPackageManager(); 387 String systemName = pm.getNameForUid(android.os.Process.SYSTEM_UID); 388 int userId = UserHandle.getUserId(config.creatorUid); 389 ApplicationInfo appInfo = null; 390 if (config.creatorName != null && config.creatorName.equals(systemName)) { 391 appInfo = mContext.getApplicationInfo(); 392 } else { 393 try { 394 IPackageManager ipm = AppGlobals.getPackageManager(); 395 appInfo = ipm.getApplicationInfo(config.creatorName, 0 /* flags */, userId); 396 } catch (RemoteException rex) { 397 } 398 } 399 if (appInfo != null && 400 !appInfo.packageName.equals(mContext.getString(R.string.settings_package)) && 401 !appInfo.packageName.equals( 402 mContext.getString(R.string.certinstaller_package))) { 403 return mContext.getString(R.string.saved_network, appInfo.loadLabel(pm)); 404 } 405 } 406 return ""; 407 } 408 409 public String getSummary() { 410 return getSettingsSummary(mConfig); 411 } 412 413 public String getSettingsSummary() { 414 return getSettingsSummary(mConfig); 415 } 416 417 private String getSettingsSummary(WifiConfiguration config) { 418 // Update to new summary 419 StringBuilder summary = new StringBuilder(); 420 421 if (isActive() && config != null && config.isPasspoint()) { 422 // This is the active connection on passpoint 423 summary.append(getSummary(mContext, getDetailedState(), 424 false, config.providerFriendlyName)); 425 } else if (isActive()) { 426 // This is the active connection on non-passpoint network 427 summary.append(getSummary(mContext, getDetailedState(), 428 mInfo != null && mInfo.isEphemeral())); 429 } else if (config != null && config.isPasspoint() 430 && config.getNetworkSelectionStatus().isNetworkEnabled()) { 431 String format = mContext.getString(R.string.available_via_passpoint); 432 summary.append(String.format(format, config.providerFriendlyName)); 433 } else if (config != null && config.hasNoInternetAccess()) { 434 int messageID = config.getNetworkSelectionStatus().isNetworkPermanentlyDisabled() 435 ? R.string.wifi_no_internet_no_reconnect 436 : R.string.wifi_no_internet; 437 summary.append(mContext.getString(messageID)); 438 } else if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 439 WifiConfiguration.NetworkSelectionStatus networkStatus = 440 config.getNetworkSelectionStatus(); 441 switch (networkStatus.getNetworkSelectionDisableReason()) { 442 case WifiConfiguration.NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE: 443 summary.append(mContext.getString(R.string.wifi_disabled_password_failure)); 444 break; 445 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE: 446 case WifiConfiguration.NetworkSelectionStatus.DISABLED_DNS_FAILURE: 447 summary.append(mContext.getString(R.string.wifi_disabled_network_failure)); 448 break; 449 case WifiConfiguration.NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION: 450 summary.append(mContext.getString(R.string.wifi_disabled_generic)); 451 break; 452 } 453 } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range 454 summary.append(mContext.getString(R.string.wifi_not_in_range)); 455 } else { // In range, not disabled. 456 if (config != null) { // Is saved network 457 summary.append(mContext.getString(R.string.wifi_remembered)); 458 } 459 } 460 461 if (WifiTracker.sVerboseLogging > 0) { 462 // Add RSSI/band information for this config, what was seen up to 6 seconds ago 463 // verbose WiFi Logging is only turned on thru developers settings 464 if (mInfo != null && mNetworkInfo != null) { // This is the active connection 465 summary.append(" f=" + Integer.toString(mInfo.getFrequency())); 466 } 467 summary.append(" " + getVisibilityStatus()); 468 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 469 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString()); 470 if (config.getNetworkSelectionStatus().getDisableTime() > 0) { 471 long now = System.currentTimeMillis(); 472 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000; 473 long sec = diff%60; //seconds 474 long min = (diff/60)%60; //minutes 475 long hour = (min/60)%60; //hours 476 summary.append(", "); 477 if (hour > 0) summary.append(Long.toString(hour) + "h "); 478 summary.append( Long.toString(min) + "m "); 479 summary.append( Long.toString(sec) + "s "); 480 } 481 summary.append(")"); 482 } 483 484 if (config != null) { 485 WifiConfiguration.NetworkSelectionStatus networkStatus = 486 config.getNetworkSelectionStatus(); 487 for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE; 488 index < WifiConfiguration.NetworkSelectionStatus 489 .NETWORK_SELECTION_DISABLED_MAX; index++) { 490 if (networkStatus.getDisableReasonCounter(index) != 0) { 491 summary.append(" " + WifiConfiguration.NetworkSelectionStatus 492 .getNetworkDisableReasonString(index) + "=" 493 + networkStatus.getDisableReasonCounter(index)); 494 } 495 } 496 } 497 } 498 return summary.toString(); 499 } 500 501 /** 502 * Returns the visibility status of the WifiConfiguration. 503 * 504 * @return autojoin debugging information 505 * TODO: use a string formatter 506 * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"] 507 * For instance [-40,5/-30,2] 508 */ 509 private String getVisibilityStatus() { 510 StringBuilder visibility = new StringBuilder(); 511 StringBuilder scans24GHz = null; 512 StringBuilder scans5GHz = null; 513 String bssid = null; 514 515 long now = System.currentTimeMillis(); 516 517 if (mInfo != null) { 518 bssid = mInfo.getBSSID(); 519 if (bssid != null) { 520 visibility.append(" ").append(bssid); 521 } 522 visibility.append(" rssi=").append(mInfo.getRssi()); 523 visibility.append(" "); 524 visibility.append(" score=").append(mInfo.score); 525 visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate)); 526 visibility.append(String.format("%.1f,", mInfo.txRetriesRate)); 527 visibility.append(String.format("%.1f ", mInfo.txBadRate)); 528 visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate)); 529 } 530 531 int rssi5 = WifiConfiguration.INVALID_RSSI; 532 int rssi24 = WifiConfiguration.INVALID_RSSI; 533 int num5 = 0; 534 int num24 = 0; 535 int numBlackListed = 0; 536 int n24 = 0; // Number scan results we included in the string 537 int n5 = 0; // Number scan results we included in the string 538 evictOldScanResults(); 539 // TODO: sort list by RSSI or age 540 for (ScanResult result : mScanResultCache.values()) { 541 542 if (result.frequency >= LOWER_FREQ_5GHZ 543 && result.frequency <= HIGHER_FREQ_5GHZ) { 544 // Strictly speaking: [4915, 5825] 545 // number of known BSSID on 5GHz band 546 num5 = num5 + 1; 547 } else if (result.frequency >= LOWER_FREQ_24GHZ 548 && result.frequency <= HIGHER_FREQ_24GHZ) { 549 // Strictly speaking: [2412, 2482] 550 // number of known BSSID on 2.4Ghz band 551 num24 = num24 + 1; 552 } 553 554 555 if (result.frequency >= LOWER_FREQ_5GHZ 556 && result.frequency <= HIGHER_FREQ_5GHZ) { 557 if (result.level > rssi5) { 558 rssi5 = result.level; 559 } 560 if (n5 < 4) { 561 if (scans5GHz == null) scans5GHz = new StringBuilder(); 562 scans5GHz.append(" \n{").append(result.BSSID); 563 if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*"); 564 scans5GHz.append("=").append(result.frequency); 565 scans5GHz.append(",").append(result.level); 566 scans5GHz.append("}"); 567 n5++; 568 } 569 } else if (result.frequency >= LOWER_FREQ_24GHZ 570 && result.frequency <= HIGHER_FREQ_24GHZ) { 571 if (result.level > rssi24) { 572 rssi24 = result.level; 573 } 574 if (n24 < 4) { 575 if (scans24GHz == null) scans24GHz = new StringBuilder(); 576 scans24GHz.append(" \n{").append(result.BSSID); 577 if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*"); 578 scans24GHz.append("=").append(result.frequency); 579 scans24GHz.append(",").append(result.level); 580 scans24GHz.append("}"); 581 n24++; 582 } 583 } 584 } 585 visibility.append(" ["); 586 if (num24 > 0) { 587 visibility.append("(").append(num24).append(")"); 588 if (n24 <= 4) { 589 if (scans24GHz != null) { 590 visibility.append(scans24GHz.toString()); 591 } 592 } else { 593 visibility.append("max=").append(rssi24); 594 if (scans24GHz != null) { 595 visibility.append(",").append(scans24GHz.toString()); 596 } 597 } 598 } 599 visibility.append(";"); 600 if (num5 > 0) { 601 visibility.append("(").append(num5).append(")"); 602 if (n5 <= 4) { 603 if (scans5GHz != null) { 604 visibility.append(scans5GHz.toString()); 605 } 606 } else { 607 visibility.append("max=").append(rssi5); 608 if (scans5GHz != null) { 609 visibility.append(",").append(scans5GHz.toString()); 610 } 611 } 612 } 613 if (numBlackListed > 0) 614 visibility.append("!").append(numBlackListed); 615 visibility.append("]"); 616 617 return visibility.toString(); 618 } 619 620 /** 621 * Return whether this is the active connection. 622 * For ephemeral connections (networkId is invalid), this returns false if the network is 623 * disconnected. 624 */ 625 public boolean isActive() { 626 return mNetworkInfo != null && 627 (networkId != WifiConfiguration.INVALID_NETWORK_ID || 628 mNetworkInfo.getState() != State.DISCONNECTED); 629 } 630 631 public boolean isConnectable() { 632 return getLevel() != -1 && getDetailedState() == null; 633 } 634 635 public boolean isEphemeral() { 636 return mInfo != null && mInfo.isEphemeral() && 637 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED; 638 } 639 640 public boolean isPasspoint() { 641 return mConfig != null && mConfig.isPasspoint(); 642 } 643 644 /** 645 * Return whether the given {@link WifiInfo} is for this access point. 646 * If the current AP does not have a network Id then the config is used to 647 * match based on SSID and security. 648 */ 649 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) { 650 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) { 651 return networkId == info.getNetworkId(); 652 } else if (config != null) { 653 return matches(config); 654 } 655 else { 656 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID. 657 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID). 658 // TODO: Handle hex string SSIDs. 659 return ssid.equals(removeDoubleQuotes(info.getSSID())); 660 } 661 } 662 663 public boolean isSaved() { 664 return networkId != WifiConfiguration.INVALID_NETWORK_ID; 665 } 666 667 public Object getTag() { 668 return mTag; 669 } 670 671 public void setTag(Object tag) { 672 mTag = tag; 673 } 674 675 /** 676 * Generate and save a default wifiConfiguration with common values. 677 * Can only be called for unsecured networks. 678 */ 679 public void generateOpenNetworkConfig() { 680 if (security != SECURITY_NONE) 681 throw new IllegalStateException(); 682 if (mConfig != null) 683 return; 684 mConfig = new WifiConfiguration(); 685 mConfig.SSID = AccessPoint.convertToQuotedString(ssid); 686 mConfig.allowedKeyManagement.set(KeyMgmt.NONE); 687 } 688 689 void loadConfig(WifiConfiguration config) { 690 if (config.isPasspoint()) 691 ssid = config.providerFriendlyName; 692 else 693 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID)); 694 695 bssid = config.BSSID; 696 security = getSecurity(config); 697 networkId = config.networkId; 698 mConfig = config; 699 } 700 701 private void initWithScanResult(ScanResult result) { 702 ssid = result.SSID; 703 bssid = result.BSSID; 704 security = getSecurity(result); 705 if (security == SECURITY_PSK) 706 pskType = getPskType(result); 707 mRssi = result.level; 708 mSeen = result.timestamp; 709 } 710 711 public void saveWifiState(Bundle savedState) { 712 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr()); 713 savedState.putInt(KEY_SECURITY, security); 714 savedState.putInt(KEY_PSKTYPE, pskType); 715 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig); 716 savedState.putParcelable(KEY_WIFIINFO, mInfo); 717 evictOldScanResults(); 718 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE, 719 new ArrayList<ScanResult>(mScanResultCache.values())); 720 if (mNetworkInfo != null) { 721 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo); 722 } 723 } 724 725 public void setListener(AccessPointListener listener) { 726 mAccessPointListener = listener; 727 } 728 729 boolean update(ScanResult result) { 730 if (matches(result)) { 731 /* Add or update the scan result for the BSSID */ 732 mScanResultCache.put(result.BSSID, result); 733 734 int oldLevel = getLevel(); 735 int oldRssi = getRssi(); 736 mSeen = getSeen(); 737 mRssi = (getRssi() + oldRssi)/2; 738 int newLevel = getLevel(); 739 740 if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) { 741 mAccessPointListener.onLevelChanged(this); 742 } 743 // This flag only comes from scans, is not easily saved in config 744 if (security == SECURITY_PSK) { 745 pskType = getPskType(result); 746 } 747 748 if (mAccessPointListener != null) { 749 mAccessPointListener.onAccessPointChanged(this); 750 } 751 752 return true; 753 } 754 return false; 755 } 756 757 boolean update(WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) { 758 boolean reorder = false; 759 if (info != null && isInfoForThisAccessPoint(config, info)) { 760 reorder = (mInfo == null); 761 mRssi = info.getRssi(); 762 mInfo = info; 763 mNetworkInfo = networkInfo; 764 if (mAccessPointListener != null) { 765 mAccessPointListener.onAccessPointChanged(this); 766 } 767 } else if (mInfo != null) { 768 reorder = true; 769 mInfo = null; 770 mNetworkInfo = null; 771 if (mAccessPointListener != null) { 772 mAccessPointListener.onAccessPointChanged(this); 773 } 774 } 775 return reorder; 776 } 777 778 void update(WifiConfiguration config) { 779 mConfig = config; 780 networkId = config.networkId; 781 if (mAccessPointListener != null) { 782 mAccessPointListener.onAccessPointChanged(this); 783 } 784 } 785 786 void setRssi(int rssi) { 787 mRssi = rssi; 788 } 789 790 public static String getSummary(Context context, String ssid, DetailedState state, 791 boolean isEphemeral, String passpointProvider) { 792 if (state == DetailedState.CONNECTED && ssid == null) { 793 if (TextUtils.isEmpty(passpointProvider) == false) { 794 // Special case for connected + passpoint networks. 795 String format = context.getString(R.string.connected_via_passpoint); 796 return String.format(format, passpointProvider); 797 } else if (isEphemeral) { 798 // Special case for connected + ephemeral networks. 799 return context.getString(R.string.connected_via_wfa); 800 } 801 } 802 803 // Case when there is wifi connected without internet connectivity. 804 final ConnectivityManager cm = (ConnectivityManager) 805 context.getSystemService(Context.CONNECTIVITY_SERVICE); 806 if (state == DetailedState.CONNECTED) { 807 IWifiManager wifiManager = IWifiManager.Stub.asInterface( 808 ServiceManager.getService(Context.WIFI_SERVICE)); 809 NetworkCapabilities nc = null; 810 811 try { 812 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork()); 813 } catch (RemoteException e) {} 814 815 if (nc != null) { 816 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) { 817 return context.getString( 818 com.android.internal.R.string.network_available_sign_in); 819 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) { 820 return context.getString(R.string.wifi_connected_no_internet); 821 } 822 } 823 } 824 if (state == null) { 825 Log.w(TAG, "state is null, returning empty summary"); 826 return ""; 827 } 828 String[] formats = context.getResources().getStringArray((ssid == null) 829 ? R.array.wifi_status : R.array.wifi_status_with_ssid); 830 int index = state.ordinal(); 831 832 if (index >= formats.length || formats[index].length() == 0) { 833 return ""; 834 } 835 return String.format(formats[index], ssid); 836 } 837 838 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) { 839 return getSummary(context, null, state, isEphemeral, null); 840 } 841 842 public static String getSummary(Context context, DetailedState state, boolean isEphemeral, 843 String passpointProvider) { 844 return getSummary(context, null, state, isEphemeral, passpointProvider); 845 } 846 847 public static String convertToQuotedString(String string) { 848 return "\"" + string + "\""; 849 } 850 851 private static int getPskType(ScanResult result) { 852 boolean wpa = result.capabilities.contains("WPA-PSK"); 853 boolean wpa2 = result.capabilities.contains("WPA2-PSK"); 854 if (wpa2 && wpa) { 855 return PSK_WPA_WPA2; 856 } else if (wpa2) { 857 return PSK_WPA2; 858 } else if (wpa) { 859 return PSK_WPA; 860 } else { 861 Log.w(TAG, "Received abnormal flag string: " + result.capabilities); 862 return PSK_UNKNOWN; 863 } 864 } 865 866 private static int getSecurity(ScanResult result) { 867 if (result.capabilities.contains("WEP")) { 868 return SECURITY_WEP; 869 } else if (result.capabilities.contains("PSK")) { 870 return SECURITY_PSK; 871 } else if (result.capabilities.contains("EAP")) { 872 return SECURITY_EAP; 873 } 874 return SECURITY_NONE; 875 } 876 877 static int getSecurity(WifiConfiguration config) { 878 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 879 return SECURITY_PSK; 880 } 881 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || 882 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { 883 return SECURITY_EAP; 884 } 885 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE; 886 } 887 888 public static String securityToString(int security, int pskType) { 889 if (security == SECURITY_WEP) { 890 return "WEP"; 891 } else if (security == SECURITY_PSK) { 892 if (pskType == PSK_WPA) { 893 return "WPA"; 894 } else if (pskType == PSK_WPA2) { 895 return "WPA2"; 896 } else if (pskType == PSK_WPA_WPA2) { 897 return "WPA_WPA2"; 898 } 899 return "PSK"; 900 } else if (security == SECURITY_EAP) { 901 return "EAP"; 902 } 903 return "NONE"; 904 } 905 906 static String removeDoubleQuotes(String string) { 907 if (TextUtils.isEmpty(string)) { 908 return ""; 909 } 910 int length = string.length(); 911 if ((length > 1) && (string.charAt(0) == '"') 912 && (string.charAt(length - 1) == '"')) { 913 return string.substring(1, length - 1); 914 } 915 return string; 916 } 917 918 public interface AccessPointListener { 919 void onAccessPointChanged(AccessPoint accessPoint); 920 void onLevelChanged(AccessPoint accessPoint); 921 } 922} 923