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