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