WifiConfigManager.java revision a6b66a48b231f5729b8015d3446feb4c2fa0a9d1
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.content.pm.UserInfo;
29import android.net.IpConfiguration;
30import android.net.IpConfiguration.IpAssignment;
31import android.net.IpConfiguration.ProxySettings;
32import android.net.NetworkInfo.DetailedState;
33import android.net.ProxyInfo;
34import android.net.StaticIpConfiguration;
35import android.net.wifi.PasspointManagementObjectDefinition;
36import android.net.wifi.ScanResult;
37import android.net.wifi.WifiConfiguration;
38import android.net.wifi.WifiConfiguration.KeyMgmt;
39import android.net.wifi.WifiConfiguration.Status;
40import android.net.wifi.WifiEnterpriseConfig;
41import android.net.wifi.WifiInfo;
42import android.net.wifi.WifiManager;
43import android.net.wifi.WifiScanner;
44import android.net.wifi.WpsInfo;
45import android.net.wifi.WpsResult;
46import android.os.Environment;
47import android.os.RemoteException;
48import android.os.SystemClock;
49import android.os.UserHandle;
50import android.os.UserManager;
51import android.provider.Settings;
52import android.security.KeyStore;
53import android.text.TextUtils;
54import android.util.LocalLog;
55import android.util.Log;
56import android.util.SparseArray;
57
58import com.android.internal.R;
59import com.android.server.LocalServices;
60import com.android.server.net.DelayedDiskWrite;
61import com.android.server.net.IpConfigStore;
62import com.android.server.wifi.anqp.ANQPElement;
63import com.android.server.wifi.anqp.ANQPFactory;
64import com.android.server.wifi.anqp.Constants;
65import com.android.server.wifi.hotspot2.ANQPData;
66import com.android.server.wifi.hotspot2.AnqpCache;
67import com.android.server.wifi.hotspot2.IconEvent;
68import com.android.server.wifi.hotspot2.NetworkDetail;
69import com.android.server.wifi.hotspot2.PasspointMatch;
70import com.android.server.wifi.hotspot2.SupplicantBridge;
71import com.android.server.wifi.hotspot2.Utils;
72import com.android.server.wifi.hotspot2.omadm.PasspointManagementObjectManager;
73import com.android.server.wifi.hotspot2.pps.Credential;
74import com.android.server.wifi.hotspot2.pps.HomeSP;
75
76import org.xml.sax.SAXException;
77
78import java.io.BufferedReader;
79import java.io.DataOutputStream;
80import java.io.File;
81import java.io.FileDescriptor;
82import java.io.FileNotFoundException;
83import java.io.FileReader;
84import java.io.IOException;
85import java.io.PrintWriter;
86import java.security.cert.X509Certificate;
87import java.text.DateFormat;
88import java.util.ArrayList;
89import java.util.BitSet;
90import java.util.Calendar;
91import java.util.Collection;
92import java.util.Collections;
93import java.util.Comparator;
94import java.util.Date;
95import java.util.HashMap;
96import java.util.HashSet;
97import java.util.List;
98import java.util.Map;
99import java.util.Objects;
100import java.util.Set;
101import java.util.concurrent.ConcurrentHashMap;
102import java.util.concurrent.atomic.AtomicBoolean;
103import java.util.concurrent.atomic.AtomicInteger;
104import java.util.zip.CRC32;
105import java.util.zip.Checksum;
106
107
108/**
109 * This class provides the API to manage configured
110 * wifi networks. The API is not thread safe is being
111 * used only from WifiStateMachine.
112 *
113 * It deals with the following
114 * - Add/update/remove a WifiConfiguration
115 *   The configuration contains two types of information.
116 *     = IP and proxy configuration that is handled by WifiConfigManager and
117 *       is saved to disk on any change.
118 *
119 *       The format of configuration file is as follows:
120 *       <version>
121 *       <netA_key1><netA_value1><netA_key2><netA_value2>...<EOS>
122 *       <netB_key1><netB_value1><netB_key2><netB_value2>...<EOS>
123 *       ..
124 *
125 *       (key, value) pairs for a given network are grouped together and can
126 *       be in any order. A EOS at the end of a set of (key, value) pairs
127 *       indicates that the next set of (key, value) pairs are for a new
128 *       network. A network is identified by a unique ID_KEY. If there is no
129 *       ID_KEY in the (key, value) pairs, the data is discarded.
130 *
131 *       An invalid version on read would result in discarding the contents of
132 *       the file. On the next write, the latest version is written to file.
133 *
134 *       Any failures during read or write to the configuration file are ignored
135 *       without reporting to the user since the likelihood of these errors are
136 *       low and the impact on connectivity is low.
137 *
138 *     = SSID & security details that is pushed to the supplicant.
139 *       supplicant saves these details to the disk on calling
140 *       saveConfigCommand().
141 *
142 *       We have two kinds of APIs exposed:
143 *        > public API calls that provide fine grained control
144 *          - enableNetwork, disableNetwork, addOrUpdateNetwork(),
145 *          removeNetwork(). For these calls, the config is not persisted
146 *          to the disk. (TODO: deprecate these calls in WifiManager)
147 *        > The new API calls - selectNetwork(), saveNetwork() & forgetNetwork().
148 *          These calls persist the supplicant config to disk.
149 *
150 * - Maintain a list of configured networks for quick access
151 *
152 */
153public class WifiConfigManager {
154    private static boolean sVDBG = false;
155    private static boolean sVVDBG = false;
156    public static final String TAG = "WifiConfigManager";
157    public static final int MAX_TX_PACKET_FOR_FULL_SCANS = 8;
158    public static final int MAX_RX_PACKET_FOR_FULL_SCANS = 16;
159    public static final int MAX_TX_PACKET_FOR_PARTIAL_SCANS = 40;
160    public static final int MAX_RX_PACKET_FOR_PARTIAL_SCANS = 80;
161    public static final boolean ROAM_ON_ANY = false;
162    public static final int MAX_NUM_SCAN_CACHE_ENTRIES = 128;
163    private static final boolean DBG = true;
164    private static final String PPS_FILE = "/data/misc/wifi/PerProviderSubscription.conf";
165    private static final String IP_CONFIG_FILE =
166            Environment.getDataDirectory() + "/misc/wifi/ipconfig.txt";
167
168    // The Wifi verbose log is provided as a way to persist the verbose logging settings
169    // for testing purpose.
170    // It is not intended for normal use.
171    private static final String WIFI_VERBOSE_LOGS_KEY = "WIFI_VERBOSE_LOGS";
172
173    // As we keep deleted PSK WifiConfiguration for a while, the PSK of
174    // those deleted WifiConfiguration is set to this random unused PSK
175    private static final String DELETED_CONFIG_PSK = "Mjkd86jEMGn79KhKll298Uu7-deleted";
176
177    /**
178     * The maximum number of times we will retry a connection to an access point
179     * for which we have failed in acquiring an IP address from DHCP. A value of
180     * N means that we will make N+1 connection attempts in all.
181     * <p>
182     * See {@link Settings.Secure#WIFI_MAX_DHCP_RETRY_COUNT}. This is the default
183     * value if a Settings value is not present.
184     */
185    private static final int DEFAULT_MAX_DHCP_RETRIES = 9;
186
187    /**
188     * The threshold for each kind of error. If a network continuously encounter the same error more
189     * than the threshold times, this network will be disabled. -1 means unavailable.
190     */
191    private static final int[] NETWORK_SELECTION_DISABLE_THRESHOLD = {
192            -1, //  threshold for NETWORK_SELECTION_ENABLE
193            1,  //  threshold for DISABLED_BAD_LINK
194            5,  //  threshold for DISABLED_ASSOCIATION_REJECTION
195            5,  //  threshold for DISABLED_AUTHENTICATION_FAILURE
196            5,  //  threshold for DISABLED_DHCP_FAILURE
197            5,  //  threshold for DISABLED_DNS_FAILURE
198            6,  //  threshold for DISABLED_TLS_VERSION_MISMATCH
199            1,  //  threshold for DISABLED_AUTHENTICATION_NO_CREDENTIALS
200            1,  //  threshold for DISABLED_NO_INTERNET
201            1   //  threshold for DISABLED_BY_WIFI_MANAGER
202    };
203
204    /**
205     * Timeout for each kind of error. After the timeout minutes, unblock the network again.
206     */
207    private static final int[] NETWORK_SELECTION_DISABLE_TIMEOUT = {
208            Integer.MAX_VALUE,  // threshold for NETWORK_SELECTION_ENABLE
209            15,                 // threshold for DISABLED_BAD_LINK
210            5,                  // threshold for DISABLED_ASSOCIATION_REJECTION
211            5,                  // threshold for DISABLED_AUTHENTICATION_FAILURE
212            5,                  // threshold for DISABLED_DHCP_FAILURE
213            5,                  // threshold for DISABLED_DNS_FAILURE
214            Integer.MAX_VALUE,  // threshold for DISABLED_TLS_VERSION
215            Integer.MAX_VALUE,  // threshold for DISABLED_AUTHENTICATION_NO_CREDENTIALS
216            Integer.MAX_VALUE,  // threshold for DISABLED_NO_INTERNET
217            Integer.MAX_VALUE   // threshold for DISABLED_BY_WIFI_MANAGER
218    };
219
220    public final AtomicBoolean mEnableAutoJoinWhenAssociated = new AtomicBoolean();
221    public final AtomicBoolean mEnableFullBandScanWhenAssociated = new AtomicBoolean(true);
222    public final AtomicBoolean mEnableChipWakeUpWhenAssociated = new AtomicBoolean(true);
223    public final AtomicBoolean mEnableRssiPollWhenAssociated = new AtomicBoolean(true);
224    public final AtomicInteger mThresholdSaturatedRssi5 = new AtomicInteger();
225    public final AtomicInteger mThresholdQualifiedRssi24 = new AtomicInteger();
226    public final AtomicInteger mEnableVerboseLogging = new AtomicInteger(0);
227    public final AtomicInteger mAssociatedFullScanBackoff =
228            new AtomicInteger(); // Will be divided by 8 by WifiStateMachine
229    public final AtomicInteger mAlwaysEnableScansWhileAssociated = new AtomicInteger(0);
230    public final AtomicInteger mMaxNumActiveChannelsForPartialScans = new AtomicInteger();
231    public final AtomicInteger mWifiDisconnectedShortScanIntervalMs = new AtomicInteger();
232    public final AtomicInteger mWifiAssociatedShortScanIntervalMs = new AtomicInteger();
233
234    public boolean mEnableLinkDebouncing;
235    public boolean mEnableWifiCellularHandoverUserTriggeredAdjustment;
236    public int mAssociatedFullScanMaxIntervalMs;
237    public int mNetworkSwitchingBlackListPeriodMs;
238    public int mBadLinkSpeed24;
239    public int mBadLinkSpeed5;
240    public int mGoodLinkSpeed24;
241    public int mGoodLinkSpeed5;
242
243    // These fields are non-final for testing.
244    public AtomicInteger mThresholdQualifiedRssi5 = new AtomicInteger();
245    public AtomicInteger mThresholdMinimumRssi5 = new AtomicInteger();
246    public AtomicInteger mThresholdSaturatedRssi24 = new AtomicInteger();
247    public AtomicInteger mThresholdMinimumRssi24 = new AtomicInteger();
248    public AtomicInteger mCurrentNetworkBoost = new AtomicInteger();
249    public AtomicInteger mBandAward5Ghz = new AtomicInteger();
250
251    /**
252     * If Connectivity Service has triggered an unwanted network disconnect
253     */
254    public long mLastUnwantedNetworkDisconnectTimestamp = 0;
255
256    /**
257     * Framework keeps a list of ephemeral SSIDs that where deleted by user,
258     * so as, framework knows not to autojoin again those SSIDs based on scorer input.
259     * The list is never cleared up.
260     *
261     * The SSIDs are encoded in a String as per definition of WifiConfiguration.SSID field.
262     */
263    public Set<String> mDeletedEphemeralSSIDs = new HashSet<String>();
264
265    /* configured networks with network id as the key */
266    private final ConfigurationMap mConfiguredNetworks;
267
268    private final LocalLog mLocalLog;
269    private final KeyStore mKeyStore;
270    private final WifiNetworkHistory mWifiNetworkHistory;
271    private final WifiConfigStore mWifiConfigStore;
272    private final AnqpCache mAnqpCache;
273    private final SupplicantBridge mSupplicantBridge;
274    private final SupplicantBridgeCallbacks mSupplicantBridgeCallbacks;
275    private final PasspointManagementObjectManager mMOManager;
276    private final boolean mEnableOsuQueries;
277    private final SIMAccessor mSIMAccessor;
278    private final UserManager mUserManager;
279    private final Object mActiveScanDetailLock = new Object();
280
281    private Context mContext;
282    private FrameworkFacade mFacade;
283    private Clock mClock;
284    private IpConfigStore mIpconfigStore;
285    private DelayedDiskWrite mWriter;
286    private boolean mOnlyLinkSameCredentialConfigurations;
287    private boolean mShowNetworks = false;
288    private int mCurrentUserId = UserHandle.USER_SYSTEM;
289
290    /* Stores a map of NetworkId to ScanCache */
291    private ConcurrentHashMap<Integer, ScanDetailCache> mScanDetailCaches;
292
293    /* Tracks the highest priority of configured networks */
294    private int mLastPriority = -1;
295
296    /**
297     * The mLastSelectedConfiguration is used to remember which network
298     * was selected last by the user.
299     * The connection to this network may not be successful, as well
300     * the selection (i.e. network priority) might not be persisted.
301     * WiFi state machine is the only object that sets this variable.
302     */
303    private String mLastSelectedConfiguration = null;
304    private long mLastSelectedTimeStamp =
305            WifiConfiguration.NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP;
306
307    /*
308     * Lost config list, whenever we read a config from networkHistory.txt that was not in
309     * wpa_supplicant.conf
310     */
311    private HashSet<String> mLostConfigsDbg = new HashSet<String>();
312
313    private ScanDetail mActiveScanDetail;   // ScanDetail associated with active network
314
315    private class SupplicantBridgeCallbacks implements SupplicantBridge.SupplicantBridgeCallbacks {
316        @Override
317        public void notifyANQPResponse(ScanDetail scanDetail,
318                                       Map<Constants.ANQPElementType, ANQPElement> anqpElements) {
319            updateAnqpCache(scanDetail, anqpElements);
320            if (anqpElements == null || anqpElements.isEmpty()) {
321                return;
322            }
323            scanDetail.propagateANQPInfo(anqpElements);
324
325            Map<HomeSP, PasspointMatch> matches = matchNetwork(scanDetail, false);
326            Log.d(Utils.hs2LogTag(getClass()), scanDetail.getSSID() + " pass 2 matches: "
327                    + toMatchString(matches));
328
329            cacheScanResultForPasspointConfigs(scanDetail, matches, null);
330        }
331        @Override
332        public void notifyIconFailed(long bssid) {
333            Intent intent = new Intent(WifiManager.PASSPOINT_ICON_RECEIVED_ACTION);
334            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
335            intent.putExtra(WifiManager.EXTRA_PASSPOINT_ICON_BSSID, bssid);
336            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
337        }
338
339    }
340
341    WifiConfigManager(Context context, WifiNative wifiNative, FrameworkFacade facade, Clock clock,
342            UserManager userManager, KeyStore keyStore) {
343        mContext = context;
344        mFacade = facade;
345        mClock = clock;
346        mKeyStore = keyStore;
347        mUserManager = userManager;
348
349        if (mShowNetworks) {
350            mLocalLog = wifiNative.getLocalLog();
351        } else {
352            mLocalLog = null;
353        }
354
355        mWifiAssociatedShortScanIntervalMs.set(mContext.getResources().getInteger(
356                R.integer.config_wifi_associated_short_scan_interval));
357        mWifiDisconnectedShortScanIntervalMs.set(mContext.getResources().getInteger(
358                R.integer.config_wifi_disconnected_short_scan_interval));
359        mOnlyLinkSameCredentialConfigurations = mContext.getResources().getBoolean(
360                R.bool.config_wifi_only_link_same_credential_configurations);
361        mMaxNumActiveChannelsForPartialScans.set(mContext.getResources().getInteger(
362                R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels));
363        mAssociatedFullScanMaxIntervalMs = mContext.getResources().getInteger(
364                R.integer.config_wifi_framework_associated_full_scan_max_interval);
365        mAssociatedFullScanBackoff.set(mContext.getResources().getInteger(
366                R.integer.config_wifi_framework_associated_full_scan_backoff));
367        mEnableLinkDebouncing = mContext.getResources().getBoolean(
368                R.bool.config_wifi_enable_disconnection_debounce);
369        mBandAward5Ghz.set(mContext.getResources().getInteger(
370                R.integer.config_wifi_framework_5GHz_preference_boost_factor));
371        mThresholdMinimumRssi5.set(mContext.getResources().getInteger(
372                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_5GHz));
373        mThresholdQualifiedRssi5.set(mContext.getResources().getInteger(
374                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_5GHz));
375        mThresholdSaturatedRssi5.set(mContext.getResources().getInteger(
376                R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_5GHz));
377        mThresholdMinimumRssi24.set(mContext.getResources().getInteger(
378                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_24GHz));
379        mThresholdQualifiedRssi24.set(mContext.getResources().getInteger(
380                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_24GHz));
381        mThresholdSaturatedRssi24.set(mContext.getResources().getInteger(
382                R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_24GHz));
383        mEnableWifiCellularHandoverUserTriggeredAdjustment = mContext.getResources().getBoolean(
384                R.bool.config_wifi_framework_cellular_handover_enable_user_triggered_adjustment);
385        mBadLinkSpeed24 = mContext.getResources().getInteger(
386                R.integer.config_wifi_framework_wifi_score_bad_link_speed_24);
387        mBadLinkSpeed5 = mContext.getResources().getInteger(
388                R.integer.config_wifi_framework_wifi_score_bad_link_speed_5);
389        mGoodLinkSpeed24 = mContext.getResources().getInteger(
390                R.integer.config_wifi_framework_wifi_score_good_link_speed_24);
391        mGoodLinkSpeed5 = mContext.getResources().getInteger(
392                R.integer.config_wifi_framework_wifi_score_good_link_speed_5);
393        mEnableAutoJoinWhenAssociated.set(mContext.getResources().getBoolean(
394                R.bool.config_wifi_framework_enable_associated_network_selection));
395        mCurrentNetworkBoost.set(mContext.getResources().getInteger(
396                R.integer.config_wifi_framework_current_network_boost));
397        mNetworkSwitchingBlackListPeriodMs = mContext.getResources().getInteger(
398                R.integer.config_wifi_network_switching_blacklist_time);
399
400        boolean hs2on = mContext.getResources().getBoolean(R.bool.config_wifi_hotspot2_enabled);
401        Log.d(Utils.hs2LogTag(getClass()), "Passpoint is " + (hs2on ? "enabled" : "disabled"));
402
403        mConfiguredNetworks = new ConfigurationMap(userManager);
404        mMOManager = new PasspointManagementObjectManager(new File(PPS_FILE), hs2on);
405        mEnableOsuQueries = true;
406        mAnqpCache = new AnqpCache(mClock);
407        mSupplicantBridgeCallbacks = new SupplicantBridgeCallbacks();
408        mSupplicantBridge = new SupplicantBridge(wifiNative, mSupplicantBridgeCallbacks);
409        mScanDetailCaches = new ConcurrentHashMap<>(16, 0.75f, 2);
410        mSIMAccessor = new SIMAccessor(mContext);
411        mWriter = new DelayedDiskWrite();
412        mIpconfigStore = new IpConfigStore(mWriter);
413        mWifiNetworkHistory = new WifiNetworkHistory(context, mLocalLog, mWriter);
414        mWifiConfigStore =
415                new WifiConfigStore(wifiNative, mKeyStore, mLocalLog, mShowNetworks, true);
416    }
417
418    public void trimANQPCache(boolean all) {
419        mAnqpCache.clear(all, DBG);
420    }
421
422    void enableVerboseLogging(int verbose) {
423        mEnableVerboseLogging.set(verbose);
424        if (verbose > 0) {
425            sVDBG = true;
426            mShowNetworks = true;
427        } else {
428            sVDBG = false;
429        }
430        if (verbose > 1) {
431            sVVDBG = true;
432        } else {
433            sVVDBG = false;
434        }
435    }
436
437    /**
438     * Fetch the list of configured networks
439     * and enable all stored networks in supplicant.
440     */
441    void loadAndEnableAllNetworks() {
442        if (DBG) log("Loading config and enabling all networks ");
443        loadConfiguredNetworks();
444        enableAllNetworks();
445    }
446
447    int getConfiguredNetworksSize() {
448        return mConfiguredNetworks.sizeForCurrentUser();
449    }
450
451    /**
452     * Fetch the list of currently saved networks (i.e. all configured networks, excluding
453     * ephemeral networks).
454     * @param pskMap Map of preSharedKeys, keyed by the configKey of the configuration the
455     * preSharedKeys belong to
456     * @return List of networks
457     */
458    private List<WifiConfiguration> getSavedNetworks(Map<String, String> pskMap) {
459        List<WifiConfiguration> networks = new ArrayList<>();
460        for (WifiConfiguration config : mConfiguredNetworks.valuesForCurrentUser()) {
461            WifiConfiguration newConfig = new WifiConfiguration(config);
462            // When updating this condition, update WifiStateMachine's CONNECT_NETWORK handler to
463            // correctly handle updating existing configs that are filtered out here.
464            if (config.ephemeral) {
465                // Do not enumerate and return this configuration to anyone (e.g. WiFi Picker);
466                // treat it as unknown instead. This configuration can still be retrieved
467                // directly by its key or networkId.
468                continue;
469            }
470
471            if (pskMap != null && config.allowedKeyManagement != null
472                    && config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)
473                    && pskMap.containsKey(config.configKey(true))) {
474                newConfig.preSharedKey = pskMap.get(config.configKey(true));
475            }
476            networks.add(newConfig);
477        }
478        return networks;
479    }
480
481    /**
482     * This function returns all configuration, and is used for debug and creating bug reports.
483     */
484    private List<WifiConfiguration> getAllConfiguredNetworks() {
485        List<WifiConfiguration> networks = new ArrayList<>();
486        for (WifiConfiguration config : mConfiguredNetworks.valuesForCurrentUser()) {
487            WifiConfiguration newConfig = new WifiConfiguration(config);
488            networks.add(newConfig);
489        }
490        return networks;
491    }
492
493    /**
494     * Fetch the list of currently saved networks (i.e. all configured networks, excluding
495     * ephemeral networks).
496     * @return List of networks
497     */
498    public List<WifiConfiguration> getSavedNetworks() {
499        return getSavedNetworks(null);
500    }
501
502    /**
503     * Fetch the list of currently saved networks (i.e. all configured networks, excluding
504     * ephemeral networks), filled with real preSharedKeys.
505     * @return List of networks
506     */
507    List<WifiConfiguration> getPrivilegedSavedNetworks() {
508        Map<String, String> pskMap = getCredentialsByConfigKeyMap();
509        List<WifiConfiguration> configurations = getSavedNetworks(pskMap);
510        for (WifiConfiguration configuration : configurations) {
511            try {
512                configuration
513                        .setPasspointManagementObjectTree(mMOManager.getMOTree(configuration.FQDN));
514            } catch (IOException ioe) {
515                Log.w(TAG, "Failed to parse MO from " + configuration.FQDN + ": " + ioe);
516            }
517        }
518        return configurations;
519    }
520
521    /**
522     * Fetch the list of networkId's which are hidden in current user's configuration.
523     * @return List of networkIds
524     */
525    public Set<Integer> getHiddenConfiguredNetworkIds() {
526        return mConfiguredNetworks.getHiddenNetworkIdsForCurrentUser();
527    }
528
529    /**
530     * Find matching network for this scanResult
531     */
532    WifiConfiguration getMatchingConfig(ScanResult scanResult) {
533
534        for (Map.Entry entry : mScanDetailCaches.entrySet()) {
535            Integer netId = (Integer) entry.getKey();
536            ScanDetailCache cache = (ScanDetailCache) entry.getValue();
537            WifiConfiguration config = getWifiConfiguration(netId);
538            if (config == null) {
539                continue;
540            }
541            if (cache.get(scanResult.BSSID) != null) {
542                return config;
543            }
544        }
545
546        return null;
547    }
548
549    /**
550     * Fetch the preSharedKeys for all networks.
551     * @return a map from configKey to preSharedKey.
552     */
553    private Map<String, String> getCredentialsByConfigKeyMap() {
554        return readNetworkVariablesFromSupplicantFile("psk");
555    }
556
557    /**
558     * Fetch the list of currently saved networks (i.e. all configured networks, excluding
559     * ephemeral networks) that were recently seen.
560     *
561     * @param scanResultAgeMs The maximum age (in ms) of scan results for which we calculate the
562     * RSSI values
563     * @param copy If true, the returned list will contain copies of the configurations for the
564     * saved networks. Otherwise, the returned list will contain references to these
565     * configurations.
566     * @return List of networks
567     */
568    List<WifiConfiguration> getRecentSavedNetworks(int scanResultAgeMs, boolean copy) {
569        List<WifiConfiguration> networks = new ArrayList<WifiConfiguration>();
570
571        for (WifiConfiguration config : mConfiguredNetworks.valuesForCurrentUser()) {
572            if (config.ephemeral) {
573                // Do not enumerate and return this configuration to anyone (e.g. WiFi Picker);
574                // treat it as unknown instead. This configuration can still be retrieved
575                // directly by its key or networkId.
576                continue;
577            }
578
579            // Calculate the RSSI for scan results that are more recent than scanResultAgeMs.
580            ScanDetailCache cache = getScanDetailCache(config);
581            if (cache == null) {
582                continue;
583            }
584            config.setVisibility(cache.getVisibility(scanResultAgeMs));
585            if (config.visibility == null) {
586                continue;
587            }
588            if (config.visibility.rssi5 == WifiConfiguration.INVALID_RSSI
589                    && config.visibility.rssi24 == WifiConfiguration.INVALID_RSSI) {
590                continue;
591            }
592            if (copy) {
593                networks.add(new WifiConfiguration(config));
594            } else {
595                networks.add(config);
596            }
597        }
598        return networks;
599    }
600
601    /**
602     *  Update the configuration and BSSID with latest RSSI value.
603     */
604    void updateConfiguration(WifiInfo info) {
605        WifiConfiguration config = getWifiConfiguration(info.getNetworkId());
606        if (config != null && getScanDetailCache(config) != null) {
607            ScanDetail scanDetail = getScanDetailCache(config).getScanDetail(info.getBSSID());
608            if (scanDetail != null) {
609                ScanResult result = scanDetail.getScanResult();
610                long previousSeen = result.seen;
611                int previousRssi = result.level;
612
613                // Update the scan result
614                scanDetail.setSeen();
615                result.level = info.getRssi();
616
617                // Average the RSSI value
618                result.averageRssi(previousRssi, previousSeen,
619                        WifiQualifiedNetworkSelector.SCAN_RESULT_MAXIMUNM_AGE);
620                if (sVDBG) {
621                    loge("updateConfiguration freq=" + result.frequency
622                            + " BSSID=" + result.BSSID
623                            + " RSSI=" + result.level
624                            + " " + config.configKey());
625                }
626            }
627        }
628    }
629
630    /**
631     * get the Wificonfiguration for this netId
632     *
633     * @return Wificonfiguration
634     */
635    public WifiConfiguration getWifiConfiguration(int netId) {
636        return mConfiguredNetworks.getForCurrentUser(netId);
637    }
638
639    /**
640     * Get the Wificonfiguration for this key
641     * @return Wificonfiguration
642     */
643    public WifiConfiguration getWifiConfiguration(String key) {
644        return mConfiguredNetworks.getByConfigKeyForCurrentUser(key);
645    }
646
647    /**
648     * Enable all networks (if disabled time expire) and save config. This will be a no-op if the
649     * list of configured networks indicates all networks as being enabled
650     */
651    void enableAllNetworks() {
652        boolean networkEnabledStateChanged = false;
653
654        for (WifiConfiguration config : mConfiguredNetworks.valuesForCurrentUser()) {
655            if (config != null && !config.ephemeral
656                    && !config.getNetworkSelectionStatus().isNetworkEnabled()) {
657                if (tryEnableQualifiedNetwork(config)) {
658                    networkEnabledStateChanged = true;
659                }
660            }
661        }
662
663        if (networkEnabledStateChanged) {
664            saveConfig();
665            sendConfiguredNetworksChangedBroadcast();
666        }
667    }
668
669    private boolean setNetworkPriorityNative(WifiConfiguration config, int priority) {
670        return mWifiConfigStore.setNetworkPriority(config, priority);
671    }
672
673    private boolean setSSIDNative(WifiConfiguration config, String ssid) {
674        return mWifiConfigStore.setNetworkSSID(config, ssid);
675    }
676
677    public boolean updateLastConnectUid(WifiConfiguration config, int uid) {
678        if (config != null) {
679            if (config.lastConnectUid != uid) {
680                config.lastConnectUid = uid;
681                return true;
682            }
683        }
684        return false;
685    }
686
687    /**
688     * Selects the specified network for connection. This involves
689     * updating the priority of all the networks and enabling the given
690     * network while disabling others.
691     *
692     * Selecting a network will leave the other networks disabled and
693     * a call to enableAllNetworks() needs to be issued upon a connection
694     * or a failure event from supplicant
695     *
696     * @param config network to select for connection
697     * @param updatePriorities makes config highest priority network
698     * @return false if the network id is invalid
699     */
700    boolean selectNetwork(WifiConfiguration config, boolean updatePriorities, int uid) {
701        if (sVDBG) localLogNetwork("selectNetwork", config.networkId);
702        if (config.networkId == INVALID_NETWORK_ID) return false;
703        if (!WifiConfigurationUtil.isVisibleToAnyProfile(config,
704                mUserManager.getProfiles(mCurrentUserId))) {
705            loge("selectNetwork " + Integer.toString(config.networkId) + ": Network config is not "
706                    + "visible to current user.");
707            return false;
708        }
709
710        // Reset the priority of each network at start or if it goes too high.
711        if (mLastPriority == -1 || mLastPriority > 1000000) {
712            if (updatePriorities) {
713                for (WifiConfiguration config2 : mConfiguredNetworks.valuesForCurrentUser()) {
714                    if (config2.networkId != INVALID_NETWORK_ID) {
715                        setNetworkPriorityNative(config2, 0);
716                    }
717                }
718            }
719            mLastPriority = 0;
720        }
721
722        // Set to the highest priority and save the configuration.
723        if (updatePriorities) {
724            setNetworkPriorityNative(config, ++mLastPriority);
725        }
726
727        if (config.isPasspoint()) {
728            /* need to slap on the SSID of selected bssid to work */
729            if (getScanDetailCache(config).size() != 0) {
730                ScanDetail result = getScanDetailCache(config).getFirst();
731                if (result == null) {
732                    loge("Could not find scan result for " + config.BSSID);
733                } else {
734                    log("Setting SSID for " + config.networkId + " to" + result.getSSID());
735                    setSSIDNative(config, result.getSSID());
736                }
737
738            } else {
739                loge("Could not find bssid for " + config);
740            }
741        }
742
743        mWifiConfigStore.enableHS20(config.isPasspoint());
744
745        if (updatePriorities) {
746            saveConfig();
747        }
748
749        updateLastConnectUid(config, uid);
750
751        writeKnownNetworkHistory();
752
753        /* Enable the given network while disabling all other networks */
754        selectNetworkWithoutBroadcast(config.networkId);
755
756       /* Avoid saving the config & sending a broadcast to prevent settings
757        * from displaying a disabled list of networks */
758        return true;
759    }
760
761    /**
762     * Add/update the specified configuration and save config
763     *
764     * @param config WifiConfiguration to be saved
765     * @return network update result
766     */
767    NetworkUpdateResult saveNetwork(WifiConfiguration config, int uid) {
768        WifiConfiguration conf;
769
770        // A new network cannot have null SSID
771        if (config == null || (config.networkId == INVALID_NETWORK_ID && config.SSID == null)) {
772            return new NetworkUpdateResult(INVALID_NETWORK_ID);
773        }
774
775        if (!WifiConfigurationUtil.isVisibleToAnyProfile(config,
776                mUserManager.getProfiles(mCurrentUserId))) {
777            return new NetworkUpdateResult(INVALID_NETWORK_ID);
778        }
779
780        if (sVDBG) localLogNetwork("WifiConfigManager: saveNetwork netId", config.networkId);
781        if (sVDBG) {
782            logd("WifiConfigManager saveNetwork,"
783                    + " size=" + Integer.toString(mConfiguredNetworks.sizeForAllUsers())
784                    + " (for all users)"
785                    + " SSID=" + config.SSID
786                    + " Uid=" + Integer.toString(config.creatorUid)
787                    + "/" + Integer.toString(config.lastUpdateUid));
788        }
789
790        if (mDeletedEphemeralSSIDs.remove(config.SSID)) {
791            if (sVDBG) {
792                loge("WifiConfigManager: removed from ephemeral blacklist: " + config.SSID);
793            }
794            // NOTE: This will be flushed to disk as part of the addOrUpdateNetworkNative call
795            // below, since we're creating/modifying a config.
796        }
797
798        boolean newNetwork = (config.networkId == INVALID_NETWORK_ID);
799        NetworkUpdateResult result = addOrUpdateNetworkNative(config, uid);
800        int netId = result.getNetworkId();
801
802        if (sVDBG) localLogNetwork("WifiConfigManager: saveNetwork got it back netId=", netId);
803
804        conf = mConfiguredNetworks.getForCurrentUser(netId);
805        if (conf != null) {
806            if (!conf.getNetworkSelectionStatus().isNetworkEnabled()) {
807                if (sVDBG) localLog("WifiConfigManager: re-enabling: " + conf.SSID);
808
809                // reenable autojoin, since new information has been provided
810                updateNetworkSelectionStatus(netId,
811                        WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE);
812            }
813            if (sVDBG) {
814                loge("WifiConfigManager: saveNetwork got config back netId="
815                        + Integer.toString(netId)
816                        + " uid=" + Integer.toString(config.creatorUid));
817            }
818        }
819
820        saveConfig();
821        sendConfiguredNetworksChangedBroadcast(
822                conf,
823                result.isNewNetwork()
824                        ? WifiManager.CHANGE_REASON_ADDED
825                        : WifiManager.CHANGE_REASON_CONFIG_CHANGE);
826        return result;
827    }
828
829    void noteRoamingFailure(WifiConfiguration config, int reason) {
830        if (config == null) return;
831        config.lastRoamingFailure = System.currentTimeMillis();
832        config.roamingFailureBlackListTimeMilli =
833                2 * (config.roamingFailureBlackListTimeMilli + 1000);
834        if (config.roamingFailureBlackListTimeMilli > mNetworkSwitchingBlackListPeriodMs) {
835            config.roamingFailureBlackListTimeMilli = mNetworkSwitchingBlackListPeriodMs;
836        }
837        config.lastRoamingFailureReason = reason;
838    }
839
840    void saveWifiConfigBSSID(WifiConfiguration config, String bssid) {
841        mWifiConfigStore.setNetworkBSSID(config, bssid);
842    }
843
844
845    void updateStatus(int netId, DetailedState state) {
846        if (netId != INVALID_NETWORK_ID) {
847            WifiConfiguration config = mConfiguredNetworks.getForAllUsers(netId);
848            if (config == null) return;
849            switch (state) {
850                case CONNECTED:
851                    config.status = Status.CURRENT;
852                    //we successfully connected, hence remove the blacklist
853                    updateNetworkSelectionStatus(netId,
854                            WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE);
855                    break;
856                case DISCONNECTED:
857                    //If network is already disabled, keep the status
858                    if (config.status == Status.CURRENT) {
859                        config.status = Status.ENABLED;
860                    }
861                    break;
862                default:
863                    //do nothing, retain the existing state
864                    break;
865            }
866        }
867    }
868
869
870    /**
871     * Disable an ephemeral SSID for the purpose of auto-joining thru scored.
872     * This SSID will never be scored anymore.
873     * The only way to "un-disable it" is if the user create a network for that SSID and then
874     * forget it.
875     *
876     * @param ssid caller must ensure that the SSID passed thru this API match
877     *            the WifiConfiguration.SSID rules, and thus be surrounded by quotes.
878     * @return the {@link WifiConfiguration} corresponding to this SSID, if any, so that we can
879     *         disconnect if this is the current network.
880     */
881    WifiConfiguration disableEphemeralNetwork(String ssid) {
882        if (ssid == null) {
883            return null;
884        }
885
886        WifiConfiguration foundConfig = mConfiguredNetworks.getEphemeralForCurrentUser(ssid);
887
888        mDeletedEphemeralSSIDs.add(ssid);
889        loge("Forget ephemeral SSID " + ssid + " num=" + mDeletedEphemeralSSIDs.size());
890
891        if (foundConfig != null) {
892            loge("Found ephemeral config in disableEphemeralNetwork: " + foundConfig.networkId);
893        }
894
895        writeKnownNetworkHistory();
896        return foundConfig;
897    }
898
899    /**
900     * Forget the specified network and save config
901     *
902     * @param netId network to forget
903     * @return {@code true} if it succeeds, {@code false} otherwise
904     */
905    boolean forgetNetwork(int netId) {
906        if (mShowNetworks) localLogNetwork("forgetNetwork", netId);
907        if (!removeNetwork(netId)) {
908            loge("Failed to forget network " + netId);
909            return false;
910        }
911        saveConfig();
912        writeKnownNetworkHistory();
913        return true;
914    }
915
916    /**
917     * Add/update a network. Note that there is no saveConfig operation.
918     * This function is retained for compatibility with the public
919     * API. The more powerful saveNetwork() is used by the
920     * state machine
921     *
922     * @param config wifi configuration to add/update
923     * @return network Id
924     */
925    int addOrUpdateNetwork(WifiConfiguration config, int uid) {
926        if (config == null || !WifiConfigurationUtil.isVisibleToAnyProfile(config,
927                mUserManager.getProfiles(mCurrentUserId))) {
928            return WifiConfiguration.INVALID_NETWORK_ID;
929        }
930
931        if (mShowNetworks) localLogNetwork("addOrUpdateNetwork id=", config.networkId);
932        if (config.isPasspoint()) {
933            /* create a temporary SSID with providerFriendlyName */
934            Long csum = getChecksum(config.FQDN);
935            config.SSID = csum.toString();
936            config.enterpriseConfig.setDomainSuffixMatch(config.FQDN);
937        }
938
939        NetworkUpdateResult result = addOrUpdateNetworkNative(config, uid);
940        if (result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID) {
941            WifiConfiguration conf = mConfiguredNetworks.getForCurrentUser(result.getNetworkId());
942            if (conf != null) {
943                sendConfiguredNetworksChangedBroadcast(
944                        conf,
945                        result.isNewNetwork
946                                ? WifiManager.CHANGE_REASON_ADDED
947                                : WifiManager.CHANGE_REASON_CONFIG_CHANGE);
948            }
949        }
950
951        return result.getNetworkId();
952    }
953
954    public int addPasspointManagementObject(String managementObject) {
955        try {
956            mMOManager.addSP(managementObject);
957            return 0;
958        } catch (IOException | SAXException e) {
959            return -1;
960        }
961    }
962
963    public int modifyPasspointMo(String fqdn, List<PasspointManagementObjectDefinition> mos) {
964        try {
965            return mMOManager.modifySP(fqdn, mos);
966        } catch (IOException | SAXException e) {
967            return -1;
968        }
969    }
970
971    public boolean queryPasspointIcon(long bssid, String fileName) {
972        return mSupplicantBridge.doIconQuery(bssid, fileName);
973    }
974
975    public int matchProviderWithCurrentNetwork(String fqdn) {
976        ScanDetail scanDetail = null;
977        synchronized (mActiveScanDetailLock) {
978            scanDetail = mActiveScanDetail;
979        }
980        if (scanDetail == null) {
981            return PasspointMatch.None.ordinal();
982        }
983        HomeSP homeSP = mMOManager.getHomeSP(fqdn);
984        if (homeSP == null) {
985            return PasspointMatch.None.ordinal();
986        }
987
988        ANQPData anqpData = mAnqpCache.getEntry(scanDetail.getNetworkDetail());
989
990        Map<Constants.ANQPElementType, ANQPElement> anqpElements =
991                anqpData != null ? anqpData.getANQPElements() : null;
992
993        return homeSP.match(scanDetail.getNetworkDetail(), anqpElements, mSIMAccessor).ordinal();
994    }
995
996    /**
997     * General PnoNetwork list sorting algorithm:
998     * 1, Place the fully enabled networks first. Among the fully enabled networks,
999     * sort them in the oder determined by the return of |compareConfigurations| method
1000     * implementation.
1001     * 2. Next place all the temporarily disabled networks. Among the temporarily disabled
1002     * networks, sort them in the order determined by the return of |compareConfigurations| method
1003     * implementation.
1004     * 3. Place the permanently disabled networks last. The order among permanently disabled
1005     * networks doesn't matter.
1006     */
1007    private static class PnoListComparator implements Comparator<WifiConfiguration> {
1008
1009        public final int ENABLED_NETWORK_SCORE = 3;
1010        public final int TEMPORARY_DISABLED_NETWORK_SCORE = 2;
1011        public final int PERMANENTLY_DISABLED_NETWORK_SCORE = 1;
1012
1013        @Override
1014        public int compare(WifiConfiguration a, WifiConfiguration b) {
1015            int configAScore = getPnoNetworkSortScore(a);
1016            int configBScore = getPnoNetworkSortScore(b);
1017            if (configAScore == configBScore) {
1018                return compareConfigurations(a, b);
1019            } else {
1020                return Integer.compare(configBScore, configAScore);
1021            }
1022        }
1023
1024        // This needs to be implemented by the connected/disconnected PNO list comparator.
1025        public int compareConfigurations(WifiConfiguration a, WifiConfiguration b) {
1026            return 0;
1027        }
1028
1029        /**
1030         * Returns an integer representing a score for each configuration. The scores are assigned
1031         * based on the status of the configuration. The scores are assigned according to the order:
1032         * Fully enabled network > Temporarily disabled network > Permanently disabled network.
1033         */
1034        private int getPnoNetworkSortScore(WifiConfiguration config) {
1035            if (config.getNetworkSelectionStatus().isNetworkEnabled()) {
1036                return ENABLED_NETWORK_SCORE;
1037            } else if (config.getNetworkSelectionStatus().isNetworkTemporaryDisabled()) {
1038                return TEMPORARY_DISABLED_NETWORK_SCORE;
1039            } else {
1040                return PERMANENTLY_DISABLED_NETWORK_SCORE;
1041            }
1042        }
1043    }
1044
1045    /**
1046     * Disconnected PnoNetwork list sorting algorithm:
1047     * Place the configurations in descending order of their |numAssociation| values. If networks
1048     * have the same |numAssociation|, then sort them in descending order of their |priority|
1049     * values.
1050     */
1051    private static final PnoListComparator sDisconnectedPnoListComparator =
1052            new PnoListComparator() {
1053                @Override
1054                public int compareConfigurations(WifiConfiguration a, WifiConfiguration b) {
1055                    if (a.numAssociation != b.numAssociation) {
1056                        return Long.compare(b.numAssociation, a.numAssociation);
1057                    } else {
1058                        return Integer.compare(b.priority, a.priority);
1059                    }
1060                }
1061            };
1062
1063    /**
1064     * Retrieves an updated list of priorities for all the saved networks before
1065     * enabling disconnected PNO (wpa_supplicant based PNO).
1066     *
1067     * wpa_supplicant uses the priority of networks to build the list of SSID's to monitor
1068     * during PNO. If there are a lot of saved networks, this list will be truncated and we
1069     * might end up not connecting to the networks we use most frequently. So, We want the networks
1070     * to be re-sorted based on the relative |numAssociation| values.
1071     *
1072     * @return list of networks with updated priorities.
1073     */
1074    public ArrayList<WifiScanner.PnoSettings.PnoNetwork> retrieveDisconnectedPnoNetworkList() {
1075        return retrievePnoNetworkList(sDisconnectedPnoListComparator);
1076    }
1077
1078    /**
1079     * Connected PnoNetwork list sorting algorithm:
1080     * Place the configurations with |lastSeenInQualifiedNetworkSelection| set first. If networks
1081     * have the same value, then sort them in descending order of their |numAssociation|
1082     * values.
1083     */
1084    private static final PnoListComparator sConnectedPnoListComparator =
1085            new PnoListComparator() {
1086                @Override
1087                public int compareConfigurations(WifiConfiguration a, WifiConfiguration b) {
1088                    boolean isConfigALastSeen =
1089                            a.getNetworkSelectionStatus().getSeenInLastQualifiedNetworkSelection();
1090                    boolean isConfigBLastSeen =
1091                            b.getNetworkSelectionStatus().getSeenInLastQualifiedNetworkSelection();
1092                    if (isConfigALastSeen != isConfigBLastSeen) {
1093                        return Boolean.compare(isConfigBLastSeen, isConfigALastSeen);
1094                    } else {
1095                        return Long.compare(b.numAssociation, a.numAssociation);
1096                    }
1097                }
1098            };
1099
1100    /**
1101     * Retrieves an updated list of priorities for all the saved networks before
1102     * enabling connected PNO (HAL based ePno).
1103     *
1104     * @return list of networks with updated priorities.
1105     */
1106    public ArrayList<WifiScanner.PnoSettings.PnoNetwork> retrieveConnectedPnoNetworkList() {
1107        return retrievePnoNetworkList(sConnectedPnoListComparator);
1108    }
1109
1110    /**
1111     * Create a PnoNetwork object from the provided WifiConfiguration.
1112     * @param config Configuration corresponding to the network.
1113     * @param newPriority New priority to be assigned to the network.
1114     */
1115    private static WifiScanner.PnoSettings.PnoNetwork createPnoNetworkFromWifiConfiguration(
1116            WifiConfiguration config, int newPriority) {
1117        WifiScanner.PnoSettings.PnoNetwork pnoNetwork =
1118                new WifiScanner.PnoSettings.PnoNetwork(config.SSID);
1119        pnoNetwork.networkId = config.networkId;
1120        pnoNetwork.priority = newPriority;
1121        if (config.hiddenSSID) {
1122            pnoNetwork.flags |= WifiScanner.PnoSettings.PnoNetwork.FLAG_DIRECTED_SCAN;
1123        }
1124        pnoNetwork.flags |= WifiScanner.PnoSettings.PnoNetwork.FLAG_A_BAND;
1125        pnoNetwork.flags |= WifiScanner.PnoSettings.PnoNetwork.FLAG_G_BAND;
1126        if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
1127            pnoNetwork.authBitField |= WifiScanner.PnoSettings.PnoNetwork.AUTH_CODE_PSK;
1128        } else if (config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)
1129                || config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
1130            pnoNetwork.authBitField |= WifiScanner.PnoSettings.PnoNetwork.AUTH_CODE_EAPOL;
1131        } else {
1132            pnoNetwork.authBitField |= WifiScanner.PnoSettings.PnoNetwork.AUTH_CODE_OPEN;
1133        }
1134        return pnoNetwork;
1135    }
1136
1137    /**
1138     * Retrieves an updated list of priorities for all the saved networks before
1139     * enabling/disabling PNO.
1140     *
1141     * @param pnoListComparator The comparator to use for sorting networks
1142     * @return list of networks with updated priorities.
1143     */
1144    private ArrayList<WifiScanner.PnoSettings.PnoNetwork> retrievePnoNetworkList(
1145            PnoListComparator pnoListComparator) {
1146        ArrayList<WifiScanner.PnoSettings.PnoNetwork> pnoList = new ArrayList<>();
1147        ArrayList<WifiConfiguration> wifiConfigurations =
1148                new ArrayList<>(mConfiguredNetworks.valuesForCurrentUser());
1149        Collections.sort(wifiConfigurations, pnoListComparator);
1150        // Let's use the network list size as the highest priority and then go down from there.
1151        // So, the most frequently connected network has the highest priority now.
1152        int priority = wifiConfigurations.size();
1153        for (WifiConfiguration config : wifiConfigurations) {
1154            pnoList.add(createPnoNetworkFromWifiConfiguration(config, priority));
1155            priority--;
1156        }
1157        return pnoList;
1158    }
1159
1160    /**
1161     * Remove a network. Note that there is no saveConfig operation.
1162     * This function is retained for compatibility with the public
1163     * API. The more powerful forgetNetwork() is used by the
1164     * state machine for network removal
1165     *
1166     * @param netId network to be removed
1167     * @return {@code true} if it succeeds, {@code false} otherwise
1168     */
1169    boolean removeNetwork(int netId) {
1170        if (mShowNetworks) localLogNetwork("removeNetwork", netId);
1171        WifiConfiguration config = mConfiguredNetworks.getForCurrentUser(netId);
1172        if (!removeConfigAndSendBroadcastIfNeeded(config)) {
1173            return false;
1174        }
1175        if (config.isPasspoint()) {
1176            writePasspointConfigs(config.FQDN, null);
1177        }
1178        return true;
1179    }
1180
1181    private static Long getChecksum(String source) {
1182        Checksum csum = new CRC32();
1183        csum.update(source.getBytes(), 0, source.getBytes().length);
1184        return csum.getValue();
1185    }
1186
1187    private boolean removeConfigWithoutBroadcast(WifiConfiguration config) {
1188        if (config == null) {
1189            return false;
1190        }
1191        if (!mWifiConfigStore.removeNetwork(config)) {
1192            loge("Failed to remove network " + config.networkId);
1193            return false;
1194        }
1195        if (config.configKey().equals(mLastSelectedConfiguration)) {
1196            mLastSelectedConfiguration = null;
1197        }
1198        mConfiguredNetworks.remove(config.networkId);
1199        mScanDetailCaches.remove(config.networkId);
1200        return true;
1201    }
1202
1203    private boolean removeConfigAndSendBroadcastIfNeeded(WifiConfiguration config) {
1204        if (!removeConfigWithoutBroadcast(config)) {
1205            return false;
1206        }
1207        String key = config.configKey();
1208        if (sVDBG) {
1209            logd("removeNetwork " + " key=" + key + " config.id=" + config.networkId);
1210        }
1211        writeIpAndProxyConfigurations();
1212        sendConfiguredNetworksChangedBroadcast(config, WifiManager.CHANGE_REASON_REMOVED);
1213        if (!config.ephemeral) {
1214            removeUserSelectionPreference(key);
1215        }
1216        writeKnownNetworkHistory();
1217        return true;
1218    }
1219
1220    private void removeUserSelectionPreference(String configKey) {
1221        if (DBG) {
1222            Log.d(TAG, "removeUserSelectionPreference: key is " + configKey);
1223        }
1224        if (configKey == null) {
1225            return;
1226        }
1227        for (WifiConfiguration config : mConfiguredNetworks.valuesForCurrentUser()) {
1228            WifiConfiguration.NetworkSelectionStatus status = config.getNetworkSelectionStatus();
1229            String connectChoice = status.getConnectChoice();
1230            if (connectChoice != null && connectChoice.equals(configKey)) {
1231                Log.d(TAG, "remove connect choice:" + connectChoice + " from " + config.SSID
1232                        + " : " + config.networkId);
1233                status.setConnectChoice(null);
1234                status.setConnectChoiceTimestamp(WifiConfiguration.NetworkSelectionStatus
1235                            .INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP);
1236            }
1237        }
1238    }
1239
1240    /*
1241     * Remove all networks associated with an application
1242     *
1243     * @param packageName name of the package of networks to remove
1244     * @return {@code true} if all networks removed successfully, {@code false} otherwise
1245     */
1246    boolean removeNetworksForApp(ApplicationInfo app) {
1247        if (app == null || app.packageName == null) {
1248            return false;
1249        }
1250
1251        boolean success = true;
1252
1253        WifiConfiguration [] copiedConfigs =
1254                mConfiguredNetworks.valuesForCurrentUser().toArray(new WifiConfiguration[0]);
1255        for (WifiConfiguration config : copiedConfigs) {
1256            if (app.uid != config.creatorUid || !app.packageName.equals(config.creatorName)) {
1257                continue;
1258            }
1259            if (mShowNetworks) {
1260                localLog("Removing network " + config.SSID
1261                         + ", application \"" + app.packageName + "\" uninstalled"
1262                         + " from user " + UserHandle.getUserId(app.uid));
1263            }
1264            success &= removeNetwork(config.networkId);
1265        }
1266
1267        saveConfig();
1268
1269        return success;
1270    }
1271
1272    boolean removeNetworksForUser(int userId) {
1273        boolean success = true;
1274
1275        WifiConfiguration[] copiedConfigs =
1276                mConfiguredNetworks.valuesForAllUsers().toArray(new WifiConfiguration[0]);
1277        for (WifiConfiguration config : copiedConfigs) {
1278            if (userId != UserHandle.getUserId(config.creatorUid)) {
1279                continue;
1280            }
1281            success &= removeNetwork(config.networkId);
1282            if (mShowNetworks) {
1283                localLog("Removing network " + config.SSID
1284                        + ", user " + userId + " removed");
1285            }
1286        }
1287
1288        return success;
1289    }
1290
1291    /**
1292     * Enable a network. Note that there is no saveConfig operation.
1293     * This function is retained for compatibility with the public
1294     * API. The more powerful selectNetwork()/saveNetwork() is used by the
1295     * state machine for connecting to a network
1296     *
1297     * @param netId network to be enabled
1298     * @return {@code true} if it succeeds, {@code false} otherwise
1299     */
1300    boolean enableNetwork(int netId, boolean disableOthers, int uid) {
1301        WifiConfiguration config = mConfiguredNetworks.getForCurrentUser(netId);
1302        if (config == null) {
1303            return false;
1304        }
1305        boolean ret = true;
1306        if (disableOthers) {
1307            ret = selectNetworkWithoutBroadcast(netId);
1308            if (sVDBG) {
1309                localLogNetwork("enableNetwork(disableOthers=true, uid=" + uid + ") ", netId);
1310            }
1311            updateLastConnectUid(getWifiConfiguration(netId), uid);
1312
1313            writeKnownNetworkHistory();
1314            sendConfiguredNetworksChangedBroadcast();
1315        } else {
1316            if (sVDBG) localLogNetwork("enableNetwork(disableOthers=false) ", netId);
1317            WifiConfiguration enabledNetwork;
1318            synchronized (mConfiguredNetworks) {                     // !!! Useless synchronization!
1319                enabledNetwork = mConfiguredNetworks.getForCurrentUser(netId);
1320            }
1321            // check just in case the network was removed by someone else.
1322            if (enabledNetwork != null) {
1323                sendConfiguredNetworksChangedBroadcast(enabledNetwork,
1324                        WifiManager.CHANGE_REASON_CONFIG_CHANGE);
1325            }
1326        }
1327        return ret;
1328    }
1329
1330    boolean selectNetworkWithoutBroadcast(int netId) {
1331        return mWifiConfigStore.selectNetwork(
1332                mConfiguredNetworks.getForCurrentUser(netId),
1333                mConfiguredNetworks.valuesForCurrentUser());
1334    }
1335
1336    /**
1337     * Disable a network in wpa_supplicant.
1338     */
1339    boolean disableNetworkNative(WifiConfiguration config) {
1340        return mWifiConfigStore.disableNetwork(config);
1341    }
1342
1343    /**
1344     * Disable all networks in wpa_supplicant.
1345     */
1346    void disableAllNetworksNative() {
1347        mWifiConfigStore.disableAllNetworks(mConfiguredNetworks.valuesForCurrentUser());
1348    }
1349
1350    /**
1351     * Disable a network. Note that there is no saveConfig operation.
1352     * @param netId network to be disabled
1353     * @return {@code true} if it succeeds, {@code false} otherwise
1354     */
1355    boolean disableNetwork(int netId) {
1356        return mWifiConfigStore.disableNetwork(mConfiguredNetworks.getForCurrentUser(netId));
1357    }
1358
1359    /**
1360     * Update a network according to the update reason and its current state
1361     * @param netId The network ID of the network need update
1362     * @param reason The reason to update the network
1363     * @return false if no change made to the input configure file, can due to error or need not
1364     *         true the input config file has been changed
1365     */
1366    boolean updateNetworkSelectionStatus(int netId, int reason) {
1367        WifiConfiguration config = getWifiConfiguration(netId);
1368        return updateNetworkSelectionStatus(config, reason);
1369    }
1370
1371    /**
1372     * Update a network according to the update reason and its current state
1373     * @param config the network need update
1374     * @param reason The reason to update the network
1375     * @return false if no change made to the input configure file, can due to error or need not
1376     *         true the input config file has been changed
1377     */
1378    boolean updateNetworkSelectionStatus(WifiConfiguration config, int reason) {
1379        if (config == null) {
1380            return false;
1381        }
1382
1383        WifiConfiguration.NetworkSelectionStatus networkStatus = config.getNetworkSelectionStatus();
1384        if (reason == WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE) {
1385            updateNetworkStatus(config, WifiConfiguration.NetworkSelectionStatus
1386                    .NETWORK_SELECTION_ENABLE);
1387            localLog("Enable network:" + config.configKey());
1388            return true;
1389        }
1390
1391        networkStatus.incrementDisableReasonCounter(reason);
1392        if (DBG) {
1393            localLog("Network:" + config.SSID + "disable counter of "
1394                    + WifiConfiguration.NetworkSelectionStatus.getNetworkDisableReasonString(reason)
1395                    + " is: " + networkStatus.getDisableReasonCounter(reason) + "and threshold is: "
1396                    + NETWORK_SELECTION_DISABLE_THRESHOLD[reason]);
1397        }
1398
1399        if (networkStatus.getDisableReasonCounter(reason)
1400                >= NETWORK_SELECTION_DISABLE_THRESHOLD[reason]) {
1401            return updateNetworkStatus(config, reason);
1402        }
1403        return true;
1404    }
1405
1406    /**
1407     * Check the config. If it is temporarily disabled, check the disable time is expired or not, If
1408     * expired, enabled it again for qualified network selection.
1409     * @param networkId the id of the network to be checked for possible unblock (due to timeout)
1410     * @return true if network status has been changed
1411     *         false network status is not changed
1412     */
1413    boolean tryEnableQualifiedNetwork(int networkId) {
1414        WifiConfiguration config = getWifiConfiguration(networkId);
1415        if (config == null) {
1416            localLog("updateQualifiedNetworkstatus invalid network.");
1417            return false;
1418        }
1419        return tryEnableQualifiedNetwork(config);
1420    }
1421
1422    /**
1423     * Check the config. If it is temporarily disabled, check the disable is expired or not, If
1424     * expired, enabled it again for qualified network selection.
1425     * @param config network to be checked for possible unblock (due to timeout)
1426     * @return true if network status has been changed
1427     *         false network status is not changed
1428     */
1429    boolean tryEnableQualifiedNetwork(WifiConfiguration config) {
1430        WifiConfiguration.NetworkSelectionStatus networkStatus = config.getNetworkSelectionStatus();
1431        if (networkStatus.isNetworkTemporaryDisabled()) {
1432            //time difference in minutes
1433            long timeDifference = (System.currentTimeMillis()
1434                    - networkStatus.getDisableTime()) / 1000 / 60;
1435            if (timeDifference < 0 || timeDifference
1436                    >= NETWORK_SELECTION_DISABLE_TIMEOUT[
1437                    networkStatus.getNetworkSelectionDisableReason()]) {
1438                updateNetworkSelectionStatus(config.networkId,
1439                        networkStatus.NETWORK_SELECTION_ENABLE);
1440                return true;
1441            }
1442        }
1443        return false;
1444    }
1445
1446    /**
1447     * Update a network's status. Note that there is no saveConfig operation.
1448     * @param config network to be updated
1449     * @param reason reason code for updated
1450     * @return false if no change made to the input configure file, can due to error or need not
1451     *         true the input config file has been changed
1452     */
1453    boolean updateNetworkStatus(WifiConfiguration config, int reason) {
1454        localLog("updateNetworkStatus:" + (config == null ? null : config.SSID));
1455        if (config == null) {
1456            return false;
1457        }
1458
1459        WifiConfiguration.NetworkSelectionStatus networkStatus = config.getNetworkSelectionStatus();
1460        if (reason < 0 || reason >= WifiConfiguration.NetworkSelectionStatus
1461                .NETWORK_SELECTION_DISABLED_MAX) {
1462            localLog("Invalid Network disable reason:" + reason);
1463            return false;
1464        }
1465
1466        if (reason == WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE) {
1467            if (networkStatus.isNetworkEnabled()) {
1468                if (DBG) {
1469                    localLog("Need not change Qualified network Selection status since"
1470                            + " already enabled");
1471                }
1472                return false;
1473            }
1474            networkStatus.setNetworkSelectionStatus(WifiConfiguration.NetworkSelectionStatus
1475                    .NETWORK_SELECTION_ENABLED);
1476            networkStatus.setNetworkSelectionDisableReason(reason);
1477            networkStatus.setDisableTime(
1478                    WifiConfiguration.NetworkSelectionStatus
1479                    .INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP);
1480            networkStatus.clearDisableReasonCounter();
1481            String disableTime = DateFormat.getDateTimeInstance().format(new Date());
1482            if (DBG) {
1483                localLog("Re-enable network: " + config.SSID + " at " + disableTime);
1484            }
1485            sendConfiguredNetworksChangedBroadcast(config, WifiManager.CHANGE_REASON_CONFIG_CHANGE);
1486        } else {
1487            //disable the network
1488            if (networkStatus.isNetworkPermanentlyDisabled()) {
1489                //alreay permanent disable
1490                if (DBG) {
1491                    localLog("Do nothing. Alreay permanent disabled! "
1492                            + WifiConfiguration.NetworkSelectionStatus
1493                            .getNetworkDisableReasonString(reason));
1494                }
1495                return false;
1496            } else if (networkStatus.isNetworkTemporaryDisabled()
1497                    && reason < WifiConfiguration.NetworkSelectionStatus
1498                    .DISABLED_TLS_VERSION_MISMATCH) {
1499                //alreay temporarily disable
1500                if (DBG) {
1501                    localLog("Do nothing. Already temporarily disabled! "
1502                            + WifiConfiguration.NetworkSelectionStatus
1503                            .getNetworkDisableReasonString(reason));
1504                }
1505                return false;
1506            }
1507
1508            if (networkStatus.isNetworkEnabled()) {
1509                disableNetworkNative(config);
1510                sendConfiguredNetworksChangedBroadcast(config,
1511                        WifiManager.CHANGE_REASON_CONFIG_CHANGE);
1512                localLog("Disable network " + config.SSID + " reason:"
1513                        + WifiConfiguration.NetworkSelectionStatus
1514                        .getNetworkDisableReasonString(reason));
1515            }
1516            if (reason < WifiConfiguration.NetworkSelectionStatus.DISABLED_TLS_VERSION_MISMATCH) {
1517                networkStatus.setNetworkSelectionStatus(WifiConfiguration.NetworkSelectionStatus
1518                        .NETWORK_SELECTION_TEMPORARY_DISABLED);
1519                networkStatus.setDisableTime(System.currentTimeMillis());
1520            } else {
1521                networkStatus.setNetworkSelectionStatus(WifiConfiguration.NetworkSelectionStatus
1522                        .NETWORK_SELECTION_PERMANENTLY_DISABLED);
1523            }
1524            networkStatus.setNetworkSelectionDisableReason(reason);
1525            if (DBG) {
1526                String disableTime = DateFormat.getDateTimeInstance().format(new Date());
1527                localLog("Network:" + config.SSID + "Configure new status:"
1528                        + networkStatus.getNetworkStatusString() + " with reason:"
1529                        + networkStatus.getNetworkDisableReasonString() + " at: " + disableTime);
1530            }
1531        }
1532        return true;
1533    }
1534
1535    /**
1536     * Save the configured networks in supplicant to disk
1537     * @return {@code true} if it succeeds, {@code false} otherwise
1538     */
1539    boolean saveConfig() {
1540        return mWifiConfigStore.saveConfig();
1541    }
1542
1543    /**
1544     * Start WPS pin method configuration with pin obtained
1545     * from the access point
1546     * @param config WPS configuration
1547     * @return Wps result containing status and pin
1548     */
1549    WpsResult startWpsWithPinFromAccessPoint(WpsInfo config) {
1550        return mWifiConfigStore.startWpsWithPinFromAccessPoint(
1551                config, mConfiguredNetworks.valuesForCurrentUser());
1552    }
1553
1554    /**
1555     * Start WPS pin method configuration with obtained
1556     * from the device
1557     * @return WpsResult indicating status and pin
1558     */
1559    WpsResult startWpsWithPinFromDevice(WpsInfo config) {
1560        return mWifiConfigStore.startWpsWithPinFromDevice(
1561            config, mConfiguredNetworks.valuesForCurrentUser());
1562    }
1563
1564    /**
1565     * Start WPS push button configuration
1566     * @param config WPS configuration
1567     * @return WpsResult indicating status and pin
1568     */
1569    WpsResult startWpsPbc(WpsInfo config) {
1570        return mWifiConfigStore.startWpsPbc(
1571            config, mConfiguredNetworks.valuesForCurrentUser());
1572    }
1573
1574    /**
1575     * Fetch the static IP configuration for a given network id
1576     */
1577    StaticIpConfiguration getStaticIpConfiguration(int netId) {
1578        WifiConfiguration config = mConfiguredNetworks.getForCurrentUser(netId);
1579        if (config != null) {
1580            return config.getStaticIpConfiguration();
1581        }
1582        return null;
1583    }
1584
1585    /**
1586     * Set the static IP configuration for a given network id
1587     */
1588    void setStaticIpConfiguration(int netId, StaticIpConfiguration staticIpConfiguration) {
1589        WifiConfiguration config = mConfiguredNetworks.getForCurrentUser(netId);
1590        if (config != null) {
1591            config.setStaticIpConfiguration(staticIpConfiguration);
1592        }
1593    }
1594
1595    /**
1596     * set default GW MAC address
1597     */
1598    void setDefaultGwMacAddress(int netId, String macAddress) {
1599        WifiConfiguration config = mConfiguredNetworks.getForCurrentUser(netId);
1600        if (config != null) {
1601            //update defaultGwMacAddress
1602            config.defaultGwMacAddress = macAddress;
1603        }
1604    }
1605
1606
1607    /**
1608     * Fetch the proxy properties for a given network id
1609     * @param netId id
1610     * @return ProxyInfo for the network id
1611     */
1612    ProxyInfo getProxyProperties(int netId) {
1613        WifiConfiguration config = mConfiguredNetworks.getForCurrentUser(netId);
1614        if (config != null) {
1615            return config.getHttpProxy();
1616        }
1617        return null;
1618    }
1619
1620    /**
1621     * Return if the specified network is using static IP
1622     * @param netId id
1623     * @return {@code true} if using static ip for netId
1624     */
1625    boolean isUsingStaticIp(int netId) {
1626        WifiConfiguration config = mConfiguredNetworks.getForCurrentUser(netId);
1627        if (config != null && config.getIpAssignment() == IpAssignment.STATIC) {
1628            return true;
1629        }
1630        return false;
1631    }
1632
1633    boolean isEphemeral(int netId) {
1634        WifiConfiguration config = mConfiguredNetworks.getForCurrentUser(netId);
1635        return config != null && config.ephemeral;
1636    }
1637
1638    boolean getMeteredHint(int netId) {
1639        WifiConfiguration config = mConfiguredNetworks.getForCurrentUser(netId);
1640        return config != null && config.meteredHint;
1641    }
1642
1643    /**
1644     * Should be called when a single network configuration is made.
1645     * @param network The network configuration that changed.
1646     * @param reason The reason for the change, should be one of WifiManager.CHANGE_REASON_ADDED,
1647     * WifiManager.CHANGE_REASON_REMOVED, or WifiManager.CHANGE_REASON_CHANGE.
1648     */
1649    private void sendConfiguredNetworksChangedBroadcast(WifiConfiguration network,
1650            int reason) {
1651        Intent intent = new Intent(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
1652        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1653        intent.putExtra(WifiManager.EXTRA_MULTIPLE_NETWORKS_CHANGED, false);
1654        intent.putExtra(WifiManager.EXTRA_WIFI_CONFIGURATION, network);
1655        intent.putExtra(WifiManager.EXTRA_CHANGE_REASON, reason);
1656        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1657    }
1658
1659    /**
1660     * Should be called when multiple network configuration changes are made.
1661     */
1662    private void sendConfiguredNetworksChangedBroadcast() {
1663        Intent intent = new Intent(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
1664        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1665        intent.putExtra(WifiManager.EXTRA_MULTIPLE_NETWORKS_CHANGED, true);
1666        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1667    }
1668
1669    void loadConfiguredNetworks() {
1670
1671        final Map<String, WifiConfiguration> configs = new HashMap<>();
1672        final SparseArray<Map<String, String>> networkExtras = new SparseArray<>();
1673        mLastPriority = mWifiConfigStore.loadNetworks(configs, networkExtras);
1674
1675        readNetworkHistory(configs);
1676        readPasspointConfig(configs, networkExtras);
1677
1678        // We are only now updating mConfiguredNetworks for two reasons:
1679        // 1) The information required to compute configKeys is spread across wpa_supplicant.conf
1680        //    and networkHistory.txt. Thus, we had to load both files first.
1681        // 2) mConfiguredNetworks caches a Passpoint network's FQDN the moment the network is added.
1682        //    Thus, we had to load the FQDNs first.
1683        mConfiguredNetworks.clear();
1684        for (Map.Entry<String, WifiConfiguration> entry : configs.entrySet()) {
1685            final String configKey = entry.getKey();
1686            final WifiConfiguration config = entry.getValue();
1687            if (!configKey.equals(config.configKey())) {
1688                if (mShowNetworks) {
1689                    log("Ignoring network " + config.networkId + " because the configKey loaded "
1690                            + "from wpa_supplicant.conf is not valid.");
1691                }
1692                mWifiConfigStore.removeNetwork(config);
1693                continue;
1694            }
1695            mConfiguredNetworks.put(config);
1696        }
1697
1698        readIpAndProxyConfigurations();
1699
1700        sendConfiguredNetworksChangedBroadcast();
1701
1702        if (mShowNetworks) {
1703            localLog("loadConfiguredNetworks loaded " + mConfiguredNetworks.sizeForAllUsers()
1704                    + " networks (for all users)");
1705        }
1706
1707        if (mConfiguredNetworks.sizeForAllUsers() == 0) {
1708            // no networks? Lets log if the file contents
1709            logKernelTime();
1710            logContents(WifiConfigStore.SUPPLICANT_CONFIG_FILE);
1711            logContents(WifiConfigStore.SUPPLICANT_CONFIG_FILE_BACKUP);
1712            logContents(WifiNetworkHistory.NETWORK_HISTORY_CONFIG_FILE);
1713        }
1714    }
1715
1716    private void logContents(String file) {
1717        localLogAndLogcat("--- Begin " + file + " ---");
1718        BufferedReader reader = null;
1719        try {
1720            reader = new BufferedReader(new FileReader(file));
1721            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
1722                localLogAndLogcat(line);
1723            }
1724        } catch (FileNotFoundException e) {
1725            localLog("Could not open " + file + ", " + e);
1726            Log.w(TAG, "Could not open " + file + ", " + e);
1727        } catch (IOException e) {
1728            localLog("Could not read " + file + ", " + e);
1729            Log.w(TAG, "Could not read " + file + ", " + e);
1730        } finally {
1731            try {
1732                if (reader != null) {
1733                    reader.close();
1734                }
1735            } catch (IOException e) {
1736                // Just ignore the fact that we couldn't close
1737            }
1738        }
1739        localLogAndLogcat("--- End " + file + " Contents ---");
1740    }
1741
1742    private Map<String, String> readNetworkVariablesFromSupplicantFile(String key) {
1743        return mWifiConfigStore.readNetworkVariablesFromSupplicantFile(key);
1744    }
1745
1746    private String readNetworkVariableFromSupplicantFile(String configKey, String key) {
1747        long start = SystemClock.elapsedRealtimeNanos();
1748        Map<String, String> data = mWifiConfigStore.readNetworkVariablesFromSupplicantFile(key);
1749        long end = SystemClock.elapsedRealtimeNanos();
1750
1751        if (sVDBG) {
1752            localLog("readNetworkVariableFromSupplicantFile configKey=[" + configKey + "] key="
1753                    + key + " duration=" + (long) (end - start));
1754        }
1755        return data.get(configKey);
1756    }
1757
1758    boolean needsUnlockedKeyStore() {
1759
1760        // Any network using certificates to authenticate access requires
1761        // unlocked key store; unless the certificates can be stored with
1762        // hardware encryption
1763
1764        for (WifiConfiguration config : mConfiguredNetworks.valuesForCurrentUser()) {
1765
1766            if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP)
1767                    && config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
1768
1769                if (needsSoftwareBackedKeyStore(config.enterpriseConfig)) {
1770                    return true;
1771                }
1772            }
1773        }
1774
1775        return false;
1776    }
1777
1778    void readPasspointConfig(Map<String, WifiConfiguration> configs,
1779            SparseArray<Map<String, String>> networkExtras) {
1780        List<HomeSP> homeSPs;
1781        try {
1782            homeSPs = mMOManager.loadAllSPs();
1783        } catch (IOException e) {
1784            loge("Could not read " + PPS_FILE + " : " + e);
1785            return;
1786        }
1787
1788        int matchedConfigs = 0;
1789        for (HomeSP homeSp : homeSPs) {
1790            String fqdn = homeSp.getFQDN();
1791            Log.d(TAG, "Looking for " + fqdn);
1792            for (WifiConfiguration config : configs.values()) {
1793                Log.d(TAG, "Testing " + config.SSID);
1794
1795                if (config.enterpriseConfig == null) {
1796                    continue;
1797                }
1798                final String configFqdn =
1799                        networkExtras.get(config.networkId).get(WifiConfigStore.ID_STRING_KEY_FQDN);
1800                if (configFqdn != null && configFqdn.equals(fqdn)) {
1801                    Log.d(TAG, "Matched " + configFqdn + " with " + config.networkId);
1802                    ++matchedConfigs;
1803                    config.FQDN = fqdn;
1804                    config.providerFriendlyName = homeSp.getFriendlyName();
1805
1806                    HashSet<Long> roamingConsortiumIds = homeSp.getRoamingConsortiums();
1807                    config.roamingConsortiumIds = new long[roamingConsortiumIds.size()];
1808                    int i = 0;
1809                    for (long id : roamingConsortiumIds) {
1810                        config.roamingConsortiumIds[i] = id;
1811                        i++;
1812                    }
1813                    IMSIParameter imsiParameter = homeSp.getCredential().getImsi();
1814                    config.enterpriseConfig.setPlmn(
1815                            imsiParameter != null ? imsiParameter.toString() : null);
1816                    config.enterpriseConfig.setRealm(homeSp.getCredential().getRealm());
1817                }
1818            }
1819        }
1820
1821        Log.d(TAG, "loaded " + matchedConfigs + " passpoint configs");
1822    }
1823
1824    public void writePasspointConfigs(final String fqdn, final HomeSP homeSP) {
1825        mWriter.write(PPS_FILE, new DelayedDiskWrite.Writer() {
1826            @Override
1827            public void onWriteCalled(DataOutputStream out) throws IOException {
1828                try {
1829                    if (homeSP != null) {
1830                        mMOManager.addSP(homeSP);
1831                    } else {
1832                        mMOManager.removeSP(fqdn);
1833                    }
1834                } catch (IOException e) {
1835                    loge("Could not write " + PPS_FILE + " : " + e);
1836                }
1837            }
1838        }, false);
1839    }
1840
1841    /**
1842     *  Write network history, WifiConfigurations and mScanDetailCaches to file.
1843     */
1844    private void readNetworkHistory(Map<String, WifiConfiguration> configs) {
1845        mWifiNetworkHistory.readNetworkHistory(configs,
1846                mScanDetailCaches,
1847                mDeletedEphemeralSSIDs);
1848    }
1849
1850    /**
1851     *  Read Network history from file, merge it into mConfiguredNetowrks and mScanDetailCaches
1852     */
1853    public void writeKnownNetworkHistory() {
1854        final List<WifiConfiguration> networks = new ArrayList<WifiConfiguration>();
1855        for (WifiConfiguration config : mConfiguredNetworks.valuesForAllUsers()) {
1856            networks.add(new WifiConfiguration(config));
1857        }
1858        mWifiNetworkHistory.writeKnownNetworkHistory(networks,
1859                mScanDetailCaches,
1860                mDeletedEphemeralSSIDs);
1861    }
1862
1863    public void setAndEnableLastSelectedConfiguration(int netId) {
1864        if (sVDBG) {
1865            loge("setLastSelectedConfiguration " + Integer.toString(netId));
1866        }
1867        if (netId == WifiConfiguration.INVALID_NETWORK_ID) {
1868            mLastSelectedConfiguration = null;
1869            mLastSelectedTimeStamp = -1;
1870        } else {
1871            WifiConfiguration selected = getWifiConfiguration(netId);
1872            if (selected == null) {
1873                mLastSelectedConfiguration = null;
1874                mLastSelectedTimeStamp = -1;
1875            } else {
1876                mLastSelectedConfiguration = selected.configKey();
1877                mLastSelectedTimeStamp = System.currentTimeMillis();
1878                updateNetworkSelectionStatus(netId,
1879                        WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE);
1880                if (sVDBG) {
1881                    loge("setLastSelectedConfiguration now: " + mLastSelectedConfiguration);
1882                }
1883            }
1884        }
1885    }
1886
1887    public void setLatestUserSelectedConfiguration(WifiConfiguration network) {
1888        if (network != null) {
1889            mLastSelectedConfiguration = network.configKey();
1890            mLastSelectedTimeStamp = System.currentTimeMillis();
1891        }
1892    }
1893
1894    public String getLastSelectedConfiguration() {
1895        return mLastSelectedConfiguration;
1896    }
1897
1898    public long getLastSelectedTimeStamp() {
1899        return mLastSelectedTimeStamp;
1900    }
1901
1902    public boolean isLastSelectedConfiguration(WifiConfiguration config) {
1903        return (mLastSelectedConfiguration != null
1904                && config != null
1905                && mLastSelectedConfiguration.equals(config.configKey()));
1906    }
1907
1908    private void writeIpAndProxyConfigurations() {
1909        final SparseArray<IpConfiguration> networks = new SparseArray<IpConfiguration>();
1910        for (WifiConfiguration config : mConfiguredNetworks.valuesForAllUsers()) {
1911            if (!config.ephemeral) {
1912                networks.put(configKey(config), config.getIpConfiguration());
1913            }
1914        }
1915
1916        mIpconfigStore.writeIpAndProxyConfigurations(IP_CONFIG_FILE, networks);
1917    }
1918
1919    private void readIpAndProxyConfigurations() {
1920        SparseArray<IpConfiguration> networks =
1921                mIpconfigStore.readIpAndProxyConfigurations(IP_CONFIG_FILE);
1922
1923        if (networks == null || networks.size() == 0) {
1924            // IpConfigStore.readIpAndProxyConfigurations has already logged an error.
1925            return;
1926        }
1927
1928        for (int i = 0; i < networks.size(); i++) {
1929            int id = networks.keyAt(i);
1930            WifiConfiguration config = mConfiguredNetworks.getByConfigKeyIDForAllUsers(id);
1931            // This is the only place the map is looked up through a (dangerous) hash-value!
1932
1933            if (config == null || config.ephemeral) {
1934                loge("configuration found for missing network, nid=" + id
1935                        + ", ignored, networks.size=" + Integer.toString(networks.size()));
1936            } else {
1937                config.setIpConfiguration(networks.valueAt(i));
1938            }
1939        }
1940    }
1941
1942    private NetworkUpdateResult addOrUpdateNetworkNative(WifiConfiguration config, int uid) {
1943        /*
1944         * If the supplied networkId is INVALID_NETWORK_ID, we create a new empty
1945         * network configuration. Otherwise, the networkId should
1946         * refer to an existing configuration.
1947         */
1948
1949        if (sVDBG) localLog("addOrUpdateNetworkNative " + config.getPrintableSsid());
1950        if (config.isPasspoint() && !mMOManager.isEnabled()) {
1951            Log.e(TAG, "Passpoint is not enabled");
1952            return new NetworkUpdateResult(INVALID_NETWORK_ID);
1953        }
1954
1955        boolean newNetwork = false;
1956        boolean existingMO = false;
1957        WifiConfiguration currentConfig;
1958        // networkId of INVALID_NETWORK_ID means we want to create a new network
1959        if (config.networkId == INVALID_NETWORK_ID) {
1960            // Try to fetch the existing config using configKey
1961            currentConfig = mConfiguredNetworks.getByConfigKeyForCurrentUser(config.configKey());
1962            if (currentConfig != null) {
1963                config.networkId = currentConfig.networkId;
1964            } else {
1965                if (mMOManager.getHomeSP(config.FQDN) != null) {
1966                    loge("addOrUpdateNetworkNative passpoint " + config.FQDN
1967                            + " was found, but no network Id");
1968                    existingMO = true;
1969                }
1970                newNetwork = true;
1971            }
1972        } else {
1973            // Fetch the existing config using networkID
1974            currentConfig = mConfiguredNetworks.getForCurrentUser(config.networkId);
1975        }
1976
1977        // originalConfig is used to check for credential and config changes that would cause
1978        // HasEverConnected to be set to false.
1979        WifiConfiguration originalConfig = new WifiConfiguration(currentConfig);
1980
1981        if (!mWifiConfigStore.addOrUpdateNetwork(config, currentConfig)) {
1982            return new NetworkUpdateResult(INVALID_NETWORK_ID);
1983        }
1984        int netId = config.networkId;
1985        String savedConfigKey = config.configKey();
1986
1987        /* An update of the network variables requires reading them
1988         * back from the supplicant to update mConfiguredNetworks.
1989         * This is because some of the variables (SSID, wep keys &
1990         * passphrases) reflect different values when read back than
1991         * when written. For example, wep key is stored as * irrespective
1992         * of the value sent to the supplicant.
1993         */
1994        if (currentConfig == null) {
1995            currentConfig = new WifiConfiguration();
1996            currentConfig.setIpAssignment(IpAssignment.DHCP);
1997            currentConfig.setProxySettings(ProxySettings.NONE);
1998            currentConfig.networkId = netId;
1999            if (config != null) {
2000                // Carry over the creation parameters
2001                currentConfig.selfAdded = config.selfAdded;
2002                currentConfig.didSelfAdd = config.didSelfAdd;
2003                currentConfig.ephemeral = config.ephemeral;
2004                currentConfig.meteredHint = config.meteredHint;
2005                currentConfig.lastConnectUid = config.lastConnectUid;
2006                currentConfig.lastUpdateUid = config.lastUpdateUid;
2007                currentConfig.creatorUid = config.creatorUid;
2008                currentConfig.creatorName = config.creatorName;
2009                currentConfig.lastUpdateName = config.lastUpdateName;
2010                currentConfig.peerWifiConfiguration = config.peerWifiConfiguration;
2011                currentConfig.FQDN = config.FQDN;
2012                currentConfig.providerFriendlyName = config.providerFriendlyName;
2013                currentConfig.roamingConsortiumIds = config.roamingConsortiumIds;
2014                currentConfig.validatedInternetAccess = config.validatedInternetAccess;
2015                currentConfig.numNoInternetAccessReports = config.numNoInternetAccessReports;
2016                currentConfig.updateTime = config.updateTime;
2017                currentConfig.creationTime = config.creationTime;
2018                currentConfig.shared = config.shared;
2019            }
2020            if (DBG) {
2021                log("created new config netId=" + Integer.toString(netId)
2022                        + " uid=" + Integer.toString(currentConfig.creatorUid)
2023                        + " name=" + currentConfig.creatorName);
2024            }
2025        }
2026
2027        /* save HomeSP object for passpoint networks */
2028        HomeSP homeSP = null;
2029
2030        if (!existingMO && config.isPasspoint()) {
2031            try {
2032                if (config.updateIdentifier == null) {   // Only create an MO for r1 networks
2033                    Credential credential =
2034                            new Credential(config.enterpriseConfig, mKeyStore, !newNetwork);
2035                    HashSet<Long> roamingConsortiumIds = new HashSet<Long>();
2036                    for (Long roamingConsortiumId : config.roamingConsortiumIds) {
2037                        roamingConsortiumIds.add(roamingConsortiumId);
2038                    }
2039
2040                    homeSP = new HomeSP(Collections.<String, Long>emptyMap(), config.FQDN,
2041                            roamingConsortiumIds, Collections.<String>emptySet(),
2042                            Collections.<Long>emptySet(), Collections.<Long>emptyList(),
2043                            config.providerFriendlyName, null, credential);
2044
2045                    log("created a homeSP object for " + config.networkId + ":" + config.SSID);
2046                }
2047
2048                /* fix enterprise config properties for passpoint */
2049                currentConfig.enterpriseConfig.setRealm(config.enterpriseConfig.getRealm());
2050                currentConfig.enterpriseConfig.setPlmn(config.enterpriseConfig.getPlmn());
2051            } catch (IOException ioe) {
2052                Log.e(TAG, "Failed to create Passpoint config: " + ioe);
2053                return new NetworkUpdateResult(INVALID_NETWORK_ID);
2054            }
2055        }
2056
2057        if (uid != WifiConfiguration.UNKNOWN_UID) {
2058            if (newNetwork) {
2059                currentConfig.creatorUid = uid;
2060            } else {
2061                currentConfig.lastUpdateUid = uid;
2062            }
2063        }
2064
2065        // For debug, record the time the configuration was modified
2066        StringBuilder sb = new StringBuilder();
2067        sb.append("time=");
2068        Calendar c = Calendar.getInstance();
2069        c.setTimeInMillis(System.currentTimeMillis());
2070        sb.append(String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c));
2071
2072        if (newNetwork) {
2073            currentConfig.creationTime = sb.toString();
2074        } else {
2075            currentConfig.updateTime = sb.toString();
2076        }
2077
2078        if (currentConfig.status == WifiConfiguration.Status.ENABLED) {
2079            // Make sure autojoin remain in sync with user modifying the configuration
2080            updateNetworkSelectionStatus(currentConfig.networkId,
2081                    WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_ENABLE);
2082        }
2083
2084        if (currentConfig.configKey().equals(getLastSelectedConfiguration())
2085                && currentConfig.ephemeral) {
2086            // Make the config non-ephemeral since the user just explicitly clicked it.
2087            currentConfig.ephemeral = false;
2088            if (DBG) {
2089                log("remove ephemeral status netId=" + Integer.toString(netId)
2090                        + " " + currentConfig.configKey());
2091            }
2092        }
2093
2094        if (sVDBG) log("will read network variables netId=" + Integer.toString(netId));
2095
2096        readNetworkVariables(currentConfig);
2097        // When we read back the config from wpa_supplicant, some of the default values are set
2098        // which could change the configKey.
2099        if (!savedConfigKey.equals(currentConfig.configKey())) {
2100            if (!mWifiConfigStore.saveNetworkMetadata(currentConfig)) {
2101                loge("Failed to set network metadata. Removing config " + config.networkId);
2102                mWifiConfigStore.removeNetwork(config);
2103                return new NetworkUpdateResult(INVALID_NETWORK_ID);
2104            }
2105        }
2106
2107        boolean passwordChanged = false;
2108        // check passed in config to see if it has more than a password set.
2109        if (!newNetwork && config.preSharedKey != null && !config.preSharedKey.equals("*")) {
2110            passwordChanged = true;
2111        }
2112
2113        if (newNetwork || passwordChanged || wasCredentialChange(originalConfig, currentConfig)) {
2114            currentConfig.getNetworkSelectionStatus().setHasEverConnected(false);
2115        }
2116
2117        // Persist configuration paramaters that are not saved by supplicant.
2118        if (config.lastUpdateName != null) {
2119            currentConfig.lastUpdateName = config.lastUpdateName;
2120        }
2121        if (config.lastUpdateUid != WifiConfiguration.UNKNOWN_UID) {
2122            currentConfig.lastUpdateUid = config.lastUpdateUid;
2123        }
2124
2125        mConfiguredNetworks.put(currentConfig);
2126
2127        NetworkUpdateResult result =
2128                writeIpAndProxyConfigurationsOnChange(currentConfig, config, newNetwork);
2129        result.setIsNewNetwork(newNetwork);
2130        result.setNetworkId(netId);
2131
2132        if (homeSP != null) {
2133            writePasspointConfigs(null, homeSP);
2134        }
2135
2136        saveConfig();
2137        writeKnownNetworkHistory();
2138
2139        return result;
2140    }
2141
2142    private boolean wasBitSetUpdated(BitSet originalBitSet, BitSet currentBitSet) {
2143        if (originalBitSet != null && currentBitSet != null) {
2144            // both configs have values set, check if they are different
2145            if (!originalBitSet.equals(currentBitSet)) {
2146                // the BitSets are different
2147                return true;
2148            }
2149        } else if (originalBitSet != null || currentBitSet != null) {
2150            return true;
2151        }
2152        return false;
2153    }
2154
2155    private boolean wasCredentialChange(WifiConfiguration originalConfig,
2156            WifiConfiguration currentConfig) {
2157        // Check if any core WifiConfiguration parameters changed that would impact new connections
2158        if (originalConfig == null) {
2159            return true;
2160        }
2161
2162        if (wasBitSetUpdated(originalConfig.allowedKeyManagement,
2163                currentConfig.allowedKeyManagement)) {
2164            return true;
2165        }
2166
2167        if (wasBitSetUpdated(originalConfig.allowedProtocols, currentConfig.allowedProtocols)) {
2168            return true;
2169        }
2170
2171        if (wasBitSetUpdated(originalConfig.allowedAuthAlgorithms,
2172                currentConfig.allowedAuthAlgorithms)) {
2173            return true;
2174        }
2175
2176        if (wasBitSetUpdated(originalConfig.allowedPairwiseCiphers,
2177                currentConfig.allowedPairwiseCiphers)) {
2178            return true;
2179        }
2180
2181        if (wasBitSetUpdated(originalConfig.allowedGroupCiphers,
2182                currentConfig.allowedGroupCiphers)) {
2183            return true;
2184        }
2185
2186        if (originalConfig.wepKeys != null && currentConfig.wepKeys != null) {
2187            if (originalConfig.wepKeys.length == currentConfig.wepKeys.length) {
2188                for (int i = 0; i < originalConfig.wepKeys.length; i++) {
2189                    if (originalConfig.wepKeys[i] != currentConfig.wepKeys[i]) {
2190                        return true;
2191                    }
2192                }
2193            } else {
2194                return true;
2195            }
2196        }
2197
2198        if (originalConfig.hiddenSSID != currentConfig.hiddenSSID) {
2199            return true;
2200        }
2201
2202        if (originalConfig.requirePMF != currentConfig.requirePMF) {
2203            return true;
2204        }
2205
2206        if (wasEnterpriseConfigChange(originalConfig.enterpriseConfig,
2207                currentConfig.enterpriseConfig)) {
2208            return true;
2209        }
2210        return false;
2211    }
2212
2213
2214    protected boolean wasEnterpriseConfigChange(WifiEnterpriseConfig originalEnterpriseConfig,
2215            WifiEnterpriseConfig currentEnterpriseConfig) {
2216        if (originalEnterpriseConfig != null && currentEnterpriseConfig != null) {
2217            if (originalEnterpriseConfig.getEapMethod() != currentEnterpriseConfig.getEapMethod()) {
2218                return true;
2219            }
2220
2221            if (originalEnterpriseConfig.getPhase2Method()
2222                    != currentEnterpriseConfig.getPhase2Method()) {
2223                return true;
2224            }
2225
2226            X509Certificate[] originalCaCerts = originalEnterpriseConfig.getCaCertificates();
2227            X509Certificate[] currentCaCerts = currentEnterpriseConfig.getCaCertificates();
2228
2229            if (originalCaCerts != null && currentCaCerts != null) {
2230                if (originalCaCerts.length == currentCaCerts.length) {
2231                    for (int i = 0; i < originalCaCerts.length; i++) {
2232                        if (!originalCaCerts[i].equals(currentCaCerts[i])) {
2233                            return true;
2234                        }
2235                    }
2236                } else {
2237                    // number of aliases is different, so the configs are different
2238                    return true;
2239                }
2240            } else {
2241                // one of the enterprise configs may have aliases
2242                if (originalCaCerts != null || currentCaCerts != null) {
2243                    return true;
2244                }
2245            }
2246        } else {
2247            // One of the configs may have an enterpriseConfig
2248            if (originalEnterpriseConfig != null || currentEnterpriseConfig != null) {
2249                return true;
2250            }
2251        }
2252        return false;
2253    }
2254
2255    public WifiConfiguration getWifiConfigForHomeSP(HomeSP homeSP) {
2256        WifiConfiguration config = mConfiguredNetworks.getByFQDNForCurrentUser(homeSP.getFQDN());
2257        if (config == null) {
2258            Log.e(TAG, "Could not find network for homeSP " + homeSP.getFQDN());
2259        }
2260        return config;
2261    }
2262
2263    public HomeSP getHomeSPForConfig(WifiConfiguration config) {
2264        WifiConfiguration storedConfig = mConfiguredNetworks.getForCurrentUser(config.networkId);
2265        return storedConfig != null && storedConfig.isPasspoint()
2266                ? mMOManager.getHomeSP(storedConfig.FQDN)
2267                : null;
2268    }
2269
2270    public ScanDetailCache getScanDetailCache(WifiConfiguration config) {
2271        if (config == null) return null;
2272        ScanDetailCache cache = mScanDetailCaches.get(config.networkId);
2273        if (cache == null && config.networkId != WifiConfiguration.INVALID_NETWORK_ID) {
2274            cache = new ScanDetailCache(config);
2275            mScanDetailCaches.put(config.networkId, cache);
2276        }
2277        return cache;
2278    }
2279
2280    /**
2281     * This function run thru the Saved WifiConfigurations and check if some should be linked.
2282     * @param config
2283     */
2284    public void linkConfiguration(WifiConfiguration config) {
2285        if (!WifiConfigurationUtil.isVisibleToAnyProfile(config,
2286                mUserManager.getProfiles(mCurrentUserId))) {
2287            loge("linkConfiguration: Attempting to link config " + config.configKey()
2288                    + " that is not visible to the current user.");
2289            return;
2290        }
2291
2292        if (getScanDetailCache(config) != null && getScanDetailCache(config).size() > 6) {
2293            // Ignore configurations with large number of BSSIDs
2294            return;
2295        }
2296        if (!config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
2297            // Only link WPA_PSK config
2298            return;
2299        }
2300        for (WifiConfiguration link : mConfiguredNetworks.valuesForCurrentUser()) {
2301            boolean doLink = false;
2302
2303            if (link.configKey().equals(config.configKey())) {
2304                continue;
2305            }
2306
2307            if (link.ephemeral) {
2308                continue;
2309            }
2310
2311            // Autojoin will be allowed to dynamically jump from a linked configuration
2312            // to another, hence only link configurations that have equivalent level of security
2313            if (!link.allowedKeyManagement.equals(config.allowedKeyManagement)) {
2314                continue;
2315            }
2316
2317            ScanDetailCache linkedScanDetailCache = getScanDetailCache(link);
2318            if (linkedScanDetailCache != null && linkedScanDetailCache.size() > 6) {
2319                // Ignore configurations with large number of BSSIDs
2320                continue;
2321            }
2322
2323            if (config.defaultGwMacAddress != null && link.defaultGwMacAddress != null) {
2324                // If both default GW are known, link only if they are equal
2325                if (config.defaultGwMacAddress.equals(link.defaultGwMacAddress)) {
2326                    if (sVDBG) {
2327                        loge("linkConfiguration link due to same gw " + link.SSID
2328                                + " and " + config.SSID + " GW " + config.defaultGwMacAddress);
2329                    }
2330                    doLink = true;
2331                }
2332            } else {
2333                // We do not know BOTH default gateways hence we will try to link
2334                // hoping that WifiConfigurations are indeed behind the same gateway.
2335                // once both WifiConfiguration have been tried and thus once both efault gateways
2336                // are known we will revisit the choice of linking them
2337                if ((getScanDetailCache(config) != null)
2338                        && (getScanDetailCache(config).size() <= 6)) {
2339
2340                    for (String abssid : getScanDetailCache(config).keySet()) {
2341                        for (String bbssid : linkedScanDetailCache.keySet()) {
2342                            if (sVVDBG) {
2343                                loge("linkConfiguration try to link due to DBDC BSSID match "
2344                                        + link.SSID + " and " + config.SSID + " bssida " + abssid
2345                                        + " bssidb " + bbssid);
2346                            }
2347                            if (abssid.regionMatches(true, 0, bbssid, 0, 16)) {
2348                                // If first 16 ascii characters of BSSID matches,
2349                                // we assume this is a DBDC
2350                                doLink = true;
2351                            }
2352                        }
2353                    }
2354                }
2355            }
2356
2357            if (doLink && mOnlyLinkSameCredentialConfigurations) {
2358                String apsk =
2359                        readNetworkVariableFromSupplicantFile(link.configKey(), "psk");
2360                String bpsk =
2361                        readNetworkVariableFromSupplicantFile(config.configKey(), "psk");
2362                if (apsk == null || bpsk == null
2363                        || TextUtils.isEmpty(apsk) || TextUtils.isEmpty(apsk)
2364                        || apsk.equals("*") || apsk.equals(DELETED_CONFIG_PSK)
2365                        || !apsk.equals(bpsk)) {
2366                    doLink = false;
2367                }
2368            }
2369
2370            if (doLink) {
2371                if (sVDBG) {
2372                    loge("linkConfiguration: will link " + link.configKey()
2373                            + " and " + config.configKey());
2374                }
2375                if (link.linkedConfigurations == null) {
2376                    link.linkedConfigurations = new HashMap<String, Integer>();
2377                }
2378                if (config.linkedConfigurations == null) {
2379                    config.linkedConfigurations = new HashMap<String, Integer>();
2380                }
2381                if (link.linkedConfigurations.get(config.configKey()) == null) {
2382                    link.linkedConfigurations.put(config.configKey(), Integer.valueOf(1));
2383                }
2384                if (config.linkedConfigurations.get(link.configKey()) == null) {
2385                    config.linkedConfigurations.put(link.configKey(), Integer.valueOf(1));
2386                }
2387            } else {
2388                if (link.linkedConfigurations != null
2389                        && (link.linkedConfigurations.get(config.configKey()) != null)) {
2390                    if (sVDBG) {
2391                        loge("linkConfiguration: un-link " + config.configKey()
2392                                + " from " + link.configKey());
2393                    }
2394                    link.linkedConfigurations.remove(config.configKey());
2395                }
2396                if (config.linkedConfigurations != null
2397                        && (config.linkedConfigurations.get(link.configKey()) != null)) {
2398                    if (sVDBG) {
2399                        loge("linkConfiguration: un-link " + link.configKey()
2400                                + " from " + config.configKey());
2401                    }
2402                    config.linkedConfigurations.remove(link.configKey());
2403                }
2404            }
2405        }
2406    }
2407
2408    public HashSet<Integer> makeChannelList(WifiConfiguration config, int age, boolean restrict) {
2409        if (config == null) {
2410            return null;
2411        }
2412        long now_ms = System.currentTimeMillis();
2413
2414        HashSet<Integer> channels = new HashSet<Integer>();
2415
2416        //get channels for this configuration, if there are at least 2 BSSIDs
2417        if (getScanDetailCache(config) == null && config.linkedConfigurations == null) {
2418            return null;
2419        }
2420
2421        if (sVDBG) {
2422            StringBuilder dbg = new StringBuilder();
2423            dbg.append("makeChannelList age=" + Integer.toString(age)
2424                    + " for " + config.configKey()
2425                    + " max=" + mMaxNumActiveChannelsForPartialScans);
2426            if (getScanDetailCache(config) != null) {
2427                dbg.append(" bssids=" + getScanDetailCache(config).size());
2428            }
2429            if (config.linkedConfigurations != null) {
2430                dbg.append(" linked=" + config.linkedConfigurations.size());
2431            }
2432            loge(dbg.toString());
2433        }
2434
2435        int numChannels = 0;
2436        if (getScanDetailCache(config) != null && getScanDetailCache(config).size() > 0) {
2437            for (ScanDetail scanDetail : getScanDetailCache(config).values()) {
2438                ScanResult result = scanDetail.getScanResult();
2439                //TODO : cout active and passive channels separately
2440                if (numChannels > mMaxNumActiveChannelsForPartialScans.get()) {
2441                    break;
2442                }
2443                if (sVDBG) {
2444                    boolean test = (now_ms - result.seen) < age;
2445                    loge("has " + result.BSSID + " freq=" + Integer.toString(result.frequency)
2446                            + " age=" + Long.toString(now_ms - result.seen) + " ?=" + test);
2447                }
2448                if (((now_ms - result.seen) < age)/*||(!restrict || result.is24GHz())*/) {
2449                    channels.add(result.frequency);
2450                    numChannels++;
2451                }
2452            }
2453        }
2454
2455        //get channels for linked configurations
2456        if (config.linkedConfigurations != null) {
2457            for (String key : config.linkedConfigurations.keySet()) {
2458                WifiConfiguration linked = getWifiConfiguration(key);
2459                if (linked == null) {
2460                    continue;
2461                }
2462                if (getScanDetailCache(linked) == null) {
2463                    continue;
2464                }
2465                for (ScanDetail scanDetail : getScanDetailCache(linked).values()) {
2466                    ScanResult result = scanDetail.getScanResult();
2467                    if (sVDBG) {
2468                        loge("has link: " + result.BSSID
2469                                + " freq=" + Integer.toString(result.frequency)
2470                                + " age=" + Long.toString(now_ms - result.seen));
2471                    }
2472                    if (numChannels > mMaxNumActiveChannelsForPartialScans.get()) {
2473                        break;
2474                    }
2475                    if (((now_ms - result.seen) < age)/*||(!restrict || result.is24GHz())*/) {
2476                        channels.add(result.frequency);
2477                        numChannels++;
2478                    }
2479                }
2480            }
2481        }
2482        return channels;
2483    }
2484
2485    private Map<HomeSP, PasspointMatch> matchPasspointNetworks(ScanDetail scanDetail) {
2486        if (!mMOManager.isConfigured()) {
2487            if (mEnableOsuQueries) {
2488                NetworkDetail networkDetail = scanDetail.getNetworkDetail();
2489                List<Constants.ANQPElementType> querySet =
2490                        ANQPFactory.buildQueryList(networkDetail, false, true);
2491
2492                if (networkDetail.queriable(querySet)) {
2493                    querySet = mAnqpCache.initiate(networkDetail, querySet);
2494                    if (querySet != null) {
2495                        mSupplicantBridge.startANQP(scanDetail, querySet);
2496                    }
2497                    updateAnqpCache(scanDetail, networkDetail.getANQPElements());
2498                }
2499            }
2500            return null;
2501        }
2502        NetworkDetail networkDetail = scanDetail.getNetworkDetail();
2503        if (!networkDetail.hasInterworking()) {
2504            return null;
2505        }
2506        updateAnqpCache(scanDetail, networkDetail.getANQPElements());
2507
2508        Map<HomeSP, PasspointMatch> matches = matchNetwork(scanDetail, true);
2509        Log.d(Utils.hs2LogTag(getClass()), scanDetail.getSSID()
2510                + " pass 1 matches: " + toMatchString(matches));
2511        return matches;
2512    }
2513
2514    private Map<HomeSP, PasspointMatch> matchNetwork(ScanDetail scanDetail, boolean query) {
2515        NetworkDetail networkDetail = scanDetail.getNetworkDetail();
2516
2517        ANQPData anqpData = mAnqpCache.getEntry(networkDetail);
2518
2519        Map<Constants.ANQPElementType, ANQPElement> anqpElements =
2520                anqpData != null ? anqpData.getANQPElements() : null;
2521
2522        boolean queried = !query;
2523        Collection<HomeSP> homeSPs = mMOManager.getLoadedSPs().values();
2524        Map<HomeSP, PasspointMatch> matches = new HashMap<>(homeSPs.size());
2525        Log.d(Utils.hs2LogTag(getClass()), "match nwk " + scanDetail.toKeyString()
2526                + ", anqp " + (anqpData != null ? "present" : "missing")
2527                + ", query " + query + ", home sps: " + homeSPs.size());
2528
2529        for (HomeSP homeSP : homeSPs) {
2530            PasspointMatch match = homeSP.match(networkDetail, anqpElements, mSIMAccessor);
2531
2532            Log.d(Utils.hs2LogTag(getClass()), " -- "
2533                    + homeSP.getFQDN() + ": match " + match + ", queried " + queried);
2534
2535            if ((match == PasspointMatch.Incomplete || mEnableOsuQueries) && !queried) {
2536                boolean matchSet = match == PasspointMatch.Incomplete;
2537                boolean osu = mEnableOsuQueries;
2538                List<Constants.ANQPElementType> querySet =
2539                        ANQPFactory.buildQueryList(networkDetail, matchSet, osu);
2540                if (networkDetail.queriable(querySet)) {
2541                    querySet = mAnqpCache.initiate(networkDetail, querySet);
2542                    if (querySet != null) {
2543                        mSupplicantBridge.startANQP(scanDetail, querySet);
2544                    }
2545                }
2546                queried = true;
2547            }
2548            matches.put(homeSP, match);
2549        }
2550        return matches;
2551    }
2552
2553    public Map<Constants.ANQPElementType, ANQPElement> getANQPData(NetworkDetail network) {
2554        ANQPData data = mAnqpCache.getEntry(network);
2555        return data != null ? data.getANQPElements() : null;
2556    }
2557
2558    public SIMAccessor getSIMAccessor() {
2559        return mSIMAccessor;
2560    }
2561
2562    public void notifyANQPDone(Long bssid, boolean success) {
2563        mSupplicantBridge.notifyANQPDone(bssid, success);
2564    }
2565
2566    public void notifyIconReceived(IconEvent iconEvent) {
2567        Intent intent = new Intent(WifiManager.PASSPOINT_ICON_RECEIVED_ACTION);
2568        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2569        intent.putExtra(WifiManager.EXTRA_PASSPOINT_ICON_BSSID, iconEvent.getBSSID());
2570        intent.putExtra(WifiManager.EXTRA_PASSPOINT_ICON_FILE, iconEvent.getFileName());
2571        try {
2572            intent.putExtra(WifiManager.EXTRA_PASSPOINT_ICON_DATA,
2573                    mSupplicantBridge.retrieveIcon(iconEvent));
2574        } catch (IOException ioe) {
2575            /* Simply omit the icon data as a failure indication */
2576        }
2577        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2578
2579    }
2580
2581    private void updateAnqpCache(ScanDetail scanDetail,
2582                                 Map<Constants.ANQPElementType, ANQPElement> anqpElements) {
2583        NetworkDetail networkDetail = scanDetail.getNetworkDetail();
2584
2585        if (anqpElements == null) {
2586            // Try to pull cached data if query failed.
2587            ANQPData data = mAnqpCache.getEntry(networkDetail);
2588            if (data != null) {
2589                scanDetail.propagateANQPInfo(data.getANQPElements());
2590            }
2591            return;
2592        }
2593
2594        mAnqpCache.update(networkDetail, anqpElements);
2595    }
2596
2597    private static String toMatchString(Map<HomeSP, PasspointMatch> matches) {
2598        StringBuilder sb = new StringBuilder();
2599        for (Map.Entry<HomeSP, PasspointMatch> entry : matches.entrySet()) {
2600            sb.append(' ').append(entry.getKey().getFQDN()).append("->").append(entry.getValue());
2601        }
2602        return sb.toString();
2603    }
2604
2605    private void cacheScanResultForPasspointConfigs(ScanDetail scanDetail,
2606            Map<HomeSP, PasspointMatch> matches,
2607            List<WifiConfiguration> associatedWifiConfigurations) {
2608
2609        for (Map.Entry<HomeSP, PasspointMatch> entry : matches.entrySet()) {
2610            PasspointMatch match = entry.getValue();
2611            if (match == PasspointMatch.HomeProvider || match == PasspointMatch.RoamingProvider) {
2612                WifiConfiguration config = getWifiConfigForHomeSP(entry.getKey());
2613                if (config != null) {
2614                    cacheScanResultForConfig(config, scanDetail, entry.getValue());
2615                    if (associatedWifiConfigurations != null) {
2616                        associatedWifiConfigurations.add(config);
2617                    }
2618                } else {
2619                    Log.w(Utils.hs2LogTag(getClass()), "Failed to find config for '"
2620                            + entry.getKey().getFQDN() + "'");
2621                    /* perhaps the configuration was deleted?? */
2622                }
2623            }
2624        }
2625    }
2626
2627    private void cacheScanResultForConfig(
2628            WifiConfiguration config, ScanDetail scanDetail, PasspointMatch passpointMatch) {
2629
2630        ScanResult scanResult = scanDetail.getScanResult();
2631
2632        ScanDetailCache scanDetailCache = getScanDetailCache(config);
2633        if (scanDetailCache == null) {
2634            Log.w(TAG, "Could not allocate scan cache for " + config.SSID);
2635            return;
2636        }
2637
2638        // Adding a new BSSID
2639        ScanResult result = scanDetailCache.get(scanResult.BSSID);
2640        if (result != null) {
2641            // transfer the black list status
2642            scanResult.blackListTimestamp = result.blackListTimestamp;
2643            scanResult.numIpConfigFailures = result.numIpConfigFailures;
2644            scanResult.numConnection = result.numConnection;
2645            scanResult.isAutoJoinCandidate = result.isAutoJoinCandidate;
2646        }
2647
2648        if (config.ephemeral) {
2649            // For an ephemeral Wi-Fi config, the ScanResult should be considered
2650            // untrusted.
2651            scanResult.untrusted = true;
2652        }
2653
2654        if (scanDetailCache.size() > (MAX_NUM_SCAN_CACHE_ENTRIES + 64)) {
2655            long now_dbg = 0;
2656            if (sVVDBG) {
2657                loge(" Will trim config " + config.configKey()
2658                        + " size " + scanDetailCache.size());
2659
2660                for (ScanDetail sd : scanDetailCache.values()) {
2661                    loge("     " + sd.getBSSIDString() + " " + sd.getSeen());
2662                }
2663                now_dbg = SystemClock.elapsedRealtimeNanos();
2664            }
2665            // Trim the scan result cache to MAX_NUM_SCAN_CACHE_ENTRIES entries max
2666            // Since this operation is expensive, make sure it is not performed
2667            // until the cache has grown significantly above the trim treshold
2668            scanDetailCache.trim(MAX_NUM_SCAN_CACHE_ENTRIES);
2669            if (sVVDBG) {
2670                long diff = SystemClock.elapsedRealtimeNanos() - now_dbg;
2671                loge(" Finished trimming config, time(ns) " + diff);
2672                for (ScanDetail sd : scanDetailCache.values()) {
2673                    loge("     " + sd.getBSSIDString() + " " + sd.getSeen());
2674                }
2675            }
2676        }
2677
2678        // Add the scan result to this WifiConfiguration
2679        if (passpointMatch != null) {
2680            scanDetailCache.put(scanDetail, passpointMatch, getHomeSPForConfig(config));
2681        } else {
2682            scanDetailCache.put(scanDetail);
2683        }
2684
2685        // Since we added a scan result to this configuration, re-attempt linking
2686        linkConfiguration(config);
2687    }
2688
2689    private boolean isEncryptionWep(String encryption) {
2690        return encryption.contains("WEP");
2691    }
2692
2693    private boolean isEncryptionPsk(String encryption) {
2694        return encryption.contains("PSK");
2695    }
2696
2697    private boolean isEncryptionEap(String encryption) {
2698        return encryption.contains("EAP");
2699    }
2700
2701    public boolean isOpenNetwork(String encryption) {
2702        if (!isEncryptionWep(encryption) && !isEncryptionPsk(encryption)
2703                && !isEncryptionEap(encryption)) {
2704            return true;
2705        }
2706        return false;
2707    }
2708
2709    public boolean isOpenNetwork(ScanResult scan) {
2710        String scanResultEncrypt = scan.capabilities;
2711        return isOpenNetwork(scanResultEncrypt);
2712    }
2713
2714    public boolean isOpenNetwork(WifiConfiguration config) {
2715        String configEncrypt = config.configKey();
2716        return isOpenNetwork(configEncrypt);
2717    }
2718
2719    /**
2720     * create a mapping between the scandetail and the Wificonfiguration it associated with
2721     * because Passpoint, one BSSID can associated with multiple SSIDs
2722     * @param scanDetail input a scanDetail from the scan result
2723     * @return List<WifiConfiguration> a list of WifiConfigurations associated to this scanDetail
2724     */
2725    public List<WifiConfiguration> updateSavedNetworkWithNewScanDetail(ScanDetail scanDetail) {
2726
2727        ScanResult scanResult = scanDetail.getScanResult();
2728        NetworkDetail networkDetail = scanDetail.getNetworkDetail();
2729        List<WifiConfiguration> associatedWifiConfigurations = new ArrayList<WifiConfiguration>();
2730
2731        if (scanResult == null) {
2732            return null;
2733        }
2734
2735        String ssid = "\"" + scanResult.SSID + "\"";
2736
2737        if (networkDetail.hasInterworking()) {
2738            Map<HomeSP, PasspointMatch> matches = matchPasspointNetworks(scanDetail);
2739            if (matches != null) {
2740                cacheScanResultForPasspointConfigs(scanDetail, matches,
2741                        associatedWifiConfigurations);
2742                //Do not return here. A BSSID can belong to both passpoint network and non-passpoint
2743                //Network
2744            }
2745        }
2746
2747        for (WifiConfiguration config : mConfiguredNetworks.valuesForCurrentUser()) {
2748            boolean found = false;
2749            if (config.SSID == null || !config.SSID.equals(ssid)) {
2750                continue;
2751            }
2752            if (DBG) {
2753                localLog("updateSavedNetworkWithNewScanDetail(): try " + config.configKey()
2754                        + " SSID=" + config.SSID + " " + scanResult.SSID + " "
2755                        + scanResult.capabilities);
2756            }
2757
2758            String scanResultEncrypt = scanResult.capabilities;
2759            String configEncrypt = config.configKey();
2760            if (isEncryptionWep(scanResultEncrypt) && isEncryptionWep(configEncrypt)
2761                    || (isEncryptionPsk(scanResultEncrypt) && isEncryptionPsk(configEncrypt))
2762                    || (isEncryptionEap(scanResultEncrypt) && isEncryptionEap(configEncrypt))
2763                    || (isOpenNetwork(scanResultEncrypt) && isOpenNetwork(configEncrypt))) {
2764                found = true;
2765            }
2766
2767            if (found) {
2768                cacheScanResultForConfig(config, scanDetail, null);
2769                associatedWifiConfigurations.add(config);
2770            }
2771        }
2772
2773        if (associatedWifiConfigurations.size() == 0) {
2774            return null;
2775        } else {
2776            return associatedWifiConfigurations;
2777        }
2778    }
2779
2780    /**
2781     * Handles the switch to a different foreground user:
2782     * - Removes all ephemeral networks
2783     * - Disables private network configurations belonging to the previous foreground user
2784     * - Enables private network configurations belonging to the new foreground user
2785     *
2786     * @param userId The identifier of the new foreground user, after the switch.
2787     *
2788     * TODO(b/26785736): Terminate background users if the new foreground user has one or more
2789     * private network configurations.
2790     */
2791    public void handleUserSwitch(int userId) {
2792        mCurrentUserId = userId;
2793        Set<WifiConfiguration> ephemeralConfigs = new HashSet<>();
2794        for (WifiConfiguration config : mConfiguredNetworks.valuesForCurrentUser()) {
2795            if (config.ephemeral) {
2796                ephemeralConfigs.add(config);
2797            }
2798        }
2799        if (!ephemeralConfigs.isEmpty()) {
2800            for (WifiConfiguration config : ephemeralConfigs) {
2801                removeConfigWithoutBroadcast(config);
2802            }
2803            saveConfig();
2804            writeKnownNetworkHistory();
2805        }
2806
2807        final List<WifiConfiguration> hiddenConfigurations =
2808                mConfiguredNetworks.handleUserSwitch(mCurrentUserId);
2809        for (WifiConfiguration network : hiddenConfigurations) {
2810            disableNetworkNative(network);
2811        }
2812        enableAllNetworks();
2813
2814        // TODO(b/26785746): This broadcast is unnecessary if either of the following is true:
2815        // * The user switch did not change the list of visible networks
2816        // * The user switch revealed additional networks that were temporarily disabled and got
2817        //   re-enabled now (because enableAllNetworks() sent the same broadcast already).
2818        sendConfiguredNetworksChangedBroadcast();
2819    }
2820
2821    public int getCurrentUserId() {
2822        return mCurrentUserId;
2823    }
2824
2825    public boolean isCurrentUserProfile(int userId) {
2826        if (userId == mCurrentUserId) {
2827            return true;
2828        }
2829        final UserInfo parent = mUserManager.getProfileParent(userId);
2830        return parent != null && parent.id == mCurrentUserId;
2831    }
2832
2833    /* Compare current and new configuration and write to file on change */
2834    private NetworkUpdateResult writeIpAndProxyConfigurationsOnChange(
2835            WifiConfiguration currentConfig,
2836            WifiConfiguration newConfig,
2837            boolean isNewNetwork) {
2838        boolean ipChanged = false;
2839        boolean proxyChanged = false;
2840
2841        switch (newConfig.getIpAssignment()) {
2842            case STATIC:
2843                if (currentConfig.getIpAssignment() != newConfig.getIpAssignment()) {
2844                    ipChanged = true;
2845                } else {
2846                    ipChanged = !Objects.equals(
2847                            currentConfig.getStaticIpConfiguration(),
2848                            newConfig.getStaticIpConfiguration());
2849                }
2850                break;
2851            case DHCP:
2852                if (currentConfig.getIpAssignment() != newConfig.getIpAssignment()) {
2853                    ipChanged = true;
2854                }
2855                break;
2856            case UNASSIGNED:
2857                /* Ignore */
2858                break;
2859            default:
2860                loge("Ignore invalid ip assignment during write");
2861                break;
2862        }
2863
2864        switch (newConfig.getProxySettings()) {
2865            case STATIC:
2866            case PAC:
2867                ProxyInfo newHttpProxy = newConfig.getHttpProxy();
2868                ProxyInfo currentHttpProxy = currentConfig.getHttpProxy();
2869
2870                if (newHttpProxy != null) {
2871                    proxyChanged = !newHttpProxy.equals(currentHttpProxy);
2872                } else {
2873                    proxyChanged = (currentHttpProxy != null);
2874                }
2875                break;
2876            case NONE:
2877                if (currentConfig.getProxySettings() != newConfig.getProxySettings()) {
2878                    proxyChanged = true;
2879                }
2880                break;
2881            case UNASSIGNED:
2882                /* Ignore */
2883                break;
2884            default:
2885                loge("Ignore invalid proxy configuration during write");
2886                break;
2887        }
2888
2889        if (ipChanged) {
2890            currentConfig.setIpAssignment(newConfig.getIpAssignment());
2891            currentConfig.setStaticIpConfiguration(newConfig.getStaticIpConfiguration());
2892            log("IP config changed SSID = " + currentConfig.SSID);
2893            if (currentConfig.getStaticIpConfiguration() != null) {
2894                log(" static configuration: "
2895                        + currentConfig.getStaticIpConfiguration().toString());
2896            }
2897        }
2898
2899        if (proxyChanged) {
2900            currentConfig.setProxySettings(newConfig.getProxySettings());
2901            currentConfig.setHttpProxy(newConfig.getHttpProxy());
2902            log("proxy changed SSID = " + currentConfig.SSID);
2903            if (currentConfig.getHttpProxy() != null) {
2904                log(" proxyProperties: " + currentConfig.getHttpProxy().toString());
2905            }
2906        }
2907
2908        if (ipChanged || proxyChanged || isNewNetwork) {
2909            if (sVDBG) {
2910                logd("writeIpAndProxyConfigurationsOnChange: " + currentConfig.SSID + " -> "
2911                        + newConfig.SSID + " path: " + IP_CONFIG_FILE);
2912            }
2913            writeIpAndProxyConfigurations();
2914        }
2915        return new NetworkUpdateResult(ipChanged, proxyChanged);
2916    }
2917
2918    /**
2919     * Read the variables from the supplicant daemon that are needed to
2920     * fill in the WifiConfiguration object.
2921     *
2922     * @param config the {@link WifiConfiguration} object to be filled in.
2923     */
2924    private void readNetworkVariables(WifiConfiguration config) {
2925        mWifiConfigStore.readNetworkVariables(config);
2926    }
2927
2928    /* return the allowed key management based on a scan result */
2929
2930    public WifiConfiguration wifiConfigurationFromScanResult(ScanResult result) {
2931
2932        WifiConfiguration config = new WifiConfiguration();
2933
2934        config.SSID = "\"" + result.SSID + "\"";
2935
2936        if (sVDBG) {
2937            loge("WifiConfiguration from scan results "
2938                    + config.SSID + " cap " + result.capabilities);
2939        }
2940
2941        if (result.capabilities.contains("PSK") || result.capabilities.contains("EAP")
2942                || result.capabilities.contains("WEP")) {
2943            if (result.capabilities.contains("PSK")) {
2944                config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
2945            }
2946
2947            if (result.capabilities.contains("EAP")) {
2948                config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
2949                config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
2950            }
2951
2952            if (result.capabilities.contains("WEP")) {
2953                config.allowedKeyManagement.set(KeyMgmt.NONE);
2954                config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
2955                config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
2956            }
2957        } else {
2958            config.allowedKeyManagement.set(KeyMgmt.NONE);
2959        }
2960
2961        return config;
2962    }
2963
2964    public WifiConfiguration wifiConfigurationFromScanResult(ScanDetail scanDetail) {
2965        ScanResult result = scanDetail.getScanResult();
2966        return wifiConfigurationFromScanResult(result);
2967    }
2968
2969    /* Returns a unique for a given configuration */
2970    private static int configKey(WifiConfiguration config) {
2971        String key = config.configKey();
2972        return key.hashCode();
2973    }
2974
2975    void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2976        pw.println("Dump of WifiConfigManager");
2977        pw.println("mLastPriority " + mLastPriority);
2978        pw.println("Configured networks");
2979        for (WifiConfiguration conf : getAllConfiguredNetworks()) {
2980            pw.println(conf);
2981        }
2982        pw.println();
2983        if (mLostConfigsDbg != null && mLostConfigsDbg.size() > 0) {
2984            pw.println("LostConfigs: ");
2985            for (String s : mLostConfigsDbg) {
2986                pw.println(s);
2987            }
2988        }
2989        if (mLocalLog != null) {
2990            pw.println("WifiConfigManager - Log Begin ----");
2991            mLocalLog.dump(fd, pw, args);
2992            pw.println("WifiConfigManager - Log End ----");
2993        }
2994        if (mMOManager.isConfigured()) {
2995            pw.println("Begin dump of ANQP Cache");
2996            mAnqpCache.dump(pw);
2997            pw.println("End dump of ANQP Cache");
2998        }
2999    }
3000
3001    public String getConfigFile() {
3002        return IP_CONFIG_FILE;
3003    }
3004
3005    protected void logd(String s) {
3006        Log.d(TAG, s);
3007    }
3008
3009    protected void loge(String s) {
3010        loge(s, false);
3011    }
3012
3013    protected void loge(String s, boolean stack) {
3014        if (stack) {
3015            Log.e(TAG, s + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
3016                    + " - " + Thread.currentThread().getStackTrace()[3].getMethodName()
3017                    + " - " + Thread.currentThread().getStackTrace()[4].getMethodName()
3018                    + " - " + Thread.currentThread().getStackTrace()[5].getMethodName());
3019        } else {
3020            Log.e(TAG, s);
3021        }
3022    }
3023
3024    private void logKernelTime() {
3025        long kernelTimeMs = System.nanoTime() / (1000 * 1000);
3026        StringBuilder builder = new StringBuilder();
3027        builder.append("kernel time = ")
3028                .append(kernelTimeMs / 1000)
3029                .append(".")
3030                .append(kernelTimeMs % 1000)
3031                .append("\n");
3032        localLog(builder.toString());
3033    }
3034
3035    protected void log(String s) {
3036        Log.d(TAG, s);
3037    }
3038
3039    private void localLog(String s) {
3040        if (mLocalLog != null) {
3041            mLocalLog.log(s);
3042        }
3043    }
3044
3045    private void localLogAndLogcat(String s) {
3046        localLog(s);
3047        Log.d(TAG, s);
3048    }
3049
3050    private void localLogNetwork(String s, int netId) {
3051        if (mLocalLog == null) {
3052            return;
3053        }
3054
3055        WifiConfiguration config;
3056        synchronized (mConfiguredNetworks) {             // !!! Useless synchronization
3057            config = mConfiguredNetworks.getForAllUsers(netId);
3058        }
3059
3060        if (config != null) {
3061            mLocalLog.log(s + " " + config.getPrintableSsid() + " " + netId
3062                    + " status=" + config.status
3063                    + " key=" + config.configKey());
3064        } else {
3065            mLocalLog.log(s + " " + netId);
3066        }
3067    }
3068
3069    static boolean needsSoftwareBackedKeyStore(WifiEnterpriseConfig config) {
3070        String client = config.getClientCertificateAlias();
3071        if (!TextUtils.isEmpty(client)) {
3072            // a valid client certificate is configured
3073
3074            // BUGBUG: keyStore.get() never returns certBytes; because it is not
3075            // taking WIFI_UID as a parameter. It always looks for certificate
3076            // with SYSTEM_UID, and never finds any Wifi certificates. Assuming that
3077            // all certificates need software keystore until we get the get() API
3078            // fixed.
3079
3080            return true;
3081        }
3082
3083        /*
3084        try {
3085
3086            if (DBG) Slog.d(TAG, "Loading client certificate " + Credentials
3087                    .USER_CERTIFICATE + client);
3088
3089            CertificateFactory factory = CertificateFactory.getInstance("X.509");
3090            if (factory == null) {
3091                Slog.e(TAG, "Error getting certificate factory");
3092                return;
3093            }
3094
3095            byte[] certBytes = keyStore.get(Credentials.USER_CERTIFICATE + client);
3096            if (certBytes != null) {
3097                Certificate cert = (X509Certificate) factory.generateCertificate(
3098                        new ByteArrayInputStream(certBytes));
3099
3100                if (cert != null) {
3101                    mNeedsSoftwareKeystore = hasHardwareBackedKey(cert);
3102
3103                    if (DBG) Slog.d(TAG, "Loaded client certificate " + Credentials
3104                            .USER_CERTIFICATE + client);
3105                    if (DBG) Slog.d(TAG, "It " + (mNeedsSoftwareKeystore ? "needs" :
3106                            "does not need" ) + " software key store");
3107                } else {
3108                    Slog.d(TAG, "could not generate certificate");
3109                }
3110            } else {
3111                Slog.e(TAG, "Could not load client certificate " + Credentials
3112                        .USER_CERTIFICATE + client);
3113                mNeedsSoftwareKeystore = true;
3114            }
3115
3116        } catch(CertificateException e) {
3117            Slog.e(TAG, "Could not read certificates");
3118            mCaCert = null;
3119            mClientCertificate = null;
3120        }
3121        */
3122
3123        return false;
3124    }
3125
3126    /**
3127     * Checks if the network is a sim config.
3128     * @param config Config corresponding to the network.
3129     * @return true if it is a sim config, false otherwise.
3130     */
3131    public boolean isSimConfig(WifiConfiguration config) {
3132        return mWifiConfigStore.isSimConfig(config);
3133    }
3134
3135    /**
3136     * Resets all sim networks from the network list.
3137     */
3138    public void resetSimNetworks() {
3139        mWifiConfigStore.resetSimNetworks(mConfiguredNetworks.valuesForCurrentUser());
3140    }
3141
3142    boolean isNetworkConfigured(WifiConfiguration config) {
3143        // Check if either we have a network Id or a WifiConfiguration
3144        // matching the one we are trying to add.
3145
3146        if (config.networkId != INVALID_NETWORK_ID) {
3147            return (mConfiguredNetworks.getForCurrentUser(config.networkId) != null);
3148        }
3149
3150        return (mConfiguredNetworks.getByConfigKeyForCurrentUser(config.configKey()) != null);
3151    }
3152
3153    /**
3154     * Checks if uid has access to modify the configuration corresponding to networkId.
3155     *
3156     * The conditions checked are, in descending priority order:
3157     * - Disallow modification if the the configuration is not visible to the uid.
3158     * - Allow modification if the uid represents the Device Owner app.
3159     * - Allow modification if both of the following are true:
3160     *   - The uid represents the configuration's creator or an app holding OVERRIDE_CONFIG_WIFI.
3161     *   - The modification is only for administrative annotation (e.g. when connecting) or the
3162     *     configuration is not lockdown eligible (which currently means that it was not last
3163     *     updated by the DO).
3164     * - Allow modification if configuration lockdown is explicitly disabled and the uid represents
3165     *   an app holding OVERRIDE_CONFIG_WIFI.
3166     * - In all other cases, disallow modification.
3167     */
3168    boolean canModifyNetwork(int uid, int networkId, boolean onlyAnnotate) {
3169        WifiConfiguration config = mConfiguredNetworks.getForCurrentUser(networkId);
3170
3171        if (config == null) {
3172            loge("canModifyNetwork: cannot find config networkId " + networkId);
3173            return false;
3174        }
3175
3176        final DevicePolicyManagerInternal dpmi = LocalServices.getService(
3177                DevicePolicyManagerInternal.class);
3178
3179        final boolean isUidDeviceOwner = dpmi != null && dpmi.isActiveAdminWithPolicy(uid,
3180                DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3181
3182        if (isUidDeviceOwner) {
3183            return true;
3184        }
3185
3186        final boolean isCreator = (config.creatorUid == uid);
3187
3188        if (onlyAnnotate) {
3189            return isCreator || checkConfigOverridePermission(uid);
3190        }
3191
3192        // Check if device has DPM capability. If it has and dpmi is still null, then we
3193        // treat this case with suspicion and bail out.
3194        if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)
3195                && dpmi == null) {
3196            return false;
3197        }
3198
3199        // WiFi config lockdown related logic. At this point we know uid NOT to be a Device Owner.
3200
3201        final boolean isConfigEligibleForLockdown = dpmi != null && dpmi.isActiveAdminWithPolicy(
3202                config.creatorUid, DeviceAdminInfo.USES_POLICY_DEVICE_OWNER);
3203        if (!isConfigEligibleForLockdown) {
3204            return isCreator || checkConfigOverridePermission(uid);
3205        }
3206
3207        final ContentResolver resolver = mContext.getContentResolver();
3208        final boolean isLockdownFeatureEnabled = Settings.Global.getInt(resolver,
3209                Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0) != 0;
3210        return !isLockdownFeatureEnabled && checkConfigOverridePermission(uid);
3211    }
3212
3213    /**
3214     * Checks if uid has access to modify config.
3215     */
3216    boolean canModifyNetwork(int uid, WifiConfiguration config, boolean onlyAnnotate) {
3217        if (config == null) {
3218            loge("canModifyNetowrk recieved null configuration");
3219            return false;
3220        }
3221
3222        // Resolve the correct network id.
3223        int netid;
3224        if (config.networkId != INVALID_NETWORK_ID) {
3225            netid = config.networkId;
3226        } else {
3227            WifiConfiguration test =
3228                    mConfiguredNetworks.getByConfigKeyForCurrentUser(config.configKey());
3229            if (test == null) {
3230                return false;
3231            } else {
3232                netid = test.networkId;
3233            }
3234        }
3235
3236        return canModifyNetwork(uid, netid, onlyAnnotate);
3237    }
3238
3239    boolean checkConfigOverridePermission(int uid) {
3240        try {
3241            return (mFacade.checkUidPermission(
3242                    android.Manifest.permission.OVERRIDE_WIFI_CONFIG, uid)
3243                    == PackageManager.PERMISSION_GRANTED);
3244        } catch (RemoteException e) {
3245            return false;
3246        }
3247    }
3248
3249    /** called when CS ask WiFistateMachine to disconnect the current network
3250     * because the score is bad.
3251     */
3252    void handleBadNetworkDisconnectReport(int netId, WifiInfo info) {
3253        /* TODO verify the bad network is current */
3254        WifiConfiguration config = mConfiguredNetworks.getForCurrentUser(netId);
3255        if (config != null) {
3256            if ((info.is24GHz() && info.getRssi()
3257                    <= WifiQualifiedNetworkSelector.QUALIFIED_RSSI_24G_BAND)
3258                    || (info.is5GHz() && info.getRssi()
3259                    <= WifiQualifiedNetworkSelector.QUALIFIED_RSSI_5G_BAND)) {
3260                // We do not block due to bad RSSI since network selection should not select bad
3261                // RSSI candidate
3262            } else {
3263                // We got disabled but RSSI is good, so disable hard
3264                updateNetworkSelectionStatus(config,
3265                        WifiConfiguration.NetworkSelectionStatus.DISABLED_BAD_LINK);
3266            }
3267        }
3268        // Record last time Connectivity Service switched us away from WiFi and onto Cell
3269        mLastUnwantedNetworkDisconnectTimestamp = System.currentTimeMillis();
3270    }
3271
3272    int getMaxDhcpRetries() {
3273        return mFacade.getIntegerSetting(mContext,
3274                Settings.Global.WIFI_MAX_DHCP_RETRY_COUNT,
3275                DEFAULT_MAX_DHCP_RETRIES);
3276    }
3277
3278    void clearBssidBlacklist() {
3279        mWifiConfigStore.clearBssidBlacklist();
3280    }
3281
3282    void blackListBssid(String bssid) {
3283        mWifiConfigStore.blackListBssid(bssid);
3284    }
3285
3286    public boolean isBssidBlacklisted(String bssid) {
3287        return mWifiConfigStore.isBssidBlacklisted(bssid);
3288    }
3289
3290    public boolean getEnableAutoJoinWhenAssociated() {
3291        return mEnableAutoJoinWhenAssociated.get();
3292    }
3293
3294    public void setEnableAutoJoinWhenAssociated(boolean enabled) {
3295        mEnableAutoJoinWhenAssociated.set(enabled);
3296    }
3297
3298    public void setActiveScanDetail(ScanDetail activeScanDetail) {
3299        synchronized (mActiveScanDetailLock) {
3300            mActiveScanDetail = activeScanDetail;
3301        }
3302    }
3303
3304    /**
3305     * Check if the provided ephemeral network was deleted by the user or not.
3306     * @param ssid ssid of the network
3307     * @return true if network was deleted, false otherwise.
3308     */
3309    public boolean wasEphemeralNetworkDeleted(String ssid) {
3310        return mDeletedEphemeralSSIDs.contains(ssid);
3311    }
3312}
3313