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