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