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