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