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