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