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