summaryrefslogtreecommitdiff
path: root/Settings/src/com/android/tv/settings/connectivity/WifiConfigHelper.java
blob: 2be232a64fbdea6a316005d8f4aeb272de0249e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.tv.settings.connectivity;

import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.TextUtils;
import android.util.Log;

import com.android.settingslib.wifi.AccessPoint;
import com.android.tv.settings.R;
import com.android.tv.settings.connectivity.util.WifiSecurityUtil;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Helper class that deals with Wi-fi configuration.
 */
public final class WifiConfigHelper {

    private static final String TAG = "WifiConfigHelper";
    private static final boolean DEBUG = false;

    // Allows underscore char to supports proxies that do not
    // follow the spec
    private static final String HC = "a-zA-Z0-9\\_";

    // Matches blank input, ips, and domain names
    private static final String HOSTNAME_REGEXP =
            "^$|^[" + HC + "]+(\\-[" + HC + "]+)*(\\.[" + HC + "]+(\\-[" + HC + "]+)*)*$";
    private static final Pattern HOSTNAME_PATTERN;
    private static final String EXCLUSION_REGEXP =
            "$|^(\\*)?\\.?[" + HC + "]+(\\-[" + HC + "]+)*(\\.[" + HC + "]+(\\-[" + HC + "]+)*)*$";
    private static final Pattern EXCLUSION_PATTERN;

    private static final String BYPASS_PROXY_EXCLUDE_REGEX =
            "[a-zA-Z0-9*]+(\\-[a-zA-Z0-9*]+)*(\\.[a-zA-Z0-9*]+(\\-[a-zA-Z0-9*]+)*)*";
    private static final String BYPASS_PROXY_EXCLUDE_LIST_REGEXP = "^$|^"
            + BYPASS_PROXY_EXCLUDE_REGEX + "(," + BYPASS_PROXY_EXCLUDE_REGEX + ")*$";
    private static final Pattern BYPASS_PROXY_EXCLUSION_PATTERN;

    static {
        HOSTNAME_PATTERN = Pattern.compile(HOSTNAME_REGEXP);
        EXCLUSION_PATTERN = Pattern.compile(EXCLUSION_REGEXP);
        BYPASS_PROXY_EXCLUSION_PATTERN = Pattern.compile(BYPASS_PROXY_EXCLUDE_LIST_REGEXP);
    }

    private WifiConfigHelper() {
    }

    /**
     * Set configuration ssid.
     *
     * @param config configuration
     * @param ssid   network ssid
     */
    public static void setConfigSsid(WifiConfiguration config, String ssid) {
        config.SSID = AccessPoint.convertToQuotedString(ssid);
    }

    /**
     * Set configuration key managment by security.
     */
    public static void setConfigKeyManagementBySecurity(
            WifiConfiguration config, int security) {
        config.allowedKeyManagement.clear();
        config.allowedAuthAlgorithms.clear();
        switch (security) {
            case AccessPoint.SECURITY_NONE:
                config.allowedKeyManagement.set(KeyMgmt.NONE);
                break;
            case AccessPoint.SECURITY_WEP:
                config.allowedKeyManagement.set(KeyMgmt.NONE);
                config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
                config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
                break;
            case AccessPoint.SECURITY_PSK:
                config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
                break;
            case AccessPoint.SECURITY_EAP:
                config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
                config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
                break;
        }
    }

    /**
     * validate syntax of hostname and port entries
     *
     * @param hostname host name to be used
     * @param port port to be used
     * @param exclList what should be accepted as input
     * @return 0 on success, string resource ID on failure
     */
    public static int validate(String hostname, String port, String exclList) {
        return validate(hostname, port, exclList, false);
    }

