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