WifiStateMachineTest.java revision 8ba794562167643688ee38352f98345403fa22c8
1/* 2 * Copyright (C) 2015 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.assertEquals; 20import static org.junit.Assert.assertFalse; 21import static org.junit.Assert.assertTrue; 22import static org.mockito.Mockito.any; 23import static org.mockito.Mockito.anyBoolean; 24import static org.mockito.Mockito.anyInt; 25import static org.mockito.Mockito.anyObject; 26import static org.mockito.Mockito.anyString; 27import static org.mockito.Mockito.eq; 28import static org.mockito.Mockito.mock; 29import static org.mockito.Mockito.never; 30import static org.mockito.Mockito.verify; 31import static org.mockito.Mockito.when; 32import static org.mockito.Mockito.withSettings; 33 34import android.content.ContentResolver; 35import android.content.Context; 36import android.content.pm.PackageManager; 37import android.content.pm.UserInfo; 38import android.content.res.Resources; 39import android.net.ConnectivityManager; 40import android.net.DhcpResults; 41import android.net.LinkProperties; 42import android.net.dhcp.DhcpClient; 43import android.net.ip.IpManager; 44import android.net.wifi.ScanResult; 45import android.net.wifi.SupplicantState; 46import android.net.wifi.WifiConfiguration; 47import android.net.wifi.WifiManager; 48import android.net.wifi.WifiScanner; 49import android.net.wifi.WifiSsid; 50import android.net.wifi.p2p.IWifiP2pManager; 51import android.os.BatteryStats; 52import android.os.Binder; 53import android.os.Handler; 54import android.os.HandlerThread; 55import android.os.IBinder; 56import android.os.IInterface; 57import android.os.INetworkManagementService; 58import android.os.IPowerManager; 59import android.os.Looper; 60import android.os.Message; 61import android.os.Messenger; 62import android.os.PowerManager; 63import android.os.UserHandle; 64import android.os.UserManager; 65import android.provider.Settings; 66import android.security.KeyStore; 67import android.telephony.TelephonyManager; 68import android.test.suitebuilder.annotation.SmallTest; 69import android.util.Base64; 70import android.util.Log; 71 72import com.android.internal.R; 73import com.android.internal.app.IBatteryStats; 74import com.android.internal.util.AsyncChannel; 75import com.android.internal.util.IState; 76import com.android.internal.util.StateMachine; 77import com.android.server.wifi.MockAnswerUtil.AnswerWithArguments; 78import com.android.server.wifi.hotspot2.NetworkDetail; 79import com.android.server.wifi.hotspot2.Utils; 80import com.android.server.wifi.p2p.WifiP2pServiceImpl; 81 82import org.junit.After; 83import org.junit.Before; 84import org.junit.Test; 85import org.mockito.ArgumentCaptor; 86import org.mockito.Mock; 87import org.mockito.MockitoAnnotations; 88 89import java.io.ByteArrayOutputStream; 90import java.io.PrintWriter; 91import java.lang.reflect.Field; 92import java.lang.reflect.InvocationTargetException; 93import java.lang.reflect.Method; 94import java.util.ArrayList; 95import java.util.Arrays; 96import java.util.HashMap; 97import java.util.HashSet; 98import java.util.List; 99import java.util.Map; 100import java.util.Set; 101 102/** 103 * Unit tests for {@link com.android.server.wifi.WifiStateMachine}. 104 */ 105@SmallTest 106public class WifiStateMachineTest { 107 public static final String TAG = "WifiStateMachineTest"; 108 109 private static final int MANAGED_PROFILE_UID = 1100000; 110 private static final int OTHER_USER_UID = 1200000; 111 112 private long mBinderToken; 113 114 private static <T> T mockWithInterfaces(Class<T> class1, Class<?>... interfaces) { 115 return mock(class1, withSettings().extraInterfaces(interfaces)); 116 } 117 118 private static <T, I> IBinder mockService(Class<T> class1, Class<I> iface) { 119 T tImpl = mockWithInterfaces(class1, iface); 120 IBinder binder = mock(IBinder.class); 121 when(((IInterface) tImpl).asBinder()).thenReturn(binder); 122 when(binder.queryLocalInterface(iface.getCanonicalName())) 123 .thenReturn((IInterface) tImpl); 124 return binder; 125 } 126 127 private void enableDebugLogs() { 128 mWsm.enableVerboseLogging(1); 129 } 130 131 private class TestIpManager extends IpManager { 132 TestIpManager(Context context, String ifname, IpManager.Callback callback) { 133 // Call dependency-injection superclass constructor. 134 super(context, ifname, callback, mock(INetworkManagementService.class)); 135 } 136 137 @Override 138 public void startProvisioning(IpManager.ProvisioningConfiguration config) {} 139 140 @Override 141 public void stop() {} 142 143 @Override 144 public void confirmConfiguration() {} 145 146 void injectDhcpSuccess(DhcpResults dhcpResults) { 147 mCallback.onNewDhcpResults(dhcpResults); 148 mCallback.onProvisioningSuccess(new LinkProperties()); 149 } 150 151 void injectDhcpFailure() { 152 mCallback.onNewDhcpResults(null); 153 mCallback.onProvisioningFailure(new LinkProperties()); 154 } 155 } 156 157 private FrameworkFacade getFrameworkFacade() throws Exception { 158 FrameworkFacade facade = mock(FrameworkFacade.class); 159 160 when(facade.makeBaseLogger()).thenReturn(mock(BaseWifiLogger.class)); 161 when(facade.getService(Context.NETWORKMANAGEMENT_SERVICE)).thenReturn( 162 mockWithInterfaces(IBinder.class, INetworkManagementService.class)); 163 164 IBinder p2pBinder = mockService(WifiP2pServiceImpl.class, IWifiP2pManager.class); 165 when(facade.getService(Context.WIFI_P2P_SERVICE)).thenReturn(p2pBinder); 166 167 WifiP2pServiceImpl p2pm = (WifiP2pServiceImpl) p2pBinder.queryLocalInterface( 168 IWifiP2pManager.class.getCanonicalName()); 169 170 final Object sync = new Object(); 171 synchronized (sync) { 172 mP2pThread = new HandlerThread("WifiP2pMockThread") { 173 @Override 174 protected void onLooperPrepared() { 175 synchronized (sync) { 176 sync.notifyAll(); 177 } 178 } 179 }; 180 181 mP2pThread.start(); 182 sync.wait(); 183 } 184 185 Handler handler = new Handler(mP2pThread.getLooper()); 186 when(p2pm.getP2pStateMachineMessenger()).thenReturn(new Messenger(handler)); 187 188 IBinder batteryStatsBinder = mockService(BatteryStats.class, IBatteryStats.class); 189 when(facade.getService(BatteryStats.SERVICE_NAME)).thenReturn(batteryStatsBinder); 190 191 when(facade.makeIpManager(any(Context.class), anyString(), any(IpManager.Callback.class))) 192 .then(new AnswerWithArguments() { 193 public IpManager answer( 194 Context context, String ifname, IpManager.Callback callback) { 195 mTestIpManager = new TestIpManager(context, ifname, callback); 196 return mTestIpManager; 197 } 198 }); 199 200 when(facade.checkUidPermission(eq(android.Manifest.permission.OVERRIDE_WIFI_CONFIG), 201 anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED); 202 203 when(facade.makeWifiConfigManager(any(Context.class), any(WifiStateMachine.class), 204 any(WifiNative.class), any(FrameworkFacade.class), any(Clock.class), 205 any(UserManager.class), any(KeyStore.class))).then(new AnswerWithArguments() { 206 public WifiConfigManager answer(Context context, WifiStateMachine wifiStateMachine, 207 WifiNative wifiNative, FrameworkFacade frameworkFacade, Clock clock, 208 UserManager userManager, KeyStore keyStore){ 209 mWifiConfigManager = new WifiConfigManager(context, wifiStateMachine, wifiNative, 210 frameworkFacade, clock, userManager, keyStore); 211 return mWifiConfigManager; 212 } 213 }); 214 return facade; 215 } 216 217 private Context getContext() throws Exception { 218 PackageManager pkgMgr = mock(PackageManager.class); 219 when(pkgMgr.hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT)).thenReturn(true); 220 221 Context context = mock(Context.class); 222 when(context.getPackageManager()).thenReturn(pkgMgr); 223 when(context.getContentResolver()).thenReturn(mock(ContentResolver.class)); 224 225 MockResources resources = new com.android.server.wifi.MockResources(); 226 when(context.getResources()).thenReturn(resources); 227 228 ContentResolver cr = mock(ContentResolver.class); 229 when(context.getContentResolver()).thenReturn(cr); 230 231 when(context.getSystemService(Context.POWER_SERVICE)).thenReturn( 232 new PowerManager(context, mock(IPowerManager.class), new Handler())); 233 234 mAlarmManager = new MockAlarmManager(); 235 when(context.getSystemService(Context.ALARM_SERVICE)).thenReturn( 236 mAlarmManager.getAlarmManager()); 237 238 when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn( 239 mock(ConnectivityManager.class)); 240 241 when(context.getSystemService(Context.WIFI_SCANNING_SERVICE)).thenReturn(mWifiScanner); 242 243 return context; 244 } 245 246 private Resources getMockResources() { 247 MockResources resources = new MockResources(); 248 resources.setBoolean(R.bool.config_wifi_enable_wifi_firmware_debugging, false); 249 return resources; 250 } 251 252 private IState getCurrentState() throws 253 NoSuchMethodException, InvocationTargetException, IllegalAccessException { 254 Method method = StateMachine.class.getDeclaredMethod("getCurrentState"); 255 method.setAccessible(true); 256 return (IState) method.invoke(mWsm); 257 } 258 259 private static HandlerThread getWsmHandlerThread(WifiStateMachine wsm) throws 260 NoSuchFieldException, InvocationTargetException, IllegalAccessException { 261 Field field = StateMachine.class.getDeclaredField("mSmThread"); 262 field.setAccessible(true); 263 return (HandlerThread) field.get(wsm); 264 } 265 266 private static void stopLooper(final Looper looper) throws Exception { 267 new Handler(looper).post(new Runnable() { 268 @Override 269 public void run() { 270 looper.quitSafely(); 271 } 272 }); 273 } 274 275 private void dumpState() { 276 ByteArrayOutputStream stream = new ByteArrayOutputStream(); 277 PrintWriter writer = new PrintWriter(stream); 278 mWsm.dump(null, writer, null); 279 writer.flush(); 280 Log.d(TAG, "WifiStateMachine state -" + stream.toString()); 281 } 282 283 private static ScanDetail getGoogleGuestScanDetail(int rssi) { 284 ScanResult.InformationElement ie[] = new ScanResult.InformationElement[1]; 285 ie[0] = ScanResults.generateSsidIe(sSSID); 286 NetworkDetail nd = new NetworkDetail(sBSSID, ie, new ArrayList<String>(), sFreq); 287 ScanDetail detail = new ScanDetail(nd, sWifiSsid, sBSSID, "", rssi, sFreq, 288 Long.MAX_VALUE, /* needed so that scan results aren't rejected because 289 there older than scan start */ 290 ie, new ArrayList<String>()); 291 return detail; 292 } 293 294 private ArrayList<ScanDetail> getMockScanResults() { 295 ScanResults sr = ScanResults.create(0, 2412, 2437, 2462, 5180, 5220, 5745, 5825); 296 ArrayList<ScanDetail> list = sr.getScanDetailArrayList(); 297 298 int rssi = -65; 299 list.add(getGoogleGuestScanDetail(rssi)); 300 return list; 301 } 302 303 static final String sSSID = "\"GoogleGuest\""; 304 static final WifiSsid sWifiSsid = WifiSsid.createFromAsciiEncoded(sSSID); 305 static final String sHexSSID = sWifiSsid.getHexString().replace("0x", "").replace("22", ""); 306 static final String sBSSID = "01:02:03:04:05:06"; 307 static final int sFreq = 2437; 308 309 WifiStateMachine mWsm; 310 HandlerThread mWsmThread; 311 HandlerThread mP2pThread; 312 HandlerThread mSyncThread; 313 AsyncChannel mWsmAsyncChannel; 314 MockAlarmManager mAlarmManager; 315 MockWifiMonitor mWifiMonitor; 316 TestIpManager mTestIpManager; 317 MockLooper mLooper; 318 WifiConfigManager mWifiConfigManager; 319 320 @Mock WifiNative mWifiNative; 321 @Mock WifiScanner mWifiScanner; 322 @Mock SupplicantStateTracker mSupplicantStateTracker; 323 @Mock WifiMetrics mWifiMetrics; 324 @Mock UserManager mUserManager; 325 @Mock WifiApConfigStore mApConfigStore; 326 @Mock BackupManagerProxy mBackupManagerProxy; 327 @Mock WifiCountryCode mCountryCode; 328 329 public WifiStateMachineTest() throws Exception { 330 } 331 332 @Before 333 public void setUp() throws Exception { 334 Log.d(TAG, "Setting up ..."); 335 336 // Ensure looper exists 337 mLooper = new MockLooper(); 338 339 MockitoAnnotations.initMocks(this); 340 341 /** uncomment this to enable logs from WifiStateMachines */ 342 // enableDebugLogs(); 343 344 TestUtil.installWlanWifiNative(mWifiNative); 345 mWifiMonitor = new MockWifiMonitor(); 346 mWifiMetrics = mock(WifiMetrics.class); 347 WifiInjector wifiInjector = mock(WifiInjector.class); 348 when(wifiInjector.getWifiMetrics()).thenReturn(mWifiMetrics); 349 FrameworkFacade factory = getFrameworkFacade(); 350 Context context = getContext(); 351 352 Resources resources = getMockResources(); 353 when(context.getResources()).thenReturn(resources); 354 355 when(factory.getIntegerSetting(context, 356 Settings.Global.WIFI_FREQUENCY_BAND, 357 WifiManager.WIFI_FREQUENCY_BAND_AUTO)).thenReturn( 358 WifiManager.WIFI_FREQUENCY_BAND_AUTO); 359 360 when(factory.makeApConfigStore(eq(context), eq(mBackupManagerProxy))) 361 .thenReturn(mApConfigStore); 362 363 when(factory.makeSupplicantStateTracker( 364 any(Context.class), any(WifiConfigManager.class), 365 any(Handler.class))).thenReturn(mSupplicantStateTracker); 366 367 when(mUserManager.getProfileParent(11)) 368 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "owner", 0)); 369 when(mUserManager.getProfiles(UserHandle.USER_SYSTEM)).thenReturn(Arrays.asList( 370 new UserInfo(UserHandle.USER_SYSTEM, "owner", 0), 371 new UserInfo(11, "managed profile", 0))); 372 373 mWsm = new WifiStateMachine(context, factory, mLooper.getLooper(), 374 mUserManager, wifiInjector, mBackupManagerProxy, mCountryCode); 375 mWsmThread = getWsmHandlerThread(mWsm); 376 377 final AsyncChannel channel = new AsyncChannel(); 378 Handler handler = new Handler(mLooper.getLooper()) { 379 @Override 380 public void handleMessage(Message msg) { 381 switch (msg.what) { 382 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: 383 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 384 mWsmAsyncChannel = channel; 385 } else { 386 Log.d(TAG, "Failed to connect Command channel " + this); 387 } 388 break; 389 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: 390 Log.d(TAG, "Command channel disconnected" + this); 391 break; 392 } 393 } 394 }; 395 396 channel.connect(context, handler, mWsm.getMessenger()); 397 mLooper.dispatchAll(); 398 /* Now channel is supposed to be connected */ 399 400 mBinderToken = Binder.clearCallingIdentity(); 401 } 402 403 @After 404 public void cleanUp() throws Exception { 405 Binder.restoreCallingIdentity(mBinderToken); 406 407 if (mSyncThread != null) stopLooper(mSyncThread.getLooper()); 408 if (mWsmThread != null) stopLooper(mWsmThread.getLooper()); 409 if (mP2pThread != null) stopLooper(mP2pThread.getLooper()); 410 411 mWsmThread = null; 412 mP2pThread = null; 413 mSyncThread = null; 414 mWsmAsyncChannel = null; 415 mWsm = null; 416 } 417 418 @Test 419 public void createNew() throws Exception { 420 assertEquals("InitialState", getCurrentState().getName()); 421 422 mWsm.sendMessage(WifiStateMachine.CMD_BOOT_COMPLETED); 423 mLooper.dispatchAll(); 424 assertEquals("InitialState", getCurrentState().getName()); 425 } 426 427 @Test 428 public void loadComponents() throws Exception { 429 when(mWifiNative.loadDriver()).thenReturn(true); 430 when(mWifiNative.startHal()).thenReturn(true); 431 when(mWifiNative.startSupplicant(anyBoolean())).thenReturn(true); 432 mWsm.setSupplicantRunning(true); 433 mLooper.dispatchAll(); 434 435 assertEquals("SupplicantStartingState", getCurrentState().getName()); 436 437 when(mWifiNative.setBand(anyInt())).thenReturn(true); 438 when(mWifiNative.setDeviceName(anyString())).thenReturn(true); 439 when(mWifiNative.setManufacturer(anyString())).thenReturn(true); 440 when(mWifiNative.setModelName(anyString())).thenReturn(true); 441 when(mWifiNative.setModelNumber(anyString())).thenReturn(true); 442 when(mWifiNative.setSerialNumber(anyString())).thenReturn(true); 443 when(mWifiNative.setConfigMethods(anyString())).thenReturn(true); 444 when(mWifiNative.setDeviceType(anyString())).thenReturn(true); 445 when(mWifiNative.setSerialNumber(anyString())).thenReturn(true); 446 when(mWifiNative.setScanningMacOui(any(byte[].class))).thenReturn(true); 447 448 mWsm.sendMessage(WifiMonitor.SUP_CONNECTION_EVENT); 449 mLooper.dispatchAll(); 450 451 assertEquals("DisconnectedState", getCurrentState().getName()); 452 } 453 454 @Test 455 public void loadComponentsFailure() throws Exception { 456 when(mWifiNative.loadDriver()).thenReturn(false); 457 when(mWifiNative.startHal()).thenReturn(false); 458 when(mWifiNative.startSupplicant(anyBoolean())).thenReturn(false); 459 460 mWsm.setSupplicantRunning(true); 461 mLooper.dispatchAll(); 462 assertEquals("InitialState", getCurrentState().getName()); 463 464 when(mWifiNative.loadDriver()).thenReturn(true); 465 mWsm.setSupplicantRunning(true); 466 mLooper.dispatchAll(); 467 assertEquals("InitialState", getCurrentState().getName()); 468 469 when(mWifiNative.startHal()).thenReturn(true); 470 mWsm.setSupplicantRunning(true); 471 mLooper.dispatchAll(); 472 assertEquals("InitialState", getCurrentState().getName()); 473 } 474 475 private void addNetworkAndVerifySuccess() throws Exception { 476 addNetworkAndVerifySuccess(false); 477 } 478 479 private void addNetworkAndVerifySuccess(boolean isHidden) throws Exception { 480 loadComponents(); 481 482 final HashMap<String, String> nameToValue = new HashMap<String, String>(); 483 484 when(mWifiNative.addNetwork()).thenReturn(0); 485 when(mWifiNative.setNetworkVariable(anyInt(), anyString(), anyString())) 486 .then(new AnswerWithArguments() { 487 public boolean answer(int netId, String name, String value) { 488 if (netId != 0) { 489 Log.d(TAG, "Can't set var " + name + " for " + netId); 490 return false; 491 } 492 493 Log.d(TAG, "Setting var " + name + " to " + value + " for " + netId); 494 nameToValue.put(name, value); 495 return true; 496 } 497 }); 498 499 when(mWifiNative.setNetworkExtra(anyInt(), anyString(), (Map<String, String>) anyObject())) 500 .then(new AnswerWithArguments() { 501 public boolean answer(int netId, String name, Map<String, String> values) { 502 if (netId != 0) { 503 Log.d(TAG, "Can't set extra " + name + " for " + netId); 504 return false; 505 } 506 507 Log.d(TAG, "Setting extra for " + netId); 508 return true; 509 } 510 }); 511 512 when(mWifiNative.getNetworkVariable(anyInt(), anyString())) 513 .then(new AnswerWithArguments() { 514 public String answer(int netId, String name) throws Throwable { 515 if (netId != 0) { 516 Log.d(TAG, "Can't find var " + name + " for " + netId); 517 return null; 518 } 519 String value = nameToValue.get(name); 520 if (value != null) { 521 Log.d(TAG, "Returning var " + name + " to " + value + " for " + netId); 522 } else { 523 Log.d(TAG, "Can't find var " + name + " for " + netId); 524 } 525 return value; 526 } 527 }); 528 529 WifiConfiguration config = new WifiConfiguration(); 530 config.SSID = sSSID; 531 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 532 config.hiddenSSID = isHidden; 533 mLooper.startAutoDispatch(); 534 mWsm.syncAddOrUpdateNetwork(mWsmAsyncChannel, config); 535 mLooper.stopAutoDispatch(); 536 537 verify(mWifiNative).addNetwork(); 538 verify(mWifiNative).setNetworkVariable(0, "ssid", sHexSSID); 539 if (isHidden) { 540 verify(mWifiNative).setNetworkVariable(0, "scan_ssid", Integer.toString(1)); 541 } 542 543 mLooper.startAutoDispatch(); 544 List<WifiConfiguration> configs = mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel); 545 mLooper.stopAutoDispatch(); 546 assertEquals(1, configs.size()); 547 548 WifiConfiguration config2 = configs.get(0); 549 assertEquals("\"GoogleGuest\"", config2.SSID); 550 assertTrue(config2.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)); 551 } 552 553 private void addNetworkAndVerifyFailure() throws Exception { 554 loadComponents(); 555 556 final WifiConfiguration config = new WifiConfiguration(); 557 config.SSID = sSSID; 558 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 559 560 mLooper.startAutoDispatch(); 561 mWsm.syncAddOrUpdateNetwork(mWsmAsyncChannel, config); 562 mLooper.stopAutoDispatch(); 563 564 verify(mWifiNative, never()).addNetwork(); 565 verify(mWifiNative, never()).setNetworkVariable(anyInt(), anyString(), anyString()); 566 567 mLooper.startAutoDispatch(); 568 assertTrue(mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel).isEmpty()); 569 mLooper.stopAutoDispatch(); 570 } 571 572 /** 573 * Verifies that the current foreground user is allowed to add a network. 574 */ 575 @Test 576 public void addNetworkAsCurrentUser() throws Exception { 577 addNetworkAndVerifySuccess(); 578 } 579 580 /** 581 * Verifies that a managed profile of the current foreground user is allowed to add a network. 582 */ 583 @Test 584 public void addNetworkAsCurrentUsersManagedProfile() throws Exception { 585 BinderUtil.setUid(MANAGED_PROFILE_UID); 586 addNetworkAndVerifySuccess(); 587 } 588 589 /** 590 * Verifies that a background user is not allowed to add a network. 591 */ 592 @Test 593 public void addNetworkAsOtherUser() throws Exception { 594 BinderUtil.setUid(OTHER_USER_UID); 595 addNetworkAndVerifyFailure(); 596 } 597 598 private void removeNetworkAndVerifySuccess() throws Exception { 599 when(mWifiNative.removeNetwork(0)).thenReturn(true); 600 mLooper.startAutoDispatch(); 601 assertTrue(mWsm.syncRemoveNetwork(mWsmAsyncChannel, 0)); 602 mLooper.stopAutoDispatch(); 603 604 mLooper.startAutoDispatch(); 605 assertTrue(mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel).isEmpty()); 606 mLooper.stopAutoDispatch(); 607 } 608 609 private void removeNetworkAndVerifyFailure() throws Exception { 610 mLooper.startAutoDispatch(); 611 assertFalse(mWsm.syncRemoveNetwork(mWsmAsyncChannel, 0)); 612 mLooper.stopAutoDispatch(); 613 614 mLooper.startAutoDispatch(); 615 assertEquals(1, mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel).size()); 616 mLooper.stopAutoDispatch(); 617 verify(mWifiNative, never()).removeNetwork(anyInt()); 618 } 619 620 /** 621 * Verifies that the current foreground user is allowed to remove a network. 622 */ 623 @Test 624 public void removeNetworkAsCurrentUser() throws Exception { 625 addNetworkAndVerifySuccess(); 626 removeNetworkAndVerifySuccess(); 627 } 628 629 /** 630 * Verifies that a managed profile of the current foreground user is allowed to remove a 631 * network. 632 */ 633 @Test 634 public void removeNetworkAsCurrentUsersManagedProfile() throws Exception { 635 addNetworkAndVerifySuccess(); 636 BinderUtil.setUid(MANAGED_PROFILE_UID); 637 removeNetworkAndVerifySuccess(); 638 } 639 640 /** 641 * Verifies that a background user is not allowed to remove a network. 642 */ 643 @Test 644 public void removeNetworkAsOtherUser() throws Exception { 645 addNetworkAndVerifySuccess(); 646 BinderUtil.setUid(OTHER_USER_UID); 647 removeNetworkAndVerifyFailure(); 648 } 649 650 private void enableNetworkAndVerifySuccess() throws Exception { 651 when(mWifiNative.selectNetwork(0)).thenReturn(true); 652 653 mLooper.startAutoDispatch(); 654 assertTrue(mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true)); 655 mLooper.stopAutoDispatch(); 656 657 verify(mWifiNative).selectNetwork(0); 658 } 659 660 private void enableNetworkAndVerifyFailure() throws Exception { 661 mLooper.startAutoDispatch(); 662 assertFalse(mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true)); 663 mLooper.stopAutoDispatch(); 664 665 verify(mWifiNative, never()).selectNetwork(anyInt()); 666 } 667 668 /** 669 * Verifies that the current foreground user is allowed to enable a network. 670 */ 671 @Test 672 public void enableNetworkAsCurrentUser() throws Exception { 673 addNetworkAndVerifySuccess(); 674 enableNetworkAndVerifySuccess(); 675 } 676 677 /** 678 * Verifies that a managed profile of the current foreground user is allowed to enable a 679 * network. 680 */ 681 @Test 682 public void enableNetworkAsCurrentUsersManagedProfile() throws Exception { 683 addNetworkAndVerifySuccess(); 684 BinderUtil.setUid(MANAGED_PROFILE_UID); 685 enableNetworkAndVerifySuccess(); 686 } 687 688 /** 689 * Verifies that a background user is not allowed to enable a network. 690 */ 691 @Test 692 public void enableNetworkAsOtherUser() throws Exception { 693 addNetworkAndVerifySuccess(); 694 BinderUtil.setUid(OTHER_USER_UID); 695 enableNetworkAndVerifyFailure(); 696 } 697 698 private void forgetNetworkAndVerifySuccess() throws Exception { 699 when(mWifiNative.removeNetwork(0)).thenReturn(true); 700 mLooper.startAutoDispatch(); 701 final Message result = 702 mWsmAsyncChannel.sendMessageSynchronously(WifiManager.FORGET_NETWORK, 0); 703 mLooper.stopAutoDispatch(); 704 assertEquals(WifiManager.FORGET_NETWORK_SUCCEEDED, result.what); 705 result.recycle(); 706 mLooper.startAutoDispatch(); 707 assertTrue(mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel).isEmpty()); 708 mLooper.stopAutoDispatch(); 709 } 710 711 private void forgetNetworkAndVerifyFailure() throws Exception { 712 mLooper.startAutoDispatch(); 713 final Message result = 714 mWsmAsyncChannel.sendMessageSynchronously(WifiManager.FORGET_NETWORK, 0); 715 mLooper.stopAutoDispatch(); 716 assertEquals(WifiManager.FORGET_NETWORK_FAILED, result.what); 717 result.recycle(); 718 mLooper.startAutoDispatch(); 719 assertEquals(1, mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel).size()); 720 mLooper.stopAutoDispatch(); 721 verify(mWifiNative, never()).removeNetwork(anyInt()); 722 } 723 724 /** 725 * Verifies that the current foreground user is allowed to forget a network. 726 */ 727 @Test 728 public void forgetNetworkAsCurrentUser() throws Exception { 729 addNetworkAndVerifySuccess(); 730 forgetNetworkAndVerifySuccess(); 731 } 732 733 /** 734 * Verifies that a managed profile of the current foreground user is allowed to forget a 735 * network. 736 */ 737 @Test 738 public void forgetNetworkAsCurrentUsersManagedProfile() throws Exception { 739 addNetworkAndVerifySuccess(); 740 BinderUtil.setUid(MANAGED_PROFILE_UID); 741 forgetNetworkAndVerifySuccess(); 742 } 743 744 /** 745 * Verifies that a background user is not allowed to forget a network. 746 */ 747 @Test 748 public void forgetNetworkAsOtherUser() throws Exception { 749 addNetworkAndVerifySuccess(); 750 BinderUtil.setUid(OTHER_USER_UID); 751 forgetNetworkAndVerifyFailure(); 752 } 753 754 private void verifyScan(int band, int reportEvents, Set<Integer> configuredNetworkIds) { 755 ArgumentCaptor<WifiScanner.ScanSettings> scanSettingsCaptor = 756 ArgumentCaptor.forClass(WifiScanner.ScanSettings.class); 757 ArgumentCaptor<WifiScanner.ScanListener> scanListenerCaptor = 758 ArgumentCaptor.forClass(WifiScanner.ScanListener.class); 759 verify(mWifiScanner).startScan(scanSettingsCaptor.capture(), scanListenerCaptor.capture(), 760 eq(null)); 761 WifiScanner.ScanSettings actualSettings = scanSettingsCaptor.getValue(); 762 assertEquals("band", band, actualSettings.band); 763 assertEquals("reportEvents", reportEvents, actualSettings.reportEvents); 764 765 if (configuredNetworkIds == null) { 766 configuredNetworkIds = new HashSet<>(); 767 } 768 Set<Integer> actualConfiguredNetworkIds = new HashSet<>(); 769 if (actualSettings.hiddenNetworkIds != null) { 770 for (int i = 0; i < actualSettings.hiddenNetworkIds.length; ++i) { 771 actualConfiguredNetworkIds.add(actualSettings.hiddenNetworkIds[i]); 772 } 773 } 774 assertEquals("configured networks", configuredNetworkIds, actualConfiguredNetworkIds); 775 776 when(mWifiNative.getScanResults()).thenReturn(getMockScanResults()); 777 mWsm.sendMessage(WifiMonitor.SCAN_RESULTS_EVENT); 778 779 mLooper.dispatchAll(); 780 781 List<ScanResult> reportedResults = mWsm.syncGetScanResultsList(); 782 assertEquals(8, reportedResults.size()); 783 } 784 785 @Test 786 public void scan() throws Exception { 787 addNetworkAndVerifySuccess(); 788 789 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 790 mWsm.startScan(-1, 0, null, null); 791 mLooper.dispatchAll(); 792 793 verifyScan(WifiScanner.WIFI_BAND_BOTH_WITH_DFS, 794 WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN 795 | WifiScanner.REPORT_EVENT_FULL_SCAN_RESULT, null); 796 } 797 798 @Test 799 public void scanWithHiddenNetwork() throws Exception { 800 addNetworkAndVerifySuccess(true); 801 802 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 803 mWsm.startScan(-1, 0, null, null); 804 mLooper.dispatchAll(); 805 806 verifyScan(WifiScanner.WIFI_BAND_BOTH_WITH_DFS, 807 WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN 808 | WifiScanner.REPORT_EVENT_FULL_SCAN_RESULT, 809 mWifiConfigManager.getHiddenConfiguredNetworkIds()); 810 } 811 812 @Test 813 public void connect() throws Exception { 814 addNetworkAndVerifySuccess(); 815 816 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 817 mLooper.dispatchAll(); 818 819 mLooper.startAutoDispatch(); 820 mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true); 821 mLooper.stopAutoDispatch(); 822 823 verify(mWifiNative).selectNetwork(0); 824 825 mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, sBSSID); 826 mLooper.dispatchAll(); 827 828 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 829 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 830 mLooper.dispatchAll(); 831 832 assertEquals("ObtainingIpState", getCurrentState().getName()); 833 834 DhcpResults dhcpResults = new DhcpResults(); 835 dhcpResults.setGateway("1.2.3.4"); 836 dhcpResults.setIpAddress("192.168.1.100", 0); 837 dhcpResults.addDns("8.8.8.8"); 838 dhcpResults.setLeaseDuration(3600); 839 840 mTestIpManager.injectDhcpSuccess(dhcpResults); 841 mLooper.dispatchAll(); 842 843 assertEquals("ConnectedState", getCurrentState().getName()); 844 } 845 846 @Test 847 public void testDhcpFailure() throws Exception { 848 addNetworkAndVerifySuccess(); 849 850 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 851 mLooper.dispatchAll(); 852 853 mLooper.startAutoDispatch(); 854 mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true); 855 mLooper.stopAutoDispatch(); 856 857 verify(mWifiNative).selectNetwork(0); 858 859 mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, sBSSID); 860 mLooper.dispatchAll(); 861 862 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 863 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 864 mLooper.dispatchAll(); 865 866 assertEquals("ObtainingIpState", getCurrentState().getName()); 867 868 mTestIpManager.injectDhcpFailure(); 869 mLooper.dispatchAll(); 870 871 assertEquals("DisconnectingState", getCurrentState().getName()); 872 } 873 874 @Test 875 public void testBadNetworkEvent() throws Exception { 876 addNetworkAndVerifySuccess(); 877 878 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 879 mLooper.dispatchAll(); 880 881 mLooper.startAutoDispatch(); 882 mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true); 883 mLooper.stopAutoDispatch(); 884 885 verify(mWifiNative).selectNetwork(0); 886 887 mWsm.sendMessage(WifiMonitor.NETWORK_DISCONNECTION_EVENT, 0, 0, sBSSID); 888 mLooper.dispatchAll(); 889 890 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 891 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 892 mLooper.dispatchAll(); 893 894 assertEquals("DisconnectedState", getCurrentState().getName()); 895 } 896 897 898 @Test 899 public void smToString() throws Exception { 900 assertEquals("CMD_CHANNEL_HALF_CONNECTED", mWsm.smToString( 901 AsyncChannel.CMD_CHANNEL_HALF_CONNECTED)); 902 assertEquals("CMD_PRE_DHCP_ACTION", mWsm.smToString( 903 DhcpClient.CMD_PRE_DHCP_ACTION)); 904 assertEquals("CMD_IP_REACHABILITY_LOST", mWsm.smToString( 905 WifiStateMachine.CMD_IP_REACHABILITY_LOST)); 906 } 907 908 @Test 909 public void disconnect() throws Exception { 910 connect(); 911 912 mWsm.sendMessage(WifiMonitor.NETWORK_DISCONNECTION_EVENT, -1, 3, "01:02:03:04:05:06"); 913 mLooper.dispatchAll(); 914 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 915 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.DISCONNECTED)); 916 mLooper.dispatchAll(); 917 918 assertEquals("DisconnectedState", getCurrentState().getName()); 919 } 920 921 @Test 922 public void handleUserSwitch() throws Exception { 923 assertEquals(UserHandle.USER_SYSTEM, mWsm.getCurrentUserId()); 924 925 mWsm.handleUserSwitch(10); 926 mLooper.dispatchAll(); 927 928 assertEquals(10, mWsm.getCurrentUserId()); 929 } 930 931 @Test 932 public void iconQueryTest() throws Exception { 933 /* enable wi-fi */ 934 addNetworkAndVerifySuccess(); 935 936 long bssid = 0x1234567800FFL; 937 String filename = "iconFileName.png"; 938 String command = "REQ_HS20_ICON " + Utils.macToString(bssid) + " " + filename; 939 940 when(mWifiNative.doCustomSupplicantCommand(command)).thenReturn("OK"); 941 942 mLooper.startAutoDispatch(); 943 boolean result = mWsm.syncQueryPasspointIcon(mWsmAsyncChannel, bssid, filename); 944 mLooper.stopAutoDispatch(); 945 946 verify(mWifiNative).doCustomSupplicantCommand(command); 947 assertEquals(true, result); 948 } 949 950 private String createSimChallengeRequest(byte[] challengeValue) { 951 // Produce a base64 encoded length byte + data. 952 byte[] challengeLengthAndValue = new byte[challengeValue.length + 1]; 953 challengeLengthAndValue[0] = (byte) challengeValue.length; 954 for (int i = 0; i < challengeValue.length; ++i) { 955 challengeLengthAndValue[i + 1] = challengeValue[i]; 956 } 957 return Base64.encodeToString(challengeLengthAndValue, android.util.Base64.NO_WRAP); 958 } 959 960 private String createSimAuthResponse(byte[] sresValue, byte[] kcValue) { 961 // Produce a base64 encoded sres length byte + sres + kc length byte + kc. 962 int overallLength = sresValue.length + kcValue.length + 2; 963 byte[] result = new byte[sresValue.length + kcValue.length + 2]; 964 int idx = 0; 965 result[idx++] = (byte) sresValue.length; 966 for (int i = 0; i < sresValue.length; ++i) { 967 result[idx++] = sresValue[i]; 968 } 969 result[idx++] = (byte) kcValue.length; 970 for (int i = 0; i < kcValue.length; ++i) { 971 result[idx++] = kcValue[i]; 972 } 973 return Base64.encodeToString(result, Base64.NO_WRAP); 974 } 975 976 /** Verifies function getGsmSimAuthResponse method. */ 977 @Test 978 public void getGsmSimAuthResponseTest() throws Exception { 979 TelephonyManager tm = mock(TelephonyManager.class); 980 final String[] invalidRequests = { null, "", "XXXX" }; 981 assertEquals("", mWsm.getGsmSimAuthResponse(invalidRequests, tm)); 982 983 final String[] failedRequests = { "5E5F" }; 984 when(tm.getIccSimChallengeResponse(anyInt(), 985 eq(createSimChallengeRequest(new byte[] { 0x5e, 0x5f })))).thenReturn(null); 986 assertEquals(null, mWsm.getGsmSimAuthResponse(failedRequests, tm)); 987 988 when(tm.getIccSimChallengeResponse(2, createSimChallengeRequest(new byte[] { 0x1a, 0x2b }))) 989 .thenReturn(null); 990 when(tm.getIccSimChallengeResponse(1, createSimChallengeRequest(new byte[] { 0x1a, 0x2b }))) 991 .thenReturn(createSimAuthResponse(new byte[] { 0x1D, 0x2C }, 992 new byte[] { 0x3B, 0x4A })); 993 when(tm.getIccSimChallengeResponse(1, createSimChallengeRequest(new byte[] { 0x01, 0x23 }))) 994 .thenReturn(createSimAuthResponse(new byte[] { 0x33, 0x22 }, 995 new byte[] { 0x11, 0x00 })); 996 assertEquals(":3b4a:1d2c:1100:3322", mWsm.getGsmSimAuthResponse( 997 new String[] { "1A2B", "0123" }, tm)); 998 } 999} 1000