WifiConfigManagerTest.java revision 0f166e9103c4ef46eaa49ad20359ce0db2ef9791
1/* 2 * Copyright (C) 2016 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 org.junit.Assert.*; 20import static org.mockito.Mockito.*; 21 22import android.app.Application; 23import android.app.test.MockAnswerUtil.AnswerWithArguments; 24import android.content.Context; 25import android.content.Intent; 26import android.content.pm.ApplicationInfo; 27import android.content.pm.PackageManager; 28import android.content.pm.UserInfo; 29import android.net.IpConfiguration; 30import android.net.wifi.ScanResult; 31import android.net.wifi.WifiConfiguration; 32import android.net.wifi.WifiConfiguration.NetworkSelectionStatus; 33import android.net.wifi.WifiEnterpriseConfig; 34import android.net.wifi.WifiManager; 35import android.net.wifi.WifiScanner; 36import android.net.wifi.WifiSsid; 37import android.os.UserHandle; 38import android.os.UserManager; 39import android.telephony.TelephonyManager; 40import android.test.suitebuilder.annotation.SmallTest; 41import android.text.TextUtils; 42 43import com.android.internal.R; 44import com.android.server.wifi.WifiConfigStoreLegacy.WifiConfigStoreDataLegacy; 45 46import org.junit.After; 47import org.junit.Before; 48import org.junit.Test; 49import org.mockito.ArgumentCaptor; 50import org.mockito.InOrder; 51import org.mockito.Mock; 52import org.mockito.MockitoAnnotations; 53 54import java.util.ArrayList; 55import java.util.Arrays; 56import java.util.HashSet; 57import java.util.List; 58import java.util.Set; 59 60/** 61 * Unit tests for {@link com.android.server.wifi.WifiConfigManager}. 62 */ 63@SmallTest 64public class WifiConfigManagerTest { 65 66 private static final String TEST_BSSID = "0a:08:5c:67:89:00"; 67 private static final long TEST_WALLCLOCK_CREATION_TIME_MILLIS = 9845637; 68 private static final long TEST_WALLCLOCK_UPDATE_TIME_MILLIS = 75455637; 69 private static final long TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS = 29457631; 70 private static final int TEST_CREATOR_UID = 5; 71 private static final int TEST_UPDATE_UID = 4; 72 private static final int TEST_SYSUI_UID = 56; 73 private static final int TEST_DEFAULT_USER = UserHandle.USER_SYSTEM; 74 private static final int TEST_MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCAN = 5; 75 private static final Integer[] TEST_FREQ_LIST = {2400, 2450, 5150, 5175, 5650}; 76 private static final String TEST_CREATOR_NAME = "com.wificonfigmanagerNew.creator"; 77 private static final String TEST_UPDATE_NAME = "com.wificonfigmanagerNew.update"; 78 private static final String TEST_DEFAULT_GW_MAC_ADDRESS = "0f:67:ad:ef:09:34"; 79 80 @Mock private Context mContext; 81 @Mock private FrameworkFacade mFrameworkFacade; 82 @Mock private Clock mClock; 83 @Mock private UserManager mUserManager; 84 @Mock private TelephonyManager mTelephonyManager; 85 @Mock private WifiKeyStore mWifiKeyStore; 86 @Mock private WifiConfigStore mWifiConfigStore; 87 @Mock private WifiConfigStoreLegacy mWifiConfigStoreLegacy; 88 @Mock private PackageManager mPackageManager; 89 90 private MockResources mResources; 91 private InOrder mContextConfigStoreMockOrder; 92 private WifiConfigManager mWifiConfigManager; 93 94 /** 95 * Setup the mocks and an instance of WifiConfigManager before each test. 96 */ 97 @Before 98 public void setUp() throws Exception { 99 MockitoAnnotations.initMocks(this); 100 101 // Set up the inorder for verifications. This is needed to verify that the broadcasts, 102 // store writes for network updates followed by network additions are in the expected order. 103 mContextConfigStoreMockOrder = inOrder(mContext, mWifiConfigStore); 104 105 // Set up the package name stuff & permission override. 106 when(mContext.getPackageManager()).thenReturn(mPackageManager); 107 mResources = new MockResources(); 108 mResources.setBoolean( 109 R.bool.config_wifi_only_link_same_credential_configurations, true); 110 mResources.setInteger( 111 R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels, 112 TEST_MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCAN); 113 when(mContext.getResources()).thenReturn(mResources); 114 115 // Setup UserManager profiles for the default user. 116 setupUserProfiles(TEST_DEFAULT_USER); 117 118 doAnswer(new AnswerWithArguments() { 119 public String answer(int uid) throws Exception { 120 if (uid == TEST_CREATOR_UID) { 121 return TEST_CREATOR_NAME; 122 } else if (uid == TEST_UPDATE_UID) { 123 return TEST_UPDATE_NAME; 124 } else if (uid == TEST_SYSUI_UID) { 125 return WifiConfigManager.SYSUI_PACKAGE_NAME; 126 } 127 fail("Unexpected UID: " + uid); 128 return ""; 129 } 130 }).when(mPackageManager).getNameForUid(anyInt()); 131 doAnswer(new AnswerWithArguments() { 132 public int answer(String packageName, int flags, int userId) throws Exception { 133 if (packageName.equals(WifiConfigManager.SYSUI_PACKAGE_NAME)) { 134 return TEST_SYSUI_UID; 135 } else { 136 return 0; 137 } 138 } 139 }).when(mPackageManager).getPackageUidAsUser(anyString(), anyInt(), anyInt()); 140 141 // Both the UID's in the test have the configuration override permission granted by 142 // default. This maybe modified for particular tests if needed. 143 doAnswer(new AnswerWithArguments() { 144 public int answer(String permName, int uid) throws Exception { 145 if (uid == TEST_CREATOR_UID || uid == TEST_UPDATE_UID) { 146 return PackageManager.PERMISSION_GRANTED; 147 } 148 return PackageManager.PERMISSION_DENIED; 149 } 150 }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt()); 151 152 when(mWifiKeyStore 153 .updateNetworkKeys(any(WifiConfiguration.class), any(WifiConfiguration.class))) 154 .thenReturn(true); 155 156 when(mWifiConfigStore.areStoresPresent()).thenReturn(true); 157 158 createWifiConfigManager(); 159 } 160 161 /** 162 * Called after each test 163 */ 164 @After 165 public void cleanup() { 166 validateMockitoUsage(); 167 } 168 169 /** 170 * Verifies the addition of a single network using 171 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 172 */ 173 @Test 174 public void testAddSingleOpenNetwork() { 175 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 176 List<WifiConfiguration> networks = new ArrayList<>(); 177 networks.add(openNetwork); 178 179 verifyAddNetworkToWifiConfigManager(openNetwork); 180 181 List<WifiConfiguration> retrievedNetworks = 182 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 183 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 184 networks, retrievedNetworks); 185 } 186 187 /** 188 * Verifies the modification of a single network using 189 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 190 */ 191 @Test 192 public void testUpdateSingleOpenNetwork() { 193 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 194 List<WifiConfiguration> networks = new ArrayList<>(); 195 networks.add(openNetwork); 196 197 verifyAddNetworkToWifiConfigManager(openNetwork); 198 199 // Now change BSSID for the network. 200 assertAndSetNetworkBSSID(openNetwork, TEST_BSSID); 201 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork); 202 203 // Now verify that the modification has been effective. 204 List<WifiConfiguration> retrievedNetworks = 205 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 206 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 207 networks, retrievedNetworks); 208 } 209 210 /** 211 * Verifies the addition of a single ephemeral network using 212 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that 213 * the {@link WifiConfigManager#getSavedNetworks()} does not return this network. 214 */ 215 @Test 216 public void testAddSingleEphemeralNetwork() { 217 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 218 openNetwork.ephemeral = true; 219 List<WifiConfiguration> networks = new ArrayList<>(); 220 networks.add(openNetwork); 221 222 verifyAddEphemeralNetworkToWifiConfigManager(openNetwork); 223 224 List<WifiConfiguration> retrievedNetworks = 225 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 226 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 227 networks, retrievedNetworks); 228 229 // Ensure that this is not returned in the saved network list. 230 assertTrue(mWifiConfigManager.getSavedNetworks().isEmpty()); 231 } 232 233 /** 234 * Verifies that the modification of a single open network using 235 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with a UID which 236 * has no permission to modify the network fails. 237 */ 238 @Test 239 public void testUpdateSingleOpenNetworkFailedDueToPermissionDenied() throws Exception { 240 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 241 List<WifiConfiguration> networks = new ArrayList<>(); 242 networks.add(openNetwork); 243 244 verifyAddNetworkToWifiConfigManager(openNetwork); 245 246 // Now change BSSID of the network. 247 assertAndSetNetworkBSSID(openNetwork, TEST_BSSID); 248 249 // Deny permission for |UPDATE_UID|. 250 doAnswer(new AnswerWithArguments() { 251 public int answer(String permName, int uid) throws Exception { 252 if (uid == TEST_CREATOR_UID) { 253 return PackageManager.PERMISSION_GRANTED; 254 } 255 return PackageManager.PERMISSION_DENIED; 256 } 257 }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt()); 258 259 // Update the same configuration and ensure that the operation failed. 260 NetworkUpdateResult result = updateNetworkToWifiConfigManager(openNetwork); 261 assertTrue(result.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID); 262 } 263 264 /** 265 * Verifies that the modification of a single open network using 266 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with the creator UID 267 * should always succeed. 268 */ 269 @Test 270 public void testUpdateSingleOpenNetworkSuccessWithCreatorUID() throws Exception { 271 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 272 List<WifiConfiguration> networks = new ArrayList<>(); 273 networks.add(openNetwork); 274 275 verifyAddNetworkToWifiConfigManager(openNetwork); 276 277 // Now change BSSID of the network. 278 assertAndSetNetworkBSSID(openNetwork, TEST_BSSID); 279 280 // Deny permission for all UIDs. 281 doAnswer(new AnswerWithArguments() { 282 public int answer(String permName, int uid) throws Exception { 283 return PackageManager.PERMISSION_DENIED; 284 } 285 }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt()); 286 287 // Update the same configuration using the creator UID. 288 NetworkUpdateResult result = 289 mWifiConfigManager.addOrUpdateNetwork(openNetwork, TEST_CREATOR_UID); 290 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 291 292 // Now verify that the modification has been effective. 293 List<WifiConfiguration> retrievedNetworks = 294 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 295 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 296 networks, retrievedNetworks); 297 } 298 299 /** 300 * Verifies the addition of a single PSK network using 301 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that 302 * {@link WifiConfigManager#getSavedNetworks()} masks the password. 303 */ 304 @Test 305 public void testAddSinglePskNetwork() { 306 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 307 List<WifiConfiguration> networks = new ArrayList<>(); 308 networks.add(pskNetwork); 309 310 verifyAddNetworkToWifiConfigManager(pskNetwork); 311 312 List<WifiConfiguration> retrievedNetworks = 313 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 314 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 315 networks, retrievedNetworks); 316 317 List<WifiConfiguration> retrievedSavedNetworks = mWifiConfigManager.getSavedNetworks(); 318 assertEquals(retrievedSavedNetworks.size(), 1); 319 assertEquals(retrievedSavedNetworks.get(0).configKey(), pskNetwork.configKey()); 320 assertPasswordsMaskedInWifiConfiguration(retrievedSavedNetworks.get(0)); 321 } 322 323 /** 324 * Verifies the addition of a single WEP network using 325 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that 326 * {@link WifiConfigManager#getSavedNetworks()} masks the password. 327 */ 328 @Test 329 public void testAddSingleWepNetwork() { 330 WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork(); 331 List<WifiConfiguration> networks = new ArrayList<>(); 332 networks.add(wepNetwork); 333 334 verifyAddNetworkToWifiConfigManager(wepNetwork); 335 336 List<WifiConfiguration> retrievedNetworks = 337 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 338 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 339 networks, retrievedNetworks); 340 341 List<WifiConfiguration> retrievedSavedNetworks = mWifiConfigManager.getSavedNetworks(); 342 assertEquals(retrievedSavedNetworks.size(), 1); 343 assertEquals(retrievedSavedNetworks.get(0).configKey(), wepNetwork.configKey()); 344 assertPasswordsMaskedInWifiConfiguration(retrievedSavedNetworks.get(0)); 345 } 346 347 /** 348 * Verifies the modification of an IpConfiguration using 349 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 350 */ 351 @Test 352 public void testUpdateIpConfiguration() { 353 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 354 List<WifiConfiguration> networks = new ArrayList<>(); 355 networks.add(openNetwork); 356 357 verifyAddNetworkToWifiConfigManager(openNetwork); 358 359 // Now change BSSID of the network. 360 assertAndSetNetworkBSSID(openNetwork, TEST_BSSID); 361 362 // Update the same configuration and ensure that the IP configuration change flags 363 // are not set. 364 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork); 365 366 // Change the IpConfiguration now and ensure that the IP configuration flags are set now. 367 assertAndSetNetworkIpConfiguration( 368 openNetwork, 369 WifiConfigurationTestUtil.createStaticIpConfigurationWithStaticProxy()); 370 verifyUpdateNetworkToWifiConfigManagerWithIpChange(openNetwork); 371 372 // Now verify that all the modifications have been effective. 373 List<WifiConfiguration> retrievedNetworks = 374 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 375 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 376 networks, retrievedNetworks); 377 } 378 379 /** 380 * Verifies the removal of a single network using 381 * {@link WifiConfigManager#removeNetwork(int)} 382 */ 383 @Test 384 public void testRemoveSingleOpenNetwork() { 385 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 386 List<WifiConfiguration> networks = new ArrayList<>(); 387 networks.add(openNetwork); 388 389 verifyAddNetworkToWifiConfigManager(openNetwork); 390 391 verifyRemoveNetworkFromWifiConfigManager(openNetwork); 392 393 // Ensure that configured network list is empty now. 394 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 395 } 396 397 /** 398 * Verifies the addition & update of multiple networks using 399 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and the 400 * removal of networks using 401 * {@link WifiConfigManager#removeNetwork(int)} 402 */ 403 @Test 404 public void testAddUpdateRemoveMultipleNetworks() { 405 List<WifiConfiguration> networks = new ArrayList<>(); 406 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 407 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 408 WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork(); 409 networks.add(openNetwork); 410 networks.add(pskNetwork); 411 networks.add(wepNetwork); 412 413 verifyAddNetworkToWifiConfigManager(openNetwork); 414 verifyAddNetworkToWifiConfigManager(pskNetwork); 415 verifyAddNetworkToWifiConfigManager(wepNetwork); 416 417 // Now verify that all the additions has been effective. 418 List<WifiConfiguration> retrievedNetworks = 419 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 420 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 421 networks, retrievedNetworks); 422 423 // Modify all the 3 configurations and update it to WifiConfigManager. 424 assertAndSetNetworkBSSID(openNetwork, TEST_BSSID); 425 assertAndSetNetworkBSSID(pskNetwork, TEST_BSSID); 426 assertAndSetNetworkIpConfiguration( 427 wepNetwork, 428 WifiConfigurationTestUtil.createStaticIpConfigurationWithPacProxy()); 429 430 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork); 431 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(pskNetwork); 432 verifyUpdateNetworkToWifiConfigManagerWithIpChange(wepNetwork); 433 // Now verify that all the modifications has been effective. 434 retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords(); 435 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 436 networks, retrievedNetworks); 437 438 // Now remove all 3 networks. 439 verifyRemoveNetworkFromWifiConfigManager(openNetwork); 440 verifyRemoveNetworkFromWifiConfigManager(pskNetwork); 441 verifyRemoveNetworkFromWifiConfigManager(wepNetwork); 442 443 // Ensure that configured network list is empty now. 444 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 445 } 446 447 /** 448 * Verifies the update of network status using 449 * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)}. 450 */ 451 @Test 452 public void testNetworkSelectionStatus() { 453 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 454 455 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 456 457 // First set it to enabled. 458 verifyUpdateNetworkSelectionStatus( 459 result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 460 461 // Now set it to temporarily disabled. The threshold for association rejection is 5, so 462 // disable it 5 times to actually mark it temporarily disabled. 463 int assocRejectReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION; 464 int assocRejectThreshold = 465 WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[assocRejectReason]; 466 for (int i = 1; i <= assocRejectThreshold; i++) { 467 verifyUpdateNetworkSelectionStatus(result.getNetworkId(), assocRejectReason, i); 468 } 469 470 // Now set it to permanently disabled. 471 verifyUpdateNetworkSelectionStatus( 472 result.getNetworkId(), NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER, 0); 473 474 // Now set it back to enabled. 475 verifyUpdateNetworkSelectionStatus( 476 result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 477 } 478 479 /** 480 * Verifies the update of network status using 481 * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)} and ensures that 482 * enabling a network clears out all the temporary disable counters. 483 */ 484 @Test 485 public void testNetworkSelectionStatusEnableClearsDisableCounters() { 486 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 487 488 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 489 490 // First set it to enabled. 491 verifyUpdateNetworkSelectionStatus( 492 result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 493 494 // Now set it to temporarily disabled 2 times for 2 different reasons. 495 verifyUpdateNetworkSelectionStatus( 496 result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 1); 497 verifyUpdateNetworkSelectionStatus( 498 result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 2); 499 verifyUpdateNetworkSelectionStatus( 500 result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 1); 501 verifyUpdateNetworkSelectionStatus( 502 result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 2); 503 504 // Now set it back to enabled. 505 verifyUpdateNetworkSelectionStatus( 506 result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 507 508 // Ensure that the counters have all been reset now. 509 verifyUpdateNetworkSelectionStatus( 510 result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 1); 511 verifyUpdateNetworkSelectionStatus( 512 result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 1); 513 } 514 515 /** 516 * Verifies the enabling of temporarily disabled network using 517 * {@link WifiConfigManager#tryEnableNetwork(int)}. 518 */ 519 @Test 520 public void testTryEnableNetwork() { 521 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 522 523 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 524 525 // First set it to enabled. 526 verifyUpdateNetworkSelectionStatus( 527 result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0); 528 529 // Now set it to temporarily disabled. The threshold for association rejection is 5, so 530 // disable it 5 times to actually mark it temporarily disabled. 531 int assocRejectReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION; 532 int assocRejectThreshold = 533 WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[assocRejectReason]; 534 for (int i = 1; i <= assocRejectThreshold; i++) { 535 verifyUpdateNetworkSelectionStatus(result.getNetworkId(), assocRejectReason, i); 536 } 537 538 // Now let's try enabling this network without changing the time, this should fail and the 539 // status remains temporarily disabled. 540 assertFalse(mWifiConfigManager.tryEnableNetwork(result.getNetworkId())); 541 NetworkSelectionStatus retrievedStatus = 542 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()) 543 .getNetworkSelectionStatus(); 544 assertTrue(retrievedStatus.isNetworkTemporaryDisabled()); 545 546 // Now advance time by the timeout for association rejection and ensure that the network 547 // is now enabled. 548 int assocRejectTimeout = 549 WifiConfigManager.NETWORK_SELECTION_DISABLE_TIMEOUT_MS[assocRejectReason]; 550 when(mClock.getElapsedSinceBootMillis()) 551 .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS + assocRejectTimeout); 552 553 assertTrue(mWifiConfigManager.tryEnableNetwork(result.getNetworkId())); 554 retrievedStatus = 555 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()) 556 .getNetworkSelectionStatus(); 557 assertTrue(retrievedStatus.isNetworkEnabled()); 558 } 559 560 /** 561 * Verifies the enabling of network using 562 * {@link WifiConfigManager#enableNetwork(int, boolean, int)} and 563 * {@link WifiConfigManager#disableNetwork(int, int)}. 564 */ 565 @Test 566 public void testEnableDisableNetwork() { 567 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 568 569 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 570 571 assertTrue(mWifiConfigManager.enableNetwork( 572 result.getNetworkId(), false, TEST_CREATOR_UID)); 573 WifiConfiguration retrievedNetwork = 574 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 575 NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus(); 576 assertTrue(retrievedStatus.isNetworkEnabled()); 577 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED); 578 579 // Now set it disabled. 580 assertTrue(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_CREATOR_UID)); 581 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 582 retrievedStatus = retrievedNetwork.getNetworkSelectionStatus(); 583 assertTrue(retrievedStatus.isNetworkPermanentlyDisabled()); 584 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED); 585 } 586 587 /** 588 * Verifies the enabling of network using 589 * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with a UID which 590 * has no permission to modify the network fails.. 591 */ 592 @Test 593 public void testEnableDisableNetworkFailedDueToPermissionDenied() throws Exception { 594 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 595 596 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 597 598 assertTrue(mWifiConfigManager.enableNetwork( 599 result.getNetworkId(), false, TEST_CREATOR_UID)); 600 WifiConfiguration retrievedNetwork = 601 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 602 NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus(); 603 assertTrue(retrievedStatus.isNetworkEnabled()); 604 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED); 605 606 // Deny permission for |UPDATE_UID|. 607 doAnswer(new AnswerWithArguments() { 608 public int answer(String permName, int uid) throws Exception { 609 if (uid == TEST_CREATOR_UID) { 610 return PackageManager.PERMISSION_GRANTED; 611 } 612 return PackageManager.PERMISSION_DENIED; 613 } 614 }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt()); 615 616 // Now try to set it disabled with |TEST_UPDATE_UID|, it should fail and the network 617 // should remain enabled. 618 assertFalse(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_UPDATE_UID)); 619 retrievedStatus = 620 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()) 621 .getNetworkSelectionStatus(); 622 assertTrue(retrievedStatus.isNetworkEnabled()); 623 assertEquals(WifiConfiguration.Status.ENABLED, retrievedNetwork.status); 624 } 625 626 /** 627 * Verifies the updation of network's connectUid using 628 * {@link WifiConfigManager#checkAndUpdateLastConnectUid(int, int)}. 629 */ 630 @Test 631 public void testUpdateLastConnectUid() throws Exception { 632 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 633 634 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 635 636 assertTrue( 637 mWifiConfigManager.checkAndUpdateLastConnectUid( 638 result.getNetworkId(), TEST_CREATOR_UID)); 639 WifiConfiguration retrievedNetwork = 640 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 641 assertEquals(TEST_CREATOR_UID, retrievedNetwork.lastConnectUid); 642 643 // Deny permission for |UPDATE_UID|. 644 doAnswer(new AnswerWithArguments() { 645 public int answer(String permName, int uid) throws Exception { 646 if (uid == TEST_CREATOR_UID) { 647 return PackageManager.PERMISSION_GRANTED; 648 } 649 return PackageManager.PERMISSION_DENIED; 650 } 651 }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt()); 652 653 // Now try to update the last connect UID with |TEST_UPDATE_UID|, it should fail and 654 // the lastConnectUid should remain the same. 655 assertFalse( 656 mWifiConfigManager.checkAndUpdateLastConnectUid( 657 result.getNetworkId(), TEST_UPDATE_UID)); 658 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 659 assertEquals(TEST_CREATOR_UID, retrievedNetwork.lastConnectUid); 660 } 661 662 /** 663 * Verifies that any configuration update attempt with an null config is gracefully 664 * handled. 665 * This invokes {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}. 666 */ 667 @Test 668 public void testAddOrUpdateNetworkWithNullConfig() { 669 NetworkUpdateResult result = mWifiConfigManager.addOrUpdateNetwork(null, TEST_CREATOR_UID); 670 assertFalse(result.isSuccess()); 671 } 672 673 /** 674 * Verifies that any configuration removal attempt with an invalid networkID is gracefully 675 * handled. 676 * This invokes {@link WifiConfigManager#removeNetwork(int)}. 677 */ 678 @Test 679 public void testRemoveNetworkWithInvalidNetworkId() { 680 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 681 682 verifyAddNetworkToWifiConfigManager(openNetwork); 683 684 // Change the networkID to an invalid one. 685 openNetwork.networkId++; 686 assertFalse(mWifiConfigManager.removeNetwork(openNetwork.networkId, TEST_CREATOR_UID)); 687 } 688 689 /** 690 * Verifies that any configuration update attempt with an invalid networkID is gracefully 691 * handled. 692 * This invokes {@link WifiConfigManager#enableNetwork(int, boolean, int)}, 693 * {@link WifiConfigManager#disableNetwork(int, int)}, 694 * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)} and 695 * {@link WifiConfigManager#checkAndUpdateLastConnectUid(int, int)}. 696 */ 697 @Test 698 public void testChangeConfigurationWithInvalidNetworkId() { 699 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 700 701 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 702 703 assertFalse(mWifiConfigManager.enableNetwork( 704 result.getNetworkId() + 1, false, TEST_CREATOR_UID)); 705 assertFalse(mWifiConfigManager.disableNetwork(result.getNetworkId() + 1, TEST_CREATOR_UID)); 706 assertFalse(mWifiConfigManager.updateNetworkSelectionStatus( 707 result.getNetworkId() + 1, NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER)); 708 assertFalse(mWifiConfigManager.checkAndUpdateLastConnectUid( 709 result.getNetworkId() + 1, TEST_CREATOR_UID)); 710 } 711 712 /** 713 * Verifies multiple modification of a single network using 714 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}. 715 * This test is basically checking if the apps can reset some of the fields of the config after 716 * addition. The fields being reset in this test are the |preSharedKey| and |wepKeys|. 717 * 1. Create an open network initially. 718 * 2. Modify the added network config to a WEP network config with all the 4 keys set. 719 * 3. Modify the added network config to a WEP network config with only 1 key set. 720 * 4. Modify the added network config to a PSK network config. 721 */ 722 @Test 723 public void testMultipleUpdatesSingleNetwork() { 724 WifiConfiguration network = WifiConfigurationTestUtil.createOpenNetwork(); 725 verifyAddNetworkToWifiConfigManager(network); 726 727 // Now add |wepKeys| to the network. We don't need to update the |allowedKeyManagement| 728 // fields for open to WEP conversion. 729 String[] wepKeys = 730 Arrays.copyOf(WifiConfigurationTestUtil.TEST_WEP_KEYS, 731 WifiConfigurationTestUtil.TEST_WEP_KEYS.length); 732 int wepTxKeyIdx = WifiConfigurationTestUtil.TEST_WEP_TX_KEY_INDEX; 733 assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx); 734 735 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 736 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 737 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 738 739 // Now empty out 3 of the |wepKeys[]| and ensure that those keys have been reset correctly. 740 for (int i = 1; i < network.wepKeys.length; i++) { 741 wepKeys[i] = ""; 742 } 743 wepTxKeyIdx = 0; 744 assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx); 745 746 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 747 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 748 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 749 750 // Now change the config to a PSK network config by resetting the remaining |wepKey[0]| 751 // field and setting the |preSharedKey| and |allowedKeyManagement| fields. 752 wepKeys[0] = ""; 753 wepTxKeyIdx = -1; 754 assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx); 755 network.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 756 assertAndSetNetworkPreSharedKey(network, WifiConfigurationTestUtil.TEST_PSK); 757 758 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 759 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 760 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 761 } 762 763 /** 764 * Verifies the modification of a WifiEnteriseConfig using 765 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}. 766 */ 767 @Test 768 public void testUpdateWifiEnterpriseConfig() { 769 WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork(); 770 verifyAddNetworkToWifiConfigManager(network); 771 772 // Set the |password| field in WifiEnterpriseConfig and modify the config to PEAP/GTC. 773 network.enterpriseConfig = 774 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2(); 775 assertAndSetNetworkEnterprisePassword(network, "test"); 776 777 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 778 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 779 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 780 781 // Reset the |password| field in WifiEnterpriseConfig and modify the config to TLS/None. 782 network.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS); 783 network.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.NONE); 784 assertAndSetNetworkEnterprisePassword(network, ""); 785 786 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 787 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 788 network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 789 } 790 791 /** 792 * Verifies the modification of a single network using 793 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} by passing in nulls 794 * in all the publicly exposed fields. 795 */ 796 @Test 797 public void testUpdateSingleNetworkWithNullValues() { 798 WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork(); 799 verifyAddNetworkToWifiConfigManager(network); 800 801 // Save a copy of the original network for comparison. 802 WifiConfiguration originalNetwork = new WifiConfiguration(network); 803 804 // Now set all the public fields to null and try updating the network. 805 network.allowedAuthAlgorithms = null; 806 network.allowedProtocols = null; 807 network.allowedKeyManagement = null; 808 network.allowedPairwiseCiphers = null; 809 network.allowedGroupCiphers = null; 810 network.setIpConfiguration(null); 811 network.enterpriseConfig = null; 812 813 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 814 815 // Copy over the updated debug params to the original network config before comparison. 816 originalNetwork.lastUpdateUid = network.lastUpdateUid; 817 originalNetwork.lastUpdateName = network.lastUpdateName; 818 originalNetwork.updateTime = network.updateTime; 819 820 // Now verify that there was no change to the network configurations. 821 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 822 originalNetwork, 823 mWifiConfigManager.getConfiguredNetworkWithPassword(originalNetwork.networkId)); 824 } 825 826 /** 827 * Verifies that the modification of a single network using 828 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} does not modify 829 * existing configuration if there is a failure. 830 */ 831 @Test 832 public void testUpdateSingleNetworkFailureDoesNotModifyOriginal() { 833 WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork(); 834 network.enterpriseConfig = 835 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2(); 836 verifyAddNetworkToWifiConfigManager(network); 837 838 // Save a copy of the original network for comparison. 839 WifiConfiguration originalNetwork = new WifiConfiguration(network); 840 841 // Now modify the network's EAP method. 842 network.enterpriseConfig = 843 WifiConfigurationTestUtil.createTLSWifiEnterpriseConfigWithNonePhase2(); 844 845 // Fail this update because of cert installation failure. 846 when(mWifiKeyStore 847 .updateNetworkKeys(any(WifiConfiguration.class), any(WifiConfiguration.class))) 848 .thenReturn(false); 849 NetworkUpdateResult result = 850 mWifiConfigManager.addOrUpdateNetwork(network, TEST_UPDATE_UID); 851 assertTrue(result.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID); 852 853 // Now verify that there was no change to the network configurations. 854 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 855 originalNetwork, 856 mWifiConfigManager.getConfiguredNetworkWithPassword(originalNetwork.networkId)); 857 } 858 859 /** 860 * Verifies the matching of networks with different encryption types with the 861 * corresponding scan detail using 862 * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)}. 863 * The test also verifies that the provided scan detail was cached, 864 */ 865 @Test 866 public void testMatchScanDetailToNetworksAndCache() { 867 // Create networks of different types and ensure that they're all matched using 868 // the corresponding ScanDetail correctly. 869 verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 870 WifiConfigurationTestUtil.createOpenNetwork()); 871 verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 872 WifiConfigurationTestUtil.createWepNetwork()); 873 verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 874 WifiConfigurationTestUtil.createPskNetwork()); 875 verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 876 WifiConfigurationTestUtil.createEapNetwork()); 877 } 878 879 /** 880 * Verifies that scan details with wrong SSID/authentication types are not matched using 881 * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)} 882 * to the added networks. 883 */ 884 @Test 885 public void testNoMatchScanDetailToNetwork() { 886 // First create networks of different types. 887 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 888 WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork(); 889 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 890 WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork(); 891 892 // Now add them to WifiConfigManager. 893 verifyAddNetworkToWifiConfigManager(openNetwork); 894 verifyAddNetworkToWifiConfigManager(wepNetwork); 895 verifyAddNetworkToWifiConfigManager(pskNetwork); 896 verifyAddNetworkToWifiConfigManager(eapNetwork); 897 898 // Now create dummy scan detail corresponding to the networks. 899 ScanDetail openNetworkScanDetail = createScanDetailForNetwork(openNetwork); 900 ScanDetail wepNetworkScanDetail = createScanDetailForNetwork(wepNetwork); 901 ScanDetail pskNetworkScanDetail = createScanDetailForNetwork(pskNetwork); 902 ScanDetail eapNetworkScanDetail = createScanDetailForNetwork(eapNetwork); 903 904 // Now mix and match parameters from different scan details. 905 openNetworkScanDetail.getScanResult().SSID = 906 wepNetworkScanDetail.getScanResult().SSID; 907 wepNetworkScanDetail.getScanResult().capabilities = 908 pskNetworkScanDetail.getScanResult().capabilities; 909 pskNetworkScanDetail.getScanResult().capabilities = 910 eapNetworkScanDetail.getScanResult().capabilities; 911 eapNetworkScanDetail.getScanResult().capabilities = 912 openNetworkScanDetail.getScanResult().capabilities; 913 914 // Try to lookup a saved network using the modified scan details. All of these should fail. 915 assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(openNetworkScanDetail)); 916 assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(wepNetworkScanDetail)); 917 assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(pskNetworkScanDetail)); 918 assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(eapNetworkScanDetail)); 919 920 // All the cache's should be empty as well. 921 assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId)); 922 assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(wepNetwork.networkId)); 923 assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(pskNetwork.networkId)); 924 assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(eapNetwork.networkId)); 925 } 926 927 /** 928 * Verifies that scan detail cache is trimmed down when the size of the cache for a network 929 * exceeds {@link WifiConfigManager#SCAN_CACHE_ENTRIES_MAX_SIZE}. 930 */ 931 @Test 932 public void testScanDetailCacheTrimForNetwork() { 933 // Add a single network. 934 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 935 verifyAddNetworkToWifiConfigManager(openNetwork); 936 937 ScanDetailCache scanDetailCache; 938 String testBssidPrefix = "00:a5:b8:c9:45:"; 939 940 // Modify |BSSID| field in the scan result and add copies of scan detail 941 // |SCAN_CACHE_ENTRIES_MAX_SIZE| times. 942 int scanDetailNum = 1; 943 for (; scanDetailNum <= WifiConfigManager.SCAN_CACHE_ENTRIES_MAX_SIZE; scanDetailNum++) { 944 // Create dummy scan detail caches with different BSSID for the network. 945 ScanDetail scanDetail = 946 createScanDetailForNetwork( 947 openNetwork, String.format("%s%02x", testBssidPrefix, scanDetailNum)); 948 assertNotNull( 949 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail)); 950 951 // The size of scan detail cache should keep growing until it hits 952 // |SCAN_CACHE_ENTRIES_MAX_SIZE|. 953 scanDetailCache = 954 mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId); 955 assertEquals(scanDetailNum, scanDetailCache.size()); 956 } 957 958 // Now add the |SCAN_CACHE_ENTRIES_MAX_SIZE + 1| entry. This should trigger the trim. 959 ScanDetail scanDetail = 960 createScanDetailForNetwork( 961 openNetwork, String.format("%s%02x", testBssidPrefix, scanDetailNum)); 962 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail)); 963 964 // Retrieve the scan detail cache and ensure that the size was trimmed down to 965 // |SCAN_CACHE_ENTRIES_TRIM_SIZE + 1|. The "+1" is to account for the new entry that 966 // was added after the trim. 967 scanDetailCache = mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId); 968 assertEquals(WifiConfigManager.SCAN_CACHE_ENTRIES_TRIM_SIZE + 1, scanDetailCache.size()); 969 } 970 971 /** 972 * Verifies that hasEverConnected is false for a newly added network. 973 */ 974 @Test 975 public void testAddNetworkHasEverConnectedFalse() { 976 verifyAddNetworkHasEverConnectedFalse(WifiConfigurationTestUtil.createOpenNetwork()); 977 } 978 979 /** 980 * Verifies that hasEverConnected is false for a newly added network even when new config has 981 * mistakenly set HasEverConnected to true. 982 */ 983 @Test 984 public void testAddNetworkOverridesHasEverConnectedWhenTrueInNewConfig() { 985 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 986 openNetwork.getNetworkSelectionStatus().setHasEverConnected(true); 987 verifyAddNetworkHasEverConnectedFalse(openNetwork); 988 } 989 990 /** 991 * Verify that the |HasEverConnected| is set when 992 * {@link WifiConfigManager#updateNetworkAfterConnect(int)} is invoked. 993 */ 994 @Test 995 public void testUpdateConfigAfterConnect() { 996 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 997 verifyAddNetworkHasEverConnectedFalse(openNetwork); 998 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(openNetwork.networkId); 999 } 1000 1001 /** 1002 * Verifies that hasEverConnected is cleared when a network config |preSharedKey| is updated. 1003 */ 1004 @Test 1005 public void testUpdatePreSharedKeyClearsHasEverConnected() { 1006 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1007 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1008 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1009 1010 // Now update the same network with a different psk. 1011 assertFalse(pskNetwork.preSharedKey.equals("newpassword")); 1012 pskNetwork.preSharedKey = "newpassword"; 1013 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1014 } 1015 1016 /** 1017 * Verifies that hasEverConnected is cleared when a network config |wepKeys| is updated. 1018 */ 1019 @Test 1020 public void testUpdateWepKeysClearsHasEverConnected() { 1021 WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork(); 1022 verifyAddNetworkHasEverConnectedFalse(wepNetwork); 1023 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(wepNetwork.networkId); 1024 1025 // Now update the same network with a different wep. 1026 assertFalse(wepNetwork.wepKeys[0].equals("newpassword")); 1027 wepNetwork.wepKeys[0] = "newpassword"; 1028 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(wepNetwork); 1029 } 1030 1031 /** 1032 * Verifies that hasEverConnected is cleared when a network config |wepTxKeyIndex| is updated. 1033 */ 1034 @Test 1035 public void testUpdateWepTxKeyClearsHasEverConnected() { 1036 WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork(); 1037 verifyAddNetworkHasEverConnectedFalse(wepNetwork); 1038 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(wepNetwork.networkId); 1039 1040 // Now update the same network with a different wep. 1041 assertFalse(wepNetwork.wepTxKeyIndex == 3); 1042 wepNetwork.wepTxKeyIndex = 3; 1043 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(wepNetwork); 1044 } 1045 1046 /** 1047 * Verifies that hasEverConnected is cleared when a network config |allowedKeyManagement| is 1048 * updated. 1049 */ 1050 @Test 1051 public void testUpdateAllowedKeyManagementClearsHasEverConnected() { 1052 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1053 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1054 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1055 1056 assertFalse(pskNetwork.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)); 1057 pskNetwork.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X); 1058 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1059 } 1060 1061 /** 1062 * Verifies that hasEverConnected is cleared when a network config |allowedProtocol| is 1063 * updated. 1064 */ 1065 @Test 1066 public void testUpdateProtocolsClearsHasEverConnected() { 1067 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1068 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1069 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1070 1071 assertFalse(pskNetwork.allowedProtocols.get(WifiConfiguration.Protocol.OSEN)); 1072 pskNetwork.allowedProtocols.set(WifiConfiguration.Protocol.OSEN); 1073 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1074 } 1075 1076 /** 1077 * Verifies that hasEverConnected is cleared when a network config |allowedAuthAlgorithms| is 1078 * updated. 1079 */ 1080 @Test 1081 public void testUpdateAllowedAuthAlgorithmsClearsHasEverConnected() { 1082 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1083 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1084 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1085 1086 assertFalse(pskNetwork.allowedAuthAlgorithms.get(WifiConfiguration.AuthAlgorithm.LEAP)); 1087 pskNetwork.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.LEAP); 1088 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1089 } 1090 1091 /** 1092 * Verifies that hasEverConnected is cleared when a network config |allowedPairwiseCiphers| is 1093 * updated. 1094 */ 1095 @Test 1096 public void testUpdateAllowedPairwiseCiphersClearsHasEverConnected() { 1097 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1098 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1099 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1100 1101 assertFalse(pskNetwork.allowedPairwiseCiphers.get(WifiConfiguration.PairwiseCipher.NONE)); 1102 pskNetwork.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.NONE); 1103 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1104 } 1105 1106 /** 1107 * Verifies that hasEverConnected is cleared when a network config |allowedGroup| is 1108 * updated. 1109 */ 1110 @Test 1111 public void testUpdateAllowedGroupCiphersClearsHasEverConnected() { 1112 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1113 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1114 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1115 1116 assertTrue(pskNetwork.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.WEP104)); 1117 pskNetwork.allowedGroupCiphers.clear(WifiConfiguration.GroupCipher.WEP104); 1118 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1119 } 1120 1121 /** 1122 * Verifies that hasEverConnected is cleared when a network config |hiddenSSID| is 1123 * updated. 1124 */ 1125 @Test 1126 public void testUpdateHiddenSSIDClearsHasEverConnected() { 1127 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1128 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1129 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1130 1131 assertFalse(pskNetwork.hiddenSSID); 1132 pskNetwork.hiddenSSID = true; 1133 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork); 1134 } 1135 1136 /** 1137 * Verifies that hasEverConnected is not cleared when a network config |requirePMF| is 1138 * updated. 1139 */ 1140 @Test 1141 public void testUpdateRequirePMFDoesNotClearHasEverConnected() { 1142 WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1143 verifyAddNetworkHasEverConnectedFalse(pskNetwork); 1144 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId); 1145 1146 assertFalse(pskNetwork.requirePMF); 1147 pskNetwork.requirePMF = true; 1148 1149 NetworkUpdateResult result = 1150 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(pskNetwork); 1151 WifiConfiguration retrievedNetwork = 1152 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 1153 assertTrue("Updating network non-credentials config should not clear hasEverConnected.", 1154 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 1155 } 1156 1157 /** 1158 * Verifies that hasEverConnected is cleared when a network config |enterpriseConfig| is 1159 * updated. 1160 */ 1161 @Test 1162 public void testUpdateEnterpriseConfigClearsHasEverConnected() { 1163 WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork(); 1164 eapNetwork.enterpriseConfig = 1165 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2(); 1166 verifyAddNetworkHasEverConnectedFalse(eapNetwork); 1167 verifyUpdateNetworkAfterConnectHasEverConnectedTrue(eapNetwork.networkId); 1168 1169 assertFalse(eapNetwork.enterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TLS); 1170 eapNetwork.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS); 1171 verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(eapNetwork); 1172 } 1173 1174 /** 1175 * Verifies the ordering of network list generated using 1176 * {@link WifiConfigManager#retrievePnoNetworkList()}. 1177 */ 1178 @Test 1179 public void testRetrievePnoList() { 1180 // Create and add 3 networks. 1181 WifiConfiguration network1 = WifiConfigurationTestUtil.createEapNetwork(); 1182 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1183 WifiConfiguration network3 = WifiConfigurationTestUtil.createOpenHiddenNetwork(); 1184 verifyAddNetworkToWifiConfigManager(network1); 1185 verifyAddNetworkToWifiConfigManager(network2); 1186 verifyAddNetworkToWifiConfigManager(network3); 1187 1188 // Enable all of them. 1189 assertTrue(mWifiConfigManager.enableNetwork(network1.networkId, false, TEST_CREATOR_UID)); 1190 assertTrue(mWifiConfigManager.enableNetwork(network2.networkId, false, TEST_CREATOR_UID)); 1191 assertTrue(mWifiConfigManager.enableNetwork(network3.networkId, false, TEST_CREATOR_UID)); 1192 1193 // Now set scan results in 2 of them to set the corresponding 1194 // {@link NetworkSelectionStatus#mSeenInLastQualifiedNetworkSelection} field. 1195 assertTrue(mWifiConfigManager.setNetworkCandidateScanResult( 1196 network1.networkId, createScanDetailForNetwork(network1).getScanResult(), 54)); 1197 assertTrue(mWifiConfigManager.setNetworkCandidateScanResult( 1198 network3.networkId, createScanDetailForNetwork(network3).getScanResult(), 54)); 1199 1200 // Now increment |network3|'s association count. This should ensure that this network 1201 // is preferred over |network1|. 1202 assertTrue(mWifiConfigManager.updateNetworkAfterConnect(network3.networkId)); 1203 1204 // Retrieve the Pno network list & verify the order of the networks returned. 1205 List<WifiScanner.PnoSettings.PnoNetwork> pnoNetworks = 1206 mWifiConfigManager.retrievePnoNetworkList(); 1207 assertEquals(3, pnoNetworks.size()); 1208 assertEquals(network3.SSID, pnoNetworks.get(0).ssid); 1209 assertEquals(network1.SSID, pnoNetworks.get(1).ssid); 1210 assertEquals(network2.SSID, pnoNetworks.get(2).ssid); 1211 1212 // Now permanently disable |network3|. This should remove network 3 from the list. 1213 assertTrue(mWifiConfigManager.disableNetwork(network3.networkId, TEST_CREATOR_UID)); 1214 1215 // Retrieve the Pno network list again & verify the order of the networks returned. 1216 pnoNetworks = mWifiConfigManager.retrievePnoNetworkList(); 1217 assertEquals(2, pnoNetworks.size()); 1218 assertEquals(network1.SSID, pnoNetworks.get(0).ssid); 1219 assertEquals(network2.SSID, pnoNetworks.get(1).ssid); 1220 } 1221 1222 /** 1223 * Verifies the linking of networks when they have the same default GW Mac address in 1224 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1225 */ 1226 @Test 1227 public void testNetworkLinkUsingGwMacAddress() { 1228 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1229 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1230 WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork(); 1231 verifyAddNetworkToWifiConfigManager(network1); 1232 verifyAddNetworkToWifiConfigManager(network2); 1233 verifyAddNetworkToWifiConfigManager(network3); 1234 1235 // Set the same default GW mac address for all of the networks. 1236 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1237 network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1238 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1239 network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1240 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1241 network3.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1242 1243 // Now create dummy scan detail corresponding to the networks. 1244 ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1); 1245 ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2); 1246 ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3); 1247 1248 // Now save all these scan details corresponding to each of this network and expect 1249 // all of these networks to be linked with each other. 1250 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1)); 1251 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2)); 1252 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail3)); 1253 1254 List<WifiConfiguration> retrievedNetworks = 1255 mWifiConfigManager.getConfiguredNetworks(); 1256 for (WifiConfiguration network : retrievedNetworks) { 1257 assertEquals(2, network.linkedConfigurations.size()); 1258 for (WifiConfiguration otherNetwork : retrievedNetworks) { 1259 if (otherNetwork == network) { 1260 continue; 1261 } 1262 assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey())); 1263 } 1264 } 1265 } 1266 1267 /** 1268 * Verifies the linking of networks when they have scan results with same first 16 ASCII of 1269 * bssid in 1270 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1271 */ 1272 @Test 1273 public void testNetworkLinkUsingBSSIDMatch() { 1274 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1275 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1276 WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork(); 1277 verifyAddNetworkToWifiConfigManager(network1); 1278 verifyAddNetworkToWifiConfigManager(network2); 1279 verifyAddNetworkToWifiConfigManager(network3); 1280 1281 // Create scan results with bssid which is different in only the last char. 1282 ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67"); 1283 ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68"); 1284 ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3, "af:89:56:34:56:69"); 1285 1286 // Now save all these scan details corresponding to each of this network and expect 1287 // all of these networks to be linked with each other. 1288 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1)); 1289 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2)); 1290 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail3)); 1291 1292 List<WifiConfiguration> retrievedNetworks = 1293 mWifiConfigManager.getConfiguredNetworks(); 1294 for (WifiConfiguration network : retrievedNetworks) { 1295 assertEquals(2, network.linkedConfigurations.size()); 1296 for (WifiConfiguration otherNetwork : retrievedNetworks) { 1297 if (otherNetwork == network) { 1298 continue; 1299 } 1300 assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey())); 1301 } 1302 } 1303 } 1304 1305 /** 1306 * Verifies the linking of networks does not happen for non WPA networks when they have scan 1307 * results with same first 16 ASCII of bssid in 1308 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1309 */ 1310 @Test 1311 public void testNoNetworkLinkUsingBSSIDMatchForNonWpaNetworks() { 1312 WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork(); 1313 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1314 verifyAddNetworkToWifiConfigManager(network1); 1315 verifyAddNetworkToWifiConfigManager(network2); 1316 1317 // Create scan results with bssid which is different in only the last char. 1318 ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67"); 1319 ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68"); 1320 1321 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1)); 1322 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2)); 1323 1324 List<WifiConfiguration> retrievedNetworks = 1325 mWifiConfigManager.getConfiguredNetworks(); 1326 for (WifiConfiguration network : retrievedNetworks) { 1327 assertNull(network.linkedConfigurations); 1328 } 1329 } 1330 1331 /** 1332 * Verifies the linking of networks does not happen for networks with more than 1333 * {@link WifiConfigManager#LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES} scan 1334 * results with same first 16 ASCII of bssid in 1335 * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}. 1336 */ 1337 @Test 1338 public void testNoNetworkLinkUsingBSSIDMatchForNetworksWithHighScanDetailCacheSize() { 1339 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1340 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1341 verifyAddNetworkToWifiConfigManager(network1); 1342 verifyAddNetworkToWifiConfigManager(network2); 1343 1344 // Create 7 scan results with bssid which is different in only the last char. 1345 String test_bssid_base = "af:89:56:34:56:6"; 1346 int scan_result_num = 0; 1347 for (; scan_result_num < WifiConfigManager.LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES + 1; 1348 scan_result_num++) { 1349 ScanDetail networkScanDetail = 1350 createScanDetailForNetwork( 1351 network1, test_bssid_base + Integer.toString(scan_result_num)); 1352 assertNotNull( 1353 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1354 } 1355 1356 // Now add 1 scan result to the other network with bssid which is different in only the 1357 // last char. 1358 ScanDetail networkScanDetail2 = 1359 createScanDetailForNetwork( 1360 network2, test_bssid_base + Integer.toString(scan_result_num++)); 1361 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2)); 1362 1363 List<WifiConfiguration> retrievedNetworks = 1364 mWifiConfigManager.getConfiguredNetworks(); 1365 for (WifiConfiguration network : retrievedNetworks) { 1366 assertNull(network.linkedConfigurations); 1367 } 1368 } 1369 1370 /** 1371 * Verifies the linking of networks when they have scan results with same first 16 ASCII of 1372 * bssid in {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)} 1373 * and then subsequently delinked when the networks have default gateway set which do not match. 1374 */ 1375 @Test 1376 public void testNetworkLinkUsingBSSIDMatchAndThenUnlinkDueToGwMacAddress() { 1377 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1378 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1379 verifyAddNetworkToWifiConfigManager(network1); 1380 verifyAddNetworkToWifiConfigManager(network2); 1381 1382 // Create scan results with bssid which is different in only the last char. 1383 ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67"); 1384 ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68"); 1385 1386 // Now save all these scan details corresponding to each of this network and expect 1387 // all of these networks to be linked with each other. 1388 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1)); 1389 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2)); 1390 1391 List<WifiConfiguration> retrievedNetworks = 1392 mWifiConfigManager.getConfiguredNetworks(); 1393 for (WifiConfiguration network : retrievedNetworks) { 1394 assertEquals(1, network.linkedConfigurations.size()); 1395 for (WifiConfiguration otherNetwork : retrievedNetworks) { 1396 if (otherNetwork == network) { 1397 continue; 1398 } 1399 assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey())); 1400 } 1401 } 1402 1403 // Now Set different GW mac address for both the networks and ensure they're unlinked. 1404 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1405 network1.networkId, "de:ad:fe:45:23:34")); 1406 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1407 network2.networkId, "ad:de:fe:45:23:34")); 1408 1409 // Add some dummy scan results again to re-evaluate the linking of networks. 1410 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache( 1411 createScanDetailForNetwork(network1, "af:89:56:34:45:67"))); 1412 assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache( 1413 createScanDetailForNetwork(network1, "af:89:56:34:45:68"))); 1414 1415 retrievedNetworks = mWifiConfigManager.getConfiguredNetworks(); 1416 for (WifiConfiguration network : retrievedNetworks) { 1417 assertNull(network.linkedConfigurations); 1418 } 1419 } 1420 1421 /* 1422 * Verifies the creation of channel list using 1423 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long)}. 1424 */ 1425 @Test 1426 public void testFetchChannelSetForNetwork() { 1427 WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork(); 1428 verifyAddNetworkToWifiConfigManager(network); 1429 1430 // Create 5 scan results with different bssid's & frequencies. 1431 String test_bssid_base = "af:89:56:34:56:6"; 1432 for (int i = 0; i < TEST_FREQ_LIST.length; i++) { 1433 ScanDetail networkScanDetail = 1434 createScanDetailForNetwork( 1435 network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]); 1436 assertNotNull( 1437 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1438 1439 } 1440 assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)), 1441 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network.networkId, 1)); 1442 } 1443 1444 /** 1445 * Verifies the creation of channel list using 1446 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long)} and ensures 1447 * that scan results which have a timestamp beyond the provided age are not used in the 1448 * channel list. 1449 */ 1450 @Test 1451 public void testFetchChannelSetForNetworkIgnoresStaleScanResults() { 1452 WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork(); 1453 verifyAddNetworkToWifiConfigManager(network); 1454 1455 long wallClockBase = 0; 1456 // Create 5 scan results with different bssid's & frequencies. 1457 String test_bssid_base = "af:89:56:34:56:6"; 1458 for (int i = 0; i < TEST_FREQ_LIST.length; i++) { 1459 // Increment the seen value in the scan results for each of them. 1460 when(mClock.getWallClockMillis()).thenReturn(wallClockBase + i); 1461 ScanDetail networkScanDetail = 1462 createScanDetailForNetwork( 1463 network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]); 1464 assertNotNull( 1465 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1466 1467 } 1468 int ageInMillis = 4; 1469 // Now fetch only scan results which are 4 millis stale. This should ignore the first 1470 // scan result. 1471 assertEquals( 1472 new HashSet<>(Arrays.asList( 1473 Arrays.copyOfRange( 1474 TEST_FREQ_LIST, 1475 TEST_FREQ_LIST.length - ageInMillis, TEST_FREQ_LIST.length))), 1476 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1477 network.networkId, ageInMillis)); 1478 } 1479 1480 /** 1481 * Verifies the creation of channel list using 1482 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long)} and ensures 1483 * that the list size does not exceed the max configured for the device. 1484 */ 1485 @Test 1486 public void testFetchChannelSetForNetworkIsLimitedToConfiguredSize() { 1487 // Need to recreate the WifiConfigManager instance for this test to modify the config 1488 // value which is read only in the constructor. 1489 int maxListSize = 3; 1490 mResources.setInteger( 1491 R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels, 1492 maxListSize); 1493 createWifiConfigManager(); 1494 1495 WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork(); 1496 verifyAddNetworkToWifiConfigManager(network); 1497 1498 // Create 5 scan results with different bssid's & frequencies. 1499 String test_bssid_base = "af:89:56:34:56:6"; 1500 for (int i = 0; i < TEST_FREQ_LIST.length; i++) { 1501 ScanDetail networkScanDetail = 1502 createScanDetailForNetwork( 1503 network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]); 1504 assertNotNull( 1505 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1506 1507 } 1508 // Ensure that the fetched list size is limited. 1509 assertEquals(maxListSize, 1510 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1511 network.networkId, 1).size()); 1512 } 1513 1514 /** 1515 * Verifies the creation of channel list using 1516 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long)} and ensures 1517 * that scan results from linked networks are used in the channel list. 1518 */ 1519 @Test 1520 public void testFetchChannelSetForNetworkIncludesLinkedNetworks() { 1521 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1522 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1523 verifyAddNetworkToWifiConfigManager(network1); 1524 verifyAddNetworkToWifiConfigManager(network2); 1525 1526 String test_bssid_base = "af:89:56:34:56:6"; 1527 int TEST_FREQ_LISTIdx = 0; 1528 // Create 3 scan results with different bssid's & frequencies for network 1. 1529 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length / 2; TEST_FREQ_LISTIdx++) { 1530 ScanDetail networkScanDetail = 1531 createScanDetailForNetwork( 1532 network1, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1533 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1534 assertNotNull( 1535 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1536 1537 } 1538 // Create 3 scan results with different bssid's & frequencies for network 2. 1539 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length; TEST_FREQ_LISTIdx++) { 1540 ScanDetail networkScanDetail = 1541 createScanDetailForNetwork( 1542 network2, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1543 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1544 assertNotNull( 1545 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1546 } 1547 1548 // Link the 2 configurations together using the GwMacAddress. 1549 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1550 network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1551 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1552 network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1553 1554 // The channel list fetched should include scan results from both the linked networks. 1555 assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)), 1556 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network1.networkId, 1)); 1557 assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)), 1558 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network2.networkId, 1)); 1559 } 1560 1561 /** 1562 * Verifies the creation of channel list using 1563 * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long)} and ensures 1564 * that scan results from linked networks are used in the channel list and that the list size 1565 * does not exceed the max configured for the device. 1566 */ 1567 @Test 1568 public void testFetchChannelSetForNetworkIncludesLinkedNetworksIsLimitedToConfiguredSize() { 1569 // Need to recreate the WifiConfigManager instance for this test to modify the config 1570 // value which is read only in the constructor. 1571 int maxListSize = 3; 1572 mResources.setInteger( 1573 R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels, 1574 maxListSize); 1575 1576 createWifiConfigManager(); 1577 WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork(); 1578 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1579 verifyAddNetworkToWifiConfigManager(network1); 1580 verifyAddNetworkToWifiConfigManager(network2); 1581 1582 String test_bssid_base = "af:89:56:34:56:6"; 1583 int TEST_FREQ_LISTIdx = 0; 1584 // Create 3 scan results with different bssid's & frequencies for network 1. 1585 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length / 2; TEST_FREQ_LISTIdx++) { 1586 ScanDetail networkScanDetail = 1587 createScanDetailForNetwork( 1588 network1, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1589 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1590 assertNotNull( 1591 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1592 1593 } 1594 // Create 3 scan results with different bssid's & frequencies for network 2. 1595 for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length; TEST_FREQ_LISTIdx++) { 1596 ScanDetail networkScanDetail = 1597 createScanDetailForNetwork( 1598 network2, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0, 1599 TEST_FREQ_LIST[TEST_FREQ_LISTIdx]); 1600 assertNotNull( 1601 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail)); 1602 } 1603 1604 // Link the 2 configurations together using the GwMacAddress. 1605 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1606 network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1607 assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress( 1608 network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS)); 1609 1610 // Ensure that the fetched list size is limited. 1611 assertEquals(maxListSize, 1612 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1613 network1.networkId, 1).size()); 1614 assertEquals(maxListSize, 1615 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 1616 network2.networkId, 1).size()); 1617 } 1618 1619 /** 1620 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 1621 * and ensures that any non current user private networks are moved to shared store file. 1622 */ 1623 @Test 1624 public void testHandleUserSwitchPushesOtherPrivateNetworksToSharedStore() throws Exception { 1625 int user1 = TEST_DEFAULT_USER; 1626 int user2 = TEST_DEFAULT_USER + 1; 1627 setupUserProfiles(user2); 1628 1629 int appId = 674; 1630 1631 // Create 3 networks. 1 for user1, 1 for user2 and 1 shared. 1632 final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork(); 1633 user1Network.shared = false; 1634 user1Network.creatorUid = UserHandle.getUid(user1, appId); 1635 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 1636 user2Network.shared = false; 1637 user2Network.creatorUid = UserHandle.getUid(user2, appId); 1638 final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork(); 1639 1640 // Set up the store data first that is loaded. 1641 List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() { 1642 { 1643 add(sharedNetwork); 1644 add(user2Network); 1645 } 1646 }; 1647 List<WifiConfiguration> userNetworks = new ArrayList<WifiConfiguration>() { 1648 { 1649 add(user1Network); 1650 } 1651 }; 1652 WifiConfigStoreData loadStoreData = 1653 new WifiConfigStoreData(sharedNetworks, userNetworks, new HashSet<String>()); 1654 when(mWifiConfigStore.read()).thenReturn(loadStoreData); 1655 1656 // Now switch the user to user2 1657 mWifiConfigManager.handleUserSwitch(user2); 1658 1659 // Set the expected network list before comparing. user1Network should be in shared data. 1660 // Note: In the real world, user1Network will no longer be visible now because it should 1661 // already be in user1's private store file. But, we're purposefully exposing it 1662 // via |loadStoreData| to test if other user's private networks are pushed to shared store. 1663 List<WifiConfiguration> expectedSharedNetworks = new ArrayList<WifiConfiguration>() { 1664 { 1665 add(sharedNetwork); 1666 add(user1Network); 1667 } 1668 }; 1669 List<WifiConfiguration> expectedUserNetworks = new ArrayList<WifiConfiguration>() { 1670 { 1671 add(user2Network); 1672 } 1673 }; 1674 // Capture the written data for the old user and ensure that it was empty. 1675 WifiConfigStoreData writtenStoreData = captureWriteStoreData(); 1676 assertTrue(writtenStoreData.getConfigurations().isEmpty()); 1677 1678 // Now capture the next written data and ensure that user1Network is now in shared data. 1679 writtenStoreData = captureWriteStoreData(); 1680 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 1681 expectedSharedNetworks, writtenStoreData.getSharedConfigurations()); 1682 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 1683 expectedUserNetworks, writtenStoreData.getUserConfigurations()); 1684 } 1685 1686 /** 1687 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 1688 * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is 1689 * read immediately if the user is unlocked during the switch. 1690 */ 1691 @Test 1692 public void testHandleUserSwitchWhenUnlocked() throws Exception { 1693 int user1 = TEST_DEFAULT_USER; 1694 int user2 = TEST_DEFAULT_USER + 1; 1695 setupUserProfiles(user2); 1696 1697 when(mWifiConfigStore.read()).thenReturn( 1698 new WifiConfigStoreData( 1699 new ArrayList<WifiConfiguration>(), new ArrayList<WifiConfiguration>(), 1700 new HashSet<String>())); 1701 1702 // user2 is unlocked and switched to foreground. 1703 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true); 1704 mWifiConfigManager.handleUserSwitch(user2); 1705 // Ensure that the read was invoked. 1706 mContextConfigStoreMockOrder.verify(mWifiConfigStore).read(); 1707 } 1708 1709 /** 1710 * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)} 1711 * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is not 1712 * read until the user is unlocked. 1713 */ 1714 public void testHandleUserSwitchWhenLocked() throws Exception { 1715 int user1 = TEST_DEFAULT_USER; 1716 int user2 = TEST_DEFAULT_USER + 1; 1717 setupUserProfiles(user2); 1718 1719 // user2 is locked and switched to foreground. 1720 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 1721 mWifiConfigManager.handleUserSwitch(user2); 1722 1723 // Ensure that the read was not invoked. 1724 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read(); 1725 1726 // Now try unlocking some other user (user1), this should be ignored. 1727 mWifiConfigManager.handleUserUnlock(user1); 1728 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read(); 1729 1730 when(mWifiConfigStore.read()).thenReturn( 1731 new WifiConfigStoreData( 1732 new ArrayList<WifiConfiguration>(), new ArrayList<WifiConfiguration>(), 1733 new HashSet<String>())); 1734 1735 // Unlock the user2 and ensure that we read the data now. 1736 mWifiConfigManager.handleUserUnlock(user2); 1737 mContextConfigStoreMockOrder.verify(mWifiConfigStore).read(); 1738 } 1739 1740 /** 1741 * Verifies that the foreground user stop using {@link WifiConfigManager#handleUserStop(int)} 1742 * and ensures that the store is written only when the foreground user is stopped. 1743 */ 1744 @Test 1745 public void testHandleUserStop() throws Exception { 1746 int user1 = TEST_DEFAULT_USER; 1747 int user2 = TEST_DEFAULT_USER + 1; 1748 setupUserProfiles(user2); 1749 1750 // Try stopping background user2 first, this should not do anything. 1751 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 1752 mWifiConfigManager.handleUserStop(user2); 1753 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read(); 1754 1755 // Now try stopping the foreground user1, this should trigger a write to store. 1756 mWifiConfigManager.handleUserStop(user1); 1757 mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read(); 1758 mContextConfigStoreMockOrder.verify(mWifiConfigStore).write( 1759 anyBoolean(), any(WifiConfigStoreData.class)); 1760 } 1761 1762 /** 1763 * Verifies the private network addition using 1764 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 1765 * by a non foreground user is rejected. 1766 */ 1767 @Test 1768 public void testAddNetworkUsingBackgroundUserUId() throws Exception { 1769 int user2 = TEST_DEFAULT_USER + 1; 1770 setupUserProfiles(user2); 1771 1772 int creatorUid = UserHandle.getUid(user2, 674); 1773 1774 // Create a network for user2 try adding it. This should be rejected. 1775 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 1776 NetworkUpdateResult result = 1777 mWifiConfigManager.addOrUpdateNetwork(user2Network, creatorUid); 1778 assertFalse(result.isSuccess()); 1779 } 1780 1781 /** 1782 * Verifies the private network addition using 1783 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} 1784 * by SysUI is always accepted. 1785 */ 1786 @Test 1787 public void testAddNetworkUsingSysUiUid() throws Exception { 1788 // Set up the user profiles stuff. Needed for |WifiConfigurationUtil.isVisibleToAnyProfile| 1789 int user2 = TEST_DEFAULT_USER + 1; 1790 setupUserProfiles(user2); 1791 1792 when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false); 1793 mWifiConfigManager.handleUserSwitch(user2); 1794 1795 // Create a network for user2 try adding it. This should be rejected. 1796 final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork(); 1797 NetworkUpdateResult result = 1798 mWifiConfigManager.addOrUpdateNetwork(user2Network, TEST_SYSUI_UID); 1799 assertTrue(result.isSuccess()); 1800 } 1801 1802 /** 1803 * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()} attempts 1804 * to migrate data from legacy stores when the new store files are absent. 1805 */ 1806 @Test 1807 public void testMigrationFromLegacyStore() throws Exception { 1808 // Create the store data to be returned from legacy stores. 1809 List<WifiConfiguration> networks = new ArrayList<>(); 1810 networks.add(WifiConfigurationTestUtil.createPskNetwork()); 1811 networks.add(WifiConfigurationTestUtil.createEapNetwork()); 1812 networks.add(WifiConfigurationTestUtil.createWepNetwork()); 1813 String deletedEphemeralSSID = "EphemeralSSID"; 1814 Set<String> deletedEphermalSSIDs = new HashSet<>(Arrays.asList(deletedEphemeralSSID)); 1815 WifiConfigStoreDataLegacy storeData = 1816 new WifiConfigStoreDataLegacy(networks, deletedEphermalSSIDs); 1817 1818 // New store files not present, so migrate from the old store. 1819 when(mWifiConfigStore.areStoresPresent()).thenReturn(false); 1820 when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(true); 1821 when(mWifiConfigStoreLegacy.read()).thenReturn(storeData); 1822 1823 // Now trigger a load from store. This should populate the in memory list with all the 1824 // networks above from the legacy store. 1825 mWifiConfigManager.loadFromStore(); 1826 1827 verify(mWifiConfigStore, never()).read(); 1828 verify(mWifiConfigStoreLegacy).read(); 1829 1830 List<WifiConfiguration> retrievedNetworks = 1831 mWifiConfigManager.getConfiguredNetworksWithPasswords(); 1832 WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate( 1833 networks, retrievedNetworks); 1834 assertTrue(mWifiConfigManager.wasEphemeralNetworkDeleted(deletedEphemeralSSID)); 1835 } 1836 1837 /** 1838 * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()} does 1839 * not attempt to read from any of the stores (new or legacy) when the store files are 1840 * not present. 1841 */ 1842 @Test 1843 public void testFreshInstallDoesNotLoadFromStore() throws Exception { 1844 // New store files not present, so migrate from the old store. 1845 when(mWifiConfigStore.areStoresPresent()).thenReturn(false); 1846 when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false); 1847 1848 // Now trigger a load from store. This should populate the in memory list with all the 1849 // networks above. 1850 mWifiConfigManager.loadFromStore(); 1851 1852 verify(mWifiConfigStore, never()).read(); 1853 verify(mWifiConfigStoreLegacy, never()).read(); 1854 1855 assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty()); 1856 } 1857 1858 /** 1859 * Verifies that the last user selected network parameter is set when 1860 * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with disableOthers flag is set 1861 * to true and cleared when either {@link WifiConfigManager#disableNetwork(int, int)} or 1862 * {@link WifiConfigManager#removeNetwork(int, int)} is invoked using the same network ID. 1863 */ 1864 @Test 1865 public void testLastSelectedNetwork() throws Exception { 1866 WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork(); 1867 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork); 1868 1869 when(mClock.getElapsedSinceBootMillis()).thenReturn(67L); 1870 assertTrue(mWifiConfigManager.enableNetwork( 1871 result.getNetworkId(), true, TEST_CREATOR_UID)); 1872 assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork()); 1873 assertEquals(67, mWifiConfigManager.getLastSelectedTimeStamp()); 1874 1875 // Now disable the network and ensure that the last selected flag is cleared. 1876 assertTrue(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_CREATOR_UID)); 1877 assertEquals( 1878 WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork()); 1879 1880 // Enable it again and remove the network to ensure that the last selected flag was cleared. 1881 assertTrue(mWifiConfigManager.enableNetwork( 1882 result.getNetworkId(), true, TEST_CREATOR_UID)); 1883 assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork()); 1884 assertEquals(openNetwork.configKey(), mWifiConfigManager.getLastSelectedNetworkConfigKey()); 1885 1886 assertTrue(mWifiConfigManager.removeNetwork(result.getNetworkId(), TEST_CREATOR_UID)); 1887 assertEquals( 1888 WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork()); 1889 } 1890 1891 /** 1892 * Verifies that all the networks for the provided app is removed when 1893 * {@link WifiConfigManager#removeNetworksForApp(ApplicationInfo)} is invoked. 1894 */ 1895 @Test 1896 public void testRemoveNetworksForApp() throws Exception { 1897 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork()); 1898 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork()); 1899 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork()); 1900 1901 assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 1902 1903 ApplicationInfo app = new ApplicationInfo(); 1904 app.uid = TEST_CREATOR_UID; 1905 app.packageName = TEST_CREATOR_NAME; 1906 assertTrue(mWifiConfigManager.removeNetworksForApp(app)); 1907 1908 // Ensure all the networks are removed now. 1909 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 1910 } 1911 1912 /** 1913 * Verifies that all the networks for the provided user is removed when 1914 * {@link WifiConfigManager#removeNetworksForUser(int)} is invoked. 1915 */ 1916 @Test 1917 public void testRemoveNetworksForUser() throws Exception { 1918 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork()); 1919 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork()); 1920 verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork()); 1921 1922 assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 1923 1924 assertTrue(mWifiConfigManager.removeNetworksForUser(TEST_DEFAULT_USER)); 1925 1926 // Ensure all the networks are removed now. 1927 assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty()); 1928 } 1929 1930 /** 1931 * Verifies that the connect choice is removed from all networks when 1932 * {@link WifiConfigManager#removeNetwork(int, int)} is invoked. 1933 */ 1934 @Test 1935 public void testRemoveNetworkRemovesConnectChoice() throws Exception { 1936 WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork(); 1937 WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork(); 1938 WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork(); 1939 verifyAddNetworkToWifiConfigManager(network1); 1940 verifyAddNetworkToWifiConfigManager(network2); 1941 verifyAddNetworkToWifiConfigManager(network3); 1942 1943 // Set connect choice of network 2 over network 1. 1944 assertTrue( 1945 mWifiConfigManager.setNetworkConnectChoice( 1946 network1.networkId, network2.configKey(), 78L)); 1947 1948 WifiConfiguration retrievedNetwork = 1949 mWifiConfigManager.getConfiguredNetwork(network1.networkId); 1950 assertEquals( 1951 network2.configKey(), 1952 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 1953 1954 // Remove network 3 and ensure that the connect choice on network 1 is not removed. 1955 assertTrue(mWifiConfigManager.removeNetwork(network3.networkId, TEST_CREATOR_UID)); 1956 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId); 1957 assertEquals( 1958 network2.configKey(), 1959 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 1960 1961 // Now remove network 2 and ensure that the connect choice on network 1 is removed.. 1962 assertTrue(mWifiConfigManager.removeNetwork(network2.networkId, TEST_CREATOR_UID)); 1963 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId); 1964 assertNotEquals( 1965 network2.configKey(), 1966 retrievedNetwork.getNetworkSelectionStatus().getConnectChoice()); 1967 } 1968 1969 /** 1970 * Verifies that the modification of a single network using 1971 * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and ensures that any 1972 * updates to the network config in 1973 * {@link WifiKeyStore#updateNetworkKeys(WifiConfiguration, WifiConfiguration)} is reflected 1974 * in the internal database. 1975 */ 1976 @Test 1977 public void testUpdateSingleNetworkWithKeysUpdate() { 1978 WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork(); 1979 network.enterpriseConfig = 1980 WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2(); 1981 verifyAddNetworkToWifiConfigManager(network); 1982 1983 // Now verify that network configurations match before we make any change. 1984 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 1985 network, 1986 mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 1987 1988 // Modify the network ca_cert field in updateNetworkKeys method during a network 1989 // config update. 1990 final String newCaCertAlias = "test"; 1991 assertNotEquals(newCaCertAlias, network.enterpriseConfig.getCaCertificateAlias()); 1992 1993 doAnswer(new AnswerWithArguments() { 1994 public boolean answer(WifiConfiguration newConfig, WifiConfiguration existingConfig) { 1995 newConfig.enterpriseConfig.setCaCertificateAlias(newCaCertAlias); 1996 return true; 1997 } 1998 }).when(mWifiKeyStore).updateNetworkKeys( 1999 any(WifiConfiguration.class), any(WifiConfiguration.class)); 2000 2001 verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 2002 2003 // Now verify that the keys update is reflected in the configuration fetched from internal 2004 // db. 2005 network.enterpriseConfig.setCaCertificateAlias(newCaCertAlias); 2006 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2007 network, 2008 mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId)); 2009 } 2010 2011 private void createWifiConfigManager() { 2012 mWifiConfigManager = 2013 new WifiConfigManager( 2014 mContext, mFrameworkFacade, mClock, mUserManager, mTelephonyManager, 2015 mWifiKeyStore, mWifiConfigStore, mWifiConfigStoreLegacy); 2016 mWifiConfigManager.enableVerboseLogging(1); 2017 } 2018 2019 /** 2020 * This method sets defaults in the provided WifiConfiguration object if not set 2021 * so that it can be used for comparison with the configuration retrieved from 2022 * WifiConfigManager. 2023 */ 2024 private void setDefaults(WifiConfiguration configuration) { 2025 if (configuration.allowedAuthAlgorithms.isEmpty()) { 2026 configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); 2027 } 2028 if (configuration.allowedProtocols.isEmpty()) { 2029 configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN); 2030 configuration.allowedProtocols.set(WifiConfiguration.Protocol.WPA); 2031 } 2032 if (configuration.allowedKeyManagement.isEmpty()) { 2033 configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK); 2034 configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP); 2035 } 2036 if (configuration.allowedPairwiseCiphers.isEmpty()) { 2037 configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP); 2038 configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP); 2039 } 2040 if (configuration.allowedGroupCiphers.isEmpty()) { 2041 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP); 2042 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP); 2043 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40); 2044 configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104); 2045 } 2046 if (configuration.getIpAssignment() == IpConfiguration.IpAssignment.UNASSIGNED) { 2047 configuration.setIpAssignment(IpConfiguration.IpAssignment.DHCP); 2048 } 2049 if (configuration.getProxySettings() == IpConfiguration.ProxySettings.UNASSIGNED) { 2050 configuration.setProxySettings(IpConfiguration.ProxySettings.NONE); 2051 } 2052 } 2053 2054 /** 2055 * Modifies the provided configuration with creator uid, package name 2056 * and time. 2057 */ 2058 private void setCreationDebugParams(WifiConfiguration configuration) { 2059 configuration.creatorUid = configuration.lastUpdateUid = TEST_CREATOR_UID; 2060 configuration.creatorName = configuration.lastUpdateName = TEST_CREATOR_NAME; 2061 configuration.creationTime = configuration.updateTime = 2062 WifiConfigManager.createDebugTimeStampString( 2063 TEST_WALLCLOCK_CREATION_TIME_MILLIS); 2064 } 2065 2066 /** 2067 * Modifies the provided configuration with update uid, package name 2068 * and time. 2069 */ 2070 private void setUpdateDebugParams(WifiConfiguration configuration) { 2071 configuration.lastUpdateUid = TEST_UPDATE_UID; 2072 configuration.lastUpdateName = TEST_UPDATE_NAME; 2073 configuration.updateTime = 2074 WifiConfigManager.createDebugTimeStampString(TEST_WALLCLOCK_UPDATE_TIME_MILLIS); 2075 } 2076 2077 private void assertNotEquals(Object expected, Object actual) { 2078 if (actual != null) { 2079 assertFalse(actual.equals(expected)); 2080 } else { 2081 assertNotNull(expected); 2082 } 2083 } 2084 2085 /** 2086 * Modifies the provided WifiConfiguration with the specified bssid value. Also, asserts that 2087 * the existing |BSSID| field is not the same value as the one being set 2088 */ 2089 private void assertAndSetNetworkBSSID(WifiConfiguration configuration, String bssid) { 2090 assertNotEquals(bssid, configuration.BSSID); 2091 configuration.BSSID = bssid; 2092 } 2093 2094 /** 2095 * Modifies the provided WifiConfiguration with the specified |IpConfiguration| object. Also, 2096 * asserts that the existing |mIpConfiguration| field is not the same value as the one being set 2097 */ 2098 private void assertAndSetNetworkIpConfiguration( 2099 WifiConfiguration configuration, IpConfiguration ipConfiguration) { 2100 assertNotEquals(ipConfiguration, configuration.getIpConfiguration()); 2101 configuration.setIpConfiguration(ipConfiguration); 2102 } 2103 2104 /** 2105 * Modifies the provided WifiConfiguration with the specified |wepKeys| value and 2106 * |wepTxKeyIndex|. 2107 */ 2108 private void assertAndSetNetworkWepKeysAndTxIndex( 2109 WifiConfiguration configuration, String[] wepKeys, int wepTxKeyIdx) { 2110 assertNotEquals(wepKeys, configuration.wepKeys); 2111 assertNotEquals(wepTxKeyIdx, configuration.wepTxKeyIndex); 2112 configuration.wepKeys = Arrays.copyOf(wepKeys, wepKeys.length); 2113 configuration.wepTxKeyIndex = wepTxKeyIdx; 2114 } 2115 2116 /** 2117 * Modifies the provided WifiConfiguration with the specified |preSharedKey| value. 2118 */ 2119 private void assertAndSetNetworkPreSharedKey( 2120 WifiConfiguration configuration, String preSharedKey) { 2121 assertNotEquals(preSharedKey, configuration.preSharedKey); 2122 configuration.preSharedKey = preSharedKey; 2123 } 2124 2125 /** 2126 * Modifies the provided WifiConfiguration with the specified enteprise |password| value. 2127 */ 2128 private void assertAndSetNetworkEnterprisePassword( 2129 WifiConfiguration configuration, String password) { 2130 assertNotEquals(password, configuration.enterpriseConfig.getPassword()); 2131 configuration.enterpriseConfig.setPassword(password); 2132 } 2133 2134 /** 2135 * Helper method to capture the store data written in WifiConfigStore.write() method. 2136 */ 2137 private WifiConfigStoreData captureWriteStoreData() { 2138 try { 2139 ArgumentCaptor<WifiConfigStoreData> storeDataCaptor = 2140 ArgumentCaptor.forClass(WifiConfigStoreData.class); 2141 mContextConfigStoreMockOrder.verify(mWifiConfigStore) 2142 .write(anyBoolean(), storeDataCaptor.capture()); 2143 return storeDataCaptor.getValue(); 2144 } catch (Exception e) { 2145 fail("Exception encountered during write " + e); 2146 } 2147 return null; 2148 } 2149 2150 /** 2151 * Returns whether the provided network was in the store data or not. 2152 */ 2153 private boolean isNetworkInConfigStoreData(WifiConfiguration configuration) { 2154 WifiConfigStoreData storeData = captureWriteStoreData(); 2155 if (storeData == null) { 2156 return false; 2157 } 2158 boolean foundNetworkInStoreData = false; 2159 for (WifiConfiguration retrievedConfig : storeData.getConfigurations()) { 2160 if (retrievedConfig.configKey().equals(configuration.configKey())) { 2161 foundNetworkInStoreData = true; 2162 } 2163 } 2164 return foundNetworkInStoreData; 2165 } 2166 2167 /** 2168 * Verifies that the provided network was not present in the last config store write. 2169 */ 2170 private void verifyNetworkNotInConfigStoreData(WifiConfiguration configuration) { 2171 assertFalse(isNetworkInConfigStoreData(configuration)); 2172 } 2173 2174 /** 2175 * Verifies that the provided network was present in the last config store write. 2176 */ 2177 private void verifyNetworkInConfigStoreData(WifiConfiguration configuration) { 2178 assertTrue(isNetworkInConfigStoreData(configuration)); 2179 } 2180 2181 private void assertPasswordsMaskedInWifiConfiguration(WifiConfiguration configuration) { 2182 if (!TextUtils.isEmpty(configuration.preSharedKey)) { 2183 assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.preSharedKey); 2184 } 2185 if (configuration.wepKeys != null) { 2186 for (int i = 0; i < configuration.wepKeys.length; i++) { 2187 if (!TextUtils.isEmpty(configuration.wepKeys[i])) { 2188 assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.wepKeys[i]); 2189 } 2190 } 2191 } 2192 if (!TextUtils.isEmpty(configuration.enterpriseConfig.getPassword())) { 2193 assertEquals( 2194 WifiConfigManager.PASSWORD_MASK, 2195 configuration.enterpriseConfig.getPassword()); 2196 } 2197 } 2198 2199 /** 2200 * Verifies that the network was present in the network change broadcast and returns the 2201 * change reason. 2202 */ 2203 private int verifyNetworkInBroadcastAndReturnReason(WifiConfiguration configuration) { 2204 ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); 2205 ArgumentCaptor<UserHandle> userHandleCaptor = ArgumentCaptor.forClass(UserHandle.class); 2206 mContextConfigStoreMockOrder.verify(mContext) 2207 .sendBroadcastAsUser(intentCaptor.capture(), userHandleCaptor.capture()); 2208 2209 assertEquals(userHandleCaptor.getValue(), UserHandle.ALL); 2210 Intent intent = intentCaptor.getValue(); 2211 2212 int changeReason = intent.getIntExtra(WifiManager.EXTRA_CHANGE_REASON, -1); 2213 WifiConfiguration retrievedConfig = 2214 (WifiConfiguration) intent.getExtra(WifiManager.EXTRA_WIFI_CONFIGURATION); 2215 assertEquals(retrievedConfig.configKey(), configuration.configKey()); 2216 2217 // Verify that all the passwords are masked in the broadcast configuration. 2218 assertPasswordsMaskedInWifiConfiguration(retrievedConfig); 2219 2220 return changeReason; 2221 } 2222 2223 /** 2224 * Verifies that we sent out an add broadcast with the provided network. 2225 */ 2226 private void verifyNetworkAddBroadcast(WifiConfiguration configuration) { 2227 assertEquals( 2228 verifyNetworkInBroadcastAndReturnReason(configuration), 2229 WifiManager.CHANGE_REASON_ADDED); 2230 } 2231 2232 /** 2233 * Verifies that we sent out an update broadcast with the provided network. 2234 */ 2235 private void verifyNetworkUpdateBroadcast(WifiConfiguration configuration) { 2236 assertEquals( 2237 verifyNetworkInBroadcastAndReturnReason(configuration), 2238 WifiManager.CHANGE_REASON_CONFIG_CHANGE); 2239 } 2240 2241 /** 2242 * Verifies that we sent out a remove broadcast with the provided network. 2243 */ 2244 private void verifyNetworkRemoveBroadcast(WifiConfiguration configuration) { 2245 assertEquals( 2246 verifyNetworkInBroadcastAndReturnReason(configuration), 2247 WifiManager.CHANGE_REASON_REMOVED); 2248 } 2249 2250 /** 2251 * Adds the provided configuration to WifiConfigManager and modifies the provided configuration 2252 * with creator/update uid, package name and time. This also sets defaults for fields not 2253 * populated. 2254 * These fields are populated internally by WifiConfigManager and hence we need 2255 * to modify the configuration before we compare the added network with the retrieved network. 2256 */ 2257 private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration) { 2258 when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS); 2259 NetworkUpdateResult result = 2260 mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_CREATOR_UID); 2261 setDefaults(configuration); 2262 setCreationDebugParams(configuration); 2263 configuration.networkId = result.getNetworkId(); 2264 return result; 2265 } 2266 2267 /** 2268 * Add network to WifiConfigManager and ensure that it was successful. 2269 */ 2270 private NetworkUpdateResult verifyAddNetworkToWifiConfigManager( 2271 WifiConfiguration configuration) { 2272 NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration); 2273 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2274 assertTrue(result.isNewNetwork()); 2275 assertTrue(result.hasIpChanged()); 2276 assertTrue(result.hasProxyChanged()); 2277 2278 verifyNetworkAddBroadcast(configuration); 2279 // Verify that the config store write was triggered with this new configuration. 2280 verifyNetworkInConfigStoreData(configuration); 2281 return result; 2282 } 2283 2284 /** 2285 * Add ephemeral network to WifiConfigManager and ensure that it was successful. 2286 */ 2287 private NetworkUpdateResult verifyAddEphemeralNetworkToWifiConfigManager( 2288 WifiConfiguration configuration) { 2289 NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration); 2290 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2291 assertTrue(result.isNewNetwork()); 2292 assertTrue(result.hasIpChanged()); 2293 assertTrue(result.hasProxyChanged()); 2294 2295 verifyNetworkAddBroadcast(configuration); 2296 // Ephemeral networks should not be persisted. 2297 verifyNetworkNotInConfigStoreData(configuration); 2298 return result; 2299 } 2300 2301 /** 2302 * Updates the provided configuration to WifiConfigManager and modifies the provided 2303 * configuration with update uid, package name and time. 2304 * These fields are populated internally by WifiConfigManager and hence we need 2305 * to modify the configuration before we compare the added network with the retrieved network. 2306 */ 2307 private NetworkUpdateResult updateNetworkToWifiConfigManager(WifiConfiguration configuration) { 2308 when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_UPDATE_TIME_MILLIS); 2309 NetworkUpdateResult result = 2310 mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_UPDATE_UID); 2311 setUpdateDebugParams(configuration); 2312 return result; 2313 } 2314 2315 /** 2316 * Update network to WifiConfigManager config change and ensure that it was successful. 2317 */ 2318 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManager( 2319 WifiConfiguration configuration) { 2320 NetworkUpdateResult result = updateNetworkToWifiConfigManager(configuration); 2321 assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID); 2322 assertFalse(result.isNewNetwork()); 2323 2324 verifyNetworkUpdateBroadcast(configuration); 2325 // Verify that the config store write was triggered with this new configuration. 2326 verifyNetworkInConfigStoreData(configuration); 2327 return result; 2328 } 2329 2330 /** 2331 * Update network to WifiConfigManager without IP config change and ensure that it was 2332 * successful. 2333 */ 2334 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithoutIpChange( 2335 WifiConfiguration configuration) { 2336 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration); 2337 assertFalse(result.hasIpChanged()); 2338 assertFalse(result.hasProxyChanged()); 2339 return result; 2340 } 2341 2342 /** 2343 * Update network to WifiConfigManager with IP config change and ensure that it was 2344 * successful. 2345 */ 2346 private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithIpChange( 2347 WifiConfiguration configuration) { 2348 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration); 2349 assertTrue(result.hasIpChanged()); 2350 assertTrue(result.hasProxyChanged()); 2351 return result; 2352 } 2353 2354 /** 2355 * Removes network from WifiConfigManager and ensure that it was successful. 2356 */ 2357 private void verifyRemoveNetworkFromWifiConfigManager( 2358 WifiConfiguration configuration) { 2359 assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID)); 2360 2361 verifyNetworkRemoveBroadcast(configuration); 2362 // Verify if the config store write was triggered without this new configuration. 2363 verifyNetworkNotInConfigStoreData(configuration); 2364 } 2365 2366 /** 2367 * Verifies the provided network's public status and ensures that the network change broadcast 2368 * has been sent out. 2369 */ 2370 private void verifyUpdateNetworkStatus(WifiConfiguration configuration, int status) { 2371 assertEquals(status, configuration.status); 2372 verifyNetworkUpdateBroadcast(configuration); 2373 } 2374 2375 /** 2376 * Verifies the network's selection status update. 2377 * 2378 * For temporarily disabled reasons, the method ensures that the status has changed only if 2379 * disable reason counter has exceeded the threshold. 2380 * 2381 * For permanently disabled/enabled reasons, the method ensures that the public status has 2382 * changed and the network change broadcast has been sent out. 2383 */ 2384 private void verifyUpdateNetworkSelectionStatus( 2385 int networkId, int reason, int temporaryDisableReasonCounter) { 2386 when(mClock.getElapsedSinceBootMillis()) 2387 .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS); 2388 2389 // Fetch the current status of the network before we try to update the status. 2390 WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 2391 NetworkSelectionStatus currentStatus = retrievedNetwork.getNetworkSelectionStatus(); 2392 int currentDisableReason = currentStatus.getNetworkSelectionDisableReason(); 2393 2394 // First set the status to the provided reason. 2395 assertTrue(mWifiConfigManager.updateNetworkSelectionStatus(networkId, reason)); 2396 2397 // Now fetch the network configuration and verify the new status of the network. 2398 retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 2399 2400 NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus(); 2401 int retrievedDisableReason = retrievedStatus.getNetworkSelectionDisableReason(); 2402 long retrievedDisableTime = retrievedStatus.getDisableTime(); 2403 int retrievedDisableReasonCounter = retrievedStatus.getDisableReasonCounter(reason); 2404 int disableReasonThreshold = 2405 WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[reason]; 2406 2407 if (reason == NetworkSelectionStatus.NETWORK_SELECTION_ENABLE) { 2408 assertEquals(reason, retrievedDisableReason); 2409 assertTrue(retrievedStatus.isNetworkEnabled()); 2410 assertEquals( 2411 NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP, 2412 retrievedDisableTime); 2413 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED); 2414 } else if (reason < NetworkSelectionStatus.DISABLED_TLS_VERSION_MISMATCH) { 2415 // For temporarily disabled networks, we need to ensure that the current status remains 2416 // until the threshold is crossed. 2417 assertEquals(temporaryDisableReasonCounter, retrievedDisableReasonCounter); 2418 if (retrievedDisableReasonCounter < disableReasonThreshold) { 2419 assertEquals(currentDisableReason, retrievedDisableReason); 2420 assertEquals( 2421 currentStatus.getNetworkSelectionStatus(), 2422 retrievedStatus.getNetworkSelectionStatus()); 2423 } else { 2424 assertEquals(reason, retrievedDisableReason); 2425 assertTrue(retrievedStatus.isNetworkTemporaryDisabled()); 2426 assertEquals( 2427 TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS, retrievedDisableTime); 2428 } 2429 } else if (reason < NetworkSelectionStatus.NETWORK_SELECTION_DISABLED_MAX) { 2430 assertEquals(reason, retrievedDisableReason); 2431 assertTrue(retrievedStatus.isNetworkPermanentlyDisabled()); 2432 assertEquals( 2433 NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP, 2434 retrievedDisableTime); 2435 verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED); 2436 } 2437 } 2438 2439 /** 2440 * Creates a scan detail corresponding to the provided network and given BSSID, level &frequency 2441 * values. 2442 */ 2443 private ScanDetail createScanDetailForNetwork( 2444 WifiConfiguration configuration, String bssid, int level, int frequency) { 2445 String caps; 2446 if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) { 2447 caps = "[WPA2-PSK-CCMP]"; 2448 } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP) 2449 || configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) { 2450 caps = "[WPA2-EAP-CCMP]"; 2451 } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE) 2452 && WifiConfigurationUtil.hasAnyValidWepKey(configuration.wepKeys)) { 2453 caps = "[WEP]"; 2454 } else { 2455 caps = "[]"; 2456 } 2457 WifiSsid ssid = WifiSsid.createFromAsciiEncoded(configuration.getPrintableSsid()); 2458 // Fill in 0's in the fields we don't care about. 2459 return new ScanDetail( 2460 ssid, bssid, caps, level, frequency, mClock.getUptimeSinceBootMillis(), 2461 mClock.getWallClockMillis()); 2462 } 2463 2464 /** 2465 * Creates a scan detail corresponding to the provided network and BSSID value. 2466 */ 2467 private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration, String bssid) { 2468 return createScanDetailForNetwork(configuration, bssid, 0, 0); 2469 } 2470 2471 /** 2472 * Creates a scan detail corresponding to the provided network and fixed BSSID value. 2473 */ 2474 private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration) { 2475 return createScanDetailForNetwork(configuration, TEST_BSSID); 2476 } 2477 2478 /** 2479 * Adds the provided network and then creates a scan detail corresponding to the network. The 2480 * method then creates a ScanDetail corresponding to the network and ensures that the network 2481 * is properly matched using 2482 * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)} and also 2483 * verifies that the provided scan detail was cached, 2484 */ 2485 private void verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache( 2486 WifiConfiguration network) { 2487 // First add the provided network. 2488 verifyAddNetworkToWifiConfigManager(network); 2489 2490 // Now create a dummy scan detail corresponding to the network. 2491 ScanDetail scanDetail = createScanDetailForNetwork(network); 2492 ScanResult scanResult = scanDetail.getScanResult(); 2493 2494 WifiConfiguration retrievedNetwork = 2495 mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail); 2496 // Retrieve the network with password data for comparison. 2497 retrievedNetwork = 2498 mWifiConfigManager.getConfiguredNetworkWithPassword(retrievedNetwork.networkId); 2499 2500 WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate( 2501 network, retrievedNetwork); 2502 2503 // Now retrieve the scan detail cache and ensure that the new scan detail is in cache. 2504 ScanDetailCache retrievedScanDetailCache = 2505 mWifiConfigManager.getScanDetailCacheForNetwork(network.networkId); 2506 assertEquals(1, retrievedScanDetailCache.size()); 2507 ScanResult retrievedScanResult = retrievedScanDetailCache.get(scanResult.BSSID); 2508 2509 ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult); 2510 } 2511 2512 /** 2513 * Adds a new network and verifies that the |HasEverConnected| flag is set to false. 2514 */ 2515 private void verifyAddNetworkHasEverConnectedFalse(WifiConfiguration network) { 2516 NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network); 2517 WifiConfiguration retrievedNetwork = 2518 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 2519 assertFalse("Adding a new network should not have hasEverConnected set to true.", 2520 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 2521 } 2522 2523 /** 2524 * Updates an existing network with some credential change and verifies that the 2525 * |HasEverConnected| flag is set to false. 2526 */ 2527 private void verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse( 2528 WifiConfiguration network) { 2529 NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network); 2530 WifiConfiguration retrievedNetwork = 2531 mWifiConfigManager.getConfiguredNetwork(result.getNetworkId()); 2532 assertFalse("Updating network credentials config should clear hasEverConnected.", 2533 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 2534 } 2535 2536 /** 2537 * Updates an existing network after connection using 2538 * {@link WifiConfigManager#updateNetworkAfterConnect(int)} and asserts that the 2539 * |HasEverConnected| flag is set to true. 2540 */ 2541 private void verifyUpdateNetworkAfterConnectHasEverConnectedTrue(int networkId) { 2542 assertTrue(mWifiConfigManager.updateNetworkAfterConnect(networkId)); 2543 WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId); 2544 assertTrue("hasEverConnected expected to be true after connection.", 2545 retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected()); 2546 } 2547 2548 /** 2549 * Sets up a user profiles for WifiConfigManager testing. 2550 * 2551 * @param userId Id of the user. 2552 */ 2553 private void setupUserProfiles(int userId) { 2554 final UserInfo userInfo = 2555 new UserInfo(userId, Integer.toString(userId), UserInfo.FLAG_PRIMARY); 2556 List<UserInfo> userProfiles = Arrays.asList(userInfo); 2557 when(mUserManager.getProfiles(userId)).thenReturn(userProfiles); 2558 when(mUserManager.isUserUnlockingOrUnlocked(userId)).thenReturn(true); 2559 } 2560 2561} 2562