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