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