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