    /**
     * validate syntax of hostname and port entries
     *
     * @param hostname host name to be used
     * @param port port to be used
     * @param exclList what should be accepted as input
     * @param forProxyCheck if extra check for bypass proxy should be done
     * @return 0 on success, string resource ID on failure
     */
    public static int validate(String hostname, String port, String exclList,
                               boolean forProxyCheck) {
        if (DEBUG) {
            Log.i(TAG, "validate, hostname: " + hostname + ", for proxy=" + forProxyCheck);
        }
        Matcher match = HOSTNAME_PATTERN.matcher(hostname);
        String[] exclListArray = exclList.split(",");

        if (!match.matches()) return R.string.proxy_error_invalid_host;

        for (String excl : exclListArray) {
            Matcher m;
            if (forProxyCheck) {
                m = BYPASS_PROXY_EXCLUSION_PATTERN.matcher(excl);
            } else {
                m = EXCLUSION_PATTERN.matcher(excl);
            }
            if (!m.matches()) {
                return R.string.proxy_error_invalid_exclusion_list;
            }
        }

        if (hostname.length() > 0 && port.length() == 0) {
            return R.string.proxy_error_empty_port;
        }

        if (port.length() > 0) {
            if (hostname.length() == 0) {
                return R.string.proxy_error_empty_host_set_port;
            }
            int portVal = -1;
            try {
                portVal = Integer.parseInt(port);
            } catch (NumberFormatException ex) {
                return R.string.proxy_error_invalid_port;
            }
            if (portVal <= 0 || portVal > 0xFFFF) {
                return R.string.proxy_error_invalid_port;
            }
        }
        return 0;
    }

    /**
     * Get {@link WifiConfiguration} based upon the {@link WifiManager} and networkId.
     *
     * @param networkId the id of the network.
     * @return the {@link WifiConfiguration} of the specified network.
     */
    public static WifiConfiguration getWifiConfiguration(WifiManager wifiManager, int networkId) {
        List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
        if (configuredNetworks != null) {
            for (WifiConfiguration configuredNetwork : configuredNetworks) {
                if (configuredNetwork.networkId == networkId) {
                    return configuredNetwork;
                }
            }
        }
        return null;
    }

    /**
     * Did this config come out of the supplicant?  NOT "Is the config currently in the supplicant?"
     */
    public static boolean isNetworkSaved(WifiConfiguration config) {
        return config != null && config.networkId > -1;
    }

    /**
     * Return the configured network that matches the ssid/security pair, or create one.
     */
    public static WifiConfiguration getConfiguration(Context context, String ssid, int security) {
        WifiConfiguration config = getFromConfiguredNetworks(context, ssid, security);

        if (config == null) {
            // No configured network found; populate a new one with the provided ssid / security.
            config = new WifiConfiguration();
            setConfigSsid(config, ssid);
            setConfigKeyManagementBySecurity(config, security);
        }
        return config;
    }

    /**
     * Save a wifi configuration.
     */
    public static boolean saveConfiguration(Context context, WifiConfiguration config) {
        if (config == null) {
            return false;
        }

        WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        int networkId = wifiMan.addNetwork(config);
        if (networkId == -1) {
            if (DEBUG) Log.e(TAG, "failed to add network: " + config.toString());
            return false;
        }

        if (!wifiMan.enableNetwork(networkId, false)) {
            if (DEBUG) Log.e(TAG, "enable network failed: " + networkId + "; " + config.toString());
            return false;
        }

        if (!wifiMan.saveConfiguration()) {
            if (DEBUG) Log.e(TAG, "failed to save: " + config.toString());
            return false;
        }

        if (DEBUG) Log.d(TAG, "saved network: " + config.toString());
        return true;
    }

    /**
     * @return A matching WifiConfiguration from the list of configured
     * networks, or null if no matching network is found.
     */
    private static WifiConfiguration getFromConfiguredNetworks(Context context,
            String ssid,
            int security) {
        WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        List<WifiConfiguration> configuredNetworks = wifiMan.getConfiguredNetworks();
        if (configuredNetworks != null) {
            for (WifiConfiguration configuredNetwork : configuredNetworks) {
                if (configuredNetwork == null || configuredNetwork.SSID == null) {
                    continue;  // Does this ever really happen?
                }

                // If the SSID and the security match, that's our network.
                String configuredSsid = WifiInfo.sanitizeSsid(configuredNetwork.SSID);

                if (TextUtils.equals(configuredSsid, ssid)) {
                    int configuredSecurity = WifiSecurityUtil.getSecurity(configuredNetwork);
                    if (configuredSecurity == security) {
                        return configuredNetwork;
                    }
                }
            }
        }

        return null;
    }
}