1/*
2 * Copyright (C) 2013, 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.connectivitymanagertest.functional;
18
19import com.android.connectivitymanagertest.ConnectivityManagerTestActivity;
20import com.android.connectivitymanagertest.WifiAssociationTestRunner;
21
22import android.content.Context;
23import android.os.Bundle;
24import android.net.wifi.WifiInfo;
25import android.net.wifi.WifiConfiguration;
26import android.net.wifi.WifiConfiguration.KeyMgmt;
27import android.net.wifi.WifiConfiguration.AuthAlgorithm;
28import android.net.wifi.WifiConfiguration.GroupCipher;
29import android.net.wifi.WifiConfiguration.PairwiseCipher;
30import android.net.wifi.WifiConfiguration.Protocol;
31import android.net.wifi.WifiManager;
32import android.net.ConnectivityManager;
33import android.net.NetworkInfo.State;
34import android.test.suitebuilder.annotation.LargeTest;
35import android.test.ActivityInstrumentationTestCase2;
36import android.util.Log;
37
38/**
39 * Test Wi-Fi connection with different configuration
40 * To run this tests:
41 *  * adb shell am instrument -e ssid <ssid> -e password <password> \
42 * -e security-type [OPEN|WEP64|WEP128|WPA_TKIP|WPA2_AES] -e frequency-band [2.4|5.0|auto]
43 * -w com.android.connectivitymanagertest/.WifiAssociationTestRunner"
44 */
45public class WifiAssociationTest
46    extends ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> {
47    private static final String TAG = "WifiAssociationTest";
48    private ConnectivityManagerTestActivity mAct;
49    private String mSsid = null;
50    private String mPassword = null;
51    private String mSecurityType = null;
52    private String mFrequencyBand = null;
53    private int mBand;
54    private WifiManager mWifiManager = null;
55
56    enum SECURITY_TYPE {
57        OPEN, WEP64, WEP128, WPA_TKIP, WPA2_AES
58    };
59
60    public WifiAssociationTest() {
61        super(ConnectivityManagerTestActivity.class);
62    }
63
64    @Override
65    public void setUp() throws Exception {
66        super.setUp();
67        WifiAssociationTestRunner mRunner = (WifiAssociationTestRunner)getInstrumentation();
68        mWifiManager = (WifiManager) mRunner.getContext().getSystemService(Context.WIFI_SERVICE);
69        mAct = getActivity();
70        Bundle arguments = mRunner.getArguments();
71        mSecurityType = arguments.getString("security-type");
72        mSsid = arguments.getString("ssid");
73        mPassword = arguments.getString("password");
74        mFrequencyBand = arguments.getString("frequency-band");
75        mBand = mRunner.mBand;
76        assertNotNull("Security type is empty", mSecurityType);
77        assertNotNull("Ssid is empty", mSsid);
78        validateFrequencyBand();
79        // enable Wifi and verify wpa_supplicant is started
80        assertTrue("enable Wifi failed", mAct.enableWifi());
81        sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT,
82                "interrupted while waiting for WPA_SUPPLICANT to start");
83        WifiInfo mConnection = mAct.mWifiManager.getConnectionInfo();
84        assertNotNull(mConnection);
85        assertTrue("wpa_supplicant is not started ", mAct.mWifiManager.pingSupplicant());
86    }
87
88    @Override
89    public void tearDown() throws Exception {
90        log("tearDown()");
91        super.tearDown();
92    }
93
94    private void validateFrequencyBand() {
95        if (mFrequencyBand != null) {
96            int currentFreq = mWifiManager.getFrequencyBand();
97            Log.v(TAG, "read frequency band: " + currentFreq);
98            assertTrue("device frequency band is not set successfully", (mBand == currentFreq));
99         }
100    }
101
102    /**
103     * Connect to the provided Wi-Fi network
104     * @param config is the network configuration
105     * @return true if the connection is successful.
106     */
107    private void connectToWifi(WifiConfiguration config) {
108        // step 1: connect to the test access point
109        assertTrue("failed to associate with " + config.SSID,
110                mAct.connectToWifiWithConfiguration(config));
111
112        // step 2: verify Wifi state and network state;
113        assertTrue("failed to connect with " + config.SSID,
114                mAct.waitForNetworkState(ConnectivityManager.TYPE_WIFI,
115                State.CONNECTED, ConnectivityManagerTestActivity.WIFI_CONNECTION_TIMEOUT));
116
117        // step 3: verify the current connected network is the given SSID
118        assertNotNull("Wifi connection returns null", mAct.mWifiManager.getConnectionInfo());
119        assertTrue(config.SSID.contains(mAct.mWifiManager.getConnectionInfo().getSSID()));
120    }
121
122    private void sleep(long sometime, String errorMsg) {
123        try {
124            Thread.sleep(sometime);
125        } catch (InterruptedException e) {
126            fail(errorMsg);
127        }
128    }
129
130    private void log(String message) {
131        Log.v(TAG, message);
132    }
133
134    @LargeTest
135    public void testWifiAssociation() {
136        assertNotNull("no test ssid", mSsid);
137        WifiConfiguration config = new WifiConfiguration();
138        config.SSID = mSsid;
139        SECURITY_TYPE security = SECURITY_TYPE.valueOf(mSecurityType);
140        log("Security type is " + security.toString());
141        switch (security) {
142            // set network configurations
143            case OPEN:
144                config.allowedKeyManagement.set(KeyMgmt.NONE);
145                break;
146            case WEP64:
147                // always use hex pair for WEP-40
148                assertTrue("not a WEP64 security type?", mPassword.length() == 10);
149                config.allowedKeyManagement.set(KeyMgmt.NONE);
150                config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
151                config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
152                config.allowedGroupCiphers.set(GroupCipher.WEP40);
153                if (mPassword != null) {
154                    int length = mPassword.length();
155                    // WEP-40
156                    if (mPassword.matches("[0-9A-Fa-f]*")) {
157                        config.wepKeys[0] = mPassword;
158                    } else {
159                        fail("Please type hex pair for the password");
160                    }
161                }
162                break;
163            case WEP128:
164                assertNotNull("password is empty", mPassword);
165                // always use hex pair for WEP-104
166                assertTrue("not a WEP128 security type?", mPassword.length() == 26);
167                config.allowedKeyManagement.set(KeyMgmt.NONE);
168                config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
169                config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
170                config.allowedGroupCiphers.set(GroupCipher.WEP104);
171                if (mPassword != null) {
172                    int length = mPassword.length();
173                    // WEP-40
174                    if (mPassword.matches("[0-9A-Fa-f]*")) {
175                        config.wepKeys[0] = mPassword;
176                    } else {
177                        fail("Please type hex pair for the password");
178                    }
179                }
180                break;
181            case WPA_TKIP:
182                assertNotNull("missing password", mPassword);
183                config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
184                config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
185                config.allowedProtocols.set(Protocol.WPA);
186                config.allowedPairwiseCiphers.set(PairwiseCipher.TKIP);
187                config.allowedGroupCiphers.set(GroupCipher.TKIP);
188                if (mPassword.matches("[0-9A-Fa-f]{64}")) {
189                    config.preSharedKey = mPassword;
190                } else {
191                    config.preSharedKey = '"' + mPassword + '"';
192                }
193                break;
194            case WPA2_AES:
195                assertNotNull("missing password", mPassword);
196                config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
197                config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
198                config.allowedProtocols.set(Protocol.RSN);
199                config.allowedPairwiseCiphers.set(PairwiseCipher.CCMP);
200                config.allowedGroupCiphers.set(GroupCipher.CCMP);
201                config.allowedProtocols.set(Protocol.RSN);
202                if (mPassword.matches("[0-9A-Fa-f]{64}")) {
203                    config.preSharedKey = mPassword;
204                } else {
205                    config.preSharedKey = '"' + mPassword + '"';
206                }
207                break;
208            default:
209                fail("Not a valid security type: " + mSecurityType);
210                break;
211        }
212        Log.v(TAG, "network config: " + config.toString());
213        connectToWifi(config);
214    }
215}
216