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