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