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