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