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