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