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