AccessPoint.java revision 68cf9f538bc302c6c1038697a70476f282b09039
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 summary.append(mContext.getString(R.string.wifi_remembered)); 725 } 726 } 727 728 if (WifiTracker.sVerboseLogging) { 729 // Add RSSI/band information for this config, what was seen up to 6 seconds ago 730 // verbose WiFi Logging is only turned on thru developers settings 731 if (mInfo != null && mNetworkInfo != null) { // This is the active connection 732 summary.append(" f=" + Integer.toString(mInfo.getFrequency())); 733 } 734 summary.append(" " + getVisibilityStatus()); 735 if (config != null && !config.getNetworkSelectionStatus().isNetworkEnabled()) { 736 summary.append(" (" + config.getNetworkSelectionStatus().getNetworkStatusString()); 737 if (config.getNetworkSelectionStatus().getDisableTime() > 0) { 738 long now = System.currentTimeMillis(); 739 long diff = (now - config.getNetworkSelectionStatus().getDisableTime()) / 1000; 740 long sec = diff%60; //seconds 741 long min = (diff/60)%60; //minutes 742 long hour = (min/60)%60; //hours 743 summary.append(", "); 744 if (hour > 0) summary.append(Long.toString(hour) + "h "); 745 summary.append( Long.toString(min) + "m "); 746 summary.append( Long.toString(sec) + "s "); 747 } 748 summary.append(")"); 749 } 750 751 if (config != null) { 752 WifiConfiguration.NetworkSelectionStatus networkStatus = 753 config.getNetworkSelectionStatus(); 754 for (int index = WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE; 755 index < WifiConfiguration.NetworkSelectionStatus 756 .NETWORK_SELECTION_DISABLED_MAX; index++) { 757 if (networkStatus.getDisableReasonCounter(index) != 0) { 758 summary.append(" " + WifiConfiguration.NetworkSelectionStatus 759 .getNetworkDisableReasonString(index) + "=" 760 + networkStatus.getDisableReasonCounter(index)); 761 } 762 } 763 } 764 } 765 766 // Strip trailing delimiter if applicable 767 int concatLength = concatenator.length(); 768 if (summary.length() >= concatLength && summary.substring( 769 summary.length() - concatLength, summary.length()).equals(concatenator)) { 770 summary.delete(summary.length() - concatLength, summary.length()); 771 } 772 773 return summary.toString(); 774 } 775 776 /** 777 * Returns the visibility status of the WifiConfiguration. 778 * 779 * @return autojoin debugging information 780 * TODO: use a string formatter 781 * ["rssi 5Ghz", "num results on 5GHz" / "rssi 5Ghz", "num results on 5GHz"] 782 * For instance [-40,5/-30,2] 783 */ 784 private String getVisibilityStatus() { 785 StringBuilder visibility = new StringBuilder(); 786 StringBuilder scans24GHz = null; 787 StringBuilder scans5GHz = null; 788 String bssid = null; 789 790 long now = System.currentTimeMillis(); 791 792 if (mInfo != null) { 793 bssid = mInfo.getBSSID(); 794 if (bssid != null) { 795 visibility.append(" ").append(bssid); 796 } 797 visibility.append(" rssi=").append(mInfo.getRssi()); 798 visibility.append(" "); 799 visibility.append(" score=").append(mInfo.score); 800 if (mRankingScore != Integer.MIN_VALUE) { 801 visibility.append(" rankingScore=").append(getRankingScore()); 802 } 803 if (mSpeed != Speed.NONE) { 804 visibility.append(" speed=").append(getSpeedLabel()); 805 } 806 visibility.append(String.format(" tx=%.1f,", mInfo.txSuccessRate)); 807 visibility.append(String.format("%.1f,", mInfo.txRetriesRate)); 808 visibility.append(String.format("%.1f ", mInfo.txBadRate)); 809 visibility.append(String.format("rx=%.1f", mInfo.rxSuccessRate)); 810 } 811 812 int rssi5 = WifiConfiguration.INVALID_RSSI; 813 int rssi24 = WifiConfiguration.INVALID_RSSI; 814 int num5 = 0; 815 int num24 = 0; 816 int numBlackListed = 0; 817 int n24 = 0; // Number scan results we included in the string 818 int n5 = 0; // Number scan results we included in the string 819 evictOldScanResults(); 820 // TODO: sort list by RSSI or age 821 for (ScanResult result : mScanResultCache.values()) { 822 823 if (result.frequency >= LOWER_FREQ_5GHZ 824 && result.frequency <= HIGHER_FREQ_5GHZ) { 825 // Strictly speaking: [4915, 5825] 826 // number of known BSSID on 5GHz band 827 num5 = num5 + 1; 828 } else if (result.frequency >= LOWER_FREQ_24GHZ 829 && result.frequency <= HIGHER_FREQ_24GHZ) { 830 // Strictly speaking: [2412, 2482] 831 // number of known BSSID on 2.4Ghz band 832 num24 = num24 + 1; 833 } 834 835 836 if (result.frequency >= LOWER_FREQ_5GHZ 837 && result.frequency <= HIGHER_FREQ_5GHZ) { 838 if (result.level > rssi5) { 839 rssi5 = result.level; 840 } 841 if (n5 < 4) { 842 if (scans5GHz == null) scans5GHz = new StringBuilder(); 843 scans5GHz.append(" \n{").append(result.BSSID); 844 if (bssid != null && result.BSSID.equals(bssid)) scans5GHz.append("*"); 845 scans5GHz.append("=").append(result.frequency); 846 scans5GHz.append(",").append(result.level); 847 scans5GHz.append("}"); 848 n5++; 849 } 850 } else if (result.frequency >= LOWER_FREQ_24GHZ 851 && result.frequency <= HIGHER_FREQ_24GHZ) { 852 if (result.level > rssi24) { 853 rssi24 = result.level; 854 } 855 if (n24 < 4) { 856 if (scans24GHz == null) scans24GHz = new StringBuilder(); 857 scans24GHz.append(" \n{").append(result.BSSID); 858 if (bssid != null && result.BSSID.equals(bssid)) scans24GHz.append("*"); 859 scans24GHz.append("=").append(result.frequency); 860 scans24GHz.append(",").append(result.level); 861 scans24GHz.append("}"); 862 n24++; 863 } 864 } 865 } 866 visibility.append(" ["); 867 if (num24 > 0) { 868 visibility.append("(").append(num24).append(")"); 869 if (n24 <= 4) { 870 if (scans24GHz != null) { 871 visibility.append(scans24GHz.toString()); 872 } 873 } else { 874 visibility.append("max=").append(rssi24); 875 if (scans24GHz != null) { 876 visibility.append(",").append(scans24GHz.toString()); 877 } 878 } 879 } 880 visibility.append(";"); 881 if (num5 > 0) { 882 visibility.append("(").append(num5).append(")"); 883 if (n5 <= 4) { 884 if (scans5GHz != null) { 885 visibility.append(scans5GHz.toString()); 886 } 887 } else { 888 visibility.append("max=").append(rssi5); 889 if (scans5GHz != null) { 890 visibility.append(",").append(scans5GHz.toString()); 891 } 892 } 893 } 894 if (numBlackListed > 0) 895 visibility.append("!").append(numBlackListed); 896 visibility.append("]"); 897 898 return visibility.toString(); 899 } 900 901 /** 902 * Return whether this is the active connection. 903 * For ephemeral connections (networkId is invalid), this returns false if the network is 904 * disconnected. 905 */ 906 public boolean isActive() { 907 return mNetworkInfo != null && 908 (networkId != WifiConfiguration.INVALID_NETWORK_ID || 909 mNetworkInfo.getState() != State.DISCONNECTED); 910 } 911 912 public boolean isConnectable() { 913 return getLevel() != -1 && getDetailedState() == null; 914 } 915 916 public boolean isEphemeral() { 917 return mInfo != null && mInfo.isEphemeral() && 918 mNetworkInfo != null && mNetworkInfo.getState() != State.DISCONNECTED; 919 } 920 921 /** 922 * Return true if this AccessPoint represents a Passpoint AP. 923 */ 924 public boolean isPasspoint() { 925 return mConfig != null && mConfig.isPasspoint(); 926 } 927 928 /** 929 * Return true if this AccessPoint represents a Passpoint provider configuration. 930 */ 931 public boolean isPasspointConfig() { 932 return mFqdn != null; 933 } 934 935 /** 936 * Return whether the given {@link WifiInfo} is for this access point. 937 * If the current AP does not have a network Id then the config is used to 938 * match based on SSID and security. 939 */ 940 private boolean isInfoForThisAccessPoint(WifiConfiguration config, WifiInfo info) { 941 if (isPasspoint() == false && networkId != WifiConfiguration.INVALID_NETWORK_ID) { 942 return networkId == info.getNetworkId(); 943 } else if (config != null) { 944 return matches(config); 945 } 946 else { 947 // Might be an ephemeral connection with no WifiConfiguration. Try matching on SSID. 948 // (Note that we only do this if the WifiConfiguration explicitly equals INVALID). 949 // TODO: Handle hex string SSIDs. 950 return ssid.equals(removeDoubleQuotes(info.getSSID())); 951 } 952 } 953 954 public boolean isSaved() { 955 return networkId != WifiConfiguration.INVALID_NETWORK_ID; 956 } 957 958 public Object getTag() { 959 return mTag; 960 } 961 962 public void setTag(Object tag) { 963 mTag = tag; 964 } 965 966 /** 967 * Generate and save a default wifiConfiguration with common values. 968 * Can only be called for unsecured networks. 969 */ 970 public void generateOpenNetworkConfig() { 971 if (security != SECURITY_NONE) 972 throw new IllegalStateException(); 973 if (mConfig != null) 974 return; 975 mConfig = new WifiConfiguration(); 976 mConfig.SSID = AccessPoint.convertToQuotedString(ssid); 977 mConfig.allowedKeyManagement.set(KeyMgmt.NONE); 978 } 979 980 void loadConfig(WifiConfiguration config) { 981 ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID)); 982 bssid = config.BSSID; 983 security = getSecurity(config); 984 networkId = config.networkId; 985 mConfig = config; 986 } 987 988 private void initWithScanResult(ScanResult result) { 989 ssid = result.SSID; 990 bssid = result.BSSID; 991 security = getSecurity(result); 992 if (security == SECURITY_PSK) 993 pskType = getPskType(result); 994 995 mScanResultCache.put(result.BSSID, result); 996 updateRssi(); 997 mSeen = result.timestamp; // even if the timestamp is old it is still valid 998 } 999 1000 public void saveWifiState(Bundle savedState) { 1001 if (ssid != null) savedState.putString(KEY_SSID, getSsidStr()); 1002 savedState.putInt(KEY_SECURITY, security); 1003 savedState.putInt(KEY_PSKTYPE, pskType); 1004 if (mConfig != null) savedState.putParcelable(KEY_CONFIG, mConfig); 1005 savedState.putParcelable(KEY_WIFIINFO, mInfo); 1006 evictOldScanResults(); 1007 savedState.putParcelableArrayList(KEY_SCANRESULTCACHE, 1008 new ArrayList<ScanResult>(mScanResultCache.values())); 1009 if (mNetworkInfo != null) { 1010 savedState.putParcelable(KEY_NETWORKINFO, mNetworkInfo); 1011 } 1012 if (mFqdn != null) { 1013 savedState.putString(KEY_FQDN, mFqdn); 1014 } 1015 if (mProviderFriendlyName != null) { 1016 savedState.putString(KEY_PROVIDER_FRIENDLY_NAME, mProviderFriendlyName); 1017 } 1018 } 1019 1020 public void setListener(AccessPointListener listener) { 1021 mAccessPointListener = listener; 1022 } 1023 1024 boolean update(ScanResult result) { 1025 if (matches(result)) { 1026 int oldLevel = getLevel(); 1027 1028 /* Add or update the scan result for the BSSID */ 1029 mScanResultCache.put(result.BSSID, result); 1030 updateSeen(); 1031 updateRssi(); 1032 int newLevel = getLevel(); 1033 1034 if (newLevel > 0 && newLevel != oldLevel && mAccessPointListener != null) { 1035 mAccessPointListener.onLevelChanged(this); 1036 } 1037 // This flag only comes from scans, is not easily saved in config 1038 if (security == SECURITY_PSK) { 1039 pskType = getPskType(result); 1040 } 1041 1042 if (mAccessPointListener != null) { 1043 mAccessPointListener.onAccessPointChanged(this); 1044 } 1045 1046 return true; 1047 } 1048 return false; 1049 } 1050 1051 /** Attempt to update the AccessPoint and return true if an update occurred. */ 1052 public boolean update( 1053 @Nullable WifiConfiguration config, WifiInfo info, NetworkInfo networkInfo) { 1054 boolean updated = false; 1055 final int oldLevel = getLevel(); 1056 if (info != null && isInfoForThisAccessPoint(config, info)) { 1057 updated = (mInfo == null); 1058 if (mConfig != config) { 1059 // We do not set updated = true as we do not want to increase the amount of sorting 1060 // and copying performed in WifiTracker at this time. If issues involving refresh 1061 // are still seen, we will investigate further. 1062 update(config); // Notifies the AccessPointListener of the change 1063 } 1064 if (mRssi != info.getRssi()) { 1065 mRssi = info.getRssi(); 1066 updated = true; 1067 } else if (mNetworkInfo != null && networkInfo != null 1068 && mNetworkInfo.getDetailedState() != networkInfo.getDetailedState()) { 1069 updated = true; 1070 } 1071 mInfo = info; 1072 mNetworkInfo = networkInfo; 1073 } else if (mInfo != null) { 1074 updated = true; 1075 mInfo = null; 1076 mNetworkInfo = null; 1077 } 1078 if (updated && mAccessPointListener != null) { 1079 mAccessPointListener.onAccessPointChanged(this); 1080 1081 if (oldLevel != getLevel() /* current level */) { 1082 mAccessPointListener.onLevelChanged(this); 1083 } 1084 } 1085 return updated; 1086 } 1087 1088 void update(@Nullable WifiConfiguration config) { 1089 mConfig = config; 1090 networkId = config != null ? config.networkId : WifiConfiguration.INVALID_NETWORK_ID; 1091 if (mAccessPointListener != null) { 1092 mAccessPointListener.onAccessPointChanged(this); 1093 } 1094 } 1095 1096 @VisibleForTesting 1097 void setRssi(int rssi) { 1098 mRssi = rssi; 1099 } 1100 1101 /** Sets the rssi to {@link #UNREACHABLE_RSSI}. */ 1102 void setUnreachable() { 1103 setRssi(AccessPoint.UNREACHABLE_RSSI); 1104 } 1105 1106 int getRankingScore() { 1107 return mRankingScore; 1108 } 1109 1110 int getSpeed() { return mSpeed;} 1111 1112 @Nullable 1113 String getSpeedLabel() { 1114 switch (mSpeed) { 1115 case Speed.VERY_FAST: 1116 return mContext.getString(R.string.speed_label_very_fast); 1117 case Speed.FAST: 1118 return mContext.getString(R.string.speed_label_fast); 1119 case Speed.MODERATE: 1120 return mContext.getString(R.string.speed_label_okay); 1121 case Speed.SLOW: 1122 return mContext.getString(R.string.speed_label_slow); 1123 case Speed.NONE: 1124 default: 1125 return null; 1126 } 1127 } 1128 1129 /** Return true if the current RSSI is reachable, and false otherwise. */ 1130 public boolean isReachable() { 1131 return mRssi != UNREACHABLE_RSSI; 1132 } 1133 1134 public static String getSummary(Context context, String ssid, DetailedState state, 1135 boolean isEphemeral, String passpointProvider) { 1136 if (state == DetailedState.CONNECTED && ssid == null) { 1137 if (TextUtils.isEmpty(passpointProvider) == false) { 1138 // Special case for connected + passpoint networks. 1139 String format = context.getString(R.string.connected_via_passpoint); 1140 return String.format(format, passpointProvider); 1141 } else if (isEphemeral) { 1142 // Special case for connected + ephemeral networks. 1143 final NetworkScoreManager networkScoreManager = context.getSystemService( 1144 NetworkScoreManager.class); 1145 NetworkScorerAppData scorer = networkScoreManager.getActiveScorer(); 1146 if (scorer != null && scorer.getRecommendationServiceLabel() != null) { 1147 String format = context.getString(R.string.connected_via_network_scorer); 1148 return String.format(format, scorer.getRecommendationServiceLabel()); 1149 } else { 1150 return context.getString(R.string.connected_via_network_scorer_default); 1151 } 1152 } 1153 } 1154 1155 // Case when there is wifi connected without internet connectivity. 1156 final ConnectivityManager cm = (ConnectivityManager) 1157 context.getSystemService(Context.CONNECTIVITY_SERVICE); 1158 if (state == DetailedState.CONNECTED) { 1159 IWifiManager wifiManager = IWifiManager.Stub.asInterface( 1160 ServiceManager.getService(Context.WIFI_SERVICE)); 1161 NetworkCapabilities nc = null; 1162 1163 try { 1164 nc = cm.getNetworkCapabilities(wifiManager.getCurrentNetwork()); 1165 } catch (RemoteException e) {} 1166 1167 if (nc != null) { 1168 if (nc.hasCapability(nc.NET_CAPABILITY_CAPTIVE_PORTAL)) { 1169 int id = context.getResources() 1170 .getIdentifier("network_available_sign_in", "string", "android"); 1171 return context.getString(id); 1172 } else if (!nc.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) { 1173 return context.getString(R.string.wifi_connected_no_internet); 1174 } 1175 } 1176 } 1177 if (state == null) { 1178 Log.w(TAG, "state is null, returning empty summary"); 1179 return ""; 1180 } 1181 String[] formats = context.getResources().getStringArray((ssid == null) 1182 ? R.array.wifi_status : R.array.wifi_status_with_ssid); 1183 int index = state.ordinal(); 1184 1185 if (index >= formats.length || formats[index].length() == 0) { 1186 return ""; 1187 } 1188 return String.format(formats[index], ssid); 1189 } 1190 1191 public static String getSummary(Context context, DetailedState state, boolean isEphemeral) { 1192 return getSummary(context, null, state, isEphemeral, null); 1193 } 1194 1195 public static String getSummary(Context context, DetailedState state, boolean isEphemeral, 1196 String passpointProvider) { 1197 return getSummary(context, null, state, isEphemeral, passpointProvider); 1198 } 1199 1200 public static String convertToQuotedString(String string) { 1201 return "\"" + string + "\""; 1202 } 1203 1204 private static int getPskType(ScanResult result) { 1205 boolean wpa = result.capabilities.contains("WPA-PSK"); 1206 boolean wpa2 = result.capabilities.contains("WPA2-PSK"); 1207 if (wpa2 && wpa) { 1208 return PSK_WPA_WPA2; 1209 } else if (wpa2) { 1210 return PSK_WPA2; 1211 } else if (wpa) { 1212 return PSK_WPA; 1213 } else { 1214 Log.w(TAG, "Received abnormal flag string: " + result.capabilities); 1215 return PSK_UNKNOWN; 1216 } 1217 } 1218 1219 private static int getSecurity(ScanResult result) { 1220 if (result.capabilities.contains("WEP")) { 1221 return SECURITY_WEP; 1222 } else if (result.capabilities.contains("PSK")) { 1223 return SECURITY_PSK; 1224 } else if (result.capabilities.contains("EAP")) { 1225 return SECURITY_EAP; 1226 } 1227 return SECURITY_NONE; 1228 } 1229 1230 static int getSecurity(WifiConfiguration config) { 1231 if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 1232 return SECURITY_PSK; 1233 } 1234 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) || 1235 config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { 1236 return SECURITY_EAP; 1237 } 1238 return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE; 1239 } 1240 1241 public static String securityToString(int security, int pskType) { 1242 if (security == SECURITY_WEP) { 1243 return "WEP"; 1244 } else if (security == SECURITY_PSK) { 1245 if (pskType == PSK_WPA) { 1246 return "WPA"; 1247 } else if (pskType == PSK_WPA2) { 1248 return "WPA2"; 1249 } else if (pskType == PSK_WPA_WPA2) { 1250 return "WPA_WPA2"; 1251 } 1252 return "PSK"; 1253 } else if (security == SECURITY_EAP) { 1254 return "EAP"; 1255 } 1256 return "NONE"; 1257 } 1258 1259 static String removeDoubleQuotes(String string) { 1260 if (TextUtils.isEmpty(string)) { 1261 return ""; 1262 } 1263 int length = string.length(); 1264 if ((length > 1) && (string.charAt(0) == '"') 1265 && (string.charAt(length - 1) == '"')) { 1266 return string.substring(1, length - 1); 1267 } 1268 return string; 1269 } 1270 1271 public interface AccessPointListener { 1272 void onAccessPointChanged(AccessPoint accessPoint); 1273 void onLevelChanged(AccessPoint accessPoint); 1274 } 1275} 1276