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