WifiConfigStore.java revision 8639f6266cb70bf92d1561af43ac2d7b2b97298e
1/*
2 * Copyright (C) 2010 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 android.content.Context;
20import android.content.Intent;
21import android.net.IpConfiguration;
22import android.net.IpConfiguration.IpAssignment;
23import android.net.IpConfiguration.ProxySettings;
24import android.net.LinkAddress;
25import android.net.NetworkInfo.DetailedState;
26import android.net.ProxyInfo;
27import android.net.RouteInfo;
28import android.net.StaticIpConfiguration;
29import android.net.wifi.WifiConfiguration;
30import android.net.wifi.WifiConfiguration.KeyMgmt;
31import android.net.wifi.WifiConfiguration.Status;
32import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID;
33
34import android.net.wifi.WifiEnterpriseConfig;
35import android.net.wifi.WifiManager;
36import android.net.wifi.WifiSsid;
37import android.net.wifi.WpsInfo;
38import android.net.wifi.WpsResult;
39import android.net.wifi.ScanResult;
40import android.net.wifi.WifiInfo;
41
42import android.os.Environment;
43import android.os.FileObserver;
44import android.os.Process;
45import android.os.SystemClock;
46import android.os.UserHandle;
47import android.provider.Settings;
48import android.security.Credentials;
49import android.security.KeyChain;
50import android.security.KeyStore;
51import android.text.TextUtils;
52import android.util.LocalLog;
53import android.util.Log;
54import android.util.SparseArray;
55
56import com.android.server.net.DelayedDiskWrite;
57import com.android.server.net.IpConfigStore;
58import com.android.internal.R;
59
60import java.io.BufferedReader;
61import java.io.BufferedInputStream;
62import java.io.DataInputStream;
63import java.io.DataOutputStream;
64import java.io.EOFException;
65import java.io.File;
66import java.io.FileDescriptor;
67import java.io.FileInputStream;
68import java.io.FileNotFoundException;
69import java.io.FileReader;
70import java.io.IOException;
71import java.io.PrintWriter;
72import java.math.BigInteger;
73import java.net.InetAddress;
74import java.nio.charset.Charset;
75import java.security.PrivateKey;
76import java.security.cert.Certificate;
77import java.security.cert.CertificateException;
78import java.text.SimpleDateFormat;
79import java.text.DateFormat;
80import java.util.regex.Matcher;
81import java.util.regex.Pattern;
82import java.util.*;
83
84/**
85 * This class provides the API to manage configured
86 * wifi networks. The API is not thread safe is being
87 * used only from WifiStateMachine.
88 *
89 * It deals with the following
90 * - Add/update/remove a WifiConfiguration
91 *   The configuration contains two types of information.
92 *     = IP and proxy configuration that is handled by WifiConfigStore and
93 *       is saved to disk on any change.
94 *
95 *       The format of configuration file is as follows:
96 *       <version>
97 *       <netA_key1><netA_value1><netA_key2><netA_value2>...<EOS>
98 *       <netB_key1><netB_value1><netB_key2><netB_value2>...<EOS>
99 *       ..
100 *
101 *       (key, value) pairs for a given network are grouped together and can
102 *       be in any order. A EOS at the end of a set of (key, value) pairs
103 *       indicates that the next set of (key, value) pairs are for a new
104 *       network. A network is identified by a unique ID_KEY. If there is no
105 *       ID_KEY in the (key, value) pairs, the data is discarded.
106 *
107 *       An invalid version on read would result in discarding the contents of
108 *       the file. On the next write, the latest version is written to file.
109 *
110 *       Any failures during read or write to the configuration file are ignored
111 *       without reporting to the user since the likelihood of these errors are
112 *       low and the impact on connectivity is low.
113 *
114 *     = SSID & security details that is pushed to the supplicant.
115 *       supplicant saves these details to the disk on calling
116 *       saveConfigCommand().
117 *
118 *       We have two kinds of APIs exposed:
119 *        > public API calls that provide fine grained control
120 *          - enableNetwork, disableNetwork, addOrUpdateNetwork(),
121 *          removeNetwork(). For these calls, the config is not persisted
122 *          to the disk. (TODO: deprecate these calls in WifiManager)
123 *        > The new API calls - selectNetwork(), saveNetwork() & forgetNetwork().
124 *          These calls persist the supplicant config to disk.
125 *
126 * - Maintain a list of configured networks for quick access
127 *
128 */
129public class WifiConfigStore extends IpConfigStore {
130
131    private Context mContext;
132    private static final String TAG = "WifiConfigStore";
133    private static final boolean DBG = true;
134    private static boolean VDBG = false;
135    private static boolean VVDBG = false;
136
137    private static final String SUPPLICANT_CONFIG_FILE = "/data/misc/wifi/wpa_supplicant.conf";
138
139    /* configured networks with network id as the key */
140    private HashMap<Integer, WifiConfiguration> mConfiguredNetworks =
141            new HashMap<Integer, WifiConfiguration>();
142
143    /* A network id is a unique identifier for a network configured in the
144     * supplicant. Network ids are generated when the supplicant reads
145     * the configuration file at start and can thus change for networks.
146     * We store the IP configuration for networks along with a unique id
147     * that is generated from SSID and security type of the network. A mapping
148     * from the generated unique id to network id of the network is needed to
149     * map supplicant config to IP configuration. */
150    private HashMap<Integer, Integer> mNetworkIds =
151            new HashMap<Integer, Integer>();
152
153    /* Tracks the highest priority of configured networks */
154    private int mLastPriority = -1;
155
156    private static final String ipConfigFile = Environment.getDataDirectory() +
157            "/misc/wifi/ipconfig.txt";
158
159    private static final String networkHistoryConfigFile = Environment.getDataDirectory() +
160            "/misc/wifi/networkHistory.txt";
161
162    private static final String autoJoinConfigFile = Environment.getDataDirectory() +
163            "/misc/wifi/autojoinconfig.txt";
164
165    /* Network History Keys */
166    private static final String SSID_KEY = "SSID:  ";
167    private static final String CONFIG_KEY = "CONFIG:  ";
168    private static final String CHOICE_KEY = "CHOICE:  ";
169    private static final String LINK_KEY = "LINK:  ";
170    private static final String BSSID_KEY = "BSSID:  ";
171    private static final String BSSID_KEY_END = "/BSSID:  ";
172    private static final String RSSI_KEY = "RSSI:  ";
173    private static final String FREQ_KEY = "FREQ:  ";
174    private static final String DATE_KEY = "DATE:  ";
175    private static final String MILLI_KEY = "MILLI:  ";
176    private static final String BLACKLIST_MILLI_KEY = "BLACKLIST_MILLI:  ";
177    private static final String NETWORK_ID_KEY = "ID:  ";
178    private static final String PRIORITY_KEY = "PRIORITY:  ";
179    private static final String DEFAULT_GW_KEY = "DEFAULT_GW:  ";
180    private static final String AUTH_KEY = "AUTH:  ";
181    private static final String SEPARATOR_KEY = "\n";
182    private static final String STATUS_KEY = "AUTO_JOIN_STATUS:  ";
183    private static final String BSSID_STATUS_KEY = "BSSID_STATUS:  ";
184    private static final String SELF_ADDED_KEY = "SELF_ADDED:  ";
185    private static final String FAILURE_KEY = "FAILURE:  ";
186    private static final String DID_SELF_ADD_KEY = "DID_SELF_ADD:  ";
187    private static final String PEER_CONFIGURATION_KEY = "PEER_CONFIGURATION:  ";
188    private static final String CREATOR_UID_KEY = "CREATOR_UID_KEY:  ";
189    private static final String CONNECT_UID_KEY = "CONNECT_UID_KEY:  ";
190    private static final String UPDATE_UID_KEY = "UPDATE_UID:  ";
191    private static final String SUPPLICANT_STATUS_KEY = "SUP_STATUS:  ";
192    private static final String SUPPLICANT_DISABLE_REASON_KEY = "SUP_DIS_REASON:  ";
193    private static final String FQDN_KEY = "FQDN:  ";
194    private static final String NUM_CONNECTION_FAILURES_KEY = "CONNECT_FAILURES:  ";
195    private static final String NUM_IP_CONFIG_FAILURES_KEY = "IP_CONFIG_FAILURES:  ";
196    private static final String NUM_AUTH_FAILURES_KEY = "AUTH_FAILURES:  ";
197    private static final String SCORER_OVERRIDE_KEY = "SCORER_OVERRIDE:  ";
198    private static final String SCORER_OVERRIDE_AND_SWITCH_KEY = "SCORER_OVERRIDE_AND_SWITCH:  ";
199    private static final String NO_INTERNET_ACCESS_KEY = "NO_INTERNET_ACCESS:  ";
200    private static final String EPHEMERAL_KEY = "EPHEMERAL:   ";
201    private static final String NUM_ASSOCIATION_KEY = "NUM_ASSOCIATION:  ";
202    private static final String THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_5G_KEY
203            = "THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_5G:  ";
204    private static final String THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_24G_KEY
205            = "THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_24G:  ";
206    private static final String THRESHOLD_UNBLACKLIST_HARD_5G_KEY
207            = "THRESHOLD_UNBLACKLIST_HARD_5G:  ";
208    private static final String THRESHOLD_UNBLACKLIST_SOFT_5G_KEY
209            = "THRESHOLD_UNBLACKLIST_SOFT_5G:  ";
210    private static final String THRESHOLD_UNBLACKLIST_HARD_24G_KEY
211            = "THRESHOLD_UNBLACKLIST_HARD_24G:  ";
212    private static final String THRESHOLD_UNBLACKLIST_SOFT_24G_KEY
213            = "THRESHOLD_UNBLACKLIST_SOFT_24G:  ";
214    private static final String THRESHOLD_GOOD_RSSI_5_KEY
215            = "THRESHOLD_GOOD_RSSI_5:  ";
216    private static final String THRESHOLD_LOW_RSSI_5_KEY
217            = "THRESHOLD_LOW_RSSI_5:  ";
218    private static final String THRESHOLD_BAD_RSSI_5_KEY
219            = "THRESHOLD_BAD_RSSI_5:  ";
220    private static final String THRESHOLD_GOOD_RSSI_24_KEY
221            = "THRESHOLD_GOOD_RSSI_24:  ";
222    private static final String THRESHOLD_LOW_RSSI_24_KEY
223            = "THRESHOLD_LOW_RSSI_24:  ";
224    private static final String THRESHOLD_BAD_RSSI_24_KEY
225            = "THRESHOLD_BAD_RSSI_24:  ";
226
227    private static final String THRESHOLD_MAX_TX_PACKETS_FOR_NETWORK_SWITCHING_KEY
228            = "THRESHOLD_MAX_TX_PACKETS_FOR_NETWORK_SWITCHING:   ";
229    private static final String THRESHOLD_MAX_RX_PACKETS_FOR_NETWORK_SWITCHING_KEY
230            = "THRESHOLD_MAX_RX_PACKETS_FOR_NETWORK_SWITCHING:   ";
231
232    private static final String THRESHOLD_MAX_TX_PACKETS_FOR_FULL_SCANS_KEY
233            = "THRESHOLD_MAX_TX_PACKETS_FOR_FULL_SCANS:   ";
234    private static final String THRESHOLD_MAX_RX_PACKETS_FOR_FULL_SCANS_KEY
235            = "THRESHOLD_MAX_RX_PACKETS_FOR_FULL_SCANS:   ";
236
237    private static final String THRESHOLD_MAX_TX_PACKETS_FOR_PARTIAL_SCANS_KEY
238            = "THRESHOLD_MAX_TX_PACKETS_FOR_PARTIAL_SCANS:   ";
239    private static final String THRESHOLD_MAX_RX_PACKETS_FOR_PARTIAL_SCANS_KEY
240            = "THRESHOLD_MAX_RX_PACKETS_FOR_PARTIAL_SCANS:   ";
241
242    private static final String MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY
243            = "MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCANS:   ";
244    private static final String MAX_NUM_PASSIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY
245            = "MAX_NUM_PASSIVE_CHANNELS_FOR_PARTIAL_SCANS:   ";
246
247    private static final String A_BAND_PREFERENCE_RSSI_THRESHOLD_LOW_KEY =
248            "A_BAND_PREFERENCE_RSSI_THRESHOLD_LOW:   ";
249    private static final String A_BAND_PREFERENCE_RSSI_THRESHOLD_KEY =
250            "A_BAND_PREFERENCE_RSSI_THRESHOLD:   ";
251    private static final String G_BAND_PREFERENCE_RSSI_THRESHOLD_KEY =
252            "G_BAND_PREFERENCE_RSSI_THRESHOLD:   ";
253
254    private static final String ENABLE_AUTOJOIN_WHILE_ASSOCIATED_KEY
255            = "ENABLE_AUTOJOIN_WHILE_ASSOCIATED:   ";
256
257    private static final String ASSOCIATED_PARTIAL_SCAN_PERIOD_KEY
258            = "ASSOCIATED_PARTIAL_SCAN_PERIOD:   ";
259    private static final String ASSOCIATED_FULL_SCAN_BACKOFF_KEY
260            = "ASSOCIATED_FULL_SCAN_BACKOFF_PERIOD:   ";
261    private static final String ALWAYS_ENABLE_SCAN_WHILE_ASSOCIATED_KEY
262            = "ALWAYS_ENABLE_SCAN_WHILE_ASSOCIATED:   ";
263    private static final String ONLY_LINK_SAME_CREDENTIAL_CONFIGURATIONS_KEY
264            = "ONLY_LINK_SAME_CREDENTIAL_CONFIGURATIONS:   ";
265
266    private static final String ENABLE_FULL_BAND_SCAN_WHEN_ASSOCIATED_KEY
267            = "ENABLE_FULL_BAND_SCAN_WHEN_ASSOCIATED:   ";
268
269    // The three below configurations are mainly for power stats and CPU usage tracking
270    // allowing to incrementally disable framework features
271    private static final String ENABLE_AUTO_JOIN_SCAN_WHILE_ASSOCIATED_KEY
272            = "ENABLE_AUTO_JOIN_SCAN_WHILE_ASSOCIATED:   ";
273    private static final String ENABLE_AUTO_JOIN_WHILE_ASSOCIATED_KEY
274            = "ENABLE_AUTO_JOIN_WHILE_ASSOCIATED:   ";
275    private static final String ENABLE_CHIP_WAKE_UP_WHILE_ASSOCIATED_KEY
276            = "ENABLE_CHIP_WAKE_UP_WHILE_ASSOCIATED:   ";
277    private static final String ENABLE_RSSI_POLL_WHILE_ASSOCIATED_KEY
278            = "ENABLE_RSSI_POLL_WHILE_ASSOCIATED_KEY:   ";
279
280    // The Wifi verbose log is provided as a way to persist the verbose logging settings
281    // for testing purpose.
282    // It is not intended for normal use.
283    private static final String WIFI_VERBOSE_LOGS_KEY
284            = "WIFI_VERBOSE_LOGS:   ";
285
286    public boolean enableAutoJoinScanWhenAssociated = true;
287    public boolean enableAutoJoinWhenAssociated = true;
288    public boolean enableChipWakeUpWhenAssociated = true;
289    public boolean enableRssiPollWhenAssociated = true;
290
291    public int maxTxPacketForNetworkSwitching = 40;
292    public int maxRxPacketForNetworkSwitching = 80;
293
294    public int maxTxPacketForFullScans = 8;
295    public int maxRxPacketForFullScans = 16;
296
297    public int maxTxPacketForPartialScans = 40;
298    public int maxRxPacketForPartialScans = 80;
299
300    public boolean enableFullBandScanWhenAssociated = true;
301
302    public int thresholdInitialAutoJoinAttemptMin5RSSI
303            = WifiConfiguration.INITIAL_AUTO_JOIN_ATTEMPT_MIN_5;
304    public int thresholdInitialAutoJoinAttemptMin24RSSI
305            = WifiConfiguration.INITIAL_AUTO_JOIN_ATTEMPT_MIN_24;
306
307    public int thresholdBadRssi5 = WifiConfiguration.BAD_RSSI_5;
308    public int thresholdLowRssi5 = WifiConfiguration.LOW_RSSI_5;
309    public int thresholdGoodRssi5 = WifiConfiguration.GOOD_RSSI_5;
310    public int thresholdBadRssi24 = WifiConfiguration.BAD_RSSI_24;
311    public int thresholdLowRssi24 = WifiConfiguration.LOW_RSSI_24;
312    public int thresholdGoodRssi24 = WifiConfiguration.GOOD_RSSI_24;
313
314    public int associatedFullScanBackoff = 12; // Will be divided by 8 by WifiStateMachine
315    public int associatedFullScanMaxIntervalMilli = 300000;
316
317    public int associatedPartialScanPeriodMilli;
318
319    public int bandPreferenceBoostFactor5 = 5; // Boost by 5 dB per dB above threshold
320    public int bandPreferencePenaltyFactor5 = 2; // Penalize by 2 dB per dB below threshold
321    public int bandPreferencePenaltyThreshold5 = WifiConfiguration.G_BAND_PREFERENCE_RSSI_THRESHOLD;
322    public int bandPreferenceBoostThreshold5 = WifiConfiguration.A_BAND_PREFERENCE_RSSI_THRESHOLD;
323
324    public int badLinkSpeed24 = 6;
325    public int badLinkSpeed5 = 12;
326    public int goodLinkSpeed24 = 24;
327    public int goodLinkSpeed5 = 36;
328
329    public int maxAuthErrorsToBlacklist = 4;
330    public int maxConnectionErrorsToBlacklist = 4;
331    public int wifiConfigBlacklistMinTimeMilli = 1000 * 60 * 5;
332
333    // Boost RSSI values of associated networks
334    public int associatedHysteresisHigh = +14;
335    public int associatedHysteresisLow = +8;
336
337    public int thresholdUnblacklistThreshold5Hard
338            = WifiConfiguration.UNBLACKLIST_THRESHOLD_5_HARD;
339    public int thresholdUnblacklistThreshold5Soft
340            = WifiConfiguration.UNBLACKLIST_THRESHOLD_5_SOFT;
341    public int thresholdUnblacklistThreshold24Hard
342            = WifiConfiguration.UNBLACKLIST_THRESHOLD_24_HARD;
343    public int thresholdUnblacklistThreshold24Soft
344            = WifiConfiguration.UNBLACKLIST_THRESHOLD_24_SOFT;
345    public int enableVerboseLogging = 0;
346    boolean showNetworks = true; // TODO set this back to false, used for debugging 17516271
347
348    public int alwaysEnableScansWhileAssociated = 0;
349
350    public int maxNumActiveChannelsForPartialScans = 6;
351    public int maxNumPassiveChannelsForPartialScans = 2;
352
353    public boolean roamOnAny = false;
354    public boolean onlyLinkSameCredentialConfigurations = true;
355
356    public boolean enableLinkDebouncing = true;
357    public boolean enable5GHzPreference = true;
358    public boolean enableWifiCellularHandoverUserTriggeredAdjustment = true;
359
360    /**
361     * Regex pattern for extracting a connect choice.
362     * Matches a strings like the following:
363     * <configKey>=([0:9]+)
364     */
365    private static Pattern mConnectChoice =
366            Pattern.compile("(.*)=([0-9]+)");
367
368
369    /* Enterprise configuration keys */
370    /**
371     * In old configurations, the "private_key" field was used. However, newer
372     * configurations use the key_id field with the engine_id set to "keystore".
373     * If this field is found in the configuration, the migration code is
374     * triggered.
375     */
376    public static final String OLD_PRIVATE_KEY_NAME = "private_key";
377
378    /**
379     * This represents an empty value of an enterprise field.
380     * NULL is used at wpa_supplicant to indicate an empty value
381     */
382    static final String EMPTY_VALUE = "NULL";
383
384    // Internal use only
385    private static final String[] ENTERPRISE_CONFIG_SUPPLICANT_KEYS = new String[] {
386            WifiEnterpriseConfig.EAP_KEY, WifiEnterpriseConfig.PHASE2_KEY,
387            WifiEnterpriseConfig.IDENTITY_KEY, WifiEnterpriseConfig.ANON_IDENTITY_KEY,
388            WifiEnterpriseConfig.PASSWORD_KEY, WifiEnterpriseConfig.CLIENT_CERT_KEY,
389            WifiEnterpriseConfig.CA_CERT_KEY, WifiEnterpriseConfig.SUBJECT_MATCH_KEY,
390            WifiEnterpriseConfig.ENGINE_KEY, WifiEnterpriseConfig.ENGINE_ID_KEY,
391            WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY };
392
393
394    /**
395     * The maximum number of times we will retry a connection to an access point
396     * for which we have failed in acquiring an IP address from DHCP. A value of
397     * N means that we will make N+1 connection attempts in all.
398     * <p>
399     * See {@link Settings.Secure#WIFI_MAX_DHCP_RETRY_COUNT}. This is the default
400     * value if a Settings value is not present.
401     */
402    private static final int DEFAULT_MAX_DHCP_RETRIES = 9;
403
404
405    private final LocalLog mLocalLog;
406    private final WpaConfigFileObserver mFileObserver;
407
408    private WifiNative mWifiNative;
409    private final KeyStore mKeyStore = KeyStore.getInstance();
410
411    /**
412     * The lastSelectedConfiguration is used to remember which network
413     * was selected last by the user.
414     * The connection to this network may not be successful, as well
415     * the selection (i.e. network priority) might not be persisted.
416     * WiFi state machine is the only object that sets this variable.
417     */
418    private String lastSelectedConfiguration = null;
419
420    WifiConfigStore(Context c, WifiNative wn) {
421        mContext = c;
422        mWifiNative = wn;
423
424        if (showNetworks) {
425            mLocalLog = mWifiNative.getLocalLog();
426            mFileObserver = new WpaConfigFileObserver();
427            mFileObserver.startWatching();
428        } else {
429            mLocalLog = null;
430            mFileObserver = null;
431        }
432
433        associatedPartialScanPeriodMilli = mContext.getResources().getInteger(
434                R.integer.config_wifi_framework_associated_scan_interval);
435        loge("associatedPartialScanPeriodMilli set to " + associatedPartialScanPeriodMilli);
436
437        onlyLinkSameCredentialConfigurations = mContext.getResources().getBoolean(
438                R.bool.config_wifi_only_link_same_credential_configurations);
439        maxNumActiveChannelsForPartialScans = mContext.getResources().getInteger(
440                R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels);
441        maxNumPassiveChannelsForPartialScans = mContext.getResources().getInteger(
442                R.integer.config_wifi_framework_associated_partial_scan_max_num_passive_channels);
443        associatedFullScanMaxIntervalMilli = mContext.getResources().getInteger(
444                R.integer.config_wifi_framework_associated_full_scan_max_interval);
445        associatedFullScanBackoff = mContext.getResources().getInteger(
446                R.integer.config_wifi_framework_associated_full_scan_backoff);
447        enableLinkDebouncing = mContext.getResources().getBoolean(
448                R.bool.config_wifi_enable_disconnection_debounce);
449
450        enable5GHzPreference = mContext.getResources().getBoolean(
451                R.bool.config_wifi_enable_5GHz_preference);
452
453        bandPreferenceBoostFactor5 = mContext.getResources().getInteger(
454                R.integer.config_wifi_framework_5GHz_preference_boost_factor);
455        bandPreferencePenaltyFactor5 = mContext.getResources().getInteger(
456                R.integer.config_wifi_framework_5GHz_preference_penalty_factor);
457
458        bandPreferencePenaltyThreshold5 = mContext.getResources().getInteger(
459                R.integer.config_wifi_framework_5GHz_preference_penalty_threshold);
460        bandPreferenceBoostThreshold5 = mContext.getResources().getInteger(
461                R.integer.config_wifi_framework_5GHz_preference_boost_threshold);
462
463        associatedHysteresisHigh = mContext.getResources().getInteger(
464                R.integer.config_wifi_framework_current_association_hysteresis_high);
465        associatedHysteresisLow = mContext.getResources().getInteger(
466                R.integer.config_wifi_framework_current_association_hysteresis_low);
467
468        thresholdBadRssi5 = mContext.getResources().getInteger(
469                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_5GHz);
470        thresholdLowRssi5 = mContext.getResources().getInteger(
471                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_5GHz);
472        thresholdGoodRssi5 = mContext.getResources().getInteger(
473                R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_5GHz);
474        thresholdBadRssi24 = mContext.getResources().getInteger(
475                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_24GHz);
476        thresholdLowRssi24 = mContext.getResources().getInteger(
477                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_24GHz);
478        thresholdGoodRssi24 = mContext.getResources().getInteger(
479                R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_24GHz);
480
481        enableWifiCellularHandoverUserTriggeredAdjustment = mContext.getResources().getBoolean(
482                R.bool.config_wifi_framework_cellular_handover_enable_user_triggered_adjustment);
483
484        badLinkSpeed24 = mContext.getResources().getInteger(
485                R.integer.config_wifi_framework_wifi_score_bad_link_speed_24);
486        badLinkSpeed5 = mContext.getResources().getInteger(
487                R.integer.config_wifi_framework_wifi_score_bad_link_speed_5);
488        goodLinkSpeed24 = mContext.getResources().getInteger(
489                R.integer.config_wifi_framework_wifi_score_good_link_speed_24);
490        goodLinkSpeed5 = mContext.getResources().getInteger(
491                R.integer.config_wifi_framework_wifi_score_good_link_speed_5);
492
493        maxAuthErrorsToBlacklist = mContext.getResources().getInteger(
494                R.integer.config_wifi_framework_max_auth_errors_to_blacklist);
495        maxConnectionErrorsToBlacklist = mContext.getResources().getInteger(
496                R.integer.config_wifi_framework_max_connection_errors_to_blacklist);
497        wifiConfigBlacklistMinTimeMilli = mContext.getResources().getInteger(
498                R.integer.config_wifi_framework_network_black_list_min_time_milli);
499
500
501        enableAutoJoinScanWhenAssociated = mContext.getResources().getBoolean(
502                R.bool.config_wifi_framework_enable_associated_autojoin_scan);
503
504        enableAutoJoinWhenAssociated = mContext.getResources().getBoolean(
505                R.bool.config_wifi_framework_enable_associated_network_selection);
506    }
507
508    void enableVerboseLogging(int verbose) {
509        enableVerboseLogging = verbose;
510        if (verbose > 0) {
511            VDBG = true;
512            showNetworks = true;
513        } else {
514            VDBG = false;
515        }
516        if (verbose > 1) {
517            VVDBG = true;
518        } else {
519            VVDBG = false;
520        }
521    }
522
523    class WpaConfigFileObserver extends FileObserver {
524
525        public WpaConfigFileObserver() {
526            super(SUPPLICANT_CONFIG_FILE, CLOSE_WRITE);
527        }
528
529        @Override
530        public void onEvent(int event, String path) {
531            if (event == CLOSE_WRITE) {
532                File file = new File(SUPPLICANT_CONFIG_FILE);
533                if (VDBG) localLog("wpa_supplicant.conf changed; new size = " + file.length());
534            }
535        }
536    }
537
538
539    /**
540     * Fetch the list of configured networks
541     * and enable all stored networks in supplicant.
542     */
543    void loadAndEnableAllNetworks() {
544        if (DBG) log("Loading config and enabling all networks ");
545        loadConfiguredNetworks();
546        enableAllNetworks();
547    }
548
549    int getConfiguredNetworksSize() {
550        return mConfiguredNetworks.size();
551    }
552
553    private List<WifiConfiguration> getConfiguredNetworks(Map<String, String> pskMap) {
554        List<WifiConfiguration> networks = new ArrayList<>();
555        for(WifiConfiguration config : mConfiguredNetworks.values()) {
556            WifiConfiguration newConfig = new WifiConfiguration(config);
557            if (config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED || config.ephemeral) {
558                // Do not enumerate and return this configuration to any one,
559                // for instance WiFi Picker.
560                // instead treat it as unknown. the configuration can still be retrieved
561                // directly by the key or networkId
562                continue;
563            }
564
565            if (pskMap != null && config.allowedKeyManagement != null
566                    && config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)
567                    && pskMap.containsKey(config.SSID)) {
568                newConfig.preSharedKey = pskMap.get(config.SSID);
569            }
570            networks.add(newConfig);
571        }
572        return networks;
573    }
574
575    /**
576     * Fetch the list of currently configured networks
577     * @return List of networks
578     */
579    List<WifiConfiguration> getConfiguredNetworks() {
580        return getConfiguredNetworks(null);
581    }
582
583    /**
584     * Fetch the list of currently configured networks, filled with real preSharedKeys
585     * @return List of networks
586     */
587    List<WifiConfiguration> getPrivilegedConfiguredNetworks() {
588        Map<String, String> pskMap = getCredentialsBySsidMap();
589        return getConfiguredNetworks(pskMap);
590    }
591
592    /**
593     * Fetch the preSharedKeys for all networks.
594     * @return a map from Ssid to preSharedKey.
595     */
596    private Map<String, String> getCredentialsBySsidMap() {
597        return readNetworkVariablesFromSupplicantFile("psk");
598    }
599
600    int getconfiguredNetworkSize() {
601        if (mConfiguredNetworks == null)
602            return 0;
603        return mConfiguredNetworks.size();
604    }
605
606    /**
607     * Fetch the list of currently configured networks that were recently seen
608     *
609     * @return List of networks
610     */
611    List<WifiConfiguration> getRecentConfiguredNetworks(int milli, boolean copy) {
612        List<WifiConfiguration> networks = new ArrayList<WifiConfiguration>();
613
614        for (WifiConfiguration config : mConfiguredNetworks.values()) {
615            if (config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED || config.ephemeral) {
616                // Do not enumerate and return this configuration to any one,
617                // instead treat it as unknown. the configuration can still be retrieved
618                // directly by the key or networkId
619                continue;
620            }
621
622            // Calculate the RSSI for scan results that are more recent than milli
623            config.setVisibility(milli);
624            if (config.visibility == null) {
625                continue;
626            }
627            if (config.visibility.rssi5 == WifiConfiguration.INVALID_RSSI &&
628                    config.visibility.rssi24 == WifiConfiguration.INVALID_RSSI) {
629                continue;
630            }
631            if (copy) {
632                networks.add(new WifiConfiguration(config));
633            } else {
634                networks.add(config);
635            }
636        }
637        return networks;
638    }
639
640    /**
641     *  Update the configuration and BSSID with latest RSSI value.
642     */
643    void updateConfiguration(WifiInfo info) {
644        WifiConfiguration config = getWifiConfiguration(info.getNetworkId());
645        if (config != null && config.scanResultCache != null) {
646            ScanResult result = config.scanResultCache.get(info.getBSSID());
647            if (result != null) {
648                long previousSeen = result.seen;
649                int previousRssi = result.level;
650
651                // Update the scan result
652                result.seen = System.currentTimeMillis();
653                result.level = info.getRssi();
654
655                // Average the RSSI value
656                result.averageRssi(previousRssi, previousSeen,
657                        WifiAutoJoinController.mScanResultMaximumAge);
658                if (VDBG) {
659                    loge("updateConfiguration freq=" + result.frequency
660                        + " BSSID=" + result.BSSID
661                        + " RSSI=" + result.level
662                        + " " + config.configKey());
663                }
664            }
665        }
666    }
667
668    /**
669     * get the Wificonfiguration for this netId
670     *
671     * @return Wificonfiguration
672     */
673    WifiConfiguration getWifiConfiguration(int netId) {
674        if (mConfiguredNetworks == null)
675            return null;
676        return mConfiguredNetworks.get(netId);
677    }
678
679    /**
680     * Get the Wificonfiguration for this key
681     * @return Wificonfiguration
682     */
683    WifiConfiguration getWifiConfiguration(String key) {
684        if (key == null)
685            return null;
686        int hash = key.hashCode();
687        if (mNetworkIds == null)
688            return null;
689        Integer n = mNetworkIds.get(hash);
690        if (n == null)
691            return null;
692        int netId = n.intValue();
693        return getWifiConfiguration(netId);
694    }
695
696    /**
697     * Enable all networks and save config. This will be a no-op if the list
698     * of configured networks indicates all networks as being enabled
699     */
700    void enableAllNetworks() {
701        long now = System.currentTimeMillis();
702        boolean networkEnabledStateChanged = false;
703
704        for(WifiConfiguration config : mConfiguredNetworks.values()) {
705
706            if(config != null && config.status == Status.DISABLED
707                    && (config.autoJoinStatus
708                    <= WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE)) {
709
710                // Wait for 20 minutes before reenabling config that have known, repeated connection
711                // or DHCP failures
712                if (config.disableReason == WifiConfiguration.DISABLED_DHCP_FAILURE
713                        || config.disableReason == WifiConfiguration.DISABLED_ASSOCIATION_REJECT
714                        || config.disableReason == WifiConfiguration.DISABLED_AUTH_FAILURE) {
715                    if (config.blackListTimestamp != 0
716                           && now > config.blackListTimestamp
717                           && (now - config.blackListTimestamp) < wifiConfigBlacklistMinTimeMilli) {
718                        continue;
719                    }
720                }
721
722                if(mWifiNative.enableNetwork(config.networkId, false)) {
723                    networkEnabledStateChanged = true;
724                    config.status = Status.ENABLED;
725
726                    // Reset the blacklist condition
727                    config.numConnectionFailures = 0;
728                    config.numIpConfigFailures = 0;
729                    config.numAuthFailures = 0;
730
731                    // Reenable the wifi configuration
732                    config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED);
733                } else {
734                    loge("Enable network failed on " + config.networkId);
735                }
736            }
737        }
738
739        if (networkEnabledStateChanged) {
740            mWifiNative.saveConfig();
741            sendConfiguredNetworksChangedBroadcast();
742        }
743    }
744
745
746    /**
747     * Selects the specified network for connection. This involves
748     * updating the priority of all the networks and enabling the given
749     * network while disabling others.
750     *
751     * Selecting a network will leave the other networks disabled and
752     * a call to enableAllNetworks() needs to be issued upon a connection
753     * or a failure event from supplicant
754     *
755     * @param netId network to select for connection
756     * @return false if the network id is invalid
757     */
758    boolean selectNetwork(int netId) {
759        if (VDBG) localLog("selectNetwork", netId);
760        if (netId == INVALID_NETWORK_ID) return false;
761
762        // Reset the priority of each network at start or if it goes too high.
763        if (mLastPriority == -1 || mLastPriority > 1000000) {
764            for(WifiConfiguration config : mConfiguredNetworks.values()) {
765                if (config.networkId != INVALID_NETWORK_ID) {
766                    config.priority = 0;
767                    addOrUpdateNetworkNative(config, -1);
768                }
769            }
770            mLastPriority = 0;
771        }
772
773        // Set to the highest priority and save the configuration.
774        WifiConfiguration config = new WifiConfiguration();
775        config.networkId = netId;
776        config.priority = ++mLastPriority;
777
778        addOrUpdateNetworkNative(config, -1);
779        mWifiNative.saveConfig();
780
781        /* Enable the given network while disabling all other networks */
782        enableNetworkWithoutBroadcast(netId, true);
783
784       /* Avoid saving the config & sending a broadcast to prevent settings
785        * from displaying a disabled list of networks */
786        return true;
787    }
788
789    /**
790     * Add/update the specified configuration and save config
791     *
792     * @param config WifiConfiguration to be saved
793     * @return network update result
794     */
795    NetworkUpdateResult saveNetwork(WifiConfiguration config, int uid) {
796        WifiConfiguration conf;
797
798        // A new network cannot have null SSID
799        if (config == null || (config.networkId == INVALID_NETWORK_ID &&
800                config.SSID == null)) {
801            return new NetworkUpdateResult(INVALID_NETWORK_ID);
802        }
803        if (VDBG) localLog("WifiConfigStore: saveNetwork netId", config.networkId);
804        if (VDBG) {
805            loge("WifiConfigStore saveNetwork, size=" + mConfiguredNetworks.size()
806                    + " SSID=" + config.SSID
807                    + " Uid=" + Integer.toString(config.creatorUid)
808                    + "/" + Integer.toString(config.lastUpdateUid));
809        }
810        boolean newNetwork = (config.networkId == INVALID_NETWORK_ID);
811        NetworkUpdateResult result = addOrUpdateNetworkNative(config, uid);
812        int netId = result.getNetworkId();
813
814        if (VDBG) localLog("WifiConfigStore: saveNetwork got it back netId=", netId);
815
816        /* enable a new network */
817        if (newNetwork && netId != INVALID_NETWORK_ID) {
818            if (VDBG) localLog("WifiConfigStore: will enable netId=", netId);
819
820            mWifiNative.enableNetwork(netId, false);
821            conf = mConfiguredNetworks.get(netId);
822            if (conf != null)
823                conf.status = Status.ENABLED;
824        }
825
826        conf = mConfiguredNetworks.get(netId);
827        if (conf != null) {
828            if (conf.autoJoinStatus != WifiConfiguration.AUTO_JOIN_ENABLED) {
829                if (VDBG) localLog("WifiConfigStore: re-enabling: " + conf.SSID);
830
831                // reenable autojoin, since new information has been provided
832                conf.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED);
833                enableNetworkWithoutBroadcast(conf.networkId, false);
834            }
835            if (VDBG) {
836                loge("WifiConfigStore: saveNetwork got config back netId="
837                        + Integer.toString(netId)
838                        + " uid=" + Integer.toString(config.creatorUid));
839            }
840        }
841
842        mWifiNative.saveConfig();
843        sendConfiguredNetworksChangedBroadcast(conf, result.isNewNetwork() ?
844                WifiManager.CHANGE_REASON_ADDED : WifiManager.CHANGE_REASON_CONFIG_CHANGE);
845        return result;
846    }
847
848    void saveWifiConfigBSSID(WifiConfiguration config) {
849        // Sanity check the config is valid
850        if (config == null || (config.networkId == INVALID_NETWORK_ID &&
851                config.SSID == null)) {
852            return;
853        }
854
855        // If an app specified a BSSID then dont over-write it
856        if (config.BSSID != null && config.BSSID != "any") {
857            return;
858        }
859
860        // If autojoin specified a BSSID then write it in the network block
861        if (config.autoJoinBSSID != null) {
862            loge("saveWifiConfigBSSID Setting BSSID for " + config.configKey()
863                    + " to " + config.autoJoinBSSID);
864            if (!mWifiNative.setNetworkVariable(
865                    config.networkId,
866                    WifiConfiguration.bssidVarName,
867                    config.autoJoinBSSID)) {
868                loge("failed to set BSSID: " + config.autoJoinBSSID);
869            } else if (config.autoJoinBSSID.equals("any")) {
870                // Paranoia, we just want to make sure that we restore the config to normal
871                mWifiNative.saveConfig();
872            }
873        }
874    }
875
876
877    void updateStatus(int netId, DetailedState state) {
878        if (netId != INVALID_NETWORK_ID) {
879            WifiConfiguration config = mConfiguredNetworks.get(netId);
880            if (config == null) return;
881            switch (state) {
882                case CONNECTED:
883                    config.status = Status.CURRENT;
884                    //we successfully connected, hence remove the blacklist
885                    config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED);
886                    break;
887                case DISCONNECTED:
888                    //If network is already disabled, keep the status
889                    if (config.status == Status.CURRENT) {
890                        config.status = Status.ENABLED;
891                    }
892                    break;
893                default:
894                    //do nothing, retain the existing state
895                    break;
896            }
897        }
898    }
899
900    /**
901     * Forget the specified network and save config
902     *
903     * @param netId network to forget
904     * @return {@code true} if it succeeds, {@code false} otherwise
905     */
906    boolean forgetNetwork(int netId) {
907        if (showNetworks) localLog("forgetNetwork", netId);
908
909        boolean remove = removeConfigAndSendBroadcastIfNeeded(netId);
910        if (!remove) {
911            //success but we dont want to remove the network from supplicant conf file
912            return true;
913        }
914        if (mWifiNative.removeNetwork(netId)) {
915            mWifiNative.saveConfig();
916            return true;
917        } else {
918            loge("Failed to remove network " + netId);
919            return false;
920        }
921    }
922
923    /**
924     * Add/update a network. Note that there is no saveConfig operation.
925     * This function is retained for compatibility with the public
926     * API. The more powerful saveNetwork() is used by the
927     * state machine
928     *
929     * @param config wifi configuration to add/update
930     * @return network Id
931     */
932    int addOrUpdateNetwork(WifiConfiguration config, int uid) {
933        if (showNetworks) localLog("addOrUpdateNetwork id=", config.networkId);
934        //adding unconditional message to chase b/15111865
935        Log.e(TAG, " key=" + config.configKey() + " netId=" + Integer.toString(config.networkId)
936                + " uid=" + Integer.toString(config.creatorUid)
937                + "/" + Integer.toString(config.lastUpdateUid));
938        NetworkUpdateResult result = addOrUpdateNetworkNative(config, uid);
939        if (result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID) {
940            WifiConfiguration conf = mConfiguredNetworks.get(result.getNetworkId());
941            if (conf != null) {
942                sendConfiguredNetworksChangedBroadcast(conf,
943                    result.isNewNetwork ? WifiManager.CHANGE_REASON_ADDED :
944                            WifiManager.CHANGE_REASON_CONFIG_CHANGE);
945            }
946        }
947        return result.getNetworkId();
948    }
949
950    /**
951     * Remove a network. Note that there is no saveConfig operation.
952     * This function is retained for compatibility with the public
953     * API. The more powerful forgetNetwork() is used by the
954     * state machine for network removal
955     *
956     * @param netId network to be removed
957     * @return {@code true} if it succeeds, {@code false} otherwise
958     */
959    boolean removeNetwork(int netId) {
960        if (showNetworks) localLog("removeNetwork", netId);
961        boolean ret = mWifiNative.removeNetwork(netId);
962        if (ret) {
963            removeConfigAndSendBroadcastIfNeeded(netId);
964        }
965        return ret;
966    }
967
968    private boolean removeConfigAndSendBroadcastIfNeeded(int netId) {
969        boolean remove = true;
970        WifiConfiguration config = mConfiguredNetworks.get(netId);
971        if (config != null) {
972            if (VDBG) {
973                loge("removeNetwork " + Integer.toString(netId) + " key=" +
974                        config.configKey() + " config.id=" + Integer.toString(config.networkId));
975            }
976
977            // cancel the last user choice
978            if (config.configKey().equals(lastSelectedConfiguration)) {
979                lastSelectedConfiguration = null;
980            }
981
982            // Remove any associated keys
983            if (config.enterpriseConfig != null) {
984                removeKeys(config.enterpriseConfig);
985            }
986
987            if (config.selfAdded || config.linkedConfigurations != null
988                    || config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
989                remove = false;
990                loge("removeNetwork " + Integer.toString(netId)
991                        + " key=" + config.configKey()
992                        + " config.id=" + Integer.toString(config.networkId)
993                        + " -> mark as deleted");
994            }
995
996            if (remove) {
997                mConfiguredNetworks.remove(netId);
998                mNetworkIds.remove(configKey(config));
999            } else {
1000                /**
1001                 * We can't directly remove the configuration since we could re-add it ourselves,
1002                 * and that would look weird to the user.
1003                 * Instead mark it as deleted and completely hide it from the rest of the system.
1004                 */
1005                config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_DELETED);
1006                // Disable
1007                mWifiNative.disableNetwork(config.networkId);
1008                config.status = WifiConfiguration.Status.DISABLED;
1009                // Since we don't delete the configuration, clean it up and loose the history
1010                config.linkedConfigurations = null;
1011                config.scanResultCache = null;
1012                config.connectChoices = null;
1013                config.defaultGwMacAddress = null;
1014                config.setIpConfiguration(new IpConfiguration());
1015                // Loose the PSK
1016                if (!mWifiNative.setNetworkVariable(
1017                        config.networkId,
1018                        WifiConfiguration.pskVarName,
1019                        "\"xxxxxxxx\"")) {
1020                    loge("removeNetwork, failed to clear PSK, nid=" + config.networkId);
1021                }
1022                // Loose the BSSID
1023                config.BSSID = null;
1024                config.autoJoinBSSID = null;
1025                if (!mWifiNative.setNetworkVariable(
1026                        config.networkId,
1027                        WifiConfiguration.bssidVarName,
1028                        "any")) {
1029                    loge("removeNetwork, failed to remove BSSID");
1030                }
1031                // Loose the hiddenSSID flag
1032                config.hiddenSSID = false;
1033                if (!mWifiNative.setNetworkVariable(
1034                        config.networkId,
1035                        WifiConfiguration.hiddenSSIDVarName,
1036                        Integer.toString(0))) {
1037                    loge("removeNetwork, failed to remove hiddenSSID");
1038                }
1039
1040                mWifiNative.saveConfig();
1041            }
1042
1043            writeIpAndProxyConfigurations();
1044            sendConfiguredNetworksChangedBroadcast(config, WifiManager.CHANGE_REASON_REMOVED);
1045            writeKnownNetworkHistory();
1046        }
1047        return remove;
1048    }
1049
1050    /**
1051     * Enable a network. Note that there is no saveConfig operation.
1052     * This function is retained for compatibility with the public
1053     * API. The more powerful selectNetwork()/saveNetwork() is used by the
1054     * state machine for connecting to a network
1055     *
1056     * @param netId network to be enabled
1057     * @return {@code true} if it succeeds, {@code false} otherwise
1058     */
1059    boolean enableNetwork(int netId, boolean disableOthers) {
1060        boolean ret = enableNetworkWithoutBroadcast(netId, disableOthers);
1061        if (disableOthers) {
1062            if (VDBG) localLog("enableNetwork(disableOthers=true) ", netId);
1063            sendConfiguredNetworksChangedBroadcast();
1064        } else {
1065            if (VDBG) localLog("enableNetwork(disableOthers=false) ", netId);
1066            WifiConfiguration enabledNetwork = null;
1067            synchronized(mConfiguredNetworks) {
1068                enabledNetwork = mConfiguredNetworks.get(netId);
1069            }
1070            // check just in case the network was removed by someone else.
1071            if (enabledNetwork != null) {
1072                sendConfiguredNetworksChangedBroadcast(enabledNetwork,
1073                        WifiManager.CHANGE_REASON_CONFIG_CHANGE);
1074            }
1075        }
1076        return ret;
1077    }
1078
1079    boolean enableNetworkWithoutBroadcast(int netId, boolean disableOthers) {
1080        boolean ret = mWifiNative.enableNetwork(netId, disableOthers);
1081
1082        WifiConfiguration config = mConfiguredNetworks.get(netId);
1083        if (config != null) config.status = Status.ENABLED;
1084
1085        if (disableOthers) {
1086            markAllNetworksDisabledExcept(netId);
1087        }
1088        return ret;
1089    }
1090
1091    void disableAllNetworks() {
1092        if (VDBG) localLog("disableAllNetworks");
1093        boolean networkDisabled = false;
1094        for(WifiConfiguration config : mConfiguredNetworks.values()) {
1095            if(config != null && config.status != Status.DISABLED) {
1096                if(mWifiNative.disableNetwork(config.networkId)) {
1097                    networkDisabled = true;
1098                    config.status = Status.DISABLED;
1099                } else {
1100                    loge("Disable network failed on " + config.networkId);
1101                }
1102            }
1103        }
1104
1105        if (networkDisabled) {
1106            sendConfiguredNetworksChangedBroadcast();
1107        }
1108    }
1109    /**
1110     * Disable a network. Note that there is no saveConfig operation.
1111     * @param netId network to be disabled
1112     * @return {@code true} if it succeeds, {@code false} otherwise
1113     */
1114    boolean disableNetwork(int netId) {
1115        return disableNetwork(netId, WifiConfiguration.DISABLED_UNKNOWN_REASON);
1116    }
1117
1118    /**
1119     * Disable a network. Note that there is no saveConfig operation.
1120     * @param netId network to be disabled
1121     * @param reason reason code network was disabled
1122     * @return {@code true} if it succeeds, {@code false} otherwise
1123     */
1124    boolean disableNetwork(int netId, int reason) {
1125        if (VDBG) localLog("disableNetwork", netId);
1126        boolean ret = mWifiNative.disableNetwork(netId);
1127        WifiConfiguration network = null;
1128        WifiConfiguration config = mConfiguredNetworks.get(netId);
1129
1130        if (VDBG) {
1131            if (config != null) {
1132                loge("disableNetwork netId=" + Integer.toString(netId)
1133                        + " SSID=" + config.SSID
1134                        + " disabled=" + (config.status == Status.DISABLED)
1135                        + " reason=" + Integer.toString(config.disableReason));
1136            }
1137        }
1138        /* Only change the reason if the network was not previously disabled
1139        /* and the reason is not DISABLED_BY_WIFI_MANAGER, that is, if a 3rd party
1140         * set its configuration as disabled, then leave it disabled */
1141        if (config != null && config.status != Status.DISABLED
1142                && config.disableReason != WifiConfiguration.DISABLED_BY_WIFI_MANAGER) {
1143            config.status = Status.DISABLED;
1144            config.disableReason = reason;
1145            network = config;
1146        }
1147        if (reason == WifiConfiguration.DISABLED_BY_WIFI_MANAGER) {
1148            // Make sure autojoin wont reenable this configuration without further user
1149            // intervention
1150            config.autoJoinStatus = WifiConfiguration.AUTO_JOIN_DISABLED_USER_ACTION;
1151        }
1152        if (network != null) {
1153            sendConfiguredNetworksChangedBroadcast(network,
1154                    WifiManager.CHANGE_REASON_CONFIG_CHANGE);
1155        }
1156        return ret;
1157    }
1158
1159    /**
1160     * Save the configured networks in supplicant to disk
1161     * @return {@code true} if it succeeds, {@code false} otherwise
1162     */
1163    boolean saveConfig() {
1164        return mWifiNative.saveConfig();
1165    }
1166
1167    /**
1168     * Start WPS pin method configuration with pin obtained
1169     * from the access point
1170     * @param config WPS configuration
1171     * @return Wps result containing status and pin
1172     */
1173    WpsResult startWpsWithPinFromAccessPoint(WpsInfo config) {
1174        WpsResult result = new WpsResult();
1175        if (mWifiNative.startWpsRegistrar(config.BSSID, config.pin)) {
1176            /* WPS leaves all networks disabled */
1177            markAllNetworksDisabled();
1178            result.status = WpsResult.Status.SUCCESS;
1179        } else {
1180            loge("Failed to start WPS pin method configuration");
1181            result.status = WpsResult.Status.FAILURE;
1182        }
1183        return result;
1184    }
1185
1186    /**
1187     * Start WPS pin method configuration with pin obtained
1188     * from the device
1189     * @return WpsResult indicating status and pin
1190     */
1191    WpsResult startWpsWithPinFromDevice(WpsInfo config) {
1192        WpsResult result = new WpsResult();
1193        result.pin = mWifiNative.startWpsPinDisplay(config.BSSID);
1194        /* WPS leaves all networks disabled */
1195        if (!TextUtils.isEmpty(result.pin)) {
1196            markAllNetworksDisabled();
1197            result.status = WpsResult.Status.SUCCESS;
1198        } else {
1199            loge("Failed to start WPS pin method configuration");
1200            result.status = WpsResult.Status.FAILURE;
1201        }
1202        return result;
1203    }
1204
1205    /**
1206     * Start WPS push button configuration
1207     * @param config WPS configuration
1208     * @return WpsResult indicating status and pin
1209     */
1210    WpsResult startWpsPbc(WpsInfo config) {
1211        WpsResult result = new WpsResult();
1212        if (mWifiNative.startWpsPbc(config.BSSID)) {
1213            /* WPS leaves all networks disabled */
1214            markAllNetworksDisabled();
1215            result.status = WpsResult.Status.SUCCESS;
1216        } else {
1217            loge("Failed to start WPS push button configuration");
1218            result.status = WpsResult.Status.FAILURE;
1219        }
1220        return result;
1221    }
1222
1223    /**
1224     * Fetch the static IP configuration for a given network id
1225     */
1226    StaticIpConfiguration getStaticIpConfiguration(int netId) {
1227        WifiConfiguration config = mConfiguredNetworks.get(netId);
1228        if (config != null) {
1229            return config.getStaticIpConfiguration();
1230        }
1231        return null;
1232    }
1233
1234    /**
1235     * Set the static IP configuration for a given network id
1236     */
1237    void setStaticIpConfiguration(int netId, StaticIpConfiguration staticIpConfiguration) {
1238        WifiConfiguration config = mConfiguredNetworks.get(netId);
1239        if (config != null) {
1240            config.setStaticIpConfiguration(staticIpConfiguration);
1241        }
1242    }
1243
1244    /**
1245     * set default GW MAC address
1246     */
1247    void setDefaultGwMacAddress(int netId, String macAddress) {
1248        WifiConfiguration config = mConfiguredNetworks.get(netId);
1249        if (config != null) {
1250            //update defaultGwMacAddress
1251            config.defaultGwMacAddress = macAddress;
1252        }
1253    }
1254
1255
1256    /**
1257     * Fetch the proxy properties for a given network id
1258     * @param network id
1259     * @return ProxyInfo for the network id
1260     */
1261    ProxyInfo getProxyProperties(int netId) {
1262        WifiConfiguration config = mConfiguredNetworks.get(netId);
1263        if (config != null) {
1264            return config.getHttpProxy();
1265        }
1266        return null;
1267    }
1268
1269    /**
1270     * Return if the specified network is using static IP
1271     * @param network id
1272     * @return {@code true} if using static ip for netId
1273     */
1274    boolean isUsingStaticIp(int netId) {
1275        WifiConfiguration config = mConfiguredNetworks.get(netId);
1276        if (config != null && config.getIpAssignment() == IpAssignment.STATIC) {
1277            return true;
1278        }
1279        return false;
1280    }
1281
1282    /**
1283     * Should be called when a single network configuration is made.
1284     * @param network The network configuration that changed.
1285     * @param reason The reason for the change, should be one of WifiManager.CHANGE_REASON_ADDED,
1286     * WifiManager.CHANGE_REASON_REMOVED, or WifiManager.CHANGE_REASON_CHANGE.
1287     */
1288    private void sendConfiguredNetworksChangedBroadcast(WifiConfiguration network,
1289            int reason) {
1290        Intent intent = new Intent(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
1291        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1292        intent.putExtra(WifiManager.EXTRA_MULTIPLE_NETWORKS_CHANGED, false);
1293        intent.putExtra(WifiManager.EXTRA_WIFI_CONFIGURATION, network);
1294        intent.putExtra(WifiManager.EXTRA_CHANGE_REASON, reason);
1295        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1296    }
1297
1298    /**
1299     * Should be called when multiple network configuration changes are made.
1300     */
1301    private void sendConfiguredNetworksChangedBroadcast() {
1302        Intent intent = new Intent(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
1303        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1304        intent.putExtra(WifiManager.EXTRA_MULTIPLE_NETWORKS_CHANGED, true);
1305        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1306    }
1307
1308    void loadConfiguredNetworks() {
1309        String listStr = mWifiNative.listNetworks();
1310        mLastPriority = 0;
1311
1312        mConfiguredNetworks.clear();
1313        mNetworkIds.clear();
1314
1315        if (listStr == null)
1316            return;
1317
1318        String[] lines = listStr.split("\n");
1319
1320        if (showNetworks) {
1321            localLog("WifiConfigStore: loadConfiguredNetworks:  ");
1322            for (String net : lines) {
1323                localLog(net);
1324            }
1325        }
1326
1327        // Skip the first line, which is a header
1328        for (int i = 1; i < lines.length; i++) {
1329            String[] result = lines[i].split("\t");
1330            // network-id | ssid | bssid | flags
1331            WifiConfiguration config = new WifiConfiguration();
1332            try {
1333                config.networkId = Integer.parseInt(result[0]);
1334            } catch(NumberFormatException e) {
1335                loge("Failed to read network-id '" + result[0] + "'");
1336                continue;
1337            }
1338            if (result.length > 3) {
1339                if (result[3].indexOf("[CURRENT]") != -1)
1340                    config.status = WifiConfiguration.Status.CURRENT;
1341                else if (result[3].indexOf("[DISABLED]") != -1)
1342                    config.status = WifiConfiguration.Status.DISABLED;
1343                else
1344                    config.status = WifiConfiguration.Status.ENABLED;
1345            } else {
1346                config.status = WifiConfiguration.Status.ENABLED;
1347            }
1348            readNetworkVariables(config);
1349            if (config.priority > mLastPriority) {
1350                mLastPriority = config.priority;
1351            }
1352
1353            config.setIpAssignment(IpAssignment.DHCP);
1354            config.setProxySettings(ProxySettings.NONE);
1355
1356            if (mNetworkIds.containsKey(configKey(config))) {
1357                // That SSID is already known, just ignore this duplicate entry
1358                if (showNetworks) localLog("discarded duplicate network ", config.networkId);
1359            } else if(config.isValid()){
1360                mConfiguredNetworks.put(config.networkId, config);
1361                mNetworkIds.put(configKey(config), config.networkId);
1362                if (showNetworks) localLog("loaded configured network", config.networkId);
1363            } else {
1364                if (showNetworks) log("Ignoring loaded configured for network " + config.networkId
1365                    + " because config are not valid");
1366            }
1367        }
1368
1369        readIpAndProxyConfigurations();
1370        readNetworkHistory();
1371        readAutoJoinConfig();
1372
1373        sendConfiguredNetworksChangedBroadcast();
1374
1375        if (showNetworks) localLog("loadConfiguredNetworks loaded " + mNetworkIds.size() + " networks");
1376
1377        if (mNetworkIds.size() == 0) {
1378            // no networks? Lets log if the wpa_supplicant.conf file contents
1379            BufferedReader reader = null;
1380            try {
1381                reader = new BufferedReader(new FileReader(SUPPLICANT_CONFIG_FILE));
1382                if (DBG) {
1383                    localLog("--- Begin wpa_supplicant.conf Contents ---", true);
1384                    for (String line = reader.readLine(); line != null; line = reader.readLine()) {
1385                        localLog(line, true);
1386                    }
1387                    localLog("--- End wpa_supplicant.conf Contents ---", true);
1388                }
1389            } catch (FileNotFoundException e) {
1390                localLog("Could not open " + SUPPLICANT_CONFIG_FILE + ", " + e, true);
1391            } catch (IOException e) {
1392                localLog("Could not read " + SUPPLICANT_CONFIG_FILE + ", " + e, true);
1393            } finally {
1394                try {
1395                    if (reader != null) {
1396                        reader.close();
1397                    }
1398                } catch (IOException e) {
1399                    // Just ignore the fact that we couldn't close
1400                }
1401            }
1402        }
1403    }
1404
1405    private Map<String, String> readNetworkVariablesFromSupplicantFile(String key) {
1406        Map<String, String> result = new HashMap<>();
1407        BufferedReader reader = null;
1408        if (VDBG) loge("readNetworkVariablesFromSupplicantFile key=" + key);
1409
1410        try {
1411            reader = new BufferedReader(new FileReader(SUPPLICANT_CONFIG_FILE));
1412            boolean found = false;
1413            String networkSsid = null;
1414            String value = null;
1415
1416            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
1417
1418                if (line.matches("[ \\t]*network=\\{")) {
1419                    found = true;
1420                    networkSsid = null;
1421                    value = null;
1422                } else if (line.matches("[ \\t]*\\}")) {
1423                    found = false;
1424                    networkSsid = null;
1425                    value = null;
1426                }
1427
1428                if (found) {
1429                    String trimmedLine = line.trim();
1430                    if (trimmedLine.startsWith("ssid=")) {
1431                        networkSsid = trimmedLine.substring(5);
1432                    } else if (trimmedLine.startsWith(key + "=")) {
1433                        value = trimmedLine.substring(key.length() + 1);
1434                    }
1435
1436                    if (networkSsid != null && value != null) {
1437                        result.put(networkSsid, value);
1438                    }
1439                }
1440            }
1441        } catch (FileNotFoundException e) {
1442            if (VDBG) loge("Could not open " + SUPPLICANT_CONFIG_FILE + ", " + e);
1443        } catch (IOException e) {
1444            if (VDBG) loge("Could not read " + SUPPLICANT_CONFIG_FILE + ", " + e);
1445        } finally {
1446            try {
1447                if (reader != null) {
1448                    reader.close();
1449                }
1450            } catch (IOException e) {
1451                // Just ignore the fact that we couldn't close
1452            }
1453        }
1454
1455        return result;
1456    }
1457
1458    private String readNetworkVariableFromSupplicantFile(String ssid, String key) {
1459        Map<String, String> data = readNetworkVariablesFromSupplicantFile(key);
1460        if (VDBG) loge("readNetworkVariableFromSupplicantFile ssid=[" + ssid + "] key=" + key);
1461        return data.get(ssid);
1462    }
1463
1464    /* Mark all networks except specified netId as disabled */
1465    private void markAllNetworksDisabledExcept(int netId) {
1466        for(WifiConfiguration config : mConfiguredNetworks.values()) {
1467            if(config != null && config.networkId != netId) {
1468                if (config.status != Status.DISABLED) {
1469                    config.status = Status.DISABLED;
1470                    config.disableReason = WifiConfiguration.DISABLED_UNKNOWN_REASON;
1471                }
1472            }
1473        }
1474    }
1475
1476    private void markAllNetworksDisabled() {
1477        markAllNetworksDisabledExcept(INVALID_NETWORK_ID);
1478    }
1479
1480    boolean needsUnlockedKeyStore() {
1481
1482        // Any network using certificates to authenticate access requires
1483        // unlocked key store; unless the certificates can be stored with
1484        // hardware encryption
1485
1486        for(WifiConfiguration config : mConfiguredNetworks.values()) {
1487
1488            if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP)
1489                    && config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1490
1491                if (needsSoftwareBackedKeyStore(config.enterpriseConfig)) {
1492                    return true;
1493                }
1494            }
1495        }
1496
1497        return false;
1498    }
1499
1500    public void writeKnownNetworkHistory() {
1501        boolean needUpdate = false;
1502
1503        /* Make a copy */
1504        final List<WifiConfiguration> networks = new ArrayList<WifiConfiguration>();
1505        for (WifiConfiguration config : mConfiguredNetworks.values()) {
1506            networks.add(new WifiConfiguration(config));
1507            if (config.dirty == true) {
1508                config.dirty = false;
1509                needUpdate = true;
1510            }
1511        }
1512        if (VDBG) {
1513            loge(" writeKnownNetworkHistory() num networks:" +
1514                    mConfiguredNetworks.size() + " needWrite=" + needUpdate);
1515        }
1516        if (needUpdate == false) {
1517            return;
1518        }
1519        mWriter.write(networkHistoryConfigFile, new DelayedDiskWrite.Writer() {
1520            public void onWriteCalled(DataOutputStream out) throws IOException {
1521                for (WifiConfiguration config : networks) {
1522                    //loge("onWriteCalled write SSID: " + config.SSID);
1523                   /* if (config.getLinkProperties() != null)
1524                        loge(" lp " + config.getLinkProperties().toString());
1525                    else
1526                        loge("attempt config w/o lp");
1527                    */
1528
1529                    if (VDBG) {
1530                        int num = 0;
1531                        int numlink = 0;
1532                        if (config.connectChoices != null) {
1533                            num = config.connectChoices.size();
1534                        }
1535                        if (config.linkedConfigurations != null) {
1536                            numlink = config.linkedConfigurations.size();
1537                        }
1538                        loge("saving network history: " + config.configKey()  + " gw: " +
1539                                config.defaultGwMacAddress + " autojoin-status: " +
1540                                config.autoJoinStatus + " ephemeral=" + config.ephemeral
1541                                + " choices:" + Integer.toString(num)
1542                                + " link:" + Integer.toString(numlink)
1543                                + " status:" + Integer.toString(config.status)
1544                                + " nid:" + Integer.toString(config.networkId));
1545                    }
1546
1547                    if (config.isValid() == false)
1548                        continue;
1549
1550                    if (config.SSID == null) {
1551                        if (VDBG) {
1552                            loge("writeKnownNetworkHistory trying to write config with null SSID");
1553                        }
1554                        continue;
1555                    }
1556                    if (VDBG) {
1557                        loge("writeKnownNetworkHistory write config " + config.configKey());
1558                    }
1559                    out.writeUTF(CONFIG_KEY + config.configKey() + SEPARATOR_KEY);
1560
1561                    out.writeUTF(SSID_KEY + config.SSID + SEPARATOR_KEY);
1562                    out.writeUTF(FQDN_KEY + config.FQDN + SEPARATOR_KEY);
1563
1564                    out.writeUTF(PRIORITY_KEY + Integer.toString(config.priority) + SEPARATOR_KEY);
1565                    out.writeUTF(STATUS_KEY + Integer.toString(config.autoJoinStatus)
1566                            + SEPARATOR_KEY);
1567                    out.writeUTF(SUPPLICANT_STATUS_KEY + Integer.toString(config.status)
1568                            + SEPARATOR_KEY);
1569                    out.writeUTF(SUPPLICANT_DISABLE_REASON_KEY
1570                            + Integer.toString(config.disableReason)
1571                            + SEPARATOR_KEY);
1572                    out.writeUTF(NETWORK_ID_KEY + Integer.toString(config.networkId)
1573                            + SEPARATOR_KEY);
1574                    out.writeUTF(SELF_ADDED_KEY + Boolean.toString(config.selfAdded)
1575                            + SEPARATOR_KEY);
1576                    out.writeUTF(DID_SELF_ADD_KEY + Boolean.toString(config.didSelfAdd)
1577                            + SEPARATOR_KEY);
1578                    out.writeUTF(NO_INTERNET_ACCESS_KEY
1579                            + Boolean.toString(config.noInternetAccess)
1580                            + SEPARATOR_KEY);
1581                    out.writeUTF(EPHEMERAL_KEY
1582                            + Boolean.toString(config.ephemeral)
1583                            + SEPARATOR_KEY);
1584                    if (config.peerWifiConfiguration != null) {
1585                        out.writeUTF(PEER_CONFIGURATION_KEY + config.peerWifiConfiguration
1586                                + SEPARATOR_KEY);
1587                    }
1588                    out.writeUTF(NUM_CONNECTION_FAILURES_KEY
1589                            + Integer.toString(config.numConnectionFailures)
1590                            + SEPARATOR_KEY);
1591                    out.writeUTF(NUM_AUTH_FAILURES_KEY
1592                            + Integer.toString(config.numAuthFailures)
1593                            + SEPARATOR_KEY);
1594                    out.writeUTF(NUM_IP_CONFIG_FAILURES_KEY
1595                            + Integer.toString(config.numIpConfigFailures)
1596                            + SEPARATOR_KEY);
1597                    out.writeUTF(SCORER_OVERRIDE_KEY + Integer.toString(config.numScorerOverride)
1598                            + SEPARATOR_KEY);
1599                    out.writeUTF(SCORER_OVERRIDE_AND_SWITCH_KEY
1600                            + Integer.toString(config.numScorerOverrideAndSwitchedNetwork)
1601                            + SEPARATOR_KEY);
1602                    out.writeUTF(NUM_ASSOCIATION_KEY
1603                            + Integer.toString(config.numAssociation)
1604                            + SEPARATOR_KEY);
1605                    //out.writeUTF(BLACKLIST_MILLI_KEY + Long.toString(config.blackListTimestamp)
1606                    //        + SEPARATOR_KEY);
1607                    out.writeUTF(CREATOR_UID_KEY + Integer.toString(config.creatorUid)
1608                            + SEPARATOR_KEY);
1609                    out.writeUTF(CONNECT_UID_KEY + Integer.toString(config.lastConnectUid)
1610                            + SEPARATOR_KEY);
1611                    out.writeUTF(UPDATE_UID_KEY + Integer.toString(config.lastUpdateUid)
1612                            + SEPARATOR_KEY);
1613                    String allowedKeyManagementString =
1614                            makeString(config.allowedKeyManagement,
1615                                    WifiConfiguration.KeyMgmt.strings);
1616                    out.writeUTF(AUTH_KEY + allowedKeyManagementString + SEPARATOR_KEY);
1617
1618                    if (config.connectChoices != null) {
1619                        for (String key : config.connectChoices.keySet()) {
1620                            Integer choice = config.connectChoices.get(key);
1621                            out.writeUTF(CHOICE_KEY + key + "="
1622                                    + choice.toString() + SEPARATOR_KEY);
1623                        }
1624                    }
1625                    if (config.linkedConfigurations != null) {
1626                        loge("writeKnownNetworkHistory write linked "
1627                                + config.linkedConfigurations.size());
1628
1629                        for (String key : config.linkedConfigurations.keySet()) {
1630                            out.writeUTF(LINK_KEY + key + SEPARATOR_KEY);
1631                        }
1632                    }
1633
1634                    String macAddress = config.defaultGwMacAddress;
1635                    if (macAddress != null) {
1636                        out.writeUTF(DEFAULT_GW_KEY + macAddress + SEPARATOR_KEY);
1637                    }
1638
1639                    if (config.scanResultCache != null) {
1640                        for (ScanResult result : config.scanResultCache.values()) {
1641                            out.writeUTF(BSSID_KEY + result.BSSID + SEPARATOR_KEY);
1642
1643                            out.writeUTF(FREQ_KEY + Integer.toString(result.frequency)
1644                                    + SEPARATOR_KEY);
1645
1646                            out.writeUTF(RSSI_KEY + Integer.toString(result.level)
1647                                    + SEPARATOR_KEY);
1648
1649                            out.writeUTF(BSSID_STATUS_KEY
1650                                    + Integer.toString(result.autoJoinStatus)
1651                                    + SEPARATOR_KEY);
1652
1653                            //if (result.seen != 0) {
1654                            //    out.writeUTF(MILLI_KEY + Long.toString(result.seen)
1655                            //            + SEPARATOR_KEY);
1656                            //}
1657                            out.writeUTF(BSSID_KEY_END + SEPARATOR_KEY);
1658                        }
1659                    }
1660                    if (config.lastFailure != null) {
1661                        out.writeUTF(FAILURE_KEY + config.lastFailure + SEPARATOR_KEY);
1662                    }
1663                    out.writeUTF(SEPARATOR_KEY);
1664                    // Add extra blank lines for clarity
1665                    out.writeUTF(SEPARATOR_KEY);
1666                    out.writeUTF(SEPARATOR_KEY);
1667                }
1668            }
1669
1670        });
1671    }
1672
1673    public void setLastSelectedConfiguration(int netId) {
1674        if (DBG) {
1675            loge("setLastSelectedConfiguration " + Integer.toString(netId));
1676        }
1677        if (netId == WifiConfiguration.INVALID_NETWORK_ID) {
1678            lastSelectedConfiguration = null;
1679        } else {
1680            WifiConfiguration selected = getWifiConfiguration(netId);
1681            if (selected == null) {
1682                lastSelectedConfiguration = null;
1683            } else {
1684                lastSelectedConfiguration = selected.configKey();
1685                selected.numConnectionFailures = 0;
1686                selected.numIpConfigFailures = 0;
1687                selected.numAuthFailures = 0;
1688                if (VDBG) {
1689                    loge("setLastSelectedConfiguration now: " + lastSelectedConfiguration);
1690                }
1691            }
1692        }
1693    }
1694
1695    public String getLastSelectedConfiguration() {
1696        return lastSelectedConfiguration;
1697    }
1698
1699    public boolean isLastSelectedConfiguration(WifiConfiguration config) {
1700        return (lastSelectedConfiguration != null
1701                && config != null
1702                && lastSelectedConfiguration.equals(config.configKey()));
1703    }
1704
1705    private void readNetworkHistory() {
1706        if (showNetworks) {
1707            localLog("readNetworkHistory() path:" + networkHistoryConfigFile);
1708        }
1709        DataInputStream in = null;
1710        try {
1711            in = new DataInputStream(new BufferedInputStream(new FileInputStream(
1712                    networkHistoryConfigFile)));
1713            WifiConfiguration config = null;
1714            while (true) {
1715                int id = -1;
1716                String key = in.readUTF();
1717                String bssid = null;
1718                String ssid = null;
1719
1720                int freq = 0;
1721                int status = 0;
1722                long seen = 0;
1723                int rssi = WifiConfiguration.INVALID_RSSI;
1724                String caps = null;
1725                if (key.startsWith(CONFIG_KEY)) {
1726
1727                    if (config != null) {
1728                        config = null;
1729                    }
1730                    String configKey = key.replace(CONFIG_KEY, "");
1731                    configKey = configKey.replace(SEPARATOR_KEY, "");
1732                    // get the networkId for that config Key
1733                    Integer n = mNetworkIds.get(configKey.hashCode());
1734                    // skip reading that configuration data
1735                    // since we don't have a corresponding network ID
1736                    if (n == null) {
1737                        localLog("readNetworkHistory didnt find netid for hash="
1738                                + Integer.toString(configKey.hashCode())
1739                                + " key: " + configKey);
1740                        continue;
1741                    }
1742                    config = mConfiguredNetworks.get(n);
1743                    if (config == null) {
1744                        localLog("readNetworkHistory didnt find config for netid="
1745                                + n.toString()
1746                                + " key: " + configKey);
1747                    }
1748                    status = 0;
1749                    ssid = null;
1750                    bssid = null;
1751                    freq = 0;
1752                    seen = 0;
1753                    rssi = WifiConfiguration.INVALID_RSSI;
1754                    caps = null;
1755
1756                } else if (config != null) {
1757                    if (key.startsWith(SSID_KEY)) {
1758                        ssid = key.replace(SSID_KEY, "");
1759                        ssid = ssid.replace(SEPARATOR_KEY, "");
1760                        if (config.SSID != null && !config.SSID.equals(ssid)) {
1761                            loge("Error parsing network history file, mismatched SSIDs");
1762                            config = null; //error
1763                            ssid = null;
1764                        } else {
1765                            config.SSID = ssid;
1766                        }
1767                    }
1768
1769                    if (key.startsWith(FQDN_KEY)) {
1770                        String fqdn = key.replace(FQDN_KEY, "");
1771                        fqdn = fqdn.replace(SEPARATOR_KEY, "");
1772                        config.FQDN = fqdn;
1773                    }
1774
1775                    if (key.startsWith(DEFAULT_GW_KEY)) {
1776                        String gateway = key.replace(DEFAULT_GW_KEY, "");
1777                        gateway = gateway.replace(SEPARATOR_KEY, "");
1778                        config.defaultGwMacAddress = gateway;
1779                    }
1780
1781                    if (key.startsWith(STATUS_KEY)) {
1782                        String st = key.replace(STATUS_KEY, "");
1783                        st = st.replace(SEPARATOR_KEY, "");
1784                        config.autoJoinStatus = Integer.parseInt(st);
1785                    }
1786
1787                    if (key.startsWith(SUPPLICANT_DISABLE_REASON_KEY)) {
1788                        String reason = key.replace(SUPPLICANT_DISABLE_REASON_KEY, "");
1789                        reason = reason.replace(SEPARATOR_KEY, "");
1790                        config.disableReason = Integer.parseInt(reason);
1791                    }
1792
1793                    if (key.startsWith(SELF_ADDED_KEY)) {
1794                        String selfAdded = key.replace(SELF_ADDED_KEY, "");
1795                        selfAdded = selfAdded.replace(SEPARATOR_KEY, "");
1796                        config.selfAdded = Boolean.parseBoolean(selfAdded);
1797                    }
1798
1799                    if (key.startsWith(DID_SELF_ADD_KEY)) {
1800                        String didSelfAdd = key.replace(DID_SELF_ADD_KEY, "");
1801                        didSelfAdd = didSelfAdd.replace(SEPARATOR_KEY, "");
1802                        config.didSelfAdd = Boolean.parseBoolean(didSelfAdd);
1803                    }
1804
1805                    if (key.startsWith(NO_INTERNET_ACCESS_KEY)) {
1806                        String access = key.replace(NO_INTERNET_ACCESS_KEY, "");
1807                        access = access.replace(SEPARATOR_KEY, "");
1808                        config.noInternetAccess = Boolean.parseBoolean(access);
1809                    }
1810
1811                    if (key.startsWith(EPHEMERAL_KEY)) {
1812                        String access = key.replace(EPHEMERAL_KEY, "");
1813                        access = access.replace(SEPARATOR_KEY, "");
1814                        config.ephemeral = Boolean.parseBoolean(access);
1815                    }
1816
1817                    if (key.startsWith(CREATOR_UID_KEY)) {
1818                        String uid = key.replace(CREATOR_UID_KEY, "");
1819                        uid = uid.replace(SEPARATOR_KEY, "");
1820                        config.creatorUid = Integer.parseInt(uid);
1821                    }
1822
1823                    if (key.startsWith(BLACKLIST_MILLI_KEY)) {
1824                        String milli = key.replace(BLACKLIST_MILLI_KEY, "");
1825                        milli = milli.replace(SEPARATOR_KEY, "");
1826                        config.blackListTimestamp = Long.parseLong(milli);
1827                    }
1828
1829                    if (key.startsWith(NUM_CONNECTION_FAILURES_KEY)) {
1830                        String num = key.replace(NUM_CONNECTION_FAILURES_KEY, "");
1831                        num = num.replace(SEPARATOR_KEY, "");
1832                        config.numConnectionFailures = Integer.parseInt(num);
1833                    }
1834
1835                    if (key.startsWith(NUM_IP_CONFIG_FAILURES_KEY)) {
1836                        String num = key.replace(NUM_IP_CONFIG_FAILURES_KEY, "");
1837                        num = num.replace(SEPARATOR_KEY, "");
1838                        config.numIpConfigFailures = Integer.parseInt(num);
1839                    }
1840
1841                    if (key.startsWith(NUM_AUTH_FAILURES_KEY)) {
1842                        String num = key.replace(NUM_AUTH_FAILURES_KEY, "");
1843                        num = num.replace(SEPARATOR_KEY, "");
1844                        config.numIpConfigFailures = Integer.parseInt(num);
1845                    }
1846
1847                    if (key.startsWith(SCORER_OVERRIDE_KEY)) {
1848                        String num = key.replace(SCORER_OVERRIDE_KEY, "");
1849                        num = num.replace(SEPARATOR_KEY, "");
1850                        config.numScorerOverride = Integer.parseInt(num);
1851                    }
1852
1853                    if (key.startsWith(SCORER_OVERRIDE_AND_SWITCH_KEY)) {
1854                        String num = key.replace(SCORER_OVERRIDE_AND_SWITCH_KEY, "");
1855                        num = num.replace(SEPARATOR_KEY, "");
1856                        config.numScorerOverrideAndSwitchedNetwork = Integer.parseInt(num);
1857                    }
1858
1859                    if (key.startsWith(NUM_ASSOCIATION_KEY)) {
1860                        String num = key.replace(NUM_ASSOCIATION_KEY, "");
1861                        num = num.replace(SEPARATOR_KEY, "");
1862                        config.numAssociation = Integer.parseInt(num);
1863                    }
1864
1865                    if (key.startsWith(CONNECT_UID_KEY)) {
1866                        String uid = key.replace(CONNECT_UID_KEY, "");
1867                        uid = uid.replace(SEPARATOR_KEY, "");
1868                        config.lastConnectUid = Integer.parseInt(uid);
1869                    }
1870
1871                    if (key.startsWith(UPDATE_UID_KEY)) {
1872                        String uid = key.replace(UPDATE_UID_KEY, "");
1873                        uid = uid.replace(SEPARATOR_KEY, "");
1874                        config.lastUpdateUid = Integer.parseInt(uid);
1875                    }
1876
1877                    if (key.startsWith(FAILURE_KEY)) {
1878                        config.lastFailure = key.replace(FAILURE_KEY, "");
1879                        config.lastFailure = config.lastFailure.replace(SEPARATOR_KEY, "");
1880                    }
1881
1882                    if (key.startsWith(PEER_CONFIGURATION_KEY)) {
1883                        config.peerWifiConfiguration = key.replace(PEER_CONFIGURATION_KEY, "");
1884                        config.peerWifiConfiguration =
1885                                config.peerWifiConfiguration.replace(SEPARATOR_KEY, "");
1886                    }
1887
1888                    if (key.startsWith(CHOICE_KEY)) {
1889                        String choiceStr = key.replace(CHOICE_KEY, "");
1890                        choiceStr = choiceStr.replace(SEPARATOR_KEY, "");
1891                        String configKey = "";
1892                        int choice = 0;
1893                        Matcher match = mConnectChoice.matcher(choiceStr);
1894                        if (!match.find()) {
1895                            if (DBG) Log.d(TAG, "WifiConfigStore: connectChoice: " +
1896                                    " Couldnt match pattern : " + choiceStr);
1897                        } else {
1898                            configKey = match.group(1);
1899                            try {
1900                                choice = Integer.parseInt(match.group(2));
1901                            } catch (NumberFormatException e) {
1902                                choice = 0;
1903                            }
1904                            if (choice > 0) {
1905                                if (config.connectChoices == null) {
1906                                    config.connectChoices = new HashMap<String, Integer>();
1907                                }
1908                                config.connectChoices.put(configKey, choice);
1909                            }
1910                        }
1911                    }
1912
1913                    if (key.startsWith(LINK_KEY)) {
1914                        String configKey = key.replace(LINK_KEY, "");
1915                        configKey = configKey.replace(SEPARATOR_KEY, "");
1916                        if (config.linkedConfigurations == null) {
1917                            config.linkedConfigurations = new HashMap<String, Integer>();
1918                        }
1919                        if (config.linkedConfigurations != null) {
1920                            config.linkedConfigurations.put(configKey, -1);
1921                        }
1922                    }
1923
1924                    if (key.startsWith(BSSID_KEY)) {
1925                        if (key.startsWith(BSSID_KEY)) {
1926                            bssid = key.replace(BSSID_KEY, "");
1927                            bssid = bssid.replace(SEPARATOR_KEY, "");
1928                            freq = 0;
1929                            seen = 0;
1930                            rssi = WifiConfiguration.INVALID_RSSI;
1931                            caps = "";
1932                            status = 0;
1933                        }
1934
1935                        if (key.startsWith(RSSI_KEY)) {
1936                            String lvl = key.replace(RSSI_KEY, "");
1937                            lvl = lvl.replace(SEPARATOR_KEY, "");
1938                            rssi = Integer.parseInt(lvl);
1939                        }
1940
1941                        if (key.startsWith(BSSID_STATUS_KEY)) {
1942                            String st = key.replace(BSSID_STATUS_KEY, "");
1943                            st = st.replace(SEPARATOR_KEY, "");
1944                            status = Integer.parseInt(st);
1945                        }
1946
1947                        if (key.startsWith(FREQ_KEY)) {
1948                            String channel = key.replace(FREQ_KEY, "");
1949                            channel = channel.replace(SEPARATOR_KEY, "");
1950                            freq = Integer.parseInt(channel);
1951                        }
1952
1953                        if (key.startsWith(DATE_KEY)) {
1954                        /*
1955                         * when reading the configuration from file we don't update the date
1956                         * so as to avoid reading back stale or non-sensical data that would
1957                         * depend on network time.
1958                         * The date of a WifiConfiguration should only come from actual scan result.
1959                         *
1960                        String s = key.replace(FREQ_KEY, "");
1961                        seen = Integer.getInteger(s);
1962                        */
1963                        }
1964
1965                        if (key.startsWith(BSSID_KEY_END)) {
1966
1967                            if ((bssid != null) && (ssid != null)) {
1968
1969                                if (config.scanResultCache == null) {
1970                                    config.scanResultCache = new HashMap<String, ScanResult>();
1971                                }
1972                                WifiSsid wssid = WifiSsid.createFromAsciiEncoded(ssid);
1973                                ScanResult result = new ScanResult(wssid, bssid,
1974                                        caps, rssi, freq, (long) 0);
1975                                result.seen = seen;
1976                                config.scanResultCache.put(bssid, result);
1977                                result.autoJoinStatus = status;
1978                            }
1979                        }
1980                    }
1981                }
1982            }
1983        } catch (EOFException ignore) {
1984            if (in != null) {
1985                try {
1986                    in.close();
1987                } catch (Exception e) {
1988                    loge("readNetworkHistory: Error reading file" + e);
1989                }
1990            }
1991        } catch (IOException e) {
1992            loge("readNetworkHistory: No config file, revert to default" + e);
1993        }
1994
1995        if(in!=null) {
1996            try {
1997                in.close();
1998            } catch (Exception e) {
1999                loge("readNetworkHistory: Error closing file" + e);
2000            }
2001        }
2002    }
2003
2004    private void readAutoJoinConfig() {
2005        BufferedReader reader = null;
2006        try {
2007
2008            reader = new BufferedReader(new FileReader(autoJoinConfigFile));
2009
2010            for (String key = reader.readLine(); key != null; key = reader.readLine()) {
2011                if (key != null) {
2012                    Log.d(TAG, "readAutoJoinConfig line: " + key);
2013                }
2014                if (key.startsWith(ENABLE_AUTO_JOIN_WHILE_ASSOCIATED_KEY)) {
2015                    String st = key.replace(ENABLE_AUTO_JOIN_WHILE_ASSOCIATED_KEY, "");
2016                    st = st.replace(SEPARATOR_KEY, "");
2017                    try {
2018                        enableAutoJoinWhenAssociated = Integer.parseInt(st) != 0;
2019                        Log.d(TAG,"readAutoJoinConfig: enabled = " + enableAutoJoinWhenAssociated);
2020                    } catch (NumberFormatException e) {
2021                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2022                    }
2023                }
2024
2025                if (key.startsWith(ENABLE_FULL_BAND_SCAN_WHEN_ASSOCIATED_KEY)) {
2026                    String st = key.replace(ENABLE_FULL_BAND_SCAN_WHEN_ASSOCIATED_KEY, "");
2027                    st = st.replace(SEPARATOR_KEY, "");
2028                    try {
2029                        enableFullBandScanWhenAssociated = Integer.parseInt(st) != 0;
2030                        Log.d(TAG,"readAutoJoinConfig: enableFullBandScanWhenAssociated = "
2031                                + enableFullBandScanWhenAssociated);
2032                    } catch (NumberFormatException e) {
2033                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2034                    }
2035                }
2036
2037                if (key.startsWith(ENABLE_AUTO_JOIN_SCAN_WHILE_ASSOCIATED_KEY)) {
2038                    String st = key.replace(ENABLE_AUTO_JOIN_SCAN_WHILE_ASSOCIATED_KEY, "");
2039                    st = st.replace(SEPARATOR_KEY, "");
2040                    try {
2041                        enableAutoJoinScanWhenAssociated = Integer.parseInt(st) != 0;
2042                        Log.d(TAG,"readAutoJoinConfig: enabled = "
2043                                + enableAutoJoinScanWhenAssociated);
2044                    } catch (NumberFormatException e) {
2045                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2046                    }
2047                }
2048
2049                if (key.startsWith(ENABLE_CHIP_WAKE_UP_WHILE_ASSOCIATED_KEY)) {
2050                    String st = key.replace(ENABLE_CHIP_WAKE_UP_WHILE_ASSOCIATED_KEY, "");
2051                    st = st.replace(SEPARATOR_KEY, "");
2052                    try {
2053                        enableChipWakeUpWhenAssociated = Integer.parseInt(st) != 0;
2054                        Log.d(TAG,"readAutoJoinConfig: enabled = "
2055                                + enableChipWakeUpWhenAssociated);
2056                    } catch (NumberFormatException e) {
2057                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2058                    }
2059                }
2060
2061                if (key.startsWith(ENABLE_RSSI_POLL_WHILE_ASSOCIATED_KEY)) {
2062                    String st = key.replace(ENABLE_RSSI_POLL_WHILE_ASSOCIATED_KEY, "");
2063                    st = st.replace(SEPARATOR_KEY, "");
2064                    try {
2065                        enableRssiPollWhenAssociated = Integer.parseInt(st) != 0;
2066                        Log.d(TAG,"readAutoJoinConfig: enabled = "
2067                                + enableRssiPollWhenAssociated);
2068                    } catch (NumberFormatException e) {
2069                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2070                    }
2071                }
2072
2073                if (key.startsWith(THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_5G_KEY)) {
2074                    String st =
2075                            key.replace(THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_5G_KEY, "");
2076                    st = st.replace(SEPARATOR_KEY, "");
2077                    try {
2078                        thresholdInitialAutoJoinAttemptMin5RSSI = Integer.parseInt(st);
2079                        Log.d(TAG,"readAutoJoinConfig: thresholdInitialAutoJoinAttemptMin5RSSI = "
2080                                + Integer.toString(thresholdInitialAutoJoinAttemptMin5RSSI));
2081                    } catch (NumberFormatException e) {
2082                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2083                    }
2084                }
2085
2086                if (key.startsWith(THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_24G_KEY)) {
2087                    String st =
2088                            key.replace(THRESHOLD_INITIAL_AUTO_JOIN_ATTEMPT_RSSI_MIN_24G_KEY, "");
2089                    st = st.replace(SEPARATOR_KEY, "");
2090                    try {
2091                        thresholdInitialAutoJoinAttemptMin24RSSI = Integer.parseInt(st);
2092                        Log.d(TAG,"readAutoJoinConfig: thresholdInitialAutoJoinAttemptMin24RSSI = "
2093                                + Integer.toString(thresholdInitialAutoJoinAttemptMin24RSSI));
2094                    } catch (NumberFormatException e) {
2095                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2096                    }
2097                }
2098
2099                if (key.startsWith(THRESHOLD_UNBLACKLIST_HARD_5G_KEY)) {
2100                    String st = key.replace(THRESHOLD_UNBLACKLIST_HARD_5G_KEY, "");
2101                    st = st.replace(SEPARATOR_KEY, "");
2102                    try {
2103                        thresholdUnblacklistThreshold5Hard = Integer.parseInt(st);
2104                        Log.d(TAG,"readAutoJoinConfig: thresholdUnblacklistThreshold5Hard = "
2105                            + Integer.toString(thresholdUnblacklistThreshold5Hard));
2106                    } catch (NumberFormatException e) {
2107                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2108                    }
2109                }
2110                if (key.startsWith(THRESHOLD_UNBLACKLIST_SOFT_5G_KEY)) {
2111                    String st = key.replace(THRESHOLD_UNBLACKLIST_SOFT_5G_KEY, "");
2112                    st = st.replace(SEPARATOR_KEY, "");
2113                    try {
2114                        thresholdUnblacklistThreshold5Soft = Integer.parseInt(st);
2115                        Log.d(TAG,"readAutoJoinConfig: thresholdUnblacklistThreshold5Soft = "
2116                            + Integer.toString(thresholdUnblacklistThreshold5Soft));
2117                    } catch (NumberFormatException e) {
2118                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2119                    }
2120                }
2121                if (key.startsWith(THRESHOLD_UNBLACKLIST_HARD_24G_KEY)) {
2122                    String st = key.replace(THRESHOLD_UNBLACKLIST_HARD_24G_KEY, "");
2123                    st = st.replace(SEPARATOR_KEY, "");
2124                    try {
2125                        thresholdUnblacklistThreshold24Hard = Integer.parseInt(st);
2126                        Log.d(TAG,"readAutoJoinConfig: thresholdUnblacklistThreshold24Hard = "
2127                            + Integer.toString(thresholdUnblacklistThreshold24Hard));
2128                    } catch (NumberFormatException e) {
2129                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2130                    }
2131                }
2132                if (key.startsWith(THRESHOLD_UNBLACKLIST_SOFT_24G_KEY)) {
2133                    String st = key.replace(THRESHOLD_UNBLACKLIST_SOFT_24G_KEY, "");
2134                    st = st.replace(SEPARATOR_KEY, "");
2135                    try {
2136                        thresholdUnblacklistThreshold24Soft = Integer.parseInt(st);
2137                        Log.d(TAG,"readAutoJoinConfig: thresholdUnblacklistThreshold24Soft = "
2138                            + Integer.toString(thresholdUnblacklistThreshold24Soft));
2139                    } catch (NumberFormatException e) {
2140                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2141                    }
2142                }
2143
2144                if (key.startsWith(THRESHOLD_GOOD_RSSI_5_KEY)) {
2145                    String st = key.replace(THRESHOLD_GOOD_RSSI_5_KEY, "");
2146                    st = st.replace(SEPARATOR_KEY, "");
2147                    try {
2148                        thresholdGoodRssi5 = Integer.parseInt(st);
2149                        Log.d(TAG,"readAutoJoinConfig: thresholdGoodRssi5 = "
2150                            + Integer.toString(thresholdGoodRssi5));
2151                    } catch (NumberFormatException e) {
2152                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2153                    }
2154                }
2155                if (key.startsWith(THRESHOLD_LOW_RSSI_5_KEY)) {
2156                    String st = key.replace(THRESHOLD_LOW_RSSI_5_KEY, "");
2157                    st = st.replace(SEPARATOR_KEY, "");
2158                    try {
2159                        thresholdLowRssi5 = Integer.parseInt(st);
2160                        Log.d(TAG,"readAutoJoinConfig: thresholdLowRssi5 = "
2161                            + Integer.toString(thresholdLowRssi5));
2162                    } catch (NumberFormatException e) {
2163                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2164                    }
2165                }
2166                if (key.startsWith(THRESHOLD_BAD_RSSI_5_KEY)) {
2167                    String st = key.replace(THRESHOLD_BAD_RSSI_5_KEY, "");
2168                    st = st.replace(SEPARATOR_KEY, "");
2169                    try {
2170                        thresholdBadRssi5 = Integer.parseInt(st);
2171                        Log.d(TAG,"readAutoJoinConfig: thresholdBadRssi5 = "
2172                            + Integer.toString(thresholdBadRssi5));
2173                    } catch (NumberFormatException e) {
2174                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2175                    }
2176                }
2177
2178                if (key.startsWith(THRESHOLD_GOOD_RSSI_24_KEY)) {
2179                    String st = key.replace(THRESHOLD_GOOD_RSSI_24_KEY, "");
2180                    st = st.replace(SEPARATOR_KEY, "");
2181                    try {
2182                        thresholdGoodRssi24 = Integer.parseInt(st);
2183                        Log.d(TAG,"readAutoJoinConfig: thresholdGoodRssi24 = "
2184                            + Integer.toString(thresholdGoodRssi24));
2185                    } catch (NumberFormatException e) {
2186                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2187                    }
2188                }
2189                if (key.startsWith(THRESHOLD_LOW_RSSI_24_KEY)) {
2190                    String st = key.replace(THRESHOLD_LOW_RSSI_24_KEY, "");
2191                    st = st.replace(SEPARATOR_KEY, "");
2192                    try {
2193                        thresholdLowRssi24 = Integer.parseInt(st);
2194                        Log.d(TAG,"readAutoJoinConfig: thresholdLowRssi24 = "
2195                            + Integer.toString(thresholdLowRssi24));
2196                    } catch (NumberFormatException e) {
2197                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2198                    }
2199                }
2200                if (key.startsWith(THRESHOLD_BAD_RSSI_24_KEY)) {
2201                    String st = key.replace(THRESHOLD_BAD_RSSI_24_KEY, "");
2202                    st = st.replace(SEPARATOR_KEY, "");
2203                    try {
2204                        thresholdBadRssi24 = Integer.parseInt(st);
2205                        Log.d(TAG,"readAutoJoinConfig: thresholdBadRssi24 = "
2206                            + Integer.toString(thresholdBadRssi24));
2207                    } catch (NumberFormatException e) {
2208                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2209                    }
2210                }
2211
2212                if (key.startsWith(THRESHOLD_MAX_TX_PACKETS_FOR_NETWORK_SWITCHING_KEY)) {
2213                    String st = key.replace(THRESHOLD_MAX_TX_PACKETS_FOR_NETWORK_SWITCHING_KEY, "");
2214                    st = st.replace(SEPARATOR_KEY, "");
2215                    try {
2216                        maxTxPacketForNetworkSwitching = Integer.parseInt(st);
2217                        Log.d(TAG,"readAutoJoinConfig: maxTxPacketForNetworkSwitching = "
2218                            + Integer.toString(maxTxPacketForNetworkSwitching));
2219                    } catch (NumberFormatException e) {
2220                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2221                    }
2222                }
2223                if (key.startsWith(THRESHOLD_MAX_RX_PACKETS_FOR_NETWORK_SWITCHING_KEY)) {
2224                    String st = key.replace(THRESHOLD_MAX_RX_PACKETS_FOR_NETWORK_SWITCHING_KEY, "");
2225                    st = st.replace(SEPARATOR_KEY, "");
2226                    try {
2227                        maxRxPacketForNetworkSwitching = Integer.parseInt(st);
2228                        Log.d(TAG,"readAutoJoinConfig: maxRxPacketForNetworkSwitching = "
2229                            + Integer.toString(maxRxPacketForNetworkSwitching));
2230                    } catch (NumberFormatException e) {
2231                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2232                    }
2233                }
2234
2235                if (key.startsWith(THRESHOLD_MAX_TX_PACKETS_FOR_FULL_SCANS_KEY)) {
2236                    String st = key.replace(THRESHOLD_MAX_TX_PACKETS_FOR_FULL_SCANS_KEY, "");
2237                    st = st.replace(SEPARATOR_KEY, "");
2238                    try {
2239                        maxTxPacketForNetworkSwitching = Integer.parseInt(st);
2240                        Log.d(TAG,"readAutoJoinConfig: maxTxPacketForFullScans = "
2241                                + Integer.toString(maxTxPacketForFullScans));
2242                    } catch (NumberFormatException e) {
2243                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2244                    }
2245                }
2246                if (key.startsWith(THRESHOLD_MAX_RX_PACKETS_FOR_FULL_SCANS_KEY)) {
2247                    String st = key.replace(THRESHOLD_MAX_RX_PACKETS_FOR_FULL_SCANS_KEY, "");
2248                    st = st.replace(SEPARATOR_KEY, "");
2249                    try {
2250                        maxRxPacketForNetworkSwitching = Integer.parseInt(st);
2251                        Log.d(TAG,"readAutoJoinConfig: maxRxPacketForFullScans = "
2252                                + Integer.toString(maxRxPacketForFullScans));
2253                    } catch (NumberFormatException e) {
2254                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2255                    }
2256                }
2257
2258                if (key.startsWith(THRESHOLD_MAX_TX_PACKETS_FOR_PARTIAL_SCANS_KEY)) {
2259                    String st = key.replace(THRESHOLD_MAX_TX_PACKETS_FOR_PARTIAL_SCANS_KEY, "");
2260                    st = st.replace(SEPARATOR_KEY, "");
2261                    try {
2262                        maxTxPacketForNetworkSwitching = Integer.parseInt(st);
2263                        Log.d(TAG,"readAutoJoinConfig: maxTxPacketForPartialScans = "
2264                                + Integer.toString(maxTxPacketForPartialScans));
2265                    } catch (NumberFormatException e) {
2266                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2267                    }
2268                }
2269                if (key.startsWith(THRESHOLD_MAX_RX_PACKETS_FOR_PARTIAL_SCANS_KEY)) {
2270                    String st = key.replace(THRESHOLD_MAX_RX_PACKETS_FOR_PARTIAL_SCANS_KEY, "");
2271                    st = st.replace(SEPARATOR_KEY, "");
2272                    try {
2273                        maxRxPacketForNetworkSwitching = Integer.parseInt(st);
2274                        Log.d(TAG,"readAutoJoinConfig: maxRxPacketForPartialScans = "
2275                                + Integer.toString(maxRxPacketForPartialScans));
2276                    } catch (NumberFormatException e) {
2277                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2278                    }
2279                }
2280
2281                if (key.startsWith(WIFI_VERBOSE_LOGS_KEY)) {
2282                    String st = key.replace(WIFI_VERBOSE_LOGS_KEY, "");
2283                    st = st.replace(SEPARATOR_KEY, "");
2284                    try {
2285                        enableVerboseLogging = Integer.parseInt(st);
2286                        Log.d(TAG,"readAutoJoinConfig: enable verbose logs = "
2287                                + Integer.toString(enableVerboseLogging));
2288                    } catch (NumberFormatException e) {
2289                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2290                    }
2291                }
2292                if (key.startsWith(A_BAND_PREFERENCE_RSSI_THRESHOLD_KEY)) {
2293                    String st = key.replace(A_BAND_PREFERENCE_RSSI_THRESHOLD_KEY, "");
2294                    st = st.replace(SEPARATOR_KEY, "");
2295                    try {
2296                        bandPreferenceBoostThreshold5 = Integer.parseInt(st);
2297                        Log.d(TAG,"readAutoJoinConfig: bandPreferenceBoostThreshold5 = "
2298                            + Integer.toString(bandPreferenceBoostThreshold5));
2299                    } catch (NumberFormatException e) {
2300                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2301                    }
2302                }
2303                if (key.startsWith(ASSOCIATED_PARTIAL_SCAN_PERIOD_KEY)) {
2304                    String st = key.replace(ASSOCIATED_PARTIAL_SCAN_PERIOD_KEY, "");
2305                    st = st.replace(SEPARATOR_KEY, "");
2306                    try {
2307                        associatedPartialScanPeriodMilli = Integer.parseInt(st);
2308                        Log.d(TAG,"readAutoJoinConfig: associatedScanPeriod = "
2309                                + Integer.toString(associatedPartialScanPeriodMilli));
2310                    } catch (NumberFormatException e) {
2311                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2312                    }
2313                }
2314                if (key.startsWith(ASSOCIATED_FULL_SCAN_BACKOFF_KEY)) {
2315                    String st = key.replace(ASSOCIATED_FULL_SCAN_BACKOFF_KEY, "");
2316                    st = st.replace(SEPARATOR_KEY, "");
2317                    try {
2318                        associatedFullScanBackoff = Integer.parseInt(st);
2319                        Log.d(TAG,"readAutoJoinConfig: associatedFullScanBackoff = "
2320                                + Integer.toString(associatedFullScanBackoff));
2321                    } catch (NumberFormatException e) {
2322                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2323                    }
2324                }
2325                if (key.startsWith(G_BAND_PREFERENCE_RSSI_THRESHOLD_KEY)) {
2326                    String st = key.replace(G_BAND_PREFERENCE_RSSI_THRESHOLD_KEY, "");
2327                    st = st.replace(SEPARATOR_KEY, "");
2328                    try {
2329                        bandPreferencePenaltyThreshold5 = Integer.parseInt(st);
2330                        Log.d(TAG,"readAutoJoinConfig: bandPreferencePenaltyThreshold5 = "
2331                            + Integer.toString(bandPreferencePenaltyThreshold5));
2332                    } catch (NumberFormatException e) {
2333                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2334                    }
2335                }
2336                if (key.startsWith(ALWAYS_ENABLE_SCAN_WHILE_ASSOCIATED_KEY)) {
2337                    String st = key.replace(ALWAYS_ENABLE_SCAN_WHILE_ASSOCIATED_KEY, "");
2338                    st = st.replace(SEPARATOR_KEY, "");
2339                    try {
2340                        alwaysEnableScansWhileAssociated = Integer.parseInt(st);
2341                        Log.d(TAG,"readAutoJoinConfig: alwaysEnableScansWhileAssociated = "
2342                                + Integer.toString(alwaysEnableScansWhileAssociated));
2343                    } catch (NumberFormatException e) {
2344                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2345                    }
2346                }
2347                if (key.startsWith(MAX_NUM_PASSIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY)) {
2348                    String st = key.replace(MAX_NUM_PASSIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY, "");
2349                    st = st.replace(SEPARATOR_KEY, "");
2350                    try {
2351                        maxNumPassiveChannelsForPartialScans = Integer.parseInt(st);
2352                        Log.d(TAG,"readAutoJoinConfig: maxNumPassiveChannelsForPartialScans = "
2353                                + Integer.toString(maxNumPassiveChannelsForPartialScans));
2354                    } catch (NumberFormatException e) {
2355                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2356                    }
2357                }
2358                if (key.startsWith(MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY)) {
2359                    String st = key.replace(MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCANS_KEY, "");
2360                    st = st.replace(SEPARATOR_KEY, "");
2361                    try {
2362                        maxNumActiveChannelsForPartialScans = Integer.parseInt(st);
2363                        Log.d(TAG,"readAutoJoinConfig: maxNumActiveChannelsForPartialScans = "
2364                                + Integer.toString(maxNumActiveChannelsForPartialScans));
2365                    } catch (NumberFormatException e) {
2366                        Log.d(TAG,"readAutoJoinConfig: incorrect format :" + key);
2367                    }
2368                }
2369            }
2370        } catch (EOFException ignore) {
2371            if (reader != null) {
2372                try {
2373                    reader.close();
2374                    reader = null;
2375                } catch (Exception e) {
2376                    loge("readAutoJoinStatus: Error closing file" + e);
2377                }
2378            }
2379        } catch (FileNotFoundException ignore) {
2380            if (reader != null) {
2381                try {
2382                    reader.close();
2383                    reader = null;
2384                } catch (Exception e) {
2385                    loge("readAutoJoinStatus: Error closing file" + e);
2386                }
2387            }
2388        } catch (IOException e) {
2389            loge("readAutoJoinStatus: Error parsing configuration" + e);
2390        }
2391
2392        if (reader!=null) {
2393           try {
2394               reader.close();
2395           } catch (Exception e) {
2396               loge("readAutoJoinStatus: Error closing file" + e);
2397           }
2398        }
2399    }
2400
2401
2402    private void writeIpAndProxyConfigurations() {
2403        final SparseArray<IpConfiguration> networks = new SparseArray<IpConfiguration>();
2404        for(WifiConfiguration config : mConfiguredNetworks.values()) {
2405            if (!config.ephemeral && config.autoJoinStatus != WifiConfiguration.AUTO_JOIN_DELETED) {
2406                networks.put(configKey(config), config.getIpConfiguration());
2407            }
2408        }
2409
2410        super.writeIpAndProxyConfigurations(ipConfigFile, networks);
2411    }
2412
2413    private void readIpAndProxyConfigurations() {
2414        SparseArray<IpConfiguration> networks = super.readIpAndProxyConfigurations(ipConfigFile);
2415
2416        if (networks.size() == 0) {
2417            // IpConfigStore.readIpAndProxyConfigurations has already logged an error.
2418            return;
2419        }
2420
2421        for (int i = 0; i < networks.size(); i++) {
2422            int id = networks.keyAt(i);
2423            WifiConfiguration config = mConfiguredNetworks.get(mNetworkIds.get(id));
2424
2425
2426            if (config == null || config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED ||
2427                    config.ephemeral) {
2428                loge("configuration found for missing network, nid=" + id
2429                        +", ignored, networks.size=" + Integer.toString(networks.size()));
2430            } else {
2431                config.setIpConfiguration(networks.valueAt(i));
2432            }
2433        }
2434    }
2435
2436    /*
2437     * Convert string to Hexadecimal before passing to wifi native layer
2438     * In native function "doCommand()" have trouble in converting Unicode character string to UTF8
2439     * conversion to hex is required because SSIDs can have space characters in them;
2440     * and that can confuses the supplicant because it uses space charaters as delimiters
2441     */
2442
2443    private String encodeSSID(String str){
2444        String tmp = removeDoubleQuotes(str);
2445        return String.format("%x", new BigInteger(1, tmp.getBytes(Charset.forName("UTF-8"))));
2446    }
2447
2448    private NetworkUpdateResult addOrUpdateNetworkNative(WifiConfiguration config, int uid) {
2449        /*
2450         * If the supplied networkId is INVALID_NETWORK_ID, we create a new empty
2451         * network configuration. Otherwise, the networkId should
2452         * refer to an existing configuration.
2453         */
2454
2455        if (VDBG) localLog("addOrUpdateNetworkNative " + config.getPrintableSsid());
2456
2457        int netId = config.networkId;
2458        boolean newNetwork = false;
2459        // networkId of INVALID_NETWORK_ID means we want to create a new network
2460        if (netId == INVALID_NETWORK_ID) {
2461            Integer savedNetId = mNetworkIds.get(configKey(config));
2462            // Check if either we have a network Id or a WifiConfiguration
2463            // matching the one we are trying to add.
2464            if (savedNetId == null) {
2465                for (WifiConfiguration test : mConfiguredNetworks.values()) {
2466                    if (test.configKey().equals(config.configKey())) {
2467                        savedNetId = test.networkId;
2468                        loge("addOrUpdateNetworkNative " + config.configKey()
2469                                + " was found, but no network Id");
2470                        break;
2471                    }
2472                }
2473            }
2474            if (savedNetId != null) {
2475                netId = savedNetId;
2476            } else {
2477                newNetwork = true;
2478                netId = mWifiNative.addNetwork();
2479                if (netId < 0) {
2480                    loge("Failed to add a network!");
2481                    return new NetworkUpdateResult(INVALID_NETWORK_ID);
2482                } else {
2483                    loge("addOrUpdateNetworkNative created netId=" + netId);
2484                }
2485            }
2486        }
2487
2488        boolean updateFailed = true;
2489
2490        setVariables: {
2491
2492            if (config.SSID != null &&
2493                    !mWifiNative.setNetworkVariable(
2494                        netId,
2495                        WifiConfiguration.ssidVarName,
2496                        encodeSSID(config.SSID))) {
2497                loge("failed to set SSID: "+config.SSID);
2498                break setVariables;
2499            }
2500
2501            if (config.BSSID != null) {
2502                loge("Setting BSSID for " + config.configKey() + " to " + config.BSSID);
2503                if (!mWifiNative.setNetworkVariable(
2504                        netId,
2505                        WifiConfiguration.bssidVarName,
2506                        config.BSSID)) {
2507                    loge("failed to set BSSID: " + config.BSSID);
2508                    break setVariables;
2509                }
2510            }
2511
2512            String allowedKeyManagementString =
2513                makeString(config.allowedKeyManagement, WifiConfiguration.KeyMgmt.strings);
2514            if (config.allowedKeyManagement.cardinality() != 0 &&
2515                    !mWifiNative.setNetworkVariable(
2516                        netId,
2517                        WifiConfiguration.KeyMgmt.varName,
2518                        allowedKeyManagementString)) {
2519                loge("failed to set key_mgmt: "+
2520                        allowedKeyManagementString);
2521                break setVariables;
2522            }
2523
2524            String allowedProtocolsString =
2525                makeString(config.allowedProtocols, WifiConfiguration.Protocol.strings);
2526            if (config.allowedProtocols.cardinality() != 0 &&
2527                    !mWifiNative.setNetworkVariable(
2528                        netId,
2529                        WifiConfiguration.Protocol.varName,
2530                        allowedProtocolsString)) {
2531                loge("failed to set proto: "+
2532                        allowedProtocolsString);
2533                break setVariables;
2534            }
2535
2536            String allowedAuthAlgorithmsString =
2537                makeString(config.allowedAuthAlgorithms, WifiConfiguration.AuthAlgorithm.strings);
2538            if (config.allowedAuthAlgorithms.cardinality() != 0 &&
2539                    !mWifiNative.setNetworkVariable(
2540                        netId,
2541                        WifiConfiguration.AuthAlgorithm.varName,
2542                        allowedAuthAlgorithmsString)) {
2543                loge("failed to set auth_alg: "+
2544                        allowedAuthAlgorithmsString);
2545                break setVariables;
2546            }
2547
2548            String allowedPairwiseCiphersString =
2549                    makeString(config.allowedPairwiseCiphers,
2550                    WifiConfiguration.PairwiseCipher.strings);
2551            if (config.allowedPairwiseCiphers.cardinality() != 0 &&
2552                    !mWifiNative.setNetworkVariable(
2553                        netId,
2554                        WifiConfiguration.PairwiseCipher.varName,
2555                        allowedPairwiseCiphersString)) {
2556                loge("failed to set pairwise: "+
2557                        allowedPairwiseCiphersString);
2558                break setVariables;
2559            }
2560
2561            String allowedGroupCiphersString =
2562                makeString(config.allowedGroupCiphers, WifiConfiguration.GroupCipher.strings);
2563            if (config.allowedGroupCiphers.cardinality() != 0 &&
2564                    !mWifiNative.setNetworkVariable(
2565                        netId,
2566                        WifiConfiguration.GroupCipher.varName,
2567                        allowedGroupCiphersString)) {
2568                loge("failed to set group: "+
2569                        allowedGroupCiphersString);
2570                break setVariables;
2571            }
2572
2573            // Prevent client screw-up by passing in a WifiConfiguration we gave it
2574            // by preventing "*" as a key.
2575            if (config.preSharedKey != null && !config.preSharedKey.equals("*") &&
2576                    !mWifiNative.setNetworkVariable(
2577                        netId,
2578                        WifiConfiguration.pskVarName,
2579                        config.preSharedKey)) {
2580                loge("failed to set psk");
2581                break setVariables;
2582            }
2583
2584            boolean hasSetKey = false;
2585            if (config.wepKeys != null) {
2586                for (int i = 0; i < config.wepKeys.length; i++) {
2587                    // Prevent client screw-up by passing in a WifiConfiguration we gave it
2588                    // by preventing "*" as a key.
2589                    if (config.wepKeys[i] != null && !config.wepKeys[i].equals("*")) {
2590                        if (!mWifiNative.setNetworkVariable(
2591                                    netId,
2592                                    WifiConfiguration.wepKeyVarNames[i],
2593                                    config.wepKeys[i])) {
2594                            loge("failed to set wep_key" + i + ": " + config.wepKeys[i]);
2595                            break setVariables;
2596                        }
2597                        hasSetKey = true;
2598                    }
2599                }
2600            }
2601
2602            if (hasSetKey) {
2603                if (!mWifiNative.setNetworkVariable(
2604                            netId,
2605                            WifiConfiguration.wepTxKeyIdxVarName,
2606                            Integer.toString(config.wepTxKeyIndex))) {
2607                    loge("failed to set wep_tx_keyidx: " + config.wepTxKeyIndex);
2608                    break setVariables;
2609                }
2610            }
2611
2612            if (!mWifiNative.setNetworkVariable(
2613                        netId,
2614                        WifiConfiguration.priorityVarName,
2615                        Integer.toString(config.priority))) {
2616                loge(config.SSID + ": failed to set priority: "
2617                        +config.priority);
2618                break setVariables;
2619            }
2620
2621            if (config.hiddenSSID && !mWifiNative.setNetworkVariable(
2622                        netId,
2623                        WifiConfiguration.hiddenSSIDVarName,
2624                        Integer.toString(config.hiddenSSID ? 1 : 0))) {
2625                loge(config.SSID + ": failed to set hiddenSSID: "+
2626                        config.hiddenSSID);
2627                break setVariables;
2628            }
2629
2630            if (config.requirePMF && !mWifiNative.setNetworkVariable(
2631                        netId,
2632                        WifiConfiguration.pmfVarName,
2633                        "2")) {
2634                loge(config.SSID + ": failed to set requirePMF: "+
2635                        config.requirePMF);
2636                break setVariables;
2637            }
2638
2639            if (config.updateIdentifier != null && !mWifiNative.setNetworkVariable(
2640                    netId,
2641                    WifiConfiguration.updateIdentiferVarName,
2642                    config.updateIdentifier)) {
2643                loge(config.SSID + ": failed to set updateIdentifier: "+
2644                        config.updateIdentifier);
2645                break setVariables;
2646            }
2647
2648            if (config.enterpriseConfig != null &&
2649                    config.enterpriseConfig.getEapMethod() != WifiEnterpriseConfig.Eap.NONE) {
2650
2651                WifiEnterpriseConfig enterpriseConfig = config.enterpriseConfig;
2652
2653                if (needsKeyStore(enterpriseConfig)) {
2654                    /**
2655                     * Keyguard settings may eventually be controlled by device policy.
2656                     * We check here if keystore is unlocked before installing
2657                     * credentials.
2658                     * TODO: Do we need a dialog here ?
2659                     */
2660                    if (mKeyStore.state() != KeyStore.State.UNLOCKED) {
2661                        loge(config.SSID + ": key store is locked");
2662                        break setVariables;
2663                    }
2664
2665                    try {
2666                        /* config passed may include only fields being updated.
2667                         * In order to generate the key id, fetch uninitialized
2668                         * fields from the currently tracked configuration
2669                         */
2670                        WifiConfiguration currentConfig = mConfiguredNetworks.get(netId);
2671                        String keyId = config.getKeyIdForCredentials(currentConfig);
2672
2673                        if (!installKeys(enterpriseConfig, keyId)) {
2674                            loge(config.SSID + ": failed to install keys");
2675                            break setVariables;
2676                        }
2677                    } catch (IllegalStateException e) {
2678                        loge(config.SSID + " invalid config for key installation");
2679                        break setVariables;
2680                    }
2681                }
2682
2683                HashMap<String, String> enterpriseFields = enterpriseConfig.getFields();
2684                for (String key : enterpriseFields.keySet()) {
2685                        String value = enterpriseFields.get(key);
2686                        if (key.equals("password") && value != null && value.equals("*")) {
2687                            // No need to try to set an obfuscated password, which will fail
2688                            continue;
2689                        }
2690                        if (!mWifiNative.setNetworkVariable(
2691                                    netId,
2692                                    key,
2693                                    value)) {
2694                            removeKeys(enterpriseConfig);
2695                            loge(config.SSID + ": failed to set " + key +
2696                                    ": " + value);
2697                            break setVariables;
2698                        }
2699                }
2700            }
2701            updateFailed = false;
2702        } // End of setVariables
2703
2704        if (updateFailed) {
2705            if (newNetwork) {
2706                mWifiNative.removeNetwork(netId);
2707                loge("Failed to set a network variable, removed network: " + netId);
2708            }
2709            return new NetworkUpdateResult(INVALID_NETWORK_ID);
2710        }
2711
2712        /* An update of the network variables requires reading them
2713         * back from the supplicant to update mConfiguredNetworks.
2714         * This is because some of the variables (SSID, wep keys &
2715         * passphrases) reflect different values when read back than
2716         * when written. For example, wep key is stored as * irrespective
2717         * of the value sent to the supplicant
2718         */
2719        WifiConfiguration currentConfig = mConfiguredNetworks.get(netId);
2720        if (currentConfig == null) {
2721            currentConfig = new WifiConfiguration();
2722            currentConfig.setIpAssignment(IpAssignment.DHCP);
2723            currentConfig.setProxySettings(ProxySettings.NONE);
2724            currentConfig.networkId = netId;
2725            if (config != null) {
2726                // Carry over the creation parameters
2727                currentConfig.selfAdded = config.selfAdded;
2728                currentConfig.didSelfAdd = config.didSelfAdd;
2729                currentConfig.ephemeral = config.ephemeral;
2730                currentConfig.autoJoinUseAggressiveJoinAttemptThreshold
2731                        = config.autoJoinUseAggressiveJoinAttemptThreshold;
2732                currentConfig.lastConnectUid = config.lastConnectUid;
2733                currentConfig.lastUpdateUid = config.lastUpdateUid;
2734                currentConfig.creatorUid = config.creatorUid;
2735                currentConfig.peerWifiConfiguration = config.peerWifiConfiguration;
2736            }
2737            if (DBG) {
2738                loge("created new config netId=" + Integer.toString(netId)
2739                        + " uid=" + Integer.toString(currentConfig.creatorUid));
2740            }
2741        }
2742
2743        if (uid >= 0) {
2744            if (newNetwork) {
2745                currentConfig.creatorUid = uid;
2746            } else {
2747                currentConfig.lastUpdateUid = uid;
2748            }
2749        }
2750
2751        if (newNetwork) {
2752            currentConfig.dirty = true;
2753        }
2754
2755        if (currentConfig.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED) {
2756            // Make sure the configuration is not deleted anymore since we just
2757            // added or modified it.
2758            currentConfig.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED);
2759            currentConfig.selfAdded = false;
2760            currentConfig.didSelfAdd = false;
2761            if (DBG) {
2762                loge("remove deleted status netId=" + Integer.toString(netId)
2763                        + " " + currentConfig.configKey());
2764            }
2765        }
2766
2767        if (currentConfig.status == WifiConfiguration.Status.ENABLED) {
2768            // Make sure autojoin remain in sync with user modifying the configuration
2769            currentConfig.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED);
2770        }
2771
2772        if (currentConfig.configKey().equals(getLastSelectedConfiguration()) &&
2773                currentConfig.ephemeral) {
2774            // Make the config non-ephemeral since the user just explicitly clicked it.
2775            currentConfig.ephemeral = false;
2776            if (DBG) loge("remove ephemeral status netId=" + Integer.toString(netId)
2777                    + " " + currentConfig.configKey());
2778        }
2779
2780        if (DBG) loge("will read network variables netId=" + Integer.toString(netId));
2781
2782        readNetworkVariables(currentConfig);
2783
2784        mConfiguredNetworks.put(netId, currentConfig);
2785        mNetworkIds.put(configKey(currentConfig), netId);
2786
2787        NetworkUpdateResult result = writeIpAndProxyConfigurationsOnChange(currentConfig, config);
2788        result.setIsNewNetwork(newNetwork);
2789        result.setNetworkId(netId);
2790
2791        writeKnownNetworkHistory();
2792
2793        return result;
2794    }
2795
2796
2797    /**
2798     * This function run thru the Saved WifiConfigurations and check if some should be linked.
2799     * @param config
2800     */
2801    public void linkConfiguration(WifiConfiguration config) {
2802
2803        if (config.scanResultCache != null && config.scanResultCache.size() > 6) {
2804            // Ignore configurations with large number of BSSIDs
2805            return;
2806        }
2807        if (!config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
2808            // Only link WPA_PSK config
2809            return;
2810        }
2811        for (WifiConfiguration link : mConfiguredNetworks.values()) {
2812            boolean doLink = false;
2813
2814            if (link.configKey().equals(config.configKey())) {
2815                continue;
2816            }
2817
2818            if (link.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED || link.ephemeral) {
2819                continue;
2820            }
2821
2822            // Autojoin will be allowed to dynamically jump from a linked configuration
2823            // to another, hence only link configurations that have equivalent level of security
2824            if (!link.allowedKeyManagement.equals(config.allowedKeyManagement)) {
2825                continue;
2826            }
2827
2828            if (link.scanResultCache != null && link.scanResultCache.size() > 6) {
2829                // Ignore configurations with large number of BSSIDs
2830                continue;
2831            }
2832
2833            if (config.defaultGwMacAddress != null && link.defaultGwMacAddress != null) {
2834                // If both default GW are known, link only if they are equal
2835                if (config.defaultGwMacAddress.equals(link.defaultGwMacAddress)) {
2836                    if (VDBG) {
2837                        loge("linkConfiguration link due to same gw " + link.SSID +
2838                                " and " + config.SSID + " GW " + config.defaultGwMacAddress);
2839                    }
2840                    doLink = true;
2841                }
2842            } else {
2843                // We do not know BOTH default gateways hence we will try to link
2844                // hoping that WifiConfigurations are indeed behind the same gateway.
2845                // once both WifiConfiguration have been tried and thus once both efault gateways
2846                // are known we will revisit the choice of linking them
2847                if ((config.scanResultCache != null) && (config.scanResultCache.size() <= 6)
2848                        && (link.scanResultCache != null) && (link.scanResultCache.size() <= 6)) {
2849                    for (String abssid : config.scanResultCache.keySet()) {
2850                        for (String bbssid : link.scanResultCache.keySet()) {
2851                            if (VVDBG) {
2852                                loge("linkConfiguration try to link due to DBDC BSSID match "
2853                                        + link.SSID +
2854                                        " and " + config.SSID + " bssida " + abssid
2855                                        + " bssidb " + bbssid);
2856                            }
2857                            if (abssid.regionMatches(true, 0, bbssid, 0, 16)) {
2858                                // If first 16 ascii characters of BSSID matches,
2859                                // we assume this is a DBDC
2860                                doLink = true;
2861                            }
2862                        }
2863                    }
2864                }
2865            }
2866
2867            if (doLink == true && onlyLinkSameCredentialConfigurations) {
2868                String apsk = readNetworkVariableFromSupplicantFile(link.SSID, "psk");
2869                String bpsk = readNetworkVariableFromSupplicantFile(config.SSID, "psk");
2870                if (apsk == null || bpsk == null
2871                        || TextUtils.isEmpty(apsk) || TextUtils.isEmpty(apsk)
2872                        || apsk.equals("*") || apsk.equals("xxxxxxxx")
2873                        || !apsk.equals(bpsk)) {
2874                    doLink = false;
2875                }
2876            }
2877
2878            if (doLink) {
2879                if (VDBG) {
2880                   loge("linkConfiguration: will link " + link.configKey()
2881                           + " and " + config.configKey());
2882                }
2883                if (link.linkedConfigurations == null) {
2884                    link.linkedConfigurations = new HashMap<String, Integer>();
2885                }
2886                if (config.linkedConfigurations == null) {
2887                    config.linkedConfigurations = new HashMap<String, Integer>();
2888                }
2889                if (link.linkedConfigurations.get(config.configKey()) == null) {
2890                    link.linkedConfigurations.put(config.configKey(), Integer.valueOf(1));
2891                    link.dirty = true;
2892                }
2893                if (config.linkedConfigurations.get(link.configKey()) == null) {
2894                    config.linkedConfigurations.put(link.configKey(), Integer.valueOf(1));
2895                    config.dirty = true;
2896                }
2897            } else {
2898                if (link.linkedConfigurations != null
2899                        && (link.linkedConfigurations.get(config.configKey()) != null)) {
2900                    if (VDBG) {
2901                        loge("linkConfiguration: un-link " + config.configKey()
2902                                + " from " + link.configKey());
2903                    }
2904                    link.dirty = true;
2905                    link.linkedConfigurations.remove(config.configKey());
2906                }
2907                if (config.linkedConfigurations != null
2908                        && (config.linkedConfigurations.get(link.configKey()) != null)) {
2909                    if (VDBG) {
2910                        loge("linkConfiguration: un-link " + link.configKey()
2911                                + " from " + config.configKey());
2912                    }
2913                    config.dirty = true;
2914                    config.linkedConfigurations.remove(link.configKey());
2915                }
2916            }
2917        }
2918    }
2919
2920    /*
2921     * We try to link a scan result with a WifiConfiguration for which SSID and
2922     * key management dont match,
2923     * for instance, we try identify the 5GHz SSID of a DBDC AP,
2924     * even though we know only of the 2.4GHz
2925     *
2926     * Obviously, this function is not optimal since it is used to compare every scan
2927     * result with every Saved WifiConfiguration, with a string.equals operation.
2928     * As a speed up, might be better to implement the mConfiguredNetworks store as a
2929     * <String, WifiConfiguration> object instead of a <Integer, WifiConfiguration> object
2930     * so as to speed this up. Also to prevent the tiny probability of hash collision.
2931     *
2932     */
2933    public WifiConfiguration associateWithConfiguration(ScanResult result) {
2934        String configKey = WifiConfiguration.configKey(result);
2935        if (configKey == null) {
2936            if (DBG) loge("associateWithConfiguration(): no config key " );
2937            return null;
2938        }
2939
2940        // Need to compare with quoted string
2941        String SSID = "\"" + result.SSID + "\"";
2942
2943        if (VVDBG) {
2944            loge("associateWithConfiguration(): try " + configKey);
2945        }
2946
2947        WifiConfiguration config = null;
2948        for (WifiConfiguration link : mConfiguredNetworks.values()) {
2949            boolean doLink = false;
2950
2951            if (link.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED || link.selfAdded ||
2952                    link.ephemeral) {
2953                if (VVDBG) loge("associateWithConfiguration(): skip selfadd " + link.configKey() );
2954                // Make sure we dont associate the scan result to a deleted config
2955                continue;
2956            }
2957
2958            if (!link.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
2959                if (VVDBG) loge("associateWithConfiguration(): skip non-PSK " + link.configKey() );
2960                // Make sure we dont associate the scan result to a non-PSK config
2961                continue;
2962            }
2963
2964            if (configKey.equals(link.configKey())) {
2965                if (VVDBG) loge("associateWithConfiguration(): found it!!! " + configKey );
2966                return link; // Found it exactly
2967            }
2968
2969            if ((link.scanResultCache != null) && (link.scanResultCache.size() <= 6)) {
2970                for (String bssid : link.scanResultCache.keySet()) {
2971                    if (result.BSSID.regionMatches(true, 0, bssid, 0, 16)
2972                            && SSID.regionMatches(false, 0, link.SSID, 0, 4)) {
2973                        // If first 16 ascii characters of BSSID matches, and first 3
2974                        // characters of SSID match, we assume this is a home setup
2975                        // and thus we will try to transfer the password from the known
2976                        // BSSID/SSID to the recently found BSSID/SSID
2977
2978                        // If (VDBG)
2979                        //    loge("associateWithConfiguration OK " );
2980                        doLink = true;
2981                        break;
2982                    }
2983                }
2984            }
2985
2986            if (doLink) {
2987                // Try to make a non verified WifiConfiguration, but only if the original
2988                // configuration was not self already added
2989                if (VDBG) {
2990                    loge("associateWithConfiguration: will create " +
2991                            result.SSID + " and associate it with: " + link.SSID);
2992                }
2993                config = wifiConfigurationFromScanResult(result);
2994                if (config != null) {
2995                    config.selfAdded = true;
2996                    config.didSelfAdd = true;
2997                    config.dirty = true;
2998                    config.peerWifiConfiguration = link.configKey();
2999                    if (config.allowedKeyManagement.equals(link.allowedKeyManagement) &&
3000                            config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
3001                        // Transfer the credentials from the configuration we are linking from
3002                        String psk = readNetworkVariableFromSupplicantFile(link.SSID, "psk");
3003                        if (psk != null) {
3004                            config.preSharedKey = psk;
3005                            if (VDBG) {
3006                                if (config.preSharedKey != null)
3007                                    loge(" transfer PSK : " + config.preSharedKey);
3008                            }
3009
3010                            // Link configurations
3011                            if (link.linkedConfigurations == null) {
3012                                link.linkedConfigurations = new HashMap<String, Integer>();
3013                            }
3014                            if (config.linkedConfigurations == null) {
3015                                config.linkedConfigurations = new HashMap<String, Integer>();
3016                            }
3017                            link.linkedConfigurations.put(config.configKey(), Integer.valueOf(1));
3018                            config.linkedConfigurations.put(link.configKey(), Integer.valueOf(1));
3019                        } else {
3020                            config = null;
3021                        }
3022                    } else {
3023                        config = null;
3024                    }
3025                    if (config != null) break;
3026                }
3027            }
3028        }
3029        return config;
3030    }
3031
3032    public HashSet<Integer> makeChannelList(WifiConfiguration config, int age, boolean restrict) {
3033        if (config == null)
3034            return null;
3035        long now_ms = System.currentTimeMillis();
3036
3037        HashSet<Integer> channels = new HashSet<Integer>();
3038
3039        //get channels for this configuration, if there are at least 2 BSSIDs
3040        if (config.scanResultCache == null && config.linkedConfigurations == null) {
3041            return null;
3042        }
3043
3044        if (VDBG) {
3045            StringBuilder dbg = new StringBuilder();
3046            dbg.append("makeChannelList age=" + Integer.toString(age)
3047                    + " for " + config.configKey()
3048                    + " max=" + maxNumActiveChannelsForPartialScans);
3049            if (config.scanResultCache != null) {
3050                dbg.append(" bssids=" + config.scanResultCache.size());
3051            }
3052            if (config.linkedConfigurations != null) {
3053                dbg.append(" linked=" + config.linkedConfigurations.size());
3054            }
3055            loge(dbg.toString());
3056        }
3057
3058        int numChannels = 0;
3059        if (config.scanResultCache != null && config.scanResultCache.size() > 0) {
3060            for (ScanResult result : config.scanResultCache.values()) {
3061                //TODO : cout active and passive channels separately
3062                if (numChannels > maxNumActiveChannelsForPartialScans) {
3063                    break;
3064                }
3065                if (VDBG) {
3066                    boolean test = (now_ms - result.seen) < age;
3067                    loge("has " + result.BSSID + " freq=" + Integer.toString(result.frequency)
3068                            + " age=" + Long.toString(now_ms - result.seen) + " ?=" + test);
3069                }
3070                if (((now_ms - result.seen) < age)/*||(!restrict || result.is24GHz())*/) {
3071                    channels.add(result.frequency);
3072                    numChannels++;
3073                }
3074            }
3075        }
3076
3077        //get channels for linked configurations
3078        if (config.linkedConfigurations != null) {
3079            for (String key : config.linkedConfigurations.keySet()) {
3080                WifiConfiguration linked = getWifiConfiguration(key);
3081                if (linked == null)
3082                    continue;
3083                if (linked.scanResultCache == null) {
3084                    continue;
3085                }
3086                for (ScanResult result : linked.scanResultCache.values()) {
3087                    if (VDBG) {
3088                        loge("has link: " + result.BSSID
3089                                + " freq=" + Integer.toString(result.frequency)
3090                                + " age=" + Long.toString(now_ms - result.seen));
3091                    }
3092                    if (numChannels > maxNumActiveChannelsForPartialScans) {
3093                        break;
3094                    }
3095                    if (((now_ms - result.seen) < age)/*||(!restrict || result.is24GHz())*/) {
3096                        channels.add(result.frequency);
3097                        numChannels++;
3098                    }
3099                }
3100            }
3101        }
3102        return channels;
3103    }
3104
3105    // Update the WifiConfiguration database with the new scan result
3106    // A scan result can be associated to multiple WifiConfigurations
3107    public boolean updateSavedNetworkHistory(ScanResult scanResult) {
3108        int numConfigFound = 0;
3109        if (scanResult == null)
3110            return false;
3111
3112        String SSID = "\"" + scanResult.SSID + "\"";
3113
3114        for (WifiConfiguration config : mConfiguredNetworks.values()) {
3115            boolean found = false;
3116
3117            if (config.autoJoinStatus >= WifiConfiguration.AUTO_JOIN_DELETED) {
3118                continue;
3119            }
3120
3121            if (config.SSID == null || !config.SSID.equals(SSID)) {
3122                // SSID mismatch
3123                if (VVDBG) {
3124                    loge("updateSavedNetworkHistory(): SSID mismatch " + config.configKey()
3125                            + " SSID=" + config.SSID + " " + SSID);
3126                }
3127                continue;
3128            }
3129            if (VDBG) {
3130                loge("updateSavedNetworkHistory(): try " + config.configKey()
3131                        + " SSID=" + config.SSID + " " + scanResult.SSID
3132                        + " " + scanResult.capabilities
3133                        + " ajst=" + config.autoJoinStatus);
3134            }
3135            if (scanResult.capabilities.contains("WEP")
3136                    && config.configKey().contains("WEP")) {
3137                found = true;
3138            } else if (scanResult.capabilities.contains("PSK")
3139                    && config.configKey().contains("PSK")) {
3140                found = true;
3141            } else if (scanResult.capabilities.contains("EAP")
3142                    && config.configKey().contains("EAP")) {
3143                found = true;
3144            } else if (!scanResult.capabilities.contains("WEP")
3145                && !scanResult.capabilities.contains("PSK")
3146                && !scanResult.capabilities.contains("EAP")
3147                && !config.configKey().contains("WEP")
3148                    && !config.configKey().contains("PSK")
3149                    && !config.configKey().contains("EAP")) {
3150                found = true;
3151            }
3152
3153            if (found) {
3154                numConfigFound ++;
3155
3156                if (config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DELETED) {
3157                    if (VVDBG) {
3158                        loge("updateSavedNetworkHistory(): found a deleted, skip it...  "
3159                                + config.configKey());
3160                    }
3161                    // The scan result belongs to a deleted config:
3162                    //   - increment numConfigFound to remember that we found a config
3163                    //            matching for this scan result
3164                    //   - dont do anything since the config was deleted, just skip...
3165                    continue;
3166                }
3167
3168                if (config.scanResultCache == null) {
3169                    config.scanResultCache = new HashMap<String, ScanResult>();
3170                }
3171
3172                // Adding a new BSSID
3173                if (config.scanResultCache.get(scanResult.BSSID) == null) {
3174                    config.dirty = true;
3175                }
3176
3177                // Add the scan result to this WifiConfiguration
3178                config.scanResultCache.put(scanResult.BSSID, scanResult);
3179                // Since we added a scan result to this configuration, re-attempt linking
3180                linkConfiguration(config);
3181            }
3182
3183            if (VDBG && found) {
3184                String status = "";
3185                if (scanResult.autoJoinStatus > 0) {
3186                    status = " status=" + Integer.toString(scanResult.autoJoinStatus);
3187                }
3188                loge("        got known scan result " +
3189                        scanResult.BSSID + " key : "
3190                        + config.configKey() + " num: " +
3191                        Integer.toString(config.scanResultCache.size())
3192                        + " rssi=" + Integer.toString(scanResult.level)
3193                        + " freq=" + Integer.toString(scanResult.frequency)
3194                        + status);
3195            }
3196        }
3197        return numConfigFound != 0;
3198    }
3199
3200    /* Compare current and new configuration and write to file on change */
3201    private NetworkUpdateResult writeIpAndProxyConfigurationsOnChange(
3202            WifiConfiguration currentConfig,
3203            WifiConfiguration newConfig) {
3204        boolean ipChanged = false;
3205        boolean proxyChanged = false;
3206
3207        if (VDBG) {
3208            loge("writeIpAndProxyConfigurationsOnChange: " + currentConfig.SSID + " -> " +
3209                    newConfig.SSID + " path: " + ipConfigFile);
3210        }
3211
3212
3213        switch (newConfig.getIpAssignment()) {
3214            case STATIC:
3215                if (currentConfig.getIpAssignment() != newConfig.getIpAssignment()) {
3216                    ipChanged = true;
3217                } else {
3218                    ipChanged = !Objects.equals(
3219                            currentConfig.getStaticIpConfiguration(),
3220                            newConfig.getStaticIpConfiguration());
3221                }
3222                break;
3223            case DHCP:
3224                if (currentConfig.getIpAssignment() != newConfig.getIpAssignment()) {
3225                    ipChanged = true;
3226                }
3227                break;
3228            case UNASSIGNED:
3229                /* Ignore */
3230                break;
3231            default:
3232                loge("Ignore invalid ip assignment during write");
3233                break;
3234        }
3235
3236        switch (newConfig.getProxySettings()) {
3237            case STATIC:
3238            case PAC:
3239                ProxyInfo newHttpProxy = newConfig.getHttpProxy();
3240                ProxyInfo currentHttpProxy = currentConfig.getHttpProxy();
3241
3242                if (newHttpProxy != null) {
3243                    proxyChanged = !newHttpProxy.equals(currentHttpProxy);
3244                } else {
3245                    proxyChanged = (currentHttpProxy != null);
3246                }
3247                break;
3248            case NONE:
3249                if (currentConfig.getProxySettings() != newConfig.getProxySettings()) {
3250                    proxyChanged = true;
3251                }
3252                break;
3253            case UNASSIGNED:
3254                /* Ignore */
3255                break;
3256            default:
3257                loge("Ignore invalid proxy configuration during write");
3258                break;
3259        }
3260
3261        if (ipChanged) {
3262            currentConfig.setIpAssignment(newConfig.getIpAssignment());
3263            currentConfig.setStaticIpConfiguration(newConfig.getStaticIpConfiguration());
3264            log("IP config changed SSID = " + currentConfig.SSID);
3265            if (currentConfig.getStaticIpConfiguration() != null) {
3266                log(" static configuration: " +
3267                    currentConfig.getStaticIpConfiguration().toString());
3268            }
3269        }
3270
3271        if (proxyChanged) {
3272            currentConfig.setProxySettings(newConfig.getProxySettings());
3273            currentConfig.setHttpProxy(newConfig.getHttpProxy());
3274            log("proxy changed SSID = " + currentConfig.SSID);
3275            if (currentConfig.getHttpProxy() != null) {
3276                log(" proxyProperties: " + currentConfig.getHttpProxy().toString());
3277            }
3278        }
3279
3280        if (ipChanged || proxyChanged) {
3281            writeIpAndProxyConfigurations();
3282            sendConfiguredNetworksChangedBroadcast(currentConfig,
3283                    WifiManager.CHANGE_REASON_CONFIG_CHANGE);
3284        }
3285        return new NetworkUpdateResult(ipChanged, proxyChanged);
3286    }
3287
3288    /** Returns true if a particular config key needs to be quoted when passed to the supplicant. */
3289    private boolean enterpriseConfigKeyShouldBeQuoted(String key) {
3290        switch (key) {
3291            case WifiEnterpriseConfig.EAP_KEY:
3292            case WifiEnterpriseConfig.ENGINE_KEY:
3293                return false;
3294            default:
3295                return true;
3296        }
3297    }
3298
3299    /**
3300     * Read the variables from the supplicant daemon that are needed to
3301     * fill in the WifiConfiguration object.
3302     *
3303     * @param config the {@link WifiConfiguration} object to be filled in.
3304     */
3305    private void readNetworkVariables(WifiConfiguration config) {
3306
3307        int netId = config.networkId;
3308        if (netId < 0)
3309            return;
3310
3311        /*
3312         * TODO: maybe should have a native method that takes an array of
3313         * variable names and returns an array of values. But we'd still
3314         * be doing a round trip to the supplicant daemon for each variable.
3315         */
3316        String value;
3317
3318        value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.ssidVarName);
3319        if (!TextUtils.isEmpty(value)) {
3320            if (value.charAt(0) != '"') {
3321                config.SSID = "\"" + WifiSsid.createFromHex(value).toString() + "\"";
3322                //TODO: convert a hex string that is not UTF-8 decodable to a P-formatted
3323                //supplicant string
3324            } else {
3325                config.SSID = value;
3326            }
3327        } else {
3328            config.SSID = null;
3329        }
3330
3331        value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.bssidVarName);
3332        if (!TextUtils.isEmpty(value)) {
3333            config.BSSID = value;
3334        } else {
3335            config.BSSID = null;
3336        }
3337
3338        value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.priorityVarName);
3339        config.priority = -1;
3340        if (!TextUtils.isEmpty(value)) {
3341            try {
3342                config.priority = Integer.parseInt(value);
3343            } catch (NumberFormatException ignore) {
3344            }
3345        }
3346
3347        value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.hiddenSSIDVarName);
3348        config.hiddenSSID = false;
3349        if (!TextUtils.isEmpty(value)) {
3350            try {
3351                config.hiddenSSID = Integer.parseInt(value) != 0;
3352            } catch (NumberFormatException ignore) {
3353            }
3354        }
3355
3356        value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.wepTxKeyIdxVarName);
3357        config.wepTxKeyIndex = -1;
3358        if (!TextUtils.isEmpty(value)) {
3359            try {
3360                config.wepTxKeyIndex = Integer.parseInt(value);
3361            } catch (NumberFormatException ignore) {
3362            }
3363        }
3364
3365        for (int i = 0; i < 4; i++) {
3366            value = mWifiNative.getNetworkVariable(netId,
3367                    WifiConfiguration.wepKeyVarNames[i]);
3368            if (!TextUtils.isEmpty(value)) {
3369                config.wepKeys[i] = value;
3370            } else {
3371                config.wepKeys[i] = null;
3372            }
3373        }
3374
3375        value = mWifiNative.getNetworkVariable(netId, WifiConfiguration.pskVarName);
3376        if (!TextUtils.isEmpty(value)) {
3377            config.preSharedKey = value;
3378        } else {
3379            config.preSharedKey = null;
3380        }
3381
3382        value = mWifiNative.getNetworkVariable(config.networkId,
3383                WifiConfiguration.Protocol.varName);
3384        if (!TextUtils.isEmpty(value)) {
3385            String vals[] = value.split(" ");
3386            for (String val : vals) {
3387                int index =
3388                    lookupString(val, WifiConfiguration.Protocol.strings);
3389                if (0 <= index) {
3390                    config.allowedProtocols.set(index);
3391                }
3392            }
3393        }
3394
3395        value = mWifiNative.getNetworkVariable(config.networkId,
3396                WifiConfiguration.KeyMgmt.varName);
3397        if (!TextUtils.isEmpty(value)) {
3398            String vals[] = value.split(" ");
3399            for (String val : vals) {
3400                int index =
3401                    lookupString(val, WifiConfiguration.KeyMgmt.strings);
3402                if (0 <= index) {
3403                    config.allowedKeyManagement.set(index);
3404                }
3405            }
3406        }
3407
3408        value = mWifiNative.getNetworkVariable(config.networkId,
3409                WifiConfiguration.AuthAlgorithm.varName);
3410        if (!TextUtils.isEmpty(value)) {
3411            String vals[] = value.split(" ");
3412            for (String val : vals) {
3413                int index =
3414                    lookupString(val, WifiConfiguration.AuthAlgorithm.strings);
3415                if (0 <= index) {
3416                    config.allowedAuthAlgorithms.set(index);
3417                }
3418            }
3419        }
3420
3421        value = mWifiNative.getNetworkVariable(config.networkId,
3422                WifiConfiguration.PairwiseCipher.varName);
3423        if (!TextUtils.isEmpty(value)) {
3424            String vals[] = value.split(" ");
3425            for (String val : vals) {
3426                int index =
3427                    lookupString(val, WifiConfiguration.PairwiseCipher.strings);
3428                if (0 <= index) {
3429                    config.allowedPairwiseCiphers.set(index);
3430                }
3431            }
3432        }
3433
3434        value = mWifiNative.getNetworkVariable(config.networkId,
3435                WifiConfiguration.GroupCipher.varName);
3436        if (!TextUtils.isEmpty(value)) {
3437            String vals[] = value.split(" ");
3438            for (String val : vals) {
3439                int index =
3440                    lookupString(val, WifiConfiguration.GroupCipher.strings);
3441                if (0 <= index) {
3442                    config.allowedGroupCiphers.set(index);
3443                }
3444            }
3445        }
3446
3447        if (config.enterpriseConfig == null) {
3448            config.enterpriseConfig = new WifiEnterpriseConfig();
3449        }
3450        HashMap<String, String> enterpriseFields = config.enterpriseConfig.getFields();
3451        for (String key : ENTERPRISE_CONFIG_SUPPLICANT_KEYS) {
3452            value = mWifiNative.getNetworkVariable(netId, key);
3453            if (!TextUtils.isEmpty(value)) {
3454                if (!enterpriseConfigKeyShouldBeQuoted(key)) {
3455                    value = removeDoubleQuotes(value);
3456                }
3457                enterpriseFields.put(key, value);
3458            } else {
3459                enterpriseFields.put(key, EMPTY_VALUE);
3460            }
3461        }
3462
3463        if (migrateOldEapTlsNative(config.enterpriseConfig, netId)) {
3464            saveConfig();
3465        }
3466
3467        migrateCerts(config.enterpriseConfig);
3468        // initializeSoftwareKeystoreFlag(config.enterpriseConfig, mKeyStore);
3469    }
3470
3471    private static String removeDoubleQuotes(String string) {
3472        int length = string.length();
3473        if ((length > 1) && (string.charAt(0) == '"')
3474                && (string.charAt(length - 1) == '"')) {
3475            return string.substring(1, length - 1);
3476        }
3477        return string;
3478    }
3479
3480    private static String makeString(BitSet set, String[] strings) {
3481        StringBuffer buf = new StringBuffer();
3482        int nextSetBit = -1;
3483
3484        /* Make sure all set bits are in [0, strings.length) to avoid
3485         * going out of bounds on strings.  (Shouldn't happen, but...) */
3486        set = set.get(0, strings.length);
3487
3488        while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
3489            buf.append(strings[nextSetBit].replace('_', '-')).append(' ');
3490        }
3491
3492        // remove trailing space
3493        if (set.cardinality() > 0) {
3494            buf.setLength(buf.length() - 1);
3495        }
3496
3497        return buf.toString();
3498    }
3499
3500    private int lookupString(String string, String[] strings) {
3501        int size = strings.length;
3502
3503        string = string.replace('-', '_');
3504
3505        for (int i = 0; i < size; i++)
3506            if (string.equals(strings[i]))
3507                return i;
3508
3509        // if we ever get here, we should probably add the
3510        // value to WifiConfiguration to reflect that it's
3511        // supported by the WPA supplicant
3512        loge("Failed to look-up a string: " + string);
3513
3514        return -1;
3515    }
3516
3517    /* return the allowed key management based on a scan result */
3518
3519    public WifiConfiguration wifiConfigurationFromScanResult(ScanResult result) {
3520        WifiConfiguration config = new WifiConfiguration();
3521
3522        config.SSID = "\"" + result.SSID + "\"";
3523
3524        if (VDBG) {
3525            loge("WifiConfiguration from scan results " +
3526                    config.SSID + " cap " + result.capabilities);
3527        }
3528        if (result.capabilities.contains("WEP")) {
3529            config.allowedKeyManagement.set(KeyMgmt.NONE);
3530            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN); //?
3531            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
3532        }
3533
3534        if (result.capabilities.contains("PSK")) {
3535            config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
3536        }
3537
3538        if (result.capabilities.contains("EAP")) {
3539            //this is probably wrong, as we don't have a way to enter the enterprise config
3540            config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
3541            config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
3542        }
3543
3544        config.scanResultCache = new HashMap<String, ScanResult>();
3545        if (config.scanResultCache == null)
3546            return null;
3547        config.scanResultCache.put(result.BSSID, result);
3548
3549        return config;
3550    }
3551
3552
3553    /* Returns a unique for a given configuration */
3554    private static int configKey(WifiConfiguration config) {
3555        String key = config.configKey();
3556        return key.hashCode();
3557    }
3558
3559    void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3560        pw.println("Dump of WifiConfigStore");
3561        pw.println("mLastPriority " + mLastPriority);
3562        pw.println("Configured networks");
3563        for (WifiConfiguration conf : getConfiguredNetworks()) {
3564            pw.println(conf);
3565        }
3566        pw.println();
3567
3568        if (mLocalLog != null) {
3569            pw.println("WifiConfigStore - Log Begin ----");
3570            mLocalLog.dump(fd, pw, args);
3571            pw.println("WifiConfigStore - Log End ----");
3572        }
3573    }
3574
3575    public String getConfigFile() {
3576        return ipConfigFile;
3577    }
3578
3579    protected void loge(String s) {
3580        loge(s, false);
3581    }
3582
3583    protected void loge(String s, boolean stack) {
3584        if (stack) {
3585            Log.e(TAG, s + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
3586                    + " - " + Thread.currentThread().getStackTrace()[3].getMethodName()
3587                    + " - " + Thread.currentThread().getStackTrace()[4].getMethodName()
3588                    + " - " + Thread.currentThread().getStackTrace()[5].getMethodName());
3589        } else {
3590            Log.e(TAG, s);
3591        }
3592    }
3593
3594    protected void log(String s) {
3595        Log.d(TAG, s);
3596    }
3597
3598    private void localLog(String s) {
3599        if (mLocalLog != null) {
3600            mLocalLog.log(s);
3601        }
3602    }
3603
3604    private void localLog(String s, boolean force) {
3605        localLog(s);
3606        if (force) loge(s);
3607    }
3608
3609    private void localLog(String s, int netId) {
3610        if (mLocalLog == null) {
3611            return;
3612        }
3613
3614        WifiConfiguration config;
3615        synchronized(mConfiguredNetworks) {
3616            config = mConfiguredNetworks.get(netId);
3617        }
3618
3619        if (config != null) {
3620            mLocalLog.log(s + " " + config.getPrintableSsid() + " " + netId
3621                    + " status=" + config.status
3622                    + " key=" + config.configKey());
3623        } else {
3624            mLocalLog.log(s + " " + netId);
3625        }
3626    }
3627
3628    // Certificate and private key management for EnterpriseConfig
3629    static boolean needsKeyStore(WifiEnterpriseConfig config) {
3630        // Has no keys to be installed
3631        if (config.getClientCertificate() == null && config.getCaCertificate() == null)
3632            return false;
3633        return true;
3634    }
3635
3636    static boolean isHardwareBackedKey(PrivateKey key) {
3637        return KeyChain.isBoundKeyAlgorithm(key.getAlgorithm());
3638    }
3639
3640    static boolean hasHardwareBackedKey(Certificate certificate) {
3641        return KeyChain.isBoundKeyAlgorithm(certificate.getPublicKey().getAlgorithm());
3642    }
3643
3644    static boolean needsSoftwareBackedKeyStore(WifiEnterpriseConfig config) {
3645        String client = config.getClientCertificateAlias();
3646        if (!TextUtils.isEmpty(client)) {
3647            // a valid client certificate is configured
3648
3649            // BUGBUG: keyStore.get() never returns certBytes; because it is not
3650            // taking WIFI_UID as a parameter. It always looks for certificate
3651            // with SYSTEM_UID, and never finds any Wifi certificates. Assuming that
3652            // all certificates need software keystore until we get the get() API
3653            // fixed.
3654
3655            return true;
3656        }
3657
3658        /*
3659        try {
3660
3661            if (DBG) Slog.d(TAG, "Loading client certificate " + Credentials
3662                    .USER_CERTIFICATE + client);
3663
3664            CertificateFactory factory = CertificateFactory.getInstance("X.509");
3665            if (factory == null) {
3666                Slog.e(TAG, "Error getting certificate factory");
3667                return;
3668            }
3669
3670            byte[] certBytes = keyStore.get(Credentials.USER_CERTIFICATE + client);
3671            if (certBytes != null) {
3672                Certificate cert = (X509Certificate) factory.generateCertificate(
3673                        new ByteArrayInputStream(certBytes));
3674
3675                if (cert != null) {
3676                    mNeedsSoftwareKeystore = hasHardwareBackedKey(cert);
3677
3678                    if (DBG) Slog.d(TAG, "Loaded client certificate " + Credentials
3679                            .USER_CERTIFICATE + client);
3680                    if (DBG) Slog.d(TAG, "It " + (mNeedsSoftwareKeystore ? "needs" :
3681                            "does not need" ) + " software key store");
3682                } else {
3683                    Slog.d(TAG, "could not generate certificate");
3684                }
3685            } else {
3686                Slog.e(TAG, "Could not load client certificate " + Credentials
3687                        .USER_CERTIFICATE + client);
3688                mNeedsSoftwareKeystore = true;
3689            }
3690
3691        } catch(CertificateException e) {
3692            Slog.e(TAG, "Could not read certificates");
3693            mCaCert = null;
3694            mClientCertificate = null;
3695        }
3696        */
3697
3698        return false;
3699    }
3700
3701    /** called when CS ask WiFistateMachine to disconnect the current network
3702     * because the score is bad.
3703     */
3704    void handleBadNetworkDisconnectReport(int netId, WifiInfo info) {
3705        /* TODO verify the bad network is current */
3706        WifiConfiguration config = mConfiguredNetworks.get(netId);
3707        if (config != null) {
3708            if ((info.getRssi() < WifiConfiguration.UNWANTED_BLACKLIST_SOFT_RSSI_24
3709                    && info.is24GHz()) || (info.getRssi() <
3710                            WifiConfiguration.UNWANTED_BLACKLIST_SOFT_RSSI_5 && info.is5GHz())) {
3711                // We got disconnected and RSSI was bad, so disable light
3712                config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_TEMPORARY_DISABLED
3713                        + WifiConfiguration.UNWANTED_BLACKLIST_SOFT_BUMP);
3714                loge("handleBadNetworkDisconnectReport (+4) "
3715                        + Integer.toString(netId) + " " + info);
3716            } else {
3717                // We got disabled but RSSI is good, so disable hard
3718                config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_TEMPORARY_DISABLED
3719                        + WifiConfiguration.UNWANTED_BLACKLIST_HARD_BUMP);
3720                loge("handleBadNetworkDisconnectReport (+8) "
3721                        + Integer.toString(netId) + " " + info);
3722            }
3723        }
3724    }
3725
3726    boolean handleBSSIDBlackList(int netId, String BSSID, boolean enable) {
3727        boolean found = false;
3728        if (BSSID == null)
3729            return found;
3730
3731        // Look for the BSSID in our config store
3732        for (WifiConfiguration config : mConfiguredNetworks.values()) {
3733            if (config.scanResultCache != null) {
3734                for (ScanResult result: config.scanResultCache.values()) {
3735                    if (result.BSSID.equals(BSSID)) {
3736                        if (enable) {
3737                            result.setAutoJoinStatus(ScanResult.ENABLED);
3738                        } else {
3739                            // Black list the BSSID we were trying to join
3740                            // so as the Roam state machine
3741                            // doesn't pick it up over and over
3742                            result.setAutoJoinStatus(ScanResult.AUTO_ROAM_DISABLED);
3743                            found = true;
3744                        }
3745                    }
3746                }
3747            }
3748        }
3749        return found;
3750    }
3751
3752    int getMaxDhcpRetries() {
3753        return Settings.Global.getInt(mContext.getContentResolver(),
3754                Settings.Global.WIFI_MAX_DHCP_RETRY_COUNT,
3755                DEFAULT_MAX_DHCP_RETRIES);
3756    }
3757
3758    void handleSSIDStateChange(int netId, boolean enabled, String message, String BSSID) {
3759        WifiConfiguration config = mConfiguredNetworks.get(netId);
3760        if (config != null) {
3761            if (enabled) {
3762                loge("SSID re-enabled for  " + config.configKey() +
3763                        " had autoJoinStatus=" + Integer.toString(config.autoJoinStatus)
3764                        + " self added " + config.selfAdded + " ephemeral " + config.ephemeral);
3765                //TODO: http://b/16381983 Fix Wifi Network Blacklisting
3766                //TODO: really I don't know if re-enabling is right but we
3767                //TODO: should err on the side of trying to connect
3768                //TODO: even if the attempt will fail
3769                if (config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE) {
3770                    config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED);
3771                }
3772            } else {
3773                loge("SSID temp disabled for  " + config.configKey() +
3774                        " had autoJoinStatus=" + Integer.toString(config.autoJoinStatus)
3775                        + " self added " + config.selfAdded + " ephemeral " + config.ephemeral);
3776                if (message != null) {
3777                    loge(" message=" + message);
3778                }
3779                if (config.selfAdded && config.lastConnected == 0) {
3780                    // This is a network we self added, and we never succeeded,
3781                    // the user did not create this network and never entered its credentials,
3782                    // so we want to be very aggressive in disabling it completely.
3783                    removeConfigAndSendBroadcastIfNeeded(config.networkId);
3784                } else {
3785                    if (message != null) {
3786                        if (message.contains("no identity")) {
3787                            config.setAutoJoinStatus(
3788                                    WifiConfiguration.AUTO_JOIN_DISABLED_NO_CREDENTIALS);
3789                            if (DBG) {
3790                                loge("no identity blacklisted " + config.configKey() + " to "
3791                                        + Integer.toString(config.autoJoinStatus));
3792                            }
3793                        } else if (message.contains("WRONG_KEY")
3794                                || message.contains("AUTH_FAILED")) {
3795                            // This configuration has received an auth failure, so disable it
3796                            // temporarily because we don't want auto-join to try it out.
3797                            // this network may be re-enabled by the "usual"
3798                            // enableAllNetwork function
3799                            config.numAuthFailures++;
3800                            if (config.numAuthFailures > maxAuthErrorsToBlacklist) {
3801                                config.setAutoJoinStatus
3802                                        (WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE);
3803                                disableNetwork(netId,
3804                                        WifiConfiguration.DISABLED_AUTH_FAILURE);
3805                                loge("Authentication failure, blacklist " + config.configKey() + " "
3806                                            + Integer.toString(config.networkId)
3807                                            + " num failures " + config.numAuthFailures);
3808                            }
3809                        } else if (message.contains("DHCP FAILURE")) {
3810                            config.numIpConfigFailures++;
3811                            config.lastConnectionFailure = System.currentTimeMillis();
3812                            int maxRetries = getMaxDhcpRetries();
3813                            // maxRetries == 0 means keep trying forever
3814                            if (maxRetries > 0 && config.numIpConfigFailures > maxRetries) {
3815                                /**
3816                                 * If we've exceeded the maximum number of retries for DHCP
3817                                 * to a given network, disable the network
3818                                 */
3819                                config.setAutoJoinStatus
3820                                        (WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE);
3821                                disableNetwork(netId, WifiConfiguration.DISABLED_DHCP_FAILURE);
3822                                loge("DHCP failure, blacklist " + config.configKey() + " "
3823                                        + Integer.toString(config.networkId)
3824                                        + " num failures " + config.numIpConfigFailures);
3825                            }
3826
3827                            // Also blacklist the BSSId if we find it
3828                            ScanResult result = null;
3829                            String bssidDbg = "";
3830                            if (config.scanResultCache != null && BSSID != null) {
3831                                result = config.scanResultCache.get(BSSID);
3832                            }
3833                            if (result != null) {
3834                                result.numIpConfigFailures ++;
3835                                bssidDbg = BSSID + " ipfail=" + result.numIpConfigFailures;
3836                                if (result.numIpConfigFailures > 3) {
3837                                    // Tell supplicant to stop trying this BSSID
3838                                    mWifiNative.addToBlacklist(BSSID);
3839                                    result.setAutoJoinStatus(ScanResult.AUTO_JOIN_DISABLED);
3840                                }
3841                            }
3842
3843                            if (DBG) {
3844                                loge("blacklisted " + config.configKey() + " to "
3845                                        + config.autoJoinStatus
3846                                        + " due to IP config failures, count="
3847                                        + config.numIpConfigFailures
3848                                        + " disableReason=" + config.disableReason
3849                                        + " " + bssidDbg);
3850                            }
3851                        } else if (message.contains("CONN_FAILED")) {
3852                            config.numConnectionFailures++;
3853                            if (config.numConnectionFailures > maxConnectionErrorsToBlacklist) {
3854                                config.setAutoJoinStatus
3855                                        (WifiConfiguration.AUTO_JOIN_DISABLED_ON_AUTH_FAILURE);
3856                                disableNetwork(netId,
3857                                        WifiConfiguration.DISABLED_ASSOCIATION_REJECT);
3858                                loge("Connection failure, blacklist " + config.configKey() + " "
3859                                        + config.networkId
3860                                        + " num failures " + config.numConnectionFailures);
3861                            }
3862                        }
3863                        message.replace("\n", "");
3864                        message.replace("\r", "");
3865                        config.lastFailure = message;
3866                    }
3867                }
3868            }
3869        }
3870    }
3871
3872    boolean installKeys(WifiEnterpriseConfig config, String name) {
3873        boolean ret = true;
3874        String privKeyName = Credentials.USER_PRIVATE_KEY + name;
3875        String userCertName = Credentials.USER_CERTIFICATE + name;
3876        String caCertName = Credentials.CA_CERTIFICATE + name;
3877        if (config.getClientCertificate() != null) {
3878            byte[] privKeyData = config.getClientPrivateKey().getEncoded();
3879            if (isHardwareBackedKey(config.getClientPrivateKey())) {
3880                // Hardware backed key store is secure enough to store keys un-encrypted, this
3881                // removes the need for user to punch a PIN to get access to these keys
3882                if (DBG) Log.d(TAG, "importing keys " + name + " in hardware backed store");
3883                ret = mKeyStore.importKey(privKeyName, privKeyData, android.os.Process.WIFI_UID,
3884                        KeyStore.FLAG_NONE);
3885            } else {
3886                // Software backed key store is NOT secure enough to store keys un-encrypted.
3887                // Save keys encrypted so they are protected with user's PIN. User will
3888                // have to unlock phone before being able to use these keys and connect to
3889                // networks.
3890                if (DBG) Log.d(TAG, "importing keys " + name + " in software backed store");
3891                ret = mKeyStore.importKey(privKeyName, privKeyData, Process.WIFI_UID,
3892                        KeyStore.FLAG_ENCRYPTED);
3893            }
3894            if (ret == false) {
3895                return ret;
3896            }
3897
3898            ret = putCertInKeyStore(userCertName, config.getClientCertificate());
3899            if (ret == false) {
3900                // Remove private key installed
3901                mKeyStore.delKey(privKeyName, Process.WIFI_UID);
3902                return ret;
3903            }
3904        }
3905
3906        if (config.getCaCertificate() != null) {
3907            ret = putCertInKeyStore(caCertName, config.getCaCertificate());
3908            if (ret == false) {
3909                if (config.getClientCertificate() != null) {
3910                    // Remove client key+cert
3911                    mKeyStore.delKey(privKeyName, Process.WIFI_UID);
3912                    mKeyStore.delete(userCertName, Process.WIFI_UID);
3913                }
3914                return ret;
3915            }
3916        }
3917
3918        // Set alias names
3919        if (config.getClientCertificate() != null) {
3920            config.setClientCertificateAlias(name);
3921            config.resetClientKeyEntry();
3922        }
3923
3924        if (config.getCaCertificate() != null) {
3925            config.setCaCertificateAlias(name);
3926            config.resetCaCertificate();
3927        }
3928
3929        return ret;
3930    }
3931
3932    private boolean putCertInKeyStore(String name, Certificate cert) {
3933        try {
3934            byte[] certData = Credentials.convertToPem(cert);
3935            if (DBG) Log.d(TAG, "putting certificate " + name + " in keystore");
3936            return mKeyStore.put(name, certData, Process.WIFI_UID, KeyStore.FLAG_NONE);
3937
3938        } catch (IOException e1) {
3939            return false;
3940        } catch (CertificateException e2) {
3941            return false;
3942        }
3943    }
3944
3945    void removeKeys(WifiEnterpriseConfig config) {
3946        String client = config.getClientCertificateAlias();
3947        // a valid client certificate is configured
3948        if (!TextUtils.isEmpty(client)) {
3949            if (DBG) Log.d(TAG, "removing client private key and user cert");
3950            mKeyStore.delKey(Credentials.USER_PRIVATE_KEY + client, Process.WIFI_UID);
3951            mKeyStore.delete(Credentials.USER_CERTIFICATE + client, Process.WIFI_UID);
3952        }
3953
3954        String ca = config.getCaCertificateAlias();
3955        // a valid ca certificate is configured
3956        if (!TextUtils.isEmpty(ca)) {
3957            if (DBG) Log.d(TAG, "removing CA cert");
3958            mKeyStore.delete(Credentials.CA_CERTIFICATE + ca, Process.WIFI_UID);
3959        }
3960    }
3961
3962
3963    /** Migrates the old style TLS config to the new config style. This should only be used
3964     * when restoring an old wpa_supplicant.conf or upgrading from a previous
3965     * platform version.
3966     * @return true if the config was updated
3967     * @hide
3968     */
3969    boolean migrateOldEapTlsNative(WifiEnterpriseConfig config, int netId) {
3970        String oldPrivateKey = mWifiNative.getNetworkVariable(netId, OLD_PRIVATE_KEY_NAME);
3971        /*
3972         * If the old configuration value is not present, then there is nothing
3973         * to do.
3974         */
3975        if (TextUtils.isEmpty(oldPrivateKey)) {
3976            return false;
3977        } else {
3978            // Also ignore it if it's empty quotes.
3979            oldPrivateKey = removeDoubleQuotes(oldPrivateKey);
3980            if (TextUtils.isEmpty(oldPrivateKey)) {
3981                return false;
3982            }
3983        }
3984
3985        config.setFieldValue(WifiEnterpriseConfig.ENGINE_KEY, WifiEnterpriseConfig.ENGINE_ENABLE);
3986        config.setFieldValue(WifiEnterpriseConfig.ENGINE_ID_KEY,
3987                WifiEnterpriseConfig.ENGINE_ID_KEYSTORE);
3988
3989        /*
3990        * The old key started with the keystore:// URI prefix, but we don't
3991        * need that anymore. Trim it off if it exists.
3992        */
3993        final String keyName;
3994        if (oldPrivateKey.startsWith(WifiEnterpriseConfig.KEYSTORE_URI)) {
3995            keyName = new String(
3996                    oldPrivateKey.substring(WifiEnterpriseConfig.KEYSTORE_URI.length()));
3997        } else {
3998            keyName = oldPrivateKey;
3999        }
4000        config.setFieldValue(WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY, keyName);
4001
4002        mWifiNative.setNetworkVariable(netId, WifiEnterpriseConfig.ENGINE_KEY,
4003                config.getFieldValue(WifiEnterpriseConfig.ENGINE_KEY, ""));
4004
4005        mWifiNative.setNetworkVariable(netId, WifiEnterpriseConfig.ENGINE_ID_KEY,
4006                config.getFieldValue(WifiEnterpriseConfig.ENGINE_ID_KEY, ""));
4007
4008        mWifiNative.setNetworkVariable(netId, WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY,
4009                config.getFieldValue(WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY, ""));
4010
4011        // Remove old private_key string so we don't run this again.
4012        mWifiNative.setNetworkVariable(netId, OLD_PRIVATE_KEY_NAME, EMPTY_VALUE);
4013
4014        return true;
4015    }
4016
4017    /** Migrate certs from global pool to wifi UID if not already done */
4018    void migrateCerts(WifiEnterpriseConfig config) {
4019        String client = config.getClientCertificateAlias();
4020        // a valid client certificate is configured
4021        if (!TextUtils.isEmpty(client)) {
4022            if (!mKeyStore.contains(Credentials.USER_PRIVATE_KEY + client, Process.WIFI_UID)) {
4023                mKeyStore.duplicate(Credentials.USER_PRIVATE_KEY + client, -1,
4024                        Credentials.USER_PRIVATE_KEY + client, Process.WIFI_UID);
4025                mKeyStore.duplicate(Credentials.USER_CERTIFICATE + client, -1,
4026                        Credentials.USER_CERTIFICATE + client, Process.WIFI_UID);
4027            }
4028        }
4029
4030        String ca = config.getCaCertificateAlias();
4031        // a valid ca certificate is configured
4032        if (!TextUtils.isEmpty(ca)) {
4033            if (!mKeyStore.contains(Credentials.CA_CERTIFICATE + ca, Process.WIFI_UID)) {
4034                mKeyStore.duplicate(Credentials.CA_CERTIFICATE + ca, -1,
4035                        Credentials.CA_CERTIFICATE + ca, Process.WIFI_UID);
4036            }
4037        }
4038    }
4039
4040}
4041