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