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 android.net.wifi.WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE; 20import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_FAILURE_REASON; 21import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_INTERFACE_NAME; 22import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_MODE; 23import static android.net.wifi.WifiManager.EXTRA_WIFI_AP_STATE; 24import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED; 25import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLING; 26import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED; 27import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLING; 28 29import static com.android.server.wifi.LocalOnlyHotspotRequestInfo.HOTSPOT_NO_ERROR; 30 31import static org.junit.Assert.assertEquals; 32import static org.junit.Assert.assertFalse; 33import static org.junit.Assert.assertNull; 34import static org.junit.Assert.assertTrue; 35import static org.mockito.Mockito.*; 36 37import android.app.ActivityManager; 38import android.app.test.MockAnswerUtil.AnswerWithArguments; 39import android.app.test.TestAlarmManager; 40import android.content.Context; 41import android.content.Intent; 42import android.content.pm.PackageManager; 43import android.content.pm.UserInfo; 44import android.content.res.Resources; 45import android.net.ConnectivityManager; 46import android.net.DhcpResults; 47import android.net.LinkProperties; 48import android.net.dhcp.DhcpClient; 49import android.net.ip.IpManager; 50import android.net.wifi.IApInterface; 51import android.net.wifi.IClientInterface; 52import android.net.wifi.IWificond; 53import android.net.wifi.ScanResult; 54import android.net.wifi.SupplicantState; 55import android.net.wifi.WifiConfiguration; 56import android.net.wifi.WifiInfo; 57import android.net.wifi.WifiManager; 58import android.net.wifi.WifiScanner; 59import android.net.wifi.WifiSsid; 60import android.net.wifi.WpsInfo; 61import android.net.wifi.hotspot2.PasspointConfiguration; 62import android.net.wifi.hotspot2.pps.HomeSp; 63import android.net.wifi.p2p.IWifiP2pManager; 64import android.os.BatteryStats; 65import android.os.Binder; 66import android.os.Bundle; 67import android.os.Handler; 68import android.os.HandlerThread; 69import android.os.IBinder; 70import android.os.IInterface; 71import android.os.INetworkManagementService; 72import android.os.IPowerManager; 73import android.os.Looper; 74import android.os.Message; 75import android.os.Messenger; 76import android.os.PowerManager; 77import android.os.RemoteException; 78import android.os.UserHandle; 79import android.os.UserManager; 80import android.os.test.TestLooper; 81import android.provider.Settings; 82import android.security.KeyStore; 83import android.test.mock.MockContentProvider; 84import android.test.mock.MockContentResolver; 85import android.test.suitebuilder.annotation.SmallTest; 86import android.util.Log; 87import android.util.SparseArray; 88 89import com.android.internal.R; 90import com.android.internal.app.IBatteryStats; 91import com.android.internal.util.AsyncChannel; 92import com.android.internal.util.IState; 93import com.android.internal.util.StateMachine; 94import com.android.server.wifi.hotspot2.NetworkDetail; 95import com.android.server.wifi.hotspot2.PasspointManager; 96import com.android.server.wifi.p2p.WifiP2pServiceImpl; 97 98import org.junit.After; 99import org.junit.Before; 100import org.junit.Test; 101import org.mockito.ArgumentCaptor; 102import org.mockito.ArgumentMatcher; 103import org.mockito.InOrder; 104import org.mockito.Mock; 105import org.mockito.MockitoAnnotations; 106 107import java.io.ByteArrayOutputStream; 108import java.io.PrintWriter; 109import java.lang.reflect.Field; 110import java.lang.reflect.InvocationTargetException; 111import java.lang.reflect.Method; 112import java.util.ArrayList; 113import java.util.Arrays; 114import java.util.HashSet; 115import java.util.List; 116import java.util.Map; 117import java.util.Set; 118import java.util.concurrent.CountDownLatch; 119 120/** 121 * Unit tests for {@link com.android.server.wifi.WifiStateMachine}. 122 */ 123@SmallTest 124public class WifiStateMachineTest { 125 public static final String TAG = "WifiStateMachineTest"; 126 127 private static final int MANAGED_PROFILE_UID = 1100000; 128 private static final int OTHER_USER_UID = 1200000; 129 private static final int LOG_REC_LIMIT_IN_VERBOSE_MODE = 130 (ActivityManager.isLowRamDeviceStatic() 131 ? WifiStateMachine.NUM_LOG_RECS_VERBOSE_LOW_MEMORY 132 : WifiStateMachine.NUM_LOG_RECS_VERBOSE); 133 private static final int WPS_SUPPLICANT_NETWORK_ID = 5; 134 private static final int WPS_FRAMEWORK_NETWORK_ID = 10; 135 private static final String DEFAULT_TEST_SSID = "\"GoogleGuest\""; 136 137 private long mBinderToken; 138 139 private static <T> T mockWithInterfaces(Class<T> class1, Class<?>... interfaces) { 140 return mock(class1, withSettings().extraInterfaces(interfaces)); 141 } 142 143 private static <T, I> IBinder mockService(Class<T> class1, Class<I> iface) { 144 T tImpl = mockWithInterfaces(class1, iface); 145 IBinder binder = mock(IBinder.class); 146 when(((IInterface) tImpl).asBinder()).thenReturn(binder); 147 when(binder.queryLocalInterface(iface.getCanonicalName())) 148 .thenReturn((IInterface) tImpl); 149 return binder; 150 } 151 152 private void enableDebugLogs() { 153 mWsm.enableVerboseLogging(1); 154 } 155 156 private class TestIpManager extends IpManager { 157 TestIpManager(Context context, String ifname, IpManager.Callback callback) { 158 // Call dependency-injection superclass constructor. 159 super(context, ifname, callback, mock(INetworkManagementService.class)); 160 } 161 162 @Override 163 public void startProvisioning(IpManager.ProvisioningConfiguration config) {} 164 165 @Override 166 public void stop() {} 167 168 @Override 169 public void confirmConfiguration() {} 170 171 void injectDhcpSuccess(DhcpResults dhcpResults) { 172 mCallback.onNewDhcpResults(dhcpResults); 173 mCallback.onProvisioningSuccess(new LinkProperties()); 174 } 175 176 void injectDhcpFailure() { 177 mCallback.onNewDhcpResults(null); 178 mCallback.onProvisioningFailure(new LinkProperties()); 179 } 180 } 181 182 private FrameworkFacade getFrameworkFacade() throws Exception { 183 FrameworkFacade facade = mock(FrameworkFacade.class); 184 185 when(facade.getService(Context.NETWORKMANAGEMENT_SERVICE)).thenReturn( 186 mockWithInterfaces(IBinder.class, INetworkManagementService.class)); 187 188 IBinder p2pBinder = mockService(WifiP2pServiceImpl.class, IWifiP2pManager.class); 189 when(facade.getService(Context.WIFI_P2P_SERVICE)).thenReturn(p2pBinder); 190 191 WifiP2pServiceImpl p2pm = (WifiP2pServiceImpl) p2pBinder.queryLocalInterface( 192 IWifiP2pManager.class.getCanonicalName()); 193 194 final CountDownLatch untilDone = new CountDownLatch(1); 195 mP2pThread = new HandlerThread("WifiP2pMockThread") { 196 @Override 197 protected void onLooperPrepared() { 198 untilDone.countDown(); 199 } 200 }; 201 202 mP2pThread.start(); 203 untilDone.await(); 204 205 Handler handler = new Handler(mP2pThread.getLooper()); 206 when(p2pm.getP2pStateMachineMessenger()).thenReturn(new Messenger(handler)); 207 208 IBinder batteryStatsBinder = mockService(BatteryStats.class, IBatteryStats.class); 209 when(facade.getService(BatteryStats.SERVICE_NAME)).thenReturn(batteryStatsBinder); 210 211 when(facade.makeIpManager(any(Context.class), anyString(), any(IpManager.Callback.class))) 212 .then(new AnswerWithArguments() { 213 public IpManager answer( 214 Context context, String ifname, IpManager.Callback callback) { 215 mTestIpManager = new TestIpManager(context, ifname, callback); 216 return mTestIpManager; 217 } 218 }); 219 220 return facade; 221 } 222 223 private Context getContext() throws Exception { 224 PackageManager pkgMgr = mock(PackageManager.class); 225 when(pkgMgr.hasSystemFeature(PackageManager.FEATURE_WIFI_DIRECT)).thenReturn(true); 226 227 Context context = mock(Context.class); 228 when(context.getPackageManager()).thenReturn(pkgMgr); 229 230 MockResources resources = new com.android.server.wifi.MockResources(); 231 when(context.getResources()).thenReturn(resources); 232 233 MockContentResolver mockContentResolver = new MockContentResolver(); 234 mockContentResolver.addProvider(Settings.AUTHORITY, 235 new MockContentProvider(context) { 236 @Override 237 public Bundle call(String method, String arg, Bundle extras) { 238 return new Bundle(); 239 } 240 }); 241 when(context.getContentResolver()).thenReturn(mockContentResolver); 242 243 when(context.getSystemService(Context.POWER_SERVICE)).thenReturn( 244 new PowerManager(context, mock(IPowerManager.class), new Handler())); 245 246 mAlarmManager = new TestAlarmManager(); 247 when(context.getSystemService(Context.ALARM_SERVICE)).thenReturn( 248 mAlarmManager.getAlarmManager()); 249 250 when(context.getSystemService(Context.CONNECTIVITY_SERVICE)).thenReturn( 251 mock(ConnectivityManager.class)); 252 253 return context; 254 } 255 256 private Resources getMockResources() { 257 MockResources resources = new MockResources(); 258 resources.setBoolean(R.bool.config_wifi_enable_wifi_firmware_debugging, false); 259 return resources; 260 } 261 262 private IState getCurrentState() throws 263 NoSuchMethodException, InvocationTargetException, IllegalAccessException { 264 Method method = StateMachine.class.getDeclaredMethod("getCurrentState"); 265 method.setAccessible(true); 266 return (IState) method.invoke(mWsm); 267 } 268 269 private static HandlerThread getWsmHandlerThread(WifiStateMachine wsm) throws 270 NoSuchFieldException, InvocationTargetException, IllegalAccessException { 271 Field field = StateMachine.class.getDeclaredField("mSmThread"); 272 field.setAccessible(true); 273 return (HandlerThread) field.get(wsm); 274 } 275 276 private static void stopLooper(final Looper looper) throws Exception { 277 new Handler(looper).post(new Runnable() { 278 @Override 279 public void run() { 280 looper.quitSafely(); 281 } 282 }); 283 } 284 285 private void dumpState() { 286 ByteArrayOutputStream stream = new ByteArrayOutputStream(); 287 PrintWriter writer = new PrintWriter(stream); 288 mWsm.dump(null, writer, null); 289 writer.flush(); 290 Log.d(TAG, "WifiStateMachine state -" + stream.toString()); 291 } 292 293 private static ScanDetail getGoogleGuestScanDetail(int rssi) { 294 ScanResult.InformationElement ie[] = new ScanResult.InformationElement[1]; 295 ie[0] = ScanResults.generateSsidIe(sSSID); 296 NetworkDetail nd = new NetworkDetail(sBSSID, ie, new ArrayList<String>(), sFreq); 297 ScanDetail detail = new ScanDetail(nd, sWifiSsid, sBSSID, "", rssi, sFreq, 298 Long.MAX_VALUE, /* needed so that scan results aren't rejected because 299 there older than scan start */ 300 ie, new ArrayList<String>()); 301 return detail; 302 } 303 304 private ArrayList<ScanDetail> getMockScanResults() { 305 ScanResults sr = ScanResults.create(0, 2412, 2437, 2462, 5180, 5220, 5745, 5825); 306 ArrayList<ScanDetail> list = sr.getScanDetailArrayList(); 307 308 int rssi = -65; 309 list.add(getGoogleGuestScanDetail(rssi)); 310 return list; 311 } 312 313 static final String sSSID = "\"GoogleGuest\""; 314 static final WifiSsid sWifiSsid = WifiSsid.createFromAsciiEncoded(sSSID); 315 static final String sHexSSID = sWifiSsid.getHexString().replace("0x", "").replace("22", ""); 316 static final String sBSSID = "01:02:03:04:05:06"; 317 static final int sFreq = 2437; 318 static final String WIFI_IFACE_NAME = "mockWlan"; 319 320 WifiStateMachine mWsm; 321 HandlerThread mWsmThread; 322 HandlerThread mP2pThread; 323 HandlerThread mSyncThread; 324 AsyncChannel mWsmAsyncChannel; 325 TestAlarmManager mAlarmManager; 326 MockWifiMonitor mWifiMonitor; 327 TestIpManager mTestIpManager; 328 TestLooper mLooper; 329 Context mContext; 330 331 final ArgumentCaptor<SoftApManager.Listener> mSoftApManagerListenerCaptor = 332 ArgumentCaptor.forClass(SoftApManager.Listener.class); 333 334 @Mock WifiScanner mWifiScanner; 335 @Mock SupplicantStateTracker mSupplicantStateTracker; 336 @Mock WifiMetrics mWifiMetrics; 337 @Mock UserManager mUserManager; 338 @Mock WifiApConfigStore mApConfigStore; 339 @Mock BackupManagerProxy mBackupManagerProxy; 340 @Mock WifiCountryCode mCountryCode; 341 @Mock WifiInjector mWifiInjector; 342 @Mock WifiLastResortWatchdog mWifiLastResortWatchdog; 343 @Mock PropertyService mPropertyService; 344 @Mock BuildProperties mBuildProperties; 345 @Mock IWificond mWificond; 346 @Mock IApInterface mApInterface; 347 @Mock IClientInterface mClientInterface; 348 @Mock IBinder mApInterfaceBinder; 349 @Mock IBinder mClientInterfaceBinder; 350 @Mock WifiConfigManager mWifiConfigManager; 351 @Mock WifiNative mWifiNative; 352 @Mock WifiConnectivityManager mWifiConnectivityManager; 353 @Mock SoftApManager mSoftApManager; 354 @Mock WifiStateTracker mWifiStateTracker; 355 @Mock PasspointManager mPasspointManager; 356 @Mock SelfRecovery mSelfRecovery; 357 358 public WifiStateMachineTest() throws Exception { 359 } 360 361 @Before 362 public void setUp() throws Exception { 363 Log.d(TAG, "Setting up ..."); 364 365 // Ensure looper exists 366 mLooper = new TestLooper(); 367 368 MockitoAnnotations.initMocks(this); 369 370 /** uncomment this to enable logs from WifiStateMachines */ 371 // enableDebugLogs(); 372 373 mWifiMonitor = new MockWifiMonitor(); 374 when(mWifiInjector.getWifiMetrics()).thenReturn(mWifiMetrics); 375 when(mWifiInjector.getClock()).thenReturn(new Clock()); 376 when(mWifiInjector.getWifiLastResortWatchdog()).thenReturn(mWifiLastResortWatchdog); 377 when(mWifiInjector.getPropertyService()).thenReturn(mPropertyService); 378 when(mWifiInjector.getBuildProperties()).thenReturn(mBuildProperties); 379 when(mWifiInjector.getKeyStore()).thenReturn(mock(KeyStore.class)); 380 when(mWifiInjector.getWifiBackupRestore()).thenReturn(mock(WifiBackupRestore.class)); 381 when(mWifiInjector.makeWifiDiagnostics(anyObject())).thenReturn( 382 mock(BaseWifiDiagnostics.class)); 383 when(mWifiInjector.makeWificond()).thenReturn(mWificond); 384 when(mWifiInjector.getWifiConfigManager()).thenReturn(mWifiConfigManager); 385 when(mWifiInjector.getWifiScanner()).thenReturn(mWifiScanner); 386 when(mWifiInjector.makeWifiConnectivityManager(any(WifiInfo.class), anyBoolean())) 387 .thenReturn(mWifiConnectivityManager); 388 when(mWifiInjector.makeSoftApManager(any(INetworkManagementService.class), 389 mSoftApManagerListenerCaptor.capture(), any(IApInterface.class), 390 any(WifiConfiguration.class))) 391 .thenReturn(mSoftApManager); 392 when(mWifiInjector.getPasspointManager()).thenReturn(mPasspointManager); 393 when(mWifiInjector.getWifiStateTracker()).thenReturn(mWifiStateTracker); 394 when(mWifiInjector.getWifiMonitor()).thenReturn(mWifiMonitor); 395 when(mWifiInjector.getWifiNative()).thenReturn(mWifiNative); 396 when(mWifiInjector.getSelfRecovery()).thenReturn(mSelfRecovery); 397 398 when(mWifiNative.setupForClientMode()).thenReturn(mClientInterface); 399 when(mWifiNative.setupForSoftApMode()).thenReturn(mApInterface); 400 when(mApInterface.getInterfaceName()).thenReturn(WIFI_IFACE_NAME); 401 when(mWifiNative.getInterfaceName()).thenReturn(WIFI_IFACE_NAME); 402 when(mWifiNative.enableSupplicant()).thenReturn(true); 403 when(mWifiNative.disableSupplicant()).thenReturn(true); 404 when(mWifiNative.getFrameworkNetworkId(anyInt())).thenReturn(0); 405 406 407 FrameworkFacade factory = getFrameworkFacade(); 408 mContext = getContext(); 409 410 Resources resources = getMockResources(); 411 when(mContext.getResources()).thenReturn(resources); 412 413 when(factory.getIntegerSetting(mContext, 414 Settings.Global.WIFI_FREQUENCY_BAND, 415 WifiManager.WIFI_FREQUENCY_BAND_AUTO)).thenReturn( 416 WifiManager.WIFI_FREQUENCY_BAND_AUTO); 417 418 when(factory.makeApConfigStore(eq(mContext), eq(mBackupManagerProxy))) 419 .thenReturn(mApConfigStore); 420 421 when(factory.makeSupplicantStateTracker( 422 any(Context.class), any(WifiConfigManager.class), 423 any(Handler.class))).thenReturn(mSupplicantStateTracker); 424 425 when(mUserManager.getProfileParent(11)) 426 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "owner", 0)); 427 when(mUserManager.getProfiles(UserHandle.USER_SYSTEM)).thenReturn(Arrays.asList( 428 new UserInfo(UserHandle.USER_SYSTEM, "owner", 0), 429 new UserInfo(11, "managed profile", 0))); 430 431 when(mApInterface.asBinder()).thenReturn(mApInterfaceBinder); 432 when(mClientInterface.asBinder()).thenReturn(mClientInterfaceBinder); 433 434 mWsm = new WifiStateMachine(mContext, factory, mLooper.getLooper(), 435 mUserManager, mWifiInjector, mBackupManagerProxy, mCountryCode, mWifiNative); 436 mWsmThread = getWsmHandlerThread(mWsm); 437 438 final AsyncChannel channel = new AsyncChannel(); 439 Handler handler = new Handler(mLooper.getLooper()) { 440 @Override 441 public void handleMessage(Message msg) { 442 switch (msg.what) { 443 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: 444 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 445 mWsmAsyncChannel = channel; 446 } else { 447 Log.d(TAG, "Failed to connect Command channel " + this); 448 } 449 break; 450 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: 451 Log.d(TAG, "Command channel disconnected" + this); 452 break; 453 } 454 } 455 }; 456 457 channel.connect(mContext, handler, mWsm.getMessenger()); 458 mLooper.dispatchAll(); 459 /* Now channel is supposed to be connected */ 460 461 mBinderToken = Binder.clearCallingIdentity(); 462 } 463 464 @After 465 public void cleanUp() throws Exception { 466 Binder.restoreCallingIdentity(mBinderToken); 467 468 if (mSyncThread != null) stopLooper(mSyncThread.getLooper()); 469 if (mWsmThread != null) stopLooper(mWsmThread.getLooper()); 470 if (mP2pThread != null) stopLooper(mP2pThread.getLooper()); 471 472 mWsmThread = null; 473 mP2pThread = null; 474 mSyncThread = null; 475 mWsmAsyncChannel = null; 476 mWsm = null; 477 } 478 479 @Test 480 public void createNew() throws Exception { 481 assertEquals("InitialState", getCurrentState().getName()); 482 483 mWsm.sendMessage(WifiStateMachine.CMD_BOOT_COMPLETED); 484 mLooper.dispatchAll(); 485 assertEquals("InitialState", getCurrentState().getName()); 486 } 487 488 @Test 489 public void loadComponentsInStaMode() throws Exception { 490 startSupplicantAndDispatchMessages(); 491 492 verify(mContext).sendStickyBroadcastAsUser( 493 (Intent) argThat(new WifiEnablingStateIntentMatcher()), eq(UserHandle.ALL)); 494 495 assertEquals("DisconnectedState", getCurrentState().getName()); 496 } 497 498 private void checkApStateChangedBroadcast(Intent intent, int expectedCurrentState, 499 int expectedPrevState, int expectedErrorCode, String expectedIfaceName, 500 int expectedMode) { 501 int currentState = intent.getIntExtra(EXTRA_WIFI_AP_STATE, WIFI_AP_STATE_DISABLED); 502 int prevState = intent.getIntExtra(EXTRA_PREVIOUS_WIFI_AP_STATE, WIFI_AP_STATE_DISABLED); 503 int errorCode = intent.getIntExtra(EXTRA_WIFI_AP_FAILURE_REASON, HOTSPOT_NO_ERROR); 504 String ifaceName = intent.getStringExtra(EXTRA_WIFI_AP_INTERFACE_NAME); 505 int mode = intent.getIntExtra(EXTRA_WIFI_AP_MODE, WifiManager.IFACE_IP_MODE_UNSPECIFIED); 506 assertEquals(expectedCurrentState, currentState); 507 assertEquals(expectedPrevState, prevState); 508 assertEquals(expectedErrorCode, errorCode); 509 assertEquals(expectedIfaceName, ifaceName); 510 assertEquals(expectedMode, mode); 511 } 512 513 private void loadComponentsInApMode(int mode) throws Exception { 514 SoftApModeConfiguration config = new SoftApModeConfiguration(mode, new WifiConfiguration()); 515 mWsm.setHostApRunning(config, true); 516 mLooper.dispatchAll(); 517 518 assertEquals("SoftApState", getCurrentState().getName()); 519 520 verify(mSoftApManager).start(); 521 522 // reset expectations for mContext due to previously sent AP broadcast 523 reset(mContext); 524 525 // get the SoftApManager.Listener and trigger some updates 526 SoftApManager.Listener listener = mSoftApManagerListenerCaptor.getValue(); 527 listener.onStateChanged(WIFI_AP_STATE_ENABLING, 0); 528 listener.onStateChanged(WIFI_AP_STATE_ENABLED, 0); 529 listener.onStateChanged(WIFI_AP_STATE_DISABLING, 0); 530 // note, this will trigger a mode change when TestLooper is dispatched 531 listener.onStateChanged(WIFI_AP_STATE_DISABLED, 0); 532 533 ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class); 534 verify(mContext, times(4)) 535 .sendStickyBroadcastAsUser(intentCaptor.capture(), eq(UserHandle.ALL)); 536 537 List<Intent> capturedIntents = intentCaptor.getAllValues(); 538 checkApStateChangedBroadcast(capturedIntents.get(0), WIFI_AP_STATE_ENABLING, 539 WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR, WIFI_IFACE_NAME, mode); 540 checkApStateChangedBroadcast(capturedIntents.get(1), WIFI_AP_STATE_ENABLED, 541 WIFI_AP_STATE_ENABLING, HOTSPOT_NO_ERROR, WIFI_IFACE_NAME, mode); 542 checkApStateChangedBroadcast(capturedIntents.get(2), WIFI_AP_STATE_DISABLING, 543 WIFI_AP_STATE_ENABLED, HOTSPOT_NO_ERROR, WIFI_IFACE_NAME, mode); 544 checkApStateChangedBroadcast(capturedIntents.get(3), WIFI_AP_STATE_DISABLED, 545 WIFI_AP_STATE_DISABLING, HOTSPOT_NO_ERROR, WIFI_IFACE_NAME, mode); 546 } 547 548 @Test 549 public void loadComponentsInApModeForTethering() throws Exception { 550 loadComponentsInApMode(WifiManager.IFACE_IP_MODE_TETHERED); 551 } 552 553 @Test 554 public void loadComponentsInApModeForLOHS() throws Exception { 555 loadComponentsInApMode(WifiManager.IFACE_IP_MODE_LOCAL_ONLY); 556 } 557 558 @Test 559 public void shouldRequireSupplicantStartupToLeaveInitialState() throws Exception { 560 when(mWifiNative.enableSupplicant()).thenReturn(false); 561 mWsm.setSupplicantRunning(true); 562 mLooper.dispatchAll(); 563 assertEquals("InitialState", getCurrentState().getName()); 564 // we should not be sending a wifi enabling update 565 verify(mContext, never()).sendStickyBroadcastAsUser( 566 (Intent) argThat(new WifiEnablingStateIntentMatcher()), any()); 567 } 568 569 @Test 570 public void shouldRequireWificondToLeaveInitialState() throws Exception { 571 // We start out with valid default values, break them going backwards so that 572 // we test all the bailout cases. 573 574 // ClientInterface dies after creation. 575 doThrow(new RemoteException()).when(mClientInterfaceBinder).linkToDeath(any(), anyInt()); 576 mWsm.setSupplicantRunning(true); 577 mLooper.dispatchAll(); 578 assertEquals("InitialState", getCurrentState().getName()); 579 580 // Failed to even create the client interface. 581 when(mWificond.createClientInterface()).thenReturn(null); 582 mWsm.setSupplicantRunning(true); 583 mLooper.dispatchAll(); 584 assertEquals("InitialState", getCurrentState().getName()); 585 586 // Failed to get wificond proxy. 587 when(mWifiInjector.makeWificond()).thenReturn(null); 588 mWsm.setSupplicantRunning(true); 589 mLooper.dispatchAll(); 590 assertEquals("InitialState", getCurrentState().getName()); 591 } 592 593 @Test 594 public void loadComponentsFailure() throws Exception { 595 when(mWifiNative.enableSupplicant()).thenReturn(false); 596 597 mWsm.setSupplicantRunning(true); 598 mLooper.dispatchAll(); 599 assertEquals("InitialState", getCurrentState().getName()); 600 601 mWsm.setSupplicantRunning(true); 602 mLooper.dispatchAll(); 603 assertEquals("InitialState", getCurrentState().getName()); 604 } 605 606 @Test 607 public void checkInitialStateStickyWhenDisabledMode() throws Exception { 608 mLooper.dispatchAll(); 609 assertEquals("InitialState", getCurrentState().getName()); 610 assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest()); 611 612 mWsm.setOperationalMode(WifiStateMachine.DISABLED_MODE); 613 mLooper.dispatchAll(); 614 assertEquals(WifiStateMachine.DISABLED_MODE, mWsm.getOperationalModeForTest()); 615 assertEquals("InitialState", getCurrentState().getName()); 616 } 617 618 @Test 619 public void shouldStartSupplicantWhenConnectModeRequested() throws Exception { 620 // The first time we start out in InitialState, we sit around here. 621 mLooper.dispatchAll(); 622 assertEquals("InitialState", getCurrentState().getName()); 623 assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest()); 624 625 // But if someone tells us to enter connect mode, we start up supplicant 626 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 627 mLooper.dispatchAll(); 628 assertEquals("SupplicantStartingState", getCurrentState().getName()); 629 } 630 631 /** 632 * Test that mode changes accurately reflect the value for isWifiEnabled. 633 */ 634 @Test 635 public void checkIsWifiEnabledForModeChanges() throws Exception { 636 // Check initial state 637 mLooper.dispatchAll(); 638 assertEquals("InitialState", getCurrentState().getName()); 639 assertEquals(WifiManager.WIFI_STATE_DISABLED, mWsm.syncGetWifiState()); 640 641 mWsm.setOperationalMode(WifiStateMachine.SCAN_ONLY_MODE); 642 startSupplicantAndDispatchMessages(); 643 mWsm.setSupplicantRunning(true); 644 mLooper.dispatchAll(); 645 assertEquals(WifiStateMachine.SCAN_ONLY_MODE, mWsm.getOperationalModeForTest()); 646 assertEquals("ScanModeState", getCurrentState().getName()); 647 assertEquals(WifiManager.WIFI_STATE_DISABLED, mWsm.syncGetWifiState()); 648 verify(mContext, never()).sendStickyBroadcastAsUser( 649 (Intent) argThat(new WifiEnablingStateIntentMatcher()), any()); 650 651 652 // switch to connect mode and verify wifi is reported as enabled 653 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 654 mLooper.dispatchAll(); 655 assertEquals("DisconnectedState", getCurrentState().getName()); 656 assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest()); 657 assertEquals(WifiManager.WIFI_STATE_ENABLED, mWsm.syncGetWifiState()); 658 verify(mContext).sendStickyBroadcastAsUser( 659 (Intent) argThat(new WifiEnablingStateIntentMatcher()), eq(UserHandle.ALL)); 660 661 // reset the expectations on mContext since we did get an expected broadcast, but we should 662 // not on the next transition 663 reset(mContext); 664 665 // now go back to scan mode with "wifi disabled" to verify the reported wifi state. 666 mWsm.setOperationalMode(WifiStateMachine.SCAN_ONLY_WITH_WIFI_OFF_MODE); 667 mLooper.dispatchAll(); 668 assertEquals(WifiStateMachine.SCAN_ONLY_WITH_WIFI_OFF_MODE, 669 mWsm.getOperationalModeForTest()); 670 assertEquals("ScanModeState", getCurrentState().getName()); 671 assertEquals(WifiManager.WIFI_STATE_DISABLED, mWsm.syncGetWifiState()); 672 verify(mContext, never()).sendStickyBroadcastAsUser( 673 (Intent) argThat(new WifiEnablingStateIntentMatcher()), any()); 674 675 // now go to AP mode 676 mWsm.setSupplicantRunning(false); 677 mWsm.sendMessage(WifiStateMachine.CMD_DISABLE_P2P_RSP); 678 mWsm.sendMessage(WifiMonitor.SUP_DISCONNECTION_EVENT); 679 SoftApModeConfiguration config = new SoftApModeConfiguration( 680 WifiManager.IFACE_IP_MODE_TETHERED, new WifiConfiguration()); 681 mWsm.setHostApRunning(config, true); 682 mLooper.dispatchAll(); 683 assertEquals("SoftApState", getCurrentState().getName()); 684 assertEquals(WifiManager.WIFI_STATE_DISABLED, mWsm.syncGetWifiState()); 685 verify(mContext, never()).sendStickyBroadcastAsUser( 686 (Intent) argThat(new WifiEnablingStateIntentMatcher()), any()); 687 } 688 689 private class WifiEnablingStateIntentMatcher implements ArgumentMatcher<Intent> { 690 @Override 691 public boolean matches(Intent intent) { 692 if (WifiManager.WIFI_STATE_CHANGED_ACTION != intent.getAction()) { 693 // not the correct type 694 return false; 695 } 696 return WifiManager.WIFI_STATE_ENABLING 697 == intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 698 WifiManager.WIFI_STATE_DISABLED); 699 } 700 } 701 702 /** 703 * Test that mode changes for WifiStateMachine in the InitialState are realized when supplicant 704 * is started. 705 */ 706 @Test 707 public void checkStartInCorrectStateAfterChangingInitialState() throws Exception { 708 // Check initial state 709 mLooper.dispatchAll(); 710 assertEquals("InitialState", getCurrentState().getName()); 711 assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest()); 712 713 // Update the mode 714 mWsm.setOperationalMode(WifiStateMachine.SCAN_ONLY_MODE); 715 mLooper.dispatchAll(); 716 assertEquals(WifiStateMachine.SCAN_ONLY_MODE, mWsm.getOperationalModeForTest()); 717 718 // Start supplicant so we move to the next state 719 startSupplicantAndDispatchMessages(); 720 721 assertEquals("ScanModeState", getCurrentState().getName()); 722 verify(mContext, never()).sendStickyBroadcastAsUser( 723 (Intent) argThat(new WifiEnablingStateIntentMatcher()), any()); 724 } 725 726 /** 727 * Verifies that configs can be removed when in client mode. 728 */ 729 @Test 730 public void canRemoveNetworkConfigInClientMode() throws Exception { 731 boolean result; 732 when(mWifiConfigManager.removeNetwork(eq(0), anyInt())).thenReturn(true); 733 initializeAndAddNetworkAndVerifySuccess(); 734 mLooper.startAutoDispatch(); 735 result = mWsm.syncRemoveNetwork(mWsmAsyncChannel, 0); 736 mLooper.stopAutoDispatch(); 737 assertTrue(result); 738 } 739 740 /** 741 * Verifies that configs can be removed when not in client mode. 742 */ 743 @Test 744 public void canRemoveNetworkConfigWhenWifiDisabled() { 745 boolean result; 746 when(mWifiConfigManager.removeNetwork(eq(0), anyInt())).thenReturn(true); 747 mLooper.startAutoDispatch(); 748 result = mWsm.syncRemoveNetwork(mWsmAsyncChannel, 0); 749 mLooper.stopAutoDispatch(); 750 751 assertTrue(result); 752 verify(mWifiConfigManager).removeNetwork(anyInt(), anyInt()); 753 } 754 755 /** 756 * Verifies that configs can be forgotten when in client mode. 757 */ 758 @Test 759 public void canForgetNetworkConfigInClientMode() throws Exception { 760 when(mWifiConfigManager.removeNetwork(eq(0), anyInt())).thenReturn(true); 761 initializeAndAddNetworkAndVerifySuccess(); 762 mWsm.sendMessage(WifiManager.FORGET_NETWORK, 0, MANAGED_PROFILE_UID); 763 mLooper.dispatchAll(); 764 verify(mWifiConfigManager).removeNetwork(anyInt(), anyInt()); 765 } 766 767 /** 768 * Verifies that configs can be removed when not in client mode. 769 */ 770 @Test 771 public void canForgetNetworkConfigWhenWifiDisabled() throws Exception { 772 when(mWifiConfigManager.removeNetwork(eq(0), anyInt())).thenReturn(true); 773 mWsm.sendMessage(WifiManager.FORGET_NETWORK, 0, MANAGED_PROFILE_UID); 774 mLooper.dispatchAll(); 775 verify(mWifiConfigManager).removeNetwork(anyInt(), anyInt()); 776 } 777 778 /** 779 * Helper method to move through SupplicantStarting and SupplicantStarted states. 780 */ 781 private void startSupplicantAndDispatchMessages() throws Exception { 782 mWsm.setSupplicantRunning(true); 783 mLooper.dispatchAll(); 784 785 assertEquals("SupplicantStartingState", getCurrentState().getName()); 786 787 when(mWifiNative.setDeviceName(anyString())).thenReturn(true); 788 when(mWifiNative.setManufacturer(anyString())).thenReturn(true); 789 when(mWifiNative.setModelName(anyString())).thenReturn(true); 790 when(mWifiNative.setModelNumber(anyString())).thenReturn(true); 791 when(mWifiNative.setSerialNumber(anyString())).thenReturn(true); 792 when(mWifiNative.setConfigMethods(anyString())).thenReturn(true); 793 when(mWifiNative.setDeviceType(anyString())).thenReturn(true); 794 when(mWifiNative.setSerialNumber(anyString())).thenReturn(true); 795 when(mWifiNative.setScanningMacOui(any(byte[].class))).thenReturn(true); 796 797 mWsm.sendMessage(WifiMonitor.SUP_CONNECTION_EVENT); 798 mLooper.dispatchAll(); 799 } 800 801 private void addNetworkAndVerifySuccess(boolean isHidden) throws Exception { 802 WifiConfiguration config = new WifiConfiguration(); 803 config.SSID = sSSID; 804 config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE); 805 config.hiddenSSID = isHidden; 806 807 when(mWifiConfigManager.addOrUpdateNetwork(any(WifiConfiguration.class), anyInt())) 808 .thenReturn(new NetworkUpdateResult(0)); 809 when(mWifiConfigManager.getSavedNetworks()).thenReturn(Arrays.asList(config)); 810 when(mWifiConfigManager.getConfiguredNetwork(0)).thenReturn(config); 811 812 mLooper.startAutoDispatch(); 813 mWsm.syncAddOrUpdateNetwork(mWsmAsyncChannel, config); 814 mLooper.stopAutoDispatch(); 815 816 verify(mWifiConfigManager).addOrUpdateNetwork(eq(config), anyInt()); 817 818 mLooper.startAutoDispatch(); 819 List<WifiConfiguration> configs = mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel); 820 mLooper.stopAutoDispatch(); 821 assertEquals(1, configs.size()); 822 823 WifiConfiguration config2 = configs.get(0); 824 assertEquals("\"GoogleGuest\"", config2.SSID); 825 assertTrue(config2.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)); 826 } 827 828 private void initializeAndAddNetworkAndVerifySuccess() throws Exception { 829 initializeAndAddNetworkAndVerifySuccess(false); 830 } 831 832 private void initializeAndAddNetworkAndVerifySuccess(boolean isHidden) throws Exception { 833 loadComponentsInStaMode(); 834 addNetworkAndVerifySuccess(isHidden); 835 } 836 837 /** 838 * Helper method to retrieve WifiConfiguration by SSID. 839 * 840 * Returns the associated WifiConfiguration if it is found, null otherwise. 841 */ 842 private WifiConfiguration getWifiConfigurationForNetwork(String ssid) { 843 mLooper.startAutoDispatch(); 844 List<WifiConfiguration> configs = mWsm.syncGetConfiguredNetworks(-1, mWsmAsyncChannel); 845 mLooper.stopAutoDispatch(); 846 847 for (WifiConfiguration checkConfig : configs) { 848 if (checkConfig.SSID.equals(ssid)) { 849 return checkConfig; 850 } 851 } 852 return null; 853 } 854 855 private void verifyScan(int band, int reportEvents, Set<String> hiddenNetworkSSIDSet) { 856 ArgumentCaptor<WifiScanner.ScanSettings> scanSettingsCaptor = 857 ArgumentCaptor.forClass(WifiScanner.ScanSettings.class); 858 ArgumentCaptor<WifiScanner.ScanListener> scanListenerCaptor = 859 ArgumentCaptor.forClass(WifiScanner.ScanListener.class); 860 verify(mWifiScanner).startScan(scanSettingsCaptor.capture(), scanListenerCaptor.capture(), 861 eq(null)); 862 WifiScanner.ScanSettings actualSettings = scanSettingsCaptor.getValue(); 863 assertEquals("band", band, actualSettings.band); 864 assertEquals("reportEvents", reportEvents, actualSettings.reportEvents); 865 866 if (hiddenNetworkSSIDSet == null) { 867 hiddenNetworkSSIDSet = new HashSet<>(); 868 } 869 Set<String> actualHiddenNetworkSSIDSet = new HashSet<>(); 870 if (actualSettings.hiddenNetworks != null) { 871 for (int i = 0; i < actualSettings.hiddenNetworks.length; ++i) { 872 actualHiddenNetworkSSIDSet.add(actualSettings.hiddenNetworks[i].ssid); 873 } 874 } 875 assertEquals("hidden networks", hiddenNetworkSSIDSet, actualHiddenNetworkSSIDSet); 876 877 when(mWifiNative.getScanResults()).thenReturn(getMockScanResults()); 878 mWsm.sendMessage(WifiMonitor.SCAN_RESULTS_EVENT); 879 880 mLooper.dispatchAll(); 881 882 List<ScanResult> reportedResults = mWsm.syncGetScanResultsList(); 883 assertEquals(8, reportedResults.size()); 884 } 885 886 @Test 887 public void scan() throws Exception { 888 initializeAndAddNetworkAndVerifySuccess(); 889 890 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 891 mWsm.startScan(-1, 0, null, null); 892 mLooper.dispatchAll(); 893 894 verifyScan(WifiScanner.WIFI_BAND_BOTH_WITH_DFS, 895 WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN 896 | WifiScanner.REPORT_EVENT_FULL_SCAN_RESULT, null); 897 } 898 899 @Test 900 public void scanWithHiddenNetwork() throws Exception { 901 initializeAndAddNetworkAndVerifySuccess(true); 902 903 Set<String> hiddenNetworkSet = new HashSet<>(); 904 hiddenNetworkSet.add(sSSID); 905 List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworkList = new ArrayList<>(); 906 hiddenNetworkList.add(new WifiScanner.ScanSettings.HiddenNetwork(sSSID)); 907 when(mWifiConfigManager.retrieveHiddenNetworkList()).thenReturn(hiddenNetworkList); 908 909 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 910 mWsm.startScan(-1, 0, null, null); 911 mLooper.dispatchAll(); 912 913 verifyScan(WifiScanner.WIFI_BAND_BOTH_WITH_DFS, 914 WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN 915 | WifiScanner.REPORT_EVENT_FULL_SCAN_RESULT, 916 hiddenNetworkSet); 917 } 918 919 @Test 920 public void connect() throws Exception { 921 initializeAndAddNetworkAndVerifySuccess(); 922 when(mWifiConfigManager.enableNetwork(eq(0), eq(true), anyInt())).thenReturn(true); 923 when(mWifiConfigManager.checkAndUpdateLastConnectUid(eq(0), anyInt())).thenReturn(true); 924 925 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 926 mLooper.dispatchAll(); 927 verify(mWifiNative).removeAllNetworks(); 928 929 mLooper.startAutoDispatch(); 930 assertTrue(mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true)); 931 mLooper.stopAutoDispatch(); 932 933 verify(mWifiConfigManager).enableNetwork(eq(0), eq(true), anyInt()); 934 verify(mWifiConnectivityManager).setUserConnectChoice(eq(0)); 935 936 mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, sBSSID); 937 mLooper.dispatchAll(); 938 939 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 940 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 941 mLooper.dispatchAll(); 942 943 assertEquals("ObtainingIpState", getCurrentState().getName()); 944 945 DhcpResults dhcpResults = new DhcpResults(); 946 dhcpResults.setGateway("1.2.3.4"); 947 dhcpResults.setIpAddress("192.168.1.100", 0); 948 dhcpResults.addDns("8.8.8.8"); 949 dhcpResults.setLeaseDuration(3600); 950 951 mTestIpManager.injectDhcpSuccess(dhcpResults); 952 mLooper.dispatchAll(); 953 954 assertEquals("ConnectedState", getCurrentState().getName()); 955 } 956 957 @Test 958 public void connectWithNoEnablePermission() throws Exception { 959 initializeAndAddNetworkAndVerifySuccess(); 960 when(mWifiConfigManager.enableNetwork(eq(0), eq(true), anyInt())).thenReturn(false); 961 when(mWifiConfigManager.checkAndUpdateLastConnectUid(eq(0), anyInt())).thenReturn(false); 962 963 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 964 mLooper.dispatchAll(); 965 verify(mWifiNative).removeAllNetworks(); 966 967 mLooper.startAutoDispatch(); 968 assertTrue(mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true)); 969 mLooper.stopAutoDispatch(); 970 971 verify(mWifiConfigManager).enableNetwork(eq(0), eq(true), anyInt()); 972 verify(mWifiConnectivityManager, never()).setUserConnectChoice(eq(0)); 973 974 mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, sBSSID); 975 mLooper.dispatchAll(); 976 977 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 978 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 979 mLooper.dispatchAll(); 980 981 assertEquals("ObtainingIpState", getCurrentState().getName()); 982 983 DhcpResults dhcpResults = new DhcpResults(); 984 dhcpResults.setGateway("1.2.3.4"); 985 dhcpResults.setIpAddress("192.168.1.100", 0); 986 dhcpResults.addDns("8.8.8.8"); 987 dhcpResults.setLeaseDuration(3600); 988 989 mTestIpManager.injectDhcpSuccess(dhcpResults); 990 mLooper.dispatchAll(); 991 992 assertEquals("ConnectedState", getCurrentState().getName()); 993 } 994 995 @Test 996 public void enableWithInvalidNetworkId() throws Exception { 997 initializeAndAddNetworkAndVerifySuccess(); 998 when(mWifiConfigManager.getConfiguredNetwork(eq(0))).thenReturn(null); 999 1000 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1001 mLooper.dispatchAll(); 1002 verify(mWifiNative).removeAllNetworks(); 1003 1004 mLooper.startAutoDispatch(); 1005 assertFalse(mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true)); 1006 mLooper.stopAutoDispatch(); 1007 1008 verify(mWifiConfigManager, never()).enableNetwork(eq(0), eq(true), anyInt()); 1009 verify(mWifiConfigManager, never()).checkAndUpdateLastConnectUid(eq(0), anyInt()); 1010 } 1011 1012 /** 1013 * If caller tries to connect to a network that is already connected, the connection request 1014 * should succeed. 1015 * 1016 * Test: Create and connect to a network, then try to reconnect to the same network. Verify 1017 * that connection request returns with CONNECT_NETWORK_SUCCEEDED. 1018 */ 1019 @Test 1020 public void reconnectToConnectedNetwork() throws Exception { 1021 initializeAndAddNetworkAndVerifySuccess(); 1022 1023 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1024 mLooper.dispatchAll(); 1025 verify(mWifiNative).removeAllNetworks(); 1026 1027 mLooper.startAutoDispatch(); 1028 mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true); 1029 mLooper.stopAutoDispatch(); 1030 1031 verify(mWifiConfigManager).enableNetwork(eq(0), eq(true), anyInt()); 1032 1033 mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, sBSSID); 1034 mLooper.dispatchAll(); 1035 1036 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 1037 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 1038 mLooper.dispatchAll(); 1039 1040 assertEquals("ObtainingIpState", getCurrentState().getName()); 1041 1042 // try to reconnect 1043 mLooper.startAutoDispatch(); 1044 Message reply = mWsmAsyncChannel.sendMessageSynchronously(WifiManager.CONNECT_NETWORK, 0); 1045 mLooper.stopAutoDispatch(); 1046 1047 assertEquals(WifiManager.CONNECT_NETWORK_SUCCEEDED, reply.what); 1048 } 1049 1050 @Test 1051 public void testDhcpFailure() throws Exception { 1052 initializeAndAddNetworkAndVerifySuccess(); 1053 1054 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1055 mLooper.dispatchAll(); 1056 1057 mLooper.startAutoDispatch(); 1058 mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true); 1059 mLooper.stopAutoDispatch(); 1060 1061 verify(mWifiConfigManager).enableNetwork(eq(0), eq(true), anyInt()); 1062 1063 mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, sBSSID); 1064 mLooper.dispatchAll(); 1065 1066 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 1067 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 1068 mLooper.dispatchAll(); 1069 1070 assertEquals("ObtainingIpState", getCurrentState().getName()); 1071 1072 mTestIpManager.injectDhcpFailure(); 1073 mLooper.dispatchAll(); 1074 1075 assertEquals("DisconnectingState", getCurrentState().getName()); 1076 } 1077 1078 @Test 1079 public void testBadNetworkEvent() throws Exception { 1080 initializeAndAddNetworkAndVerifySuccess(); 1081 1082 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1083 mLooper.dispatchAll(); 1084 1085 mLooper.startAutoDispatch(); 1086 mWsm.syncEnableNetwork(mWsmAsyncChannel, 0, true); 1087 mLooper.stopAutoDispatch(); 1088 1089 verify(mWifiConfigManager).enableNetwork(eq(0), eq(true), anyInt()); 1090 1091 mWsm.sendMessage(WifiMonitor.NETWORK_DISCONNECTION_EVENT, 0, 0, sBSSID); 1092 mLooper.dispatchAll(); 1093 1094 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 1095 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 1096 mLooper.dispatchAll(); 1097 1098 assertEquals("DisconnectedState", getCurrentState().getName()); 1099 } 1100 1101 1102 @Test 1103 public void smToString() throws Exception { 1104 assertEquals("CMD_CHANNEL_HALF_CONNECTED", mWsm.smToString( 1105 AsyncChannel.CMD_CHANNEL_HALF_CONNECTED)); 1106 assertEquals("CMD_PRE_DHCP_ACTION", mWsm.smToString( 1107 DhcpClient.CMD_PRE_DHCP_ACTION)); 1108 assertEquals("CMD_IP_REACHABILITY_LOST", mWsm.smToString( 1109 WifiStateMachine.CMD_IP_REACHABILITY_LOST)); 1110 } 1111 1112 @Test 1113 public void disconnect() throws Exception { 1114 connect(); 1115 1116 mWsm.sendMessage(WifiMonitor.NETWORK_DISCONNECTION_EVENT, -1, 3, "01:02:03:04:05:06"); 1117 mLooper.dispatchAll(); 1118 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 1119 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.DISCONNECTED)); 1120 mLooper.dispatchAll(); 1121 1122 assertEquals("DisconnectedState", getCurrentState().getName()); 1123 } 1124 1125 /** 1126 * Successfully connecting to a network will set WifiConfiguration's value of HasEverConnected 1127 * to true. 1128 * 1129 * Test: Successfully create and connect to a network. Check the config and verify 1130 * WifiConfiguration.getHasEverConnected() is true. 1131 */ 1132 @Test 1133 public void setHasEverConnectedTrueOnConnect() throws Exception { 1134 connect(); 1135 verify(mWifiConfigManager, atLeastOnce()).updateNetworkAfterConnect(0); 1136 } 1137 1138 /** 1139 * Fail network connection attempt and verify HasEverConnected remains false. 1140 * 1141 * Test: Successfully create a network but fail when connecting. Check the config and verify 1142 * WifiConfiguration.getHasEverConnected() is false. 1143 */ 1144 @Test 1145 public void connectionFailureDoesNotSetHasEverConnectedTrue() throws Exception { 1146 testDhcpFailure(); 1147 verify(mWifiConfigManager, never()).updateNetworkAfterConnect(0); 1148 } 1149 1150 @Test 1151 public void iconQueryTest() throws Exception { 1152 // TODO(b/31065385): Passpoint config management. 1153 } 1154 1155 @Test 1156 public void verboseLogRecSizeIsGreaterThanNormalSize() { 1157 assertTrue(LOG_REC_LIMIT_IN_VERBOSE_MODE > WifiStateMachine.NUM_LOG_RECS_NORMAL); 1158 } 1159 1160 /** 1161 * Verifies that, by default, we allow only the "normal" number of log records. 1162 */ 1163 @Test 1164 public void normalLogRecSizeIsUsedByDefault() { 1165 assertEquals(WifiStateMachine.NUM_LOG_RECS_NORMAL, mWsm.getLogRecMaxSize()); 1166 } 1167 1168 /** 1169 * Verifies that, in verbose mode, we allow a larger number of log records. 1170 */ 1171 @Test 1172 public void enablingVerboseLoggingUpdatesLogRecSize() { 1173 mWsm.enableVerboseLogging(1); 1174 assertEquals(LOG_REC_LIMIT_IN_VERBOSE_MODE, mWsm.getLogRecMaxSize()); 1175 } 1176 1177 @Test 1178 public void disablingVerboseLoggingClearsRecords() { 1179 mWsm.sendMessage(WifiStateMachine.CMD_DISCONNECT); 1180 mLooper.dispatchAll(); 1181 assertTrue(mWsm.getLogRecSize() >= 1); 1182 1183 mWsm.enableVerboseLogging(0); 1184 assertEquals(0, mWsm.getLogRecSize()); 1185 } 1186 1187 @Test 1188 public void disablingVerboseLoggingUpdatesLogRecSize() { 1189 mWsm.enableVerboseLogging(1); 1190 mWsm.enableVerboseLogging(0); 1191 assertEquals(WifiStateMachine.NUM_LOG_RECS_NORMAL, mWsm.getLogRecMaxSize()); 1192 } 1193 1194 @Test 1195 public void logRecsIncludeDisconnectCommand() { 1196 // There's nothing special about the DISCONNECT command. It's just representative of 1197 // "normal" commands. 1198 mWsm.sendMessage(WifiStateMachine.CMD_DISCONNECT); 1199 mLooper.dispatchAll(); 1200 assertEquals(1, mWsm.copyLogRecs() 1201 .stream() 1202 .filter(logRec -> logRec.getWhat() == WifiStateMachine.CMD_DISCONNECT) 1203 .count()); 1204 } 1205 1206 @Test 1207 public void logRecsExcludeRssiPollCommandByDefault() { 1208 mWsm.sendMessage(WifiStateMachine.CMD_RSSI_POLL); 1209 mLooper.dispatchAll(); 1210 assertEquals(0, mWsm.copyLogRecs() 1211 .stream() 1212 .filter(logRec -> logRec.getWhat() == WifiStateMachine.CMD_RSSI_POLL) 1213 .count()); 1214 } 1215 1216 @Test 1217 public void logRecsIncludeRssiPollCommandWhenVerboseLoggingIsEnabled() { 1218 mWsm.enableVerboseLogging(1); 1219 mWsm.sendMessage(WifiStateMachine.CMD_RSSI_POLL); 1220 mLooper.dispatchAll(); 1221 assertEquals(1, mWsm.copyLogRecs() 1222 .stream() 1223 .filter(logRec -> logRec.getWhat() == WifiStateMachine.CMD_RSSI_POLL) 1224 .count()); 1225 } 1226 1227 /** Verifies that enabling verbose logging sets the hal log property in eng builds. */ 1228 @Test 1229 public void enablingVerboseLoggingSetsHalLogPropertyInEngBuilds() { 1230 reset(mPropertyService); // Ignore calls made in setUp() 1231 when(mBuildProperties.isEngBuild()).thenReturn(true); 1232 when(mBuildProperties.isUserdebugBuild()).thenReturn(false); 1233 when(mBuildProperties.isUserBuild()).thenReturn(false); 1234 mWsm.enableVerboseLogging(1); 1235 verify(mPropertyService).set("log.tag.WifiHAL", "V"); 1236 } 1237 1238 /** Verifies that enabling verbose logging sets the hal log property in userdebug builds. */ 1239 @Test 1240 public void enablingVerboseLoggingSetsHalLogPropertyInUserdebugBuilds() { 1241 reset(mPropertyService); // Ignore calls made in setUp() 1242 when(mBuildProperties.isUserdebugBuild()).thenReturn(true); 1243 when(mBuildProperties.isEngBuild()).thenReturn(false); 1244 when(mBuildProperties.isUserBuild()).thenReturn(false); 1245 mWsm.enableVerboseLogging(1); 1246 verify(mPropertyService).set("log.tag.WifiHAL", "V"); 1247 } 1248 1249 /** Verifies that enabling verbose logging does NOT set the hal log property in user builds. */ 1250 @Test 1251 public void enablingVerboseLoggingDoeNotSetHalLogPropertyInUserBuilds() { 1252 reset(mPropertyService); // Ignore calls made in setUp() 1253 when(mBuildProperties.isUserBuild()).thenReturn(true); 1254 when(mBuildProperties.isEngBuild()).thenReturn(false); 1255 when(mBuildProperties.isUserdebugBuild()).thenReturn(false); 1256 mWsm.enableVerboseLogging(1); 1257 verify(mPropertyService, never()).set(anyString(), anyString()); 1258 } 1259 1260 private int testGetSupportedFeaturesCase(int supportedFeatures, boolean rttConfigured) { 1261 AsyncChannel channel = mock(AsyncChannel.class); 1262 Message reply = Message.obtain(); 1263 reply.arg1 = supportedFeatures; 1264 reset(mPropertyService); // Ignore calls made in setUp() 1265 when(channel.sendMessageSynchronously(WifiStateMachine.CMD_GET_SUPPORTED_FEATURES)) 1266 .thenReturn(reply); 1267 when(mPropertyService.getBoolean("config.disable_rtt", false)) 1268 .thenReturn(rttConfigured); 1269 return mWsm.syncGetSupportedFeatures(channel); 1270 } 1271 1272 /** Verifies that syncGetSupportedFeatures() masks out capabilities based on system flags. */ 1273 @Test 1274 public void syncGetSupportedFeatures() { 1275 final int featureAware = WifiManager.WIFI_FEATURE_AWARE; 1276 final int featureInfra = WifiManager.WIFI_FEATURE_INFRA; 1277 final int featureD2dRtt = WifiManager.WIFI_FEATURE_D2D_RTT; 1278 final int featureD2apRtt = WifiManager.WIFI_FEATURE_D2AP_RTT; 1279 1280 assertEquals(0, testGetSupportedFeaturesCase(0, false)); 1281 assertEquals(0, testGetSupportedFeaturesCase(0, true)); 1282 assertEquals(featureAware | featureInfra, 1283 testGetSupportedFeaturesCase(featureAware | featureInfra, false)); 1284 assertEquals(featureAware | featureInfra, 1285 testGetSupportedFeaturesCase(featureAware | featureInfra, true)); 1286 assertEquals(featureInfra | featureD2dRtt, 1287 testGetSupportedFeaturesCase(featureInfra | featureD2dRtt, false)); 1288 assertEquals(featureInfra, 1289 testGetSupportedFeaturesCase(featureInfra | featureD2dRtt, true)); 1290 assertEquals(featureInfra | featureD2apRtt, 1291 testGetSupportedFeaturesCase(featureInfra | featureD2apRtt, false)); 1292 assertEquals(featureInfra, 1293 testGetSupportedFeaturesCase(featureInfra | featureD2apRtt, true)); 1294 assertEquals(featureInfra | featureD2dRtt | featureD2apRtt, 1295 testGetSupportedFeaturesCase(featureInfra | featureD2dRtt | featureD2apRtt, false)); 1296 assertEquals(featureInfra, 1297 testGetSupportedFeaturesCase(featureInfra | featureD2dRtt | featureD2apRtt, true)); 1298 } 1299 1300 /** 1301 * Verify that syncAddOrUpdatePasspointConfig will redirect calls to {@link PasspointManager} 1302 * and returning the result that's returned from {@link PasspointManager}. 1303 */ 1304 @Test 1305 public void syncAddOrUpdatePasspointConfig() throws Exception { 1306 PasspointConfiguration config = new PasspointConfiguration(); 1307 HomeSp homeSp = new HomeSp(); 1308 homeSp.setFqdn("test.com"); 1309 config.setHomeSp(homeSp); 1310 1311 when(mPasspointManager.addOrUpdateProvider(config, MANAGED_PROFILE_UID)).thenReturn(true); 1312 mLooper.startAutoDispatch(); 1313 assertTrue(mWsm.syncAddOrUpdatePasspointConfig( 1314 mWsmAsyncChannel, config, MANAGED_PROFILE_UID)); 1315 mLooper.stopAutoDispatch(); 1316 reset(mPasspointManager); 1317 1318 when(mPasspointManager.addOrUpdateProvider(config, MANAGED_PROFILE_UID)).thenReturn(false); 1319 mLooper.startAutoDispatch(); 1320 assertFalse(mWsm.syncAddOrUpdatePasspointConfig( 1321 mWsmAsyncChannel, config, MANAGED_PROFILE_UID)); 1322 mLooper.stopAutoDispatch(); 1323 } 1324 1325 /** 1326 * Verify that syncAddOrUpdatePasspointConfig will redirect calls to {@link PasspointManager} 1327 * and returning the result that's returned from {@link PasspointManager} when in client mode. 1328 */ 1329 @Test 1330 public void syncAddOrUpdatePasspointConfigInClientMode() throws Exception { 1331 loadComponentsInStaMode(); 1332 syncAddOrUpdatePasspointConfig(); 1333 } 1334 1335 /** 1336 * Verify that syncRemovePasspointConfig will redirect calls to {@link PasspointManager} 1337 * and returning the result that's returned from {@link PasspointManager}. 1338 */ 1339 @Test 1340 public void syncRemovePasspointConfig() throws Exception { 1341 String fqdn = "test.com"; 1342 when(mPasspointManager.removeProvider(fqdn)).thenReturn(true); 1343 mLooper.startAutoDispatch(); 1344 assertTrue(mWsm.syncRemovePasspointConfig(mWsmAsyncChannel, fqdn)); 1345 mLooper.stopAutoDispatch(); 1346 reset(mPasspointManager); 1347 1348 when(mPasspointManager.removeProvider(fqdn)).thenReturn(false); 1349 mLooper.startAutoDispatch(); 1350 assertFalse(mWsm.syncRemovePasspointConfig(mWsmAsyncChannel, fqdn)); 1351 mLooper.stopAutoDispatch(); 1352 } 1353 1354 /** 1355 * Verify that syncRemovePasspointConfig will redirect calls to {@link PasspointManager} 1356 * and returning the result that's returned from {@link PasspointManager} when in client mode. 1357 */ 1358 @Test 1359 public void syncRemovePasspointConfigInClientMode() throws Exception { 1360 loadComponentsInStaMode(); 1361 syncRemovePasspointConfig(); 1362 } 1363 1364 /** 1365 * Verify that syncGetPasspointConfigs will redirect calls to {@link PasspointManager} 1366 * and returning the result that's returned from {@link PasspointManager}. 1367 */ 1368 @Test 1369 public void syncGetPasspointConfigs() throws Exception { 1370 // Setup expected configs. 1371 List<PasspointConfiguration> expectedConfigs = new ArrayList<>(); 1372 PasspointConfiguration config = new PasspointConfiguration(); 1373 HomeSp homeSp = new HomeSp(); 1374 homeSp.setFqdn("test.com"); 1375 config.setHomeSp(homeSp); 1376 expectedConfigs.add(config); 1377 1378 when(mPasspointManager.getProviderConfigs()).thenReturn(expectedConfigs); 1379 mLooper.startAutoDispatch(); 1380 assertEquals(expectedConfigs, mWsm.syncGetPasspointConfigs(mWsmAsyncChannel)); 1381 mLooper.stopAutoDispatch(); 1382 reset(mPasspointManager); 1383 1384 when(mPasspointManager.getProviderConfigs()) 1385 .thenReturn(new ArrayList<PasspointConfiguration>()); 1386 mLooper.startAutoDispatch(); 1387 assertTrue(mWsm.syncGetPasspointConfigs(mWsmAsyncChannel).isEmpty()); 1388 mLooper.stopAutoDispatch(); 1389 } 1390 1391 /** 1392 * Verify that syncGetMatchingWifiConfig will redirect calls to {@link PasspointManager} 1393 * with expected {@link WifiConfiguration} being returned when in client mode. 1394 * 1395 * @throws Exception 1396 */ 1397 @Test 1398 public void syncGetMatchingWifiConfigInClientMode() throws Exception { 1399 loadComponentsInStaMode(); 1400 1401 when(mPasspointManager.getMatchingWifiConfig(any(ScanResult.class))).thenReturn(null); 1402 mLooper.startAutoDispatch(); 1403 assertNull(mWsm.syncGetMatchingWifiConfig(new ScanResult(), mWsmAsyncChannel)); 1404 mLooper.stopAutoDispatch(); 1405 reset(mPasspointManager); 1406 1407 WifiConfiguration expectedConfig = new WifiConfiguration(); 1408 expectedConfig.SSID = "TestSSID"; 1409 when(mPasspointManager.getMatchingWifiConfig(any(ScanResult.class))) 1410 .thenReturn(expectedConfig); 1411 mLooper.startAutoDispatch(); 1412 WifiConfiguration actualConfig = mWsm.syncGetMatchingWifiConfig(new ScanResult(), 1413 mWsmAsyncChannel); 1414 mLooper.stopAutoDispatch(); 1415 assertEquals(expectedConfig.SSID, actualConfig.SSID); 1416 } 1417 1418 /** 1419 * Verify that syncGetMatchingWifiConfig will be a no-op and return {@code null} when not in 1420 * client mode. 1421 * 1422 * @throws Exception 1423 */ 1424 @Test 1425 public void syncGetMatchingWifiConfigInNonClientMode() throws Exception { 1426 mLooper.startAutoDispatch(); 1427 assertNull(mWsm.syncGetMatchingWifiConfig(new ScanResult(), mWsmAsyncChannel)); 1428 mLooper.stopAutoDispatch(); 1429 verify(mPasspointManager, never()).getMatchingWifiConfig(any(ScanResult.class)); 1430 } 1431 1432 /** 1433 * Verify successful Wps PBC network connection. 1434 */ 1435 @Test 1436 public void wpsPbcConnectSuccess() throws Exception { 1437 loadComponentsInStaMode(); 1438 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1439 mLooper.dispatchAll(); 1440 1441 when(mWifiNative.startWpsPbc(eq(sBSSID))).thenReturn(true); 1442 WpsInfo wpsInfo = new WpsInfo(); 1443 wpsInfo.setup = WpsInfo.PBC; 1444 wpsInfo.BSSID = sBSSID; 1445 1446 mWsm.sendMessage(WifiManager.START_WPS, 0, 0, wpsInfo); 1447 mLooper.dispatchAll(); 1448 verify(mWifiNative).startWpsPbc(eq(sBSSID)); 1449 1450 assertEquals("WpsRunningState", getCurrentState().getName()); 1451 1452 setupMocksForWpsNetworkMigration(); 1453 1454 mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, null); 1455 mLooper.dispatchAll(); 1456 1457 assertEquals("DisconnectedState", getCurrentState().getName()); 1458 verifyMocksForWpsNetworkMigration(); 1459 } 1460 1461 /** 1462 * Verify failure in starting Wps PBC network connection. 1463 */ 1464 @Test 1465 public void wpsPbcConnectFailure() throws Exception { 1466 loadComponentsInStaMode(); 1467 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1468 mLooper.dispatchAll(); 1469 1470 when(mWifiNative.startWpsPbc(eq(sBSSID))).thenReturn(false); 1471 WpsInfo wpsInfo = new WpsInfo(); 1472 wpsInfo.setup = WpsInfo.PBC; 1473 wpsInfo.BSSID = sBSSID; 1474 1475 mWsm.sendMessage(WifiManager.START_WPS, 0, 0, wpsInfo); 1476 mLooper.dispatchAll(); 1477 verify(mWifiNative).startWpsPbc(eq(sBSSID)); 1478 1479 assertFalse("WpsRunningState".equals(getCurrentState().getName())); 1480 } 1481 1482 /** 1483 * Verify successful Wps Pin Display network connection. 1484 */ 1485 @Test 1486 public void wpsPinDisplayConnectSuccess() throws Exception { 1487 loadComponentsInStaMode(); 1488 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1489 mLooper.dispatchAll(); 1490 1491 when(mWifiNative.startWpsPinDisplay(eq(sBSSID))).thenReturn("34545434"); 1492 WpsInfo wpsInfo = new WpsInfo(); 1493 wpsInfo.setup = WpsInfo.DISPLAY; 1494 wpsInfo.BSSID = sBSSID; 1495 1496 mWsm.sendMessage(WifiManager.START_WPS, 0, 0, wpsInfo); 1497 mLooper.dispatchAll(); 1498 verify(mWifiNative).startWpsPinDisplay(eq(sBSSID)); 1499 1500 assertEquals("WpsRunningState", getCurrentState().getName()); 1501 1502 setupMocksForWpsNetworkMigration(); 1503 1504 mWsm.sendMessage(WifiMonitor.NETWORK_CONNECTION_EVENT, 0, 0, null); 1505 mLooper.dispatchAll(); 1506 1507 assertEquals("DisconnectedState", getCurrentState().getName()); 1508 verifyMocksForWpsNetworkMigration(); 1509 } 1510 1511 /** 1512 * Verify failure in Wps Pin Display network connection. 1513 */ 1514 @Test 1515 public void wpsPinDisplayConnectFailure() throws Exception { 1516 loadComponentsInStaMode(); 1517 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1518 mLooper.dispatchAll(); 1519 1520 when(mWifiNative.startWpsPinDisplay(eq(sBSSID))).thenReturn(null); 1521 WpsInfo wpsInfo = new WpsInfo(); 1522 wpsInfo.setup = WpsInfo.DISPLAY; 1523 wpsInfo.BSSID = sBSSID; 1524 1525 mWsm.sendMessage(WifiManager.START_WPS, 0, 0, wpsInfo); 1526 mLooper.dispatchAll(); 1527 verify(mWifiNative).startWpsPinDisplay(eq(sBSSID)); 1528 1529 assertFalse("WpsRunningState".equals(getCurrentState().getName())); 1530 } 1531 1532 @Test 1533 public void handleVendorHalDeath() throws Exception { 1534 ArgumentCaptor<WifiNative.VendorHalDeathEventHandler> deathHandlerCapturer = 1535 ArgumentCaptor.forClass(WifiNative.VendorHalDeathEventHandler.class); 1536 when(mWifiNative.initializeVendorHal(deathHandlerCapturer.capture())).thenReturn(true); 1537 1538 // Trigger initialize to capture the death handler registration. 1539 mLooper.startAutoDispatch(); 1540 assertTrue(mWsm.syncInitialize(mWsmAsyncChannel)); 1541 mLooper.stopAutoDispatch(); 1542 1543 verify(mWifiNative).initializeVendorHal(any(WifiNative.VendorHalDeathEventHandler.class)); 1544 WifiNative.VendorHalDeathEventHandler deathHandler = deathHandlerCapturer.getValue(); 1545 1546 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1547 mLooper.dispatchAll(); 1548 1549 // Now trigger the death notification. 1550 deathHandler.onDeath(); 1551 mLooper.dispatchAll(); 1552 1553 verify(mWifiMetrics).incrementNumHalCrashes(); 1554 verify(mSelfRecovery).trigger(eq(SelfRecovery.REASON_HAL_CRASH)); 1555 } 1556 1557 @Test 1558 public void handleWificondDeath() throws Exception { 1559 ArgumentCaptor<StateMachineDeathRecipient> deathHandlerCapturer = 1560 ArgumentCaptor.forClass(StateMachineDeathRecipient.class); 1561 1562 // Trigger initialize to capture the death handler registration. 1563 loadComponentsInStaMode(); 1564 1565 verify(mClientInterfaceBinder).linkToDeath(deathHandlerCapturer.capture(), anyInt()); 1566 StateMachineDeathRecipient deathHandler = deathHandlerCapturer.getValue(); 1567 1568 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1569 mLooper.dispatchAll(); 1570 1571 // Now trigger the death notification. 1572 deathHandler.binderDied(); 1573 mLooper.dispatchAll(); 1574 1575 verify(mWifiMetrics).incrementNumWificondCrashes(); 1576 verify(mSelfRecovery).trigger(eq(SelfRecovery.REASON_WIFICOND_CRASH)); 1577 } 1578 1579 private void setupMocksForWpsNetworkMigration() { 1580 // Now trigger the network connection event for adding the WPS network. 1581 doAnswer(new AnswerWithArguments() { 1582 public boolean answer(Map<String, WifiConfiguration> configs, 1583 SparseArray<Map<String, String>> networkExtras) throws Exception { 1584 WifiConfiguration config = new WifiConfiguration(); 1585 config.networkId = WPS_SUPPLICANT_NETWORK_ID; 1586 config.SSID = DEFAULT_TEST_SSID; 1587 configs.put("dummy", config); 1588 return true; 1589 } 1590 }).when(mWifiNative).migrateNetworksFromSupplicant(any(Map.class), any(SparseArray.class)); 1591 when(mWifiConfigManager.addOrUpdateNetwork(any(WifiConfiguration.class), anyInt())) 1592 .thenReturn(new NetworkUpdateResult(WPS_FRAMEWORK_NETWORK_ID)); 1593 when(mWifiConfigManager.enableNetwork(eq(WPS_FRAMEWORK_NETWORK_ID), anyBoolean(), anyInt())) 1594 .thenReturn(true); 1595 } 1596 1597 private void verifyMocksForWpsNetworkMigration() { 1598 // Network Ids should be reset so that it is treated as addition. 1599 ArgumentCaptor<WifiConfiguration> wifiConfigCaptor = 1600 ArgumentCaptor.forClass(WifiConfiguration.class); 1601 verify(mWifiConfigManager).addOrUpdateNetwork(wifiConfigCaptor.capture(), anyInt()); 1602 assertEquals(WifiConfiguration.INVALID_NETWORK_ID, wifiConfigCaptor.getValue().networkId); 1603 assertEquals(DEFAULT_TEST_SSID, wifiConfigCaptor.getValue().SSID); 1604 verify(mWifiConfigManager).enableNetwork(eq(WPS_FRAMEWORK_NETWORK_ID), anyBoolean(), 1605 anyInt()); 1606 } 1607 1608 /** 1609 * Verifies that WifiInfo is cleared upon exiting and entering WifiInfo, and that it is not 1610 * updated by SUPPLICAN_STATE_CHANGE_EVENTs in ScanModeState. 1611 * This protects WifiStateMachine from getting into a bad state where WifiInfo says wifi is 1612 * already Connected or Connecting, (when it is in-fact Disconnected), so 1613 * WifiConnectivityManager does not attempt any new Connections, freezing wifi. 1614 */ 1615 @Test 1616 public void testWifiInfoCleanedUpEnteringExitingConnectModeState() throws Exception { 1617 InOrder inOrder = inOrder(mWifiConnectivityManager); 1618 Log.i(TAG, mWsm.getCurrentState().getName()); 1619 String initialBSSID = "aa:bb:cc:dd:ee:ff"; 1620 WifiInfo wifiInfo = mWsm.getWifiInfo(); 1621 wifiInfo.setBSSID(initialBSSID); 1622 1623 // Set WSM to CONNECT_MODE and verify state, and wifi enabled in ConnectivityManager 1624 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1625 startSupplicantAndDispatchMessages(); 1626 mWsm.setSupplicantRunning(true); 1627 mLooper.dispatchAll(); 1628 assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest()); 1629 assertEquals(WifiManager.WIFI_STATE_ENABLED, mWsm.syncGetWifiState()); 1630 inOrder.verify(mWifiConnectivityManager).setWifiEnabled(eq(true)); 1631 assertNull(wifiInfo.getBSSID()); 1632 1633 // Send a SUPPLICANT_STATE_CHANGE_EVENT, verify WifiInfo is updated 1634 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 1635 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 1636 mLooper.dispatchAll(); 1637 assertEquals(sBSSID, wifiInfo.getBSSID()); 1638 assertEquals(SupplicantState.COMPLETED, wifiInfo.getSupplicantState()); 1639 1640 // Set WSM to SCAN_ONLY_MODE, verify state and wifi disabled in ConnectivityManager, and 1641 // WifiInfo is reset() and state set to DISCONNECTED 1642 mWsm.setOperationalMode(WifiStateMachine.SCAN_ONLY_MODE); 1643 mLooper.dispatchAll(); 1644 assertEquals(WifiStateMachine.SCAN_ONLY_MODE, mWsm.getOperationalModeForTest()); 1645 assertEquals("ScanModeState", getCurrentState().getName()); 1646 assertEquals(WifiManager.WIFI_STATE_DISABLED, mWsm.syncGetWifiState()); 1647 inOrder.verify(mWifiConnectivityManager).setWifiEnabled(eq(false)); 1648 assertNull(wifiInfo.getBSSID()); 1649 assertEquals(SupplicantState.DISCONNECTED, wifiInfo.getSupplicantState()); 1650 1651 // Send a SUPPLICANT_STATE_CHANGE_EVENT, verify WifiInfo is not updated 1652 mWsm.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0, 1653 new StateChangeResult(0, sWifiSsid, sBSSID, SupplicantState.COMPLETED)); 1654 mLooper.dispatchAll(); 1655 assertNull(wifiInfo.getBSSID()); 1656 assertEquals(SupplicantState.DISCONNECTED, wifiInfo.getSupplicantState()); 1657 1658 // Set the bssid to something, so we can verify it is cleared (just in case) 1659 wifiInfo.setBSSID(initialBSSID); 1660 1661 // Set WSM to CONNECT_MODE and verify state, and wifi enabled in ConnectivityManager, 1662 // and WifiInfo has been reset 1663 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1664 mLooper.dispatchAll(); 1665 assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest()); 1666 assertEquals(WifiManager.WIFI_STATE_ENABLED, mWsm.syncGetWifiState()); 1667 inOrder.verify(mWifiConnectivityManager).setWifiEnabled(eq(true)); 1668 assertEquals("DisconnectedState", getCurrentState().getName()); 1669 assertEquals(SupplicantState.DISCONNECTED, wifiInfo.getSupplicantState()); 1670 assertNull(wifiInfo.getBSSID()); 1671 } 1672 1673 /** 1674 * Adds the network without putting WifiStateMachine into ConnectMode. 1675 */ 1676 @Test 1677 public void addNetworkInInitialState() throws Exception { 1678 // We should not be in initial state now. 1679 assertTrue("InitialState".equals(getCurrentState().getName())); 1680 addNetworkAndVerifySuccess(false); 1681 verify(mWifiConnectivityManager, never()).setUserConnectChoice(eq(0)); 1682 } 1683 1684 /** 1685 * Test START_WPS with a null wpsInfo object fails gracefully (No NPE) 1686 */ 1687 @Test 1688 public void testStartWps_nullWpsInfo() throws Exception { 1689 loadComponentsInStaMode(); 1690 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1691 assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest()); 1692 assertEquals("DisconnectedState", getCurrentState().getName()); 1693 mLooper.startAutoDispatch(); 1694 Message reply = mWsmAsyncChannel.sendMessageSynchronously(WifiManager.START_WPS, 0, 0, 1695 null); 1696 mLooper.stopAutoDispatch(); 1697 assertEquals(WifiManager.WPS_FAILED, reply.what); 1698 } 1699 1700 /** 1701 * Test that DISABLE_NETWORK returns failure to public API when WifiConfigManager returns 1702 * failure. 1703 */ 1704 @Test 1705 public void testSyncDisableNetwork_failure() throws Exception { 1706 loadComponentsInStaMode(); 1707 mWsm.setOperationalMode(WifiStateMachine.CONNECT_MODE); 1708 assertEquals(WifiStateMachine.CONNECT_MODE, mWsm.getOperationalModeForTest()); 1709 assertEquals("DisconnectedState", getCurrentState().getName()); 1710 when(mWifiConfigManager.disableNetwork(anyInt(), anyInt())).thenReturn(false); 1711 1712 mLooper.startAutoDispatch(); 1713 boolean succeeded = mWsm.syncDisableNetwork(mWsmAsyncChannel, 0); 1714 mLooper.stopAutoDispatch(); 1715 assertFalse(succeeded); 1716 } 1717} 1718