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