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