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