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