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