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