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