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