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