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