1/* 2 * Copyright (C) 2010 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.server.wifi; 18 19import android.content.Context; 20import android.content.Intent; 21import android.net.IpConfiguration; 22import android.net.IpConfiguration.IpAssignment; 23import android.net.IpConfiguration.ProxySettings; 24import android.net.LinkAddress; 25import android.net.NetworkInfo.DetailedState; 26import android.net.ProxyInfo; 27import android.net.RouteInfo; 28import android.net.StaticIpConfiguration; 29import android.net.wifi.WifiConfiguration; 30import android.net.wifi.WifiConfiguration.KeyMgmt; 31import android.net.wifi.WifiConfiguration.Status; 32import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID; 33 34import android.net.wifi.WifiEnterpriseConfig; 35import android.net.wifi.WifiManager; 36import android.net.wifi.WifiSsid; 37import android.net.wifi.WpsInfo; 38import android.net.wifi.WpsResult; 39import android.net.wifi.ScanResult; 40import android.net.wifi.WifiInfo; 41 42import android.os.Environment; 43import android.os.FileObserver; 44import android.os.Process; 45import android.os.SystemClock; 46import android.os.UserHandle; 47import android.provider.Settings; 48import android.security.Credentials; 49import android.security.KeyChain; 50import android.security.KeyStore; 51import android.text.TextUtils; 52import android.util.LocalLog; 53import android.util.Log; 54import android.util.SparseArray; 55 56import com.android.server.net.DelayedDiskWrite; 57import com.android.server.net.IpConfigStore; 58import com.android.internal.R; 59 60import java.io.BufferedReader; 61import java.io.BufferedInputStream; 62import java.io.DataInputStream; 63import java.io.DataOutputStream; 64import java.io.EOFException; 65import java.io.File; 66import java.io.FileDescriptor; 67import java.io.FileInputStream; 68import java.io.FileNotFoundException; 69import java.io.FileReader; 70import java.io.IOException; 71import java.io.PrintWriter; 72import java.math.BigInteger; 73import java.net.InetAddress; 74import java.nio.charset.Charset; 75import java.security.PrivateKey; 76import java.security.cert.Certificate; 77import java.security.cert.CertificateException; 78import java.text.SimpleDateFormat; 79import java.text.DateFormat; 80import java.util.regex.Matcher; 81import java.util.regex.Pattern; 82import java.util.*; 83import java.util.zip.Checksum; 84import java.util.zip.CRC32; 85 86/** 87 * This class provides the API to manage configured 88 * wifi networks. The API is not thread safe is being 89 * used only from WifiStateMachine. 90 * 91 * It deals with the following 92 * - Add/update/remove a WifiConfiguration 93 * The configuration contains two types of information. 94 * = IP and proxy configuration that is handled by WifiConfigStore and 95 * is saved to disk on any change. 96 * 97 * The format of configuration file is as follows: 98 * <version> 99 * <netA_key1><netA_value1><netA_key2><netA_value2>...<EOS> 100 * <netB_key1><netB_value1><netB_key2><netB_value2>...<EOS> 101 * .. 102 * 103 * (key, value) pairs for a given network are grouped together and can 104 * be in any order. A EOS at the end of a set of (key, value) pairs 105 * indicates that the next set of (key, value) pairs are for a new 106 * network. A network is identified by a unique ID_KEY. If there is no 107 * ID_KEY in the (key, value) pairs, the data is discarded. 108 * 109 * An invalid version on read would result in discarding the contents of 110 * the file. On the next write, the latest version is written to file. 111 * 112 * Any failures during read or write to the configuration file are ignored 113 * without reporting to the user since the likelihood of these errors are 114 * low and the impact on connectivity is low. 115 * 116 * = SSID & security details that is pushed to the supplicant. 117 * supplicant saves these details to the disk on calling 118 * saveConfigCommand(). 119 * 120 * We have two kinds of APIs exposed: 121 * > public API calls that provide fine grained control 122 * - enableNetwork, disableNetwork, addOrUpdateNetwork(), 123 * removeNetwork(). For these calls, the config is not persisted 124 * to the disk. (TODO: deprecate these calls in WifiManager) 125 * > The new API calls - selectNetwork(), saveNetwork() & forgetNetwork(). 126 * These calls persist the supplicant config to disk. 127 * 128 * - Maintain a list of configured networks for quick access 129 * 130 */ 131public class WifiConfigStore extends IpConfigStore { 132 133 private Context mContext; 134 private static final String TAG = "WifiConfigStore"; 135 private static final boolean DBG = true; 136 private static boolean VDBG = false; 137 private static boolean VVDBG = false; 138 139 private static final String SUPPLICANT_CONFIG_FILE = "/data/misc/wifi/wpa_supplicant.conf"; 140 141 /* configured networks with network id as the key */ 142 private HashMap<Integer, WifiConfiguration> mConfiguredNetworks = 143 new HashMap<Integer, WifiConfiguration>(); 144 145 /* A network id is a unique identifier for a network configured in the 146 * supplicant. Network ids are generated when the supplicant reads 147 * the configuration file at start and can thus change for networks. 148 * We store the IP configuration for networks along with a unique id 149 * that is generated from SSID and security type of the network. A mapping 150 * from the generated unique id to network id of the network is needed to 151 * map supplicant config to IP configuration. */ 152 private HashMap<Integer, Integer> mNetworkIds = 153 new HashMap<Integer, Integer>(); 154 155 /** 156 * Framework keeps a list of (the CRC32 hashes of) all SSIDs that where deleted by user, 157 * so as, framework knows not to re-add those SSIDs automatically to the Saved networks 158 */ 159 private Set<Long> mDeletedSSIDs = new HashSet<Long>(); 160 161 /** 162 * Framework keeps a list of ephemeral SSIDs that where deleted by user, 163 * so as, framework knows not to autojoin again those SSIDs based on scorer input. 164 * The list is never cleared up. 165 * 166 * The SSIDs are encoded in a String as per definition of WifiConfiguration.SSID field. 167 */ 168 public Set<String> mDeletedEphemeralSSIDs = new HashSet<String>(); 169 170 /* Tracks the highest priority of configured networks */ 171 private int mLastPriority = -1; 172 173 private static final String ipConfigFile = Environment.getDataDirectory() + 174 "/misc/wifi/ipconfig.txt"; 175 176 private static final String networkHistoryConfigFile = Environment.getDataDirectory() + 177 "/misc/wifi/networkHistory.txt"; 178 179 private static final String autoJoinConfigFile = Environment.getDataDirectory() + 180 "/misc/wifi/autojoinconfig.txt"; 181 182 /* Network History Keys */ 183 private static final String SSID_KEY = "SSID: "; 184 private static final String CONFIG_KEY = "CONFIG: "; 185 private static final String CHOICE_KEY = "CHOICE: "; 186 private static final String LINK_KEY = "LINK: "; 187 private static final String BSSID_KEY = "BSSID: "; 188 private static final String BSSID_KEY_END = "/BSSID: "; 189 private static final String RSSI_KEY = "RSSI: "; 190 private static final String FREQ_KEY = "FREQ: "; 191 private static final String DATE_KEY = "DATE: "; 192 private static final String MILLI_KEY = "MILLI: "; 193 private static final String BLACKLIST_MILLI_KEY = "BLACKLIST_MILLI: "; 194 private static final String NETWORK_ID_KEY = "ID: "; 195 private static final String PRIORITY_KEY = "PRIORITY: "; 196 private static final String DEFAULT_GW_KEY = "DEFAULT_GW: "; 197 private static final String AUTH_KEY = "AUTH: "; 198 private static final String SEPARATOR_KEY = "\n"; 199 private static final String STATUS_KEY = "AUTO_JOIN_STATUS: "; 200 private static final String BSSID_STATUS_KEY = "BSSID_STATUS: "; 201 private static final String SELF_ADDED_KEY = "SELF_ADDED: "; 202 private static final String FAILURE_KEY = "FAILURE: "; 203 private static final String DID_SELF_ADD_KEY = "DID_SELF_ADD: "; 204 private static final String PEER_CONFIGURATION_KEY = "PEER_CONFIGURATION: "; 205 private static final String CREATOR_UID_KEY = "CREATOR_UID_KEY: "; 206 private static final String CONNECT_UID_KEY = "CONNECT_UID_KEY: "; 207 private static final String UPDATE_UID_KEY = "UPDATE_UID: "; 208 private static final String SUPPLICANT_STATUS_KEY = "SUP_STATUS: "; 209 private static final String SUPPLICANT_DISABLE_REASON_KEY = "SUP_DIS_REASON: "; 210 private static final String FQDN_KEY = "FQDN: "; 211 private static final String NUM_CONNECTION_FAILURES_KEY = "CONNECT_FAILURES: "; 212 private static final String NUM_IP_CONFIG_FAILURES_KEY = "IP_CONFIG_FAILURES: "; 213 private static final String NUM_AUTH_FAILURES_KEY = "AUTH_FAILURES: "; 214 private static final String SCORER_OVERRIDE_KEY = "SCORER_OVERRIDE: "; 215 private static final String SCORER_OVERRIDE_AND_SWITCH_KEY = "SCORER_OVERRIDE_AND_SWITCH: "; 216 private static final String VALIDATED_INTERNET_ACCESS_KEY = "VALIDATED_INTERNET_ACCESS: "; 217 private static final String NO_INTERNET_ACCESS_REPORTS_KEY = "NO_INTERNET_ACCESS_REPORTS : "; 218 private static final String EPHEMERAL_KEY = "EPHEMERAL: "; 219 private static final String NUM_ASSOCIATION_KEY = "NUM_ASSOCIATION: "; 220 private static final String DELETED_CRC32_KEY = "DELETED_CRC32: "; 221 private static final String DELETED_EPHEMERAL_KEY = "DELETED_EPHEMERAL: "; 222 223 private static final String JOIN_ATTEMPT_BOOST_KEY = "JOIN_ATTEMPT_BOOST: "; 224 private static final String THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_5G_KEY 225 = "THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_5G: "; 226 private static final String THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_24G_KEY 227 = "THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_24G: "; 228 private static final String THRESHOLD_UNBLACKLIST_HARD_5G_KEY 229 = "THRESHOLD_UNBLACKLIST_HARD_5G: "; 230 private static final String THRESHOLD_UNBLACKLIST_SOFT_5G_KEY 231 = "THRESHOLD_UNBLACKLIST_SOFT_5G: "; 232 private static final String THRESHOLD_UNBLACKLIST_HARD_24G_KEY 233 = "THRESHOLD_UNBLACKLIST_HARD_24G: "; 234 private static final String THRESHOLD_UNBLACKLIST_SOFT_24G_KEY 235 = "THRESHOLD_UNBLACKLIST_SOFT_24G: "; 236 private static final String THRESHOLD_GOOD_RSSI_5_KEY 237 = "THRESHOLD_GOOD_RSSI_5: "; 238 private static final String THRESHOLD_LOW_RSSI_5_KEY 239 = "THRESHOLD_LOW_RSSI_5: "; 240 private static final String THRESHOLD_BAD_RSSI_5_KEY 241 = "THRESHOLD_BAD_RSSI_5: "; 242 private static final String THRESHOLD_GOOD_RSSI_24_KEY 243 = "THRESHOLD_GOOD_RSSI_24: "; 244 private static final String THRESHOLD_LOW_RSSI_24_KEY 245 = "THRESHOLD_LOW_RSSI_24: "; 246 private static final String THRESHOLD_BAD_RSSI_24_KEY 247 = "THRESHOLD_BAD_RSSI_24: "; 248 249 private static final String THRESHOLD_MAX_TX_PACKETS_FOR_NETWORK_SWITCHING_KEY 250 = "THRESHOLD_MAX_TX_PACKETS_FOR_NETWORK_SWITCHING: "; 251 private static final String THRESHOLD_MAX_RX_PACKETS_FOR_NETWORK_SWITCHING_KEY 252 = "THRESHOLD_MAX_RX_PACKETS_FOR_NETWORK_SWITCHING: "; 253 254 private static final String THRESHOLD_MAX_TX_PACKETS_FOR_FULL_SCANS_KEY 255 = "THRESHOLD_MAX_TX_PACKETS_FOR_FULL_SCANS: "; 256 private static final String THRESHOLD_MAX_RX_PACKETS_FOR_FULL_SCANS_KEY 257 = "THRESHOLD_MAX_RX_PACKETS_FOR_FULL_SCANS: "; 258 259 private static final String THRESHOLD_MAX_TX_PACKETS_FOR_PARTIAL_SCANS_KEY 260 = "THRESHOLD_MAX_TX_PACKETS_FOR_PARTIAL_SCANS: "; 261 private static final String THRESHOLD_MAX_RX_PACKETS_FOR_PARTIAL_SCANS_KEY 262 = "THRESHOLD_MAX_RX_PACKETS_FOR_PARTIAL_SCANS: "; 263 264 private static final String MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY 265 = "MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCANS: "; 266 private static final String MAX_NUM_PASSIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY 267 = "MAX_NUM_PASSIVE_CHANNELS_FOR_PARTIAL_SCANS: "; 268 269 private static final String A_BAND_PREFERENCE_RSSI_THRESHOLD_LOW_KEY = 270 "A_BAND_PREFERENCE_RSSI_THRESHOLD_LOW: "; 271 private static final String A_BAND_PREFERENCE_RSSI_THRESHOLD_KEY = 272 "A_BAND_PREFERENCE_RSSI_THRESHOLD: "; 273 private static final String G_BAND_PREFERENCE_RSSI_THRESHOLD_KEY = 274 "G_BAND_PREFERENCE_RSSI_THRESHOLD: "; 275 276 private static final String ENABLE_AUTOJOIN_WHILE_ASSOCIATED_KEY 277 = "ENABLE_AUTOJOIN_WHILE_ASSOCIATED: "; 278 279 private static final String ASSOCIATED_PARTIAL_SCAN_PERIOD_KEY 280 = "ASSOCIATED_PARTIAL_SCAN_PERIOD: "; 281 private static final String ASSOCIATED_FULL_SCAN_BACKOFF_KEY 282 = "ASSOCIATED_FULL_SCAN_BACKOFF_PERIOD: "; 283 private static final String ALWAYS_ENABLE_SCAN_WHILE_ASSOCIATED_KEY 284 = "ALWAYS_ENABLE_SCAN_WHILE_ASSOCIATED: "; 285 private static final String ONLY_LINK_SAME_CREDENTIAL_CONFIGURATIONS_KEY 286 = "ONLY_LINK_SAME_CREDENTIAL_CONFIGURATIONS: "; 287 288 private static final String ENABLE_FULL_BAND_SCAN_WHEN_ASSOCIATED_KEY 289 = "ENABLE_FULL_BAND_SCAN_WHEN_ASSOCIATED: "; 290 291 // The three below configurations are mainly for power stats and CPU usage tracking 292 // allowing to incrementally disable framework features 293 private static final String ENABLE_AUTO_JOIN_SCAN_WHILE_ASSOCIATED_KEY 294 = "ENABLE_AUTO_JOIN_SCAN_WHILE_ASSOCIATED: "; 295 private static final String ENABLE_AUTO_JOIN_WHILE_ASSOCIATED_KEY 296 = "ENABLE_AUTO_JOIN_WHILE_ASSOCIATED: "; 297 private static final String ENABLE_CHIP_WAKE_UP_WHILE_ASSOCIATED_KEY 298 = "ENABLE_CHIP_WAKE_UP_WHILE_ASSOCIATED: "; 299 private static final String ENABLE_RSSI_POLL_WHILE_ASSOCIATED_KEY 300 = "ENABLE_RSSI_POLL_WHILE_ASSOCIATED_KEY: "; 301 302 // The Wifi verbose log is provided as a way to persist the verbose logging settings 303 // for testing purpose. 304 // It is not intended for normal use. 305 private static final String WIFI_VERBOSE_LOGS_KEY 306 = "WIFI_VERBOSE_LOGS: "; 307 308 // As we keep deleted PSK WifiConfiguration for a while, the PSK of 309 // those deleted WifiConfiguration is set to this random unused PSK 310 private static final String DELETED_CONFIG_PSK = "Mjkd86jEMGn79KhKll298Uu7-deleted"; 311 312 public boolean enableAutoJoinScanWhenAssociated = true; 313 public boolean enableAutoJoinWhenAssociated = true; 314 public boolean enableChipWakeUpWhenAssociated = true; 315 public boolean enableRssiPollWhenAssociated = true; 316 317 public int maxTxPacketForNetworkSwitching = 40; 318 public int maxRxPacketForNetworkSwitching = 80; 319 320 public int maxTxPacketForFullScans = 8; 321 public int maxRxPacketForFullScans = 16; 322 323 public int maxTxPacketForPartialScans = 40; 324 public int maxRxPacketForPartialScans = 80; 325 326 public boolean enableFullBandScanWhenAssociated = true; 327 328 public int thresholdInitialAutoJoinAttemptMin5RSSI 329 = WifiConfiguration.INITIAL_AUTO_JOIN_ATTEMPT_MIN_5; 330 public int thresholdInitialAutoJoinAttemptMin24RSSI 331 = WifiConfiguration.INITIAL_AUTO_JOIN_ATTEMPT_MIN_24; 332 333 public int thresholdBadRssi5 = WifiConfiguration.BAD_RSSI_5; 334 public int thresholdLowRssi5 = WifiConfiguration.LOW_RSSI_5; 335 public int thresholdGoodRssi5 = WifiConfiguration.GOOD_RSSI_5; 336 public int thresholdBadRssi24 = WifiConfiguration.BAD_RSSI_24; 337 public int thresholdLowRssi24 = WifiConfiguration.LOW_RSSI_24; 338 public int thresholdGoodRssi24 = WifiConfiguration.GOOD_RSSI_24; 339 340 public int associatedFullScanBackoff = 12; // Will be divided by 8 by WifiStateMachine 341 public int associatedFullScanMaxIntervalMilli = 300000; 342 343 public int associatedPartialScanPeriodMilli; 344 345 // Sane value for roam blacklisting (not switching to a network if already associated) 346 // 2 days 347 public int networkSwitchingBlackListPeriodMilli = 2 * 24 * 60 * 60 * 1000; 348 349 public int bandPreferenceBoostFactor5 = 5; // Boost by 5 dB per dB above threshold 350 public int bandPreferencePenaltyFactor5 = 2; // Penalize by 2 dB per dB below threshold 351 public int bandPreferencePenaltyThreshold5 = WifiConfiguration.G_BAND_PREFERENCE_RSSI_THRESHOLD; 352 public int bandPreferenceBoostThreshold5 = WifiConfiguration.A_BAND_PREFERENCE_RSSI_THRESHOLD; 353 354 public int badLinkSpeed24 = 6; 355 public int badLinkSpeed5 = 12; 356 public int goodLinkSpeed24 = 24; 357 public int goodLinkSpeed5 = 36; 358 359 public int maxAuthErrorsToBlacklist = 4; 360 public int maxConnectionErrorsToBlacklist = 4; 361 public int wifiConfigBlacklistMinTimeMilli = 1000 * 60 * 5; 362 363 // How long a disconnected config remain considered as the last user selection 364 public int wifiConfigLastSelectionHysteresis = 1000 * 60 * 3; 365 366 // Boost RSSI values of associated networks 367 public int associatedHysteresisHigh = +14; 368 public int associatedHysteresisLow = +8; 369 370 public int thresholdUnblacklistThreshold5Hard 371 = WifiConfiguration.UNBLACKLIST_THRESHOLD_5_HARD; 372 public int thresholdUnblacklistThreshold5Soft 373 = WifiConfiguration.UNBLACKLIST_THRESHOLD_5_SOFT; 374 public int thresholdUnblacklistThreshold24Hard 375 = WifiConfiguration.UNBLACKLIST_THRESHOLD_24_HARD; 376 public int thresholdUnblacklistThreshold24Soft 377 = WifiConfiguration.UNBLACKLIST_THRESHOLD_24_SOFT; 378 public int enableVerboseLogging = 0; 379 boolean showNetworks = true; // TODO set this back to false, used for debugging 17516271 380 381 public int alwaysEnableScansWhileAssociated = 0; 382 383 public int maxNumActiveChannelsForPartialScans = 6; 384 public int maxNumPassiveChannelsForPartialScans = 2; 385 386 public boolean roamOnAny = false; 387 public boolean onlyLinkSameCredentialConfigurations = true; 388 389 public boolean enableLinkDebouncing = true; 390 public boolean enable5GHzPreference = true; 391 public boolean enableWifiCellularHandoverUserTriggeredAdjustment = true; 392 393 public int currentNetworkBoost = 25; 394 public int scanResultRssiLevelPatchUp = -85; 395 396 public static final int maxNumScanCacheEntries = 128; 397 398 /** 399 * Regex pattern for extracting a connect choice. 400 * Matches a strings like the following: 401 * <configKey>=([0:9]+) 402 */ 403 private static Pattern mConnectChoice = 404 Pattern.compile("(.*)=([0-9]+)"); 405 406 407 /* Enterprise configuration keys */ 408 /** 409 * In old configurations, the "private_key" field was used. However, newer 410 * configurations use the key_id field with the engine_id set to "keystore". 411 * If this field is found in the configuration, the migration code is 412 * triggered. 413 */ 414 public static final String OLD_PRIVATE_KEY_NAME = "private_key"; 415 416 /** 417 * This represents an empty value of an enterprise field. 418 * NULL is used at wpa_supplicant to indicate an empty value 419 */ 420 static final String EMPTY_VALUE = "NULL"; 421 422 // Internal use only 423 private static final String[] ENTERPRISE_CONFIG_SUPPLICANT_KEYS = new String[] { 424 WifiEnterpriseConfig.EAP_KEY, WifiEnterpriseConfig.PHASE2_KEY, 425 WifiEnterpriseConfig.IDENTITY_KEY, WifiEnterpriseConfig.ANON_IDENTITY_KEY, 426 WifiEnterpriseConfig.PASSWORD_KEY, WifiEnterpriseConfig.CLIENT_CERT_KEY, 427 WifiEnterpriseConfig.CA_CERT_KEY, WifiEnterpriseConfig.SUBJECT_MATCH_KEY, 428 WifiEnterpriseConfig.ENGINE_KEY, WifiEnterpriseConfig.ENGINE_ID_KEY, 429 WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY }; 430 431 432 /** 433 * If Connectivity Service has triggered an unwanted network disconnect 434 */ 435 public long lastUnwantedNetworkDisconnectTimestamp = 0; 436 437 /** 438 * The maximum number of times we will retry a connection to an access point 439 * for which we have failed in acquiring an IP address from DHCP. A value of 440 * N means that we will make N+1 connection attempts in all. 441 * <p> 442 * See {@link Settings.Secure#WIFI_MAX_DHCP_RETRY_COUNT}. This is the default 443 * value if a Settings value is not present. 444 */ 445 private static final int DEFAULT_MAX_DHCP_RETRIES = 9; 446 447 448 private final LocalLog mLocalLog; 449 private final WpaConfigFileObserver mFileObserver; 450 451 private WifiNative mWifiNative; 452 private final KeyStore mKeyStore = KeyStore.getInstance(); 453 454 /** 455 * The lastSelectedConfiguration is used to remember which network 456 * was selected last by the user. 457 * The connection to this network may not be successful, as well 458 * the selection (i.e. network priority) might not be persisted. 459 * WiFi state machine is the only object that sets this variable. 460 */ 461 private String lastSelectedConfiguration = null; 462 463 WifiConfigStore(Context c, WifiNative wn) { 464 mContext = c; 465 mWifiNative = wn; 466 467 if (showNetworks) { 468 mLocalLog = mWifiNative.getLocalLog(); 469 mFileObserver = new WpaConfigFileObserver(); 470 mFileObserver.startWatching(); 471 } else { 472 mLocalLog = null; 473 mFileObserver = null; 474 } 475 476 associatedPartialScanPeriodMilli = mContext.getResources().getInteger( 477 R.integer.config_wifi_framework_associated_scan_interval); 478 loge("associatedPartialScanPeriodMilli set to " + associatedPartialScanPeriodMilli); 479 480 onlyLinkSameCredentialConfigurations = mContext.getResources().getBoolean( 481 R.bool.config_wifi_only_link_same_credential_configurations); 482 maxNumActiveChannelsForPartialScans = mContext.getResources().getInteger( 483 R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels); 484 maxNumPassiveChannelsForPartialScans = mContext.getResources().getInteger( 485 R.integer.config_wifi_framework_associated_partial_scan_max_num_passive_channels); 486 associatedFullScanMaxIntervalMilli = mContext.getResources().getInteger( 487 R.integer.config_wifi_framework_associated_full_scan_max_interval); 488 associatedFullScanBackoff = mContext.getResources().getInteger( 489 R.integer.config_wifi_framework_associated_full_scan_backoff); 490 enableLinkDebouncing = mContext.getResources().getBoolean( 491 R.bool.config_wifi_enable_disconnection_debounce); 492 493 enable5GHzPreference = mContext.getResources().getBoolean( 494 R.bool.config_wifi_enable_5GHz_preference); 495 496 bandPreferenceBoostFactor5 = mContext.getResources().getInteger( 497 R.integer.config_wifi_framework_5GHz_preference_boost_factor); 498 bandPreferencePenaltyFactor5 = mContext.getResources().getInteger( 499 R.integer.config_wifi_framework_5GHz_preference_penalty_factor); 500 501 bandPreferencePenaltyThreshold5 = mContext.getResources().getInteger( 502 R.integer.config_wifi_framework_5GHz_preference_penalty_threshold); 503 bandPreferenceBoostThreshold5 = mContext.getResources().getInteger( 504 R.integer.config_wifi_framework_5GHz_preference_boost_threshold); 505 506 associatedHysteresisHigh = mContext.getResources().getInteger( 507 R.integer.config_wifi_framework_current_association_hysteresis_high); 508 associatedHysteresisLow = mContext.getResources().getInteger( 509 R.integer.config_wifi_framework_current_association_hysteresis_low); 510 511 thresholdBadRssi5 = mContext.getResources().getInteger( 512 R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_5GHz); 513 thresholdLowRssi5 = mContext.getResources().getInteger( 514 R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_5GHz); 515 thresholdGoodRssi5 = mContext.getResources().getInteger( 516 R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_5GHz); 517 thresholdBadRssi24 = mContext.getResources().getInteger( 518 R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_24GHz); 519 thresholdLowRssi24 = mContext.getResources().getInteger( 520 R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_24GHz); 521 thresholdGoodRssi24 = mContext.getResources().getInteger( 522 R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_24GHz); 523 524 enableWifiCellularHandoverUserTriggeredAdjustment = mContext.getResources().getBoolean( 525 R.bool.config_wifi_framework_cellular_handover_enable_user_triggered_adjustment); 526 527 badLinkSpeed24 = mContext.getResources().getInteger( 528 R.integer.config_wifi_framework_wifi_score_bad_link_speed_24); 529 badLinkSpeed5 = mContext.getResources().getInteger( 530 R.integer.config_wifi_framework_wifi_score_bad_link_speed_5); 531 goodLinkSpeed24 = mContext.getResources().getInteger( 532 R.integer.config_wifi_framework_wifi_score_good_link_speed_24); 533 goodLinkSpeed5 = mContext.getResources().getInteger( 534 R.integer.config_wifi_framework_wifi_score_good_link_speed_5); 535 536 maxAuthErrorsToBlacklist = mContext.getResources().getInteger( 537 R.integer.config_wifi_framework_max_auth_errors_to_blacklist); 538 maxConnectionErrorsToBlacklist = mContext.getResources().getInteger( 539 R.integer.config_wifi_framework_max_connection_errors_to_blacklist); 540 wifiConfigBlacklistMinTimeMilli = mContext.getResources().getInteger( 541 R.integer.config_wifi_framework_network_black_list_min_time_milli); 542 543 544 enableAutoJoinScanWhenAssociated = mContext.getResources().getBoolean( 545 R.bool.config_wifi_framework_enable_associated_autojoin_scan); 546 547 enableAutoJoinWhenAssociated = mContext.getResources().getBoolean( 548 R.bool.config_wifi_framework_enable_associated_network_selection); 549 550 currentNetworkBoost = mContext.getResources().getInteger( 551 R.integer.config_wifi_framework_current_network_boost); 552 553 scanResultRssiLevelPatchUp = mContext.getResources().getInteger( 554 R.integer.config_wifi_framework_scan_result_rssi_level_patchup_value); 555 556 networkSwitchingBlackListPeriodMilli = mContext.getResources().getInteger( 557 R.integer.config_wifi_network_switching_blacklist_time); 558 } 559 560 void enableVerboseLogging(int verbose) { 561 enableVerboseLogging = verbose; 562 if (verbose > 0) { 563 VDBG = true; 564 showNetworks = true; 565 } else { 566 VDBG = false; 567 } 568 if (verbose > 1) { 569 VVDBG = true; 570 } else { 571 VVDBG = false; 572 } 573 } 574 575 class WpaConfigFileObserver extends FileObserver { 576 577 public WpaConfigFileObserver() { 578 super(SUPPLICANT_CONFIG_FILE, CLOSE_WRITE); 579 } 580 581 @Override 582 public void onEvent(int event, String path) { 583 if (event == CLOSE_WRITE) { 584 File file = new File(SUPPLICANT_CONFIG_FILE); 585 if (VDBG) localLog("wpa_supplicant.conf changed; new size = " + file.length()); 586 } 587 } 588 } 589 590 591 /** 592 * Fetch the list of configured networks 593 * and enable all stored networks in supplicant. 594 */ 595 void loadAndEnableAllNetworks() { 596 if (DBG) log("Loading config and enabling all networks "); 597 loadConfiguredNetworks(); 598 enableAllNetworks(); 599 } 600 601 int getConfiguredNetworksSize() { 602 return mConfiguredNetworks.size(); 603 } 604 605 private List<WifiConfiguration> getConfiguredNetworks(Map<String, String> pskMap) { 606 List<WifiConfiguration> networks = new ArrayList<>(); 607 for(WifiConfiguration config : mConfiguredNetworks.values()) { 608 WifiConfiguration newConfig = new WifiConfiguration(config); 609 // When updating this condition, update WifiStateMachine's CONNECT_NETWORK handler to 610 // correctly handle updating existing configs that are filtered out here. 611 if (config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED || config.ephemeral) { 612 // Do not enumerate and return this configuration to any one, 613 // for instance WiFi Picker. 614 // instead treat it as unknown. the configuration can still be retrieved 615 // directly by the key or networkId 616 continue; 617 } 618 619 if (pskMap != null && config.allowedKeyManagement != null 620 && config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK) 621 && pskMap.containsKey(config.SSID)) { 622 newConfig.preSharedKey = pskMap.get(config.SSID); 623 } 624 networks.add(newConfig); 625 } 626 return networks; 627 } 628 629 /** 630 * Fetch the list of currently configured networks 631 * @return List of networks 632 */ 633 List<WifiConfiguration> getConfiguredNetworks() { 634 return getConfiguredNetworks(null); 635 } 636 637 /** 638 * Fetch the list of currently configured networks, filled with real preSharedKeys 639 * @return List of networks 640 */ 641 List<WifiConfiguration> getPrivilegedConfiguredNetworks() { 642 Map<String, String> pskMap = getCredentialsBySsidMap(); 643 return getConfiguredNetworks(pskMap); 644 } 645 646 /** 647 * Fetch the preSharedKeys for all networks. 648 * @return a map from Ssid to preSharedKey. 649 */ 650 private Map<String, String> getCredentialsBySsidMap() { 651 return readNetworkVariablesFromSupplicantFile("psk"); 652 } 653 654 int getconfiguredNetworkSize() { 655 if (mConfiguredNetworks == null) 656 return 0; 657 return mConfiguredNetworks.size(); 658 } 659 660 /** 661 * Fetch the list of currently configured networks that were recently seen 662 * 663 * @return List of networks 664 */ 665 List<WifiConfiguration> getRecentConfiguredNetworks(int milli, boolean copy) { 666 List<WifiConfiguration> networks = new ArrayList<WifiConfiguration>(); 667 668 for (WifiConfiguration config : mConfiguredNetworks.values()) { 669 if (config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED || config.ephemeral) { 670 // Do not enumerate and return this configuration to any one, 671 // instead treat it as unknown. the configuration can still be retrieved 672 // directly by the key or networkId 673 continue; 674 } 675 676 // Calculate the RSSI for scan results that are more recent than milli 677 config.setVisibility(milli); 678 if (config.visibility == null) { 679 continue; 680 } 681 if (config.visibility.rssi5 == WifiConfiguration.INVALID_RSSI && 682 config.visibility.rssi24 == WifiConfiguration.INVALID_RSSI) { 683 continue; 684 } 685 if (copy) { 686 networks.add(new WifiConfiguration(config)); 687 } else { 688 networks.add(config); 689 } 690 } 691 return networks; 692 } 693 694 /** 695 * Update the configuration and BSSID with latest RSSI value. 696 */ 697 void updateConfiguration(WifiInfo info) { 698 WifiConfiguration config = getWifiConfiguration(info.getNetworkId()); 699 if (config != null && config.scanResultCache != null) { 700 ScanResult result = config.scanResultCache.get(info.getBSSID()); 701 if (result != null) { 702 long previousSeen = result.seen; 703 int previousRssi = result.level; 704 705 // Update the scan result 706 result.seen = System.currentTimeMillis(); 707 result.level = info.getRssi(); 708 709 // Average the RSSI value 710 result.averageRssi(previousRssi, previousSeen, 711 WifiAutoJoinController.mScanResultMaximumAge); 712 if (VDBG) { 713 loge("updateConfiguration freq=" + result.frequency 714 + " BSSID=" + result.BSSID 715 + " RSSI=" + result.level 716 + " " + config.configKey()); 717 } 718 } 719 } 720 } 721 722 /** 723 * get the Wificonfiguration for this netId 724 * 725 * @return Wificonfiguration 726 */ 727 WifiConfiguration getWifiConfiguration(int netId) { 728 if (mConfiguredNetworks == null) 729 return null; 730 return mConfiguredNetworks.get(netId); 731 } 732 733 /** 734 * Get the Wificonfiguration for this key 735 * @return Wificonfiguration 736 */ 737 WifiConfiguration getWifiConfiguration(String key) { 738 if (key == null) 739 return null; 740 int hash = key.hashCode(); 741 if (mNetworkIds == null) 742 return null; 743 Integer n = mNetworkIds.get(hash); 744 if (n == null) 745 return null; 746 int netId = n.intValue(); 747 return getWifiConfiguration(netId); 748 } 749 750 /** 751 * Enable all networks and save config. This will be a no-op if the list 752 * of configured networks indicates all networks as being enabled 753 */ 754 void enableAllNetworks() { 755 long now = System.currentTimeMillis(); 756 boolean networkEnabledStateChanged = false; 757 758 for(WifiConfiguration config : mConfiguredNetworks.values()) { 759 760 if(config != null && config.status == Status.DISABLED && !config.ephemeral 761 && (config.autoJoinStatus 762 <= WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE)) { 763 764 // Wait for 5 minutes before reenabling config that have known, repeated connection 765 // or DHCP failures 766 if (config.disableReason == WifiConfiguration.DISABLED_DHCP_FAILURE 767 || config.disableReason == WifiConfiguration.DISABLED_ASSOCIATION_REJECT 768 || config.disableReason == WifiConfiguration.DISABLED_AUTH_FAILURE) { 769 if (config.blackListTimestamp != 0 770 && now > config.blackListTimestamp 771 && (now - config.blackListTimestamp) < wifiConfigBlacklistMinTimeMilli) { 772 continue; 773 } 774 } 775 776 if(mWifiNative.enableNetwork(config.networkId, false)) { 777 networkEnabledStateChanged = true; 778 config.status = Status.ENABLED; 779 780 // Reset the blacklist condition 781 config.numConnectionFailures = 0; 782 config.numIpConfigFailures = 0; 783 config.numAuthFailures = 0; 784 785 // Reenable the wifi configuration 786 config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED); 787 } else { 788 loge("Enable network failed on " + config.networkId); 789 } 790 } 791 } 792 793 if (networkEnabledStateChanged) { 794 mWifiNative.saveConfig(); 795 sendConfiguredNetworksChangedBroadcast(); 796 } 797 } 798 799 800 /** 801 * Selects the specified network for connection. This involves 802 * updating the priority of all the networks and enabling the given 803 * network while disabling others. 804 * 805 * Selecting a network will leave the other networks disabled and 806 * a call to enableAllNetworks() needs to be issued upon a connection 807 * or a failure event from supplicant 808 * 809 * @param netId network to select for connection 810 * @return false if the network id is invalid 811 */ 812 boolean selectNetwork(int netId) { 813 if (VDBG) localLog("selectNetwork", netId); 814 if (netId == INVALID_NETWORK_ID) return false; 815 816 // Reset the priority of each network at start or if it goes too high. 817 if (mLastPriority == -1 || mLastPriority > 1000000) { 818 for(WifiConfiguration config : mConfiguredNetworks.values()) { 819 if (config.networkId != INVALID_NETWORK_ID) { 820 config.priority = 0; 821 addOrUpdateNetworkNative(config, -1); 822 } 823 } 824 mLastPriority = 0; 825 } 826 827 // Set to the highest priority and save the configuration. 828 WifiConfiguration config = new WifiConfiguration(); 829 config.networkId = netId; 830 config.priority = ++mLastPriority; 831 832 addOrUpdateNetworkNative(config, -1); 833 mWifiNative.saveConfig(); 834 835 /* Enable the given network while disabling all other networks */ 836 enableNetworkWithoutBroadcast(netId, true); 837 838 /* Avoid saving the config & sending a broadcast to prevent settings 839 * from displaying a disabled list of networks */ 840 return true; 841 } 842 843 /** 844 * Add/update the specified configuration and save config 845 * 846 * @param config WifiConfiguration to be saved 847 * @return network update result 848 */ 849 NetworkUpdateResult saveNetwork(WifiConfiguration config, int uid) { 850 WifiConfiguration conf; 851 852 // A new network cannot have null SSID 853 if (config == null || (config.networkId == INVALID_NETWORK_ID && 854 config.SSID == null)) { 855 return new NetworkUpdateResult(INVALID_NETWORK_ID); 856 } 857 if (VDBG) localLog("WifiConfigStore: saveNetwork netId", config.networkId); 858 if (VDBG) { 859 loge("WifiConfigStore saveNetwork, size=" + mConfiguredNetworks.size() 860 + " SSID=" + config.SSID 861 + " Uid=" + Integer.toString(config.creatorUid) 862 + "/" + Integer.toString(config.lastUpdateUid)); 863 } 864 865 if (mDeletedEphemeralSSIDs.remove(config.SSID)) { 866 if (VDBG) { 867 loge("WifiConfigStore: removed from ephemeral blacklist: " + config.SSID); 868 } 869 // NOTE: This will be flushed to disk as part of the addOrUpdateNetworkNative call 870 // below, since we're creating/modifying a config. 871 } 872 873 boolean newNetwork = (config.networkId == INVALID_NETWORK_ID); 874 NetworkUpdateResult result = addOrUpdateNetworkNative(config, uid); 875 int netId = result.getNetworkId(); 876 877 if (VDBG) localLog("WifiConfigStore: saveNetwork got it back netId=", netId); 878 879 /* enable a new network */ 880 if (newNetwork && netId != INVALID_NETWORK_ID) { 881 if (VDBG) localLog("WifiConfigStore: will enable netId=", netId); 882 883 mWifiNative.enableNetwork(netId, false); 884 conf = mConfiguredNetworks.get(netId); 885 if (conf != null) 886 conf.status = Status.ENABLED; 887 } 888 889 conf = mConfiguredNetworks.get(netId); 890 if (conf != null) { 891 if (conf.autoJoinStatus != WifiConfiguration.AUTO_JOIN_ENABLED) { 892 if (VDBG) localLog("WifiConfigStore: re-enabling: " + conf.SSID); 893 894 // reenable autojoin, since new information has been provided 895 conf.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED); 896 enableNetworkWithoutBroadcast(conf.networkId, false); 897 } 898 if (VDBG) { 899 loge("WifiConfigStore: saveNetwork got config back netId=" 900 + Integer.toString(netId) 901 + " uid=" + Integer.toString(config.creatorUid)); 902 } 903 } 904 905 mWifiNative.saveConfig(); 906 sendConfiguredNetworksChangedBroadcast(conf, result.isNewNetwork() ? 907 WifiManager.CHANGE_REASON_ADDED : WifiManager.CHANGE_REASON_CONFIG_CHANGE); 908 return result; 909 } 910 911 /** 912 * Firmware is roaming away from this BSSID, and this BSSID was on 5GHz, and it's RSSI was good, 913 * this means we have a situation where we would want to remain on this BSSID but firmware 914 * is not successful at it. 915 * This situation is observed on a small number of Access Points, b/17960587 916 * In that situation, blacklist this BSSID really hard so as framework will not attempt to 917 * roam to it for the next 8 hours. We do not to keep flipping between 2.4 and 5GHz band.. 918 * TODO: review the blacklisting strategy so as to make it softer and adaptive 919 * @param info 920 */ 921 void driverRoamedFrom(WifiInfo info) { 922 if (info != null 923 && info.getBSSID() != null 924 && ScanResult.is5GHz(info.getFrequency()) 925 && info.getRssi() > (bandPreferenceBoostThreshold5 + 3)) { 926 WifiConfiguration config = getWifiConfiguration(info.getNetworkId()); 927 if (config != null) { 928 if (config.scanResultCache != null) { 929 ScanResult result = config.scanResultCache.get(info.getBSSID()); 930 if (result != null) { 931 result.setAutoJoinStatus(ScanResult.AUTO_ROAM_DISABLED + 1); 932 } 933 } 934 } 935 } 936 } 937 938 void noteRoamingFailure(WifiConfiguration config, int reason) { 939 if (config == null) return; 940 config.lastRoamingFailure = System.currentTimeMillis(); 941 config.roamingFailureBlackListTimeMilli 942 = 2 * (config.roamingFailureBlackListTimeMilli + 1000); 943 if (config.roamingFailureBlackListTimeMilli 944 > networkSwitchingBlackListPeriodMilli) { 945 config.roamingFailureBlackListTimeMilli = 946 networkSwitchingBlackListPeriodMilli; 947 } 948 config.lastRoamingFailureReason = reason; 949 } 950 951 void saveWifiConfigBSSID(WifiConfiguration config) { 952 // Sanity check the config is valid 953 if (config == null || (config.networkId == INVALID_NETWORK_ID && 954 config.SSID == null)) { 955 return; 956 } 957 958 // If an app specified a BSSID then dont over-write it 959 if (config.BSSID != null && config.BSSID != "any") { 960 return; 961 } 962 963 // If autojoin specified a BSSID then write it in the network block 964 if (config.autoJoinBSSID != null) { 965 loge("saveWifiConfigBSSID Setting BSSID for " + config.configKey() 966 + " to " + config.autoJoinBSSID); 967 if (!mWifiNative.setNetworkVariable( 968 config.networkId, 969 WifiConfiguration.bssidVarName, 970 config.autoJoinBSSID)) { 971 loge("failed to set BSSID: " + config.autoJoinBSSID); 972 } else if (config.autoJoinBSSID.equals("any")) { 973 // Paranoia, we just want to make sure that we restore the config to normal 974 mWifiNative.saveConfig(); 975 } 976 } 977 } 978 979 980 void updateStatus(int netId, DetailedState state) { 981 if (netId != INVALID_NETWORK_ID) { 982 WifiConfiguration config = mConfiguredNetworks.get(netId); 983 if (config == null) return; 984 switch (state) { 985 case CONNECTED: 986 config.status = Status.CURRENT; 987 //we successfully connected, hence remove the blacklist 988 config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED); 989 break; 990 case DISCONNECTED: 991 //If network is already disabled, keep the status 992 if (config.status == Status.CURRENT) { 993 config.status = Status.ENABLED; 994 } 995 break; 996 default: 997 //do nothing, retain the existing state 998 break; 999 } 1000 } 1001 } 1002 1003 1004 /** 1005 * Disable an ephemeral SSID for the purpose of auto-joining thru scored. 1006 * This SSID will never be scored anymore. 1007 * The only way to "un-disable it" is if the user create a network for that SSID and then 1008 * forget it. 1009 * 1010 * @param SSID caller must ensure that the SSID passed thru this API match 1011 * the WifiConfiguration.SSID rules, and thus be surrounded by quotes. 1012 * @return the {@link WifiConfiguration} corresponding to this SSID, if any, so that we can 1013 * disconnect if this is the current network. 1014 */ 1015 WifiConfiguration disableEphemeralNetwork(String SSID) { 1016 if (SSID == null) { 1017 return null; 1018 } 1019 1020 WifiConfiguration foundConfig = null; 1021 1022 mDeletedEphemeralSSIDs.add(SSID); 1023 loge("Forget ephemeral SSID " + SSID + " num=" + mDeletedEphemeralSSIDs.size()); 1024 1025 for (WifiConfiguration config : mConfiguredNetworks.values()) { 1026 if (SSID.equals(config.SSID) && config.ephemeral) { 1027 loge("Found ephemeral config in disableEphemeralNetwork: " + config.networkId); 1028 foundConfig = config; 1029 } 1030 } 1031 1032 // Force a write, because the mDeletedEphemeralSSIDs list has changed even though the 1033 // configurations may not have. 1034 writeKnownNetworkHistory(true); 1035 1036 return foundConfig; 1037 } 1038 1039 /** 1040 * Forget the specified network and save config 1041 * 1042 * @param netId network to forget 1043 * @return {@code true} if it succeeds, {@code false} otherwise 1044 */ 1045 boolean forgetNetwork(int netId) { 1046 if (showNetworks) localLog("forgetNetwork", netId); 1047 1048 boolean remove = removeConfigAndSendBroadcastIfNeeded(netId); 1049 if (!remove) { 1050 //success but we dont want to remove the network from supplicant conf file 1051 return true; 1052 } 1053 if (mWifiNative.removeNetwork(netId)) { 1054 mWifiNative.saveConfig(); 1055 return true; 1056 } else { 1057 loge("Failed to remove network " + netId); 1058 return false; 1059 } 1060 } 1061 1062 /** 1063 * Add/update a network. Note that there is no saveConfig operation. 1064 * This function is retained for compatibility with the public 1065 * API. The more powerful saveNetwork() is used by the 1066 * state machine 1067 * 1068 * @param config wifi configuration to add/update 1069 * @return network Id 1070 */ 1071 int addOrUpdateNetwork(WifiConfiguration config, int uid) { 1072 if (showNetworks) localLog("addOrUpdateNetwork id=", config.networkId); 1073 //adding unconditional message to chase b/15111865 1074 Log.e(TAG, " key=" + config.configKey() + " netId=" + Integer.toString(config.networkId) 1075 + " uid=" + Integer.toString(config.creatorUid) 1076 + "/" + Integer.toString(config.lastUpdateUid)); 1077 NetworkUpdateResult result = addOrUpdateNetworkNative(config, uid); 1078 if (result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID) { 1079 WifiConfiguration conf = mConfiguredNetworks.get(result.getNetworkId()); 1080 if (conf != null) { 1081 sendConfiguredNetworksChangedBroadcast(conf, 1082 result.isNewNetwork ? WifiManager.CHANGE_REASON_ADDED : 1083 WifiManager.CHANGE_REASON_CONFIG_CHANGE); 1084 } 1085 } 1086 return result.getNetworkId(); 1087 } 1088 1089 /** 1090 * Remove a network. Note that there is no saveConfig operation. 1091 * This function is retained for compatibility with the public 1092 * API. The more powerful forgetNetwork() is used by the 1093 * state machine for network removal 1094 * 1095 * @param netId network to be removed 1096 * @return {@code true} if it succeeds, {@code false} otherwise 1097 */ 1098 boolean removeNetwork(int netId) { 1099 if (showNetworks) localLog("removeNetwork", netId); 1100 boolean ret = mWifiNative.removeNetwork(netId); 1101 if (ret) { 1102 removeConfigAndSendBroadcastIfNeeded(netId); 1103 } 1104 return ret; 1105 } 1106 1107 private boolean removeConfigAndSendBroadcastIfNeeded(int netId) { 1108 WifiConfiguration config = mConfiguredNetworks.get(netId); 1109 if (config != null) { 1110 if (VDBG) { 1111 loge("removeNetwork " + Integer.toString(netId) + " key=" + 1112 config.configKey() + " config.id=" + Integer.toString(config.networkId)); 1113 } 1114 1115 // cancel the last user choice 1116 if (config.configKey().equals(lastSelectedConfiguration)) { 1117 lastSelectedConfiguration = null; 1118 } 1119 1120 // Remove any associated keys 1121 if (config.enterpriseConfig != null) { 1122 removeKeys(config.enterpriseConfig); 1123 } 1124 1125 if (config.selfAdded || config.linkedConfigurations != null 1126 || config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 1127 if (!TextUtils.isEmpty(config.SSID)) { 1128 /* Remember that we deleted this PSK SSID */ 1129 Checksum csum = new CRC32(); 1130 if (config.SSID != null) { 1131 csum.update(config.SSID.getBytes(), 0, config.SSID.getBytes().length); 1132 mDeletedSSIDs.add(csum.getValue()); 1133 } 1134 loge("removeNetwork " + Integer.toString(netId) 1135 + " key=" + config.configKey() 1136 + " config.id=" + Integer.toString(config.networkId) 1137 + " crc=" + csum.getValue()); 1138 } 1139 } 1140 1141 mConfiguredNetworks.remove(netId); 1142 mNetworkIds.remove(configKey(config)); 1143 1144 writeIpAndProxyConfigurations(); 1145 sendConfiguredNetworksChangedBroadcast(config, WifiManager.CHANGE_REASON_REMOVED); 1146 writeKnownNetworkHistory(true); 1147 } 1148 return true; 1149 } 1150 1151 /** 1152 * Enable a network. Note that there is no saveConfig operation. 1153 * This function is retained for compatibility with the public 1154 * API. The more powerful selectNetwork()/saveNetwork() is used by the 1155 * state machine for connecting to a network 1156 * 1157 * @param netId network to be enabled 1158 * @return {@code true} if it succeeds, {@code false} otherwise 1159 */ 1160 boolean enableNetwork(int netId, boolean disableOthers) { 1161 boolean ret = enableNetworkWithoutBroadcast(netId, disableOthers); 1162 if (disableOthers) { 1163 if (VDBG) localLog("enableNetwork(disableOthers=true) ", netId); 1164 sendConfiguredNetworksChangedBroadcast(); 1165 } else { 1166 if (VDBG) localLog("enableNetwork(disableOthers=false) ", netId); 1167 WifiConfiguration enabledNetwork = null; 1168 synchronized(mConfiguredNetworks) { 1169 enabledNetwork = mConfiguredNetworks.get(netId); 1170 } 1171 // check just in case the network was removed by someone else. 1172 if (enabledNetwork != null) { 1173 sendConfiguredNetworksChangedBroadcast(enabledNetwork, 1174 WifiManager.CHANGE_REASON_CONFIG_CHANGE); 1175 } 1176 } 1177 return ret; 1178 } 1179 1180 boolean enableNetworkWithoutBroadcast(int netId, boolean disableOthers) { 1181 boolean ret = mWifiNative.enableNetwork(netId, disableOthers); 1182 1183 WifiConfiguration config = mConfiguredNetworks.get(netId); 1184 if (config != null) config.status = Status.ENABLED; 1185 1186 if (disableOthers) { 1187 markAllNetworksDisabledExcept(netId); 1188 } 1189 return ret; 1190 } 1191 1192 void disableAllNetworks() { 1193 if (VDBG) localLog("disableAllNetworks"); 1194 boolean networkDisabled = false; 1195 for(WifiConfiguration config : mConfiguredNetworks.values()) { 1196 if(config != null && config.status != Status.DISABLED) { 1197 if(mWifiNative.disableNetwork(config.networkId)) { 1198 networkDisabled = true; 1199 config.status = Status.DISABLED; 1200 } else { 1201 loge("Disable network failed on " + config.networkId); 1202 } 1203 } 1204 } 1205 1206 if (networkDisabled) { 1207 sendConfiguredNetworksChangedBroadcast(); 1208 } 1209 } 1210 /** 1211 * Disable a network. Note that there is no saveConfig operation. 1212 * @param netId network to be disabled 1213 * @return {@code true} if it succeeds, {@code false} otherwise 1214 */ 1215 boolean disableNetwork(int netId) { 1216 return disableNetwork(netId, WifiConfiguration.DISABLED_UNKNOWN_REASON); 1217 } 1218 1219 /** 1220 * Disable a network. Note that there is no saveConfig operation. 1221 * @param netId network to be disabled 1222 * @param reason reason code network was disabled 1223 * @return {@code true} if it succeeds, {@code false} otherwise 1224 */ 1225 boolean disableNetwork(int netId, int reason) { 1226 if (VDBG) localLog("disableNetwork", netId); 1227 boolean ret = mWifiNative.disableNetwork(netId); 1228 WifiConfiguration network = null; 1229 WifiConfiguration config = mConfiguredNetworks.get(netId); 1230 1231 if (VDBG) { 1232 if (config != null) { 1233 loge("disableNetwork netId=" + Integer.toString(netId) 1234 + " SSID=" + config.SSID 1235 + " disabled=" + (config.status == Status.DISABLED) 1236 + " reason=" + Integer.toString(config.disableReason)); 1237 } 1238 } 1239 /* Only change the reason if the network was not previously disabled 1240 /* and the reason is not DISABLED_BY_WIFI_MANAGER, that is, if a 3rd party 1241 * set its configuration as disabled, then leave it disabled */ 1242 if (config != null) { 1243 if (config.status != Status.DISABLED 1244 && config.disableReason != WifiConfiguration.DISABLED_BY_WIFI_MANAGER) { 1245 config.status = Status.DISABLED; 1246 config.disableReason = reason; 1247 network = config; 1248 } 1249 if (reason == WifiConfiguration.DISABLED_BY_WIFI_MANAGER) { 1250 // Make sure autojoin wont reenable this configuration without further user 1251 // intervention 1252 config.status = Status.DISABLED; 1253 config.autoJoinStatus = WifiConfiguration.AUTO_JOIN_DISABLED_USER_ACTION; 1254 } 1255 } 1256 if (network != null) { 1257 sendConfiguredNetworksChangedBroadcast(network, 1258 WifiManager.CHANGE_REASON_CONFIG_CHANGE); 1259 } 1260 return ret; 1261 } 1262 1263 /** 1264 * Save the configured networks in supplicant to disk 1265 * @return {@code true} if it succeeds, {@code false} otherwise 1266 */ 1267 boolean saveConfig() { 1268 return mWifiNative.saveConfig(); 1269 } 1270 1271 /** 1272 * Start WPS pin method configuration with pin obtained 1273 * from the access point 1274 * @param config WPS configuration 1275 * @return Wps result containing status and pin 1276 */ 1277 WpsResult startWpsWithPinFromAccessPoint(WpsInfo config) { 1278 WpsResult result = new WpsResult(); 1279 if (mWifiNative.startWpsRegistrar(config.BSSID, config.pin)) { 1280 /* WPS leaves all networks disabled */ 1281 markAllNetworksDisabled(); 1282 result.status = WpsResult.Status.SUCCESS; 1283 } else { 1284 loge("Failed to start WPS pin method configuration"); 1285 result.status = WpsResult.Status.FAILURE; 1286 } 1287 return result; 1288 } 1289 1290 /** 1291 * Start WPS pin method configuration with pin obtained 1292 * from the device 1293 * @return WpsResult indicating status and pin 1294 */ 1295 WpsResult startWpsWithPinFromDevice(WpsInfo config) { 1296 WpsResult result = new WpsResult(); 1297 result.pin = mWifiNative.startWpsPinDisplay(config.BSSID); 1298 /* WPS leaves all networks disabled */ 1299 if (!TextUtils.isEmpty(result.pin)) { 1300 markAllNetworksDisabled(); 1301 result.status = WpsResult.Status.SUCCESS; 1302 } else { 1303 loge("Failed to start WPS pin method configuration"); 1304 result.status = WpsResult.Status.FAILURE; 1305 } 1306 return result; 1307 } 1308 1309 /** 1310 * Start WPS push button configuration 1311 * @param config WPS configuration 1312 * @return WpsResult indicating status and pin 1313 */ 1314 WpsResult startWpsPbc(WpsInfo config) { 1315 WpsResult result = new WpsResult(); 1316 if (mWifiNative.startWpsPbc(config.BSSID)) { 1317 /* WPS leaves all networks disabled */ 1318 markAllNetworksDisabled(); 1319 result.status = WpsResult.Status.SUCCESS; 1320 } else { 1321 loge("Failed to start WPS push button configuration"); 1322 result.status = WpsResult.Status.FAILURE; 1323 } 1324 return result; 1325 } 1326 1327 /** 1328 * Fetch the static IP configuration for a given network id 1329 */ 1330 StaticIpConfiguration getStaticIpConfiguration(int netId) { 1331 WifiConfiguration config = mConfiguredNetworks.get(netId); 1332 if (config != null) { 1333 return config.getStaticIpConfiguration(); 1334 } 1335 return null; 1336 } 1337 1338 /** 1339 * Set the static IP configuration for a given network id 1340 */ 1341 void setStaticIpConfiguration(int netId, StaticIpConfiguration staticIpConfiguration) { 1342 WifiConfiguration config = mConfiguredNetworks.get(netId); 1343 if (config != null) { 1344 config.setStaticIpConfiguration(staticIpConfiguration); 1345 } 1346 } 1347 1348 /** 1349 * set default GW MAC address 1350 */ 1351 void setDefaultGwMacAddress(int netId, String macAddress) { 1352 WifiConfiguration config = mConfiguredNetworks.get(netId); 1353 if (config != null) { 1354 //update defaultGwMacAddress 1355 config.defaultGwMacAddress = macAddress; 1356 } 1357 } 1358 1359 1360 /** 1361 * Fetch the proxy properties for a given network id 1362 * @param network id 1363 * @return ProxyInfo for the network id 1364 */ 1365 ProxyInfo getProxyProperties(int netId) { 1366 WifiConfiguration config = mConfiguredNetworks.get(netId); 1367 if (config != null) { 1368 return config.getHttpProxy(); 1369 } 1370 return null; 1371 } 1372 1373 /** 1374 * Return if the specified network is using static IP 1375 * @param network id 1376 * @return {@code true} if using static ip for netId 1377 */ 1378 boolean isUsingStaticIp(int netId) { 1379 WifiConfiguration config = mConfiguredNetworks.get(netId); 1380 if (config != null && config.getIpAssignment() == IpAssignment.STATIC) { 1381 return true; 1382 } 1383 return false; 1384 } 1385 1386 /** 1387 * Should be called when a single network configuration is made. 1388 * @param network The network configuration that changed. 1389 * @param reason The reason for the change, should be one of WifiManager.CHANGE_REASON_ADDED, 1390 * WifiManager.CHANGE_REASON_REMOVED, or WifiManager.CHANGE_REASON_CHANGE. 1391 */ 1392 private void sendConfiguredNetworksChangedBroadcast(WifiConfiguration network, 1393 int reason) { 1394 Intent intent = new Intent(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION); 1395 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1396 intent.putExtra(WifiManager.EXTRA_MULTIPLE_NETWORKS_CHANGED, false); 1397 intent.putExtra(WifiManager.EXTRA_WIFI_CONFIGURATION, network); 1398 intent.putExtra(WifiManager.EXTRA_CHANGE_REASON, reason); 1399 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 1400 } 1401 1402 /** 1403 * Should be called when multiple network configuration changes are made. 1404 */ 1405 private void sendConfiguredNetworksChangedBroadcast() { 1406 Intent intent = new Intent(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION); 1407 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1408 intent.putExtra(WifiManager.EXTRA_MULTIPLE_NETWORKS_CHANGED, true); 1409 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 1410 } 1411 1412 void loadConfiguredNetworks() { 1413 1414 mLastPriority = 0; 1415 1416 mConfiguredNetworks.clear(); 1417 mNetworkIds.clear(); 1418 1419 int last_id = -1; 1420 boolean done = false; 1421 while (!done) { 1422 1423 String listStr = mWifiNative.listNetworks(last_id); 1424 if (listStr == null) 1425 return; 1426 1427 String[] lines = listStr.split("\n"); 1428 1429 if (showNetworks) { 1430 localLog("WifiConfigStore: loadConfiguredNetworks: "); 1431 for (String net : lines) { 1432 localLog(net); 1433 } 1434 } 1435 1436 // Skip the first line, which is a header 1437 for (int i = 1; i < lines.length; i++) { 1438 String[] result = lines[i].split("\t"); 1439 // network-id | ssid | bssid | flags 1440 WifiConfiguration config = new WifiConfiguration(); 1441 try { 1442 config.networkId = Integer.parseInt(result[0]); 1443 last_id = config.networkId; 1444 } catch(NumberFormatException e) { 1445 loge("Failed to read network-id '" + result[0] + "'"); 1446 continue; 1447 } 1448 if (result.length > 3) { 1449 if (result[3].indexOf("[CURRENT]") != -1) 1450 config.status = WifiConfiguration.Status.CURRENT; 1451 else if (result[3].indexOf("[DISABLED]") != -1) 1452 config.status = WifiConfiguration.Status.DISABLED; 1453 else 1454 config.status = WifiConfiguration.Status.ENABLED; 1455 } else { 1456 config.status = WifiConfiguration.Status.ENABLED; 1457 } 1458 1459 readNetworkVariables(config); 1460 1461 Checksum csum = new CRC32(); 1462 if (config.SSID != null) { 1463 csum.update(config.SSID.getBytes(), 0, config.SSID.getBytes().length); 1464 long d = csum.getValue(); 1465 if (mDeletedSSIDs.contains(d)) { 1466 loge(" got CRC for SSID " + config.SSID + " -> " + d + ", was deleted"); 1467 } 1468 } 1469 1470 if (config.priority > mLastPriority) { 1471 mLastPriority = config.priority; 1472 } 1473 1474 config.setIpAssignment(IpAssignment.DHCP); 1475 config.setProxySettings(ProxySettings.NONE); 1476 1477 if (mNetworkIds.containsKey(configKey(config))) { 1478 // That SSID is already known, just ignore this duplicate entry 1479 if (showNetworks) localLog("discarded duplicate network ", config.networkId); 1480 } else if(config.isValid()){ 1481 mConfiguredNetworks.put(config.networkId, config); 1482 mNetworkIds.put(configKey(config), config.networkId); 1483 if (showNetworks) localLog("loaded configured network", config.networkId); 1484 } else { 1485 if (showNetworks) log("Ignoring loaded configured for network " + config.networkId 1486 + " because config are not valid"); 1487 } 1488 } 1489 1490 done = (lines.length == 1); 1491 } 1492 1493 readIpAndProxyConfigurations(); 1494 readNetworkHistory(); 1495 readAutoJoinConfig(); 1496 1497 sendConfiguredNetworksChangedBroadcast(); 1498 1499 if (showNetworks) localLog("loadConfiguredNetworks loaded " + mNetworkIds.size() + " networks"); 1500 1501 if (mNetworkIds.size() == 0) { 1502 // no networks? Lets log if the wpa_supplicant.conf file contents 1503 BufferedReader reader = null; 1504 try { 1505 reader = new BufferedReader(new FileReader(SUPPLICANT_CONFIG_FILE)); 1506 if (DBG) { 1507 localLog("--- Begin wpa_supplicant.conf Contents ---", true); 1508 for (String line = reader.readLine(); line != null; line = reader.readLine()) { 1509 localLog(line, true); 1510 } 1511 localLog("--- End wpa_supplicant.conf Contents ---", true); 1512 } 1513 } catch (FileNotFoundException e) { 1514 localLog("Could not open " + SUPPLICANT_CONFIG_FILE + ", " + e, true); 1515 } catch (IOException e) { 1516 localLog("Could not read " + SUPPLICANT_CONFIG_FILE + ", " + e, true); 1517 } finally { 1518 try { 1519 if (reader != null) { 1520 reader.close(); 1521 } 1522 } catch (IOException e) { 1523 // Just ignore the fact that we couldn't close 1524 } 1525 } 1526 } 1527 } 1528 1529 private Map<String, String> readNetworkVariablesFromSupplicantFile(String key) { 1530 Map<String, String> result = new HashMap<>(); 1531 BufferedReader reader = null; 1532 if (VDBG) loge("readNetworkVariablesFromSupplicantFile key=" + key); 1533 1534 try { 1535 reader = new BufferedReader(new FileReader(SUPPLICANT_CONFIG_FILE)); 1536 boolean found = false; 1537 String networkSsid = null; 1538 String value = null; 1539 1540 for (String line = reader.readLine(); line != null; line = reader.readLine()) { 1541 1542 if (line.matches("[ \\t]*network=\\{")) { 1543 found = true; 1544 networkSsid = null; 1545 value = null; 1546 } else if (line.matches("[ \\t]*\\}")) { 1547 found = false; 1548 networkSsid = null; 1549 value = null; 1550 } 1551 1552 if (found) { 1553 String trimmedLine = line.trim(); 1554 if (trimmedLine.startsWith("ssid=")) { 1555 networkSsid = trimmedLine.substring(5); 1556 } else if (trimmedLine.startsWith(key + "=")) { 1557 value = trimmedLine.substring(key.length() + 1); 1558 } 1559 1560 if (networkSsid != null && value != null) { 1561 result.put(networkSsid, value); 1562 } 1563 } 1564 } 1565 } catch (FileNotFoundException e) { 1566 if (VDBG) loge("Could not open " + SUPPLICANT_CONFIG_FILE + ", " + e); 1567 } catch (IOException e) { 1568 if (VDBG) loge("Could not read " + SUPPLICANT_CONFIG_FILE + ", " + e); 1569 } finally { 1570 try { 1571 if (reader != null) { 1572 reader.close(); 1573 } 1574 } catch (IOException e) { 1575 // Just ignore the fact that we couldn't close 1576 } 1577 } 1578 1579 return result; 1580 } 1581 1582 private String readNetworkVariableFromSupplicantFile(String ssid, String key) { 1583 long start = SystemClock.elapsedRealtimeNanos(); 1584 Map<String, String> data = readNetworkVariablesFromSupplicantFile(key); 1585 long end = SystemClock.elapsedRealtimeNanos(); 1586 1587 if (VDBG) { 1588 loge("readNetworkVariableFromSupplicantFile ssid=[" + ssid + "] key=" + key 1589 + " duration=" + (long)(end - start)); 1590 } 1591 return data.get(ssid); 1592 } 1593 1594 /* Mark all networks except specified netId as disabled */ 1595 private void markAllNetworksDisabledExcept(int netId) { 1596 for(WifiConfiguration config : mConfiguredNetworks.values()) { 1597 if(config != null && config.networkId != netId) { 1598 if (config.status != Status.DISABLED) { 1599 config.status = Status.DISABLED; 1600 config.disableReason = WifiConfiguration.DISABLED_UNKNOWN_REASON; 1601 } 1602 } 1603 } 1604 } 1605 1606 private void markAllNetworksDisabled() { 1607 markAllNetworksDisabledExcept(INVALID_NETWORK_ID); 1608 } 1609 1610 boolean needsUnlockedKeyStore() { 1611 1612 // Any network using certificates to authenticate access requires 1613 // unlocked key store; unless the certificates can be stored with 1614 // hardware encryption 1615 1616 for(WifiConfiguration config : mConfiguredNetworks.values()) { 1617 1618 if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) 1619 && config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) { 1620 1621 if (needsSoftwareBackedKeyStore(config.enterpriseConfig)) { 1622 return true; 1623 } 1624 } 1625 } 1626 1627 return false; 1628 } 1629 1630 public void writeKnownNetworkHistory(boolean force) { 1631 boolean needUpdate = force; 1632 1633 /* Make a copy */ 1634 final List<WifiConfiguration> networks = new ArrayList<WifiConfiguration>(); 1635 for (WifiConfiguration config : mConfiguredNetworks.values()) { 1636 networks.add(new WifiConfiguration(config)); 1637 if (config.dirty == true) { 1638 loge(" rewrite network history for " + config.configKey()); 1639 config.dirty = false; 1640 needUpdate = true; 1641 } 1642 } 1643 if (VDBG) { 1644 loge(" writeKnownNetworkHistory() num networks:" + 1645 mConfiguredNetworks.size() + " needWrite=" + needUpdate); 1646 } 1647 if (needUpdate == false) { 1648 return; 1649 } 1650 mWriter.write(networkHistoryConfigFile, new DelayedDiskWrite.Writer() { 1651 public void onWriteCalled(DataOutputStream out) throws IOException { 1652 for (WifiConfiguration config : networks) { 1653 //loge("onWriteCalled write SSID: " + config.SSID); 1654 /* if (config.getLinkProperties() != null) 1655 loge(" lp " + config.getLinkProperties().toString()); 1656 else 1657 loge("attempt config w/o lp"); 1658 */ 1659 1660 if (VDBG) { 1661 int num = 0; 1662 int numlink = 0; 1663 if (config.connectChoices != null) { 1664 num = config.connectChoices.size(); 1665 } 1666 if (config.linkedConfigurations != null) { 1667 numlink = config.linkedConfigurations.size(); 1668 } 1669 loge("saving network history: " + config.configKey() + " gw: " + 1670 config.defaultGwMacAddress + " autojoin-status: " + 1671 config.autoJoinStatus + " ephemeral=" + config.ephemeral 1672 + " choices:" + Integer.toString(num) 1673 + " link:" + Integer.toString(numlink) 1674 + " status:" + Integer.toString(config.status) 1675 + " nid:" + Integer.toString(config.networkId)); 1676 } 1677 1678 if (config.isValid() == false) 1679 continue; 1680 1681 if (config.SSID == null) { 1682 if (VDBG) { 1683 loge("writeKnownNetworkHistory trying to write config with null SSID"); 1684 } 1685 continue; 1686 } 1687 if (VDBG) { 1688 loge("writeKnownNetworkHistory write config " + config.configKey()); 1689 } 1690 out.writeUTF(CONFIG_KEY + config.configKey() + SEPARATOR_KEY); 1691 1692 out.writeUTF(SSID_KEY + config.SSID + SEPARATOR_KEY); 1693 out.writeUTF(FQDN_KEY + config.FQDN + SEPARATOR_KEY); 1694 1695 out.writeUTF(PRIORITY_KEY + Integer.toString(config.priority) + SEPARATOR_KEY); 1696 out.writeUTF(STATUS_KEY + Integer.toString(config.autoJoinStatus) 1697 + SEPARATOR_KEY); 1698 out.writeUTF(SUPPLICANT_STATUS_KEY + Integer.toString(config.status) 1699 + SEPARATOR_KEY); 1700 out.writeUTF(SUPPLICANT_DISABLE_REASON_KEY 1701 + Integer.toString(config.disableReason) 1702 + SEPARATOR_KEY); 1703 out.writeUTF(NETWORK_ID_KEY + Integer.toString(config.networkId) 1704 + SEPARATOR_KEY); 1705 out.writeUTF(SELF_ADDED_KEY + Boolean.toString(config.selfAdded) 1706 + SEPARATOR_KEY); 1707 out.writeUTF(DID_SELF_ADD_KEY + Boolean.toString(config.didSelfAdd) 1708 + SEPARATOR_KEY); 1709 out.writeUTF(NO_INTERNET_ACCESS_REPORTS_KEY 1710 + Integer.toString(config.numNoInternetAccessReports) 1711 + SEPARATOR_KEY); 1712 out.writeUTF(VALIDATED_INTERNET_ACCESS_KEY 1713 + Boolean.toString(config.validatedInternetAccess) 1714 + SEPARATOR_KEY); 1715 out.writeUTF(EPHEMERAL_KEY 1716 + Boolean.toString(config.ephemeral) 1717 + SEPARATOR_KEY); 1718 if (config.peerWifiConfiguration != null) { 1719 out.writeUTF(PEER_CONFIGURATION_KEY + config.peerWifiConfiguration 1720 + SEPARATOR_KEY); 1721 } 1722 out.writeUTF(NUM_CONNECTION_FAILURES_KEY 1723 + Integer.toString(config.numConnectionFailures) 1724 + SEPARATOR_KEY); 1725 out.writeUTF(NUM_AUTH_FAILURES_KEY 1726 + Integer.toString(config.numAuthFailures) 1727 + SEPARATOR_KEY); 1728 out.writeUTF(NUM_IP_CONFIG_FAILURES_KEY 1729 + Integer.toString(config.numIpConfigFailures) 1730 + SEPARATOR_KEY); 1731 out.writeUTF(SCORER_OVERRIDE_KEY + Integer.toString(config.numScorerOverride) 1732 + SEPARATOR_KEY); 1733 out.writeUTF(SCORER_OVERRIDE_AND_SWITCH_KEY 1734 + Integer.toString(config.numScorerOverrideAndSwitchedNetwork) 1735 + SEPARATOR_KEY); 1736 out.writeUTF(NUM_ASSOCIATION_KEY 1737 + Integer.toString(config.numAssociation) 1738 + SEPARATOR_KEY); 1739 out.writeUTF(JOIN_ATTEMPT_BOOST_KEY 1740 + Integer.toString(config.autoJoinUseAggressiveJoinAttemptThreshold) 1741 + SEPARATOR_KEY); 1742 //out.writeUTF(BLACKLIST_MILLI_KEY + Long.toString(config.blackListTimestamp) 1743 // + SEPARATOR_KEY); 1744 out.writeUTF(CREATOR_UID_KEY + Integer.toString(config.creatorUid) 1745 + SEPARATOR_KEY); 1746 out.writeUTF(CONNECT_UID_KEY + Integer.toString(config.lastConnectUid) 1747 + SEPARATOR_KEY); 1748 out.writeUTF(UPDATE_UID_KEY + Integer.toString(config.lastUpdateUid) 1749 + SEPARATOR_KEY); 1750 String allowedKeyManagementString = 1751 makeString(config.allowedKeyManagement, 1752 WifiConfiguration.KeyMgmt.strings); 1753 out.writeUTF(AUTH_KEY + allowedKeyManagementString + SEPARATOR_KEY); 1754 1755 if (config.connectChoices != null) { 1756 for (String key : config.connectChoices.keySet()) { 1757 Integer choice = config.connectChoices.get(key); 1758 out.writeUTF(CHOICE_KEY + key + "=" 1759 + choice.toString() + SEPARATOR_KEY); 1760 } 1761 } 1762 if (config.linkedConfigurations != null) { 1763 loge("writeKnownNetworkHistory write linked " 1764 + config.linkedConfigurations.size()); 1765 1766 for (String key : config.linkedConfigurations.keySet()) { 1767 out.writeUTF(LINK_KEY + key + SEPARATOR_KEY); 1768 } 1769 } 1770 1771 String macAddress = config.defaultGwMacAddress; 1772 if (macAddress != null) { 1773 out.writeUTF(DEFAULT_GW_KEY + macAddress + SEPARATOR_KEY); 1774 } 1775 1776 if (config.scanResultCache != null) { 1777 for (ScanResult result : config.scanResultCache.values()) { 1778 out.writeUTF(BSSID_KEY + result.BSSID + SEPARATOR_KEY); 1779 1780 out.writeUTF(FREQ_KEY + Integer.toString(result.frequency) 1781 + SEPARATOR_KEY); 1782 1783 out.writeUTF(RSSI_KEY + Integer.toString(result.level) 1784 + SEPARATOR_KEY); 1785 1786 out.writeUTF(BSSID_STATUS_KEY 1787 + Integer.toString(result.autoJoinStatus) 1788 + SEPARATOR_KEY); 1789 1790 //if (result.seen != 0) { 1791 // out.writeUTF(MILLI_KEY + Long.toString(result.seen) 1792 // + SEPARATOR_KEY); 1793 //} 1794 out.writeUTF(BSSID_KEY_END + SEPARATOR_KEY); 1795 } 1796 } 1797 if (config.lastFailure != null) { 1798 out.writeUTF(FAILURE_KEY + config.lastFailure + SEPARATOR_KEY); 1799 } 1800 out.writeUTF(SEPARATOR_KEY); 1801 // Add extra blank lines for clarity 1802 out.writeUTF(SEPARATOR_KEY); 1803 out.writeUTF(SEPARATOR_KEY); 1804 } 1805 if (mDeletedSSIDs != null && mDeletedSSIDs.size() > 0) { 1806 for (Long i : mDeletedSSIDs) { 1807 out.writeUTF(DELETED_CRC32_KEY); 1808 out.writeUTF(String.valueOf(i)); 1809 out.writeUTF(SEPARATOR_KEY); 1810 } 1811 } 1812 if (mDeletedEphemeralSSIDs != null && mDeletedEphemeralSSIDs.size() > 0) { 1813 for (String ssid : mDeletedEphemeralSSIDs) { 1814 out.writeUTF(DELETED_EPHEMERAL_KEY); 1815 out.writeUTF(ssid); 1816 out.writeUTF(SEPARATOR_KEY); 1817 } 1818 } 1819 } 1820 }); 1821 } 1822 1823 public void setLastSelectedConfiguration(int netId) { 1824 if (VDBG) { 1825 loge("setLastSelectedConfiguration " + Integer.toString(netId)); 1826 } 1827 if (netId == WifiConfiguration.INVALID_NETWORK_ID) { 1828 lastSelectedConfiguration = null; 1829 } else { 1830 WifiConfiguration selected = getWifiConfiguration(netId); 1831 if (selected == null) { 1832 lastSelectedConfiguration = null; 1833 } else { 1834 lastSelectedConfiguration = selected.configKey(); 1835 selected.numConnectionFailures = 0; 1836 selected.numIpConfigFailures = 0; 1837 selected.numAuthFailures = 0; 1838 selected.numNoInternetAccessReports = 0; 1839 if (VDBG) { 1840 loge("setLastSelectedConfiguration now: " + lastSelectedConfiguration); 1841 } 1842 } 1843 } 1844 } 1845 1846 public String getLastSelectedConfiguration() { 1847 return lastSelectedConfiguration; 1848 } 1849 1850 public boolean isLastSelectedConfiguration(WifiConfiguration config) { 1851 return (lastSelectedConfiguration != null 1852 && config != null 1853 && lastSelectedConfiguration.equals(config.configKey())); 1854 } 1855 1856 private void readNetworkHistory() { 1857 if (showNetworks) { 1858 localLog("readNetworkHistory() path:" + networkHistoryConfigFile); 1859 } 1860 DataInputStream in = null; 1861 try { 1862 in = new DataInputStream(new BufferedInputStream(new FileInputStream( 1863 networkHistoryConfigFile))); 1864 WifiConfiguration config = null; 1865 while (true) { 1866 int id = -1; 1867 String key = in.readUTF(); 1868 String bssid = null; 1869 String ssid = null; 1870 1871 int freq = 0; 1872 int status = 0; 1873 long seen = 0; 1874 int rssi = WifiConfiguration.INVALID_RSSI; 1875 String caps = null; 1876 if (key.startsWith(CONFIG_KEY)) { 1877 1878 if (config != null) { 1879 config = null; 1880 } 1881 String configKey = key.replace(CONFIG_KEY, ""); 1882 configKey = configKey.replace(SEPARATOR_KEY, ""); 1883 // get the networkId for that config Key 1884 Integer n = mNetworkIds.get(configKey.hashCode()); 1885 // skip reading that configuration data 1886 // since we don't have a corresponding network ID 1887 if (n == null) { 1888 localLog("readNetworkHistory didnt find netid for hash=" 1889 + Integer.toString(configKey.hashCode()) 1890 + " key: " + configKey); 1891 continue; 1892 } 1893 config = mConfiguredNetworks.get(n); 1894 if (config == null) { 1895 localLog("readNetworkHistory didnt find config for netid=" 1896 + n.toString() 1897 + " key: " + configKey); 1898 } 1899 status = 0; 1900 ssid = null; 1901 bssid = null; 1902 freq = 0; 1903 seen = 0; 1904 rssi = WifiConfiguration.INVALID_RSSI; 1905 caps = null; 1906 1907 } else if (config != null) { 1908 if (key.startsWith(SSID_KEY)) { 1909 ssid = key.replace(SSID_KEY, ""); 1910 ssid = ssid.replace(SEPARATOR_KEY, ""); 1911 if (config.SSID != null && !config.SSID.equals(ssid)) { 1912 loge("Error parsing network history file, mismatched SSIDs"); 1913 config = null; //error 1914 ssid = null; 1915 } else { 1916 config.SSID = ssid; 1917 } 1918 } 1919 1920 if (key.startsWith(FQDN_KEY)) { 1921 String fqdn = key.replace(FQDN_KEY, ""); 1922 fqdn = fqdn.replace(SEPARATOR_KEY, ""); 1923 config.FQDN = fqdn; 1924 } 1925 1926 if (key.startsWith(DEFAULT_GW_KEY)) { 1927 String gateway = key.replace(DEFAULT_GW_KEY, ""); 1928 gateway = gateway.replace(SEPARATOR_KEY, ""); 1929 config.defaultGwMacAddress = gateway; 1930 } 1931 1932 if (key.startsWith(STATUS_KEY)) { 1933 String st = key.replace(STATUS_KEY, ""); 1934 st = st.replace(SEPARATOR_KEY, ""); 1935 config.autoJoinStatus = Integer.parseInt(st); 1936 } 1937 1938 if (key.startsWith(SUPPLICANT_DISABLE_REASON_KEY)) { 1939 String reason = key.replace(SUPPLICANT_DISABLE_REASON_KEY, ""); 1940 reason = reason.replace(SEPARATOR_KEY, ""); 1941 config.disableReason = Integer.parseInt(reason); 1942 } 1943 1944 if (key.startsWith(SELF_ADDED_KEY)) { 1945 String selfAdded = key.replace(SELF_ADDED_KEY, ""); 1946 selfAdded = selfAdded.replace(SEPARATOR_KEY, ""); 1947 config.selfAdded = Boolean.parseBoolean(selfAdded); 1948 } 1949 1950 if (key.startsWith(DID_SELF_ADD_KEY)) { 1951 String didSelfAdd = key.replace(DID_SELF_ADD_KEY, ""); 1952 didSelfAdd = didSelfAdd.replace(SEPARATOR_KEY, ""); 1953 config.didSelfAdd = Boolean.parseBoolean(didSelfAdd); 1954 } 1955 1956 if (key.startsWith(NO_INTERNET_ACCESS_REPORTS_KEY)) { 1957 String access = key.replace(NO_INTERNET_ACCESS_REPORTS_KEY, ""); 1958 access = access.replace(SEPARATOR_KEY, ""); 1959 config.numNoInternetAccessReports = Integer.parseInt(access); 1960 } 1961 1962 if (key.startsWith(VALIDATED_INTERNET_ACCESS_KEY)) { 1963 String access = key.replace(VALIDATED_INTERNET_ACCESS_KEY, ""); 1964 access = access.replace(SEPARATOR_KEY, ""); 1965 config.validatedInternetAccess = Boolean.parseBoolean(access); 1966 } 1967 1968 if (key.startsWith(EPHEMERAL_KEY)) { 1969 String access = key.replace(EPHEMERAL_KEY, ""); 1970 access = access.replace(SEPARATOR_KEY, ""); 1971 config.ephemeral = Boolean.parseBoolean(access); 1972 } 1973 1974 if (key.startsWith(CREATOR_UID_KEY)) { 1975 String uid = key.replace(CREATOR_UID_KEY, ""); 1976 uid = uid.replace(SEPARATOR_KEY, ""); 1977 config.creatorUid = Integer.parseInt(uid); 1978 } 1979 1980 if (key.startsWith(BLACKLIST_MILLI_KEY)) { 1981 String milli = key.replace(BLACKLIST_MILLI_KEY, ""); 1982 milli = milli.replace(SEPARATOR_KEY, ""); 1983 config.blackListTimestamp = Long.parseLong(milli); 1984 } 1985 1986 if (key.startsWith(NUM_CONNECTION_FAILURES_KEY)) { 1987 String num = key.replace(NUM_CONNECTION_FAILURES_KEY, ""); 1988 num = num.replace(SEPARATOR_KEY, ""); 1989 config.numConnectionFailures = Integer.parseInt(num); 1990 } 1991 1992 if (key.startsWith(NUM_IP_CONFIG_FAILURES_KEY)) { 1993 String num = key.replace(NUM_IP_CONFIG_FAILURES_KEY, ""); 1994 num = num.replace(SEPARATOR_KEY, ""); 1995 config.numIpConfigFailures = Integer.parseInt(num); 1996 } 1997 1998 if (key.startsWith(NUM_AUTH_FAILURES_KEY)) { 1999 String num = key.replace(NUM_AUTH_FAILURES_KEY, ""); 2000 num = num.replace(SEPARATOR_KEY, ""); 2001 config.numIpConfigFailures = Integer.parseInt(num); 2002 } 2003 2004 if (key.startsWith(SCORER_OVERRIDE_KEY)) { 2005 String num = key.replace(SCORER_OVERRIDE_KEY, ""); 2006 num = num.replace(SEPARATOR_KEY, ""); 2007 config.numScorerOverride = Integer.parseInt(num); 2008 } 2009 2010 if (key.startsWith(SCORER_OVERRIDE_AND_SWITCH_KEY)) { 2011 String num = key.replace(SCORER_OVERRIDE_AND_SWITCH_KEY, ""); 2012 num = num.replace(SEPARATOR_KEY, ""); 2013 config.numScorerOverrideAndSwitchedNetwork = Integer.parseInt(num); 2014 } 2015 2016 if (key.startsWith(NUM_ASSOCIATION_KEY)) { 2017 String num = key.replace(NUM_ASSOCIATION_KEY, ""); 2018 num = num.replace(SEPARATOR_KEY, ""); 2019 config.numAssociation = Integer.parseInt(num); 2020 } 2021 2022 if (key.startsWith(JOIN_ATTEMPT_BOOST_KEY)) { 2023 String num = key.replace(JOIN_ATTEMPT_BOOST_KEY, ""); 2024 num = num.replace(SEPARATOR_KEY, ""); 2025 config.autoJoinUseAggressiveJoinAttemptThreshold = Integer.parseInt(num); 2026 } 2027 2028 if (key.startsWith(CONNECT_UID_KEY)) { 2029 String uid = key.replace(CONNECT_UID_KEY, ""); 2030 uid = uid.replace(SEPARATOR_KEY, ""); 2031 config.lastConnectUid = Integer.parseInt(uid); 2032 } 2033 2034 if (key.startsWith(UPDATE_UID_KEY)) { 2035 String uid = key.replace(UPDATE_UID_KEY, ""); 2036 uid = uid.replace(SEPARATOR_KEY, ""); 2037 config.lastUpdateUid = Integer.parseInt(uid); 2038 } 2039 2040 if (key.startsWith(FAILURE_KEY)) { 2041 config.lastFailure = key.replace(FAILURE_KEY, ""); 2042 config.lastFailure = config.lastFailure.replace(SEPARATOR_KEY, ""); 2043 } 2044 2045 if (key.startsWith(PEER_CONFIGURATION_KEY)) { 2046 config.peerWifiConfiguration = key.replace(PEER_CONFIGURATION_KEY, ""); 2047 config.peerWifiConfiguration = 2048 config.peerWifiConfiguration.replace(SEPARATOR_KEY, ""); 2049 } 2050 2051 if (key.startsWith(CHOICE_KEY)) { 2052 String choiceStr = key.replace(CHOICE_KEY, ""); 2053 choiceStr = choiceStr.replace(SEPARATOR_KEY, ""); 2054 String configKey = ""; 2055 int choice = 0; 2056 Matcher match = mConnectChoice.matcher(choiceStr); 2057 if (!match.find()) { 2058 if (DBG) Log.d(TAG, "WifiConfigStore: connectChoice: " + 2059 " Couldnt match pattern : " + choiceStr); 2060 } else { 2061 configKey = match.group(1); 2062 try { 2063 choice = Integer.parseInt(match.group(2)); 2064 } catch (NumberFormatException e) { 2065 choice = 0; 2066 } 2067 if (choice > 0) { 2068 if (config.connectChoices == null) { 2069 config.connectChoices = new HashMap<String, Integer>(); 2070 } 2071 config.connectChoices.put(configKey, choice); 2072 } 2073 } 2074 } 2075 2076 if (key.startsWith(LINK_KEY)) { 2077 String configKey = key.replace(LINK_KEY, ""); 2078 configKey = configKey.replace(SEPARATOR_KEY, ""); 2079 if (config.linkedConfigurations == null) { 2080 config.linkedConfigurations = new HashMap<String, Integer>(); 2081 } 2082 if (config.linkedConfigurations != null) { 2083 config.linkedConfigurations.put(configKey, -1); 2084 } 2085 } 2086 2087 if (key.startsWith(BSSID_KEY)) { 2088 if (key.startsWith(BSSID_KEY)) { 2089 bssid = key.replace(BSSID_KEY, ""); 2090 bssid = bssid.replace(SEPARATOR_KEY, ""); 2091 freq = 0; 2092 seen = 0; 2093 rssi = WifiConfiguration.INVALID_RSSI; 2094 caps = ""; 2095 status = 0; 2096 } 2097 2098 if (key.startsWith(RSSI_KEY)) { 2099 String lvl = key.replace(RSSI_KEY, ""); 2100 lvl = lvl.replace(SEPARATOR_KEY, ""); 2101 rssi = Integer.parseInt(lvl); 2102 } 2103 2104 if (key.startsWith(BSSID_STATUS_KEY)) { 2105 String st = key.replace(BSSID_STATUS_KEY, ""); 2106 st = st.replace(SEPARATOR_KEY, ""); 2107 status = Integer.parseInt(st); 2108 } 2109 2110 if (key.startsWith(FREQ_KEY)) { 2111 String channel = key.replace(FREQ_KEY, ""); 2112 channel = channel.replace(SEPARATOR_KEY, ""); 2113 freq = Integer.parseInt(channel); 2114 } 2115 2116 if (key.startsWith(DATE_KEY)) { 2117 /* 2118 * when reading the configuration from file we don't update the date 2119 * so as to avoid reading back stale or non-sensical data that would 2120 * depend on network time. 2121 * The date of a WifiConfiguration should only come from actual scan result. 2122 * 2123 String s = key.replace(FREQ_KEY, ""); 2124 seen = Integer.getInteger(s); 2125 */ 2126 } 2127 2128 if (key.startsWith(BSSID_KEY_END)) { 2129 if ((bssid != null) && (ssid != null)) { 2130 2131 if (config.scanResultCache == null) { 2132 config.scanResultCache = new HashMap<String, ScanResult>(); 2133 } 2134 WifiSsid wssid = WifiSsid.createFromAsciiEncoded(ssid); 2135 ScanResult result = new ScanResult(wssid, bssid, 2136 caps, rssi, freq, (long) 0); 2137 result.seen = seen; 2138 config.scanResultCache.put(bssid, result); 2139 result.autoJoinStatus = status; 2140 } 2141 } 2142 2143 if (key.startsWith(DELETED_CRC32_KEY)) { 2144 String crc = key.replace(DELETED_CRC32_KEY, ""); 2145 Long c = Long.parseLong(crc); 2146 mDeletedSSIDs.add(c); 2147 } 2148 if (key.startsWith(DELETED_EPHEMERAL_KEY)) { 2149 String s = key.replace(DELETED_EPHEMERAL_KEY, ""); 2150 if (!TextUtils.isEmpty(s)) { 2151 s = s.replace(SEPARATOR_KEY, ""); 2152 mDeletedEphemeralSSIDs.add(s); 2153 } 2154 } 2155 } 2156 } 2157 } 2158 } catch (EOFException ignore) { 2159 if (in != null) { 2160 try { 2161 in.close(); 2162 } catch (Exception e) { 2163 loge("readNetworkHistory: Error reading file" + e); 2164 } 2165 } 2166 } catch (IOException e) { 2167 loge("readNetworkHistory: No config file, revert to default" + e); 2168 } 2169 2170 if(in!=null) { 2171 try { 2172 in.close(); 2173 } catch (Exception e) { 2174 loge("readNetworkHistory: Error closing file" + e); 2175 } 2176 } 2177 } 2178 2179 private void readAutoJoinConfig() { 2180 BufferedReader reader = null; 2181 try { 2182 2183 reader = new BufferedReader(new FileReader(autoJoinConfigFile)); 2184 2185 for (String key = reader.readLine(); key != null; key = reader.readLine()) { 2186 if (key != null) { 2187 Log.d(TAG, "readAutoJoinConfig line: " + key); 2188 } 2189 if (key.startsWith(ENABLE_AUTO_JOIN_WHILE_ASSOCIATED_KEY)) { 2190 String st = key.replace(ENABLE_AUTO_JOIN_WHILE_ASSOCIATED_KEY, ""); 2191 st = st.replace(SEPARATOR_KEY, ""); 2192 try { 2193 enableAutoJoinWhenAssociated = Integer.parseInt(st) != 0; 2194 Log.d(TAG,"readAutoJoinConfig: enabled = " + enableAutoJoinWhenAssociated); 2195 } catch (NumberFormatException e) { 2196 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2197 } 2198 } 2199 2200 if (key.startsWith(ENABLE_FULL_BAND_SCAN_WHEN_ASSOCIATED_KEY)) { 2201 String st = key.replace(ENABLE_FULL_BAND_SCAN_WHEN_ASSOCIATED_KEY, ""); 2202 st = st.replace(SEPARATOR_KEY, ""); 2203 try { 2204 enableFullBandScanWhenAssociated = Integer.parseInt(st) != 0; 2205 Log.d(TAG,"readAutoJoinConfig: enableFullBandScanWhenAssociated = " 2206 + enableFullBandScanWhenAssociated); 2207 } catch (NumberFormatException e) { 2208 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2209 } 2210 } 2211 2212 if (key.startsWith(ENABLE_AUTO_JOIN_SCAN_WHILE_ASSOCIATED_KEY)) { 2213 String st = key.replace(ENABLE_AUTO_JOIN_SCAN_WHILE_ASSOCIATED_KEY, ""); 2214 st = st.replace(SEPARATOR_KEY, ""); 2215 try { 2216 enableAutoJoinScanWhenAssociated = Integer.parseInt(st) != 0; 2217 Log.d(TAG,"readAutoJoinConfig: enabled = " 2218 + enableAutoJoinScanWhenAssociated); 2219 } catch (NumberFormatException e) { 2220 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2221 } 2222 } 2223 2224 if (key.startsWith(ENABLE_CHIP_WAKE_UP_WHILE_ASSOCIATED_KEY)) { 2225 String st = key.replace(ENABLE_CHIP_WAKE_UP_WHILE_ASSOCIATED_KEY, ""); 2226 st = st.replace(SEPARATOR_KEY, ""); 2227 try { 2228 enableChipWakeUpWhenAssociated = Integer.parseInt(st) != 0; 2229 Log.d(TAG,"readAutoJoinConfig: enabled = " 2230 + enableChipWakeUpWhenAssociated); 2231 } catch (NumberFormatException e) { 2232 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2233 } 2234 } 2235 2236 if (key.startsWith(ENABLE_RSSI_POLL_WHILE_ASSOCIATED_KEY)) { 2237 String st = key.replace(ENABLE_RSSI_POLL_WHILE_ASSOCIATED_KEY, ""); 2238 st = st.replace(SEPARATOR_KEY, ""); 2239 try { 2240 enableRssiPollWhenAssociated = Integer.parseInt(st) != 0; 2241 Log.d(TAG,"readAutoJoinConfig: enabled = " 2242 + enableRssiPollWhenAssociated); 2243 } catch (NumberFormatException e) { 2244 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2245 } 2246 } 2247 2248 if (key.startsWith(THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_5G_KEY)) { 2249 String st = 2250 key.replace(THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_5G_KEY, ""); 2251 st = st.replace(SEPARATOR_KEY, ""); 2252 try { 2253 thresholdInitialAutoJoinAttemptMin5RSSI = Integer.parseInt(st); 2254 Log.d(TAG,"readAutoJoinConfig: thresholdInitialAutoJoinAttemptMin5RSSI = " 2255 + Integer.toString(thresholdInitialAutoJoinAttemptMin5RSSI)); 2256 } catch (NumberFormatException e) { 2257 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2258 } 2259 } 2260 2261 if (key.startsWith(THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_24G_KEY)) { 2262 String st = 2263 key.replace(THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_24G_KEY, ""); 2264 st = st.replace(SEPARATOR_KEY, ""); 2265 try { 2266 thresholdInitialAutoJoinAttemptMin24RSSI = Integer.parseInt(st); 2267 Log.d(TAG,"readAutoJoinConfig: thresholdInitialAutoJoinAttemptMin24RSSI = " 2268 + Integer.toString(thresholdInitialAutoJoinAttemptMin24RSSI)); 2269 } catch (NumberFormatException e) { 2270 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2271 } 2272 } 2273 2274 if (key.startsWith(THRESHOLD_UNBLACKLIST_HARD_5G_KEY)) { 2275 String st = key.replace(THRESHOLD_UNBLACKLIST_HARD_5G_KEY, ""); 2276 st = st.replace(SEPARATOR_KEY, ""); 2277 try { 2278 thresholdUnblacklistThreshold5Hard = Integer.parseInt(st); 2279 Log.d(TAG,"readAutoJoinConfig: thresholdUnblacklistThreshold5Hard = " 2280 + Integer.toString(thresholdUnblacklistThreshold5Hard)); 2281 } catch (NumberFormatException e) { 2282 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2283 } 2284 } 2285 if (key.startsWith(THRESHOLD_UNBLACKLIST_SOFT_5G_KEY)) { 2286 String st = key.replace(THRESHOLD_UNBLACKLIST_SOFT_5G_KEY, ""); 2287 st = st.replace(SEPARATOR_KEY, ""); 2288 try { 2289 thresholdUnblacklistThreshold5Soft = Integer.parseInt(st); 2290 Log.d(TAG,"readAutoJoinConfig: thresholdUnblacklistThreshold5Soft = " 2291 + Integer.toString(thresholdUnblacklistThreshold5Soft)); 2292 } catch (NumberFormatException e) { 2293 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2294 } 2295 } 2296 if (key.startsWith(THRESHOLD_UNBLACKLIST_HARD_24G_KEY)) { 2297 String st = key.replace(THRESHOLD_UNBLACKLIST_HARD_24G_KEY, ""); 2298 st = st.replace(SEPARATOR_KEY, ""); 2299 try { 2300 thresholdUnblacklistThreshold24Hard = Integer.parseInt(st); 2301 Log.d(TAG,"readAutoJoinConfig: thresholdUnblacklistThreshold24Hard = " 2302 + Integer.toString(thresholdUnblacklistThreshold24Hard)); 2303 } catch (NumberFormatException e) { 2304 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2305 } 2306 } 2307 if (key.startsWith(THRESHOLD_UNBLACKLIST_SOFT_24G_KEY)) { 2308 String st = key.replace(THRESHOLD_UNBLACKLIST_SOFT_24G_KEY, ""); 2309 st = st.replace(SEPARATOR_KEY, ""); 2310 try { 2311 thresholdUnblacklistThreshold24Soft = Integer.parseInt(st); 2312 Log.d(TAG,"readAutoJoinConfig: thresholdUnblacklistThreshold24Soft = " 2313 + Integer.toString(thresholdUnblacklistThreshold24Soft)); 2314 } catch (NumberFormatException e) { 2315 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2316 } 2317 } 2318 2319 if (key.startsWith(THRESHOLD_GOOD_RSSI_5_KEY)) { 2320 String st = key.replace(THRESHOLD_GOOD_RSSI_5_KEY, ""); 2321 st = st.replace(SEPARATOR_KEY, ""); 2322 try { 2323 thresholdGoodRssi5 = Integer.parseInt(st); 2324 Log.d(TAG,"readAutoJoinConfig: thresholdGoodRssi5 = " 2325 + Integer.toString(thresholdGoodRssi5)); 2326 } catch (NumberFormatException e) { 2327 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2328 } 2329 } 2330 if (key.startsWith(THRESHOLD_LOW_RSSI_5_KEY)) { 2331 String st = key.replace(THRESHOLD_LOW_RSSI_5_KEY, ""); 2332 st = st.replace(SEPARATOR_KEY, ""); 2333 try { 2334 thresholdLowRssi5 = Integer.parseInt(st); 2335 Log.d(TAG,"readAutoJoinConfig: thresholdLowRssi5 = " 2336 + Integer.toString(thresholdLowRssi5)); 2337 } catch (NumberFormatException e) { 2338 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2339 } 2340 } 2341 if (key.startsWith(THRESHOLD_BAD_RSSI_5_KEY)) { 2342 String st = key.replace(THRESHOLD_BAD_RSSI_5_KEY, ""); 2343 st = st.replace(SEPARATOR_KEY, ""); 2344 try { 2345 thresholdBadRssi5 = Integer.parseInt(st); 2346 Log.d(TAG,"readAutoJoinConfig: thresholdBadRssi5 = " 2347 + Integer.toString(thresholdBadRssi5)); 2348 } catch (NumberFormatException e) { 2349 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2350 } 2351 } 2352 2353 if (key.startsWith(THRESHOLD_GOOD_RSSI_24_KEY)) { 2354 String st = key.replace(THRESHOLD_GOOD_RSSI_24_KEY, ""); 2355 st = st.replace(SEPARATOR_KEY, ""); 2356 try { 2357 thresholdGoodRssi24 = Integer.parseInt(st); 2358 Log.d(TAG,"readAutoJoinConfig: thresholdGoodRssi24 = " 2359 + Integer.toString(thresholdGoodRssi24)); 2360 } catch (NumberFormatException e) { 2361 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2362 } 2363 } 2364 if (key.startsWith(THRESHOLD_LOW_RSSI_24_KEY)) { 2365 String st = key.replace(THRESHOLD_LOW_RSSI_24_KEY, ""); 2366 st = st.replace(SEPARATOR_KEY, ""); 2367 try { 2368 thresholdLowRssi24 = Integer.parseInt(st); 2369 Log.d(TAG,"readAutoJoinConfig: thresholdLowRssi24 = " 2370 + Integer.toString(thresholdLowRssi24)); 2371 } catch (NumberFormatException e) { 2372 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2373 } 2374 } 2375 if (key.startsWith(THRESHOLD_BAD_RSSI_24_KEY)) { 2376 String st = key.replace(THRESHOLD_BAD_RSSI_24_KEY, ""); 2377 st = st.replace(SEPARATOR_KEY, ""); 2378 try { 2379 thresholdBadRssi24 = Integer.parseInt(st); 2380 Log.d(TAG,"readAutoJoinConfig: thresholdBadRssi24 = " 2381 + Integer.toString(thresholdBadRssi24)); 2382 } catch (NumberFormatException e) { 2383 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2384 } 2385 } 2386 2387 if (key.startsWith(THRESHOLD_MAX_TX_PACKETS_FOR_NETWORK_SWITCHING_KEY)) { 2388 String st = key.replace(THRESHOLD_MAX_TX_PACKETS_FOR_NETWORK_SWITCHING_KEY, ""); 2389 st = st.replace(SEPARATOR_KEY, ""); 2390 try { 2391 maxTxPacketForNetworkSwitching = Integer.parseInt(st); 2392 Log.d(TAG,"readAutoJoinConfig: maxTxPacketForNetworkSwitching = " 2393 + Integer.toString(maxTxPacketForNetworkSwitching)); 2394 } catch (NumberFormatException e) { 2395 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2396 } 2397 } 2398 if (key.startsWith(THRESHOLD_MAX_RX_PACKETS_FOR_NETWORK_SWITCHING_KEY)) { 2399 String st = key.replace(THRESHOLD_MAX_RX_PACKETS_FOR_NETWORK_SWITCHING_KEY, ""); 2400 st = st.replace(SEPARATOR_KEY, ""); 2401 try { 2402 maxRxPacketForNetworkSwitching = Integer.parseInt(st); 2403 Log.d(TAG,"readAutoJoinConfig: maxRxPacketForNetworkSwitching = " 2404 + Integer.toString(maxRxPacketForNetworkSwitching)); 2405 } catch (NumberFormatException e) { 2406 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2407 } 2408 } 2409 2410 if (key.startsWith(THRESHOLD_MAX_TX_PACKETS_FOR_FULL_SCANS_KEY)) { 2411 String st = key.replace(THRESHOLD_MAX_TX_PACKETS_FOR_FULL_SCANS_KEY, ""); 2412 st = st.replace(SEPARATOR_KEY, ""); 2413 try { 2414 maxTxPacketForNetworkSwitching = Integer.parseInt(st); 2415 Log.d(TAG,"readAutoJoinConfig: maxTxPacketForFullScans = " 2416 + Integer.toString(maxTxPacketForFullScans)); 2417 } catch (NumberFormatException e) { 2418 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2419 } 2420 } 2421 if (key.startsWith(THRESHOLD_MAX_RX_PACKETS_FOR_FULL_SCANS_KEY)) { 2422 String st = key.replace(THRESHOLD_MAX_RX_PACKETS_FOR_FULL_SCANS_KEY, ""); 2423 st = st.replace(SEPARATOR_KEY, ""); 2424 try { 2425 maxRxPacketForNetworkSwitching = Integer.parseInt(st); 2426 Log.d(TAG,"readAutoJoinConfig: maxRxPacketForFullScans = " 2427 + Integer.toString(maxRxPacketForFullScans)); 2428 } catch (NumberFormatException e) { 2429 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2430 } 2431 } 2432 2433 if (key.startsWith(THRESHOLD_MAX_TX_PACKETS_FOR_PARTIAL_SCANS_KEY)) { 2434 String st = key.replace(THRESHOLD_MAX_TX_PACKETS_FOR_PARTIAL_SCANS_KEY, ""); 2435 st = st.replace(SEPARATOR_KEY, ""); 2436 try { 2437 maxTxPacketForNetworkSwitching = Integer.parseInt(st); 2438 Log.d(TAG,"readAutoJoinConfig: maxTxPacketForPartialScans = " 2439 + Integer.toString(maxTxPacketForPartialScans)); 2440 } catch (NumberFormatException e) { 2441 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2442 } 2443 } 2444 if (key.startsWith(THRESHOLD_MAX_RX_PACKETS_FOR_PARTIAL_SCANS_KEY)) { 2445 String st = key.replace(THRESHOLD_MAX_RX_PACKETS_FOR_PARTIAL_SCANS_KEY, ""); 2446 st = st.replace(SEPARATOR_KEY, ""); 2447 try { 2448 maxRxPacketForNetworkSwitching = Integer.parseInt(st); 2449 Log.d(TAG,"readAutoJoinConfig: maxRxPacketForPartialScans = " 2450 + Integer.toString(maxRxPacketForPartialScans)); 2451 } catch (NumberFormatException e) { 2452 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2453 } 2454 } 2455 2456 if (key.startsWith(WIFI_VERBOSE_LOGS_KEY)) { 2457 String st = key.replace(WIFI_VERBOSE_LOGS_KEY, ""); 2458 st = st.replace(SEPARATOR_KEY, ""); 2459 try { 2460 enableVerboseLogging = Integer.parseInt(st); 2461 Log.d(TAG,"readAutoJoinConfig: enable verbose logs = " 2462 + Integer.toString(enableVerboseLogging)); 2463 } catch (NumberFormatException e) { 2464 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2465 } 2466 } 2467 if (key.startsWith(A_BAND_PREFERENCE_RSSI_THRESHOLD_KEY)) { 2468 String st = key.replace(A_BAND_PREFERENCE_RSSI_THRESHOLD_KEY, ""); 2469 st = st.replace(SEPARATOR_KEY, ""); 2470 try { 2471 bandPreferenceBoostThreshold5 = Integer.parseInt(st); 2472 Log.d(TAG,"readAutoJoinConfig: bandPreferenceBoostThreshold5 = " 2473 + Integer.toString(bandPreferenceBoostThreshold5)); 2474 } catch (NumberFormatException e) { 2475 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2476 } 2477 } 2478 if (key.startsWith(ASSOCIATED_PARTIAL_SCAN_PERIOD_KEY)) { 2479 String st = key.replace(ASSOCIATED_PARTIAL_SCAN_PERIOD_KEY, ""); 2480 st = st.replace(SEPARATOR_KEY, ""); 2481 try { 2482 associatedPartialScanPeriodMilli = Integer.parseInt(st); 2483 Log.d(TAG,"readAutoJoinConfig: associatedScanPeriod = " 2484 + Integer.toString(associatedPartialScanPeriodMilli)); 2485 } catch (NumberFormatException e) { 2486 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2487 } 2488 } 2489 if (key.startsWith(ASSOCIATED_FULL_SCAN_BACKOFF_KEY)) { 2490 String st = key.replace(ASSOCIATED_FULL_SCAN_BACKOFF_KEY, ""); 2491 st = st.replace(SEPARATOR_KEY, ""); 2492 try { 2493 associatedFullScanBackoff = Integer.parseInt(st); 2494 Log.d(TAG,"readAutoJoinConfig: associatedFullScanBackoff = " 2495 + Integer.toString(associatedFullScanBackoff)); 2496 } catch (NumberFormatException e) { 2497 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2498 } 2499 } 2500 if (key.startsWith(G_BAND_PREFERENCE_RSSI_THRESHOLD_KEY)) { 2501 String st = key.replace(G_BAND_PREFERENCE_RSSI_THRESHOLD_KEY, ""); 2502 st = st.replace(SEPARATOR_KEY, ""); 2503 try { 2504 bandPreferencePenaltyThreshold5 = Integer.parseInt(st); 2505 Log.d(TAG,"readAutoJoinConfig: bandPreferencePenaltyThreshold5 = " 2506 + Integer.toString(bandPreferencePenaltyThreshold5)); 2507 } catch (NumberFormatException e) { 2508 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2509 } 2510 } 2511 if (key.startsWith(ALWAYS_ENABLE_SCAN_WHILE_ASSOCIATED_KEY)) { 2512 String st = key.replace(ALWAYS_ENABLE_SCAN_WHILE_ASSOCIATED_KEY, ""); 2513 st = st.replace(SEPARATOR_KEY, ""); 2514 try { 2515 alwaysEnableScansWhileAssociated = Integer.parseInt(st); 2516 Log.d(TAG,"readAutoJoinConfig: alwaysEnableScansWhileAssociated = " 2517 + Integer.toString(alwaysEnableScansWhileAssociated)); 2518 } catch (NumberFormatException e) { 2519 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2520 } 2521 } 2522 if (key.startsWith(MAX_NUM_PASSIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY)) { 2523 String st = key.replace(MAX_NUM_PASSIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY, ""); 2524 st = st.replace(SEPARATOR_KEY, ""); 2525 try { 2526 maxNumPassiveChannelsForPartialScans = Integer.parseInt(st); 2527 Log.d(TAG,"readAutoJoinConfig: maxNumPassiveChannelsForPartialScans = " 2528 + Integer.toString(maxNumPassiveChannelsForPartialScans)); 2529 } catch (NumberFormatException e) { 2530 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2531 } 2532 } 2533 if (key.startsWith(MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY)) { 2534 String st = key.replace(MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY, ""); 2535 st = st.replace(SEPARATOR_KEY, ""); 2536 try { 2537 maxNumActiveChannelsForPartialScans = Integer.parseInt(st); 2538 Log.d(TAG,"readAutoJoinConfig: maxNumActiveChannelsForPartialScans = " 2539 + Integer.toString(maxNumActiveChannelsForPartialScans)); 2540 } catch (NumberFormatException e) { 2541 Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key); 2542 } 2543 } 2544 } 2545 } catch (EOFException ignore) { 2546 if (reader != null) { 2547 try { 2548 reader.close(); 2549 reader = null; 2550 } catch (Exception e) { 2551 loge("readAutoJoinStatus: Error closing file" + e); 2552 } 2553 } 2554 } catch (FileNotFoundException ignore) { 2555 if (reader != null) { 2556 try { 2557 reader.close(); 2558 reader = null; 2559 } catch (Exception e) { 2560 loge("readAutoJoinStatus: Error closing file" + e); 2561 } 2562 } 2563 } catch (IOException e) { 2564 loge("readAutoJoinStatus: Error parsing configuration" + e); 2565 } 2566 2567 if (reader!=null) { 2568 try { 2569 reader.close(); 2570 } catch (Exception e) { 2571 loge("readAutoJoinStatus: Error closing file" + e); 2572 } 2573 } 2574 } 2575 2576 2577 private void writeIpAndProxyConfigurations() { 2578 final SparseArray<IpConfiguration> networks = new SparseArray<IpConfiguration>(); 2579 for(WifiConfiguration config : mConfiguredNetworks.values()) { 2580 if (!config.ephemeral && config.autoJoinStatus != WifiConfiguration.AUTO_JOIN_DELETED) { 2581 networks.put(configKey(config), config.getIpConfiguration()); 2582 } 2583 } 2584 2585 super.writeIpAndProxyConfigurations(ipConfigFile, networks); 2586 } 2587 2588 private void readIpAndProxyConfigurations() { 2589 SparseArray<IpConfiguration> networks = super.readIpAndProxyConfigurations(ipConfigFile); 2590 2591 if (networks == null || networks.size() == 0) { 2592 // IpConfigStore.readIpAndProxyConfigurations has already logged an error. 2593 return; 2594 } 2595 2596 for (int i = 0; i < networks.size(); i++) { 2597 int id = networks.keyAt(i); 2598 WifiConfiguration config = mConfiguredNetworks.get(mNetworkIds.get(id)); 2599 2600 2601 if (config == null || config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED || 2602 config.ephemeral) { 2603 loge("configuration found for missing network, nid=" + id 2604 +", ignored, networks.size=" + Integer.toString(networks.size())); 2605 } else { 2606 config.setIpConfiguration(networks.valueAt(i)); 2607 } 2608 } 2609 } 2610 2611 /* 2612 * Convert string to Hexadecimal before passing to wifi native layer 2613 * In native function "doCommand()" have trouble in converting Unicode character string to UTF8 2614 * conversion to hex is required because SSIDs can have space characters in them; 2615 * and that can confuses the supplicant because it uses space charaters as delimiters 2616 */ 2617 2618 private String encodeSSID(String str){ 2619 String tmp = removeDoubleQuotes(str); 2620 return String.format("%x", new BigInteger(1, tmp.getBytes(Charset.forName("UTF-8")))); 2621 } 2622 2623 private NetworkUpdateResult addOrUpdateNetworkNative(WifiConfiguration config, int uid) { 2624 /* 2625 * If the supplied networkId is INVALID_NETWORK_ID, we create a new empty 2626 * network configuration. Otherwise, the networkId should 2627 * refer to an existing configuration. 2628 */ 2629 2630 if (VDBG) localLog("addOrUpdateNetworkNative " + config.getPrintableSsid()); 2631 2632 int netId = config.networkId; 2633 boolean newNetwork = false; 2634 // networkId of INVALID_NETWORK_ID means we want to create a new network 2635 if (netId == INVALID_NETWORK_ID) { 2636 Integer savedNetId = mNetworkIds.get(configKey(config)); 2637 // Check if either we have a network Id or a WifiConfiguration 2638 // matching the one we are trying to add. 2639 if (savedNetId == null) { 2640 for (WifiConfiguration test : mConfiguredNetworks.values()) { 2641 if (test.configKey().equals(config.configKey())) { 2642 savedNetId = test.networkId; 2643 loge("addOrUpdateNetworkNative " + config.configKey() 2644 + " was found, but no network Id"); 2645 break; 2646 } 2647 } 2648 } 2649 if (savedNetId != null) { 2650 netId = savedNetId; 2651 } else { 2652 newNetwork = true; 2653 netId = mWifiNative.addNetwork(); 2654 if (netId < 0) { 2655 loge("Failed to add a network!"); 2656 return new NetworkUpdateResult(INVALID_NETWORK_ID); 2657 } else { 2658 loge("addOrUpdateNetworkNative created netId=" + netId); 2659 } 2660 } 2661 } 2662 2663 boolean updateFailed = true; 2664 2665 setVariables: { 2666 2667 if (config.SSID != null && 2668 !mWifiNative.setNetworkVariable( 2669 netId, 2670 WifiConfiguration.ssidVarName, 2671 encodeSSID(config.SSID))) { 2672 loge("failed to set SSID: "+config.SSID); 2673 break setVariables; 2674 } 2675 2676 if (config.BSSID != null) { 2677 loge("Setting BSSID for " + config.configKey() + " to " + config.BSSID); 2678 if (!mWifiNative.setNetworkVariable( 2679 netId, 2680 WifiConfiguration.bssidVarName, 2681 config.BSSID)) { 2682 loge("failed to set BSSID: " + config.BSSID); 2683 break setVariables; 2684 } 2685 } 2686 2687 String allowedKeyManagementString = 2688 makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings); 2689 if (config.allowedKeyManagement.cardinality() != 0 && 2690 !mWifiNative.setNetworkVariable( 2691 netId, 2692 WifiConfiguration.KeyMgmt.varName, 2693 allowedKeyManagementString)) { 2694 loge("failed to set key_mgmt: "+ 2695 allowedKeyManagementString); 2696 break setVariables; 2697 } 2698 2699 String allowedProtocolsString = 2700 makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings); 2701 if (config.allowedProtocols.cardinality() != 0 && 2702 !mWifiNative.setNetworkVariable( 2703 netId, 2704 WifiConfiguration.Protocol.varName, 2705 allowedProtocolsString)) { 2706 loge("failed to set proto: "+ 2707 allowedProtocolsString); 2708 break setVariables; 2709 } 2710 2711 String allowedAuthAlgorithmsString = 2712 makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings); 2713 if (config.allowedAuthAlgorithms.cardinality() != 0 && 2714 !mWifiNative.setNetworkVariable( 2715 netId, 2716 WifiConfiguration.AuthAlgorithm.varName, 2717 allowedAuthAlgorithmsString)) { 2718 loge("failed to set auth_alg: "+ 2719 allowedAuthAlgorithmsString); 2720 break setVariables; 2721 } 2722 2723 String allowedPairwiseCiphersString = 2724 makeString(config.allowedPairwiseCiphers, 2725 WifiConfiguration.PairwiseCipher.strings); 2726 if (config.allowedPairwiseCiphers.cardinality() != 0 && 2727 !mWifiNative.setNetworkVariable( 2728 netId, 2729 WifiConfiguration.PairwiseCipher.varName, 2730 allowedPairwiseCiphersString)) { 2731 loge("failed to set pairwise: "+ 2732 allowedPairwiseCiphersString); 2733 break setVariables; 2734 } 2735 2736 String allowedGroupCiphersString = 2737 makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings); 2738 if (config.allowedGroupCiphers.cardinality() != 0 && 2739 !mWifiNative.setNetworkVariable( 2740 netId, 2741 WifiConfiguration.GroupCipher.varName, 2742 allowedGroupCiphersString)) { 2743 loge("failed to set group: "+ 2744 allowedGroupCiphersString); 2745 break setVariables; 2746 } 2747 2748 // Prevent client screw-up by passing in a WifiConfiguration we gave it 2749 // by preventing "*" as a key. 2750 if (config.preSharedKey != null && !config.preSharedKey.equals("*") && 2751 !mWifiNative.setNetworkVariable( 2752 netId, 2753 WifiConfiguration.pskVarName, 2754 config.preSharedKey)) { 2755 loge("failed to set psk"); 2756 break setVariables; 2757 } 2758 2759 boolean hasSetKey = false; 2760 if (config.wepKeys != null) { 2761 for (int i = 0; i < config.wepKeys.length; i++) { 2762 // Prevent client screw-up by passing in a WifiConfiguration we gave it 2763 // by preventing "*" as a key. 2764 if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) { 2765 if (!mWifiNative.setNetworkVariable( 2766 netId, 2767 WifiConfiguration.wepKeyVarNames[i], 2768 config.wepKeys[i])) { 2769 loge("failed to set wep_key" + i + ": " + config.wepKeys[i]); 2770 break setVariables; 2771 } 2772 hasSetKey = true; 2773 } 2774 } 2775 } 2776 2777 if (hasSetKey) { 2778 if (!mWifiNative.setNetworkVariable( 2779 netId, 2780 WifiConfiguration.wepTxKeyIdxVarName, 2781 Integer.toString(config.wepTxKeyIndex))) { 2782 loge("failed to set wep_tx_keyidx: " + config.wepTxKeyIndex); 2783 break setVariables; 2784 } 2785 } 2786 2787 if (!mWifiNative.setNetworkVariable( 2788 netId, 2789 WifiConfiguration.priorityVarName, 2790 Integer.toString(config.priority))) { 2791 loge(config.SSID + ": failed to set priority: " 2792 +config.priority); 2793 break setVariables; 2794 } 2795 2796 if (config.hiddenSSID && !mWifiNative.setNetworkVariable( 2797 netId, 2798 WifiConfiguration.hiddenSSIDVarName, 2799 Integer.toString(config.hiddenSSID ? 1 : 0))) { 2800 loge(config.SSID + ": failed to set hiddenSSID: "+ 2801 config.hiddenSSID); 2802 break setVariables; 2803 } 2804 2805 if (config.requirePMF && !mWifiNative.setNetworkVariable( 2806 netId, 2807 WifiConfiguration.pmfVarName, 2808 "2")) { 2809 loge(config.SSID + ": failed to set requirePMF: "+ 2810 config.requirePMF); 2811 break setVariables; 2812 } 2813 2814 if (config.updateIdentifier != null && !mWifiNative.setNetworkVariable( 2815 netId, 2816 WifiConfiguration.updateIdentiferVarName, 2817 config.updateIdentifier)) { 2818 loge(config.SSID + ": failed to set updateIdentifier: "+ 2819 config.updateIdentifier); 2820 break setVariables; 2821 } 2822 2823 if (config.enterpriseConfig != null && 2824 config.enterpriseConfig.getEapMethod() != WifiEnterpriseConfig.Eap.NONE) { 2825 2826 WifiEnterpriseConfig enterpriseConfig = config.enterpriseConfig; 2827 2828 if (needsKeyStore(enterpriseConfig)) { 2829 /** 2830 * Keyguard settings may eventually be controlled by device policy. 2831 * We check here if keystore is unlocked before installing 2832 * credentials. 2833 * TODO: Do we need a dialog here ? 2834 */ 2835 if (mKeyStore.state() != KeyStore.State.UNLOCKED) { 2836 loge(config.SSID + ": key store is locked"); 2837 break setVariables; 2838 } 2839 2840 try { 2841 /* config passed may include only fields being updated. 2842 * In order to generate the key id, fetch uninitialized 2843 * fields from the currently tracked configuration 2844 */ 2845 WifiConfiguration currentConfig = mConfiguredNetworks.get(netId); 2846 String keyId = config.getKeyIdForCredentials(currentConfig); 2847 2848 if (!installKeys(enterpriseConfig, keyId)) { 2849 loge(config.SSID + ": failed to install keys"); 2850 break setVariables; 2851 } 2852 } catch (IllegalStateException e) { 2853 loge(config.SSID + " invalid config for key installation"); 2854 break setVariables; 2855 } 2856 } 2857 2858 HashMap<String, String> enterpriseFields = enterpriseConfig.getFields(); 2859 for (String key : enterpriseFields.keySet()) { 2860 String value = enterpriseFields.get(key); 2861 if (key.equals("password") && value != null && value.equals("*")) { 2862 // No need to try to set an obfuscated password, which will fail 2863 continue; 2864 } 2865 if (!mWifiNative.setNetworkVariable( 2866 netId, 2867 key, 2868 value)) { 2869 removeKeys(enterpriseConfig); 2870 loge(config.SSID + ": failed to set " + key + 2871 ": " + value); 2872 break setVariables; 2873 } 2874 } 2875 } 2876 updateFailed = false; 2877 } // End of setVariables 2878 2879 if (updateFailed) { 2880 if (newNetwork) { 2881 mWifiNative.removeNetwork(netId); 2882 loge("Failed to set a network variable, removed network: " + netId); 2883 } 2884 return new NetworkUpdateResult(INVALID_NETWORK_ID); 2885 } 2886 2887 /* An update of the network variables requires reading them 2888 * back from the supplicant to update mConfiguredNetworks. 2889 * This is because some of the variables (SSID, wep keys & 2890 * passphrases) reflect different values when read back than 2891 * when written. For example, wep key is stored as * irrespective 2892 * of the value sent to the supplicant 2893 */ 2894 WifiConfiguration currentConfig = mConfiguredNetworks.get(netId); 2895 if (currentConfig == null) { 2896 currentConfig = new WifiConfiguration(); 2897 currentConfig.setIpAssignment(IpAssignment.DHCP); 2898 currentConfig.setProxySettings(ProxySettings.NONE); 2899 currentConfig.networkId = netId; 2900 if (config != null) { 2901 // Carry over the creation parameters 2902 currentConfig.selfAdded = config.selfAdded; 2903 currentConfig.didSelfAdd = config.didSelfAdd; 2904 currentConfig.ephemeral = config.ephemeral; 2905 currentConfig.autoJoinUseAggressiveJoinAttemptThreshold 2906 = config.autoJoinUseAggressiveJoinAttemptThreshold; 2907 currentConfig.lastConnectUid = config.lastConnectUid; 2908 currentConfig.lastUpdateUid = config.lastUpdateUid; 2909 currentConfig.creatorUid = config.creatorUid; 2910 currentConfig.peerWifiConfiguration = config.peerWifiConfiguration; 2911 } 2912 if (DBG) { 2913 loge("created new config netId=" + Integer.toString(netId) 2914 + " uid=" + Integer.toString(currentConfig.creatorUid)); 2915 } 2916 } 2917 2918 if (uid >= 0) { 2919 if (newNetwork) { 2920 currentConfig.creatorUid = uid; 2921 } else { 2922 currentConfig.lastUpdateUid = uid; 2923 } 2924 } 2925 2926 if (newNetwork) { 2927 currentConfig.dirty = true; 2928 } 2929 2930 if (currentConfig.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED) { 2931 // Make sure the configuration is not deleted anymore since we just 2932 // added or modified it. 2933 currentConfig.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED); 2934 currentConfig.selfAdded = false; 2935 currentConfig.didSelfAdd = false; 2936 if (DBG) { 2937 loge("remove deleted status netId=" + Integer.toString(netId) 2938 + " " + currentConfig.configKey()); 2939 } 2940 } 2941 2942 if (currentConfig.status == WifiConfiguration.Status.ENABLED) { 2943 // Make sure autojoin remain in sync with user modifying the configuration 2944 currentConfig.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED); 2945 } 2946 2947 if (currentConfig.configKey().equals(getLastSelectedConfiguration()) && 2948 currentConfig.ephemeral) { 2949 // Make the config non-ephemeral since the user just explicitly clicked it. 2950 currentConfig.ephemeral = false; 2951 if (DBG) loge("remove ephemeral status netId=" + Integer.toString(netId) 2952 + " " + currentConfig.configKey()); 2953 } 2954 2955 if (DBG) loge("will read network variables netId=" + Integer.toString(netId)); 2956 2957 readNetworkVariables(currentConfig); 2958 2959 mConfiguredNetworks.put(netId, currentConfig); 2960 mNetworkIds.put(configKey(currentConfig), netId); 2961 2962 NetworkUpdateResult result = writeIpAndProxyConfigurationsOnChange(currentConfig, config); 2963 result.setIsNewNetwork(newNetwork); 2964 result.setNetworkId(netId); 2965 2966 writeKnownNetworkHistory(false); 2967 2968 return result; 2969 } 2970 2971 2972 /** 2973 * This function run thru the Saved WifiConfigurations and check if some should be linked. 2974 * @param config 2975 */ 2976 public void linkConfiguration(WifiConfiguration config) { 2977 2978 if (config.scanResultCache != null && config.scanResultCache.size() > 6) { 2979 // Ignore configurations with large number of BSSIDs 2980 return; 2981 } 2982 if (!config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 2983 // Only link WPA_PSK config 2984 return; 2985 } 2986 for (WifiConfiguration link : mConfiguredNetworks.values()) { 2987 boolean doLink = false; 2988 2989 if (link.configKey().equals(config.configKey())) { 2990 continue; 2991 } 2992 2993 if (link.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED || link.ephemeral) { 2994 continue; 2995 } 2996 2997 // Autojoin will be allowed to dynamically jump from a linked configuration 2998 // to another, hence only link configurations that have equivalent level of security 2999 if (!link.allowedKeyManagement.equals(config.allowedKeyManagement)) { 3000 continue; 3001 } 3002 3003 if (link.scanResultCache != null && link.scanResultCache.size() > 6) { 3004 // Ignore configurations with large number of BSSIDs 3005 continue; 3006 } 3007 3008 if (config.defaultGwMacAddress != null && link.defaultGwMacAddress != null) { 3009 // If both default GW are known, link only if they are equal 3010 if (config.defaultGwMacAddress.equals(link.defaultGwMacAddress)) { 3011 if (VDBG) { 3012 loge("linkConfiguration link due to same gw " + link.SSID + 3013 " and " + config.SSID + " GW " + config.defaultGwMacAddress); 3014 } 3015 doLink = true; 3016 } 3017 } else { 3018 // We do not know BOTH default gateways hence we will try to link 3019 // hoping that WifiConfigurations are indeed behind the same gateway. 3020 // once both WifiConfiguration have been tried and thus once both efault gateways 3021 // are known we will revisit the choice of linking them 3022 if ((config.scanResultCache != null) && (config.scanResultCache.size() <= 6) 3023 && (link.scanResultCache != null) && (link.scanResultCache.size() <= 6)) { 3024 for (String abssid : config.scanResultCache.keySet()) { 3025 for (String bbssid : link.scanResultCache.keySet()) { 3026 if (VVDBG) { 3027 loge("linkConfiguration try to link due to DBDC BSSID match " 3028 + link.SSID + 3029 " and " + config.SSID + " bssida " + abssid 3030 + " bssidb " + bbssid); 3031 } 3032 if (abssid.regionMatches(true, 0, bbssid, 0, 16)) { 3033 // If first 16 ascii characters of BSSID matches, 3034 // we assume this is a DBDC 3035 doLink = true; 3036 } 3037 } 3038 } 3039 } 3040 } 3041 3042 if (doLink == true && onlyLinkSameCredentialConfigurations) { 3043 String apsk = readNetworkVariableFromSupplicantFile(link.SSID, "psk"); 3044 String bpsk = readNetworkVariableFromSupplicantFile(config.SSID, "psk"); 3045 if (apsk == null || bpsk == null 3046 || TextUtils.isEmpty(apsk) || TextUtils.isEmpty(apsk) 3047 || apsk.equals("*") || apsk.equals(DELETED_CONFIG_PSK) 3048 || !apsk.equals(bpsk)) { 3049 doLink = false; 3050 } 3051 } 3052 3053 if (doLink) { 3054 if (VDBG) { 3055 loge("linkConfiguration: will link " + link.configKey() 3056 + " and " + config.configKey()); 3057 } 3058 if (link.linkedConfigurations == null) { 3059 link.linkedConfigurations = new HashMap<String, Integer>(); 3060 } 3061 if (config.linkedConfigurations == null) { 3062 config.linkedConfigurations = new HashMap<String, Integer>(); 3063 } 3064 if (link.linkedConfigurations.get(config.configKey()) == null) { 3065 link.linkedConfigurations.put(config.configKey(), Integer.valueOf(1)); 3066 link.dirty = true; 3067 } 3068 if (config.linkedConfigurations.get(link.configKey()) == null) { 3069 config.linkedConfigurations.put(link.configKey(), Integer.valueOf(1)); 3070 config.dirty = true; 3071 } 3072 } else { 3073 if (link.linkedConfigurations != null 3074 && (link.linkedConfigurations.get(config.configKey()) != null)) { 3075 if (VDBG) { 3076 loge("linkConfiguration: un-link " + config.configKey() 3077 + " from " + link.configKey()); 3078 } 3079 link.dirty = true; 3080 link.linkedConfigurations.remove(config.configKey()); 3081 } 3082 if (config.linkedConfigurations != null 3083 && (config.linkedConfigurations.get(link.configKey()) != null)) { 3084 if (VDBG) { 3085 loge("linkConfiguration: un-link " + link.configKey() 3086 + " from " + config.configKey()); 3087 } 3088 config.dirty = true; 3089 config.linkedConfigurations.remove(link.configKey()); 3090 } 3091 } 3092 } 3093 } 3094 3095 /* 3096 * We try to link a scan result with a WifiConfiguration for which SSID and 3097 * key management dont match, 3098 * for instance, we try identify the 5GHz SSID of a DBDC AP, 3099 * even though we know only of the 2.4GHz 3100 * 3101 * Obviously, this function is not optimal since it is used to compare every scan 3102 * result with every Saved WifiConfiguration, with a string.equals operation. 3103 * As a speed up, might be better to implement the mConfiguredNetworks store as a 3104 * <String, WifiConfiguration> object instead of a <Integer, WifiConfiguration> object 3105 * so as to speed this up. Also to prevent the tiny probability of hash collision. 3106 * 3107 */ 3108 public WifiConfiguration associateWithConfiguration(ScanResult result) { 3109 boolean doNotAdd = false; 3110 String configKey = WifiConfiguration.configKey(result); 3111 if (configKey == null) { 3112 if (DBG) loge("associateWithConfiguration(): no config key " ); 3113 return null; 3114 } 3115 3116 // Need to compare with quoted string 3117 String SSID = "\"" + result.SSID + "\""; 3118 3119 if (VVDBG) { 3120 loge("associateWithConfiguration(): try " + configKey); 3121 } 3122 3123 Checksum csum = new CRC32(); 3124 csum.update(SSID.getBytes(), 0, SSID.getBytes().length); 3125 if (mDeletedSSIDs.contains(csum.getValue())) { 3126 doNotAdd = true; 3127 } 3128 3129 WifiConfiguration config = null; 3130 for (WifiConfiguration link : mConfiguredNetworks.values()) { 3131 boolean doLink = false; 3132 3133 if (link.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED || link.selfAdded || 3134 link.ephemeral) { 3135 if (VVDBG) loge("associateWithConfiguration(): skip selfadd " + link.configKey() ); 3136 // Make sure we dont associate the scan result to a deleted config 3137 continue; 3138 } 3139 3140 if (!link.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 3141 if (VVDBG) loge("associateWithConfiguration(): skip non-PSK " + link.configKey() ); 3142 // Make sure we dont associate the scan result to a non-PSK config 3143 continue; 3144 } 3145 3146 if (configKey.equals(link.configKey())) { 3147 if (VVDBG) loge("associateWithConfiguration(): found it!!! " + configKey ); 3148 return link; // Found it exactly 3149 } 3150 3151 if (!doNotAdd && (link.scanResultCache != null) && (link.scanResultCache.size() <= 6)) { 3152 for (String bssid : link.scanResultCache.keySet()) { 3153 if (result.BSSID.regionMatches(true, 0, bssid, 0, 16) 3154 && SSID.regionMatches(false, 0, link.SSID, 0, 4)) { 3155 // If first 16 ascii characters of BSSID matches, and first 3 3156 // characters of SSID match, we assume this is a home setup 3157 // and thus we will try to transfer the password from the known 3158 // BSSID/SSID to the recently found BSSID/SSID 3159 3160 // If (VDBG) 3161 // loge("associateWithConfiguration OK " ); 3162 doLink = true; 3163 break; 3164 } 3165 } 3166 } 3167 3168 if (doLink) { 3169 // Try to make a non verified WifiConfiguration, but only if the original 3170 // configuration was not self already added 3171 if (VDBG) { 3172 loge("associateWithConfiguration: try to create " + 3173 result.SSID + " and associate it with: " + link.SSID 3174 + " key " + link.configKey()); 3175 } 3176 config = wifiConfigurationFromScanResult(result); 3177 if (config != null) { 3178 config.selfAdded = true; 3179 config.didSelfAdd = true; 3180 config.dirty = true; 3181 config.peerWifiConfiguration = link.configKey(); 3182 if (config.allowedKeyManagement.equals(link.allowedKeyManagement) && 3183 config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) { 3184 if (VDBG && config != null) { 3185 loge("associateWithConfiguration: got a config from beacon" 3186 + config.SSID + " key " + config.configKey()); 3187 } 3188 // Transfer the credentials from the configuration we are linking from 3189 String psk = readNetworkVariableFromSupplicantFile(link.SSID, "psk"); 3190 if (psk != null) { 3191 config.preSharedKey = psk; 3192 if (VDBG) { 3193 if (config.preSharedKey != null) 3194 loge(" transfer PSK : " + config.preSharedKey); 3195 } 3196 3197 // Link configurations 3198 if (link.linkedConfigurations == null) { 3199 link.linkedConfigurations = new HashMap<String, Integer>(); 3200 } 3201 if (config.linkedConfigurations == null) { 3202 config.linkedConfigurations = new HashMap<String, Integer>(); 3203 } 3204 link.linkedConfigurations.put(config.configKey(), Integer.valueOf(1)); 3205 config.linkedConfigurations.put(link.configKey(), Integer.valueOf(1)); 3206 3207 // Carry over the Ip configuration 3208 if (link.getIpConfiguration() != null) { 3209 config.setIpConfiguration(link.getIpConfiguration()); 3210 } 3211 } else { 3212 config = null; 3213 } 3214 } else { 3215 config = null; 3216 } 3217 if (config != null) break; 3218 } 3219 if (VDBG && config != null) { 3220 loge("associateWithConfiguration: success, created: " + config.SSID 3221 + " key " + config.configKey()); 3222 } 3223 } 3224 } 3225 return config; 3226 } 3227 3228 public HashSet<Integer> makeChannelList(WifiConfiguration config, int age, boolean restrict) { 3229 if (config == null) 3230 return null; 3231 long now_ms = System.currentTimeMillis(); 3232 3233 HashSet<Integer> channels = new HashSet<Integer>(); 3234 3235 //get channels for this configuration, if there are at least 2 BSSIDs 3236 if (config.scanResultCache == null && config.linkedConfigurations == null) { 3237 return null; 3238 } 3239 3240 if (VDBG) { 3241 StringBuilder dbg = new StringBuilder(); 3242 dbg.append("makeChannelList age=" + Integer.toString(age) 3243 + " for " + config.configKey() 3244 + " max=" + maxNumActiveChannelsForPartialScans); 3245 if (config.scanResultCache != null) { 3246 dbg.append(" bssids=" + config.scanResultCache.size()); 3247 } 3248 if (config.linkedConfigurations != null) { 3249 dbg.append(" linked=" + config.linkedConfigurations.size()); 3250 } 3251 loge(dbg.toString()); 3252 } 3253 3254 int numChannels = 0; 3255 if (config.scanResultCache != null && config.scanResultCache.size() > 0) { 3256 for (ScanResult result : config.scanResultCache.values()) { 3257 //TODO : cout active and passive channels separately 3258 if (numChannels > maxNumActiveChannelsForPartialScans) { 3259 break; 3260 } 3261 if (VDBG) { 3262 boolean test = (now_ms - result.seen) < age; 3263 loge("has " + result.BSSID + " freq=" + Integer.toString(result.frequency) 3264 + " age=" + Long.toString(now_ms - result.seen) + " ?=" + test); 3265 } 3266 if (((now_ms - result.seen) < age)/*||(!restrict || result.is24GHz())*/) { 3267 channels.add(result.frequency); 3268 numChannels++; 3269 } 3270 } 3271 } 3272 3273 //get channels for linked configurations 3274 if (config.linkedConfigurations != null) { 3275 for (String key : config.linkedConfigurations.keySet()) { 3276 WifiConfiguration linked = getWifiConfiguration(key); 3277 if (linked == null) 3278 continue; 3279 if (linked.scanResultCache == null) { 3280 continue; 3281 } 3282 for (ScanResult result : linked.scanResultCache.values()) { 3283 if (VDBG) { 3284 loge("has link: " + result.BSSID 3285 + " freq=" + Integer.toString(result.frequency) 3286 + " age=" + Long.toString(now_ms - result.seen)); 3287 } 3288 if (numChannels > maxNumActiveChannelsForPartialScans) { 3289 break; 3290 } 3291 if (((now_ms - result.seen) < age)/*||(!restrict || result.is24GHz())*/) { 3292 channels.add(result.frequency); 3293 numChannels++; 3294 } 3295 } 3296 } 3297 } 3298 return channels; 3299 } 3300 3301 // Update the WifiConfiguration database with the new scan result 3302 // A scan result can be associated to multiple WifiConfigurations 3303 public boolean updateSavedNetworkHistory(ScanResult scanResult) { 3304 int numConfigFound = 0; 3305 if (scanResult == null) 3306 return false; 3307 3308 String SSID = "\"" + scanResult.SSID + "\""; 3309 3310 for (WifiConfiguration config : mConfiguredNetworks.values()) { 3311 boolean found = false; 3312 3313 if (config.SSID == null || !config.SSID.equals(SSID)) { 3314 // SSID mismatch 3315 if (VVDBG) { 3316 loge("updateSavedNetworkHistory(): SSID mismatch " + config.configKey() 3317 + " SSID=" + config.SSID + " " + SSID); 3318 } 3319 continue; 3320 } 3321 if (VDBG) { 3322 loge("updateSavedNetworkHistory(): try " + config.configKey() 3323 + " SSID=" + config.SSID + " " + scanResult.SSID 3324 + " " + scanResult.capabilities 3325 + " ajst=" + config.autoJoinStatus); 3326 } 3327 if (scanResult.capabilities.contains("WEP") 3328 && config.configKey().contains("WEP")) { 3329 found = true; 3330 } else if (scanResult.capabilities.contains("PSK") 3331 && config.configKey().contains("PSK")) { 3332 found = true; 3333 } else if (scanResult.capabilities.contains("EAP") 3334 && config.configKey().contains("EAP")) { 3335 found = true; 3336 } else if (!scanResult.capabilities.contains("WEP") 3337 && !scanResult.capabilities.contains("PSK") 3338 && !scanResult.capabilities.contains("EAP") 3339 && !config.configKey().contains("WEP") 3340 && !config.configKey().contains("PSK") 3341 && !config.configKey().contains("EAP")) { 3342 found = true; 3343 } 3344 3345 if (found) { 3346 numConfigFound ++; 3347 3348 if (config.autoJoinStatus >= WifiConfiguration.AUTO_JOIN_DELETED) { 3349 if (VVDBG) { 3350 loge("updateSavedNetworkHistory(): found a deleted, skip it... " 3351 + config.configKey()); 3352 } 3353 // The scan result belongs to a deleted config: 3354 // - increment numConfigFound to remember that we found a config 3355 // matching for this scan result 3356 // - dont do anything since the config was deleted, just skip... 3357 continue; 3358 } 3359 3360 if (config.scanResultCache == null) { 3361 config.scanResultCache = new HashMap<String, ScanResult>(); 3362 } 3363 3364 // Adding a new BSSID 3365 ScanResult result = config.scanResultCache.get(scanResult.BSSID); 3366 if (result == null) { 3367 config.dirty = true; 3368 } else { 3369 // transfer the black list status 3370 scanResult.autoJoinStatus = result.autoJoinStatus; 3371 scanResult.blackListTimestamp = result.blackListTimestamp; 3372 scanResult.numIpConfigFailures = result.numIpConfigFailures; 3373 scanResult.numConnection = result.numConnection; 3374 scanResult.isAutoJoinCandidate = result.isAutoJoinCandidate; 3375 } 3376 3377 if (config.ephemeral) { 3378 // For an ephemeral Wi-Fi config, the ScanResult should be considered 3379 // untrusted. 3380 scanResult.untrusted = true; 3381 } 3382 3383 if (config.scanResultCache.size() > (maxNumScanCacheEntries + 64)) { 3384 long now_dbg = 0; 3385 if (VVDBG) { 3386 loge(" Will trim config " + config.configKey() 3387 + " size " + config.scanResultCache.size()); 3388 3389 for (ScanResult r : config.scanResultCache.values()) { 3390 loge(" " + result.BSSID + " " + result.seen); 3391 } 3392 now_dbg = SystemClock.elapsedRealtimeNanos(); 3393 } 3394 // Trim the scan result cache to maxNumScanCacheEntries entries max 3395 // Since this operation is expensive, make sure it is not performed 3396 // until the cache has grown significantly above the trim treshold 3397 config.trimScanResultsCache(maxNumScanCacheEntries); 3398 if (VVDBG) { 3399 long diff = SystemClock.elapsedRealtimeNanos() - now_dbg; 3400 loge(" Finished trimming config, time(ns) " + diff); 3401 for (ScanResult r : config.scanResultCache.values()) { 3402 loge(" " + r.BSSID + " " + r.seen); 3403 } 3404 } 3405 } 3406 3407 // Add the scan result to this WifiConfiguration 3408 config.scanResultCache.put(scanResult.BSSID, scanResult); 3409 // Since we added a scan result to this configuration, re-attempt linking 3410 linkConfiguration(config); 3411 } 3412 3413 if (VDBG && found) { 3414 String status = ""; 3415 if (scanResult.autoJoinStatus > 0) { 3416 status = " status=" + Integer.toString(scanResult.autoJoinStatus); 3417 } 3418 loge(" got known scan result " + 3419 scanResult.BSSID + " key : " 3420 + config.configKey() + " num: " + 3421 Integer.toString(config.scanResultCache.size()) 3422 + " rssi=" + Integer.toString(scanResult.level) 3423 + " freq=" + Integer.toString(scanResult.frequency) 3424 + status); 3425 } 3426 } 3427 return numConfigFound != 0; 3428 } 3429 3430 /* Compare current and new configuration and write to file on change */ 3431 private NetworkUpdateResult writeIpAndProxyConfigurationsOnChange( 3432 WifiConfiguration currentConfig, 3433 WifiConfiguration newConfig) { 3434 boolean ipChanged = false; 3435 boolean proxyChanged = false; 3436 3437 if (VDBG) { 3438 loge("writeIpAndProxyConfigurationsOnChange: " + currentConfig.SSID + " -> " + 3439 newConfig.SSID + " path: " + ipConfigFile); 3440 } 3441 3442 3443 switch (newConfig.getIpAssignment()) { 3444 case STATIC: 3445 if (currentConfig.getIpAssignment() != newConfig.getIpAssignment()) { 3446 ipChanged = true; 3447 } else { 3448 ipChanged = !Objects.equals( 3449 currentConfig.getStaticIpConfiguration(), 3450 newConfig.getStaticIpConfiguration()); 3451 } 3452 break; 3453 case DHCP: 3454 if (currentConfig.getIpAssignment() != newConfig.getIpAssignment()) { 3455 ipChanged = true; 3456 } 3457 break; 3458 case UNASSIGNED: 3459 /* Ignore */ 3460 break; 3461 default: 3462 loge("Ignore invalid ip assignment during write"); 3463 break; 3464 } 3465 3466 switch (newConfig.getProxySettings()) { 3467 case STATIC: 3468 case PAC: 3469 ProxyInfo newHttpProxy = newConfig.getHttpProxy(); 3470 ProxyInfo currentHttpProxy = currentConfig.getHttpProxy(); 3471 3472 if (newHttpProxy != null) { 3473 proxyChanged = !newHttpProxy.equals(currentHttpProxy); 3474 } else { 3475 proxyChanged = (currentHttpProxy != null); 3476 } 3477 break; 3478 case NONE: 3479 if (currentConfig.getProxySettings() != newConfig.getProxySettings()) { 3480 proxyChanged = true; 3481 } 3482 break; 3483 case UNASSIGNED: 3484 /* Ignore */ 3485 break; 3486 default: 3487 loge("Ignore invalid proxy configuration during write"); 3488 break; 3489 } 3490 3491 if (ipChanged) { 3492 currentConfig.setIpAssignment(newConfig.getIpAssignment()); 3493 currentConfig.setStaticIpConfiguration(newConfig.getStaticIpConfiguration()); 3494 log("IP config changed SSID = " + currentConfig.SSID); 3495 if (currentConfig.getStaticIpConfiguration() != null) { 3496 log(" static configuration: " + 3497 currentConfig.getStaticIpConfiguration().toString()); 3498 } 3499 } 3500 3501 if (proxyChanged) { 3502 currentConfig.setProxySettings(newConfig.getProxySettings()); 3503 currentConfig.setHttpProxy(newConfig.getHttpProxy()); 3504 log("proxy changed SSID = " + currentConfig.SSID); 3505 if (currentConfig.getHttpProxy() != null) { 3506 log(" proxyProperties: " + currentConfig.getHttpProxy().toString()); 3507 } 3508 } 3509 3510 if (ipChanged || proxyChanged) { 3511 writeIpAndProxyConfigurations(); 3512 sendConfiguredNetworksChangedBroadcast(currentConfig, 3513 WifiManager.CHANGE_REASON_CONFIG_CHANGE); 3514 } 3515 return new NetworkUpdateResult(ipChanged, proxyChanged); 3516 } 3517 3518 /** Returns true if a particular config key needs to be quoted when passed to the supplicant. */ 3519 private boolean enterpriseConfigKeyShouldBeQuoted(String key) { 3520 switch (key) { 3521 case WifiEnterpriseConfig.EAP_KEY: 3522 case WifiEnterpriseConfig.ENGINE_KEY: 3523 return false; 3524 default: 3525 return true; 3526 } 3527 } 3528 3529 /** 3530 * Read the variables from the supplicant daemon that are needed to 3531 * fill in the WifiConfiguration object. 3532 * 3533 * @param config the {@link WifiConfiguration} object to be filled in. 3534 */ 3535 private void readNetworkVariables(WifiConfiguration config) { 3536 3537 int netId = config.networkId; 3538 if (netId < 0) 3539 return; 3540 3541 /* 3542 * TODO: maybe should have a native method that takes an array of 3543 * variable names and returns an array of values. But we'd still 3544 * be doing a round trip to the supplicant daemon for each variable. 3545 */ 3546 String value; 3547 3548 value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.ssidVarName); 3549 if (!TextUtils.isEmpty(value)) { 3550 if (value.charAt(0) != '"') { 3551 config.SSID = "\"" + WifiSsid.createFromHex(value).toString() + "\""; 3552 //TODO: convert a hex string that is not UTF-8 decodable to a P-formatted 3553 //supplicant string 3554 } else { 3555 config.SSID = value; 3556 } 3557 } else { 3558 config.SSID = null; 3559 } 3560 3561 value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.bssidVarName); 3562 if (!TextUtils.isEmpty(value)) { 3563 config.BSSID = value; 3564 } else { 3565 config.BSSID = null; 3566 } 3567 3568 value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.priorityVarName); 3569 config.priority = -1; 3570 if (!TextUtils.isEmpty(value)) { 3571 try { 3572 config.priority = Integer.parseInt(value); 3573 } catch (NumberFormatException ignore) { 3574 } 3575 } 3576 3577 value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName); 3578 config.hiddenSSID = false; 3579 if (!TextUtils.isEmpty(value)) { 3580 try { 3581 config.hiddenSSID = Integer.parseInt(value) != 0; 3582 } catch (NumberFormatException ignore) { 3583 } 3584 } 3585 3586 value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName); 3587 config.wepTxKeyIndex = -1; 3588 if (!TextUtils.isEmpty(value)) { 3589 try { 3590 config.wepTxKeyIndex = Integer.parseInt(value); 3591 } catch (NumberFormatException ignore) { 3592 } 3593 } 3594 3595 for (int i = 0; i < 4; i++) { 3596 value = mWifiNative.getNetworkVariable(netId, 3597 WifiConfiguration.wepKeyVarNames[i]); 3598 if (!TextUtils.isEmpty(value)) { 3599 config.wepKeys[i] = value; 3600 } else { 3601 config.wepKeys[i] = null; 3602 } 3603 } 3604 3605 value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.pskVarName); 3606 if (!TextUtils.isEmpty(value)) { 3607 config.preSharedKey = value; 3608 } else { 3609 config.preSharedKey = null; 3610 } 3611 3612 value = mWifiNative.getNetworkVariable(config.networkId, 3613 WifiConfiguration.Protocol.varName); 3614 if (!TextUtils.isEmpty(value)) { 3615 String vals[] = value.split(" "); 3616 for (String val : vals) { 3617 int index = 3618 lookupString(val, WifiConfiguration.Protocol.strings); 3619 if (0 <= index) { 3620 config.allowedProtocols.set(index); 3621 } 3622 } 3623 } 3624 3625 value = mWifiNative.getNetworkVariable(config.networkId, 3626 WifiConfiguration.KeyMgmt.varName); 3627 if (!TextUtils.isEmpty(value)) { 3628 String vals[] = value.split(" "); 3629 for (String val : vals) { 3630 int index = 3631 lookupString(val, WifiConfiguration.KeyMgmt.strings); 3632 if (0 <= index) { 3633 config.allowedKeyManagement.set(index); 3634 } 3635 } 3636 } 3637 3638 value = mWifiNative.getNetworkVariable(config.networkId, 3639 WifiConfiguration.AuthAlgorithm.varName); 3640 if (!TextUtils.isEmpty(value)) { 3641 String vals[] = value.split(" "); 3642 for (String val : vals) { 3643 int index = 3644 lookupString(val, WifiConfiguration.AuthAlgorithm.strings); 3645 if (0 <= index) { 3646 config.allowedAuthAlgorithms.set(index); 3647 } 3648 } 3649 } 3650 3651 value = mWifiNative.getNetworkVariable(config.networkId, 3652 WifiConfiguration.PairwiseCipher.varName); 3653 if (!TextUtils.isEmpty(value)) { 3654 String vals[] = value.split(" "); 3655 for (String val : vals) { 3656 int index = 3657 lookupString(val, WifiConfiguration.PairwiseCipher.strings); 3658 if (0 <= index) { 3659 config.allowedPairwiseCiphers.set(index); 3660 } 3661 } 3662 } 3663 3664 value = mWifiNative.getNetworkVariable(config.networkId, 3665 WifiConfiguration.GroupCipher.varName); 3666 if (!TextUtils.isEmpty(value)) { 3667 String vals[] = value.split(" "); 3668 for (String val : vals) { 3669 int index = 3670 lookupString(val, WifiConfiguration.GroupCipher.strings); 3671 if (0 <= index) { 3672 config.allowedGroupCiphers.set(index); 3673 } 3674 } 3675 } 3676 3677 if (config.enterpriseConfig == null) { 3678 config.enterpriseConfig = new WifiEnterpriseConfig(); 3679 } 3680 HashMap<String, String> enterpriseFields = config.enterpriseConfig.getFields(); 3681 for (String key : ENTERPRISE_CONFIG_SUPPLICANT_KEYS) { 3682 value = mWifiNative.getNetworkVariable(netId, key); 3683 if (!TextUtils.isEmpty(value)) { 3684 if (!enterpriseConfigKeyShouldBeQuoted(key)) { 3685 value = removeDoubleQuotes(value); 3686 } 3687 enterpriseFields.put(key, value); 3688 } else { 3689 enterpriseFields.put(key, EMPTY_VALUE); 3690 } 3691 } 3692 3693 if (migrateOldEapTlsNative(config.enterpriseConfig, netId)) { 3694 saveConfig(); 3695 } 3696 3697 migrateCerts(config.enterpriseConfig); 3698 // initializeSoftwareKeystoreFlag(config.enterpriseConfig, mKeyStore); 3699 } 3700 3701 private static String removeDoubleQuotes(String string) { 3702 int length = string.length(); 3703 if ((length > 1) && (string.charAt(0) == '"') 3704 && (string.charAt(length - 1) == '"')) { 3705 return string.substring(1, length - 1); 3706 } 3707 return string; 3708 } 3709 3710 private static String makeString(BitSet set, String[] strings) { 3711 StringBuffer buf = new StringBuffer(); 3712 int nextSetBit = -1; 3713 3714 /* Make sure all set bits are in [0, strings.length) to avoid 3715 * going out of bounds on strings. (Shouldn't happen, but...) */ 3716 set = set.get(0, strings.length); 3717 3718 while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) { 3719 buf.append(strings[nextSetBit].replace('_', '-')).append(' '); 3720 } 3721 3722 // remove trailing space 3723 if (set.cardinality() > 0) { 3724 buf.setLength(buf.length() - 1); 3725 } 3726 3727 return buf.toString(); 3728 } 3729 3730 private int lookupString(String string, String[] strings) { 3731 int size = strings.length; 3732 3733 string = string.replace('-', '_'); 3734 3735 for (int i = 0; i < size; i++) 3736 if (string.equals(strings[i])) 3737 return i; 3738 3739 // if we ever get here, we should probably add the 3740 // value to WifiConfiguration to reflect that it's 3741 // supported by the WPA supplicant 3742 loge("Failed to look-up a string: " + string); 3743 3744 return -1; 3745 } 3746 3747 /* return the allowed key management based on a scan result */ 3748 3749 public WifiConfiguration wifiConfigurationFromScanResult(ScanResult result) { 3750 WifiConfiguration config = new WifiConfiguration(); 3751 3752 config.SSID = "\"" + result.SSID + "\""; 3753 3754 if (VDBG) { 3755 loge("WifiConfiguration from scan results " + 3756 config.SSID + " cap " + result.capabilities); 3757 } 3758 if (result.capabilities.contains("WEP")) { 3759 config.allowedKeyManagement.set(KeyMgmt.NONE); 3760 config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); //? 3761 config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED); 3762 } 3763 3764 if (result.capabilities.contains("PSK")) { 3765 config.allowedKeyManagement.set(KeyMgmt.WPA_PSK); 3766 } 3767 3768 if (result.capabilities.contains("EAP")) { 3769 //this is probably wrong, as we don't have a way to enter the enterprise config 3770 config.allowedKeyManagement.set(KeyMgmt.WPA_EAP); 3771 config.allowedKeyManagement.set(KeyMgmt.IEEE8021X); 3772 } 3773 3774 config.scanResultCache = new HashMap<String, ScanResult>(); 3775 if (config.scanResultCache == null) 3776 return null; 3777 config.scanResultCache.put(result.BSSID, result); 3778 3779 return config; 3780 } 3781 3782 3783 /* Returns a unique for a given configuration */ 3784 private static int configKey(WifiConfiguration config) { 3785 String key = config.configKey(); 3786 return key.hashCode(); 3787 } 3788 3789 void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3790 pw.println("Dump of WifiConfigStore"); 3791 pw.println("mLastPriority " + mLastPriority); 3792 pw.println("Configured networks"); 3793 for (WifiConfiguration conf : getConfiguredNetworks()) { 3794 pw.println(conf); 3795 } 3796 pw.println(); 3797 3798 if (mLocalLog != null) { 3799 pw.println("WifiConfigStore - Log Begin ----"); 3800 mLocalLog.dump(fd, pw, args); 3801 pw.println("WifiConfigStore - Log End ----"); 3802 } 3803 } 3804 3805 public String getConfigFile() { 3806 return ipConfigFile; 3807 } 3808 3809 protected void loge(String s) { 3810 loge(s, false); 3811 } 3812 3813 protected void loge(String s, boolean stack) { 3814 if (stack) { 3815 Log.e(TAG, s + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName() 3816 + " - " + Thread.currentThread().getStackTrace()[3].getMethodName() 3817 + " - " + Thread.currentThread().getStackTrace()[4].getMethodName() 3818 + " - " + Thread.currentThread().getStackTrace()[5].getMethodName()); 3819 } else { 3820 Log.e(TAG, s); 3821 } 3822 } 3823 3824 protected void log(String s) { 3825 Log.d(TAG, s); 3826 } 3827 3828 private void localLog(String s) { 3829 if (mLocalLog != null) { 3830 mLocalLog.log(s); 3831 } 3832 } 3833 3834 private void localLog(String s, boolean force) { 3835 localLog(s); 3836 if (force) loge(s); 3837 } 3838 3839 private void localLog(String s, int netId) { 3840 if (mLocalLog == null) { 3841 return; 3842 } 3843 3844 WifiConfiguration config; 3845 synchronized(mConfiguredNetworks) { 3846 config = mConfiguredNetworks.get(netId); 3847 } 3848 3849 if (config != null) { 3850 mLocalLog.log(s + " " + config.getPrintableSsid() + " " + netId 3851 + " status=" + config.status 3852 + " key=" + config.configKey()); 3853 } else { 3854 mLocalLog.log(s + " " + netId); 3855 } 3856 } 3857 3858 // Certificate and private key management for EnterpriseConfig 3859 static boolean needsKeyStore(WifiEnterpriseConfig config) { 3860 // Has no keys to be installed 3861 if (config.getClientCertificate() == null && config.getCaCertificate() == null) 3862 return false; 3863 return true; 3864 } 3865 3866 static boolean isHardwareBackedKey(PrivateKey key) { 3867 return KeyChain.isBoundKeyAlgorithm(key.getAlgorithm()); 3868 } 3869 3870 static boolean hasHardwareBackedKey(Certificate certificate) { 3871 return KeyChain.isBoundKeyAlgorithm(certificate.getPublicKey().getAlgorithm()); 3872 } 3873 3874 static boolean needsSoftwareBackedKeyStore(WifiEnterpriseConfig config) { 3875 String client = config.getClientCertificateAlias(); 3876 if (!TextUtils.isEmpty(client)) { 3877 // a valid client certificate is configured 3878 3879 // BUGBUG: keyStore.get() never returns certBytes; because it is not 3880 // taking WIFI_UID as a parameter. It always looks for certificate 3881 // with SYSTEM_UID, and never finds any Wifi certificates. Assuming that 3882 // all certificates need software keystore until we get the get() API 3883 // fixed. 3884 3885 return true; 3886 } 3887 3888 /* 3889 try { 3890 3891 if (DBG) Slog.d(TAG, "Loading client certificate " + Credentials 3892 .USER_CERTIFICATE + client); 3893 3894 CertificateFactory factory = CertificateFactory.getInstance("X.509"); 3895 if (factory == null) { 3896 Slog.e(TAG, "Error getting certificate factory"); 3897 return; 3898 } 3899 3900 byte[] certBytes = keyStore.get(Credentials.USER_CERTIFICATE + client); 3901 if (certBytes != null) { 3902 Certificate cert = (X509Certificate) factory.generateCertificate( 3903 new ByteArrayInputStream(certBytes)); 3904 3905 if (cert != null) { 3906 mNeedsSoftwareKeystore = hasHardwareBackedKey(cert); 3907 3908 if (DBG) Slog.d(TAG, "Loaded client certificate " + Credentials 3909 .USER_CERTIFICATE + client); 3910 if (DBG) Slog.d(TAG, "It " + (mNeedsSoftwareKeystore ? "needs" : 3911 "does not need" ) + " software key store"); 3912 } else { 3913 Slog.d(TAG, "could not generate certificate"); 3914 } 3915 } else { 3916 Slog.e(TAG, "Could not load client certificate " + Credentials 3917 .USER_CERTIFICATE + client); 3918 mNeedsSoftwareKeystore = true; 3919 } 3920 3921 } catch(CertificateException e) { 3922 Slog.e(TAG, "Could not read certificates"); 3923 mCaCert = null; 3924 mClientCertificate = null; 3925 } 3926 */ 3927 3928 return false; 3929 } 3930 3931 /** called when CS ask WiFistateMachine to disconnect the current network 3932 * because the score is bad. 3933 */ 3934 void handleBadNetworkDisconnectReport(int netId, WifiInfo info) { 3935 /* TODO verify the bad network is current */ 3936 WifiConfiguration config = mConfiguredNetworks.get(netId); 3937 if (config != null) { 3938 if ((info.getRssi() < WifiConfiguration.UNWANTED_BLACKLIST_SOFT_RSSI_24 3939 && info.is24GHz()) || (info.getRssi() < 3940 WifiConfiguration.UNWANTED_BLACKLIST_SOFT_RSSI_5 && info.is5GHz())) { 3941 // We got disconnected and RSSI was bad, so disable light 3942 config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_TEMPORARY_DISABLED 3943 + WifiConfiguration.UNWANTED_BLACKLIST_SOFT_BUMP); 3944 loge("handleBadNetworkDisconnectReport (+4) " 3945 + Integer.toString(netId) + " " + info); 3946 } else { 3947 // We got disabled but RSSI is good, so disable hard 3948 config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_TEMPORARY_DISABLED 3949 + WifiConfiguration.UNWANTED_BLACKLIST_HARD_BUMP); 3950 loge("handleBadNetworkDisconnectReport (+8) " 3951 + Integer.toString(netId) + " " + info); 3952 } 3953 } 3954 // Record last time Connectivity Service switched us away from WiFi and onto Cell 3955 lastUnwantedNetworkDisconnectTimestamp = System.currentTimeMillis(); 3956 } 3957 3958 boolean handleBSSIDBlackList(int netId, String BSSID, boolean enable) { 3959 boolean found = false; 3960 if (BSSID == null) 3961 return found; 3962 3963 // Look for the BSSID in our config store 3964 for (WifiConfiguration config : mConfiguredNetworks.values()) { 3965 if (config.scanResultCache != null) { 3966 for (ScanResult result: config.scanResultCache.values()) { 3967 if (result.BSSID.equals(BSSID)) { 3968 if (enable) { 3969 result.setAutoJoinStatus(ScanResult.ENABLED); 3970 } else { 3971 // Black list the BSSID we were trying to join 3972 // so as the Roam state machine 3973 // doesn't pick it up over and over 3974 result.setAutoJoinStatus(ScanResult.AUTO_ROAM_DISABLED); 3975 found = true; 3976 } 3977 } 3978 } 3979 } 3980 } 3981 return found; 3982 } 3983 3984 int getMaxDhcpRetries() { 3985 return Settings.Global.getInt(mContext.getContentResolver(), 3986 Settings.Global.WIFI_MAX_DHCP_RETRY_COUNT, 3987 DEFAULT_MAX_DHCP_RETRIES); 3988 } 3989 3990 void handleSSIDStateChange(int netId, boolean enabled, String message, String BSSID) { 3991 WifiConfiguration config = mConfiguredNetworks.get(netId); 3992 if (config != null) { 3993 if (enabled) { 3994 loge("SSID re-enabled for " + config.configKey() + 3995 " had autoJoinStatus=" + Integer.toString(config.autoJoinStatus) 3996 + " self added " + config.selfAdded + " ephemeral " + config.ephemeral); 3997 //TODO: http://b/16381983 Fix Wifi Network Blacklisting 3998 //TODO: really I don't know if re-enabling is right but we 3999 //TODO: should err on the side of trying to connect 4000 //TODO: even if the attempt will fail 4001 if (config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE) { 4002 config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED); 4003 } 4004 } else { 4005 loge("SSID temp disabled for " + config.configKey() + 4006 " had autoJoinStatus=" + Integer.toString(config.autoJoinStatus) 4007 + " self added " + config.selfAdded + " ephemeral " + config.ephemeral); 4008 if (message != null) { 4009 loge(" message=" + message); 4010 } 4011 if (config.selfAdded && config.lastConnected == 0) { 4012 // This is a network we self added, and we never succeeded, 4013 // the user did not create this network and never entered its credentials, 4014 // so we want to be very aggressive in disabling it completely. 4015 removeConfigAndSendBroadcastIfNeeded(config.networkId); 4016 } else { 4017 if (message != null) { 4018 if (message.contains("no identity")) { 4019 config.setAutoJoinStatus( 4020 WifiConfiguration.AUTO_JOIN_DISABLED_NO_CREDENTIALS); 4021 if (DBG) { 4022 loge("no identity blacklisted " + config.configKey() + " to " 4023 + Integer.toString(config.autoJoinStatus)); 4024 } 4025 } else if (message.contains("WRONG_KEY") 4026 || message.contains("AUTH_FAILED")) { 4027 // This configuration has received an auth failure, so disable it 4028 // temporarily because we don't want auto-join to try it out. 4029 // this network may be re-enabled by the "usual" 4030 // enableAllNetwork function 4031 config.numAuthFailures++; 4032 if (config.numAuthFailures > maxAuthErrorsToBlacklist) { 4033 config.setAutoJoinStatus 4034 (WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE); 4035 disableNetwork(netId, 4036 WifiConfiguration.DISABLED_AUTH_FAILURE); 4037 loge("Authentication failure, blacklist " + config.configKey() + " " 4038 + Integer.toString(config.networkId) 4039 + " num failures " + config.numAuthFailures); 4040 } 4041 } else if (message.contains("DHCP FAILURE")) { 4042 config.numIpConfigFailures++; 4043 config.lastConnectionFailure = System.currentTimeMillis(); 4044 int maxRetries = getMaxDhcpRetries(); 4045 // maxRetries == 0 means keep trying forever 4046 if (maxRetries > 0 && config.numIpConfigFailures > maxRetries) { 4047 /** 4048 * If we've exceeded the maximum number of retries for DHCP 4049 * to a given network, disable the network 4050 */ 4051 config.setAutoJoinStatus 4052 (WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE); 4053 disableNetwork(netId, WifiConfiguration.DISABLED_DHCP_FAILURE); 4054 loge("DHCP failure, blacklist " + config.configKey() + " " 4055 + Integer.toString(config.networkId) 4056 + " num failures " + config.numIpConfigFailures); 4057 } 4058 4059 // Also blacklist the BSSId if we find it 4060 ScanResult result = null; 4061 String bssidDbg = ""; 4062 if (config.scanResultCache != null && BSSID != null) { 4063 result = config.scanResultCache.get(BSSID); 4064 } 4065 if (result != null) { 4066 result.numIpConfigFailures ++; 4067 bssidDbg = BSSID + " ipfail=" + result.numIpConfigFailures; 4068 if (result.numIpConfigFailures > 3) { 4069 // Tell supplicant to stop trying this BSSID 4070 mWifiNative.addToBlacklist(BSSID); 4071 result.setAutoJoinStatus(ScanResult.AUTO_JOIN_DISABLED); 4072 } 4073 } 4074 4075 if (DBG) { 4076 loge("blacklisted " + config.configKey() + " to " 4077 + config.autoJoinStatus 4078 + " due to IP config failures, count=" 4079 + config.numIpConfigFailures 4080 + " disableReason=" + config.disableReason 4081 + " " + bssidDbg); 4082 } 4083 } else if (message.contains("CONN_FAILED")) { 4084 config.numConnectionFailures++; 4085 if (config.numConnectionFailures > maxConnectionErrorsToBlacklist) { 4086 config.setAutoJoinStatus 4087 (WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE); 4088 disableNetwork(netId, 4089 WifiConfiguration.DISABLED_ASSOCIATION_REJECT); 4090 loge("Connection failure, blacklist " + config.configKey() + " " 4091 + config.networkId 4092 + " num failures " + config.numConnectionFailures); 4093 } 4094 } 4095 message.replace("\n", ""); 4096 message.replace("\r", ""); 4097 config.lastFailure = message; 4098 } 4099 } 4100 } 4101 } 4102 } 4103 4104 boolean installKeys(WifiEnterpriseConfig config, String name) { 4105 boolean ret = true; 4106 String privKeyName = Credentials.USER_PRIVATE_KEY + name; 4107 String userCertName = Credentials.USER_CERTIFICATE + name; 4108 String caCertName = Credentials.CA_CERTIFICATE + name; 4109 if (config.getClientCertificate() != null) { 4110 byte[] privKeyData = config.getClientPrivateKey().getEncoded(); 4111 if (isHardwareBackedKey(config.getClientPrivateKey())) { 4112 // Hardware backed key store is secure enough to store keys un-encrypted, this 4113 // removes the need for user to punch a PIN to get access to these keys 4114 if (DBG) Log.d(TAG, "importing keys " + name + " in hardware backed store"); 4115 ret = mKeyStore.importKey(privKeyName, privKeyData, android.os.Process.WIFI_UID, 4116 KeyStore.FLAG_NONE); 4117 } else { 4118 // Software backed key store is NOT secure enough to store keys un-encrypted. 4119 // Save keys encrypted so they are protected with user's PIN. User will 4120 // have to unlock phone before being able to use these keys and connect to 4121 // networks. 4122 if (DBG) Log.d(TAG, "importing keys " + name + " in software backed store"); 4123 ret = mKeyStore.importKey(privKeyName, privKeyData, Process.WIFI_UID, 4124 KeyStore.FLAG_ENCRYPTED); 4125 } 4126 if (ret == false) { 4127 return ret; 4128 } 4129 4130 ret = putCertInKeyStore(userCertName, config.getClientCertificate()); 4131 if (ret == false) { 4132 // Remove private key installed 4133 mKeyStore.delKey(privKeyName, Process.WIFI_UID); 4134 return ret; 4135 } 4136 } 4137 4138 if (config.getCaCertificate() != null) { 4139 ret = putCertInKeyStore(caCertName, config.getCaCertificate()); 4140 if (ret == false) { 4141 if (config.getClientCertificate() != null) { 4142 // Remove client key+cert 4143 mKeyStore.delKey(privKeyName, Process.WIFI_UID); 4144 mKeyStore.delete(userCertName, Process.WIFI_UID); 4145 } 4146 return ret; 4147 } 4148 } 4149 4150 // Set alias names 4151 if (config.getClientCertificate() != null) { 4152 config.setClientCertificateAlias(name); 4153 config.resetClientKeyEntry(); 4154 } 4155 4156 if (config.getCaCertificate() != null) { 4157 config.setCaCertificateAlias(name); 4158 config.resetCaCertificate(); 4159 } 4160 4161 return ret; 4162 } 4163 4164 private boolean putCertInKeyStore(String name, Certificate cert) { 4165 try { 4166 byte[] certData = Credentials.convertToPem(cert); 4167 if (DBG) Log.d(TAG, "putting certificate " + name + " in keystore"); 4168 return mKeyStore.put(name, certData, Process.WIFI_UID, KeyStore.FLAG_NONE); 4169 4170 } catch (IOException e1) { 4171 return false; 4172 } catch (CertificateException e2) { 4173 return false; 4174 } 4175 } 4176 4177 void removeKeys(WifiEnterpriseConfig config) { 4178 String client = config.getClientCertificateAlias(); 4179 // a valid client certificate is configured 4180 if (!TextUtils.isEmpty(client)) { 4181 if (DBG) Log.d(TAG, "removing client private key and user cert"); 4182 mKeyStore.delKey(Credentials.USER_PRIVATE_KEY + client, Process.WIFI_UID); 4183 mKeyStore.delete(Credentials.USER_CERTIFICATE + client, Process.WIFI_UID); 4184 } 4185 4186 String ca = config.getCaCertificateAlias(); 4187 // a valid ca certificate is configured 4188 if (!TextUtils.isEmpty(ca)) { 4189 if (DBG) Log.d(TAG, "removing CA cert"); 4190 mKeyStore.delete(Credentials.CA_CERTIFICATE + ca, Process.WIFI_UID); 4191 } 4192 } 4193 4194 4195 /** Migrates the old style TLS config to the new config style. This should only be used 4196 * when restoring an old wpa_supplicant.conf or upgrading from a previous 4197 * platform version. 4198 * @return true if the config was updated 4199 * @hide 4200 */ 4201 boolean migrateOldEapTlsNative(WifiEnterpriseConfig config, int netId) { 4202 String oldPrivateKey = mWifiNative.getNetworkVariable(netId, OLD_PRIVATE_KEY_NAME); 4203 /* 4204 * If the old configuration value is not present, then there is nothing 4205 * to do. 4206 */ 4207 if (TextUtils.isEmpty(oldPrivateKey)) { 4208 return false; 4209 } else { 4210 // Also ignore it if it's empty quotes. 4211 oldPrivateKey = removeDoubleQuotes(oldPrivateKey); 4212 if (TextUtils.isEmpty(oldPrivateKey)) { 4213 return false; 4214 } 4215 } 4216 4217 config.setFieldValue(WifiEnterpriseConfig.ENGINE_KEY, WifiEnterpriseConfig.ENGINE_ENABLE); 4218 config.setFieldValue(WifiEnterpriseConfig.ENGINE_ID_KEY, 4219 WifiEnterpriseConfig.ENGINE_ID_KEYSTORE); 4220 4221 /* 4222 * The old key started with the keystore:// URI prefix, but we don't 4223 * need that anymore. Trim it off if it exists. 4224 */ 4225 final String keyName; 4226 if (oldPrivateKey.startsWith(WifiEnterpriseConfig.KEYSTORE_URI)) { 4227 keyName = new String( 4228 oldPrivateKey.substring(WifiEnterpriseConfig.KEYSTORE_URI.length())); 4229 } else { 4230 keyName = oldPrivateKey; 4231 } 4232 config.setFieldValue(WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY, keyName); 4233 4234 mWifiNative.setNetworkVariable(netId, WifiEnterpriseConfig.ENGINE_KEY, 4235 config.getFieldValue(WifiEnterpriseConfig.ENGINE_KEY, "")); 4236 4237 mWifiNative.setNetworkVariable(netId, WifiEnterpriseConfig.ENGINE_ID_KEY, 4238 config.getFieldValue(WifiEnterpriseConfig.ENGINE_ID_KEY, "")); 4239 4240 mWifiNative.setNetworkVariable(netId, WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY, 4241 config.getFieldValue(WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY, "")); 4242 4243 // Remove old private_key string so we don't run this again. 4244 mWifiNative.setNetworkVariable(netId, OLD_PRIVATE_KEY_NAME, EMPTY_VALUE); 4245 4246 return true; 4247 } 4248 4249 /** Migrate certs from global pool to wifi UID if not already done */ 4250 void migrateCerts(WifiEnterpriseConfig config) { 4251 String client = config.getClientCertificateAlias(); 4252 // a valid client certificate is configured 4253 if (!TextUtils.isEmpty(client)) { 4254 if (!mKeyStore.contains(Credentials.USER_PRIVATE_KEY + client, Process.WIFI_UID)) { 4255 mKeyStore.duplicate(Credentials.USER_PRIVATE_KEY + client, -1, 4256 Credentials.USER_PRIVATE_KEY + client, Process.WIFI_UID); 4257 mKeyStore.duplicate(Credentials.USER_CERTIFICATE + client, -1, 4258 Credentials.USER_CERTIFICATE + client, Process.WIFI_UID); 4259 } 4260 } 4261 4262 String ca = config.getCaCertificateAlias(); 4263 // a valid ca certificate is configured 4264 if (!TextUtils.isEmpty(ca)) { 4265 if (!mKeyStore.contains(Credentials.CA_CERTIFICATE + ca, Process.WIFI_UID)) { 4266 mKeyStore.duplicate(Credentials.CA_CERTIFICATE + ca, -1, 4267 Credentials.CA_CERTIFICATE + ca, Process.WIFI_UID); 4268 } 4269 } 4270 } 4271 4272} 4273