WifiStateMachine.java revision 486cc89df3277ce7c7ace55fdfd02ae24ce0d665
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.wifi;
18
19import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED;
20import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLING;
21import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED;
22import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLING;
23import static android.net.wifi.WifiManager.WIFI_AP_STATE_FAILED;
24import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
25import static android.net.wifi.WifiManager.WIFI_STATE_DISABLING;
26import static android.net.wifi.WifiManager.WIFI_STATE_ENABLED;
27import static android.net.wifi.WifiManager.WIFI_STATE_ENABLING;
28/**
29 * TODO:
30 * Deprecate WIFI_STATE_UNKNOWN
31 */
32import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
33
34import android.app.ActivityManager;
35import android.app.AlarmManager;
36import android.app.PendingIntent;
37import android.app.backup.IBackupManager;
38import android.bluetooth.BluetoothAdapter;
39import android.content.BroadcastReceiver;
40import android.content.Context;
41import android.content.Intent;
42import android.content.IntentFilter;
43import android.content.pm.PackageManager;
44import android.database.ContentObserver;
45import android.net.ConnectivityManager;
46import android.net.DhcpResults;
47import android.net.BaseDhcpStateMachine;
48import android.net.DhcpStateMachine;
49import android.net.dhcp.DhcpClient;
50import android.net.InterfaceConfiguration;
51import android.net.LinkAddress;
52import android.net.LinkProperties;
53import android.net.NetworkAgent;
54import android.net.NetworkCapabilities;
55import android.net.NetworkFactory;
56import android.net.NetworkInfo;
57import android.net.NetworkInfo.DetailedState;
58import android.net.NetworkRequest;
59import android.net.NetworkUtils;
60import android.net.RouteInfo;
61import android.net.StaticIpConfiguration;
62import android.net.TrafficStats;
63import android.net.wifi.RssiPacketCountInfo;
64import android.net.wifi.ScanResult;
65import android.net.wifi.ScanSettings;
66import android.net.wifi.SupplicantState;
67import android.net.wifi.WifiChannel;
68import android.net.wifi.WifiConfiguration;
69import android.net.wifi.WifiConnectionStatistics;
70import android.net.wifi.WifiEnterpriseConfig;
71import android.net.wifi.WifiInfo;
72import android.net.wifi.WifiLinkLayerStats;
73import android.net.wifi.WifiManager;
74import android.net.wifi.WifiScanner;
75import android.net.wifi.WifiSsid;
76import android.net.wifi.WpsInfo;
77import android.net.wifi.WpsResult;
78import android.net.wifi.WpsResult.Status;
79import android.net.wifi.p2p.IWifiP2pManager;
80import android.os.BatteryStats;
81import android.os.Bundle;
82import android.os.IBinder;
83import android.os.INetworkManagementService;
84import android.os.Looper;
85import android.os.Message;
86import android.os.Messenger;
87import android.os.PowerManager;
88import android.os.Process;
89import android.os.RemoteException;
90import android.os.ServiceManager;
91import android.os.SystemClock;
92import android.os.SystemProperties;
93import android.os.UserHandle;
94import android.os.WorkSource;
95import android.provider.Settings;
96import android.telephony.TelephonyManager;
97import android.text.TextUtils;
98import android.util.Log;
99import android.util.LruCache;
100
101import com.android.internal.R;
102import com.android.internal.app.IBatteryStats;
103import com.android.internal.util.AsyncChannel;
104import com.android.internal.util.Protocol;
105import com.android.internal.util.State;
106import com.android.internal.util.StateMachine;
107import com.android.server.net.NetlinkTracker;
108import com.android.server.wifi.hotspot2.NetworkDetail;
109import com.android.server.wifi.hotspot2.SupplicantBridge;
110import com.android.server.wifi.hotspot2.Utils;
111import com.android.server.wifi.p2p.WifiP2pServiceImpl;
112
113import java.io.BufferedReader;
114import java.io.FileDescriptor;
115import java.io.FileNotFoundException;
116import java.io.FileReader;
117import java.io.IOException;
118import java.io.PrintWriter;
119import java.net.Inet4Address;
120import java.net.InetAddress;
121import java.util.ArrayList;
122import java.util.Calendar;
123import java.util.HashSet;
124import java.util.LinkedList;
125import java.util.List;
126import java.util.Locale;
127import java.util.Queue;
128import java.util.Random;
129import java.util.concurrent.atomic.AtomicBoolean;
130import java.util.concurrent.atomic.AtomicInteger;
131import java.util.regex.Pattern;
132
133/**
134 * Track the state of Wifi connectivity. All event handling is done here,
135 * and all changes in connectivity state are initiated here.
136 *
137 * Wi-Fi now supports three modes of operation: Client, SoftAp and p2p
138 * In the current implementation, we support concurrent wifi p2p and wifi operation.
139 * The WifiStateMachine handles SoftAp and Client operations while WifiP2pService
140 * handles p2p operation.
141 *
142 * @hide
143 */
144public class WifiStateMachine extends StateMachine implements WifiNative.WifiPnoEventHandler {
145
146    private static final String NETWORKTYPE = "WIFI";
147    private static final String NETWORKTYPE_UNTRUSTED = "WIFI_UT";
148    private static boolean DBG = false;
149    private static boolean VDBG = false;
150    private static boolean VVDBG = false;
151    private static boolean USE_PAUSE_SCANS = false;
152    private static boolean mLogMessages = false;
153    private static final String TAG = "WifiStateMachine";
154
155    private static final int ONE_HOUR_MILLI = 1000 * 60 * 60;
156
157    private static final String GOOGLE_OUI = "DA-A1-19";
158
159    /* temporary debug flag - best network selection development */
160    private static boolean PDBG = false;
161
162    /* debug flag, indicating if handling of ASSOCIATION_REJECT ended up blacklisting
163     * the corresponding BSSID.
164     */
165    private boolean didBlackListBSSID = false;
166
167    /**
168     * Log with error attribute
169     *
170     * @param s is string log
171     */
172    protected void loge(String s) {
173        Log.e(getName(), s);
174    }
175    protected void log(String s) {
176        Log.e(getName(), s);
177    }
178
179    private WifiMonitor mWifiMonitor;
180    private WifiNative mWifiNative;
181    private WifiConfigStore mWifiConfigStore;
182    private WifiAutoJoinController mWifiAutoJoinController;
183    private INetworkManagementService mNwService;
184    private ConnectivityManager mCm;
185    private WifiLogger mWifiLogger;
186
187    private final boolean mP2pSupported;
188    private final AtomicBoolean mP2pConnected = new AtomicBoolean(false);
189    private boolean mTemporarilyDisconnectWifi = false;
190    private final String mPrimaryDeviceType;
191
192    /* Scan results handling */
193    private List<ScanDetail> mScanResults = new ArrayList<>();
194    private static final Pattern scanResultPattern = Pattern.compile("\t+");
195    private static final int SCAN_RESULT_CACHE_SIZE = 160;
196    private final LruCache<NetworkDetail, ScanDetail> mScanResultCache;
197    // For debug, number of known scan results that were found as part of last scan result event,
198    // as well the number of scans results returned by the supplicant with that message
199    private int mNumScanResultsKnown;
200    private int mNumScanResultsReturned;
201
202    private boolean mScreenOn = false;
203
204    /* Chipset supports background scan */
205    private final boolean mBackgroundScanSupported;
206
207    private String mInterfaceName;
208    /* Tethering interface could be separate from wlan interface */
209    private String mTetherInterfaceName;
210
211    private int mLastSignalLevel = -1;
212    private String mLastBssid;
213    private int mLastNetworkId; // The network Id we successfully joined
214    private boolean linkDebouncing = false;
215
216    private boolean mHalBasedPnoDriverSupported = false;
217
218    // Below booleans are configurations coming from the Developper Settings
219    private boolean mEnableAssociatedNetworkSwitchingInDevSettings = true;
220    private boolean mHalBasedPnoEnableInDevSettings = false;
221
222
223    private int mHalFeatureSet = 0;
224    private static int mPnoResultFound = 0;
225
226    @Override
227    public void onPnoNetworkFound(ScanResult results[]) {
228        if (DBG) {
229            Log.e(TAG, "onPnoNetworkFound event received num = " + results.length);
230            for (int i = 0; i < results.length; i++) {
231                Log.e(TAG, results[i].toString());
232            }
233        }
234        sendMessage(CMD_PNO_NETWORK_FOUND, results.length, 0, results);
235    }
236
237    public void processPnoNetworkFound(ScanResult results[]) {
238        ScanSettings settings = new ScanSettings();
239        settings.channelSet = new ArrayList<WifiChannel>();
240        StringBuilder sb = new StringBuilder();
241        sb.append("");
242        for (int i=0; i<results.length; i++) {
243            WifiChannel channel = new WifiChannel();
244            channel.freqMHz = results[i].frequency;
245            settings.channelSet.add(channel);
246            sb.append(results[i].SSID).append(" ");
247        }
248
249        stopPnoOffload();
250
251        Log.e(TAG, "processPnoNetworkFound starting scan cnt=" + mPnoResultFound);
252        startScan(PNO_NETWORK_FOUND_SOURCE, mPnoResultFound,  settings, null);
253        mPnoResultFound ++;
254        //sendMessage(CMD_SCAN_RESULTS_AVAILABLE);
255        int delay = 30 * 1000;
256        // reconfigure Pno after 1 minutes if we're still in disconnected state
257        sendMessageDelayed(CMD_RESTART_AUTOJOIN_OFFLOAD, delay,
258                mRestartAutoJoinOffloadCounter, " processPnoNetworkFound " + sb.toString(),
259                (long)delay);
260        mRestartAutoJoinOffloadCounter++;
261    }
262
263    // Testing various network disconnect cases by sending lots of spurious
264    // disconnect to supplicant
265    private boolean testNetworkDisconnect = false;
266
267    private boolean mEnableRssiPolling = false;
268    private boolean mLegacyPnoEnabled = false;
269    private int mRssiPollToken = 0;
270    /* 3 operational states for STA operation: CONNECT_MODE, SCAN_ONLY_MODE, SCAN_ONLY_WIFI_OFF_MODE
271    * In CONNECT_MODE, the STA can scan and connect to an access point
272    * In SCAN_ONLY_MODE, the STA can only scan for access points
273    * In SCAN_ONLY_WIFI_OFF_MODE, the STA can only scan for access points with wifi toggle being off
274    */
275    private int mOperationalMode = CONNECT_MODE;
276    private boolean mIsScanOngoing = false;
277    private boolean mIsFullScanOngoing = false;
278    private boolean mSendScanResultsBroadcast = false;
279
280    private final Queue<Message> mBufferedScanMsg = new LinkedList<Message>();
281    private WorkSource mScanWorkSource = null;
282    private static final int UNKNOWN_SCAN_SOURCE = -1;
283    private static final int SCAN_ALARM_SOURCE = -2;
284    private static final int ADD_OR_UPDATE_SOURCE = -3;
285    private static final int SET_ALLOW_UNTRUSTED_SOURCE = -4;
286    private static final int ENABLE_WIFI = -5;
287    public static final int DFS_RESTRICTED_SCAN_REQUEST = -6;
288    public static final int PNO_NETWORK_FOUND_SOURCE = -7;
289
290    private static final int SCAN_REQUEST_BUFFER_MAX_SIZE = 10;
291    private static final String CUSTOMIZED_SCAN_SETTING = "customized_scan_settings";
292    private static final String CUSTOMIZED_SCAN_WORKSOURCE = "customized_scan_worksource";
293    private static final String SCAN_REQUEST_TIME = "scan_request_time";
294
295    /* Tracks if state machine has received any screen state change broadcast yet.
296     * We can miss one of these at boot.
297     */
298    private AtomicBoolean mScreenBroadcastReceived = new AtomicBoolean(false);
299
300    private boolean mBluetoothConnectionActive = false;
301
302    private PowerManager.WakeLock mSuspendWakeLock;
303
304    /**
305     * Interval in milliseconds between polling for RSSI
306     * and linkspeed information
307     */
308    private static final int POLL_RSSI_INTERVAL_MSECS = 3000;
309
310    /**
311     * Interval in milliseconds between receiving a disconnect event
312     * while connected to a good AP, and handling the disconnect proper
313     */
314    private static final int LINK_FLAPPING_DEBOUNCE_MSEC = 7000;
315
316    /**
317     * Delay between supplicant restarts upon failure to establish connection
318     */
319    private static final int SUPPLICANT_RESTART_INTERVAL_MSECS = 5000;
320
321    /**
322     * Number of times we attempt to restart supplicant
323     */
324    private static final int SUPPLICANT_RESTART_TRIES = 5;
325
326    private int mSupplicantRestartCount = 0;
327    /* Tracks sequence number on stop failure message */
328    private int mSupplicantStopFailureToken = 0;
329
330    /**
331     * Tether state change notification time out
332     */
333    private static final int TETHER_NOTIFICATION_TIME_OUT_MSECS = 5000;
334
335    /* Tracks sequence number on a tether notification time out */
336    private int mTetherToken = 0;
337
338    /**
339     * Driver start time out.
340     */
341    private static final int DRIVER_START_TIME_OUT_MSECS = 10000;
342
343    /* Tracks sequence number on a driver time out */
344    private int mDriverStartToken = 0;
345
346    /**
347     * The link properties of the wifi interface.
348     * Do not modify this directly; use updateLinkProperties instead.
349     */
350    private LinkProperties mLinkProperties;
351
352    /* Tracks sequence number on a periodic scan message */
353    private int mPeriodicScanToken = 0;
354
355    // Wakelock held during wifi start/stop and driver load/unload
356    private PowerManager.WakeLock mWakeLock;
357
358    private Context mContext;
359
360    private final Object mDhcpResultsLock = new Object();
361    private DhcpResults mDhcpResults;
362    private WifiInfo mWifiInfo;
363    private NetworkInfo mNetworkInfo;
364    private NetworkCapabilities mNetworkCapabilities;
365    private SupplicantStateTracker mSupplicantStateTracker;
366    private BaseDhcpStateMachine mDhcpStateMachine;
367    private boolean mDhcpActive = false;
368
369    private int mWifiLinkLayerStatsSupported = 4; // Temporary disable
370
371    private final AtomicInteger mCountryCodeSequence = new AtomicInteger();
372
373    // Whether the state machine goes thru the Disconnecting->Disconnected->ObtainingIpAddress
374    private int mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE;
375
376    // Roaming failure count
377    private int mRoamFailCount = 0;
378
379    // This is the BSSID we are trying to associate to, it can be set to "any"
380    // if we havent selected a BSSID for joining.
381    // if we havent selected a BSSID for joining.
382    // The BSSID we are associated to is found in mWifiInfo
383    private String mTargetRoamBSSID = "any";
384
385    private long mLastDriverRoamAttempt = 0;
386
387    private WifiConfiguration targetWificonfiguration = null;
388
389    // Used as debug to indicate which configuration last was saved
390    private WifiConfiguration lastSavedConfigurationAttempt = null;
391
392    // Used as debug to indicate which configuration last was removed
393    private WifiConfiguration lastForgetConfigurationAttempt = null;
394
395    //Random used by softAP channel Selection
396    private static Random mRandom = new Random(Calendar.getInstance().getTimeInMillis());
397
398    boolean isRoaming() {
399        return mAutoRoaming == WifiAutoJoinController.AUTO_JOIN_ROAMING
400                || mAutoRoaming == WifiAutoJoinController.AUTO_JOIN_EXTENDED_ROAMING;
401    }
402
403    public void autoRoamSetBSSID(int netId, String bssid) {
404        autoRoamSetBSSID(mWifiConfigStore.getWifiConfiguration(netId), bssid);
405    }
406
407    public boolean autoRoamSetBSSID(WifiConfiguration config, String bssid) {
408        boolean ret = true;
409        if (mTargetRoamBSSID == null) mTargetRoamBSSID = "any";
410        if (bssid == null) bssid = "any";
411        if (config == null) return false; // Nothing to do
412
413        if (mTargetRoamBSSID != null && bssid == mTargetRoamBSSID && bssid == config.BSSID) {
414            return false; // We didnt change anything
415        }
416        if (!mTargetRoamBSSID.equals("any") && bssid.equals("any")) {
417            // Changing to ANY
418            if (!mWifiConfigStore.roamOnAny) {
419                ret = false; // Nothing to do
420            }
421        }
422        if (VDBG) {
423            loge("autoRoamSetBSSID " + bssid
424                    + " key=" + config.configKey());
425        }
426        config.autoJoinBSSID = bssid;
427        mTargetRoamBSSID = bssid;
428        mWifiConfigStore.saveWifiConfigBSSID(config);
429        return ret;
430    }
431
432    /**
433     * Subset of link properties coming from netlink.
434     * Currently includes IPv4 and IPv6 addresses. In the future will also include IPv6 DNS servers
435     * and domains obtained from router advertisements (RFC 6106).
436     */
437    private NetlinkTracker mNetlinkTracker;
438
439    private AlarmManager mAlarmManager;
440    private PendingIntent mScanIntent;
441    private PendingIntent mDriverStopIntent;
442
443    /* Tracks current frequency mode */
444    private AtomicInteger mFrequencyBand = new AtomicInteger(WifiManager.WIFI_FREQUENCY_BAND_AUTO);
445
446    /* Tracks if we are filtering Multicast v4 packets. Default is to filter. */
447    private AtomicBoolean mFilteringMulticastV4Packets = new AtomicBoolean(true);
448
449    // Channel for sending replies.
450    private AsyncChannel mReplyChannel = new AsyncChannel();
451
452    private WifiP2pServiceImpl mWifiP2pServiceImpl;
453
454    // Used to initiate a connection with WifiP2pService
455    private AsyncChannel mWifiP2pChannel;
456    private AsyncChannel mWifiApConfigChannel;
457
458    private WifiScanner mWifiScanner;
459
460    private int mConnectionRequests = 0;
461    private WifiNetworkFactory mNetworkFactory;
462    private UntrustedWifiNetworkFactory mUntrustedNetworkFactory;
463    private WifiNetworkAgent mNetworkAgent;
464
465    private String[] mWhiteListedSsids = null;
466
467    // Keep track of various statistics, for retrieval by System Apps, i.e. under @SystemApi
468    // We should really persist that into the networkHistory.txt file, and read it back when
469    // WifiStateMachine starts up
470    private WifiConnectionStatistics mWifiConnectionStatistics = new WifiConnectionStatistics();
471
472    // Used to filter out requests we couldn't possibly satisfy.
473    private final NetworkCapabilities mNetworkCapabilitiesFilter = new NetworkCapabilities();
474
475    /* The base for wifi message types */
476    static final int BASE = Protocol.BASE_WIFI;
477    /* Start the supplicant */
478    static final int CMD_START_SUPPLICANT                               = BASE + 11;
479    /* Stop the supplicant */
480    static final int CMD_STOP_SUPPLICANT                                = BASE + 12;
481    /* Start the driver */
482    static final int CMD_START_DRIVER                                   = BASE + 13;
483    /* Stop the driver */
484    static final int CMD_STOP_DRIVER                                    = BASE + 14;
485    /* Indicates Static IP succeeded */
486    static final int CMD_STATIC_IP_SUCCESS                              = BASE + 15;
487    /* Indicates Static IP failed */
488    static final int CMD_STATIC_IP_FAILURE                              = BASE + 16;
489    /* Indicates supplicant stop failed */
490    static final int CMD_STOP_SUPPLICANT_FAILED                         = BASE + 17;
491    /* Delayed stop to avoid shutting down driver too quick*/
492    static final int CMD_DELAYED_STOP_DRIVER                            = BASE + 18;
493    /* A delayed message sent to start driver when it fail to come up */
494    static final int CMD_DRIVER_START_TIMED_OUT                         = BASE + 19;
495
496    /* Start the soft access point */
497    static final int CMD_START_AP                                       = BASE + 21;
498    /* Indicates soft ap start succeeded */
499    static final int CMD_START_AP_SUCCESS                               = BASE + 22;
500    /* Indicates soft ap start failed */
501    static final int CMD_START_AP_FAILURE                               = BASE + 23;
502    /* Stop the soft access point */
503    static final int CMD_STOP_AP                                        = BASE + 24;
504    /* Set the soft access point configuration */
505    static final int CMD_SET_AP_CONFIG                                  = BASE + 25;
506    /* Soft access point configuration set completed */
507    static final int CMD_SET_AP_CONFIG_COMPLETED                        = BASE + 26;
508    /* Request the soft access point configuration */
509    static final int CMD_REQUEST_AP_CONFIG                              = BASE + 27;
510    /* Response to access point configuration request */
511    static final int CMD_RESPONSE_AP_CONFIG                             = BASE + 28;
512    /* Invoked when getting a tether state change notification */
513    static final int CMD_TETHER_STATE_CHANGE                            = BASE + 29;
514    /* A delayed message sent to indicate tether state change failed to arrive */
515    static final int CMD_TETHER_NOTIFICATION_TIMED_OUT                  = BASE + 30;
516
517    static final int CMD_BLUETOOTH_ADAPTER_STATE_CHANGE                 = BASE + 31;
518
519    /* Supplicant commands */
520    /* Is supplicant alive ? */
521    static final int CMD_PING_SUPPLICANT                                = BASE + 51;
522    /* Add/update a network configuration */
523    static final int CMD_ADD_OR_UPDATE_NETWORK                          = BASE + 52;
524    /* Delete a network */
525    static final int CMD_REMOVE_NETWORK                                 = BASE + 53;
526    /* Enable a network. The device will attempt a connection to the given network. */
527    static final int CMD_ENABLE_NETWORK                                 = BASE + 54;
528    /* Enable all networks */
529    static final int CMD_ENABLE_ALL_NETWORKS                            = BASE + 55;
530    /* Blacklist network. De-prioritizes the given BSSID for connection. */
531    static final int CMD_BLACKLIST_NETWORK                              = BASE + 56;
532    /* Clear the blacklist network list */
533    static final int CMD_CLEAR_BLACKLIST                                = BASE + 57;
534    /* Save configuration */
535    static final int CMD_SAVE_CONFIG                                    = BASE + 58;
536    /* Get configured networks */
537    static final int CMD_GET_CONFIGURED_NETWORKS                        = BASE + 59;
538    /* Get available frequencies */
539    static final int CMD_GET_CAPABILITY_FREQ                            = BASE + 60;
540    /* Get adaptors */
541    static final int CMD_GET_SUPPORTED_FEATURES                         = BASE + 61;
542    /* Get configured networks with real preSharedKey */
543    static final int CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS             = BASE + 62;
544    /* Get Link Layer Stats thru HAL */
545    static final int CMD_GET_LINK_LAYER_STATS                           = BASE + 63;
546    /* Supplicant commands after driver start*/
547    /* Initiate a scan */
548    static final int CMD_START_SCAN                                     = BASE + 71;
549    /* Set operational mode. CONNECT, SCAN ONLY, SCAN_ONLY with Wi-Fi off mode */
550    static final int CMD_SET_OPERATIONAL_MODE                           = BASE + 72;
551    /* Disconnect from a network */
552    static final int CMD_DISCONNECT                                     = BASE + 73;
553    /* Reconnect to a network */
554    static final int CMD_RECONNECT                                      = BASE + 74;
555    /* Reassociate to a network */
556    static final int CMD_REASSOCIATE                                    = BASE + 75;
557    /* Get Connection Statistis */
558    static final int CMD_GET_CONNECTION_STATISTICS                      = BASE + 76;
559
560    /* Controls suspend mode optimizations
561     *
562     * When high perf mode is enabled, suspend mode optimizations are disabled
563     *
564     * When high perf mode is disabled, suspend mode optimizations are enabled
565     *
566     * Suspend mode optimizations include:
567     * - packet filtering
568     * - turn off roaming
569     * - DTIM wake up settings
570     */
571    static final int CMD_SET_HIGH_PERF_MODE                             = BASE + 77;
572    /* Set the country code */
573    static final int CMD_SET_COUNTRY_CODE                               = BASE + 80;
574    /* Enables RSSI poll */
575    static final int CMD_ENABLE_RSSI_POLL                               = BASE + 82;
576    /* RSSI poll */
577    static final int CMD_RSSI_POLL                                      = BASE + 83;
578    /* Set up packet filtering */
579    static final int CMD_START_PACKET_FILTERING                         = BASE + 84;
580    /* Clear packet filter */
581    static final int CMD_STOP_PACKET_FILTERING                          = BASE + 85;
582    /* Enable suspend mode optimizations in the driver */
583    static final int CMD_SET_SUSPEND_OPT_ENABLED                        = BASE + 86;
584    /* Delayed NETWORK_DISCONNECT */
585    static final int CMD_DELAYED_NETWORK_DISCONNECT                     = BASE + 87;
586    /* When there are no saved networks, we do a periodic scan to notify user of
587     * an open network */
588    static final int CMD_NO_NETWORKS_PERIODIC_SCAN                      = BASE + 88;
589    /* Test network Disconnection NETWORK_DISCONNECT */
590    static final int CMD_TEST_NETWORK_DISCONNECT                        = BASE + 89;
591
592    private int testNetworkDisconnectCounter = 0;
593
594    /* arg1 values to CMD_STOP_PACKET_FILTERING and CMD_START_PACKET_FILTERING */
595    static final int MULTICAST_V6 = 1;
596    static final int MULTICAST_V4 = 0;
597
598    /* Set the frequency band */
599    static final int CMD_SET_FREQUENCY_BAND                             = BASE + 90;
600    /* Enable TDLS on a specific MAC address */
601    static final int CMD_ENABLE_TDLS                                    = BASE + 92;
602    /* DHCP/IP configuration watchdog */
603    static final int CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER            = BASE + 93;
604
605    /**
606     * Watchdog for protecting against b/16823537
607     * Leave time for 4-ways handshake to succeed
608     */
609    static final int ROAM_GUARD_TIMER_MSEC = 15000;
610
611    int roamWatchdogCount = 0;
612    /* Roam state watchdog */
613    static final int CMD_ROAM_WATCHDOG_TIMER                            = BASE + 94;
614    /* Screen change intent handling */
615    static final int CMD_SCREEN_STATE_CHANGED                           = BASE + 95;
616
617    /* Disconnecting state watchdog */
618    static final int CMD_DISCONNECTING_WATCHDOG_TIMER                   = BASE + 96;
619
620    /* Disable an ephemeral network */
621    static final int CMD_DISABLE_EPHEMERAL_NETWORK                      = BASE + 98;
622
623    /* Get matching network */
624    static final int CMD_GET_MATCHING_CONFIG                            = BASE + 99;
625
626    /* alert from firmware */
627    static final int CMD_FIRMWARE_ALERT                                 = BASE + 100;
628
629    /**
630     * Make this timer 40 seconds, which is about the normal DHCP timeout.
631     * In no valid case, the WiFiStateMachine should remain stuck in ObtainingIpAddress
632     * for more than 30 seconds.
633     */
634    static final int OBTAINING_IP_ADDRESS_GUARD_TIMER_MSEC = 40000;
635
636    int obtainingIpWatchdogCount = 0;
637
638    /* Commands from/to the SupplicantStateTracker */
639    /* Reset the supplicant state tracker */
640    static final int CMD_RESET_SUPPLICANT_STATE                         = BASE + 111;
641
642    int disconnectingWatchdogCount = 0;
643    static final int DISCONNECTING_GUARD_TIMER_MSEC = 5000;
644
645    /* P2p commands */
646    /* We are ok with no response here since we wont do much with it anyway */
647    public static final int CMD_ENABLE_P2P                              = BASE + 131;
648    /* In order to shut down supplicant cleanly, we wait till p2p has
649     * been disabled */
650    public static final int CMD_DISABLE_P2P_REQ                         = BASE + 132;
651    public static final int CMD_DISABLE_P2P_RSP                         = BASE + 133;
652
653    public static final int CMD_BOOT_COMPLETED                          = BASE + 134;
654
655    /* We now have a valid IP configuration. */
656    static final int CMD_IP_CONFIGURATION_SUCCESSFUL                    = BASE + 138;
657    /* We no longer have a valid IP configuration. */
658    static final int CMD_IP_CONFIGURATION_LOST                          = BASE + 139;
659    /* Link configuration (IP address, DNS, ...) changes notified via netlink */
660    static final int CMD_UPDATE_LINKPROPERTIES                          = BASE + 140;
661
662    /* Supplicant is trying to associate to a given BSSID */
663    static final int CMD_TARGET_BSSID                                   = BASE + 141;
664
665    /* Reload all networks and reconnect */
666    static final int CMD_RELOAD_TLS_AND_RECONNECT                       = BASE + 142;
667
668    static final int CMD_AUTO_CONNECT                                   = BASE + 143;
669
670    static final int network_status_unwanted_disconnect = 0;
671    static final int network_status_unwanted_disable_autojoin = 1;
672
673    static final int CMD_UNWANTED_NETWORK                               = BASE + 144;
674
675    static final int CMD_AUTO_ROAM                                      = BASE + 145;
676
677    static final int CMD_AUTO_SAVE_NETWORK                              = BASE + 146;
678
679    static final int CMD_ASSOCIATED_BSSID                               = BASE + 147;
680
681    static final int CMD_NETWORK_STATUS                                 = BASE + 148;
682
683    /* used to restart PNO when it was stopped due to association attempt */
684    static final int CMD_RESTART_AUTOJOIN_OFFLOAD                       = BASE + 149;
685
686    static int mRestartAutoJoinOffloadCounter = 0;
687
688    /* used to log if PNO was started */
689    static final int CMD_STARTED_PNO_DBG                                = BASE + 150;
690
691    static final int CMD_PNO_NETWORK_FOUND                              = BASE + 151;
692
693    static final int CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION              = BASE + 152;
694
695    /* used to log if GSCAN was started */
696    static final int CMD_STARTED_GSCAN_DBG                              = BASE + 153;
697
698
699    /* Wifi state machine modes of operation */
700    /* CONNECT_MODE - connect to any 'known' AP when it becomes available */
701    public static final int CONNECT_MODE = 1;
702    /* SCAN_ONLY_MODE - don't connect to any APs; scan, but only while apps hold lock */
703    public static final int SCAN_ONLY_MODE = 2;
704    /* SCAN_ONLY_WITH_WIFI_OFF - scan, but don't connect to any APs */
705    public static final int SCAN_ONLY_WITH_WIFI_OFF_MODE = 3;
706
707    private static final int SUCCESS = 1;
708    private static final int FAILURE = -1;
709
710    /* Tracks if suspend optimizations need to be disabled by DHCP,
711     * screen or due to high perf mode.
712     * When any of them needs to disable it, we keep the suspend optimizations
713     * disabled
714     */
715    private int mSuspendOptNeedsDisabled = 0;
716
717    private static final int SUSPEND_DUE_TO_DHCP = 1;
718    private static final int SUSPEND_DUE_TO_HIGH_PERF = 1 << 1;
719    private static final int SUSPEND_DUE_TO_SCREEN = 1 << 2;
720
721    /* Tracks if user has enabled suspend optimizations through settings */
722    private AtomicBoolean mUserWantsSuspendOpt = new AtomicBoolean(true);
723
724    /**
725     * Default framework scan interval in milliseconds. This is used in the scenario in which
726     * wifi chipset does not support background scanning to set up a
727     * periodic wake up scan so that the device can connect to a new access
728     * point on the move. {@link Settings.Global#WIFI_FRAMEWORK_SCAN_INTERVAL_MS} can
729     * override this.
730     */
731    private final int mDefaultFrameworkScanIntervalMs;
732
733
734    /**
735     * Scan period for the NO_NETWORKS_PERIIDOC_SCAN_FEATURE
736     */
737    private final int mNoNetworksPeriodicScan;
738
739    /**
740     * Supplicant scan interval in milliseconds.
741     * Comes from {@link Settings.Global#WIFI_SUPPLICANT_SCAN_INTERVAL_MS} or
742     * from the default config if the setting is not set
743     */
744    private long mSupplicantScanIntervalMs;
745
746    /**
747     * timeStamp of last full band scan we perfoemed for autojoin while connected with screen lit
748     */
749    private long lastFullBandConnectedTimeMilli;
750
751    /**
752     * time interval to the next full band scan we will perform for
753     * autojoin while connected with screen lit
754     */
755    private long fullBandConnectedTimeIntervalMilli;
756
757    /**
758     * max time interval to the next full band scan we will perform for
759     * autojoin while connected with screen lit
760     * Max time is 5 minutes
761     */
762    private static final long maxFullBandConnectedTimeIntervalMilli = 1000 * 60 * 5;
763
764    /**
765     * Minimum time interval between enabling all networks.
766     * A device can end up repeatedly connecting to a bad network on screen on/off toggle
767     * due to enabling every time. We add a threshold to avoid this.
768     */
769    private static final int MIN_INTERVAL_ENABLE_ALL_NETWORKS_MS = 10 * 60 * 1000; /* 10 minutes */
770    private long mLastEnableAllNetworksTime;
771
772    int mRunningBeaconCount = 0;
773
774    /**
775     * Starting and shutting down driver too quick causes problems leading to driver
776     * being in a bad state. Delay driver stop.
777     */
778    private final int mDriverStopDelayMs;
779    private int mDelayedStopCounter;
780    private boolean mInDelayedStop = false;
781
782    // there is a delay between StateMachine change country code and Supplicant change country code
783    // here save the current WifiStateMachine set country code
784    private volatile String mSetCountryCode = null;
785
786    // Supplicant doesn't like setting the same country code multiple times (it may drop
787    // currently connected network), so we save the current device set country code here to avoid
788    // redundency
789    private String mDriverSetCountryCode = null;
790
791    /* Default parent state */
792    private State mDefaultState = new DefaultState();
793    /* Temporary initial state */
794    private State mInitialState = new InitialState();
795    /* Driver loaded, waiting for supplicant to start */
796    private State mSupplicantStartingState = new SupplicantStartingState();
797    /* Driver loaded and supplicant ready */
798    private State mSupplicantStartedState = new SupplicantStartedState();
799    /* Waiting for supplicant to stop and monitor to exit */
800    private State mSupplicantStoppingState = new SupplicantStoppingState();
801    /* Driver start issued, waiting for completed event */
802    private State mDriverStartingState = new DriverStartingState();
803    /* Driver started */
804    private State mDriverStartedState = new DriverStartedState();
805    /* Wait until p2p is disabled
806     * This is a special state which is entered right after we exit out of DriverStartedState
807     * before transitioning to another state.
808     */
809    private State mWaitForP2pDisableState = new WaitForP2pDisableState();
810    /* Driver stopping */
811    private State mDriverStoppingState = new DriverStoppingState();
812    /* Driver stopped */
813    private State mDriverStoppedState = new DriverStoppedState();
814    /* Scan for networks, no connection will be established */
815    private State mScanModeState = new ScanModeState();
816    /* Connecting to an access point */
817    private State mConnectModeState = new ConnectModeState();
818    /* Connected at 802.11 (L2) level */
819    private State mL2ConnectedState = new L2ConnectedState();
820    /* fetching IP after connection to access point (assoc+auth complete) */
821    private State mObtainingIpState = new ObtainingIpState();
822    /* Waiting for link quality verification to be complete */
823    private State mVerifyingLinkState = new VerifyingLinkState();
824    /* Connected with IP addr */
825    private State mConnectedState = new ConnectedState();
826    /* Roaming */
827    private State mRoamingState = new RoamingState();
828    /* disconnect issued, waiting for network disconnect confirmation */
829    private State mDisconnectingState = new DisconnectingState();
830    /* Network is not connected, supplicant assoc+auth is not complete */
831    private State mDisconnectedState = new DisconnectedState();
832    /* Waiting for WPS to be completed*/
833    private State mWpsRunningState = new WpsRunningState();
834
835    /* Soft ap is starting up */
836    private State mSoftApStartingState = new SoftApStartingState();
837    /* Soft ap is running */
838    private State mSoftApStartedState = new SoftApStartedState();
839    /* Soft ap is running and we are waiting for tether notification */
840    private State mTetheringState = new TetheringState();
841    /* Soft ap is running and we are tethered through connectivity service */
842    private State mTetheredState = new TetheredState();
843    /* Waiting for untether confirmation before stopping soft Ap */
844    private State mUntetheringState = new UntetheringState();
845
846
847
848    private class WifiScanListener implements WifiScanner.ScanListener {
849        @Override
850        public void onSuccess() {
851            Log.e(TAG, "WifiScanListener onSuccess");
852        };
853        @Override
854        public void onFailure(int reason, String description) {
855            Log.e(TAG, "WifiScanListener onFailure");
856        };
857        @Override
858        public void onPeriodChanged(int periodInMs) {
859            Log.e(TAG, "WifiScanListener onPeriodChanged  period=" + periodInMs);
860        }
861        @Override
862        public void onResults(ScanResult[] results) {
863            Log.e(TAG, "WifiScanListener onResults" + results.length);
864        }
865        @Override
866        public void onResults(WifiScanner.ScanData[] results) {
867            Log.e(TAG, "WifiScanListener onResults2 "  + results.length);
868        }
869        @Override
870        public void onFullResult(ScanResult fullScanResult) {
871            Log.e(TAG, "WifiScanListener onFullResult " + fullScanResult.toString());
872        }
873
874        WifiScanListener() {}
875    }
876
877    WifiScanListener mWifiScanListener = new WifiScanListener();
878
879
880    private class TetherStateChange {
881        ArrayList<String> available;
882        ArrayList<String> active;
883
884        TetherStateChange(ArrayList<String> av, ArrayList<String> ac) {
885            available = av;
886            active = ac;
887        }
888    }
889
890    public static class SimAuthRequestData {
891        int networkId;
892        int protocol;
893        String ssid;
894        // EAP-SIM: data[] contains the 3 rand, one for each of the 3 challenges
895        // EAP-AKA/AKA': data[] contains rand & authn couple for the single challenge
896        String[] data;
897    }
898
899    /**
900     * One of  {@link WifiManager#WIFI_STATE_DISABLED},
901     * {@link WifiManager#WIFI_STATE_DISABLING},
902     * {@link WifiManager#WIFI_STATE_ENABLED},
903     * {@link WifiManager#WIFI_STATE_ENABLING},
904     * {@link WifiManager#WIFI_STATE_UNKNOWN}
905     */
906    private final AtomicInteger mWifiState = new AtomicInteger(WIFI_STATE_DISABLED);
907
908    /**
909     * One of  {@link WifiManager#WIFI_AP_STATE_DISABLED},
910     * {@link WifiManager#WIFI_AP_STATE_DISABLING},
911     * {@link WifiManager#WIFI_AP_STATE_ENABLED},
912     * {@link WifiManager#WIFI_AP_STATE_ENABLING},
913     * {@link WifiManager#WIFI_AP_STATE_FAILED}
914     */
915    private final AtomicInteger mWifiApState = new AtomicInteger(WIFI_AP_STATE_DISABLED);
916
917    private static final int SCAN_REQUEST = 0;
918    private static final String ACTION_START_SCAN =
919            "com.android.server.WifiManager.action.START_SCAN";
920
921    private static final String DELAYED_STOP_COUNTER = "DelayedStopCounter";
922    private static final int DRIVER_STOP_REQUEST = 0;
923    private static final String ACTION_DELAYED_DRIVER_STOP =
924            "com.android.server.WifiManager.action.DELAYED_DRIVER_STOP";
925
926    /**
927     * Keep track of whether WIFI is running.
928     */
929    private boolean mIsRunning = false;
930
931    /**
932     * Keep track of whether we last told the battery stats we had started.
933     */
934    private boolean mReportedRunning = false;
935
936    /**
937     * Most recently set source of starting WIFI.
938     */
939    private final WorkSource mRunningWifiUids = new WorkSource();
940
941    /**
942     * The last reported UIDs that were responsible for starting WIFI.
943     */
944    private final WorkSource mLastRunningWifiUids = new WorkSource();
945
946    private final IBatteryStats mBatteryStats;
947
948    private String mTcpBufferSizes = null;
949
950    // Used for debug and stats gathering
951    private static int sScanAlarmIntentCount = 0;
952
953    final static int frameworkMinScanIntervalSaneValue = 10000;
954
955    boolean mPnoEnabled;
956    boolean mLazyRoamEnabled;
957    long mGScanStartTimeMilli;
958    long mGScanPeriodMilli;
959
960    public WifiStateMachine(Context context, String wlanInterface,
961                            WifiTrafficPoller trafficPoller) {
962        super("WifiStateMachine");
963        mContext = context;
964        mSetCountryCode = Settings.Global.getString(
965                mContext.getContentResolver(), Settings.Global.WIFI_COUNTRY_CODE);
966        mInterfaceName = wlanInterface;
967        mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, NETWORKTYPE, "");
968        mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
969                BatteryStats.SERVICE_NAME));
970
971        IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
972        mNwService = INetworkManagementService.Stub.asInterface(b);
973
974        mP2pSupported = mContext.getPackageManager().hasSystemFeature(
975                PackageManager.FEATURE_WIFI_DIRECT);
976
977        mWifiNative = new WifiNative(mInterfaceName);
978        mWifiConfigStore = new WifiConfigStore(context, mWifiNative);
979        mWifiAutoJoinController = new WifiAutoJoinController(context, this,
980                mWifiConfigStore, mWifiConnectionStatistics, mWifiNative);
981        mWifiMonitor = new WifiMonitor(this, mWifiNative);
982        mWifiLogger = new WifiLogger(this);
983
984        mWifiInfo = new WifiInfo();
985        mSupplicantStateTracker = new SupplicantStateTracker(context, this, mWifiConfigStore,
986                getHandler());
987        mLinkProperties = new LinkProperties();
988
989        IBinder s1 = ServiceManager.getService(Context.WIFI_P2P_SERVICE);
990        mWifiP2pServiceImpl = (WifiP2pServiceImpl) IWifiP2pManager.Stub.asInterface(s1);
991
992        mNetworkInfo.setIsAvailable(false);
993        mLastBssid = null;
994        mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID;
995        mLastSignalLevel = -1;
996
997        mNetlinkTracker = new NetlinkTracker(mInterfaceName, new NetlinkTracker.Callback() {
998            public void update() {
999                sendMessage(CMD_UPDATE_LINKPROPERTIES);
1000            }
1001        });
1002        try {
1003            mNwService.registerObserver(mNetlinkTracker);
1004        } catch (RemoteException e) {
1005            loge("Couldn't register netlink tracker: " + e.toString());
1006        }
1007
1008        mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
1009        mScanIntent = getPrivateBroadcast(ACTION_START_SCAN, SCAN_REQUEST);
1010
1011        // Make sure the interval is not configured less than 10 seconds
1012        int period = mContext.getResources().getInteger(
1013                R.integer.config_wifi_framework_scan_interval);
1014        if (period < frameworkMinScanIntervalSaneValue) {
1015            period = frameworkMinScanIntervalSaneValue;
1016        }
1017        mDefaultFrameworkScanIntervalMs = period;
1018
1019        mNoNetworksPeriodicScan = mContext.getResources().getInteger(
1020                R.integer.config_wifi_no_network_periodic_scan_interval);
1021
1022        mDriverStopDelayMs = mContext.getResources().getInteger(
1023                R.integer.config_wifi_driver_stop_delay);
1024
1025        mBackgroundScanSupported = mContext.getResources().getBoolean(
1026                R.bool.config_wifi_background_scan_support);
1027
1028        mPrimaryDeviceType = mContext.getResources().getString(
1029                R.string.config_wifi_p2p_device_type);
1030
1031        mUserWantsSuspendOpt.set(Settings.Global.getInt(mContext.getContentResolver(),
1032                Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED, 1) == 1);
1033
1034        mNetworkCapabilitiesFilter.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
1035        mNetworkCapabilitiesFilter.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
1036        mNetworkCapabilitiesFilter.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
1037        mNetworkCapabilitiesFilter.setLinkUpstreamBandwidthKbps(1024 * 1024);
1038        mNetworkCapabilitiesFilter.setLinkDownstreamBandwidthKbps(1024 * 1024);
1039        // TODO - needs to be a bit more dynamic
1040        mNetworkCapabilities = new NetworkCapabilities(mNetworkCapabilitiesFilter);
1041
1042        mContext.registerReceiver(
1043                new BroadcastReceiver() {
1044                    @Override
1045                    public void onReceive(Context context, Intent intent) {
1046                        ArrayList<String> available = intent.getStringArrayListExtra(
1047                                ConnectivityManager.EXTRA_AVAILABLE_TETHER);
1048                        ArrayList<String> active = intent.getStringArrayListExtra(
1049                                ConnectivityManager.EXTRA_ACTIVE_TETHER);
1050                        sendMessage(CMD_TETHER_STATE_CHANGE, new TetherStateChange(available, active));
1051                    }
1052                }, new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED));
1053
1054        mContext.registerReceiver(
1055                new BroadcastReceiver() {
1056                    @Override
1057                    public void onReceive(Context context, Intent intent) {
1058                        sScanAlarmIntentCount++; // Used for debug only
1059                        startScan(SCAN_ALARM_SOURCE, mDelayedScanCounter.incrementAndGet(), null, null);
1060                        if (VDBG)
1061                            loge("WiFiStateMachine SCAN ALARM -> " + mDelayedScanCounter.get());
1062                    }
1063                },
1064                new IntentFilter(ACTION_START_SCAN));
1065
1066        IntentFilter filter = new IntentFilter();
1067        filter.addAction(Intent.ACTION_SCREEN_ON);
1068        filter.addAction(Intent.ACTION_SCREEN_OFF);
1069        mContext.registerReceiver(
1070                new BroadcastReceiver() {
1071                    @Override
1072                    public void onReceive(Context context, Intent intent) {
1073                        String action = intent.getAction();
1074
1075                        if (action.equals(Intent.ACTION_SCREEN_ON)) {
1076                            sendMessage(CMD_SCREEN_STATE_CHANGED, 1);
1077                        } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1078                            sendMessage(CMD_SCREEN_STATE_CHANGED, 0);
1079                        }
1080                    }
1081                }, filter);
1082
1083        mContext.registerReceiver(
1084                new BroadcastReceiver() {
1085                    @Override
1086                    public void onReceive(Context context, Intent intent) {
1087                        int counter = intent.getIntExtra(DELAYED_STOP_COUNTER, 0);
1088                        sendMessage(CMD_DELAYED_STOP_DRIVER, counter, 0);
1089                    }
1090                },
1091                new IntentFilter(ACTION_DELAYED_DRIVER_STOP));
1092
1093        mContext.getContentResolver().registerContentObserver(Settings.Global.getUriFor(
1094                        Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED), false,
1095                new ContentObserver(getHandler()) {
1096                    @Override
1097                    public void onChange(boolean selfChange) {
1098                        mUserWantsSuspendOpt.set(Settings.Global.getInt(mContext.getContentResolver(),
1099                                Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED, 1) == 1);
1100                    }
1101                });
1102
1103        mContext.registerReceiver(
1104                new BroadcastReceiver() {
1105                    @Override
1106                    public void onReceive(Context context, Intent intent) {
1107                        sendMessage(CMD_BOOT_COMPLETED);
1108                    }
1109                },
1110                new IntentFilter(Intent.ACTION_BOOT_COMPLETED));
1111
1112        mScanResultCache = new LruCache<>(SCAN_RESULT_CACHE_SIZE);
1113
1114        PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
1115        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getName());
1116
1117        mSuspendWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WifiSuspend");
1118        mSuspendWakeLock.setReferenceCounted(false);
1119
1120        mTcpBufferSizes = mContext.getResources().getString(
1121                com.android.internal.R.string.config_wifi_tcp_buffers);
1122
1123        addState(mDefaultState);
1124            addState(mInitialState, mDefaultState);
1125            addState(mSupplicantStartingState, mDefaultState);
1126            addState(mSupplicantStartedState, mDefaultState);
1127                addState(mDriverStartingState, mSupplicantStartedState);
1128                addState(mDriverStartedState, mSupplicantStartedState);
1129                    addState(mScanModeState, mDriverStartedState);
1130                    addState(mConnectModeState, mDriverStartedState);
1131                        addState(mL2ConnectedState, mConnectModeState);
1132                            addState(mObtainingIpState, mL2ConnectedState);
1133                            addState(mVerifyingLinkState, mL2ConnectedState);
1134                            addState(mConnectedState, mL2ConnectedState);
1135                            addState(mRoamingState, mL2ConnectedState);
1136                        addState(mDisconnectingState, mConnectModeState);
1137                        addState(mDisconnectedState, mConnectModeState);
1138                        addState(mWpsRunningState, mConnectModeState);
1139                addState(mWaitForP2pDisableState, mSupplicantStartedState);
1140                addState(mDriverStoppingState, mSupplicantStartedState);
1141                addState(mDriverStoppedState, mSupplicantStartedState);
1142            addState(mSupplicantStoppingState, mDefaultState);
1143            addState(mSoftApStartingState, mDefaultState);
1144            addState(mSoftApStartedState, mDefaultState);
1145                addState(mTetheringState, mSoftApStartedState);
1146                addState(mTetheredState, mSoftApStartedState);
1147                addState(mUntetheringState, mSoftApStartedState);
1148
1149        setInitialState(mInitialState);
1150
1151        setLogRecSize(ActivityManager.isLowRamDeviceStatic() ? 100 : 3000);
1152        setLogOnlyTransitions(false);
1153        if (VDBG) setDbg(true);
1154
1155        //start the state machine
1156        start();
1157
1158        final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE);
1159        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1160        intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED);
1161        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1162    }
1163
1164
1165    PendingIntent getPrivateBroadcast(String action, int requestCode) {
1166        Intent intent = new Intent(action, null);
1167        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1168        intent.setPackage(this.getClass().getPackage().getName());
1169        return PendingIntent.getBroadcast(mContext, requestCode, intent, 0);
1170    }
1171
1172    private int mVerboseLoggingLevel = 0;
1173
1174    int getVerboseLoggingLevel() {
1175        return mVerboseLoggingLevel;
1176    }
1177
1178    void enableVerboseLogging(int verbose) {
1179        mVerboseLoggingLevel = verbose;
1180        if (verbose > 0) {
1181            DBG = true;
1182            VDBG = true;
1183            PDBG = true;
1184            mLogMessages = true;
1185            //mWifiNative.setSupplicantLogLevel("DEBUG");
1186        } else {
1187            DBG = false;
1188            VDBG = false;
1189            PDBG = false;
1190            mLogMessages = false;
1191            mWifiNative.setSupplicantLogLevel("INFO");
1192        }
1193        mWifiLogger.startLogging(mVerboseLoggingLevel > 0);
1194        mWifiAutoJoinController.enableVerboseLogging(verbose);
1195        mWifiMonitor.enableVerboseLogging(verbose);
1196        mWifiNative.enableVerboseLogging(verbose);
1197        mWifiConfigStore.enableVerboseLogging(verbose);
1198        mSupplicantStateTracker.enableVerboseLogging(verbose);
1199    }
1200
1201    public void setHalBasedAutojoinOffload(int enabled) {
1202        // Shoult be used for debug only, triggered form developper settings
1203        // enabling HAl based PNO dynamically is not safe and not a normal operation
1204        mHalBasedPnoEnableInDevSettings = enabled > 0;
1205        mWifiConfigStore.enableHalBasedPno.set(mHalBasedPnoEnableInDevSettings);
1206        mWifiConfigStore.enableSsidWhitelist.set(mHalBasedPnoEnableInDevSettings);
1207        sendMessage(CMD_DISCONNECT);
1208    }
1209
1210    public void setAllowNetworkSwitchingWhileAssociated(int enabled) {
1211        mEnableAssociatedNetworkSwitchingInDevSettings = enabled > 0;
1212    }
1213
1214    int getHalBasedAutojoinOffload() {
1215        return mHalBasedPnoEnableInDevSettings ? 1 : 0;
1216    }
1217
1218    int getAllowNetworkSwitchingWhileAssociated() {
1219        return mEnableAssociatedNetworkSwitchingInDevSettings ? 1 : 0;
1220    }
1221
1222    boolean useHalBasedAutoJoinOffload() {
1223        // all three settings need to be true:
1224        // - developper settings switch
1225        // - driver support
1226        // - config option
1227        return mHalBasedPnoEnableInDevSettings
1228                && mHalBasedPnoDriverSupported
1229                && mWifiConfigStore.enableHalBasedPno.get();
1230    }
1231
1232    boolean allowFullBandScanAndAssociated() {
1233
1234        if (!mWifiConfigStore.enableAutoJoinScanWhenAssociated.get()) {
1235            if (DBG) {
1236                Log.e(TAG, "allowFullBandScanAndAssociated: "
1237                        + " enableAutoJoinScanWhenAssociated : disallow");
1238            }
1239            return false;
1240        }
1241
1242        if (mWifiInfo.txSuccessRate >
1243                mWifiConfigStore.maxTxPacketForFullScans
1244                || mWifiInfo.rxSuccessRate >
1245                mWifiConfigStore.maxRxPacketForFullScans) {
1246            if (DBG) {
1247                Log.e(TAG, "allowFullBandScanAndAssociated: packet rate tx"
1248                        + mWifiInfo.txSuccessRate + "  rx "
1249                        + mWifiInfo.rxSuccessRate
1250                        + " allow scan with traffic " + getAllowScansWithTraffic());
1251            }
1252            // Too much traffic at the interface, hence no full band scan
1253            if (getAllowScansWithTraffic() == 0) {
1254                return false;
1255            }
1256        }
1257
1258        if (getCurrentState() != mConnectedState) {
1259            if (DBG) {
1260                Log.e(TAG, "allowFullBandScanAndAssociated: getCurrentState() : disallow");
1261            }
1262            return false;
1263        }
1264
1265        return true;
1266    }
1267
1268    long mLastScanPermissionUpdate = 0;
1269    boolean mConnectedModeGScanOffloadStarted = false;
1270    // Don't do a G-scan enable/re-enable cycle more than once within 20seconds
1271    // The function updateAssociatedScanPermission() can be called quite frequently, hence
1272    // we want to throttle the GScan Stop->Start transition
1273    static final long SCAN_PERMISSION_UPDATE_THROTTLE_MILLI = 20000;
1274    void updateAssociatedScanPermission() {
1275
1276        if (useHalBasedAutoJoinOffload()) {
1277            boolean allowed = allowFullBandScanAndAssociated();
1278
1279            long now = System.currentTimeMillis();
1280            if (mConnectedModeGScanOffloadStarted && !allowed) {
1281                if (DBG) {
1282                    Log.e(TAG, " useHalBasedAutoJoinOffload stop offload");
1283                }
1284                stopPnoOffload();
1285                stopGScan(" useHalBasedAutoJoinOffload");
1286            }
1287            if (!mConnectedModeGScanOffloadStarted && allowed) {
1288                if ((now - mLastScanPermissionUpdate) > SCAN_PERMISSION_UPDATE_THROTTLE_MILLI) {
1289                    // Re-enable Gscan offload, this will trigger periodic scans and allow firmware
1290                    // to look for 5GHz BSSIDs and better networks
1291                    if (DBG) {
1292                        Log.e(TAG, " useHalBasedAutoJoinOffload restart offload");
1293                    }
1294                    startGScanConnectedModeOffload("updatePermission "
1295                            + (now - mLastScanPermissionUpdate) + "ms");
1296                    mLastScanPermissionUpdate = now;
1297                }
1298            }
1299        }
1300    }
1301
1302    private int mAggressiveHandover = 0;
1303
1304    int getAggressiveHandover() {
1305        return mAggressiveHandover;
1306    }
1307
1308    void enableAggressiveHandover(int enabled) {
1309        mAggressiveHandover = enabled;
1310    }
1311
1312    public void clearANQPCache() {
1313        mWifiConfigStore.trimANQPCache(true);
1314    }
1315
1316    public void setAllowScansWithTraffic(int enabled) {
1317        mWifiConfigStore.alwaysEnableScansWhileAssociated.set(enabled);
1318    }
1319
1320    public int getAllowScansWithTraffic() {
1321        return mWifiConfigStore.alwaysEnableScansWhileAssociated.get();
1322    }
1323
1324    public void setAllowScansWhileAssociated(int enabled) {
1325        mWifiConfigStore.enableAutoJoinScanWhenAssociated.set(enabled > 0 ? true : false);
1326    }
1327
1328    public int getAllowScansWhileAssociated() {
1329        return mWifiConfigStore.enableAutoJoinScanWhenAssociated.get() ? 1 : 0;
1330    }
1331
1332    /*
1333     *
1334     * Framework scan control
1335     */
1336
1337    private boolean mAlarmEnabled = false;
1338
1339    private AtomicInteger mDelayedScanCounter = new AtomicInteger();
1340
1341    private void setScanAlarm(boolean enabled) {
1342        if (PDBG) {
1343            String state;
1344            if (enabled) state = "enabled"; else state = "disabled";
1345            loge("setScanAlarm " + state
1346                    + " defaultperiod " + mDefaultFrameworkScanIntervalMs
1347                    + " mBackgroundScanSupported " + mBackgroundScanSupported);
1348        }
1349        if (mBackgroundScanSupported == false) {
1350            // Scan alarm is only used for background scans if they are not
1351            // offloaded to the wifi chipset, hence enable the scan alarm
1352            // gicing us RTC_WAKEUP of backgroundScan is NOT supported
1353            enabled = true;
1354        }
1355
1356        if (enabled == mAlarmEnabled) return;
1357        if (enabled) {
1358            /* Set RTC_WAKEUP alarms if PNO is not supported - because no one is */
1359            /* going to wake up the host processor to look for access points */
1360            mAlarmManager.set(AlarmManager.RTC_WAKEUP,
1361                    System.currentTimeMillis() + mDefaultFrameworkScanIntervalMs,
1362                    mScanIntent);
1363            mAlarmEnabled = true;
1364        } else {
1365            mAlarmManager.cancel(mScanIntent);
1366            mAlarmEnabled = false;
1367        }
1368    }
1369
1370    private void cancelDelayedScan() {
1371        mDelayedScanCounter.incrementAndGet();
1372    }
1373
1374    private boolean checkAndRestartDelayedScan(int counter, boolean restart, int milli,
1375                                               ScanSettings settings, WorkSource workSource) {
1376
1377        if (counter != mDelayedScanCounter.get()) {
1378            return false;
1379        }
1380        if (restart)
1381            startDelayedScan(milli, settings, workSource);
1382        return true;
1383    }
1384
1385    private void startDelayedScan(int milli, ScanSettings settings, WorkSource workSource) {
1386        if (milli <= 0) return;
1387        /**
1388         * The cases where the scan alarm should be run are :
1389         * - DisconnectedState && screenOn => used delayed timer
1390         * - DisconnectedState && !screenOn && mBackgroundScanSupported => PNO
1391         * - DisconnectedState && !screenOn && !mBackgroundScanSupported => used RTC_WAKEUP Alarm
1392         * - ConnectedState && screenOn => used delayed timer
1393         */
1394
1395        mDelayedScanCounter.incrementAndGet();
1396        if (mScreenOn &&
1397                (getCurrentState() == mDisconnectedState
1398                        || getCurrentState() == mConnectedState)) {
1399            Bundle bundle = new Bundle();
1400            bundle.putParcelable(CUSTOMIZED_SCAN_SETTING, settings);
1401            bundle.putParcelable(CUSTOMIZED_SCAN_WORKSOURCE, workSource);
1402            bundle.putLong(SCAN_REQUEST_TIME, System.currentTimeMillis());
1403            sendMessageDelayed(CMD_START_SCAN, SCAN_ALARM_SOURCE,
1404                    mDelayedScanCounter.get(), bundle, milli);
1405            if (DBG) loge("startDelayedScan send -> " + mDelayedScanCounter + " milli " + milli);
1406        } else if (mBackgroundScanSupported == false
1407                && !mScreenOn && getCurrentState() == mDisconnectedState) {
1408            setScanAlarm(true);
1409            if (DBG) loge("startDelayedScan start scan alarm -> "
1410                    + mDelayedScanCounter + " milli " + milli);
1411        } else {
1412            if (DBG) loge("startDelayedScan unhandled -> "
1413                    + mDelayedScanCounter + " milli " + milli);
1414        }
1415    }
1416
1417    private boolean setRandomMacOui() {
1418        String oui = mContext.getResources().getString(
1419                R.string.config_wifi_random_mac_oui, GOOGLE_OUI);
1420        String[] ouiParts = oui.split("-");
1421        byte[] ouiBytes = new byte[3];
1422        ouiBytes[0] = (byte) (Integer.parseInt(ouiParts[0], 16) & 0xFF);
1423        ouiBytes[1] = (byte) (Integer.parseInt(ouiParts[1], 16) & 0xFF);
1424        ouiBytes[2] = (byte) (Integer.parseInt(ouiParts[2], 16) & 0xFF);
1425
1426        logd("Setting OUI to " + oui);
1427        return mWifiNative.setScanningMacOui(ouiBytes);
1428    }
1429
1430    /**
1431     * ******************************************************
1432     * Methods exposed for public use
1433     * ******************************************************
1434     */
1435
1436    public Messenger getMessenger() {
1437        return new Messenger(getHandler());
1438    }
1439
1440    public WifiMonitor getWifiMonitor() {
1441        return mWifiMonitor;
1442    }
1443
1444    /**
1445     * TODO: doc
1446     */
1447    public boolean syncPingSupplicant(AsyncChannel channel) {
1448        Message resultMsg = channel.sendMessageSynchronously(CMD_PING_SUPPLICANT);
1449        boolean result = (resultMsg.arg1 != FAILURE);
1450        resultMsg.recycle();
1451        return result;
1452    }
1453
1454    public List<WifiChannel> syncGetChannelList(AsyncChannel channel) {
1455        Message resultMsg = channel.sendMessageSynchronously(CMD_GET_CAPABILITY_FREQ);
1456        List<WifiChannel> list = null;
1457        if (resultMsg.obj != null) {
1458            list = new ArrayList<WifiChannel>();
1459            String freqs = (String) resultMsg.obj;
1460            String[] lines = freqs.split("\n");
1461            for (String line : lines)
1462                if (line.contains("MHz")) {
1463                    // line format: " 52 = 5260 MHz (NO_IBSS) (DFS)"
1464                    WifiChannel c = new WifiChannel();
1465                    String[] prop = line.split(" ");
1466                    if (prop.length < 5) continue;
1467                    try {
1468                        c.channelNum = Integer.parseInt(prop[1]);
1469                        c.freqMHz = Integer.parseInt(prop[3]);
1470                    } catch (NumberFormatException e) {
1471                    }
1472                    c.isDFS = line.contains("(DFS)");
1473                    list.add(c);
1474                } else if (line.contains("Mode[B] Channels:")) {
1475                    // B channels are the same as G channels, skipped
1476                    break;
1477                }
1478        }
1479        resultMsg.recycle();
1480        return (list != null && list.size() > 0) ? list : null;
1481    }
1482
1483    /**
1484     * When settings allowing making use of untrusted networks change, trigger a scan
1485     * so as to kick of autojoin.
1486     */
1487    public void startScanForUntrustedSettingChange() {
1488        startScan(SET_ALLOW_UNTRUSTED_SOURCE, 0, null, null);
1489    }
1490
1491    /**
1492     * Initiate a wifi scan. If workSource is not null, blame is given to it, otherwise blame is
1493     * given to callingUid.
1494     *
1495     * @param callingUid The uid initiating the wifi scan. Blame will be given here unless
1496     *                   workSource is specified.
1497     * @param workSource If not null, blame is given to workSource.
1498     * @param settings   Scan settings, see {@link ScanSettings}.
1499     */
1500    public void startScan(int callingUid, int scanCounter,
1501                          ScanSettings settings, WorkSource workSource) {
1502        Bundle bundle = new Bundle();
1503        bundle.putParcelable(CUSTOMIZED_SCAN_SETTING, settings);
1504        bundle.putParcelable(CUSTOMIZED_SCAN_WORKSOURCE, workSource);
1505        bundle.putLong(SCAN_REQUEST_TIME, System.currentTimeMillis());
1506        sendMessage(CMD_START_SCAN, callingUid, scanCounter, bundle);
1507    }
1508
1509    // called from BroadcastListener
1510
1511    /**
1512     * Start reading new scan data
1513     * Data comes in as:
1514     * "scancount=5\n"
1515     * "nextcount=5\n"
1516     * "apcount=3\n"
1517     * "trunc\n" (optional)
1518     * "bssid=...\n"
1519     * "ssid=...\n"
1520     * "freq=...\n" (in Mhz)
1521     * "level=...\n"
1522     * "dist=...\n" (in cm)
1523     * "distsd=...\n" (standard deviation, in cm)
1524     * "===="
1525     * "bssid=...\n"
1526     * etc
1527     * "===="
1528     * "bssid=...\n"
1529     * etc
1530     * "%%%%"
1531     * "apcount=2\n"
1532     * "bssid=...\n"
1533     * etc
1534     * "%%%%
1535     * etc
1536     * "----"
1537     */
1538    private final static boolean DEBUG_PARSE = false;
1539
1540    private long mDisconnectedTimeStamp = 0;
1541
1542    public long getDisconnectedTimeMilli() {
1543        if (getCurrentState() == mDisconnectedState
1544                && mDisconnectedTimeStamp != 0) {
1545            long now_ms = System.currentTimeMillis();
1546            return now_ms - mDisconnectedTimeStamp;
1547        }
1548        return 0;
1549    }
1550
1551    // Keeping track of scan requests
1552    private long lastStartScanTimeStamp = 0;
1553    private long lastScanDuration = 0;
1554    // Last connect attempt is used to prevent scan requests:
1555    //  - for a period of 10 seconds after attempting to connect
1556    private long lastConnectAttempt = 0;
1557    private String lastScanFreqs = null;
1558
1559    // For debugging, keep track of last message status handling
1560    // TODO, find an equivalent mechanism as part of parent class
1561    private static int MESSAGE_HANDLING_STATUS_PROCESSED = 2;
1562    private static int MESSAGE_HANDLING_STATUS_OK = 1;
1563    private static int MESSAGE_HANDLING_STATUS_UNKNOWN = 0;
1564    private static int MESSAGE_HANDLING_STATUS_REFUSED = -1;
1565    private static int MESSAGE_HANDLING_STATUS_FAIL = -2;
1566    private static int MESSAGE_HANDLING_STATUS_OBSOLETE = -3;
1567    private static int MESSAGE_HANDLING_STATUS_DEFERRED = -4;
1568    private static int MESSAGE_HANDLING_STATUS_DISCARD = -5;
1569    private static int MESSAGE_HANDLING_STATUS_LOOPED = -6;
1570    private static int MESSAGE_HANDLING_STATUS_HANDLING_ERROR = -7;
1571
1572    private int messageHandlingStatus = 0;
1573
1574    //TODO: this is used only to track connection attempts, however the link state and packet per
1575    //TODO: second logic should be folded into that
1576    private boolean checkOrDeferScanAllowed(Message msg) {
1577        long now = System.currentTimeMillis();
1578        if (lastConnectAttempt != 0 && (now - lastConnectAttempt) < 10000) {
1579            Message dmsg = Message.obtain(msg);
1580            sendMessageDelayed(dmsg, 11000 - (now - lastConnectAttempt));
1581            return false;
1582        }
1583        return true;
1584    }
1585
1586    private int mOnTime = 0;
1587    private int mTxTime = 0;
1588    private int mRxTime = 0;
1589    private int mOnTimeStartScan = 0;
1590    private int mTxTimeStartScan = 0;
1591    private int mRxTimeStartScan = 0;
1592    private int mOnTimeScan = 0;
1593    private int mTxTimeScan = 0;
1594    private int mRxTimeScan = 0;
1595    private int mOnTimeThisScan = 0;
1596    private int mTxTimeThisScan = 0;
1597    private int mRxTimeThisScan = 0;
1598
1599    private int mOnTimeScreenStateChange = 0;
1600    private int mOnTimeAtLastReport = 0;
1601    private long lastOntimeReportTimeStamp = 0;
1602    private long lastScreenStateChangeTimeStamp = 0;
1603    private int mOnTimeLastReport = 0;
1604    private int mTxTimeLastReport = 0;
1605    private int mRxTimeLastReport = 0;
1606
1607    private long lastLinkLayerStatsUpdate = 0;
1608
1609    String reportOnTime() {
1610        long now = System.currentTimeMillis();
1611        StringBuilder sb = new StringBuilder();
1612        // Report stats since last report
1613        int on = mOnTime - mOnTimeLastReport;
1614        mOnTimeLastReport = mOnTime;
1615        int tx = mTxTime - mTxTimeLastReport;
1616        mTxTimeLastReport = mTxTime;
1617        int rx = mRxTime - mRxTimeLastReport;
1618        mRxTimeLastReport = mRxTime;
1619        int period = (int) (now - lastOntimeReportTimeStamp);
1620        lastOntimeReportTimeStamp = now;
1621        sb.append(String.format("[on:%d tx:%d rx:%d period:%d]", on, tx, rx, period));
1622        // Report stats since Screen State Changed
1623        on = mOnTime - mOnTimeScreenStateChange;
1624        period = (int) (now - lastScreenStateChangeTimeStamp);
1625        sb.append(String.format(" from screen [on:%d period:%d]", on, period));
1626        return sb.toString();
1627    }
1628
1629    WifiLinkLayerStats getWifiLinkLayerStats(boolean dbg) {
1630        WifiLinkLayerStats stats = null;
1631        if (mWifiLinkLayerStatsSupported > 0) {
1632            String name = "wlan0";
1633            stats = mWifiNative.getWifiLinkLayerStats(name);
1634            if (name != null && stats == null && mWifiLinkLayerStatsSupported > 0) {
1635                mWifiLinkLayerStatsSupported -= 1;
1636            } else if (stats != null) {
1637                lastLinkLayerStatsUpdate = System.currentTimeMillis();
1638                mOnTime = stats.on_time;
1639                mTxTime = stats.tx_time;
1640                mRxTime = stats.rx_time;
1641                mRunningBeaconCount = stats.beacon_rx;
1642                if (dbg) {
1643                    // loge(stats.toString());
1644                }
1645            }
1646        }
1647        if (stats == null || mWifiLinkLayerStatsSupported <= 0) {
1648            long mTxPkts = TrafficStats.getTxPackets(mInterfaceName);
1649            long mRxPkts = TrafficStats.getRxPackets(mInterfaceName);
1650            mWifiInfo.updatePacketRates(mTxPkts, mRxPkts);
1651        } else {
1652            mWifiInfo.updatePacketRates(stats);
1653        }
1654        sendMessage(CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION);
1655        return stats;
1656    }
1657
1658    void startRadioScanStats() {
1659        WifiLinkLayerStats stats = getWifiLinkLayerStats(false);
1660        if (stats != null) {
1661            mOnTimeStartScan = stats.on_time;
1662            mTxTimeStartScan = stats.tx_time;
1663            mRxTimeStartScan = stats.rx_time;
1664            mOnTime = stats.on_time;
1665            mTxTime = stats.tx_time;
1666            mRxTime = stats.rx_time;
1667        }
1668    }
1669
1670    void closeRadioScanStats() {
1671        WifiLinkLayerStats stats = getWifiLinkLayerStats(false);
1672        if (stats != null) {
1673            mOnTimeThisScan = stats.on_time - mOnTimeStartScan;
1674            mTxTimeThisScan = stats.tx_time - mTxTimeStartScan;
1675            mRxTimeThisScan = stats.rx_time - mRxTimeStartScan;
1676            mOnTimeScan += mOnTimeThisScan;
1677            mTxTimeScan += mTxTimeThisScan;
1678            mRxTimeScan += mRxTimeThisScan;
1679        }
1680    }
1681
1682    // If workSource is not null, blame is given to it, otherwise blame is given to callingUid.
1683    private void noteScanStart(int callingUid, WorkSource workSource) {
1684        long now = System.currentTimeMillis();
1685        lastStartScanTimeStamp = now;
1686        lastScanDuration = 0;
1687        if (DBG) {
1688            String ts = String.format("[%,d ms]", now);
1689            if (workSource != null) {
1690                loge(ts + " noteScanStart" + workSource.toString()
1691                        + " uid " + Integer.toString(callingUid));
1692            } else {
1693                loge(ts + " noteScanstart no scan source"
1694                        + " uid " + Integer.toString(callingUid));
1695            }
1696        }
1697        startRadioScanStats();
1698        if (mScanWorkSource == null && ((callingUid != UNKNOWN_SCAN_SOURCE
1699                && callingUid != SCAN_ALARM_SOURCE)
1700                || workSource != null)) {
1701            mScanWorkSource = workSource != null ? workSource : new WorkSource(callingUid);
1702            try {
1703                mBatteryStats.noteWifiScanStartedFromSource(mScanWorkSource);
1704            } catch (RemoteException e) {
1705                log(e.toString());
1706            }
1707        }
1708    }
1709
1710    private void noteScanEnd() {
1711        long now = System.currentTimeMillis();
1712        if (lastStartScanTimeStamp != 0) {
1713            lastScanDuration = now - lastStartScanTimeStamp;
1714        }
1715        lastStartScanTimeStamp = 0;
1716        if (DBG) {
1717            String ts = String.format("[%,d ms]", now);
1718            if (mScanWorkSource != null)
1719                loge(ts + " noteScanEnd " + mScanWorkSource.toString()
1720                        + " onTime=" + mOnTimeThisScan);
1721            else
1722                loge(ts + " noteScanEnd no scan source"
1723                        + " onTime=" + mOnTimeThisScan);
1724        }
1725        if (mScanWorkSource != null) {
1726            try {
1727                mBatteryStats.noteWifiScanStoppedFromSource(mScanWorkSource);
1728            } catch (RemoteException e) {
1729                log(e.toString());
1730            } finally {
1731                mScanWorkSource = null;
1732            }
1733        }
1734    }
1735
1736    private void handleScanRequest(int type, Message message) {
1737        ScanSettings settings = null;
1738        WorkSource workSource = null;
1739
1740        // unbundle parameters
1741        Bundle bundle = (Bundle) message.obj;
1742
1743        if (bundle != null) {
1744            settings = bundle.getParcelable(CUSTOMIZED_SCAN_SETTING);
1745            workSource = bundle.getParcelable(CUSTOMIZED_SCAN_WORKSOURCE);
1746        }
1747
1748        // parse scan settings
1749        String freqs = null;
1750        if (settings != null && settings.channelSet != null) {
1751            StringBuilder sb = new StringBuilder();
1752            boolean first = true;
1753            for (WifiChannel channel : settings.channelSet) {
1754                if (!first) sb.append(',');
1755                else first = false;
1756                sb.append(channel.freqMHz);
1757            }
1758            freqs = sb.toString();
1759        }
1760
1761        // call wifi native to start the scan
1762        if (startScanNative(type, freqs)) {
1763            // only count battery consumption if scan request is accepted
1764            noteScanStart(message.arg1, workSource);
1765            // a full scan covers everything, clearing scan request buffer
1766            if (freqs == null)
1767                mBufferedScanMsg.clear();
1768            messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK;
1769            if (workSource != null) {
1770                // External worksource was passed along the scan request,
1771                // hence always send a broadcast
1772                mSendScanResultsBroadcast = true;
1773            }
1774            return;
1775        }
1776
1777        // if reach here, scan request is rejected
1778
1779        if (!mIsScanOngoing) {
1780            // if rejection is NOT due to ongoing scan (e.g. bad scan parameters),
1781
1782            // discard this request and pop up the next one
1783            if (mBufferedScanMsg.size() > 0) {
1784                sendMessage(mBufferedScanMsg.remove());
1785            }
1786            messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
1787        } else if (!mIsFullScanOngoing) {
1788            // if rejection is due to an ongoing scan, and the ongoing one is NOT a full scan,
1789            // buffer the scan request to make sure specified channels will be scanned eventually
1790            if (freqs == null)
1791                mBufferedScanMsg.clear();
1792            if (mBufferedScanMsg.size() < SCAN_REQUEST_BUFFER_MAX_SIZE) {
1793                Message msg = obtainMessage(CMD_START_SCAN,
1794                        message.arg1, message.arg2, bundle);
1795                mBufferedScanMsg.add(msg);
1796            } else {
1797                // if too many requests in buffer, combine them into a single full scan
1798                bundle = new Bundle();
1799                bundle.putParcelable(CUSTOMIZED_SCAN_SETTING, null);
1800                bundle.putParcelable(CUSTOMIZED_SCAN_WORKSOURCE, workSource);
1801                Message msg = obtainMessage(CMD_START_SCAN, message.arg1, message.arg2, bundle);
1802                mBufferedScanMsg.clear();
1803                mBufferedScanMsg.add(msg);
1804            }
1805            messageHandlingStatus = MESSAGE_HANDLING_STATUS_LOOPED;
1806        } else {
1807            // mIsScanOngoing and mIsFullScanOngoing
1808            messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
1809        }
1810    }
1811
1812
1813    /**
1814     * return true iff scan request is accepted
1815     */
1816    private boolean startScanNative(int type, String freqs) {
1817        if (mWifiNative.scan(type, freqs)) {
1818            mIsScanOngoing = true;
1819            mIsFullScanOngoing = (freqs == null);
1820            lastScanFreqs = freqs;
1821            return true;
1822        }
1823        return false;
1824    }
1825
1826    /**
1827     * TODO: doc
1828     */
1829    public void setSupplicantRunning(boolean enable) {
1830        if (enable) {
1831            sendMessage(CMD_START_SUPPLICANT);
1832        } else {
1833            sendMessage(CMD_STOP_SUPPLICANT);
1834        }
1835    }
1836
1837    /**
1838     * TODO: doc
1839     */
1840    public void setHostApRunning(WifiConfiguration wifiConfig, boolean enable) {
1841        if (enable) {
1842            sendMessage(CMD_START_AP, wifiConfig);
1843        } else {
1844            sendMessage(CMD_STOP_AP);
1845        }
1846    }
1847
1848    public void setWifiApConfiguration(WifiConfiguration config) {
1849        mWifiApConfigChannel.sendMessage(CMD_SET_AP_CONFIG, config);
1850    }
1851
1852    public WifiConfiguration syncGetWifiApConfiguration() {
1853        Message resultMsg = mWifiApConfigChannel.sendMessageSynchronously(CMD_REQUEST_AP_CONFIG);
1854        WifiConfiguration ret = (WifiConfiguration) resultMsg.obj;
1855        resultMsg.recycle();
1856        return ret;
1857    }
1858
1859    /**
1860     * TODO: doc
1861     */
1862    public int syncGetWifiState() {
1863        return mWifiState.get();
1864    }
1865
1866    /**
1867     * TODO: doc
1868     */
1869    public String syncGetWifiStateByName() {
1870        switch (mWifiState.get()) {
1871            case WIFI_STATE_DISABLING:
1872                return "disabling";
1873            case WIFI_STATE_DISABLED:
1874                return "disabled";
1875            case WIFI_STATE_ENABLING:
1876                return "enabling";
1877            case WIFI_STATE_ENABLED:
1878                return "enabled";
1879            case WIFI_STATE_UNKNOWN:
1880                return "unknown state";
1881            default:
1882                return "[invalid state]";
1883        }
1884    }
1885
1886    /**
1887     * TODO: doc
1888     */
1889    public int syncGetWifiApState() {
1890        return mWifiApState.get();
1891    }
1892
1893    /**
1894     * TODO: doc
1895     */
1896    public String syncGetWifiApStateByName() {
1897        switch (mWifiApState.get()) {
1898            case WIFI_AP_STATE_DISABLING:
1899                return "disabling";
1900            case WIFI_AP_STATE_DISABLED:
1901                return "disabled";
1902            case WIFI_AP_STATE_ENABLING:
1903                return "enabling";
1904            case WIFI_AP_STATE_ENABLED:
1905                return "enabled";
1906            case WIFI_AP_STATE_FAILED:
1907                return "failed";
1908            default:
1909                return "[invalid state]";
1910        }
1911    }
1912
1913    /**
1914     * Get status information for the current connection, if any.
1915     *
1916     * @return a {@link WifiInfo} object containing information about the current connection
1917     */
1918    public WifiInfo syncRequestConnectionInfo() {
1919        return mWifiInfo;
1920    }
1921
1922    public DhcpResults syncGetDhcpResults() {
1923        synchronized (mDhcpResultsLock) {
1924            return new DhcpResults(mDhcpResults);
1925        }
1926    }
1927
1928    /**
1929     * TODO: doc
1930     */
1931    public void setDriverStart(boolean enable) {
1932        if (enable) {
1933            sendMessage(CMD_START_DRIVER);
1934        } else {
1935            sendMessage(CMD_STOP_DRIVER);
1936        }
1937    }
1938
1939    /**
1940     * TODO: doc
1941     */
1942    public void setOperationalMode(int mode) {
1943        if (DBG) log("setting operational mode to " + String.valueOf(mode));
1944        sendMessage(CMD_SET_OPERATIONAL_MODE, mode, 0);
1945    }
1946
1947    /**
1948     * TODO: doc
1949     */
1950    public List<ScanResult> syncGetScanResultsList() {
1951        synchronized (mScanResultCache) {
1952            List<ScanResult> scanList = new ArrayList<ScanResult>();
1953            for (ScanDetail result : mScanResults) {
1954                scanList.add(new ScanResult(result.getScanResult()));
1955            }
1956            return scanList;
1957        }
1958    }
1959
1960    public void disableEphemeralNetwork(String SSID) {
1961        if (SSID != null) {
1962            sendMessage(CMD_DISABLE_EPHEMERAL_NETWORK, SSID);
1963        }
1964    }
1965
1966    /**
1967     * Get unsynchronized pointer to scan result list
1968     * Can be called only from AutoJoinController which runs in the WifiStateMachine context
1969     */
1970    public List<ScanDetail> getScanResultsListNoCopyUnsync() {
1971        return mScanResults;
1972    }
1973
1974    /**
1975     * Disconnect from Access Point
1976     */
1977    public void disconnectCommand() {
1978        sendMessage(CMD_DISCONNECT);
1979    }
1980
1981    public void disconnectCommand(int uid, int reason) {
1982        sendMessage(CMD_DISCONNECT, uid, reason);
1983    }
1984
1985    /**
1986     * Initiate a reconnection to AP
1987     */
1988    public void reconnectCommand() {
1989        sendMessage(CMD_RECONNECT);
1990    }
1991
1992    /**
1993     * Initiate a re-association to AP
1994     */
1995    public void reassociateCommand() {
1996        sendMessage(CMD_REASSOCIATE);
1997    }
1998
1999    /**
2000     * Reload networks and then reconnect; helps load correct data for TLS networks
2001     */
2002
2003    public void reloadTlsNetworksAndReconnect() {
2004        sendMessage(CMD_RELOAD_TLS_AND_RECONNECT);
2005    }
2006
2007    /**
2008     * Add a network synchronously
2009     *
2010     * @return network id of the new network
2011     */
2012    public int syncAddOrUpdateNetwork(AsyncChannel channel, WifiConfiguration config) {
2013        Message resultMsg = channel.sendMessageSynchronously(CMD_ADD_OR_UPDATE_NETWORK, config);
2014        int result = resultMsg.arg1;
2015        resultMsg.recycle();
2016        return result;
2017    }
2018
2019    /**
2020     * Get configured networks synchronously
2021     *
2022     * @param channel
2023     * @return
2024     */
2025
2026    public List<WifiConfiguration> syncGetConfiguredNetworks(int uuid, AsyncChannel channel) {
2027        Message resultMsg = channel.sendMessageSynchronously(CMD_GET_CONFIGURED_NETWORKS, uuid);
2028        List<WifiConfiguration> result = (List<WifiConfiguration>) resultMsg.obj;
2029        resultMsg.recycle();
2030        return result;
2031    }
2032
2033    public List<WifiConfiguration> syncGetPrivilegedConfiguredNetwork(AsyncChannel channel) {
2034        Message resultMsg = channel.sendMessageSynchronously(
2035                CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS);
2036        List<WifiConfiguration> result = (List<WifiConfiguration>) resultMsg.obj;
2037        resultMsg.recycle();
2038        return result;
2039    }
2040
2041    public WifiConfiguration syncGetMatchingWifiConfig(ScanResult scanResult, AsyncChannel channel) {
2042        Message resultMsg = channel.sendMessageSynchronously(CMD_GET_MATCHING_CONFIG, scanResult);
2043        return (WifiConfiguration) resultMsg.obj;
2044    }
2045
2046    /**
2047     * Get connection statistics synchronously
2048     *
2049     * @param channel
2050     * @return
2051     */
2052
2053    public WifiConnectionStatistics syncGetConnectionStatistics(AsyncChannel channel) {
2054        Message resultMsg = channel.sendMessageSynchronously(CMD_GET_CONNECTION_STATISTICS);
2055        WifiConnectionStatistics result = (WifiConnectionStatistics) resultMsg.obj;
2056        resultMsg.recycle();
2057        return result;
2058    }
2059
2060    /**
2061     * Get adaptors synchronously
2062     */
2063
2064    public int syncGetSupportedFeatures(AsyncChannel channel) {
2065        Message resultMsg = channel.sendMessageSynchronously(CMD_GET_SUPPORTED_FEATURES);
2066        int supportedFeatureSet = resultMsg.arg1;
2067        resultMsg.recycle();
2068        return supportedFeatureSet;
2069    }
2070
2071    /**
2072     * Get link layers stats for adapter synchronously
2073     */
2074    public WifiLinkLayerStats syncGetLinkLayerStats(AsyncChannel channel) {
2075        Message resultMsg = channel.sendMessageSynchronously(CMD_GET_LINK_LAYER_STATS);
2076        WifiLinkLayerStats result = (WifiLinkLayerStats) resultMsg.obj;
2077        resultMsg.recycle();
2078        return result;
2079    }
2080
2081    /**
2082     * Delete a network
2083     *
2084     * @param networkId id of the network to be removed
2085     */
2086    public boolean syncRemoveNetwork(AsyncChannel channel, int networkId) {
2087        Message resultMsg = channel.sendMessageSynchronously(CMD_REMOVE_NETWORK, networkId);
2088        boolean result = (resultMsg.arg1 != FAILURE);
2089        resultMsg.recycle();
2090        return result;
2091    }
2092
2093    /**
2094     * Enable a network
2095     *
2096     * @param netId         network id of the network
2097     * @param disableOthers true, if all other networks have to be disabled
2098     * @return {@code true} if the operation succeeds, {@code false} otherwise
2099     */
2100    public boolean syncEnableNetwork(AsyncChannel channel, int netId, boolean disableOthers) {
2101        Message resultMsg = channel.sendMessageSynchronously(CMD_ENABLE_NETWORK, netId,
2102                disableOthers ? 1 : 0);
2103        boolean result = (resultMsg.arg1 != FAILURE);
2104        resultMsg.recycle();
2105        return result;
2106    }
2107
2108    /**
2109     * Disable a network
2110     *
2111     * @param netId network id of the network
2112     * @return {@code true} if the operation succeeds, {@code false} otherwise
2113     */
2114    public boolean syncDisableNetwork(AsyncChannel channel, int netId) {
2115        Message resultMsg = channel.sendMessageSynchronously(WifiManager.DISABLE_NETWORK, netId);
2116        boolean result = (resultMsg.arg1 != WifiManager.DISABLE_NETWORK_FAILED);
2117        resultMsg.recycle();
2118        return result;
2119    }
2120
2121    /**
2122     * Retrieves a WPS-NFC configuration token for the specified network
2123     *
2124     * @return a hex string representation of the WPS-NFC configuration token
2125     */
2126    public String syncGetWpsNfcConfigurationToken(int netId) {
2127        return mWifiNative.getNfcWpsConfigurationToken(netId);
2128    }
2129
2130    void enableBackgroundScan(boolean enable) {
2131        if (enable) {
2132            mWifiConfigStore.enableAllNetworks();
2133        }
2134        mWifiNative.enableBackgroundScan(enable);
2135        mLegacyPnoEnabled = enable;
2136    }
2137
2138    /**
2139     * Blacklist a BSSID. This will avoid the AP if there are
2140     * alternate APs to connect
2141     *
2142     * @param bssid BSSID of the network
2143     */
2144    public void addToBlacklist(String bssid) {
2145        sendMessage(CMD_BLACKLIST_NETWORK, bssid);
2146    }
2147
2148    /**
2149     * Clear the blacklist list
2150     */
2151    public void clearBlacklist() {
2152        sendMessage(CMD_CLEAR_BLACKLIST);
2153    }
2154
2155    public void enableRssiPolling(boolean enabled) {
2156        sendMessage(CMD_ENABLE_RSSI_POLL, enabled ? 1 : 0, 0);
2157    }
2158
2159    public void enableAllNetworks() {
2160        sendMessage(CMD_ENABLE_ALL_NETWORKS);
2161    }
2162
2163    /**
2164     * Start filtering Multicast v4 packets
2165     */
2166    public void startFilteringMulticastV4Packets() {
2167        mFilteringMulticastV4Packets.set(true);
2168        sendMessage(CMD_START_PACKET_FILTERING, MULTICAST_V4, 0);
2169    }
2170
2171    /**
2172     * Stop filtering Multicast v4 packets
2173     */
2174    public void stopFilteringMulticastV4Packets() {
2175        mFilteringMulticastV4Packets.set(false);
2176        sendMessage(CMD_STOP_PACKET_FILTERING, MULTICAST_V4, 0);
2177    }
2178
2179    /**
2180     * Start filtering Multicast v4 packets
2181     */
2182    public void startFilteringMulticastV6Packets() {
2183        sendMessage(CMD_START_PACKET_FILTERING, MULTICAST_V6, 0);
2184    }
2185
2186    /**
2187     * Stop filtering Multicast v4 packets
2188     */
2189    public void stopFilteringMulticastV6Packets() {
2190        sendMessage(CMD_STOP_PACKET_FILTERING, MULTICAST_V6, 0);
2191    }
2192
2193    /**
2194     * Set high performance mode of operation.
2195     * Enabling would set active power mode and disable suspend optimizations;
2196     * disabling would set auto power mode and enable suspend optimizations
2197     *
2198     * @param enable true if enable, false otherwise
2199     */
2200    public void setHighPerfModeEnabled(boolean enable) {
2201        sendMessage(CMD_SET_HIGH_PERF_MODE, enable ? 1 : 0, 0);
2202    }
2203
2204    /**
2205     * Set the country code
2206     *
2207     * @param countryCode following ISO 3166 format
2208     * @param persist     {@code true} if the setting should be remembered.
2209     */
2210    public synchronized void setCountryCode(String countryCode, boolean persist) {
2211        // If it's a good country code, apply after the current
2212        // wifi connection is terminated; ignore resetting of code
2213        // for now (it is unclear what the chipset should do when
2214        // country code is reset)
2215
2216        if (TextUtils.isEmpty(countryCode)) {
2217            log("Ignoring resetting of country code");
2218        } else {
2219            // if mCountryCodeSequence == 0, it is the first time to set country code, always set
2220            // else only when the new country code is different from the current one to set
2221            int countryCodeSequence = mCountryCodeSequence.get();
2222            if (countryCodeSequence == 0 || countryCode.equals(mSetCountryCode) == false) {
2223
2224                countryCodeSequence = mCountryCodeSequence.incrementAndGet();
2225                mSetCountryCode = countryCode;
2226                sendMessage(CMD_SET_COUNTRY_CODE, countryCodeSequence, persist ? 1 : 0,
2227                        countryCode);
2228            }
2229
2230            if (persist) {
2231                Settings.Global.putString(mContext.getContentResolver(),
2232                        Settings.Global.WIFI_COUNTRY_CODE,
2233                        countryCode);
2234            }
2235        }
2236    }
2237
2238    /**
2239     * Get the country code
2240     *
2241     * @param countryCode following ISO 3166 format
2242     */
2243    public String getCountryCode() {
2244        return mSetCountryCode;
2245    }
2246
2247
2248    /**
2249     * Set the operational frequency band
2250     *
2251     * @param band
2252     * @param persist {@code true} if the setting should be remembered.
2253     */
2254    public void setFrequencyBand(int band, boolean persist) {
2255        if (persist) {
2256            Settings.Global.putInt(mContext.getContentResolver(),
2257                    Settings.Global.WIFI_FREQUENCY_BAND,
2258                    band);
2259        }
2260        sendMessage(CMD_SET_FREQUENCY_BAND, band, 0);
2261    }
2262
2263    /**
2264     * Enable TDLS for a specific MAC address
2265     */
2266    public void enableTdls(String remoteMacAddress, boolean enable) {
2267        int enabler = enable ? 1 : 0;
2268        sendMessage(CMD_ENABLE_TDLS, enabler, 0, remoteMacAddress);
2269    }
2270
2271    /**
2272     * Returns the operational frequency band
2273     */
2274    public int getFrequencyBand() {
2275        return mFrequencyBand.get();
2276    }
2277
2278    /**
2279     * Returns the wifi configuration file
2280     */
2281    public String getConfigFile() {
2282        return mWifiConfigStore.getConfigFile();
2283    }
2284
2285    /**
2286     * Send a message indicating bluetooth adapter connection state changed
2287     */
2288    public void sendBluetoothAdapterStateChange(int state) {
2289        sendMessage(CMD_BLUETOOTH_ADAPTER_STATE_CHANGE, state, 0);
2290    }
2291
2292    /**
2293     * Save configuration on supplicant
2294     *
2295     * @return {@code true} if the operation succeeds, {@code false} otherwise
2296     * <p/>
2297     * TODO: deprecate this
2298     */
2299    public boolean syncSaveConfig(AsyncChannel channel) {
2300        Message resultMsg = channel.sendMessageSynchronously(CMD_SAVE_CONFIG);
2301        boolean result = (resultMsg.arg1 != FAILURE);
2302        resultMsg.recycle();
2303        return result;
2304    }
2305
2306    public void updateBatteryWorkSource(WorkSource newSource) {
2307        synchronized (mRunningWifiUids) {
2308            try {
2309                if (newSource != null) {
2310                    mRunningWifiUids.set(newSource);
2311                }
2312                if (mIsRunning) {
2313                    if (mReportedRunning) {
2314                        // If the work source has changed since last time, need
2315                        // to remove old work from battery stats.
2316                        if (mLastRunningWifiUids.diff(mRunningWifiUids)) {
2317                            mBatteryStats.noteWifiRunningChanged(mLastRunningWifiUids,
2318                                    mRunningWifiUids);
2319                            mLastRunningWifiUids.set(mRunningWifiUids);
2320                        }
2321                    } else {
2322                        // Now being started, report it.
2323                        mBatteryStats.noteWifiRunning(mRunningWifiUids);
2324                        mLastRunningWifiUids.set(mRunningWifiUids);
2325                        mReportedRunning = true;
2326                    }
2327                } else {
2328                    if (mReportedRunning) {
2329                        // Last reported we were running, time to stop.
2330                        mBatteryStats.noteWifiStopped(mLastRunningWifiUids);
2331                        mLastRunningWifiUids.clear();
2332                        mReportedRunning = false;
2333                    }
2334                }
2335                mWakeLock.setWorkSource(newSource);
2336            } catch (RemoteException ignore) {
2337            }
2338        }
2339    }
2340
2341    @Override
2342    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2343        super.dump(fd, pw, args);
2344        mSupplicantStateTracker.dump(fd, pw, args);
2345        pw.println("mLinkProperties " + mLinkProperties);
2346        pw.println("mWifiInfo " + mWifiInfo);
2347        pw.println("mDhcpResults " + mDhcpResults);
2348        pw.println("mNetworkInfo " + mNetworkInfo);
2349        pw.println("mLastSignalLevel " + mLastSignalLevel);
2350        pw.println("mLastBssid " + mLastBssid);
2351        pw.println("mLastNetworkId " + mLastNetworkId);
2352        pw.println("mOperationalMode " + mOperationalMode);
2353        pw.println("mUserWantsSuspendOpt " + mUserWantsSuspendOpt);
2354        pw.println("mSuspendOptNeedsDisabled " + mSuspendOptNeedsDisabled);
2355        pw.println("Supplicant status " + mWifiNative.status(true));
2356        pw.println("mLegacyPnoEnabled " + mLegacyPnoEnabled);
2357        pw.println("mSetCountryCode " + mSetCountryCode);
2358        pw.println("mDriverSetCountryCode " + mDriverSetCountryCode);
2359        pw.println("mConnectedModeGScanOffloadStarted " + mConnectedModeGScanOffloadStarted);
2360        pw.println("mGScanPeriodMilli " + mGScanPeriodMilli);
2361        if (mWhiteListedSsids != null && mWhiteListedSsids.length > 0) {
2362            pw.println("SSID whitelist :" );
2363            for (int i=0; i < mWhiteListedSsids.length; i++) {
2364                pw.println("       " + mWhiteListedSsids[i]);
2365            }
2366        }
2367        mNetworkFactory.dump(fd, pw, args);
2368        mUntrustedNetworkFactory.dump(fd, pw, args);
2369        pw.println();
2370        mWifiConfigStore.dump(fd, pw, args);
2371        pw.println();
2372        mWifiLogger.dump(fd, pw, args);
2373    }
2374
2375    /**
2376     * ******************************************************
2377     * Internal private functions
2378     * ******************************************************
2379     */
2380
2381    private void logStateAndMessage(Message message, String state) {
2382        messageHandlingStatus = 0;
2383        if (mLogMessages) {
2384            //long now = SystemClock.elapsedRealtimeNanos();
2385            //String ts = String.format("[%,d us]", now/1000);
2386
2387            loge(" " + state + " " + getLogRecString(message));
2388        }
2389    }
2390
2391    /**
2392     * helper, prints the milli time since boot wi and w/o suspended time
2393     */
2394    String printTime() {
2395        StringBuilder sb = new StringBuilder();
2396        sb.append(" rt=").append(SystemClock.uptimeMillis());
2397        sb.append("/").append(SystemClock.elapsedRealtime());
2398        return sb.toString();
2399    }
2400
2401    /**
2402     * Return the additional string to be logged by LogRec, default
2403     *
2404     * @param msg that was processed
2405     * @return information to be logged as a String
2406     */
2407    protected String getLogRecString(Message msg) {
2408        WifiConfiguration config;
2409        Long now;
2410        String report;
2411        String key;
2412        StringBuilder sb = new StringBuilder();
2413        if (mScreenOn) {
2414            sb.append("!");
2415        }
2416        if (messageHandlingStatus != MESSAGE_HANDLING_STATUS_UNKNOWN) {
2417            sb.append("(").append(messageHandlingStatus).append(")");
2418        }
2419        sb.append(smToString(msg));
2420        if (msg.sendingUid > 0 && msg.sendingUid != Process.WIFI_UID) {
2421            sb.append(" uid=" + msg.sendingUid);
2422        }
2423        switch (msg.what) {
2424            case CMD_STARTED_GSCAN_DBG:
2425            case CMD_STARTED_PNO_DBG:
2426                sb.append(" ");
2427                sb.append(Integer.toString(msg.arg1));
2428                sb.append(" ");
2429                sb.append(Integer.toString(msg.arg2));
2430                if (msg.obj != null) {
2431                    sb.append(" " + (String)msg.obj);
2432                }
2433                break;
2434            case CMD_RESTART_AUTOJOIN_OFFLOAD:
2435                sb.append(" ");
2436                sb.append(Integer.toString(msg.arg1));
2437                sb.append(" ");
2438                sb.append(Integer.toString(msg.arg2));
2439                sb.append("/").append(Integer.toString(mRestartAutoJoinOffloadCounter));
2440                if (msg.obj != null) {
2441                    sb.append(" " + (String)msg.obj);
2442                }
2443                break;
2444            case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION:
2445                sb.append(" ");
2446                sb.append(Integer.toString(msg.arg1));
2447                sb.append(" ");
2448                sb.append(Integer.toString(msg.arg2));
2449                sb.append(" halAllowed=").append(useHalBasedAutoJoinOffload());
2450                sb.append(" scanAllowed=").append(allowFullBandScanAndAssociated());
2451                sb.append(" autojoinAllowed=");
2452                sb.append(mWifiConfigStore.enableAutoJoinScanWhenAssociated.get());
2453                sb.append(" withTraffic=").append(getAllowScansWithTraffic());
2454                sb.append(" tx=").append(mWifiInfo.txSuccessRate);
2455                sb.append("/").append(mWifiConfigStore.maxTxPacketForFullScans);
2456                sb.append(" rx=").append(mWifiInfo.rxSuccessRate);
2457                sb.append("/").append(mWifiConfigStore.maxRxPacketForFullScans);
2458                sb.append(" -> ").append(mConnectedModeGScanOffloadStarted);
2459                break;
2460            case CMD_PNO_NETWORK_FOUND:
2461                sb.append(" ");
2462                sb.append(Integer.toString(msg.arg1));
2463                sb.append(" ");
2464                sb.append(Integer.toString(msg.arg2));
2465                if (msg.obj != null) {
2466                    ScanResult[] results = (ScanResult[])msg.obj;
2467                    for (int i = 0; i < results.length; i++) {
2468                       sb.append(" ").append(results[i].SSID).append(" ");
2469                       sb.append(results[i].frequency);
2470                       sb.append(" ").append(results[i].level);
2471                    }
2472                }
2473                break;
2474            case CMD_START_SCAN:
2475                now = System.currentTimeMillis();
2476                sb.append(" ");
2477                sb.append(Integer.toString(msg.arg1));
2478                sb.append(" ");
2479                sb.append(Integer.toString(msg.arg2));
2480                sb.append(" ic=");
2481                sb.append(Integer.toString(sScanAlarmIntentCount));
2482                if (msg.obj != null) {
2483                    Bundle bundle = (Bundle) msg.obj;
2484                    Long request = bundle.getLong(SCAN_REQUEST_TIME, 0);
2485                    if (request != 0) {
2486                        sb.append(" proc(ms):").append(now - request);
2487                    }
2488                }
2489                if (mIsScanOngoing) sb.append(" onGoing");
2490                if (mIsFullScanOngoing) sb.append(" full");
2491                if (lastStartScanTimeStamp != 0) {
2492                    sb.append(" started:").append(lastStartScanTimeStamp);
2493                    sb.append(",").append(now - lastStartScanTimeStamp);
2494                }
2495                if (lastScanDuration != 0) {
2496                    sb.append(" dur:").append(lastScanDuration);
2497                }
2498                sb.append(" cnt=").append(mDelayedScanCounter);
2499                sb.append(" rssi=").append(mWifiInfo.getRssi());
2500                sb.append(" f=").append(mWifiInfo.getFrequency());
2501                sb.append(" sc=").append(mWifiInfo.score);
2502                sb.append(" link=").append(mWifiInfo.getLinkSpeed());
2503                sb.append(String.format(" tx=%.1f,", mWifiInfo.txSuccessRate));
2504                sb.append(String.format(" %.1f,", mWifiInfo.txRetriesRate));
2505                sb.append(String.format(" %.1f ", mWifiInfo.txBadRate));
2506                sb.append(String.format(" rx=%.1f", mWifiInfo.rxSuccessRate));
2507                if (lastScanFreqs != null) {
2508                    sb.append(" list=").append(lastScanFreqs);
2509                } else {
2510                    sb.append(" fiv=").append(fullBandConnectedTimeIntervalMilli);
2511                }
2512                report = reportOnTime();
2513                if (report != null) {
2514                    sb.append(" ").append(report);
2515                }
2516                break;
2517            case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
2518                sb.append(" ");
2519                sb.append(Integer.toString(msg.arg1));
2520                sb.append(" ");
2521                sb.append(Integer.toString(msg.arg2));
2522                sb.append(printTime());
2523                StateChangeResult stateChangeResult = (StateChangeResult) msg.obj;
2524                if (stateChangeResult != null) {
2525                    sb.append(stateChangeResult.toString());
2526                }
2527                break;
2528            case WifiManager.SAVE_NETWORK:
2529            case WifiStateMachine.CMD_AUTO_SAVE_NETWORK:
2530                sb.append(" ");
2531                sb.append(Integer.toString(msg.arg1));
2532                sb.append(" ");
2533                sb.append(Integer.toString(msg.arg2));
2534                if (lastSavedConfigurationAttempt != null) {
2535                    sb.append(" ").append(lastSavedConfigurationAttempt.configKey());
2536                    sb.append(" nid=").append(lastSavedConfigurationAttempt.networkId);
2537                    if (lastSavedConfigurationAttempt.hiddenSSID) {
2538                        sb.append(" hidden");
2539                    }
2540                    if (lastSavedConfigurationAttempt.preSharedKey != null
2541                            && !lastSavedConfigurationAttempt.preSharedKey.equals("*")) {
2542                        sb.append(" hasPSK");
2543                    }
2544                    if (lastSavedConfigurationAttempt.ephemeral) {
2545                        sb.append(" ephemeral");
2546                    }
2547                    if (lastSavedConfigurationAttempt.selfAdded) {
2548                        sb.append(" selfAdded");
2549                    }
2550                    sb.append(" cuid=").append(lastSavedConfigurationAttempt.creatorUid);
2551                    sb.append(" suid=").append(lastSavedConfigurationAttempt.lastUpdateUid);
2552                }
2553                break;
2554            case WifiManager.FORGET_NETWORK:
2555                sb.append(" ");
2556                sb.append(Integer.toString(msg.arg1));
2557                sb.append(" ");
2558                sb.append(Integer.toString(msg.arg2));
2559                if (lastForgetConfigurationAttempt != null) {
2560                    sb.append(" ").append(lastForgetConfigurationAttempt.configKey());
2561                    sb.append(" nid=").append(lastForgetConfigurationAttempt.networkId);
2562                    if (lastForgetConfigurationAttempt.hiddenSSID) {
2563                        sb.append(" hidden");
2564                    }
2565                    if (lastForgetConfigurationAttempt.preSharedKey != null) {
2566                        sb.append(" hasPSK");
2567                    }
2568                    if (lastForgetConfigurationAttempt.ephemeral) {
2569                        sb.append(" ephemeral");
2570                    }
2571                    if (lastForgetConfigurationAttempt.selfAdded) {
2572                        sb.append(" selfAdded");
2573                    }
2574                    sb.append(" cuid=").append(lastForgetConfigurationAttempt.creatorUid);
2575                    sb.append(" suid=").append(lastForgetConfigurationAttempt.lastUpdateUid);
2576                    sb.append(" ajst=").append(lastForgetConfigurationAttempt.autoJoinStatus);
2577                }
2578                break;
2579            case WifiMonitor.ASSOCIATION_REJECTION_EVENT:
2580                sb.append(" ");
2581                sb.append(Integer.toString(msg.arg1));
2582                sb.append(" ");
2583                sb.append(Integer.toString(msg.arg2));
2584                String bssid = (String) msg.obj;
2585                if (bssid != null && bssid.length() > 0) {
2586                    sb.append(" ");
2587                    sb.append(bssid);
2588                }
2589                sb.append(" blacklist=" + Boolean.toString(didBlackListBSSID));
2590                sb.append(printTime());
2591                break;
2592            case WifiMonitor.SCAN_RESULTS_EVENT:
2593                sb.append(" ");
2594                sb.append(Integer.toString(msg.arg1));
2595                sb.append(" ");
2596                sb.append(Integer.toString(msg.arg2));
2597                if (mScanResults != null) {
2598                    sb.append(" found=");
2599                    sb.append(mScanResults.size());
2600                }
2601                sb.append(" known=").append(mNumScanResultsKnown);
2602                sb.append(" got=").append(mNumScanResultsReturned);
2603                if (lastScanDuration != 0) {
2604                    sb.append(" dur:").append(lastScanDuration);
2605                }
2606                if (mOnTime != 0) {
2607                    sb.append(" on:").append(mOnTimeThisScan).append(",").append(mOnTimeScan);
2608                    sb.append(",").append(mOnTime);
2609                }
2610                if (mTxTime != 0) {
2611                    sb.append(" tx:").append(mTxTimeThisScan).append(",").append(mTxTimeScan);
2612                    sb.append(",").append(mTxTime);
2613                }
2614                if (mRxTime != 0) {
2615                    sb.append(" rx:").append(mRxTimeThisScan).append(",").append(mRxTimeScan);
2616                    sb.append(",").append(mRxTime);
2617                }
2618                sb.append(String.format(" bcn=%d", mRunningBeaconCount));
2619                sb.append(String.format(" con=%d", mConnectionRequests));
2620                key = mWifiConfigStore.getLastSelectedConfiguration();
2621                if (key != null) {
2622                    sb.append(" last=").append(key);
2623                }
2624                break;
2625            case WifiMonitor.SCAN_FAILED_EVENT:
2626                break;
2627            case WifiMonitor.NETWORK_CONNECTION_EVENT:
2628                sb.append(" ");
2629                sb.append(Integer.toString(msg.arg1));
2630                sb.append(" ");
2631                sb.append(Integer.toString(msg.arg2));
2632                sb.append(" ").append(mLastBssid);
2633                sb.append(" nid=").append(mLastNetworkId);
2634                config = getCurrentWifiConfiguration();
2635                if (config != null) {
2636                    sb.append(" ").append(config.configKey());
2637                }
2638                sb.append(printTime());
2639                key = mWifiConfigStore.getLastSelectedConfiguration();
2640                if (key != null) {
2641                    sb.append(" last=").append(key);
2642                }
2643                break;
2644            case CMD_TARGET_BSSID:
2645            case CMD_ASSOCIATED_BSSID:
2646                sb.append(" ");
2647                sb.append(Integer.toString(msg.arg1));
2648                sb.append(" ");
2649                sb.append(Integer.toString(msg.arg2));
2650                if (msg.obj != null) {
2651                    sb.append(" BSSID=").append((String) msg.obj);
2652                }
2653                if (mTargetRoamBSSID != null) {
2654                    sb.append(" Target=").append(mTargetRoamBSSID);
2655                }
2656                sb.append(" roam=").append(Integer.toString(mAutoRoaming));
2657                sb.append(printTime());
2658                break;
2659            case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
2660                if (msg.obj != null) {
2661                    sb.append(" ").append((String) msg.obj);
2662                }
2663                sb.append(" nid=").append(msg.arg1);
2664                sb.append(" reason=").append(msg.arg2);
2665                if (mLastBssid != null) {
2666                    sb.append(" lastbssid=").append(mLastBssid);
2667                }
2668                if (mWifiInfo.getFrequency() != -1) {
2669                    sb.append(" freq=").append(mWifiInfo.getFrequency());
2670                    sb.append(" rssi=").append(mWifiInfo.getRssi());
2671                }
2672                if (linkDebouncing) {
2673                    sb.append(" debounce");
2674                }
2675                sb.append(printTime());
2676                break;
2677            case WifiMonitor.SSID_TEMP_DISABLED:
2678            case WifiMonitor.SSID_REENABLED:
2679                sb.append(" nid=").append(msg.arg1);
2680                if (msg.obj != null) {
2681                    sb.append(" ").append((String) msg.obj);
2682                }
2683                config = getCurrentWifiConfiguration();
2684                if (config != null) {
2685                    sb.append(" cur=").append(config.configKey());
2686                    sb.append(" ajst=").append(config.autoJoinStatus);
2687                    if (config.selfAdded) {
2688                        sb.append(" selfAdded");
2689                    }
2690                    if (config.status != 0) {
2691                        sb.append(" st=").append(config.status);
2692                        sb.append(" rs=").append(config.disableReason);
2693                    }
2694                    if (config.lastConnected != 0) {
2695                        now = System.currentTimeMillis();
2696                        sb.append(" lastconn=").append(now - config.lastConnected).append("(ms)");
2697                    }
2698                    if (mLastBssid != null) {
2699                        sb.append(" lastbssid=").append(mLastBssid);
2700                    }
2701                    if (mWifiInfo.getFrequency() != -1) {
2702                        sb.append(" freq=").append(mWifiInfo.getFrequency());
2703                        sb.append(" rssi=").append(mWifiInfo.getRssi());
2704                        sb.append(" bssid=").append(mWifiInfo.getBSSID());
2705                    }
2706                }
2707                sb.append(printTime());
2708                break;
2709            case CMD_RSSI_POLL:
2710            case CMD_UNWANTED_NETWORK:
2711            case WifiManager.RSSI_PKTCNT_FETCH:
2712                sb.append(" ");
2713                sb.append(Integer.toString(msg.arg1));
2714                sb.append(" ");
2715                sb.append(Integer.toString(msg.arg2));
2716                if (mWifiInfo.getSSID() != null)
2717                    if (mWifiInfo.getSSID() != null)
2718                        sb.append(" ").append(mWifiInfo.getSSID());
2719                if (mWifiInfo.getBSSID() != null)
2720                    sb.append(" ").append(mWifiInfo.getBSSID());
2721                sb.append(" rssi=").append(mWifiInfo.getRssi());
2722                sb.append(" f=").append(mWifiInfo.getFrequency());
2723                sb.append(" sc=").append(mWifiInfo.score);
2724                sb.append(" link=").append(mWifiInfo.getLinkSpeed());
2725                sb.append(String.format(" tx=%.1f,", mWifiInfo.txSuccessRate));
2726                sb.append(String.format(" %.1f,", mWifiInfo.txRetriesRate));
2727                sb.append(String.format(" %.1f ", mWifiInfo.txBadRate));
2728                sb.append(String.format(" rx=%.1f", mWifiInfo.rxSuccessRate));
2729                sb.append(String.format(" bcn=%d", mRunningBeaconCount));
2730                report = reportOnTime();
2731                if (report != null) {
2732                    sb.append(" ").append(report);
2733                }
2734                if (wifiScoringReport != null) {
2735                    sb.append(wifiScoringReport);
2736                }
2737                if (mConnectedModeGScanOffloadStarted) {
2738                    sb.append(" offload-started periodMilli " + mGScanPeriodMilli);
2739                } else {
2740                    sb.append(" offload-stopped");
2741                }
2742                break;
2743            case CMD_AUTO_CONNECT:
2744            case WifiManager.CONNECT_NETWORK:
2745                sb.append(" ");
2746                sb.append(Integer.toString(msg.arg1));
2747                sb.append(" ");
2748                sb.append(Integer.toString(msg.arg2));
2749                config = (WifiConfiguration) msg.obj;
2750                if (config != null) {
2751                    sb.append(" ").append(config.configKey());
2752                    if (config.visibility != null) {
2753                        sb.append(" ").append(config.visibility.toString());
2754                    }
2755                }
2756                if (mTargetRoamBSSID != null) {
2757                    sb.append(" ").append(mTargetRoamBSSID);
2758                }
2759                sb.append(" roam=").append(Integer.toString(mAutoRoaming));
2760                sb.append(printTime());
2761                config = getCurrentWifiConfiguration();
2762                if (config != null) {
2763                    sb.append(config.configKey());
2764                    if (config.visibility != null) {
2765                        sb.append(" ").append(config.visibility.toString());
2766                    }
2767                }
2768                break;
2769            case CMD_AUTO_ROAM:
2770                sb.append(" ");
2771                sb.append(Integer.toString(msg.arg1));
2772                sb.append(" ");
2773                sb.append(Integer.toString(msg.arg2));
2774                ScanResult result = (ScanResult) msg.obj;
2775                if (result != null) {
2776                    now = System.currentTimeMillis();
2777                    sb.append(" bssid=").append(result.BSSID);
2778                    sb.append(" rssi=").append(result.level);
2779                    sb.append(" freq=").append(result.frequency);
2780                    if (result.seen > 0 && result.seen < now) {
2781                        sb.append(" seen=").append(now - result.seen);
2782                    } else {
2783                        // Somehow the timestamp for this scan result is inconsistent
2784                        sb.append(" !seen=").append(result.seen);
2785                    }
2786                }
2787                if (mTargetRoamBSSID != null) {
2788                    sb.append(" ").append(mTargetRoamBSSID);
2789                }
2790                sb.append(" roam=").append(Integer.toString(mAutoRoaming));
2791                sb.append(" fail count=").append(Integer.toString(mRoamFailCount));
2792                sb.append(printTime());
2793                break;
2794            case CMD_ADD_OR_UPDATE_NETWORK:
2795                sb.append(" ");
2796                sb.append(Integer.toString(msg.arg1));
2797                sb.append(" ");
2798                sb.append(Integer.toString(msg.arg2));
2799                if (msg.obj != null) {
2800                    config = (WifiConfiguration) msg.obj;
2801                    sb.append(" ").append(config.configKey());
2802                    sb.append(" prio=").append(config.priority);
2803                    sb.append(" status=").append(config.status);
2804                    if (config.BSSID != null) {
2805                        sb.append(" ").append(config.BSSID);
2806                    }
2807                    WifiConfiguration curConfig = getCurrentWifiConfiguration();
2808                    if (curConfig != null) {
2809                        if (curConfig.configKey().equals(config.configKey())) {
2810                            sb.append(" is current");
2811                        } else {
2812                            sb.append(" current=").append(curConfig.configKey());
2813                            sb.append(" prio=").append(curConfig.priority);
2814                            sb.append(" status=").append(curConfig.status);
2815                        }
2816                    }
2817                }
2818                break;
2819            case WifiManager.DISABLE_NETWORK:
2820            case CMD_ENABLE_NETWORK:
2821                sb.append(" ");
2822                sb.append(Integer.toString(msg.arg1));
2823                sb.append(" ");
2824                sb.append(Integer.toString(msg.arg2));
2825                key = mWifiConfigStore.getLastSelectedConfiguration();
2826                if (key != null) {
2827                    sb.append(" last=").append(key);
2828                }
2829                config = mWifiConfigStore.getWifiConfiguration(msg.arg1);
2830                if (config != null && (key == null || !config.configKey().equals(key))) {
2831                    sb.append(" target=").append(key);
2832                }
2833                break;
2834            case CMD_GET_CONFIGURED_NETWORKS:
2835                sb.append(" ");
2836                sb.append(Integer.toString(msg.arg1));
2837                sb.append(" ");
2838                sb.append(Integer.toString(msg.arg2));
2839                sb.append(" num=").append(mWifiConfigStore.getConfiguredNetworksSize());
2840                break;
2841            case DhcpStateMachine.CMD_PRE_DHCP_ACTION:
2842                sb.append(" ");
2843                sb.append(Integer.toString(msg.arg1));
2844                sb.append(" ");
2845                sb.append(Integer.toString(msg.arg2));
2846                sb.append(" txpkts=").append(mWifiInfo.txSuccess);
2847                sb.append(",").append(mWifiInfo.txBad);
2848                sb.append(",").append(mWifiInfo.txRetries);
2849                break;
2850            case DhcpStateMachine.CMD_POST_DHCP_ACTION:
2851                sb.append(" ");
2852                sb.append(Integer.toString(msg.arg1));
2853                sb.append(" ");
2854                sb.append(Integer.toString(msg.arg2));
2855                if (msg.arg1 == DhcpStateMachine.DHCP_SUCCESS) {
2856                    sb.append(" OK ");
2857                } else if (msg.arg1 == DhcpStateMachine.DHCP_FAILURE) {
2858                    sb.append(" FAIL ");
2859                }
2860                if (mLinkProperties != null) {
2861                    if (mLinkProperties.hasIPv4Address()) {
2862                        sb.append(" v4");
2863                    }
2864                    if (mLinkProperties.hasGlobalIPv6Address()) {
2865                        sb.append(" v6");
2866                    }
2867                    if (mLinkProperties.hasIPv4DefaultRoute()) {
2868                        sb.append(" v4r");
2869                    }
2870                    if (mLinkProperties.hasIPv6DefaultRoute()) {
2871                        sb.append(" v6r");
2872                    }
2873                    if (mLinkProperties.hasIPv4DnsServer()) {
2874                        sb.append(" v4dns");
2875                    }
2876                    if (mLinkProperties.hasIPv6DnsServer()) {
2877                        sb.append(" v6dns");
2878                    }
2879                }
2880                break;
2881            case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED:
2882                sb.append(" ");
2883                sb.append(Integer.toString(msg.arg1));
2884                sb.append(" ");
2885                sb.append(Integer.toString(msg.arg2));
2886                if (msg.obj != null) {
2887                    NetworkInfo info = (NetworkInfo) msg.obj;
2888                    NetworkInfo.State state = info.getState();
2889                    NetworkInfo.DetailedState detailedState = info.getDetailedState();
2890                    if (state != null) {
2891                        sb.append(" st=").append(state);
2892                    }
2893                    if (detailedState != null) {
2894                        sb.append("/").append(detailedState);
2895                    }
2896                }
2897                break;
2898            case CMD_IP_CONFIGURATION_LOST:
2899                int count = -1;
2900                WifiConfiguration c = getCurrentWifiConfiguration();
2901                if (c != null) count = c.numIpConfigFailures;
2902                sb.append(" ");
2903                sb.append(Integer.toString(msg.arg1));
2904                sb.append(" ");
2905                sb.append(Integer.toString(msg.arg2));
2906                sb.append(" failures: ");
2907                sb.append(Integer.toString(count));
2908                sb.append("/");
2909                sb.append(Integer.toString(mWifiConfigStore.getMaxDhcpRetries()));
2910                if (mWifiInfo.getBSSID() != null) {
2911                    sb.append(" ").append(mWifiInfo.getBSSID());
2912                }
2913                if (c != null) {
2914                    ScanDetailCache scanDetailCache =
2915                            mWifiConfigStore.getScanDetailCache(c);
2916                    if (scanDetailCache != null) {
2917                        for (ScanDetail sd : scanDetailCache.values()) {
2918                            ScanResult r = sd.getScanResult();
2919                            if (r.BSSID.equals(mWifiInfo.getBSSID())) {
2920                                sb.append(" ipfail=").append(r.numIpConfigFailures);
2921                                sb.append(",st=").append(r.autoJoinStatus);
2922                            }
2923                        }
2924                    }
2925                    sb.append(" -> ajst=").append(c.autoJoinStatus);
2926                    sb.append(" ").append(c.disableReason);
2927                    sb.append(" txpkts=").append(mWifiInfo.txSuccess);
2928                    sb.append(",").append(mWifiInfo.txBad);
2929                    sb.append(",").append(mWifiInfo.txRetries);
2930                }
2931                sb.append(printTime());
2932                sb.append(String.format(" bcn=%d", mRunningBeaconCount));
2933                break;
2934            case CMD_UPDATE_LINKPROPERTIES:
2935                sb.append(" ");
2936                sb.append(Integer.toString(msg.arg1));
2937                sb.append(" ");
2938                sb.append(Integer.toString(msg.arg2));
2939                if (mLinkProperties != null) {
2940                    if (mLinkProperties.hasIPv4Address()) {
2941                        sb.append(" v4");
2942                    }
2943                    if (mLinkProperties.hasGlobalIPv6Address()) {
2944                        sb.append(" v6");
2945                    }
2946                    if (mLinkProperties.hasIPv4DefaultRoute()) {
2947                        sb.append(" v4r");
2948                    }
2949                    if (mLinkProperties.hasIPv6DefaultRoute()) {
2950                        sb.append(" v6r");
2951                    }
2952                    if (mLinkProperties.hasIPv4DnsServer()) {
2953                        sb.append(" v4dns");
2954                    }
2955                    if (mLinkProperties.hasIPv6DnsServer()) {
2956                        sb.append(" v6dns");
2957                    }
2958                }
2959                break;
2960            case CMD_SET_COUNTRY_CODE:
2961                sb.append(" ");
2962                sb.append(Integer.toString(msg.arg1));
2963                sb.append(" ");
2964                sb.append(Integer.toString(msg.arg2));
2965                if (msg.obj != null) {
2966                    sb.append(" ").append((String) msg.obj);
2967                }
2968                break;
2969            case CMD_ROAM_WATCHDOG_TIMER:
2970                sb.append(" ");
2971                sb.append(Integer.toString(msg.arg1));
2972                sb.append(" ");
2973                sb.append(Integer.toString(msg.arg2));
2974                sb.append(" cur=").append(roamWatchdogCount);
2975                break;
2976            case CMD_DISCONNECTING_WATCHDOG_TIMER:
2977                sb.append(" ");
2978                sb.append(Integer.toString(msg.arg1));
2979                sb.append(" ");
2980                sb.append(Integer.toString(msg.arg2));
2981                sb.append(" cur=").append(disconnectingWatchdogCount);
2982                break;
2983            default:
2984                sb.append(" ");
2985                sb.append(Integer.toString(msg.arg1));
2986                sb.append(" ");
2987                sb.append(Integer.toString(msg.arg2));
2988                break;
2989        }
2990
2991        return sb.toString();
2992    }
2993
2994    private void stopPnoOffload() {
2995
2996        // clear the PNO list
2997        if (!WifiNative.setPnoList(null, WifiStateMachine.this)) {
2998            Log.e(TAG, "Failed to stop pno");
2999        }
3000
3001    }
3002
3003
3004    private boolean configureSsidWhiteList() {
3005
3006        mWhiteListedSsids = mWifiConfigStore.getWhiteListedSsids(getCurrentWifiConfiguration());
3007        if (mWhiteListedSsids == null || mWhiteListedSsids.length == 0) {
3008            return true;
3009        }
3010
3011       if (!WifiNative.setSsidWhitelist(mWhiteListedSsids)) {
3012            loge("configureSsidWhiteList couldnt program SSID list, size "
3013                    + mWhiteListedSsids.length);
3014            return false;
3015        }
3016
3017        loge("configureSsidWhiteList success");
3018        return true;
3019    }
3020
3021    // In associated more, lazy roam will be looking for 5GHz roam candidate
3022    private boolean configureLazyRoam() {
3023        boolean status;
3024        if (!useHalBasedAutoJoinOffload()) return false;
3025
3026        WifiNative.WifiLazyRoamParams params = mWifiNative.new WifiLazyRoamParams();
3027        params.A_band_boost_threshold = mWifiConfigStore.bandPreferenceBoostThreshold5.get();
3028        params.A_band_penalty_threshold = mWifiConfigStore.bandPreferencePenaltyThreshold5.get();
3029        params.A_band_boost_factor = mWifiConfigStore.bandPreferenceBoostFactor5;
3030        params.A_band_penalty_factor = mWifiConfigStore.bandPreferencePenaltyFactor5;
3031        params.A_band_max_boost = 65;
3032        params.lazy_roam_hysteresis = 25;
3033        params.alert_roam_rssi_trigger = -75;
3034
3035        if (DBG) {
3036            Log.e(TAG, "configureLazyRoam " + params.toString());
3037        }
3038
3039        if (!WifiNative.setLazyRoam(true, params)) {
3040
3041            Log.e(TAG, "configureLazyRoam couldnt program params");
3042
3043            return false;
3044        }
3045        if (DBG) {
3046            Log.e(TAG, "configureLazyRoam success");
3047        }
3048        return true;
3049    }
3050
3051    // In associated more, lazy roam will be looking for 5GHz roam candidate
3052    private boolean stopLazyRoam() {
3053        boolean status;
3054        if (!useHalBasedAutoJoinOffload()) return false;
3055        if (DBG) {
3056            Log.e(TAG, "stopLazyRoam");
3057        }
3058        return WifiNative.setLazyRoam(false, null);
3059    }
3060
3061    private boolean startGScanConnectedModeOffload(String reason) {
3062        if (DBG) {
3063            if (reason == null) {
3064                reason = "";
3065            }
3066            loge("startGScanConnectedModeOffload " + reason);
3067        }
3068        stopGScan("startGScanConnectedModeOffload " + reason);
3069        if (!mScreenOn) return false;
3070
3071        if (USE_PAUSE_SCANS) {
3072            mWifiNative.pauseScan();
3073        }
3074        mPnoEnabled = configurePno();
3075        if (mPnoEnabled == false) {
3076            if (USE_PAUSE_SCANS) {
3077                mWifiNative.restartScan();
3078            }
3079            return false;
3080        }
3081        mLazyRoamEnabled = configureLazyRoam();
3082        if (mLazyRoamEnabled == false) {
3083            if (USE_PAUSE_SCANS) {
3084                mWifiNative.restartScan();
3085            }
3086            return false;
3087        }
3088        if (mWifiConfigStore.getLastSelectedConfiguration() == null) {
3089            configureSsidWhiteList();
3090        }
3091        if (!startConnectedGScan(reason)) {
3092            if (USE_PAUSE_SCANS) {
3093                mWifiNative.restartScan();
3094            }
3095            return false;
3096        }
3097        if (USE_PAUSE_SCANS) {
3098            mWifiNative.restartScan();
3099        }
3100        mConnectedModeGScanOffloadStarted = true;
3101        if (DBG) {
3102            loge("startGScanConnectedModeOffload success");
3103        }
3104        return true;
3105    }
3106
3107    private boolean startGScanDisconnectedModeOffload(String reason) {
3108        if (DBG) {
3109            loge("startGScanDisconnectedModeOffload " + reason);
3110        }
3111        stopGScan("startGScanDisconnectedModeOffload " + reason);
3112        if (USE_PAUSE_SCANS) {
3113            mWifiNative.pauseScan();
3114        }
3115        mPnoEnabled = configurePno();
3116        if (mPnoEnabled == false) {
3117            if (USE_PAUSE_SCANS) {
3118                mWifiNative.restartScan();
3119            }
3120            return false;
3121        }
3122        if (!startDisconnectedGScan(reason)) {
3123            if (USE_PAUSE_SCANS) {
3124                mWifiNative.restartScan();
3125            }
3126            return false;
3127        }
3128        if (USE_PAUSE_SCANS) {
3129            mWifiNative.restartScan();
3130        }
3131        return true;
3132    }
3133
3134    private boolean configurePno() {
3135        if (!useHalBasedAutoJoinOffload()) return false;
3136
3137        if (mWifiScanner == null) {
3138            log("configurePno: mWifiScanner is null ");
3139            return true;
3140        }
3141
3142        List<WifiNative.WifiPnoNetwork> llist
3143                = mWifiAutoJoinController.getPnoList(getCurrentWifiConfiguration());
3144        if (llist == null || llist.size() == 0) {
3145            stopPnoOffload();
3146            log("configurePno: empty PNO list ");
3147            return true;
3148        }
3149        if (DBG) {
3150            log("configurePno: got llist size " + llist.size());
3151        }
3152
3153        // first program the network we want to look for thru the pno API
3154        WifiNative.WifiPnoNetwork list[]
3155                = (WifiNative.WifiPnoNetwork[]) llist.toArray(new WifiNative.WifiPnoNetwork[0]);
3156
3157        if (!WifiNative.setPnoList(list, WifiStateMachine.this)) {
3158            Log.e(TAG, "Failed to set pno, length = " + list.length);
3159            return false;
3160        }
3161
3162        if (true) {
3163            StringBuilder sb = new StringBuilder();
3164            for (WifiNative.WifiPnoNetwork network : list) {
3165                sb.append("[").append(network.SSID).append(" auth=").append(network.auth);
3166                sb.append(" flags=");
3167                sb.append(network.flags).append(" rssi").append(network.rssi_threshold);
3168                sb.append("] ");
3169
3170            }
3171            sendMessage(CMD_STARTED_PNO_DBG, 1, (int)mGScanPeriodMilli, sb.toString());
3172        }
3173        return true;
3174    }
3175
3176    final static int DISCONNECTED_SHORT_SCANS_DURATION_MILLI = 2 * 60 * 1000;
3177    final static int CONNECTED_SHORT_SCANS_DURATION_MILLI = 2 * 60 * 1000;
3178
3179    private boolean startConnectedGScan(String reason) {
3180        // send a scan background request so as to kick firmware
3181        // 5GHz roaming and autojoin
3182        // We do this only if screen is on
3183        WifiScanner.ScanSettings settings;
3184
3185        if (mPnoEnabled || mLazyRoamEnabled) {
3186            settings = new WifiScanner.ScanSettings();
3187            settings.band = WifiScanner.WIFI_BAND_BOTH;
3188            long now = System.currentTimeMillis();
3189
3190            if (!mScreenOn  || (mGScanStartTimeMilli!= 0 && now > mGScanStartTimeMilli
3191                    && ((now - mGScanStartTimeMilli) > CONNECTED_SHORT_SCANS_DURATION_MILLI))) {
3192                settings.periodInMs = mWifiConfigStore.wifiAssociatedLongScanIntervalMilli.get();
3193            } else {
3194                mGScanStartTimeMilli = now;
3195                settings.periodInMs = mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get();
3196                // if we start offload with short interval, then reconfigure it after a given
3197                // duration of time so as to reduce the scan frequency
3198                int delay = 30 * 1000 + CONNECTED_SHORT_SCANS_DURATION_MILLI;
3199                sendMessageDelayed(CMD_RESTART_AUTOJOIN_OFFLOAD, delay,
3200                        mRestartAutoJoinOffloadCounter, " startConnectedGScan " + reason,
3201                        (long)delay);
3202                mRestartAutoJoinOffloadCounter++;
3203            }
3204            mGScanPeriodMilli = settings.periodInMs;
3205            settings.reportEvents = WifiScanner.REPORT_EVENT_AFTER_BUFFER_FULL;
3206            if (DBG) {
3207                log("startConnectedScan: settings band="+ settings.band
3208                        + " period=" + settings.periodInMs);
3209            }
3210
3211            mWifiScanner.startBackgroundScan(settings, mWifiScanListener);
3212            if (true) {
3213                sendMessage(CMD_STARTED_GSCAN_DBG, 1, (int)mGScanPeriodMilli, reason);
3214            }
3215        }
3216        return true;
3217    }
3218
3219    private boolean startDisconnectedGScan(String reason) {
3220        // send a scan background request so as to kick firmware
3221        // PNO
3222        // This is done in both screen On and screen Off modes
3223        WifiScanner.ScanSettings settings;
3224
3225        if (mWifiScanner == null) {
3226            log("startDisconnectedGScan: no wifi scanner");
3227            return false;
3228        }
3229
3230        if (mPnoEnabled || mLazyRoamEnabled) {
3231            settings = new WifiScanner.ScanSettings();
3232            settings.band = WifiScanner.WIFI_BAND_BOTH;
3233            long now = System.currentTimeMillis();
3234
3235
3236            if (!mScreenOn  || (mGScanStartTimeMilli != 0 && now > mGScanStartTimeMilli
3237                    && ((now - mGScanStartTimeMilli) > DISCONNECTED_SHORT_SCANS_DURATION_MILLI))) {
3238                settings.periodInMs = mWifiConfigStore.wifiDisconnectedLongScanIntervalMilli.get();
3239            } else {
3240                settings.periodInMs = mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get();
3241                mGScanStartTimeMilli = now;
3242                // if we start offload with short interval, then reconfigure it after a given
3243                // duration of time so as to reduce the scan frequency
3244                int delay = 30 * 1000 + DISCONNECTED_SHORT_SCANS_DURATION_MILLI;
3245                sendMessageDelayed(CMD_RESTART_AUTOJOIN_OFFLOAD, delay,
3246                        mRestartAutoJoinOffloadCounter, " startDisconnectedGScan " + reason,
3247                        (long)delay);
3248                mRestartAutoJoinOffloadCounter++;
3249            }
3250            mGScanPeriodMilli = settings.periodInMs;
3251            settings.reportEvents = WifiScanner.REPORT_EVENT_AFTER_BUFFER_FULL;
3252            if (DBG) {
3253                log("startDisconnectedScan: settings band="+ settings.band
3254                        + " period=" + settings.periodInMs);
3255            }
3256            mWifiScanner.startBackgroundScan(settings, mWifiScanListener);
3257            if (true) {
3258                sendMessage(CMD_STARTED_GSCAN_DBG, 1, (int)mGScanPeriodMilli, reason);
3259            }
3260        }
3261        return true;
3262    }
3263
3264    private boolean stopGScan(String reason) {
3265        mGScanStartTimeMilli = 0;
3266        mGScanPeriodMilli = 0;
3267        if (mWifiScanner != null) {
3268            mWifiScanner.stopBackgroundScan(mWifiScanListener);
3269        }
3270        mConnectedModeGScanOffloadStarted = false;
3271        if (true) {
3272            sendMessage(CMD_STARTED_GSCAN_DBG, 0, 0, reason);
3273        }
3274        return true;
3275    }
3276
3277    private void handleScreenStateChanged(boolean screenOn) {
3278        mScreenOn = screenOn;
3279        if (PDBG) {
3280            loge(" handleScreenStateChanged Enter: screenOn=" + screenOn
3281                    + " mUserWantsSuspendOpt=" + mUserWantsSuspendOpt
3282                    + " state " + getCurrentState().getName()
3283                    + " suppState:" + mSupplicantStateTracker.getSupplicantStateName());
3284        }
3285        enableRssiPolling(screenOn);
3286        if (screenOn) enableAllNetworks();
3287        if (mUserWantsSuspendOpt.get()) {
3288            if (screenOn) {
3289                sendMessage(CMD_SET_SUSPEND_OPT_ENABLED, 0, 0);
3290            } else {
3291                // Allow 2s for suspend optimizations to be set
3292                mSuspendWakeLock.acquire(2000);
3293                sendMessage(CMD_SET_SUSPEND_OPT_ENABLED, 1, 0);
3294            }
3295        }
3296        mScreenBroadcastReceived.set(true);
3297
3298        getWifiLinkLayerStats(false);
3299        mOnTimeScreenStateChange = mOnTime;
3300        lastScreenStateChangeTimeStamp = lastLinkLayerStatsUpdate;
3301
3302        cancelDelayedScan();
3303
3304        if (screenOn) {
3305            if (mLegacyPnoEnabled) {
3306                enableBackgroundScan(false);
3307            }
3308            setScanAlarm(false);
3309            clearBlacklist();
3310
3311            fullBandConnectedTimeIntervalMilli
3312                    = mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get();
3313            // In either Disconnectedstate or ConnectedState,
3314            // start the scan alarm so as to enable autojoin
3315            if (getCurrentState() == mConnectedState
3316                    && allowFullBandScanAndAssociated()) {
3317                if (useHalBasedAutoJoinOffload()) {
3318                    startGScanConnectedModeOffload("screenOnConnected");
3319                } else {
3320                    // Scan after 500ms
3321                    startDelayedScan(500, null, null);
3322                }
3323            } else if (getCurrentState() == mDisconnectedState) {
3324                if (useHalBasedAutoJoinOffload()) {
3325                    startGScanDisconnectedModeOffload("screenOnDisconnected");
3326                } else {
3327                    // Scan after 500ms
3328                    startDelayedScan(500, null, null);
3329                }
3330            }
3331        } else {
3332            if (getCurrentState() == mDisconnectedState) {
3333                // Screen Off and Disconnected and chipset doesn't support scan offload
3334                //              => start scan alarm
3335                // Screen Off and Disconnected and chipset does support scan offload
3336                //              => will use scan offload (i.e. background scan)
3337                if (useHalBasedAutoJoinOffload()) {
3338                    startGScanDisconnectedModeOffload("screenOffDisconnected");
3339                } else {
3340                    if (!mBackgroundScanSupported) {
3341                        setScanAlarm(true);
3342                    } else {
3343                        if (!mIsScanOngoing) {
3344                            enableBackgroundScan(true);
3345                        }
3346                    }
3347                }
3348            } else {
3349                if (mLegacyPnoEnabled) {
3350                    enableBackgroundScan(false);
3351                }
3352                stopGScan("ScreenOffStop(enableBackground=" + mLegacyPnoEnabled + ") ");
3353            }
3354        }
3355        if (DBG) logd("backgroundScan enabled=" + mLegacyPnoEnabled);
3356
3357        if (DBG) log("handleScreenStateChanged Exit: " + screenOn);
3358    }
3359
3360    private void checkAndSetConnectivityInstance() {
3361        if (mCm == null) {
3362            mCm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
3363        }
3364    }
3365
3366    private boolean startTethering(ArrayList<String> available) {
3367
3368        boolean wifiAvailable = false;
3369
3370        checkAndSetConnectivityInstance();
3371
3372        String[] wifiRegexs = mCm.getTetherableWifiRegexs();
3373
3374        for (String intf : available) {
3375            for (String regex : wifiRegexs) {
3376                if (intf.matches(regex)) {
3377
3378                    InterfaceConfiguration ifcg = null;
3379                    try {
3380                        ifcg = mNwService.getInterfaceConfig(intf);
3381                        if (ifcg != null) {
3382                            /* IP/netmask: 192.168.43.1/255.255.255.0 */
3383                            ifcg.setLinkAddress(new LinkAddress(
3384                                    NetworkUtils.numericToInetAddress("192.168.43.1"), 24));
3385                            ifcg.setInterfaceUp();
3386
3387                            mNwService.setInterfaceConfig(intf, ifcg);
3388                        }
3389                    } catch (Exception e) {
3390                        loge("Error configuring interface " + intf + ", :" + e);
3391                        return false;
3392                    }
3393
3394                    if (mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
3395                        loge("Error tethering on " + intf);
3396                        return false;
3397                    }
3398                    mTetherInterfaceName = intf;
3399                    return true;
3400                }
3401            }
3402        }
3403        // We found no interfaces to tether
3404        return false;
3405    }
3406
3407    private void stopTethering() {
3408
3409        checkAndSetConnectivityInstance();
3410
3411        /* Clear the interface config to allow dhcp correctly configure new
3412           ip settings */
3413        InterfaceConfiguration ifcg = null;
3414        try {
3415            ifcg = mNwService.getInterfaceConfig(mTetherInterfaceName);
3416            if (ifcg != null) {
3417                ifcg.setLinkAddress(
3418                        new LinkAddress(NetworkUtils.numericToInetAddress("0.0.0.0"), 0));
3419                mNwService.setInterfaceConfig(mTetherInterfaceName, ifcg);
3420            }
3421        } catch (Exception e) {
3422            loge("Error resetting interface " + mTetherInterfaceName + ", :" + e);
3423        }
3424
3425        if (mCm.untether(mTetherInterfaceName) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
3426            loge("Untether initiate failed!");
3427        }
3428    }
3429
3430    private boolean isWifiTethered(ArrayList<String> active) {
3431
3432        checkAndSetConnectivityInstance();
3433
3434        String[] wifiRegexs = mCm.getTetherableWifiRegexs();
3435        for (String intf : active) {
3436            for (String regex : wifiRegexs) {
3437                if (intf.matches(regex)) {
3438                    return true;
3439                }
3440            }
3441        }
3442        // We found no interfaces that are tethered
3443        return false;
3444    }
3445
3446    /**
3447     * Set the country code from the system setting value, if any.
3448     */
3449    private void setCountryCode() {
3450        String countryCode = Settings.Global.getString(mContext.getContentResolver(),
3451                Settings.Global.WIFI_COUNTRY_CODE);
3452        if (countryCode != null && !countryCode.isEmpty()) {
3453            setCountryCode(countryCode, false);
3454        } else {
3455            //use driver default
3456        }
3457    }
3458
3459    /**
3460     * Set the frequency band from the system setting value, if any.
3461     */
3462    private void setFrequencyBand() {
3463        int band = Settings.Global.getInt(mContext.getContentResolver(),
3464                Settings.Global.WIFI_FREQUENCY_BAND, WifiManager.WIFI_FREQUENCY_BAND_AUTO);
3465        setFrequencyBand(band, false);
3466    }
3467
3468    private void setSuspendOptimizationsNative(int reason, boolean enabled) {
3469        if (DBG) {
3470            log("setSuspendOptimizationsNative: " + reason + " " + enabled
3471                    + " -want " + mUserWantsSuspendOpt.get()
3472                    + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
3473                    + " - " + Thread.currentThread().getStackTrace()[3].getMethodName()
3474                    + " - " + Thread.currentThread().getStackTrace()[4].getMethodName()
3475                    + " - " + Thread.currentThread().getStackTrace()[5].getMethodName());
3476        }
3477        //mWifiNative.setSuspendOptimizations(enabled);
3478
3479        if (enabled) {
3480            mSuspendOptNeedsDisabled &= ~reason;
3481            /* None of dhcp, screen or highperf need it disabled and user wants it enabled */
3482            if (mSuspendOptNeedsDisabled == 0 && mUserWantsSuspendOpt.get()) {
3483                if (DBG) {
3484                    log("setSuspendOptimizationsNative do it " + reason + " " + enabled
3485                            + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
3486                            + " - " + Thread.currentThread().getStackTrace()[3].getMethodName()
3487                            + " - " + Thread.currentThread().getStackTrace()[4].getMethodName()
3488                            + " - " + Thread.currentThread().getStackTrace()[5].getMethodName());
3489                }
3490                mWifiNative.setSuspendOptimizations(true);
3491            }
3492        } else {
3493            mSuspendOptNeedsDisabled |= reason;
3494            mWifiNative.setSuspendOptimizations(false);
3495        }
3496    }
3497
3498    private void setSuspendOptimizations(int reason, boolean enabled) {
3499        if (DBG) log("setSuspendOptimizations: " + reason + " " + enabled);
3500        if (enabled) {
3501            mSuspendOptNeedsDisabled &= ~reason;
3502        } else {
3503            mSuspendOptNeedsDisabled |= reason;
3504        }
3505        if (DBG) log("mSuspendOptNeedsDisabled " + mSuspendOptNeedsDisabled);
3506    }
3507
3508    private void setWifiState(int wifiState) {
3509        final int previousWifiState = mWifiState.get();
3510
3511        try {
3512            if (wifiState == WIFI_STATE_ENABLED) {
3513                mBatteryStats.noteWifiOn();
3514            } else if (wifiState == WIFI_STATE_DISABLED) {
3515                mBatteryStats.noteWifiOff();
3516            }
3517        } catch (RemoteException e) {
3518            loge("Failed to note battery stats in wifi");
3519        }
3520
3521        mWifiState.set(wifiState);
3522
3523        if (DBG) log("setWifiState: " + syncGetWifiStateByName());
3524
3525        final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
3526        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3527        intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
3528        intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
3529        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3530    }
3531
3532    private void setWifiApState(int wifiApState) {
3533        final int previousWifiApState = mWifiApState.get();
3534
3535        try {
3536            if (wifiApState == WIFI_AP_STATE_ENABLED) {
3537                mBatteryStats.noteWifiOn();
3538            } else if (wifiApState == WIFI_AP_STATE_DISABLED) {
3539                mBatteryStats.noteWifiOff();
3540            }
3541        } catch (RemoteException e) {
3542            loge("Failed to note battery stats in wifi");
3543        }
3544
3545        // Update state
3546        mWifiApState.set(wifiApState);
3547
3548        if (DBG) log("setWifiApState: " + syncGetWifiApStateByName());
3549
3550        final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
3551        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3552        intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiApState);
3553        intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
3554        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3555    }
3556
3557    /*
3558    void ageOutScanResults(int age) {
3559        synchronized(mScanResultCache) {
3560            // Trim mScanResults, which prevent WifiStateMachine to return
3561            // obsolete scan results to queriers
3562            long now = System.CurrentTimeMillis();
3563            for (int i = 0; i < mScanResults.size(); i++) {
3564                ScanResult result = mScanResults.get(i);
3565                if ((result.seen > now || (now - result.seen) > age)) {
3566                    mScanResults.remove(i);
3567                }
3568            }
3569        }
3570    }*/
3571
3572    private static final String IE_STR = "ie=";
3573    private static final String ID_STR = "id=";
3574    private static final String BSSID_STR = "bssid=";
3575    private static final String FREQ_STR = "freq=";
3576    private static final String LEVEL_STR = "level=";
3577    private static final String TSF_STR = "tsf=";
3578    private static final String FLAGS_STR = "flags=";
3579    private static final String SSID_STR = "ssid=";
3580    private static final String DELIMITER_STR = "====";
3581    private static final String END_STR = "####";
3582
3583    int emptyScanResultCount = 0;
3584
3585    // Used for matching BSSID strings, at least one characteer must be a non-zero number
3586    private static Pattern mNotZero = Pattern.compile("[1-9a-fA-F]");
3587
3588    /**
3589     * Format:
3590     * <p/>
3591     * id=1
3592     * bssid=68:7f:76:d7:1a:6e
3593     * freq=2412
3594     * level=-44
3595     * tsf=1344626243700342
3596     * flags=[WPA2-PSK-CCMP][WPS][ESS]
3597     * ssid=zfdy
3598     * ====
3599     * id=2
3600     * bssid=68:5f:74:d7:1a:6f
3601     * freq=5180
3602     * level=-73
3603     * tsf=1344626243700373
3604     * flags=[WPA2-PSK-CCMP][WPS][ESS]
3605     * ssid=zuby
3606     * ====
3607     */
3608    private void setScanResults() {
3609        mNumScanResultsKnown = 0;
3610        mNumScanResultsReturned = 0;
3611        String bssid = "";
3612        int level = 0;
3613        int freq = 0;
3614        long tsf = 0;
3615        String flags = "";
3616        WifiSsid wifiSsid = null;
3617        String scanResults;
3618        String tmpResults;
3619        StringBuffer scanResultsBuf = new StringBuffer();
3620        int sid = 0;
3621
3622        while (true) {
3623            tmpResults = mWifiNative.scanResults(sid);
3624            if (TextUtils.isEmpty(tmpResults)) break;
3625            scanResultsBuf.append(tmpResults);
3626            scanResultsBuf.append("\n");
3627            String[] lines = tmpResults.split("\n");
3628            sid = -1;
3629            for (int i = lines.length - 1; i >= 0; i--) {
3630                if (lines[i].startsWith(END_STR)) {
3631                    break;
3632                } else if (lines[i].startsWith(ID_STR)) {
3633                    try {
3634                        sid = Integer.parseInt(lines[i].substring(ID_STR.length())) + 1;
3635                    } catch (NumberFormatException e) {
3636                        // Nothing to do
3637                    }
3638                    break;
3639                }
3640            }
3641            if (sid == -1) break;
3642        }
3643
3644        // Age out scan results, we return all scan results found in the last 12 seconds,
3645        // and NOT all scan results since last scan.
3646        // ageOutScanResults(12000);
3647
3648        scanResults = scanResultsBuf.toString();
3649        if (TextUtils.isEmpty(scanResults)) {
3650            emptyScanResultCount++;
3651            if (emptyScanResultCount > 10) {
3652                // If we got too many empty scan results, the current scan cache is stale,
3653                // hence clear it.
3654                mScanResults = new ArrayList<>();
3655            }
3656            return;
3657        }
3658
3659        emptyScanResultCount = 0;
3660
3661        mWifiConfigStore.trimANQPCache(false);
3662
3663        // note that all these splits and substrings keep references to the original
3664        // huge string buffer while the amount we really want is generally pretty small
3665        // so make copies instead (one example b/11087956 wasted 400k of heap here).
3666        synchronized (mScanResultCache) {
3667            mScanResults = new ArrayList<>();
3668            String[] lines = scanResults.split("\n");
3669            final int bssidStrLen = BSSID_STR.length();
3670            final int flagLen = FLAGS_STR.length();
3671            String infoElements = null;
3672            List<String> anqpLines = null;
3673
3674            for (String line : lines) {
3675                if (line.startsWith(BSSID_STR)) {
3676                    bssid = new String(line.getBytes(), bssidStrLen, line.length() - bssidStrLen);
3677                } else if (line.startsWith(FREQ_STR)) {
3678                    try {
3679                        freq = Integer.parseInt(line.substring(FREQ_STR.length()));
3680                    } catch (NumberFormatException e) {
3681                        freq = 0;
3682                    }
3683                } else if (line.startsWith(LEVEL_STR)) {
3684                    try {
3685                        level = Integer.parseInt(line.substring(LEVEL_STR.length()));
3686                        /* some implementations avoid negative values by adding 256
3687                         * so we need to adjust for that here.
3688                         */
3689                        if (level > 0) level -= 256;
3690                    } catch (NumberFormatException e) {
3691                        level = 0;
3692                    }
3693                } else if (line.startsWith(TSF_STR)) {
3694                    try {
3695                        tsf = Long.parseLong(line.substring(TSF_STR.length()));
3696                    } catch (NumberFormatException e) {
3697                        tsf = 0;
3698                    }
3699                } else if (line.startsWith(FLAGS_STR)) {
3700                    flags = new String(line.getBytes(), flagLen, line.length() - flagLen);
3701                } else if (line.startsWith(SSID_STR)) {
3702                    wifiSsid = WifiSsid.createFromAsciiEncoded(
3703                            line.substring(SSID_STR.length()));
3704                } else if (line.startsWith(IE_STR)) {
3705                    infoElements = line;
3706                } else if (SupplicantBridge.isAnqpAttribute(line)) {
3707                    if (anqpLines == null) {
3708                        anqpLines = new ArrayList<>();
3709                    }
3710                    anqpLines.add(line);
3711                } else if (line.startsWith(DELIMITER_STR) || line.startsWith(END_STR)) {
3712                    if (bssid != null) {
3713                        try {
3714                            NetworkDetail networkDetail =
3715                                    new NetworkDetail(bssid, infoElements, anqpLines, freq);
3716
3717                            String xssid = (wifiSsid != null) ? wifiSsid.toString() : WifiSsid.NONE;
3718                            if (!xssid.equals(networkDetail.getTrimmedSSID())) {
3719                                Log.d(Utils.hs2LogTag(getClass()),
3720                                        String.format("Inconsistent SSID on BSSID '%s':" +
3721                                                        " '%s' vs '%s': %s",
3722                                        bssid, xssid, networkDetail.getSSID(), infoElements));
3723                            }
3724
3725                            if (networkDetail.hasInterworking()) {
3726                                Log.d(Utils.hs2LogTag(getClass()), "HSNwk: '" + networkDetail);
3727                            }
3728
3729                            ScanDetail scanDetail = mScanResultCache.get(networkDetail);
3730                            if (scanDetail != null) {
3731                                scanDetail.updateResults(networkDetail, level, wifiSsid, xssid,
3732                                        flags, freq, tsf);
3733                            } else {
3734                                scanDetail = new ScanDetail(networkDetail, wifiSsid, bssid,
3735                                        flags, level, freq, tsf);
3736                                mScanResultCache.put(networkDetail, scanDetail);
3737                            }
3738
3739                            mNumScanResultsReturned++; // Keep track of how many scan results we got
3740                            // as part of this scan's processing
3741                            mScanResults.add(scanDetail);
3742                        } catch (IllegalArgumentException iae) {
3743                            Log.d(TAG, "Failed to parse information elements: " + iae);
3744                        }
3745                    }
3746                    bssid = null;
3747                    level = 0;
3748                    freq = 0;
3749                    tsf = 0;
3750                    flags = "";
3751                    wifiSsid = null;
3752                    infoElements = null;
3753                    anqpLines = null;
3754                }
3755            }
3756        }
3757
3758        boolean attemptAutoJoin = true;
3759        SupplicantState state = mWifiInfo.getSupplicantState();
3760        String selection = mWifiConfigStore.getLastSelectedConfiguration();
3761        if (getCurrentState() == mRoamingState
3762                || getCurrentState() == mObtainingIpState
3763                || getCurrentState() == mScanModeState
3764                || getCurrentState() == mDisconnectingState
3765                || (getCurrentState() == mConnectedState
3766                && !mWifiConfigStore.enableAutoJoinWhenAssociated.get())
3767                || linkDebouncing
3768                || state == SupplicantState.ASSOCIATING
3769                || state == SupplicantState.AUTHENTICATING
3770                || state == SupplicantState.FOUR_WAY_HANDSHAKE
3771                || state == SupplicantState.GROUP_HANDSHAKE
3772                || (/* keep autojoin enabled if user has manually selected a wifi network,
3773                        so as to make sure we reliably remain connected to this network */
3774                mConnectionRequests == 0 && selection == null)) {
3775            // Dont attempt auto-joining again while we are already attempting to join
3776            // and/or obtaining Ip address
3777            attemptAutoJoin = false;
3778        }
3779        if (DBG) {
3780            if (selection == null) {
3781                selection = "<none>";
3782            }
3783            loge("wifi setScanResults state" + getCurrentState()
3784                    + " sup_state=" + state
3785                    + " debouncing=" + linkDebouncing
3786                    + " mConnectionRequests=" + mConnectionRequests
3787                    + " selection=" + selection);
3788        }
3789        if (attemptAutoJoin) {
3790            messageHandlingStatus = MESSAGE_HANDLING_STATUS_PROCESSED;
3791        }
3792        // Loose last selected configuration if we have been disconnected for 5 minutes
3793        if (getDisconnectedTimeMilli() > mWifiConfigStore.wifiConfigLastSelectionHysteresis) {
3794            mWifiConfigStore.setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID);
3795        }
3796
3797        if (mWifiConfigStore.enableAutoJoinWhenAssociated.get()) {
3798            synchronized (mScanResultCache) {
3799                // AutoJoincontroller will directly acces the scan result list and update it with
3800                // ScanResult status
3801                mNumScanResultsKnown = mWifiAutoJoinController.newSupplicantResults(attemptAutoJoin);
3802            }
3803        }
3804        if (linkDebouncing) {
3805            // If debouncing, we dont re-select a SSID or BSSID hence
3806            // there is no need to call the network selection code
3807            // in WifiAutoJoinController, instead,
3808            // just try to reconnect to the same SSID by triggering a roam
3809            sendMessage(CMD_AUTO_ROAM, mLastNetworkId, 1, null);
3810        }
3811    }
3812
3813    /*
3814     * Fetch RSSI, linkspeed, and frequency on current connection
3815     */
3816    private void fetchRssiLinkSpeedAndFrequencyNative() {
3817        int newRssi = -1;
3818        int newLinkSpeed = -1;
3819        int newFrequency = -1;
3820
3821        String signalPoll = mWifiNative.signalPoll();
3822
3823        if (signalPoll != null) {
3824            String[] lines = signalPoll.split("\n");
3825            for (String line : lines) {
3826                String[] prop = line.split("=");
3827                if (prop.length < 2) continue;
3828                try {
3829                    if (prop[0].equals("RSSI")) {
3830                        newRssi = Integer.parseInt(prop[1]);
3831                    } else if (prop[0].equals("LINKSPEED")) {
3832                        newLinkSpeed = Integer.parseInt(prop[1]);
3833                    } else if (prop[0].equals("FREQUENCY")) {
3834                        newFrequency = Integer.parseInt(prop[1]);
3835                    }
3836                } catch (NumberFormatException e) {
3837                    //Ignore, defaults on rssi and linkspeed are assigned
3838                }
3839            }
3840        }
3841
3842        if (PDBG) {
3843            loge("fetchRssiLinkSpeedAndFrequencyNative rssi="
3844                    + Integer.toString(newRssi) + " linkspeed="
3845                    + Integer.toString(newLinkSpeed));
3846        }
3847
3848        if (newRssi > WifiInfo.INVALID_RSSI && newRssi < WifiInfo.MAX_RSSI) {
3849            // screen out invalid values
3850            /* some implementations avoid negative values by adding 256
3851             * so we need to adjust for that here.
3852             */
3853            if (newRssi > 0) newRssi -= 256;
3854            mWifiInfo.setRssi(newRssi);
3855            /*
3856             * Rather then sending the raw RSSI out every time it
3857             * changes, we precalculate the signal level that would
3858             * be displayed in the status bar, and only send the
3859             * broadcast if that much more coarse-grained number
3860             * changes. This cuts down greatly on the number of
3861             * broadcasts, at the cost of not informing others
3862             * interested in RSSI of all the changes in signal
3863             * level.
3864             */
3865            int newSignalLevel = WifiManager.calculateSignalLevel(newRssi, WifiManager.RSSI_LEVELS);
3866            if (newSignalLevel != mLastSignalLevel) {
3867                sendRssiChangeBroadcast(newRssi);
3868            }
3869            mLastSignalLevel = newSignalLevel;
3870        } else {
3871            mWifiInfo.setRssi(WifiInfo.INVALID_RSSI);
3872        }
3873
3874        if (newLinkSpeed != -1) {
3875            mWifiInfo.setLinkSpeed(newLinkSpeed);
3876        }
3877        if (newFrequency > 0) {
3878            if (ScanResult.is5GHz(newFrequency)) {
3879                mWifiConnectionStatistics.num5GhzConnected++;
3880            }
3881            if (ScanResult.is24GHz(newFrequency)) {
3882                mWifiConnectionStatistics.num24GhzConnected++;
3883            }
3884            mWifiInfo.setFrequency(newFrequency);
3885        }
3886        mWifiConfigStore.updateConfiguration(mWifiInfo);
3887    }
3888
3889    /**
3890     * Determine if we need to switch network:
3891     * - the delta determine the urgency to switch and/or or the expected evilness of the disruption
3892     * - match the uregncy of the switch versus the packet usage at the interface
3893     */
3894    boolean shouldSwitchNetwork(int networkDelta) {
3895        int delta;
3896        if (networkDelta <= 0) {
3897            return false;
3898        }
3899        delta = networkDelta;
3900        if (mWifiInfo != null) {
3901            if (!mWifiConfigStore.enableAutoJoinWhenAssociated.get()
3902                    && mWifiInfo.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID) {
3903                // If AutoJoin while associated is not enabled,
3904                // we should never switch network when already associated
3905                delta = -1000;
3906            } else {
3907                // TODO: Look at per AC packet count, do not switch if VO/VI traffic is present
3908                // TODO: at the interface. We should also discriminate between ucast and mcast,
3909                // TODO: since the rxSuccessRate include all the bonjour and Ipv6
3910                // TODO: broadcasts
3911                if ((mWifiInfo.txSuccessRate > 20) || (mWifiInfo.rxSuccessRate > 80)) {
3912                    delta -= 999;
3913                } else if ((mWifiInfo.txSuccessRate > 5) || (mWifiInfo.rxSuccessRate > 30)) {
3914                    delta -= 6;
3915                }
3916                loge("WifiStateMachine shouldSwitchNetwork "
3917                        + " txSuccessRate=" + String.format("%.2f", mWifiInfo.txSuccessRate)
3918                        + " rxSuccessRate=" + String.format("%.2f", mWifiInfo.rxSuccessRate)
3919                        + " delta " + networkDelta + " -> " + delta);
3920            }
3921        } else {
3922            loge("WifiStateMachine shouldSwitchNetwork "
3923                    + " delta " + networkDelta + " -> " + delta);
3924        }
3925        if (delta > 0) {
3926            return true;
3927        }
3928        return false;
3929    }
3930
3931    // Polling has completed, hence we wont have a score anymore
3932    private void cleanWifiScore() {
3933        mWifiInfo.txBadRate = 0;
3934        mWifiInfo.txSuccessRate = 0;
3935        mWifiInfo.txRetriesRate = 0;
3936        mWifiInfo.rxSuccessRate = 0;
3937    }
3938
3939    int mBadLinkspeedcount = 0;
3940
3941    // For debug, provide information about the last scoring operation
3942    String wifiScoringReport = null;
3943
3944    private void calculateWifiScore(WifiLinkLayerStats stats) {
3945        StringBuilder sb = new StringBuilder();
3946
3947        int score = 56; // Starting score, temporarily hardcoded in between 50 and 60
3948        boolean isBadLinkspeed = (mWifiInfo.is24GHz()
3949                && mWifiInfo.getLinkSpeed() < mWifiConfigStore.badLinkSpeed24)
3950                || (mWifiInfo.is5GHz() && mWifiInfo.getLinkSpeed()
3951                < mWifiConfigStore.badLinkSpeed5);
3952        boolean isGoodLinkspeed = (mWifiInfo.is24GHz()
3953                && mWifiInfo.getLinkSpeed() >= mWifiConfigStore.goodLinkSpeed24)
3954                || (mWifiInfo.is5GHz() && mWifiInfo.getLinkSpeed()
3955                >= mWifiConfigStore.goodLinkSpeed5);
3956
3957        if (isBadLinkspeed) {
3958            if (mBadLinkspeedcount < 6)
3959                mBadLinkspeedcount++;
3960        } else {
3961            if (mBadLinkspeedcount > 0)
3962                mBadLinkspeedcount--;
3963        }
3964
3965        if (isBadLinkspeed) sb.append(" bl(").append(mBadLinkspeedcount).append(")");
3966        if (isGoodLinkspeed) sb.append(" gl");
3967
3968        /**
3969         * We want to make sure that we use the 24GHz RSSI thresholds if
3970         * there are 2.4GHz scan results
3971         * otherwise we end up lowering the score based on 5GHz values
3972         * which may cause a switch to LTE before roaming has a chance to try 2.4GHz
3973         * We also might unblacklist the configuation based on 2.4GHz
3974         * thresholds but joining 5GHz anyhow, and failing over to 2.4GHz because 5GHz is not good
3975         */
3976        boolean use24Thresholds = false;
3977        boolean homeNetworkBoost = false;
3978        WifiConfiguration currentConfiguration = getCurrentWifiConfiguration();
3979        ScanDetailCache scanDetailCache =
3980                mWifiConfigStore.getScanDetailCache(currentConfiguration);
3981        if (currentConfiguration != null && scanDetailCache != null) {
3982            currentConfiguration.setVisibility(scanDetailCache.getVisibility(12000));
3983            if (currentConfiguration.visibility != null) {
3984                if (currentConfiguration.visibility.rssi24 != WifiConfiguration.INVALID_RSSI
3985                        && currentConfiguration.visibility.rssi24
3986                        >= (currentConfiguration.visibility.rssi5 - 2)) {
3987                    use24Thresholds = true;
3988                }
3989            }
3990            if (scanDetailCache.size() <= 6
3991                && currentConfiguration.allowedKeyManagement.cardinality() == 1
3992                && currentConfiguration.allowedKeyManagement.
3993                    get(WifiConfiguration.KeyMgmt.WPA_PSK) == true) {
3994                // A PSK network with less than 6 known BSSIDs
3995                // This is most likely a home network and thus we want to stick to wifi more
3996                homeNetworkBoost = true;
3997            }
3998        }
3999        if (homeNetworkBoost) sb.append(" hn");
4000        if (use24Thresholds) sb.append(" u24");
4001
4002        int rssi = mWifiInfo.getRssi() - 6 * mAggressiveHandover
4003                + (homeNetworkBoost ? WifiConfiguration.HOME_NETWORK_RSSI_BOOST : 0);
4004        sb.append(String.format(" rssi=%d ag=%d", rssi, mAggressiveHandover));
4005
4006        boolean is24GHz = use24Thresholds || mWifiInfo.is24GHz();
4007
4008        boolean isBadRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdBadRssi24.get())
4009                || (!is24GHz && rssi < mWifiConfigStore.thresholdBadRssi5.get());
4010        boolean isLowRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdLowRssi24.get())
4011                || (!is24GHz && mWifiInfo.getRssi() < mWifiConfigStore.thresholdLowRssi5.get());
4012        boolean isHighRSSI = (is24GHz && rssi >= mWifiConfigStore.thresholdGoodRssi24.get())
4013                || (!is24GHz && mWifiInfo.getRssi() >= mWifiConfigStore.thresholdGoodRssi5.get());
4014
4015        if (isBadRSSI) sb.append(" br");
4016        if (isLowRSSI) sb.append(" lr");
4017        if (isHighRSSI) sb.append(" hr");
4018
4019        int penalizedDueToUserTriggeredDisconnect = 0;        // For debug information
4020        if (currentConfiguration != null &&
4021                (mWifiInfo.txSuccessRate > 5 || mWifiInfo.rxSuccessRate > 5)) {
4022            if (isBadRSSI) {
4023                currentConfiguration.numTicksAtBadRSSI++;
4024                if (currentConfiguration.numTicksAtBadRSSI > 1000) {
4025                    // We remained associated for a compound amount of time while passing
4026                    // traffic, hence loose the corresponding user triggered disabled stats
4027                    if (currentConfiguration.numUserTriggeredWifiDisableBadRSSI > 0) {
4028                        currentConfiguration.numUserTriggeredWifiDisableBadRSSI--;
4029                    }
4030                    if (currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0) {
4031                        currentConfiguration.numUserTriggeredWifiDisableLowRSSI--;
4032                    }
4033                    if (currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) {
4034                        currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI--;
4035                    }
4036                    currentConfiguration.numTicksAtBadRSSI = 0;
4037                }
4038                if (mWifiConfigStore.enableWifiCellularHandoverUserTriggeredAdjustment &&
4039                        (currentConfiguration.numUserTriggeredWifiDisableBadRSSI > 0
4040                                || currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0
4041                                || currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0)) {
4042                    score = score - 5;
4043                    penalizedDueToUserTriggeredDisconnect = 1;
4044                    sb.append(" p1");
4045                }
4046            } else if (isLowRSSI) {
4047                currentConfiguration.numTicksAtLowRSSI++;
4048                if (currentConfiguration.numTicksAtLowRSSI > 1000) {
4049                    // We remained associated for a compound amount of time while passing
4050                    // traffic, hence loose the corresponding user triggered disabled stats
4051                    if (currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0) {
4052                        currentConfiguration.numUserTriggeredWifiDisableLowRSSI--;
4053                    }
4054                    if (currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) {
4055                        currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI--;
4056                    }
4057                    currentConfiguration.numTicksAtLowRSSI = 0;
4058                }
4059                if (mWifiConfigStore.enableWifiCellularHandoverUserTriggeredAdjustment &&
4060                        (currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0
4061                                || currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0)) {
4062                    score = score - 5;
4063                    penalizedDueToUserTriggeredDisconnect = 2;
4064                    sb.append(" p2");
4065                }
4066            } else if (!isHighRSSI) {
4067                currentConfiguration.numTicksAtNotHighRSSI++;
4068                if (currentConfiguration.numTicksAtNotHighRSSI > 1000) {
4069                    // We remained associated for a compound amount of time while passing
4070                    // traffic, hence loose the corresponding user triggered disabled stats
4071                    if (currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) {
4072                        currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI--;
4073                    }
4074                    currentConfiguration.numTicksAtNotHighRSSI = 0;
4075                }
4076                if (mWifiConfigStore.enableWifiCellularHandoverUserTriggeredAdjustment &&
4077                        currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) {
4078                    score = score - 5;
4079                    penalizedDueToUserTriggeredDisconnect = 3;
4080                    sb.append(" p3");
4081                }
4082            }
4083            sb.append(String.format(" ticks %d,%d,%d", currentConfiguration.numTicksAtBadRSSI,
4084                    currentConfiguration.numTicksAtLowRSSI,
4085                    currentConfiguration.numTicksAtNotHighRSSI));
4086        }
4087
4088        if (PDBG) {
4089            String rssiStatus = "";
4090            if (isBadRSSI) rssiStatus += " badRSSI ";
4091            else if (isHighRSSI) rssiStatus += " highRSSI ";
4092            else if (isLowRSSI) rssiStatus += " lowRSSI ";
4093            if (isBadLinkspeed) rssiStatus += " lowSpeed ";
4094            loge("calculateWifiScore freq=" + Integer.toString(mWifiInfo.getFrequency())
4095                    + " speed=" + Integer.toString(mWifiInfo.getLinkSpeed())
4096                    + " score=" + Integer.toString(mWifiInfo.score)
4097                    + rssiStatus
4098                    + " -> txbadrate=" + String.format("%.2f", mWifiInfo.txBadRate)
4099                    + " txgoodrate=" + String.format("%.2f", mWifiInfo.txSuccessRate)
4100                    + " txretriesrate=" + String.format("%.2f", mWifiInfo.txRetriesRate)
4101                    + " rxrate=" + String.format("%.2f", mWifiInfo.rxSuccessRate)
4102                    + " userTriggerdPenalty" + penalizedDueToUserTriggeredDisconnect);
4103        }
4104
4105        if ((mWifiInfo.txBadRate >= 1) && (mWifiInfo.txSuccessRate < 3)
4106                && (isBadRSSI || isLowRSSI)) {
4107            // Link is stuck
4108            if (mWifiInfo.linkStuckCount < 5)
4109                mWifiInfo.linkStuckCount += 1;
4110            sb.append(String.format(" ls+=%d", mWifiInfo.linkStuckCount));
4111            if (PDBG) loge(" bad link -> stuck count ="
4112                    + Integer.toString(mWifiInfo.linkStuckCount));
4113        } else if (mWifiInfo.txBadRate < 0.3) {
4114            if (mWifiInfo.linkStuckCount > 0)
4115                mWifiInfo.linkStuckCount -= 1;
4116            sb.append(String.format(" ls-=%d", mWifiInfo.linkStuckCount));
4117            if (PDBG) loge(" good link -> stuck count ="
4118                    + Integer.toString(mWifiInfo.linkStuckCount));
4119        }
4120
4121        sb.append(String.format(" [%d", score));
4122
4123        if (mWifiInfo.linkStuckCount > 1) {
4124            // Once link gets stuck for more than 3 seconds, start reducing the score
4125            score = score - 2 * (mWifiInfo.linkStuckCount - 1);
4126        }
4127        sb.append(String.format(",%d", score));
4128
4129        if (isBadLinkspeed) {
4130            score -= 4;
4131            if (PDBG) {
4132                loge(" isBadLinkspeed   ---> count=" + mBadLinkspeedcount
4133                        + " score=" + Integer.toString(score));
4134            }
4135        } else if ((isGoodLinkspeed) && (mWifiInfo.txSuccessRate > 5)) {
4136            score += 4; // So as bad rssi alone dont kill us
4137        }
4138        sb.append(String.format(",%d", score));
4139
4140        if (isBadRSSI) {
4141            if (mWifiInfo.badRssiCount < 7)
4142                mWifiInfo.badRssiCount += 1;
4143        } else if (isLowRSSI) {
4144            mWifiInfo.lowRssiCount = 1; // Dont increment the lowRssi count above 1
4145            if (mWifiInfo.badRssiCount > 0) {
4146                // Decrement bad Rssi count
4147                mWifiInfo.badRssiCount -= 1;
4148            }
4149        } else {
4150            mWifiInfo.badRssiCount = 0;
4151            mWifiInfo.lowRssiCount = 0;
4152        }
4153
4154        score -= mWifiInfo.badRssiCount * 2 + mWifiInfo.lowRssiCount;
4155        sb.append(String.format(",%d", score));
4156
4157        if (PDBG) loge(" badRSSI count" + Integer.toString(mWifiInfo.badRssiCount)
4158                + " lowRSSI count" + Integer.toString(mWifiInfo.lowRssiCount)
4159                + " --> score " + Integer.toString(score));
4160
4161
4162        if (isHighRSSI) {
4163            score += 5;
4164            if (PDBG) loge(" isHighRSSI       ---> score=" + Integer.toString(score));
4165        }
4166        sb.append(String.format(",%d]", score));
4167
4168        sb.append(String.format(" brc=%d lrc=%d", mWifiInfo.badRssiCount, mWifiInfo.lowRssiCount));
4169
4170        //sanitize boundaries
4171        if (score > NetworkAgent.WIFI_BASE_SCORE)
4172            score = NetworkAgent.WIFI_BASE_SCORE;
4173        if (score < 0)
4174            score = 0;
4175
4176        //report score
4177        if (score != mWifiInfo.score) {
4178            if (DBG) {
4179                loge("calculateWifiScore() report new score " + Integer.toString(score));
4180            }
4181            mWifiInfo.score = score;
4182            if (mNetworkAgent != null) {
4183                mNetworkAgent.sendNetworkScore(score);
4184            }
4185        }
4186        wifiScoringReport = sb.toString();
4187    }
4188
4189    public double getTxPacketRate() {
4190        if (mWifiInfo != null) {
4191            return mWifiInfo.txSuccessRate;
4192        }
4193        return -1;
4194    }
4195
4196    public double getRxPacketRate() {
4197        if (mWifiInfo != null) {
4198            return mWifiInfo.rxSuccessRate;
4199        }
4200        return -1;
4201    }
4202
4203    /**
4204     * Fetch TX packet counters on current connection
4205     */
4206    private void fetchPktcntNative(RssiPacketCountInfo info) {
4207        String pktcntPoll = mWifiNative.pktcntPoll();
4208
4209        if (pktcntPoll != null) {
4210            String[] lines = pktcntPoll.split("\n");
4211            for (String line : lines) {
4212                String[] prop = line.split("=");
4213                if (prop.length < 2) continue;
4214                try {
4215                    if (prop[0].equals("TXGOOD")) {
4216                        info.txgood = Integer.parseInt(prop[1]);
4217                    } else if (prop[0].equals("TXBAD")) {
4218                        info.txbad = Integer.parseInt(prop[1]);
4219                    }
4220                } catch (NumberFormatException e) {
4221                    // Ignore
4222                }
4223            }
4224        }
4225    }
4226
4227    private boolean clearIPv4Address(String iface) {
4228        try {
4229            InterfaceConfiguration ifcg = new InterfaceConfiguration();
4230            ifcg.setLinkAddress(new LinkAddress("0.0.0.0/0"));
4231            mNwService.setInterfaceConfig(iface, ifcg);
4232            return true;
4233        } catch (RemoteException e) {
4234            return false;
4235        }
4236    }
4237
4238    private boolean isProvisioned(LinkProperties lp) {
4239        return lp.isProvisioned() ||
4240                (mWifiConfigStore.isUsingStaticIp(mLastNetworkId) && lp.hasIPv4Address());
4241    }
4242
4243    /**
4244     * Updates mLinkProperties by merging information from various sources.
4245     * <p/>
4246     * This is needed because the information in mLinkProperties comes from multiple sources (DHCP,
4247     * netlink, static configuration, ...). When one of these sources of information has updated
4248     * link properties, we can't just assign them to mLinkProperties or we'd lose track of the
4249     * information that came from other sources. Instead, when one of those sources has new
4250     * information, we update the object that tracks the information from that source and then
4251     * call this method to apply the change to mLinkProperties.
4252     * <p/>
4253     * The information in mLinkProperties is currently obtained as follows:
4254     * - Interface name: set in the constructor.
4255     * - IPv4 and IPv6 addresses: netlink, passed in by mNetlinkTracker.
4256     * - IPv4 routes, DNS servers, and domains: DHCP.
4257     * - IPv6 routes and DNS servers: netlink, passed in by mNetlinkTracker.
4258     * - HTTP proxy: the wifi config store.
4259     */
4260    private void updateLinkProperties(int reason) {
4261        LinkProperties newLp = new LinkProperties();
4262
4263        // Interface name and proxy are locally configured.
4264        newLp.setInterfaceName(mInterfaceName);
4265        newLp.setHttpProxy(mWifiConfigStore.getProxyProperties(mLastNetworkId));
4266
4267        // IPv4/v6 addresses, IPv6 routes and IPv6 DNS servers come from netlink.
4268        LinkProperties netlinkLinkProperties = mNetlinkTracker.getLinkProperties();
4269        newLp.setLinkAddresses(netlinkLinkProperties.getLinkAddresses());
4270        for (RouteInfo route : netlinkLinkProperties.getRoutes()) {
4271            newLp.addRoute(route);
4272        }
4273        for (InetAddress dns : netlinkLinkProperties.getDnsServers()) {
4274            newLp.addDnsServer(dns);
4275        }
4276
4277        // IPv4 routes, DNS servers and domains come from mDhcpResults.
4278        synchronized (mDhcpResultsLock) {
4279            // Even when we're using static configuration, we don't need to look at the config
4280            // store, because static IP configuration also populates mDhcpResults.
4281            if ((mDhcpResults != null)) {
4282                for (RouteInfo route : mDhcpResults.getRoutes(mInterfaceName)) {
4283                    newLp.addRoute(route);
4284                }
4285                for (InetAddress dns : mDhcpResults.dnsServers) {
4286                    newLp.addDnsServer(dns);
4287                }
4288                newLp.setDomains(mDhcpResults.domains);
4289            }
4290        }
4291
4292        final boolean linkChanged = !newLp.equals(mLinkProperties);
4293        final boolean wasProvisioned = isProvisioned(mLinkProperties);
4294        final boolean isProvisioned = isProvisioned(newLp);
4295        final boolean lostIPv4Provisioning =
4296                mLinkProperties.hasIPv4Address() && !newLp.hasIPv4Address();
4297        final DetailedState detailedState = getNetworkDetailedState();
4298
4299        if (linkChanged) {
4300            if (DBG) {
4301                log("Link configuration changed for netId: " + mLastNetworkId
4302                        + " old: " + mLinkProperties + " new: " + newLp);
4303            }
4304            mLinkProperties = newLp;
4305            if (TextUtils.isEmpty(mTcpBufferSizes) == false) {
4306                mLinkProperties.setTcpBufferSizes(mTcpBufferSizes);
4307            }
4308            if (mNetworkAgent != null) mNetworkAgent.sendLinkProperties(mLinkProperties);
4309        }
4310
4311        if (DBG) {
4312            StringBuilder sb = new StringBuilder();
4313            sb.append("updateLinkProperties nid: " + mLastNetworkId);
4314            sb.append(" state: " + detailedState);
4315            sb.append(" reason: " + smToString(reason));
4316
4317            if (mLinkProperties != null) {
4318                if (mLinkProperties.hasIPv4Address()) {
4319                    sb.append(" v4");
4320                }
4321                if (mLinkProperties.hasGlobalIPv6Address()) {
4322                    sb.append(" v6");
4323                }
4324                if (mLinkProperties.hasIPv4DefaultRoute()) {
4325                    sb.append(" v4r");
4326                }
4327                if (mLinkProperties.hasIPv6DefaultRoute()) {
4328                    sb.append(" v6r");
4329                }
4330                if (mLinkProperties.hasIPv4DnsServer()) {
4331                    sb.append(" v4dns");
4332                }
4333                if (mLinkProperties.hasIPv6DnsServer()) {
4334                    sb.append(" v6dns");
4335                }
4336                if (isProvisioned) {
4337                    sb.append(" isprov");
4338                }
4339            }
4340            loge(sb.toString());
4341        }
4342
4343        // If we just configured or lost IP configuration, do the needful.
4344        // We don't just call handleSuccessfulIpConfiguration() or handleIpConfigurationLost()
4345        // here because those should only be called if we're attempting to connect or already
4346        // connected, whereas updateLinkProperties can be called at any time.
4347        switch (reason) {
4348            case DhcpStateMachine.DHCP_SUCCESS:
4349            case CMD_STATIC_IP_SUCCESS:
4350                // IPv4 provisioning succeded. Advance to connected state.
4351                sendMessage(CMD_IP_CONFIGURATION_SUCCESSFUL);
4352                if (!isProvisioned) {
4353                    // Can never happen unless DHCP reports success but isProvisioned thinks the
4354                    // resulting configuration is invalid (e.g., no IPv4 address, or the state in
4355                    // mLinkProperties is out of sync with reality, or there's a bug in this code).
4356                    // TODO: disconnect here instead. If our configuration is not usable, there's no
4357                    // point in staying connected, and if mLinkProperties is out of sync with
4358                    // reality, that will cause problems in the future.
4359                    loge("IPv4 config succeeded, but not provisioned");
4360                }
4361                break;
4362
4363            case DhcpStateMachine.DHCP_FAILURE:
4364                // DHCP failed. If we're not already provisioned, or we had IPv4 and now lost it,
4365                // give up and disconnect.
4366                // If we're already provisioned (e.g., IPv6-only network), stay connected.
4367                if (!isProvisioned || lostIPv4Provisioning) {
4368                    sendMessage(CMD_IP_CONFIGURATION_LOST);
4369                } else {
4370                    // DHCP failed, but we're provisioned (e.g., if we're on an IPv6-only network).
4371                    sendMessage(CMD_IP_CONFIGURATION_SUCCESSFUL);
4372
4373                    // To be sure we don't get stuck with a non-working network if all we had is
4374                    // IPv4, remove the IPv4 address from the interface (since we're using DHCP,
4375                    // and DHCP failed). If we had an IPv4 address before, the deletion of the
4376                    // address  will cause a CMD_UPDATE_LINKPROPERTIES. If the IPv4 address was
4377                    // necessary for provisioning, its deletion will cause us to disconnect.
4378                    //
4379                    // This shouldn't be needed, because on an IPv4-only network a DHCP failure will
4380                    // have empty DhcpResults and thus empty LinkProperties, and isProvisioned will
4381                    // not return true if we're using DHCP and don't have an IPv4 default route. So
4382                    // for now it's only here for extra redundancy. However, it will increase
4383                    // robustness if we move to getting IPv4 routes from netlink as well.
4384                    loge("DHCP failure: provisioned, clearing IPv4 address.");
4385                    if (!clearIPv4Address(mInterfaceName)) {
4386                        sendMessage(CMD_IP_CONFIGURATION_LOST);
4387                    }
4388                }
4389                break;
4390
4391            case CMD_STATIC_IP_FAILURE:
4392                // Static configuration was invalid, or an error occurred in applying it. Give up.
4393                sendMessage(CMD_IP_CONFIGURATION_LOST);
4394                break;
4395
4396            case CMD_UPDATE_LINKPROPERTIES:
4397                // IP addresses, DNS servers, etc. changed. Act accordingly.
4398                if (wasProvisioned && !isProvisioned) {
4399                    // We no longer have a usable network configuration. Disconnect.
4400                    sendMessage(CMD_IP_CONFIGURATION_LOST);
4401                } else if (!wasProvisioned && isProvisioned) {
4402                    // We have a usable IPv6-only config. Advance to connected state.
4403                    sendMessage(CMD_IP_CONFIGURATION_SUCCESSFUL);
4404                }
4405                if (linkChanged && getNetworkDetailedState() == DetailedState.CONNECTED) {
4406                    // If anything has changed and we're already connected, send out a notification.
4407                    sendLinkConfigurationChangedBroadcast();
4408                }
4409                break;
4410        }
4411    }
4412
4413    /**
4414     * Clears all our link properties.
4415     */
4416    private void clearLinkProperties() {
4417        // Clear the link properties obtained from DHCP and netlink.
4418        synchronized (mDhcpResultsLock) {
4419            if (mDhcpResults != null) {
4420                mDhcpResults.clear();
4421            }
4422        }
4423        mNetlinkTracker.clearLinkProperties();
4424
4425        // Now clear the merged link properties.
4426        mLinkProperties.clear();
4427        if (mNetworkAgent != null) mNetworkAgent.sendLinkProperties(mLinkProperties);
4428    }
4429
4430    /**
4431     * try to update default route MAC address.
4432     */
4433    private String updateDefaultRouteMacAddress(int timeout) {
4434        String address = null;
4435        for (RouteInfo route : mLinkProperties.getRoutes()) {
4436            if (route.isDefaultRoute() && route.hasGateway()) {
4437                InetAddress gateway = route.getGateway();
4438                if (gateway instanceof Inet4Address) {
4439                    if (PDBG) {
4440                        loge("updateDefaultRouteMacAddress found Ipv4 default :"
4441                                + gateway.getHostAddress());
4442                    }
4443                    address = macAddressFromRoute(gateway.getHostAddress());
4444                     /* The gateway's MAC address is known */
4445                    if ((address == null) && (timeout > 0)) {
4446                        boolean reachable = false;
4447                        try {
4448                            reachable = gateway.isReachable(timeout);
4449                        } catch (Exception e) {
4450                            loge("updateDefaultRouteMacAddress exception reaching :"
4451                                    + gateway.getHostAddress());
4452
4453                        } finally {
4454                            if (reachable == true) {
4455
4456                                address = macAddressFromRoute(gateway.getHostAddress());
4457                                if (PDBG) {
4458                                    loge("updateDefaultRouteMacAddress reachable (tried again) :"
4459                                            + gateway.getHostAddress() + " found " + address);
4460                                }
4461                            }
4462                        }
4463                    }
4464                    if (address != null) {
4465                        mWifiConfigStore.setDefaultGwMacAddress(mLastNetworkId, address);
4466                    }
4467                }
4468            }
4469        }
4470        return address;
4471    }
4472
4473    private void sendScanResultsAvailableBroadcast() {
4474        Intent intent = new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
4475        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
4476        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4477    }
4478
4479    private void sendRssiChangeBroadcast(final int newRssi) {
4480        try {
4481            mBatteryStats.noteWifiRssiChanged(newRssi);
4482        } catch (RemoteException e) {
4483            // Won't happen.
4484        }
4485        Intent intent = new Intent(WifiManager.RSSI_CHANGED_ACTION);
4486        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
4487        intent.putExtra(WifiManager.EXTRA_NEW_RSSI, newRssi);
4488        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
4489    }
4490
4491    private void sendNetworkStateChangeBroadcast(String bssid) {
4492        Intent intent = new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION);
4493        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
4494        intent.putExtra(WifiManager.EXTRA_NETWORK_INFO, new NetworkInfo(mNetworkInfo));
4495        intent.putExtra(WifiManager.EXTRA_LINK_PROPERTIES, new LinkProperties(mLinkProperties));
4496        if (bssid != null)
4497            intent.putExtra(WifiManager.EXTRA_BSSID, bssid);
4498        if (mNetworkInfo.getDetailedState() == DetailedState.VERIFYING_POOR_LINK ||
4499                mNetworkInfo.getDetailedState() == DetailedState.CONNECTED) {
4500            intent.putExtra(WifiManager.EXTRA_WIFI_INFO, new WifiInfo(mWifiInfo));
4501        }
4502        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
4503    }
4504
4505    private void sendLinkConfigurationChangedBroadcast() {
4506        Intent intent = new Intent(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
4507        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
4508        intent.putExtra(WifiManager.EXTRA_LINK_PROPERTIES, new LinkProperties(mLinkProperties));
4509        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4510    }
4511
4512    private void sendSupplicantConnectionChangedBroadcast(boolean connected) {
4513        Intent intent = new Intent(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
4514        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
4515        intent.putExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, connected);
4516        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4517    }
4518
4519    /**
4520     * Record the detailed state of a network.
4521     *
4522     * @param state the new {@code DetailedState}
4523     */
4524    private boolean setNetworkDetailedState(NetworkInfo.DetailedState state) {
4525        boolean hidden = false;
4526
4527        if (linkDebouncing || isRoaming()) {
4528            // There is generally a confusion in the system about colluding
4529            // WiFi Layer 2 state (as reported by supplicant) and the Network state
4530            // which leads to multiple confusion.
4531            //
4532            // If link is de-bouncing or roaming, we already have an IP address
4533            // as well we were connected and are doing L2 cycles of
4534            // reconnecting or renewing IP address to check that we still have it
4535            // This L2 link flapping should ne be reflected into the Network state
4536            // which is the state of the WiFi Network visible to Layer 3 and applications
4537            // Note that once debouncing and roaming are completed, we will
4538            // set the Network state to where it should be, or leave it as unchanged
4539            //
4540            hidden = true;
4541        }
4542        if (DBG) {
4543            log("setDetailed state, old ="
4544                    + mNetworkInfo.getDetailedState() + " and new state=" + state
4545                    + " hidden=" + hidden);
4546        }
4547        if (mNetworkInfo.getExtraInfo() != null && mWifiInfo.getSSID() != null) {
4548            // Always indicate that SSID has changed
4549            if (!mNetworkInfo.getExtraInfo().equals(mWifiInfo.getSSID())) {
4550                if (DBG) {
4551                    log("setDetailed state send new extra info" + mWifiInfo.getSSID());
4552                }
4553                mNetworkInfo.setExtraInfo(mWifiInfo.getSSID());
4554                sendNetworkStateChangeBroadcast(null);
4555            }
4556        }
4557        if (hidden == true) {
4558            return false;
4559        }
4560
4561        if (state != mNetworkInfo.getDetailedState()) {
4562            mNetworkInfo.setDetailedState(state, null, mWifiInfo.getSSID());
4563            if (mNetworkAgent != null) {
4564                mNetworkAgent.sendNetworkInfo(mNetworkInfo);
4565            }
4566            sendNetworkStateChangeBroadcast(null);
4567            return true;
4568        }
4569        return false;
4570    }
4571
4572    private DetailedState getNetworkDetailedState() {
4573        return mNetworkInfo.getDetailedState();
4574    }
4575
4576
4577    private SupplicantState handleSupplicantStateChange(Message message) {
4578        StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
4579        SupplicantState state = stateChangeResult.state;
4580        // Supplicant state change
4581        // [31-13] Reserved for future use
4582        // [8 - 0] Supplicant state (as defined in SupplicantState.java)
4583        // 50023 supplicant_state_changed (custom|1|5)
4584        mWifiInfo.setSupplicantState(state);
4585        // Network id is only valid when we start connecting
4586        if (SupplicantState.isConnecting(state)) {
4587            mWifiInfo.setNetworkId(stateChangeResult.networkId);
4588        } else {
4589            mWifiInfo.setNetworkId(WifiConfiguration.INVALID_NETWORK_ID);
4590        }
4591
4592        mWifiInfo.setBSSID(stateChangeResult.BSSID);
4593
4594        if (mWhiteListedSsids != null
4595                && mWhiteListedSsids.length > 0
4596                && stateChangeResult.wifiSsid != null) {
4597            String SSID = stateChangeResult.wifiSsid.toString();
4598            String currentSSID = mWifiInfo.getSSID();
4599            if (SSID != null
4600                    && currentSSID != null
4601                    && !SSID.equals(WifiSsid.NONE)) {
4602                    // Remove quote before comparing
4603                    if (SSID.length() >= 2 && SSID.charAt(0) == '"'
4604                            && SSID.charAt(SSID.length() - 1) == '"')
4605                    {
4606                        SSID = SSID.substring(1, SSID.length() - 1);
4607                    }
4608                    if (currentSSID.length() >= 2 && currentSSID.charAt(0) == '"'
4609                            && currentSSID.charAt(currentSSID.length() - 1) == '"') {
4610                        currentSSID = currentSSID.substring(1, currentSSID.length() - 1);
4611                    }
4612                    if ((!SSID.equals(currentSSID)) && (getCurrentState() == mConnectedState)) {
4613                        lastConnectAttempt = System.currentTimeMillis();
4614                        targetWificonfiguration
4615                            = mWifiConfigStore.getWifiConfiguration(mWifiInfo.getNetworkId());
4616                        transitionTo(mRoamingState);
4617                    }
4618             }
4619        }
4620
4621        mWifiInfo.setSSID(stateChangeResult.wifiSsid);
4622
4623        mSupplicantStateTracker.sendMessage(Message.obtain(message));
4624
4625        return state;
4626    }
4627
4628    /**
4629     * Resets the Wi-Fi Connections by clearing any state, resetting any sockets
4630     * using the interface, stopping DHCP & disabling interface
4631     */
4632    private void handleNetworkDisconnect() {
4633        if (DBG) log("handleNetworkDisconnect: Stopping DHCP and clearing IP"
4634                + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
4635                + " - " + Thread.currentThread().getStackTrace()[3].getMethodName()
4636                + " - " + Thread.currentThread().getStackTrace()[4].getMethodName()
4637                + " - " + Thread.currentThread().getStackTrace()[5].getMethodName());
4638
4639
4640        clearCurrentConfigBSSID("handleNetworkDisconnect");
4641
4642        stopDhcp();
4643
4644        try {
4645            mNwService.clearInterfaceAddresses(mInterfaceName);
4646            mNwService.disableIpv6(mInterfaceName);
4647        } catch (Exception e) {
4648            loge("Failed to clear addresses or disable ipv6" + e);
4649        }
4650
4651        /* Reset data structures */
4652        mBadLinkspeedcount = 0;
4653        mWifiInfo.reset();
4654        linkDebouncing = false;
4655        /* Reset roaming parameters */
4656        mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE;
4657
4658        /**
4659         *  fullBandConnectedTimeIntervalMilli:
4660         *  - start scans at mWifiConfigStore.wifiAssociatedShortScanIntervalMilli seconds interval
4661         *  - exponentially increase to mWifiConfigStore.associatedFullScanMaxIntervalMilli
4662         *  Initialize to sane value = 20 seconds
4663         */
4664        fullBandConnectedTimeIntervalMilli = 20 * 1000;
4665
4666        setNetworkDetailedState(DetailedState.DISCONNECTED);
4667        if (mNetworkAgent != null) {
4668            mNetworkAgent.sendNetworkInfo(mNetworkInfo);
4669            mNetworkAgent = null;
4670        }
4671        mWifiConfigStore.updateStatus(mLastNetworkId, DetailedState.DISCONNECTED);
4672
4673        /* Clear network properties */
4674        clearLinkProperties();
4675
4676        /* Cend event to CM & network change broadcast */
4677        sendNetworkStateChangeBroadcast(mLastBssid);
4678
4679        /* Cancel auto roam requests */
4680        autoRoamSetBSSID(mLastNetworkId, "any");
4681
4682        mLastBssid = null;
4683        registerDisconnected();
4684        mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID;
4685    }
4686
4687    private void handleSupplicantConnectionLoss(boolean killSupplicant) {
4688        /* Socket connection can be lost when we do a graceful shutdown
4689        * or when the driver is hung. Ensure supplicant is stopped here.
4690        */
4691        if (killSupplicant) {
4692            mWifiMonitor.killSupplicant(mP2pSupported);
4693        }
4694        mWifiNative.closeSupplicantConnection();
4695        sendSupplicantConnectionChangedBroadcast(false);
4696        setWifiState(WIFI_STATE_DISABLED);
4697    }
4698
4699    void handlePreDhcpSetup() {
4700        mDhcpActive = true;
4701        if (!mBluetoothConnectionActive) {
4702            /*
4703             * There are problems setting the Wi-Fi driver's power
4704             * mode to active when bluetooth coexistence mode is
4705             * enabled or sense.
4706             * <p>
4707             * We set Wi-Fi to active mode when
4708             * obtaining an IP address because we've found
4709             * compatibility issues with some routers with low power
4710             * mode.
4711             * <p>
4712             * In order for this active power mode to properly be set,
4713             * we disable coexistence mode until we're done with
4714             * obtaining an IP address.  One exception is if we
4715             * are currently connected to a headset, since disabling
4716             * coexistence would interrupt that connection.
4717             */
4718            // Disable the coexistence mode
4719            mWifiNative.setBluetoothCoexistenceMode(
4720                    mWifiNative.BLUETOOTH_COEXISTENCE_MODE_DISABLED);
4721        }
4722
4723        // Disable power save and suspend optimizations during DHCP
4724        // Note: The order here is important for now. Brcm driver changes
4725        // power settings when we control suspend mode optimizations.
4726        // TODO: Remove this comment when the driver is fixed.
4727        setSuspendOptimizationsNative(SUSPEND_DUE_TO_DHCP, false);
4728        mWifiNative.setPowerSave(false);
4729
4730        // Update link layer stats
4731        getWifiLinkLayerStats(false);
4732
4733        /* P2p discovery breaks dhcp, shut it down in order to get through this */
4734        Message msg = new Message();
4735        msg.what = WifiP2pServiceImpl.BLOCK_DISCOVERY;
4736        msg.arg1 = WifiP2pServiceImpl.ENABLED;
4737        msg.arg2 = DhcpStateMachine.CMD_PRE_DHCP_ACTION_COMPLETE;
4738        msg.obj = mDhcpStateMachine;
4739        mWifiP2pChannel.sendMessage(msg);
4740    }
4741
4742
4743    private boolean useLegacyDhcpClient() {
4744        return Settings.Global.getInt(
4745                mContext.getContentResolver(),
4746                Settings.Global.LEGACY_DHCP_CLIENT, 0) == 1;
4747    }
4748
4749    private void maybeInitDhcpStateMachine() {
4750        if (mDhcpStateMachine == null) {
4751            if (useLegacyDhcpClient()) {
4752                mDhcpStateMachine = DhcpStateMachine.makeDhcpStateMachine(
4753                        mContext, WifiStateMachine.this, mInterfaceName);
4754            } else {
4755                mDhcpStateMachine = DhcpClient.makeDhcpStateMachine(
4756                        mContext, WifiStateMachine.this, mInterfaceName);
4757            }
4758        }
4759    }
4760
4761    void startDhcp() {
4762        maybeInitDhcpStateMachine();
4763        mDhcpStateMachine.registerForPreDhcpNotification();
4764        mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_START_DHCP);
4765    }
4766
4767    void renewDhcp() {
4768        maybeInitDhcpStateMachine();
4769        mDhcpStateMachine.registerForPreDhcpNotification();
4770        mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_RENEW_DHCP);
4771    }
4772
4773    void stopDhcp() {
4774        if (mDhcpStateMachine != null) {
4775            /* In case we were in middle of DHCP operation restore back powermode */
4776            handlePostDhcpSetup();
4777            mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_STOP_DHCP);
4778        }
4779    }
4780
4781    void handlePostDhcpSetup() {
4782        /* Restore power save and suspend optimizations */
4783        setSuspendOptimizationsNative(SUSPEND_DUE_TO_DHCP, true);
4784        mWifiNative.setPowerSave(true);
4785
4786        mWifiP2pChannel.sendMessage(WifiP2pServiceImpl.BLOCK_DISCOVERY, WifiP2pServiceImpl.DISABLED);
4787
4788        // Set the coexistence mode back to its default value
4789        mWifiNative.setBluetoothCoexistenceMode(
4790                mWifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE);
4791
4792        mDhcpActive = false;
4793    }
4794
4795    void connectScanningService() {
4796
4797        if (mWifiScanner == null) {
4798            mWifiScanner = (WifiScanner) mContext.getSystemService(Context.WIFI_SCANNING_SERVICE);
4799        }
4800    }
4801
4802    private void handleIPv4Success(DhcpResults dhcpResults, int reason) {
4803
4804        if (PDBG) {
4805            loge("wifistatemachine handleIPv4Success <" + dhcpResults.toString() + ">");
4806            loge("link address " + dhcpResults.ipAddress);
4807        }
4808
4809        synchronized (mDhcpResultsLock) {
4810            mDhcpResults = dhcpResults;
4811        }
4812
4813        Inet4Address addr = (Inet4Address) dhcpResults.ipAddress.getAddress();
4814        if (isRoaming()) {
4815            if (addr instanceof Inet4Address) {
4816                int previousAddress = mWifiInfo.getIpAddress();
4817                int newAddress = NetworkUtils.inetAddressToInt(addr);
4818                if (previousAddress != newAddress) {
4819                    loge("handleIPv4Success, roaming and address changed" +
4820                            mWifiInfo + " got: " + addr);
4821                } else {
4822
4823                }
4824            } else {
4825                loge("handleIPv4Success, roaming and didnt get an IPv4 address" +
4826                        addr.toString());
4827            }
4828        }
4829        mWifiInfo.setInetAddress(addr);
4830        mWifiInfo.setMeteredHint(dhcpResults.hasMeteredHint());
4831        updateLinkProperties(reason);
4832    }
4833
4834    private void handleSuccessfulIpConfiguration() {
4835        mLastSignalLevel = -1; // Force update of signal strength
4836        WifiConfiguration c = getCurrentWifiConfiguration();
4837        if (c != null) {
4838            // Reset IP failure tracking
4839            c.numConnectionFailures = 0;
4840
4841            // Tell the framework whether the newly connected network is trusted or untrusted.
4842            updateCapabilities(c);
4843        }
4844        if (c != null) {
4845            ScanResult result = getCurrentScanResult();
4846            if (result == null) {
4847                loge("WifiStateMachine: handleSuccessfulIpConfiguration and no scan results" +
4848                        c.configKey());
4849            } else {
4850                // Clear the per BSSID failure count
4851                result.numIpConfigFailures = 0;
4852                // Clear the WHOLE BSSID blacklist, which means supplicant is free to retry
4853                // any BSSID, even though it may already have a non zero ip failure count,
4854                // this will typically happen if the user walks away and come back to his arrea
4855                // TODO: implement blacklisting based on a timer, i.e. keep BSSID blacklisted
4856                // in supplicant for a couple of hours or a day
4857                mWifiConfigStore.clearBssidBlacklist();
4858            }
4859        }
4860    }
4861
4862    private void handleIPv4Failure(int reason) {
4863        synchronized(mDhcpResultsLock) {
4864             if (mDhcpResults != null) {
4865                 mDhcpResults.clear();
4866             }
4867        }
4868        if (PDBG) {
4869            loge("wifistatemachine handleIPv4Failure");
4870        }
4871        updateLinkProperties(reason);
4872    }
4873
4874    private void handleIpConfigurationLost() {
4875        mWifiInfo.setInetAddress(null);
4876        mWifiInfo.setMeteredHint(false);
4877
4878        mWifiConfigStore.handleSSIDStateChange(mLastNetworkId, false,
4879                "DHCP FAILURE", mWifiInfo.getBSSID());
4880
4881        /* DHCP times out after about 30 seconds, we do a
4882         * disconnect thru supplicant, we will let autojoin retry connecting to the network
4883         */
4884        mWifiNative.disconnect();
4885    }
4886
4887    private int convertFrequencyToChannelNumber(int frequency) {
4888        if (frequency >= 2412 && frequency <= 2484) {
4889            return (frequency -2412) / 5 + 1;
4890        } else if (frequency >= 5170  &&  frequency <=5825) {
4891            //DFS is included
4892            return (frequency -5170) / 5 + 34;
4893        } else {
4894            return 0;
4895        }
4896    }
4897
4898    private int chooseApChannel(int apBand) {
4899        int apChannel;
4900        int[] channel;
4901
4902        if (apBand == 0)  {
4903            //for 2.4GHz, we only set the AP at channel 1,6,11
4904            apChannel = 5 * mRandom.nextInt(3) + 1;
4905        } else {
4906            //5G without DFS
4907            channel = mWifiNative.getChannelsForBand(2);
4908            if (channel != null && channel.length > 0) {
4909                apChannel = channel[mRandom.nextInt(channel.length)];
4910                apChannel = convertFrequencyToChannelNumber(apChannel);
4911            } else {
4912                Log.e(TAG, "SoftAp do not get available channel list");
4913                apChannel = 0;
4914            }
4915        }
4916
4917        if(DBG) {
4918            Log.d(TAG, "SoftAp set on channel " + apChannel);
4919        }
4920
4921        return apChannel;
4922    }
4923
4924
4925    /* Current design is to not set the config on a running hostapd but instead
4926     * stop and start tethering when user changes config on a running access point
4927     *
4928     * TODO: Add control channel setup through hostapd that allows changing config
4929     * on a running daemon
4930     */
4931    private void startSoftApWithConfig(final WifiConfiguration configuration) {
4932        // set channel
4933        final WifiConfiguration config = new WifiConfiguration(configuration);
4934
4935        if (DBG) {
4936            Log.d(TAG, "SoftAp config channel is: " + config.apChannel);
4937        }
4938        //set country code through HAL Here
4939        if (mSetCountryCode != null) {
4940            if(!mWifiNative.setCountryCodeHal(mSetCountryCode.toUpperCase(Locale.ROOT))) {
4941                if (config.apBand != 0) {
4942                    Log.e(TAG, "Fail to set country code. Can not setup Softap on 5GHz");
4943                    //countrycode is mandatory for 5GHz
4944                    sendMessage(CMD_START_AP_FAILURE);
4945                    return;
4946                }
4947            }
4948        } else {
4949            if (config.apBand != 0) {
4950                //countrycode is mandatory for 5GHz
4951                Log.e(TAG, "Can not setup softAp on 5GHz without country code!");
4952                sendMessage(CMD_START_AP_FAILURE);
4953                return;
4954            }
4955        }
4956
4957        if (config.apChannel == 0) {
4958            config.apChannel = chooseApChannel(config.apBand);
4959            if (config.apChannel == 0) {
4960                //fail to get available channel
4961                sendMessage(CMD_START_AP_FAILURE);
4962                return;
4963            }
4964        }
4965        //turn off interface
4966        if (!mWifiNative.toggleInterface(0)) {
4967            sendMessage(CMD_START_AP_FAILURE);
4968            return;
4969        }
4970        // Start hostapd on a separate thread
4971        new Thread(new Runnable() {
4972            public void run() {
4973                try {
4974                    mNwService.startAccessPoint(config, mInterfaceName);
4975                } catch (Exception e) {
4976                    loge("Exception in softap start " + e);
4977                    try {
4978                        mNwService.stopAccessPoint(mInterfaceName);
4979                        mNwService.startAccessPoint(config, mInterfaceName);
4980                    } catch (Exception e1) {
4981                        loge("Exception in softap re-start " + e1);
4982                        sendMessage(CMD_START_AP_FAILURE);
4983                        return;
4984                    }
4985                }
4986                if (DBG) log("Soft AP start successful");
4987                sendMessage(CMD_START_AP_SUCCESS);
4988            }
4989        }).start();
4990    }
4991
4992    /*
4993     * Read a MAC address in /proc/arp/table, used by WifistateMachine
4994     * so as to record MAC address of default gateway.
4995     **/
4996    private String macAddressFromRoute(String ipAddress) {
4997        String macAddress = null;
4998        BufferedReader reader = null;
4999        try {
5000            reader = new BufferedReader(new FileReader("/proc/net/arp"));
5001
5002            // Skip over the line bearing colum titles
5003            String line = reader.readLine();
5004
5005            while ((line = reader.readLine()) != null) {
5006                String[] tokens = line.split("[ ]+");
5007                if (tokens.length < 6) {
5008                    continue;
5009                }
5010
5011                // ARP column format is
5012                // Address HWType HWAddress Flags Mask IFace
5013                String ip = tokens[0];
5014                String mac = tokens[3];
5015
5016                if (ipAddress.equals(ip)) {
5017                    macAddress = mac;
5018                    break;
5019                }
5020            }
5021
5022            if (macAddress == null) {
5023                loge("Did not find remoteAddress {" + ipAddress + "} in " +
5024                        "/proc/net/arp");
5025            }
5026
5027        } catch (FileNotFoundException e) {
5028            loge("Could not open /proc/net/arp to lookup mac address");
5029        } catch (IOException e) {
5030            loge("Could not read /proc/net/arp to lookup mac address");
5031        } finally {
5032            try {
5033                if (reader != null) {
5034                    reader.close();
5035                }
5036            } catch (IOException e) {
5037                // Do nothing
5038            }
5039        }
5040        return macAddress;
5041
5042    }
5043
5044    private class WifiNetworkFactory extends NetworkFactory {
5045        public WifiNetworkFactory(Looper l, Context c, String TAG, NetworkCapabilities f) {
5046            super(l, c, TAG, f);
5047        }
5048
5049        @Override
5050        protected void needNetworkFor(NetworkRequest networkRequest, int score) {
5051            ++mConnectionRequests;
5052        }
5053
5054        @Override
5055        protected void releaseNetworkFor(NetworkRequest networkRequest) {
5056            --mConnectionRequests;
5057        }
5058
5059        public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5060            pw.println("mConnectionRequests " + mConnectionRequests);
5061        }
5062
5063    }
5064
5065    private class UntrustedWifiNetworkFactory extends NetworkFactory {
5066        private int mUntrustedReqCount;
5067
5068        public UntrustedWifiNetworkFactory(Looper l, Context c, String tag, NetworkCapabilities f) {
5069            super(l, c, tag, f);
5070        }
5071
5072        @Override
5073        protected void needNetworkFor(NetworkRequest networkRequest, int score) {
5074            if (!networkRequest.networkCapabilities.hasCapability(
5075                    NetworkCapabilities.NET_CAPABILITY_TRUSTED)) {
5076                if (++mUntrustedReqCount == 1) {
5077                    mWifiAutoJoinController.setAllowUntrustedConnections(true);
5078                }
5079            }
5080        }
5081
5082        @Override
5083        protected void releaseNetworkFor(NetworkRequest networkRequest) {
5084            if (!networkRequest.networkCapabilities.hasCapability(
5085                    NetworkCapabilities.NET_CAPABILITY_TRUSTED)) {
5086                if (--mUntrustedReqCount == 0) {
5087                    mWifiAutoJoinController.setAllowUntrustedConnections(false);
5088                }
5089            }
5090        }
5091
5092        public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
5093            pw.println("mUntrustedReqCount " + mUntrustedReqCount);
5094        }
5095    }
5096
5097    void maybeRegisterNetworkFactory() {
5098        if (mNetworkFactory == null) {
5099            checkAndSetConnectivityInstance();
5100            if (mCm != null) {
5101                mNetworkFactory = new WifiNetworkFactory(getHandler().getLooper(), mContext,
5102                        NETWORKTYPE, mNetworkCapabilitiesFilter);
5103                mNetworkFactory.setScoreFilter(60);
5104                mNetworkFactory.register();
5105
5106                // We can't filter untrusted network in the capabilities filter because a trusted
5107                // network would still satisfy a request that accepts untrusted ones.
5108                mUntrustedNetworkFactory = new UntrustedWifiNetworkFactory(getHandler().getLooper(),
5109                        mContext, NETWORKTYPE_UNTRUSTED, mNetworkCapabilitiesFilter);
5110                mUntrustedNetworkFactory.setScoreFilter(Integer.MAX_VALUE);
5111                mUntrustedNetworkFactory.register();
5112            }
5113        }
5114    }
5115
5116    /********************************************************
5117     * HSM states
5118     *******************************************************/
5119
5120    class DefaultState extends State {
5121        @Override
5122        public boolean processMessage(Message message) {
5123            logStateAndMessage(message, getClass().getSimpleName());
5124
5125            switch (message.what) {
5126                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
5127                    AsyncChannel ac = (AsyncChannel) message.obj;
5128                    if (ac == mWifiP2pChannel) {
5129                        if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
5130                            mWifiP2pChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
5131                        } else {
5132                            loge("WifiP2pService connection failure, error=" + message.arg1);
5133                        }
5134                    } else {
5135                        loge("got HALF_CONNECTED for unknown channel");
5136                    }
5137                    break;
5138                }
5139                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
5140                    AsyncChannel ac = (AsyncChannel) message.obj;
5141                    if (ac == mWifiP2pChannel) {
5142                        loge("WifiP2pService channel lost, message.arg1 =" + message.arg1);
5143                        //TODO: Re-establish connection to state machine after a delay
5144                        // mWifiP2pChannel.connect(mContext, getHandler(),
5145                        // mWifiP2pManager.getMessenger());
5146                    }
5147                    break;
5148                }
5149                case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE:
5150                    mBluetoothConnectionActive = (message.arg1 !=
5151                            BluetoothAdapter.STATE_DISCONNECTED);
5152                    break;
5153                    /* Synchronous call returns */
5154                case CMD_PING_SUPPLICANT:
5155                case CMD_ENABLE_NETWORK:
5156                case CMD_ADD_OR_UPDATE_NETWORK:
5157                case CMD_REMOVE_NETWORK:
5158                case CMD_SAVE_CONFIG:
5159                    replyToMessage(message, message.what, FAILURE);
5160                    break;
5161                case CMD_GET_CAPABILITY_FREQ:
5162                    replyToMessage(message, message.what, null);
5163                    break;
5164                case CMD_GET_CONFIGURED_NETWORKS:
5165                    replyToMessage(message, message.what, (List<WifiConfiguration>) null);
5166                    break;
5167                case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS:
5168                    replyToMessage(message, message.what, (List<WifiConfiguration>) null);
5169                    break;
5170                case CMD_ENABLE_RSSI_POLL:
5171                    mEnableRssiPolling = (message.arg1 == 1);
5172                    break;
5173                case CMD_SET_HIGH_PERF_MODE:
5174                    if (message.arg1 == 1) {
5175                        setSuspendOptimizations(SUSPEND_DUE_TO_HIGH_PERF, false);
5176                    } else {
5177                        setSuspendOptimizations(SUSPEND_DUE_TO_HIGH_PERF, true);
5178                    }
5179                    break;
5180                case CMD_BOOT_COMPLETED:
5181                    maybeRegisterNetworkFactory();
5182                    break;
5183                case CMD_SCREEN_STATE_CHANGED:
5184                    handleScreenStateChanged(message.arg1 != 0);
5185                    break;
5186                    /* Discard */
5187                case CMD_START_SCAN:
5188                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
5189                    break;
5190                case CMD_START_SUPPLICANT:
5191                case CMD_STOP_SUPPLICANT:
5192                case CMD_STOP_SUPPLICANT_FAILED:
5193                case CMD_START_DRIVER:
5194                case CMD_STOP_DRIVER:
5195                case CMD_DELAYED_STOP_DRIVER:
5196                case CMD_DRIVER_START_TIMED_OUT:
5197                case CMD_START_AP:
5198                case CMD_START_AP_SUCCESS:
5199                case CMD_START_AP_FAILURE:
5200                case CMD_STOP_AP:
5201                case CMD_TETHER_STATE_CHANGE:
5202                case CMD_TETHER_NOTIFICATION_TIMED_OUT:
5203                case CMD_DISCONNECT:
5204                case CMD_RECONNECT:
5205                case CMD_REASSOCIATE:
5206                case CMD_RELOAD_TLS_AND_RECONNECT:
5207                case WifiMonitor.SUP_CONNECTION_EVENT:
5208                case WifiMonitor.SUP_DISCONNECTION_EVENT:
5209                case WifiMonitor.NETWORK_CONNECTION_EVENT:
5210                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
5211                case WifiMonitor.SCAN_RESULTS_EVENT:
5212                case WifiMonitor.SCAN_FAILED_EVENT:
5213                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
5214                case WifiMonitor.AUTHENTICATION_FAILURE_EVENT:
5215                case WifiMonitor.ASSOCIATION_REJECTION_EVENT:
5216                case WifiMonitor.WPS_OVERLAP_EVENT:
5217                case CMD_BLACKLIST_NETWORK:
5218                case CMD_CLEAR_BLACKLIST:
5219                case CMD_SET_OPERATIONAL_MODE:
5220                case CMD_SET_COUNTRY_CODE:
5221                case CMD_SET_FREQUENCY_BAND:
5222                case CMD_RSSI_POLL:
5223                case CMD_ENABLE_ALL_NETWORKS:
5224                case DhcpStateMachine.CMD_PRE_DHCP_ACTION:
5225                case DhcpStateMachine.CMD_POST_DHCP_ACTION:
5226                /* Handled by WifiApConfigStore */
5227                case CMD_SET_AP_CONFIG:
5228                case CMD_SET_AP_CONFIG_COMPLETED:
5229                case CMD_REQUEST_AP_CONFIG:
5230                case CMD_RESPONSE_AP_CONFIG:
5231                case WifiWatchdogStateMachine.POOR_LINK_DETECTED:
5232                case WifiWatchdogStateMachine.GOOD_LINK_DETECTED:
5233                case CMD_NO_NETWORKS_PERIODIC_SCAN:
5234                case CMD_DISABLE_P2P_RSP:
5235                case WifiMonitor.SUP_REQUEST_IDENTITY:
5236                case CMD_TEST_NETWORK_DISCONNECT:
5237                case CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER:
5238                case WifiMonitor.SUP_REQUEST_SIM_AUTH:
5239                case CMD_TARGET_BSSID:
5240                case CMD_AUTO_CONNECT:
5241                case CMD_AUTO_ROAM:
5242                case CMD_AUTO_SAVE_NETWORK:
5243                case CMD_ASSOCIATED_BSSID:
5244                case CMD_UNWANTED_NETWORK:
5245                case CMD_DISCONNECTING_WATCHDOG_TIMER:
5246                case CMD_ROAM_WATCHDOG_TIMER:
5247                case CMD_DISABLE_EPHEMERAL_NETWORK:
5248                case CMD_GET_MATCHING_CONFIG:
5249                case CMD_RESTART_AUTOJOIN_OFFLOAD:
5250                case CMD_STARTED_PNO_DBG:
5251                case CMD_STARTED_GSCAN_DBG:
5252                case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION:
5253                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
5254                    break;
5255                case DhcpStateMachine.CMD_ON_QUIT:
5256                    mDhcpStateMachine = null;
5257                    break;
5258                case CMD_SET_SUSPEND_OPT_ENABLED:
5259                    if (message.arg1 == 1) {
5260                        mSuspendWakeLock.release();
5261                        setSuspendOptimizations(SUSPEND_DUE_TO_SCREEN, true);
5262                    } else {
5263                        setSuspendOptimizations(SUSPEND_DUE_TO_SCREEN, false);
5264                    }
5265                    break;
5266                case WifiMonitor.DRIVER_HUNG_EVENT:
5267                    setSupplicantRunning(false);
5268                    setSupplicantRunning(true);
5269                    break;
5270                case WifiManager.CONNECT_NETWORK:
5271                    replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED,
5272                            WifiManager.BUSY);
5273                    break;
5274                case WifiManager.FORGET_NETWORK:
5275                    replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED,
5276                            WifiManager.BUSY);
5277                    break;
5278                case WifiManager.SAVE_NETWORK:
5279                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
5280                    replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED,
5281                            WifiManager.BUSY);
5282                    break;
5283                case WifiManager.START_WPS:
5284                    replyToMessage(message, WifiManager.WPS_FAILED,
5285                            WifiManager.BUSY);
5286                    break;
5287                case WifiManager.CANCEL_WPS:
5288                    replyToMessage(message, WifiManager.CANCEL_WPS_FAILED,
5289                            WifiManager.BUSY);
5290                    break;
5291                case WifiManager.DISABLE_NETWORK:
5292                    replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED,
5293                            WifiManager.BUSY);
5294                    break;
5295                case WifiManager.RSSI_PKTCNT_FETCH:
5296                    replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_FAILED,
5297                            WifiManager.BUSY);
5298                    break;
5299                case CMD_GET_SUPPORTED_FEATURES:
5300                    int featureSet = WifiNative.getSupportedFeatureSet();
5301                    replyToMessage(message, message.what, featureSet);
5302                    break;
5303                case CMD_FIRMWARE_ALERT:
5304                    if (mWifiLogger != null) {
5305                        byte[] buffer = (byte[])message.obj;
5306                        mWifiLogger.captureAlertData(message.arg1, buffer);
5307                    }
5308                    break;
5309                case CMD_GET_LINK_LAYER_STATS:
5310                    // Not supported hence reply with error message
5311                    replyToMessage(message, message.what, null);
5312                    break;
5313                case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED:
5314                    NetworkInfo info = (NetworkInfo) message.obj;
5315                    mP2pConnected.set(info.isConnected());
5316                    break;
5317                case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST:
5318                    mTemporarilyDisconnectWifi = (message.arg1 == 1);
5319                    replyToMessage(message, WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE);
5320                    break;
5321                /* Link configuration (IP address, DNS, ...) changes notified via netlink */
5322                case CMD_UPDATE_LINKPROPERTIES:
5323                    updateLinkProperties(CMD_UPDATE_LINKPROPERTIES);
5324                    break;
5325                case CMD_IP_CONFIGURATION_SUCCESSFUL:
5326                case CMD_IP_CONFIGURATION_LOST:
5327                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
5328                    break;
5329                case CMD_GET_CONNECTION_STATISTICS:
5330                    replyToMessage(message, message.what, mWifiConnectionStatistics);
5331                    break;
5332                default:
5333                    loge("Error! unhandled message" + message);
5334                    break;
5335            }
5336            return HANDLED;
5337        }
5338    }
5339
5340    class InitialState extends State {
5341        @Override
5342        public void enter() {
5343            WifiNative.stopHal();
5344            mWifiNative.unloadDriver();
5345            if (mWifiP2pChannel == null) {
5346                mWifiP2pChannel = new AsyncChannel();
5347                mWifiP2pChannel.connect(mContext, getHandler(),
5348                    mWifiP2pServiceImpl.getP2pStateMachineMessenger());
5349            }
5350
5351            if (mWifiApConfigChannel == null) {
5352                mWifiApConfigChannel = new AsyncChannel();
5353                WifiApConfigStore wifiApConfigStore = WifiApConfigStore.makeWifiApConfigStore(
5354                        mContext, getHandler());
5355                wifiApConfigStore.loadApConfiguration();
5356                mWifiApConfigChannel.connectSync(mContext, getHandler(),
5357                        wifiApConfigStore.getMessenger());
5358            }
5359
5360            if (mWifiConfigStore.enableHalBasedPno.get()) {
5361                // make sure developer Settings are in sync with the config option
5362                mHalBasedPnoEnableInDevSettings = true;
5363            }
5364        }
5365        @Override
5366        public boolean processMessage(Message message) {
5367            logStateAndMessage(message, getClass().getSimpleName());
5368            switch (message.what) {
5369                case CMD_START_SUPPLICANT:
5370                    if (mWifiNative.loadDriver()) {
5371                        try {
5372                            mNwService.wifiFirmwareReload(mInterfaceName, "STA");
5373                        } catch (Exception e) {
5374                            loge("Failed to reload STA firmware " + e);
5375                            // Continue
5376                        }
5377
5378                        try {
5379                            // A runtime crash can leave the interface up and
5380                            // IP addresses configured, and this affects
5381                            // connectivity when supplicant starts up.
5382                            // Ensure interface is down and we have no IP
5383                            // addresses before a supplicant start.
5384                            mNwService.setInterfaceDown(mInterfaceName);
5385                            mNwService.clearInterfaceAddresses(mInterfaceName);
5386
5387                            // Set privacy extensions
5388                            mNwService.setInterfaceIpv6PrivacyExtensions(mInterfaceName, true);
5389
5390                            // IPv6 is enabled only as long as access point is connected since:
5391                            // - IPv6 addresses and routes stick around after disconnection
5392                            // - kernel is unaware when connected and fails to start IPv6 negotiation
5393                            // - kernel can start autoconfiguration when 802.1x is not complete
5394                            mNwService.disableIpv6(mInterfaceName);
5395                        } catch (RemoteException re) {
5396                            loge("Unable to change interface settings: " + re);
5397                        } catch (IllegalStateException ie) {
5398                            loge("Unable to change interface settings: " + ie);
5399                        }
5400
5401                       /* Stop a running supplicant after a runtime restart
5402                        * Avoids issues with drivers that do not handle interface down
5403                        * on a running supplicant properly.
5404                        */
5405                        mWifiMonitor.killSupplicant(mP2pSupported);
5406
5407                        if (WifiNative.startHal() == false) {
5408                            /* starting HAL is optional */
5409                            loge("Failed to start HAL");
5410                        }
5411
5412                        if (mWifiNative.startSupplicant(mP2pSupported)) {
5413                            setWifiState(WIFI_STATE_ENABLING);
5414                            if (DBG) log("Supplicant start successful");
5415                            mWifiMonitor.startMonitoring();
5416                            transitionTo(mSupplicantStartingState);
5417                        } else {
5418                            loge("Failed to start supplicant!");
5419                        }
5420                    } else {
5421                        loge("Failed to load driver");
5422                    }
5423                    break;
5424                case CMD_START_AP:
5425                    if (mWifiNative.loadDriver() == false) {
5426                        loge("Failed to load driver for softap");
5427                    } else {
5428
5429                        if (WifiNative.startHal() == false) {
5430                            /* starting HAL is optional */
5431                            loge("Failed to start HAL");
5432                        }
5433
5434                        setWifiApState(WIFI_AP_STATE_ENABLING);
5435                        transitionTo(mSoftApStartingState);
5436                    }
5437                    break;
5438                default:
5439                    return NOT_HANDLED;
5440            }
5441            return HANDLED;
5442        }
5443    }
5444
5445    class SupplicantStartingState extends State {
5446        private void initializeWpsDetails() {
5447            String detail;
5448            detail = SystemProperties.get("ro.product.name", "");
5449            if (!mWifiNative.setDeviceName(detail)) {
5450                loge("Failed to set device name " +  detail);
5451            }
5452            detail = SystemProperties.get("ro.product.manufacturer", "");
5453            if (!mWifiNative.setManufacturer(detail)) {
5454                loge("Failed to set manufacturer " + detail);
5455            }
5456            detail = SystemProperties.get("ro.product.model", "");
5457            if (!mWifiNative.setModelName(detail)) {
5458                loge("Failed to set model name " + detail);
5459            }
5460            detail = SystemProperties.get("ro.product.model", "");
5461            if (!mWifiNative.setModelNumber(detail)) {
5462                loge("Failed to set model number " + detail);
5463            }
5464            detail = SystemProperties.get("ro.serialno", "");
5465            if (!mWifiNative.setSerialNumber(detail)) {
5466                loge("Failed to set serial number " + detail);
5467            }
5468            if (!mWifiNative.setConfigMethods("physical_display virtual_push_button")) {
5469                loge("Failed to set WPS config methods");
5470            }
5471            if (!mWifiNative.setDeviceType(mPrimaryDeviceType)) {
5472                loge("Failed to set primary device type " + mPrimaryDeviceType);
5473            }
5474        }
5475
5476        @Override
5477        public boolean processMessage(Message message) {
5478            logStateAndMessage(message, getClass().getSimpleName());
5479
5480            switch(message.what) {
5481                case WifiMonitor.SUP_CONNECTION_EVENT:
5482                    if (DBG) log("Supplicant connection established");
5483                    setWifiState(WIFI_STATE_ENABLED);
5484                    mSupplicantRestartCount = 0;
5485                    /* Reset the supplicant state to indicate the supplicant
5486                     * state is not known at this time */
5487                    mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE);
5488                    /* Initialize data structures */
5489                    mLastBssid = null;
5490                    mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID;
5491                    mLastSignalLevel = -1;
5492
5493                    mWifiInfo.setMacAddress(mWifiNative.getMacAddress());
5494                    mWifiNative.enableSaveConfig();
5495                    mWifiConfigStore.loadAndEnableAllNetworks();
5496                    if (mWifiConfigStore.enableVerboseLogging.get() > 0) {
5497                        enableVerboseLogging(mWifiConfigStore.enableVerboseLogging.get());
5498                    }
5499                    initializeWpsDetails();
5500
5501                    sendSupplicantConnectionChangedBroadcast(true);
5502                    transitionTo(mDriverStartedState);
5503                    break;
5504                case WifiMonitor.SUP_DISCONNECTION_EVENT:
5505                    if (++mSupplicantRestartCount <= SUPPLICANT_RESTART_TRIES) {
5506                        loge("Failed to setup control channel, restart supplicant");
5507                        mWifiMonitor.killSupplicant(mP2pSupported);
5508                        transitionTo(mInitialState);
5509                        sendMessageDelayed(CMD_START_SUPPLICANT, SUPPLICANT_RESTART_INTERVAL_MSECS);
5510                    } else {
5511                        loge("Failed " + mSupplicantRestartCount +
5512                                " times to start supplicant, unload driver");
5513                        mSupplicantRestartCount = 0;
5514                        setWifiState(WIFI_STATE_UNKNOWN);
5515                        transitionTo(mInitialState);
5516                    }
5517                    break;
5518                case CMD_START_SUPPLICANT:
5519                case CMD_STOP_SUPPLICANT:
5520                case CMD_START_AP:
5521                case CMD_STOP_AP:
5522                case CMD_START_DRIVER:
5523                case CMD_STOP_DRIVER:
5524                case CMD_SET_OPERATIONAL_MODE:
5525                case CMD_SET_COUNTRY_CODE:
5526                case CMD_SET_FREQUENCY_BAND:
5527                case CMD_START_PACKET_FILTERING:
5528                case CMD_STOP_PACKET_FILTERING:
5529                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
5530                    deferMessage(message);
5531                    break;
5532                default:
5533                    return NOT_HANDLED;
5534            }
5535            return HANDLED;
5536        }
5537    }
5538
5539    class SupplicantStartedState extends State {
5540        @Override
5541        public void enter() {
5542            /* Wifi is available as long as we have a connection to supplicant */
5543            mNetworkInfo.setIsAvailable(true);
5544            if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo);
5545
5546            int defaultInterval = mContext.getResources().getInteger(
5547                    R.integer.config_wifi_supplicant_scan_interval);
5548
5549            mSupplicantScanIntervalMs = Settings.Global.getLong(mContext.getContentResolver(),
5550                    Settings.Global.WIFI_SUPPLICANT_SCAN_INTERVAL_MS,
5551                    defaultInterval);
5552
5553            mWifiNative.setScanInterval((int)mSupplicantScanIntervalMs / 1000);
5554            mWifiNative.setExternalSim(true);
5555
5556            /* turn on use of DFS channels */
5557            WifiNative.setDfsFlag(true);
5558
5559            /* set country code */
5560            setCountryCode();
5561
5562            setRandomMacOui();
5563            mWifiNative.enableAutoConnect(false);
5564        }
5565
5566        @Override
5567        public boolean processMessage(Message message) {
5568            logStateAndMessage(message, getClass().getSimpleName());
5569
5570            switch(message.what) {
5571                case CMD_STOP_SUPPLICANT:   /* Supplicant stopped by user */
5572                    if (mP2pSupported) {
5573                        transitionTo(mWaitForP2pDisableState);
5574                    } else {
5575                        transitionTo(mSupplicantStoppingState);
5576                    }
5577                    break;
5578                case WifiMonitor.SUP_DISCONNECTION_EVENT:  /* Supplicant connection lost */
5579                    loge("Connection lost, restart supplicant");
5580                    handleSupplicantConnectionLoss(true);
5581                    handleNetworkDisconnect();
5582                    mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE);
5583                    if (mP2pSupported) {
5584                        transitionTo(mWaitForP2pDisableState);
5585                    } else {
5586                        transitionTo(mInitialState);
5587                    }
5588                    sendMessageDelayed(CMD_START_SUPPLICANT, SUPPLICANT_RESTART_INTERVAL_MSECS);
5589                    break;
5590                case WifiMonitor.SCAN_RESULTS_EVENT:
5591                case WifiMonitor.SCAN_FAILED_EVENT:
5592                    maybeRegisterNetworkFactory(); // Make sure our NetworkFactory is registered
5593                    closeRadioScanStats();
5594                    noteScanEnd();
5595                    setScanResults();
5596                    if (mIsFullScanOngoing || mSendScanResultsBroadcast) {
5597                        /* Just updated results from full scan, let apps know about this */
5598                        sendScanResultsAvailableBroadcast();
5599                    }
5600                    mSendScanResultsBroadcast = false;
5601                    mIsScanOngoing = false;
5602                    mIsFullScanOngoing = false;
5603                    if (mBufferedScanMsg.size() > 0)
5604                        sendMessage(mBufferedScanMsg.remove());
5605                    break;
5606                case CMD_PING_SUPPLICANT:
5607                    boolean ok = mWifiNative.ping();
5608                    replyToMessage(message, message.what, ok ? SUCCESS : FAILURE);
5609                    break;
5610                case CMD_GET_CAPABILITY_FREQ:
5611                    String freqs = mWifiNative.getFreqCapability();
5612                    replyToMessage(message, message.what, freqs);
5613                    break;
5614                case CMD_START_AP:
5615                    /* Cannot start soft AP while in client mode */
5616                    loge("Failed to start soft AP with a running supplicant");
5617                    setWifiApState(WIFI_AP_STATE_FAILED);
5618                    break;
5619                case CMD_SET_OPERATIONAL_MODE:
5620                    mOperationalMode = message.arg1;
5621                    mWifiConfigStore.
5622                            setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID);
5623                    break;
5624                case CMD_TARGET_BSSID:
5625                    // Trying to associate to this BSSID
5626                    if (message.obj != null) {
5627                        mTargetRoamBSSID = (String) message.obj;
5628                    }
5629                    break;
5630                case CMD_GET_LINK_LAYER_STATS:
5631                    WifiLinkLayerStats stats = getWifiLinkLayerStats(DBG);
5632                    if (stats == null) {
5633                        // When firmware doesnt support link layer stats, return an empty object
5634                        stats = new WifiLinkLayerStats();
5635                    }
5636                    replyToMessage(message, message.what, stats);
5637                    break;
5638                case CMD_SET_COUNTRY_CODE:
5639                    String country = (String) message.obj;
5640
5641                    final boolean persist = (message.arg2 == 1);
5642                    final int sequence = message.arg1;
5643
5644                    if (sequence != mCountryCodeSequence.get()) {
5645                        if (DBG) log("set country code ignored due to sequnce num");
5646                        break;
5647                    }
5648                    if (DBG) log("set country code " + country);
5649                    country = country.toUpperCase(Locale.ROOT);
5650
5651                    if (mDriverSetCountryCode == null || !mDriverSetCountryCode.equals(country)) {
5652                        if (mWifiNative.setCountryCode(country)) {
5653                            mDriverSetCountryCode = country;
5654                        } else {
5655                            loge("Failed to set country code " + country);
5656                        }
5657                    }
5658
5659                    mWifiP2pChannel.sendMessage(WifiP2pServiceImpl.SET_COUNTRY_CODE, country);
5660                    break;
5661                default:
5662                    return NOT_HANDLED;
5663            }
5664            return HANDLED;
5665        }
5666
5667        @Override
5668        public void exit() {
5669            mNetworkInfo.setIsAvailable(false);
5670            if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo);
5671        }
5672    }
5673
5674    class SupplicantStoppingState extends State {
5675        @Override
5676        public void enter() {
5677            /* Send any reset commands to supplicant before shutting it down */
5678            handleNetworkDisconnect();
5679            if (mDhcpStateMachine != null) {
5680                mDhcpStateMachine.doQuit();
5681            }
5682
5683            String suppState = System.getProperty("init.svc.wpa_supplicant");
5684            if (suppState == null) suppState = "unknown";
5685            String p2pSuppState = System.getProperty("init.svc.p2p_supplicant");
5686            if (p2pSuppState == null) p2pSuppState = "unknown";
5687
5688            loge("SupplicantStoppingState: stopSupplicant "
5689                    + " init.svc.wpa_supplicant=" + suppState
5690                    + " init.svc.p2p_supplicant=" + p2pSuppState);
5691            mWifiMonitor.stopSupplicant();
5692
5693            /* Send ourselves a delayed message to indicate failure after a wait time */
5694            sendMessageDelayed(obtainMessage(CMD_STOP_SUPPLICANT_FAILED,
5695                    ++mSupplicantStopFailureToken, 0), SUPPLICANT_RESTART_INTERVAL_MSECS);
5696            setWifiState(WIFI_STATE_DISABLING);
5697            mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE);
5698        }
5699        @Override
5700        public boolean processMessage(Message message) {
5701            logStateAndMessage(message, getClass().getSimpleName());
5702
5703            switch(message.what) {
5704                case WifiMonitor.SUP_CONNECTION_EVENT:
5705                    loge("Supplicant connection received while stopping");
5706                    break;
5707                case WifiMonitor.SUP_DISCONNECTION_EVENT:
5708                    if (DBG) log("Supplicant connection lost");
5709                    handleSupplicantConnectionLoss(false);
5710                    transitionTo(mInitialState);
5711                    break;
5712                case CMD_STOP_SUPPLICANT_FAILED:
5713                    if (message.arg1 == mSupplicantStopFailureToken) {
5714                        loge("Timed out on a supplicant stop, kill and proceed");
5715                        handleSupplicantConnectionLoss(true);
5716                        transitionTo(mInitialState);
5717                    }
5718                    break;
5719                case CMD_START_SUPPLICANT:
5720                case CMD_STOP_SUPPLICANT:
5721                case CMD_START_AP:
5722                case CMD_STOP_AP:
5723                case CMD_START_DRIVER:
5724                case CMD_STOP_DRIVER:
5725                case CMD_SET_OPERATIONAL_MODE:
5726                case CMD_SET_COUNTRY_CODE:
5727                case CMD_SET_FREQUENCY_BAND:
5728                case CMD_START_PACKET_FILTERING:
5729                case CMD_STOP_PACKET_FILTERING:
5730                    deferMessage(message);
5731                    break;
5732                default:
5733                    return NOT_HANDLED;
5734            }
5735            return HANDLED;
5736        }
5737    }
5738
5739    class DriverStartingState extends State {
5740        private int mTries;
5741        @Override
5742        public void enter() {
5743            mTries = 1;
5744            /* Send ourselves a delayed message to start driver a second time */
5745            sendMessageDelayed(obtainMessage(CMD_DRIVER_START_TIMED_OUT,
5746                        ++mDriverStartToken, 0), DRIVER_START_TIME_OUT_MSECS);
5747        }
5748        @Override
5749        public boolean processMessage(Message message) {
5750            logStateAndMessage(message, getClass().getSimpleName());
5751
5752            switch(message.what) {
5753               case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
5754                    SupplicantState state = handleSupplicantStateChange(message);
5755                    /* If suplicant is exiting out of INTERFACE_DISABLED state into
5756                     * a state that indicates driver has started, it is ready to
5757                     * receive driver commands
5758                     */
5759                    if (SupplicantState.isDriverActive(state)) {
5760                        transitionTo(mDriverStartedState);
5761                    }
5762                    break;
5763                case CMD_DRIVER_START_TIMED_OUT:
5764                    if (message.arg1 == mDriverStartToken) {
5765                        if (mTries >= 2) {
5766                            loge("Failed to start driver after " + mTries);
5767                            transitionTo(mDriverStoppedState);
5768                        } else {
5769                            loge("Driver start failed, retrying");
5770                            mWakeLock.acquire();
5771                            mWifiNative.startDriver();
5772                            mWakeLock.release();
5773
5774                            ++mTries;
5775                            /* Send ourselves a delayed message to start driver again */
5776                            sendMessageDelayed(obtainMessage(CMD_DRIVER_START_TIMED_OUT,
5777                                        ++mDriverStartToken, 0), DRIVER_START_TIME_OUT_MSECS);
5778                        }
5779                    }
5780                    break;
5781                    /* Queue driver commands & connection events */
5782                case CMD_START_DRIVER:
5783                case CMD_STOP_DRIVER:
5784                case WifiMonitor.NETWORK_CONNECTION_EVENT:
5785                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
5786                case WifiMonitor.AUTHENTICATION_FAILURE_EVENT:
5787                case WifiMonitor.ASSOCIATION_REJECTION_EVENT:
5788                case WifiMonitor.WPS_OVERLAP_EVENT:
5789                case CMD_SET_COUNTRY_CODE:
5790                case CMD_SET_FREQUENCY_BAND:
5791                case CMD_START_PACKET_FILTERING:
5792                case CMD_STOP_PACKET_FILTERING:
5793                case CMD_START_SCAN:
5794                case CMD_DISCONNECT:
5795                case CMD_REASSOCIATE:
5796                case CMD_RECONNECT:
5797                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
5798                    deferMessage(message);
5799                    break;
5800                case WifiMonitor.SCAN_RESULTS_EVENT:
5801                case WifiMonitor.SCAN_FAILED_EVENT:
5802                    // Loose scan results obtained in Driver Starting state, they can only confuse
5803                    // the state machine
5804                    break;
5805                default:
5806                    return NOT_HANDLED;
5807            }
5808            return HANDLED;
5809        }
5810    }
5811
5812    class DriverStartedState extends State {
5813        @Override
5814        public void enter() {
5815
5816            if (PDBG) {
5817                loge("DriverStartedState enter");
5818            }
5819
5820            mWifiLogger.startLogging(mVerboseLoggingLevel > 0);
5821            mIsRunning = true;
5822            mInDelayedStop = false;
5823            mDelayedStopCounter++;
5824            updateBatteryWorkSource(null);
5825            /**
5826             * Enable bluetooth coexistence scan mode when bluetooth connection is active.
5827             * When this mode is on, some of the low-level scan parameters used by the
5828             * driver are changed to reduce interference with bluetooth
5829             */
5830            mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive);
5831            /* set frequency band of operation */
5832            setFrequencyBand();
5833            /* initialize network state */
5834            setNetworkDetailedState(DetailedState.DISCONNECTED);
5835
5836            /* Remove any filtering on Multicast v6 at start */
5837            mWifiNative.stopFilteringMulticastV6Packets();
5838
5839            /* Reset Multicast v4 filtering state */
5840            if (mFilteringMulticastV4Packets.get()) {
5841                mWifiNative.startFilteringMulticastV4Packets();
5842            } else {
5843                mWifiNative.stopFilteringMulticastV4Packets();
5844            }
5845
5846            mDhcpActive = false;
5847
5848            if (mOperationalMode != CONNECT_MODE) {
5849                mWifiNative.disconnect();
5850                mWifiConfigStore.disableAllNetworks();
5851                if (mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) {
5852                    setWifiState(WIFI_STATE_DISABLED);
5853                }
5854                transitionTo(mScanModeState);
5855            } else {
5856
5857                // Status pulls in the current supplicant state and network connection state
5858                // events over the monitor connection. This helps framework sync up with
5859                // current supplicant state
5860                // TODO: actually check th supplicant status string and make sure the supplicant
5861                // is in disconnecte4d state.
5862                mWifiNative.status();
5863                // Transitioning to Disconnected state will trigger a scan and subsequently AutoJoin
5864                transitionTo(mDisconnectedState);
5865                transitionTo(mDisconnectedState);
5866            }
5867
5868            // We may have missed screen update at boot
5869            if (mScreenBroadcastReceived.get() == false) {
5870                PowerManager powerManager = (PowerManager)mContext.getSystemService(
5871                        Context.POWER_SERVICE);
5872                handleScreenStateChanged(powerManager.isScreenOn());
5873            } else {
5874                // Set the right suspend mode settings
5875                mWifiNative.setSuspendOptimizations(mSuspendOptNeedsDisabled == 0
5876                        && mUserWantsSuspendOpt.get());
5877            }
5878            mWifiNative.setPowerSave(true);
5879
5880            if (mP2pSupported) {
5881                if (mOperationalMode == CONNECT_MODE) {
5882                    mWifiP2pChannel.sendMessage(WifiStateMachine.CMD_ENABLE_P2P);
5883                } else {
5884                    // P2P statemachine starts in disabled state, and is not enabled until
5885                    // CMD_ENABLE_P2P is sent from here; so, nothing needs to be done to
5886                    // keep it disabled.
5887                }
5888            }
5889
5890            final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE);
5891            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
5892            intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_ENABLED);
5893            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
5894
5895            mHalFeatureSet = WifiNative.getSupportedFeatureSet();
5896            if ((mHalFeatureSet & WifiManager.WIFI_FEATURE_HAL_EPNO)
5897                    == WifiManager.WIFI_FEATURE_HAL_EPNO) {
5898                mHalBasedPnoDriverSupported = true;
5899            }
5900
5901            // Enable link layer stats gathering
5902            mWifiNative.setWifiLinkLayerStats("wlan0", 1);
5903
5904            if (PDBG) {
5905                loge("Driverstarted State enter done, epno=" + mHalBasedPnoDriverSupported
5906                     + " feature=" + mHalFeatureSet);
5907            }
5908        }
5909
5910        @Override
5911        public boolean processMessage(Message message) {
5912            logStateAndMessage(message, getClass().getSimpleName());
5913
5914            switch(message.what) {
5915                case CMD_START_SCAN:
5916                    handleScanRequest(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message);
5917                    break;
5918                case CMD_SET_FREQUENCY_BAND:
5919                    int band =  message.arg1;
5920                    if (DBG) log("set frequency band " + band);
5921                    if (mWifiNative.setBand(band)) {
5922
5923                        if (PDBG)  loge("did set frequency band " + band);
5924
5925                        mFrequencyBand.set(band);
5926                        // Flush old data - like scan results
5927                        mWifiNative.bssFlush();
5928                        // Fetch the latest scan results when frequency band is set
5929//                        startScanNative(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, null);
5930
5931                        if (PDBG)  loge("done set frequency band " + band);
5932
5933                    } else {
5934                        loge("Failed to set frequency band " + band);
5935                    }
5936                    break;
5937                case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE:
5938                    mBluetoothConnectionActive = (message.arg1 !=
5939                            BluetoothAdapter.STATE_DISCONNECTED);
5940                    mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive);
5941                    break;
5942                case CMD_STOP_DRIVER:
5943                    int mode = message.arg1;
5944
5945                    /* Already doing a delayed stop */
5946                    if (mInDelayedStop) {
5947                        if (DBG) log("Already in delayed stop");
5948                        break;
5949                    }
5950                    /* disconnect right now, but leave the driver running for a bit */
5951                    mWifiConfigStore.disableAllNetworks();
5952
5953                    mInDelayedStop = true;
5954                    mDelayedStopCounter++;
5955                    if (DBG) log("Delayed stop message " + mDelayedStopCounter);
5956
5957                    /* send regular delayed shut down */
5958                    Intent driverStopIntent = new Intent(ACTION_DELAYED_DRIVER_STOP, null);
5959                    driverStopIntent.setPackage(this.getClass().getPackage().getName());
5960                    driverStopIntent.putExtra(DELAYED_STOP_COUNTER, mDelayedStopCounter);
5961                    mDriverStopIntent = PendingIntent.getBroadcast(mContext,
5962                            DRIVER_STOP_REQUEST, driverStopIntent,
5963                            PendingIntent.FLAG_UPDATE_CURRENT);
5964
5965                    mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
5966                            + mDriverStopDelayMs, mDriverStopIntent);
5967                    break;
5968                case CMD_START_DRIVER:
5969                    if (mInDelayedStop) {
5970                        mInDelayedStop = false;
5971                        mDelayedStopCounter++;
5972                        mAlarmManager.cancel(mDriverStopIntent);
5973                        if (DBG) log("Delayed stop ignored due to start");
5974                        if (mOperationalMode == CONNECT_MODE) {
5975                            mWifiConfigStore.enableAllNetworks();
5976                        }
5977                    }
5978                    break;
5979                case CMD_DELAYED_STOP_DRIVER:
5980                    if (DBG) log("delayed stop " + message.arg1 + " " + mDelayedStopCounter);
5981                    if (message.arg1 != mDelayedStopCounter) break;
5982                    if (getCurrentState() != mDisconnectedState) {
5983                        mWifiNative.disconnect();
5984                        handleNetworkDisconnect();
5985                    }
5986                    mWakeLock.acquire();
5987                    mWifiNative.stopDriver();
5988                    mWakeLock.release();
5989                    if (mP2pSupported) {
5990                        transitionTo(mWaitForP2pDisableState);
5991                    } else {
5992                        transitionTo(mDriverStoppingState);
5993                    }
5994                    break;
5995                case CMD_START_PACKET_FILTERING:
5996                    if (message.arg1 == MULTICAST_V6) {
5997                        mWifiNative.startFilteringMulticastV6Packets();
5998                    } else if (message.arg1 == MULTICAST_V4) {
5999                        mWifiNative.startFilteringMulticastV4Packets();
6000                    } else {
6001                        loge("Illegal arugments to CMD_START_PACKET_FILTERING");
6002                    }
6003                    break;
6004                case CMD_STOP_PACKET_FILTERING:
6005                    if (message.arg1 == MULTICAST_V6) {
6006                        mWifiNative.stopFilteringMulticastV6Packets();
6007                    } else if (message.arg1 == MULTICAST_V4) {
6008                        mWifiNative.stopFilteringMulticastV4Packets();
6009                    } else {
6010                        loge("Illegal arugments to CMD_STOP_PACKET_FILTERING");
6011                    }
6012                    break;
6013                case CMD_SET_SUSPEND_OPT_ENABLED:
6014                    if (message.arg1 == 1) {
6015                        setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, true);
6016                        mSuspendWakeLock.release();
6017                    } else {
6018                        setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, false);
6019                    }
6020                    break;
6021                case CMD_SET_HIGH_PERF_MODE:
6022                    if (message.arg1 == 1) {
6023                        setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, false);
6024                    } else {
6025                        setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, true);
6026                    }
6027                    break;
6028                case CMD_ENABLE_TDLS:
6029                    if (message.obj != null) {
6030                        String remoteAddress = (String) message.obj;
6031                        boolean enable = (message.arg1 == 1);
6032                        mWifiNative.startTdls(remoteAddress, enable);
6033                    }
6034                    break;
6035                case WifiMonitor.ANQP_DONE_EVENT:
6036                    mWifiConfigStore.notifyANQPDone((Long) message.obj, message.arg1 != 0);
6037                    break;
6038                default:
6039                    return NOT_HANDLED;
6040            }
6041            return HANDLED;
6042        }
6043        @Override
6044        public void exit() {
6045
6046            mWifiLogger.stopLogging();
6047
6048            mIsRunning = false;
6049            updateBatteryWorkSource(null);
6050            mScanResults = new ArrayList<>();
6051
6052            final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE);
6053            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
6054            intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED);
6055            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
6056            noteScanEnd(); // wrap up any pending request.
6057            mBufferedScanMsg.clear();
6058        }
6059    }
6060
6061    class WaitForP2pDisableState extends State {
6062        private State mTransitionToState;
6063        @Override
6064        public void enter() {
6065            switch (getCurrentMessage().what) {
6066                case WifiMonitor.SUP_DISCONNECTION_EVENT:
6067                    mTransitionToState = mInitialState;
6068                    break;
6069                case CMD_DELAYED_STOP_DRIVER:
6070                    mTransitionToState = mDriverStoppingState;
6071                    break;
6072                case CMD_STOP_SUPPLICANT:
6073                    mTransitionToState = mSupplicantStoppingState;
6074                    break;
6075                default:
6076                    mTransitionToState = mDriverStoppingState;
6077                    break;
6078            }
6079            mWifiP2pChannel.sendMessage(WifiStateMachine.CMD_DISABLE_P2P_REQ);
6080        }
6081        @Override
6082        public boolean processMessage(Message message) {
6083            logStateAndMessage(message, getClass().getSimpleName());
6084
6085            switch(message.what) {
6086                case WifiStateMachine.CMD_DISABLE_P2P_RSP:
6087                    transitionTo(mTransitionToState);
6088                    break;
6089                /* Defer wifi start/shut and driver commands */
6090                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
6091                case CMD_START_SUPPLICANT:
6092                case CMD_STOP_SUPPLICANT:
6093                case CMD_START_AP:
6094                case CMD_STOP_AP:
6095                case CMD_START_DRIVER:
6096                case CMD_STOP_DRIVER:
6097                case CMD_SET_OPERATIONAL_MODE:
6098                case CMD_SET_COUNTRY_CODE:
6099                case CMD_SET_FREQUENCY_BAND:
6100                case CMD_START_PACKET_FILTERING:
6101                case CMD_STOP_PACKET_FILTERING:
6102                case CMD_START_SCAN:
6103                case CMD_DISCONNECT:
6104                case CMD_REASSOCIATE:
6105                case CMD_RECONNECT:
6106                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
6107                    deferMessage(message);
6108                    break;
6109                default:
6110                    return NOT_HANDLED;
6111            }
6112            return HANDLED;
6113        }
6114    }
6115
6116    class DriverStoppingState extends State {
6117        @Override
6118        public boolean processMessage(Message message) {
6119            logStateAndMessage(message, getClass().getSimpleName());
6120
6121            switch(message.what) {
6122                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
6123                    SupplicantState state = handleSupplicantStateChange(message);
6124                    if (state == SupplicantState.INTERFACE_DISABLED) {
6125                        transitionTo(mDriverStoppedState);
6126                    }
6127                    break;
6128                    /* Queue driver commands */
6129                case CMD_START_DRIVER:
6130                case CMD_STOP_DRIVER:
6131                case CMD_SET_COUNTRY_CODE:
6132                case CMD_SET_FREQUENCY_BAND:
6133                case CMD_START_PACKET_FILTERING:
6134                case CMD_STOP_PACKET_FILTERING:
6135                case CMD_START_SCAN:
6136                case CMD_DISCONNECT:
6137                case CMD_REASSOCIATE:
6138                case CMD_RECONNECT:
6139                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
6140                    deferMessage(message);
6141                    break;
6142                default:
6143                    return NOT_HANDLED;
6144            }
6145            return HANDLED;
6146        }
6147    }
6148
6149    class DriverStoppedState extends State {
6150        @Override
6151        public boolean processMessage(Message message) {
6152            logStateAndMessage(message, getClass().getSimpleName());
6153            switch (message.what) {
6154                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
6155                    StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
6156                    SupplicantState state = stateChangeResult.state;
6157                    // A WEXT bug means that we can be back to driver started state
6158                    // unexpectedly
6159                    if (SupplicantState.isDriverActive(state)) {
6160                        transitionTo(mDriverStartedState);
6161                    }
6162                    break;
6163                case CMD_START_DRIVER:
6164                    mWakeLock.acquire();
6165                    mWifiNative.startDriver();
6166                    mWakeLock.release();
6167                    transitionTo(mDriverStartingState);
6168                    break;
6169                default:
6170                    return NOT_HANDLED;
6171            }
6172            return HANDLED;
6173        }
6174    }
6175
6176    class ScanModeState extends State {
6177        private int mLastOperationMode;
6178        @Override
6179        public void enter() {
6180            mLastOperationMode = mOperationalMode;
6181        }
6182        @Override
6183        public boolean processMessage(Message message) {
6184            logStateAndMessage(message, getClass().getSimpleName());
6185
6186            switch(message.what) {
6187                case CMD_SET_OPERATIONAL_MODE:
6188                    if (message.arg1 == CONNECT_MODE) {
6189
6190                        if (mLastOperationMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) {
6191                            setWifiState(WIFI_STATE_ENABLED);
6192                            // Load and re-enable networks when going back to enabled state
6193                            // This is essential for networks to show up after restore
6194                            mWifiConfigStore.loadAndEnableAllNetworks();
6195                            mWifiP2pChannel.sendMessage(CMD_ENABLE_P2P);
6196                        } else {
6197                            mWifiConfigStore.enableAllNetworks();
6198                        }
6199
6200                        // Try autojoining with recent network already present in the cache
6201                        // If none are found then trigger a scan which will trigger autojoin
6202                        // upon reception of scan results event
6203                        if (!mWifiAutoJoinController.attemptAutoJoin()) {
6204                            startScan(ENABLE_WIFI, 0, null, null);
6205                        }
6206
6207                        // Loose last selection choice since user toggled WiFi
6208                        mWifiConfigStore.
6209                                setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID);
6210
6211                        mOperationalMode = CONNECT_MODE;
6212                        transitionTo(mDisconnectedState);
6213                    } else {
6214                        // Nothing to do
6215                        return HANDLED;
6216                    }
6217                    break;
6218                // Handle scan. All the connection related commands are
6219                // handled only in ConnectModeState
6220                case CMD_START_SCAN:
6221                    handleScanRequest(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message);
6222                    break;
6223                default:
6224                    return NOT_HANDLED;
6225            }
6226            return HANDLED;
6227        }
6228    }
6229
6230
6231    String smToString(Message message) {
6232        return smToString(message.what);
6233    }
6234
6235    String smToString(int what) {
6236        String s = "unknown";
6237        switch (what) {
6238            case WifiMonitor.DRIVER_HUNG_EVENT:
6239                s = "DRIVER_HUNG_EVENT";
6240                break;
6241            case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
6242                s = "AsyncChannel.CMD_CHANNEL_HALF_CONNECTED";
6243                break;
6244            case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
6245                s = "AsyncChannel.CMD_CHANNEL_DISCONNECTED";
6246                break;
6247            case CMD_SET_FREQUENCY_BAND:
6248                s = "CMD_SET_FREQUENCY_BAND";
6249                break;
6250            case CMD_DELAYED_NETWORK_DISCONNECT:
6251                s = "CMD_DELAYED_NETWORK_DISCONNECT";
6252                break;
6253            case CMD_TEST_NETWORK_DISCONNECT:
6254                s = "CMD_TEST_NETWORK_DISCONNECT";
6255                break;
6256            case CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER:
6257                s = "CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER";
6258                break;
6259            case CMD_DISABLE_EPHEMERAL_NETWORK:
6260                s = "CMD_DISABLE_EPHEMERAL_NETWORK";
6261                break;
6262            case CMD_START_DRIVER:
6263                s = "CMD_START_DRIVER";
6264                break;
6265            case CMD_STOP_DRIVER:
6266                s = "CMD_STOP_DRIVER";
6267                break;
6268            case CMD_STOP_SUPPLICANT:
6269                s = "CMD_STOP_SUPPLICANT";
6270                break;
6271            case CMD_STOP_SUPPLICANT_FAILED:
6272                s = "CMD_STOP_SUPPLICANT_FAILED";
6273                break;
6274            case CMD_START_SUPPLICANT:
6275                s = "CMD_START_SUPPLICANT";
6276                break;
6277            case CMD_REQUEST_AP_CONFIG:
6278                s = "CMD_REQUEST_AP_CONFIG";
6279                break;
6280            case CMD_RESPONSE_AP_CONFIG:
6281                s = "CMD_RESPONSE_AP_CONFIG";
6282                break;
6283            case CMD_TETHER_STATE_CHANGE:
6284                s = "CMD_TETHER_STATE_CHANGE";
6285                break;
6286            case CMD_TETHER_NOTIFICATION_TIMED_OUT:
6287                s = "CMD_TETHER_NOTIFICATION_TIMED_OUT";
6288                break;
6289            case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE:
6290                s = "CMD_BLUETOOTH_ADAPTER_STATE_CHANGE";
6291                break;
6292            case CMD_ADD_OR_UPDATE_NETWORK:
6293                s = "CMD_ADD_OR_UPDATE_NETWORK";
6294                break;
6295            case CMD_REMOVE_NETWORK:
6296                s = "CMD_REMOVE_NETWORK";
6297                break;
6298            case CMD_ENABLE_NETWORK:
6299                s = "CMD_ENABLE_NETWORK";
6300                break;
6301            case CMD_ENABLE_ALL_NETWORKS:
6302                s = "CMD_ENABLE_ALL_NETWORKS";
6303                break;
6304            case CMD_AUTO_CONNECT:
6305                s = "CMD_AUTO_CONNECT";
6306                break;
6307            case CMD_AUTO_ROAM:
6308                s = "CMD_AUTO_ROAM";
6309                break;
6310            case CMD_AUTO_SAVE_NETWORK:
6311                s = "CMD_AUTO_SAVE_NETWORK";
6312                break;
6313            case CMD_BOOT_COMPLETED:
6314                s = "CMD_BOOT_COMPLETED";
6315                break;
6316            case DhcpStateMachine.CMD_START_DHCP:
6317                s = "CMD_START_DHCP";
6318                break;
6319            case DhcpStateMachine.CMD_STOP_DHCP:
6320                s = "CMD_STOP_DHCP";
6321                break;
6322            case DhcpStateMachine.CMD_RENEW_DHCP:
6323                s = "CMD_RENEW_DHCP";
6324                break;
6325            case DhcpStateMachine.CMD_PRE_DHCP_ACTION:
6326                s = "CMD_PRE_DHCP_ACTION";
6327                break;
6328            case DhcpStateMachine.CMD_POST_DHCP_ACTION:
6329                s = "CMD_POST_DHCP_ACTION";
6330                break;
6331            case DhcpStateMachine.CMD_PRE_DHCP_ACTION_COMPLETE:
6332                s = "CMD_PRE_DHCP_ACTION_COMPLETE";
6333                break;
6334            case DhcpStateMachine.CMD_ON_QUIT:
6335                s = "CMD_ON_QUIT";
6336                break;
6337            case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST:
6338                s = "WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST";
6339                break;
6340            case WifiManager.DISABLE_NETWORK:
6341                s = "WifiManager.DISABLE_NETWORK";
6342                break;
6343            case CMD_BLACKLIST_NETWORK:
6344                s = "CMD_BLACKLIST_NETWORK";
6345                break;
6346            case CMD_CLEAR_BLACKLIST:
6347                s = "CMD_CLEAR_BLACKLIST";
6348                break;
6349            case CMD_SAVE_CONFIG:
6350                s = "CMD_SAVE_CONFIG";
6351                break;
6352            case CMD_GET_CONFIGURED_NETWORKS:
6353                s = "CMD_GET_CONFIGURED_NETWORKS";
6354                break;
6355            case CMD_GET_SUPPORTED_FEATURES:
6356                s = "CMD_GET_SUPPORTED_FEATURES";
6357                break;
6358            case CMD_UNWANTED_NETWORK:
6359                s = "CMD_UNWANTED_NETWORK";
6360                break;
6361            case CMD_NETWORK_STATUS:
6362                s = "CMD_NETWORK_STATUS";
6363                break;
6364            case CMD_GET_LINK_LAYER_STATS:
6365                s = "CMD_GET_LINK_LAYER_STATS";
6366                break;
6367            case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS:
6368                s = "CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS";
6369                break;
6370            case CMD_DISCONNECT:
6371                s = "CMD_DISCONNECT";
6372                break;
6373            case CMD_RECONNECT:
6374                s = "CMD_RECONNECT";
6375                break;
6376            case CMD_REASSOCIATE:
6377                s = "CMD_REASSOCIATE";
6378                break;
6379            case CMD_GET_CONNECTION_STATISTICS:
6380                s = "CMD_GET_CONNECTION_STATISTICS";
6381                break;
6382            case CMD_SET_HIGH_PERF_MODE:
6383                s = "CMD_SET_HIGH_PERF_MODE";
6384                break;
6385            case CMD_SET_COUNTRY_CODE:
6386                s = "CMD_SET_COUNTRY_CODE";
6387                break;
6388            case CMD_ENABLE_RSSI_POLL:
6389                s = "CMD_ENABLE_RSSI_POLL";
6390                break;
6391            case CMD_RSSI_POLL:
6392                s = "CMD_RSSI_POLL";
6393                break;
6394            case CMD_START_PACKET_FILTERING:
6395                s = "CMD_START_PACKET_FILTERING";
6396                break;
6397            case CMD_STOP_PACKET_FILTERING:
6398                s = "CMD_STOP_PACKET_FILTERING";
6399                break;
6400            case CMD_SET_SUSPEND_OPT_ENABLED:
6401                s = "CMD_SET_SUSPEND_OPT_ENABLED";
6402                break;
6403            case CMD_NO_NETWORKS_PERIODIC_SCAN:
6404                s = "CMD_NO_NETWORKS_PERIODIC_SCAN";
6405                break;
6406            case CMD_UPDATE_LINKPROPERTIES:
6407                s = "CMD_UPDATE_LINKPROPERTIES";
6408                break;
6409            case CMD_RELOAD_TLS_AND_RECONNECT:
6410                s = "CMD_RELOAD_TLS_AND_RECONNECT";
6411                break;
6412            case WifiManager.CONNECT_NETWORK:
6413                s = "CONNECT_NETWORK";
6414                break;
6415            case WifiManager.SAVE_NETWORK:
6416                s = "SAVE_NETWORK";
6417                break;
6418            case WifiManager.FORGET_NETWORK:
6419                s = "FORGET_NETWORK";
6420                break;
6421            case WifiMonitor.SUP_CONNECTION_EVENT:
6422                s = "SUP_CONNECTION_EVENT";
6423                break;
6424            case WifiMonitor.SUP_DISCONNECTION_EVENT:
6425                s = "SUP_DISCONNECTION_EVENT";
6426                break;
6427            case WifiMonitor.SCAN_RESULTS_EVENT:
6428                s = "SCAN_RESULTS_EVENT";
6429                break;
6430            case WifiMonitor.SCAN_FAILED_EVENT:
6431                s = "SCAN_FAILED_EVENT";
6432                break;
6433            case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
6434                s = "SUPPLICANT_STATE_CHANGE_EVENT";
6435                break;
6436            case WifiMonitor.AUTHENTICATION_FAILURE_EVENT:
6437                s = "AUTHENTICATION_FAILURE_EVENT";
6438                break;
6439            case WifiMonitor.SSID_TEMP_DISABLED:
6440                s = "SSID_TEMP_DISABLED";
6441                break;
6442            case WifiMonitor.SSID_REENABLED:
6443                s = "SSID_REENABLED";
6444                break;
6445            case WifiMonitor.WPS_SUCCESS_EVENT:
6446                s = "WPS_SUCCESS_EVENT";
6447                break;
6448            case WifiMonitor.WPS_FAIL_EVENT:
6449                s = "WPS_FAIL_EVENT";
6450                break;
6451            case WifiMonitor.SUP_REQUEST_IDENTITY:
6452                s = "SUP_REQUEST_IDENTITY";
6453                break;
6454            case WifiMonitor.NETWORK_CONNECTION_EVENT:
6455                s = "NETWORK_CONNECTION_EVENT";
6456                break;
6457            case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
6458                s = "NETWORK_DISCONNECTION_EVENT";
6459                break;
6460            case WifiMonitor.ASSOCIATION_REJECTION_EVENT:
6461                s = "ASSOCIATION_REJECTION_EVENT";
6462                break;
6463            case CMD_SET_OPERATIONAL_MODE:
6464                s = "CMD_SET_OPERATIONAL_MODE";
6465                break;
6466            case CMD_START_SCAN:
6467                s = "CMD_START_SCAN";
6468                break;
6469            case CMD_DISABLE_P2P_RSP:
6470                s = "CMD_DISABLE_P2P_RSP";
6471                break;
6472            case CMD_DISABLE_P2P_REQ:
6473                s = "CMD_DISABLE_P2P_REQ";
6474                break;
6475            case WifiWatchdogStateMachine.GOOD_LINK_DETECTED:
6476                s = "GOOD_LINK_DETECTED";
6477                break;
6478            case WifiWatchdogStateMachine.POOR_LINK_DETECTED:
6479                s = "POOR_LINK_DETECTED";
6480                break;
6481            case WifiP2pServiceImpl.GROUP_CREATING_TIMED_OUT:
6482                s = "GROUP_CREATING_TIMED_OUT";
6483                break;
6484            case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED:
6485                s = "P2P_CONNECTION_CHANGED";
6486                break;
6487            case WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE:
6488                s = "P2P.DISCONNECT_WIFI_RESPONSE";
6489                break;
6490            case WifiP2pServiceImpl.SET_MIRACAST_MODE:
6491                s = "P2P.SET_MIRACAST_MODE";
6492                break;
6493            case WifiP2pServiceImpl.BLOCK_DISCOVERY:
6494                s = "P2P.BLOCK_DISCOVERY";
6495                break;
6496            case WifiP2pServiceImpl.SET_COUNTRY_CODE:
6497                s = "P2P.SET_COUNTRY_CODE";
6498                break;
6499            case WifiManager.CANCEL_WPS:
6500                s = "CANCEL_WPS";
6501                break;
6502            case WifiManager.CANCEL_WPS_FAILED:
6503                s = "CANCEL_WPS_FAILED";
6504                break;
6505            case WifiManager.CANCEL_WPS_SUCCEDED:
6506                s = "CANCEL_WPS_SUCCEDED";
6507                break;
6508            case WifiManager.START_WPS:
6509                s = "START_WPS";
6510                break;
6511            case WifiManager.START_WPS_SUCCEEDED:
6512                s = "START_WPS_SUCCEEDED";
6513                break;
6514            case WifiManager.WPS_FAILED:
6515                s = "WPS_FAILED";
6516                break;
6517            case WifiManager.WPS_COMPLETED:
6518                s = "WPS_COMPLETED";
6519                break;
6520            case WifiManager.RSSI_PKTCNT_FETCH:
6521                s = "RSSI_PKTCNT_FETCH";
6522                break;
6523            case CMD_IP_CONFIGURATION_LOST:
6524                s = "CMD_IP_CONFIGURATION_LOST";
6525                break;
6526            case CMD_IP_CONFIGURATION_SUCCESSFUL:
6527                s = "CMD_IP_CONFIGURATION_SUCCESSFUL";
6528                break;
6529            case CMD_STATIC_IP_SUCCESS:
6530                s = "CMD_STATIC_IP_SUCCESSFUL";
6531                break;
6532            case CMD_STATIC_IP_FAILURE:
6533                s = "CMD_STATIC_IP_FAILURE";
6534                break;
6535            case DhcpStateMachine.DHCP_SUCCESS:
6536                s = "DHCP_SUCCESS";
6537                break;
6538            case DhcpStateMachine.DHCP_FAILURE:
6539                s = "DHCP_FAILURE";
6540                break;
6541            case CMD_TARGET_BSSID:
6542                s = "CMD_TARGET_BSSID";
6543                break;
6544            case CMD_ASSOCIATED_BSSID:
6545                s = "CMD_ASSOCIATED_BSSID";
6546                break;
6547            case CMD_ROAM_WATCHDOG_TIMER:
6548                s = "CMD_ROAM_WATCHDOG_TIMER";
6549                break;
6550            case CMD_SCREEN_STATE_CHANGED:
6551                s = "CMD_SCREEN_STATE_CHANGED";
6552                break;
6553            case CMD_DISCONNECTING_WATCHDOG_TIMER:
6554                s = "CMD_DISCONNECTING_WATCHDOG_TIMER";
6555                break;
6556            case CMD_RESTART_AUTOJOIN_OFFLOAD:
6557                s = "CMD_RESTART_AUTOJOIN_OFFLOAD";
6558                break;
6559            case CMD_STARTED_PNO_DBG:
6560                s = "CMD_STARTED_PNO_DBG";
6561                break;
6562            case CMD_STARTED_GSCAN_DBG:
6563                s = "CMD_STARTED_GSCAN_DBG";
6564                break;
6565            case CMD_PNO_NETWORK_FOUND:
6566                s = "CMD_PNO_NETWORK_FOUND";
6567                break;
6568            case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION:
6569                s = "CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION";
6570                break;
6571            default:
6572                s = "what:" + Integer.toString(what);
6573                break;
6574        }
6575        return s;
6576    }
6577
6578    void registerConnected() {
6579       if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) {
6580           long now_ms = System.currentTimeMillis();
6581           // We are switching away from this configuration,
6582           // hence record the time we were connected last
6583           WifiConfiguration config = mWifiConfigStore.getWifiConfiguration(mLastNetworkId);
6584           if (config != null) {
6585               config.lastConnected = System.currentTimeMillis();
6586               config.autoJoinBailedDueToLowRssi = false;
6587               config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED);
6588               config.numConnectionFailures = 0;
6589               config.numIpConfigFailures = 0;
6590               config.numAuthFailures = 0;
6591               config.numAssociation++;
6592           }
6593           mBadLinkspeedcount = 0;
6594       }
6595    }
6596
6597    void registerDisconnected() {
6598        if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) {
6599            long now_ms = System.currentTimeMillis();
6600            // We are switching away from this configuration,
6601            // hence record the time we were connected last
6602            WifiConfiguration config = mWifiConfigStore.getWifiConfiguration(mLastNetworkId);
6603            if (config != null) {
6604                config.lastDisconnected = System.currentTimeMillis();
6605                if (config.ephemeral) {
6606                    // Remove ephemeral WifiConfigurations from file
6607                    mWifiConfigStore.forgetNetwork(mLastNetworkId);
6608                }
6609            }
6610        }
6611    }
6612
6613    void noteWifiDisabledWhileAssociated() {
6614        // We got disabled by user while we were associated, make note of it
6615        int rssi = mWifiInfo.getRssi();
6616        WifiConfiguration config = getCurrentWifiConfiguration();
6617        if (getCurrentState() == mConnectedState
6618                && rssi != WifiInfo.INVALID_RSSI
6619                && config != null) {
6620            boolean is24GHz = mWifiInfo.is24GHz();
6621            boolean isBadRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdBadRssi24.get())
6622                    || (!is24GHz && rssi < mWifiConfigStore.thresholdBadRssi5.get());
6623            boolean isLowRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdLowRssi24.get())
6624                    || (!is24GHz && mWifiInfo.getRssi() < mWifiConfigStore.thresholdLowRssi5.get());
6625            boolean isHighRSSI = (is24GHz && rssi >= mWifiConfigStore.thresholdGoodRssi24.get())
6626                    || (!is24GHz && mWifiInfo.getRssi() >= mWifiConfigStore.thresholdGoodRssi5.get());
6627            if (isBadRSSI) {
6628                // Take note that we got disabled while RSSI was Bad
6629                config.numUserTriggeredWifiDisableLowRSSI++;
6630            } else if (isLowRSSI) {
6631                // Take note that we got disabled while RSSI was Low
6632                config.numUserTriggeredWifiDisableBadRSSI++;
6633            } else if (!isHighRSSI) {
6634                // Take note that we got disabled while RSSI was Not high
6635                config.numUserTriggeredWifiDisableNotHighRSSI++;
6636            }
6637        }
6638    }
6639
6640    WifiConfiguration getCurrentWifiConfiguration() {
6641        if (mLastNetworkId == WifiConfiguration.INVALID_NETWORK_ID) {
6642            return null;
6643        }
6644        return mWifiConfigStore.getWifiConfiguration(mLastNetworkId);
6645    }
6646
6647    ScanResult getCurrentScanResult() {
6648        WifiConfiguration config = getCurrentWifiConfiguration();
6649        if (config == null) {
6650            return null;
6651        }
6652        String BSSID = mWifiInfo.getBSSID();
6653        if (BSSID == null) {
6654            BSSID = mTargetRoamBSSID;
6655        }
6656        ScanDetailCache scanDetailCache =
6657                mWifiConfigStore.getScanDetailCache(config);
6658
6659        if (scanDetailCache == null) {
6660            return null;
6661        }
6662
6663        return scanDetailCache.get(BSSID);
6664    }
6665
6666    String getCurrentBSSID() {
6667        if (linkDebouncing) {
6668            return null;
6669        }
6670        return mLastBssid;
6671    }
6672
6673    class ConnectModeState extends State {
6674
6675        @Override
6676        public void enter() {
6677            connectScanningService();
6678        }
6679
6680        @Override
6681        public boolean processMessage(Message message) {
6682            WifiConfiguration config;
6683            int netId;
6684            boolean ok;
6685            boolean didDisconnect;
6686            String bssid;
6687            String ssid;
6688            NetworkUpdateResult result;
6689            logStateAndMessage(message, getClass().getSimpleName());
6690
6691            switch (message.what) {
6692                case WifiMonitor.ASSOCIATION_REJECTION_EVENT:
6693                    mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_ASSOC_FAILURE);
6694                    didBlackListBSSID = false;
6695                    bssid = (String) message.obj;
6696                    if (bssid == null || TextUtils.isEmpty(bssid)) {
6697                        // If BSSID is null, use the target roam BSSID
6698                        bssid = mTargetRoamBSSID;
6699                    }
6700                    if (bssid != null) {
6701                        // If we have a BSSID, tell configStore to black list it
6702                        synchronized(mScanResultCache) {
6703                            didBlackListBSSID = mWifiConfigStore.handleBSSIDBlackList
6704                                    (mLastNetworkId, bssid, false);
6705                        }
6706                    }
6707                    mSupplicantStateTracker.sendMessage(WifiMonitor.ASSOCIATION_REJECTION_EVENT);
6708                    break;
6709                case WifiMonitor.AUTHENTICATION_FAILURE_EVENT:
6710                    mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_AUTH_FAILURE);
6711                    mSupplicantStateTracker.sendMessage(WifiMonitor.AUTHENTICATION_FAILURE_EVENT);
6712                    break;
6713                case WifiMonitor.SSID_TEMP_DISABLED:
6714                case WifiMonitor.SSID_REENABLED:
6715                    String substr = (String) message.obj;
6716                    String en = message.what == WifiMonitor.SSID_TEMP_DISABLED ?
6717                            "temp-disabled" : "re-enabled";
6718                    loge("ConnectModeState SSID state=" + en + " nid="
6719                            + Integer.toString(message.arg1) + " [" + substr + "]");
6720                    synchronized(mScanResultCache) {
6721                        mWifiConfigStore.handleSSIDStateChange(message.arg1, message.what ==
6722                                WifiMonitor.SSID_REENABLED, substr, mWifiInfo.getBSSID());
6723                    }
6724                    break;
6725                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
6726                    SupplicantState state = handleSupplicantStateChange(message);
6727                    // A driver/firmware hang can now put the interface in a down state.
6728                    // We detect the interface going down and recover from it
6729                    if (!SupplicantState.isDriverActive(state)) {
6730                        if (mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) {
6731                            handleNetworkDisconnect();
6732                        }
6733                        log("Detected an interface down, restart driver");
6734                        transitionTo(mDriverStoppedState);
6735                        sendMessage(CMD_START_DRIVER);
6736                        break;
6737                    }
6738
6739                    // Supplicant can fail to report a NETWORK_DISCONNECTION_EVENT
6740                    // when authentication times out after a successful connection,
6741                    // we can figure this from the supplicant state. If supplicant
6742                    // state is DISCONNECTED, but the mNetworkInfo says we are not
6743                    // disconnected, we need to handle a disconnection
6744                    if (!linkDebouncing && state == SupplicantState.DISCONNECTED &&
6745                            mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) {
6746                        if (DBG) log("Missed CTRL-EVENT-DISCONNECTED, disconnect");
6747                        handleNetworkDisconnect();
6748                        transitionTo(mDisconnectedState);
6749                    }
6750                    break;
6751                case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST:
6752                    if (message.arg1 == 1) {
6753                        mWifiNative.disconnect();
6754                        mTemporarilyDisconnectWifi = true;
6755                    } else {
6756                        mWifiNative.reconnect();
6757                        mTemporarilyDisconnectWifi = false;
6758                    }
6759                    break;
6760                case CMD_ADD_OR_UPDATE_NETWORK:
6761                    config = (WifiConfiguration) message.obj;
6762                    int res = mWifiConfigStore.addOrUpdateNetwork(config, message.sendingUid);
6763                    if (res < 0) {
6764                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
6765                    } else {
6766                        WifiConfiguration curConfig = getCurrentWifiConfiguration();
6767                        if (curConfig != null && config != null) {
6768                            if (curConfig.priority < config.priority
6769                                    && config.status == WifiConfiguration.Status.ENABLED) {
6770                                // Interpret this as a connect attempt
6771                                // Set the last selected configuration so as to allow the system to
6772                                // stick the last user choice without persisting the choice
6773                                mWifiConfigStore.setLastSelectedConfiguration(res);
6774
6775                                // Remember time of last connection attempt
6776                                lastConnectAttempt = System.currentTimeMillis();
6777
6778                                mWifiConnectionStatistics.numWifiManagerJoinAttempt++;
6779
6780                                // As a courtesy to the caller, trigger a scan now
6781                                startScan(ADD_OR_UPDATE_SOURCE, 0, null, null);
6782                            }
6783                        }
6784                    }
6785                    replyToMessage(message, CMD_ADD_OR_UPDATE_NETWORK, res);
6786                    break;
6787                case CMD_REMOVE_NETWORK:
6788                    ok = mWifiConfigStore.removeNetwork(message.arg1);
6789                    if (!ok) {
6790                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
6791                    }
6792                    replyToMessage(message, message.what, ok ? SUCCESS : FAILURE);
6793                    break;
6794                case CMD_ENABLE_NETWORK:
6795                    boolean others = message.arg2 == 1;
6796                    // Tell autojoin the user did try to select to that network
6797                    // However, do NOT persist the choice by bumping the priority of the network
6798                    if (others) {
6799                        mWifiAutoJoinController.
6800                                updateConfigurationHistory(message.arg1, true, false);
6801                        // Set the last selected configuration so as to allow the system to
6802                        // stick the last user choice without persisting the choice
6803                        mWifiConfigStore.setLastSelectedConfiguration(message.arg1);
6804
6805                        // Remember time of last connection attempt
6806                        lastConnectAttempt = System.currentTimeMillis();
6807
6808                        mWifiConnectionStatistics.numWifiManagerJoinAttempt++;
6809                    }
6810                    // Cancel auto roam requests
6811                    autoRoamSetBSSID(message.arg1, "any");
6812
6813                    ok = mWifiConfigStore.enableNetwork(message.arg1, message.arg2 == 1);
6814                    if (!ok) {
6815                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
6816                    }
6817                    replyToMessage(message, message.what, ok ? SUCCESS : FAILURE);
6818                    break;
6819                case CMD_ENABLE_ALL_NETWORKS:
6820                    long time = android.os.SystemClock.elapsedRealtime();
6821                    if (time - mLastEnableAllNetworksTime > MIN_INTERVAL_ENABLE_ALL_NETWORKS_MS) {
6822                        mWifiConfigStore.enableAllNetworks();
6823                        mLastEnableAllNetworksTime = time;
6824                    }
6825                    break;
6826                case WifiManager.DISABLE_NETWORK:
6827                    if (mWifiConfigStore.disableNetwork(message.arg1,
6828                            WifiConfiguration.DISABLED_BY_WIFI_MANAGER) == true) {
6829                        replyToMessage(message, WifiManager.DISABLE_NETWORK_SUCCEEDED);
6830                    } else {
6831                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
6832                        replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED,
6833                                WifiManager.ERROR);
6834                    }
6835                    break;
6836                case CMD_DISABLE_EPHEMERAL_NETWORK:
6837                    config = mWifiConfigStore.disableEphemeralNetwork((String)message.obj);
6838                    if (config != null) {
6839                        if (config.networkId == mLastNetworkId) {
6840                            // Disconnect and let autojoin reselect a new network
6841                            sendMessage(CMD_DISCONNECT);
6842                        }
6843                    }
6844                    break;
6845                case CMD_BLACKLIST_NETWORK:
6846                    mWifiConfigStore.blackListBssid((String) message.obj);
6847                    break;
6848                case CMD_CLEAR_BLACKLIST:
6849                    mWifiConfigStore.clearBssidBlacklist();
6850                    break;
6851                case CMD_SAVE_CONFIG:
6852                    ok = mWifiConfigStore.saveConfig();
6853
6854                    if (DBG) loge("wifistatemachine did save config " + ok);
6855                    replyToMessage(message, CMD_SAVE_CONFIG, ok ? SUCCESS : FAILURE);
6856
6857                    // Inform the backup manager about a data change
6858                    IBackupManager ibm = IBackupManager.Stub.asInterface(
6859                            ServiceManager.getService(Context.BACKUP_SERVICE));
6860                    if (ibm != null) {
6861                        try {
6862                            ibm.dataChanged("com.android.providers.settings");
6863                        } catch (Exception e) {
6864                            // Try again later
6865                        }
6866                    }
6867                    break;
6868                case CMD_GET_CONFIGURED_NETWORKS:
6869                    replyToMessage(message, message.what,
6870                            mWifiConfigStore.getConfiguredNetworks());
6871                    break;
6872                case WifiMonitor.SUP_REQUEST_IDENTITY:
6873                    int networkId = message.arg2;
6874                    boolean identitySent = false;
6875                    int eapMethod = WifiEnterpriseConfig.Eap.NONE;
6876
6877                    if (targetWificonfiguration != null
6878                            && targetWificonfiguration.enterpriseConfig != null) {
6879                        eapMethod = targetWificonfiguration.enterpriseConfig.getEapMethod();
6880                    }
6881
6882                    // For SIM & AKA/AKA' EAP method Only, get identity from ICC
6883                    if (targetWificonfiguration != null
6884                            && targetWificonfiguration.networkId == networkId
6885                            && targetWificonfiguration.allowedKeyManagement
6886                                    .get(WifiConfiguration.KeyMgmt.IEEE8021X)
6887                            &&  (eapMethod == WifiEnterpriseConfig.Eap.SIM
6888                            || eapMethod == WifiEnterpriseConfig.Eap.AKA
6889                            || eapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME)) {
6890                        TelephonyManager tm = (TelephonyManager)
6891                                mContext.getSystemService(Context.TELEPHONY_SERVICE);
6892                        if (tm != null) {
6893                            String imsi = tm.getSubscriberId();
6894                            String mccMnc = "";
6895
6896                            if (tm.getSimState() == TelephonyManager.SIM_STATE_READY)
6897                                 mccMnc = tm.getSimOperator();
6898
6899                            String identity = buildIdentity(eapMethod, imsi, mccMnc);
6900
6901                            if (!identity.isEmpty()) {
6902                                mWifiNative.simIdentityResponse(networkId, identity);
6903                                identitySent = true;
6904                            }
6905                        }
6906                    }
6907                    if (!identitySent) {
6908                        // Supplicant lacks credentials to connect to that network, hence black list
6909                        ssid = (String) message.obj;
6910                        if (targetWificonfiguration != null && ssid != null
6911                                && targetWificonfiguration.SSID != null
6912                                && targetWificonfiguration.SSID.equals("\"" + ssid + "\"")) {
6913                            mWifiConfigStore.handleSSIDStateChange(
6914                                    targetWificonfiguration.networkId, false,
6915                                    "AUTH_FAILED no identity", null);
6916                        }
6917                        // Disconnect now, as we don't have any way to fullfill
6918                        // the  supplicant request.
6919                        mWifiConfigStore.setLastSelectedConfiguration(
6920                                WifiConfiguration.INVALID_NETWORK_ID);
6921                        mWifiNative.disconnect();
6922                    }
6923                    break;
6924                case WifiMonitor.SUP_REQUEST_SIM_AUTH:
6925                    logd("Received SUP_REQUEST_SIM_AUTH");
6926                    SimAuthRequestData requestData = (SimAuthRequestData) message.obj;
6927                    if (requestData != null) {
6928                        if (requestData.protocol == WifiEnterpriseConfig.Eap.SIM) {
6929                            handleGsmAuthRequest(requestData);
6930                        } else if (requestData.protocol == WifiEnterpriseConfig.Eap.AKA
6931                            || requestData.protocol == WifiEnterpriseConfig.Eap.AKA_PRIME) {
6932                            handle3GAuthRequest(requestData);
6933                        }
6934                    } else {
6935                        loge("Invalid sim auth request");
6936                    }
6937                    break;
6938                case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS:
6939                    replyToMessage(message, message.what,
6940                            mWifiConfigStore.getPrivilegedConfiguredNetworks());
6941                    break;
6942                case CMD_GET_MATCHING_CONFIG:
6943                    replyToMessage(message, message.what,
6944                            mWifiConfigStore.getMatchingConfig((ScanResult)message.obj));
6945                    break;
6946                /* Do a redundant disconnect without transition */
6947                case CMD_DISCONNECT:
6948                    mWifiConfigStore.setLastSelectedConfiguration
6949                            (WifiConfiguration.INVALID_NETWORK_ID);
6950                    mWifiNative.disconnect();
6951                    break;
6952                case CMD_RECONNECT:
6953                    mWifiAutoJoinController.attemptAutoJoin();
6954                    break;
6955                case CMD_REASSOCIATE:
6956                    lastConnectAttempt = System.currentTimeMillis();
6957                    mWifiNative.reassociate();
6958                    break;
6959                case CMD_RELOAD_TLS_AND_RECONNECT:
6960                    if (mWifiConfigStore.needsUnlockedKeyStore()) {
6961                        logd("Reconnecting to give a chance to un-connected TLS networks");
6962                        mWifiNative.disconnect();
6963                        lastConnectAttempt = System.currentTimeMillis();
6964                        mWifiNative.reconnect();
6965                    }
6966                    break;
6967                case CMD_AUTO_ROAM:
6968                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
6969                    return HANDLED;
6970                case CMD_AUTO_CONNECT:
6971                    /* Work Around: wpa_supplicant can get in a bad state where it returns a non
6972                     * associated status to the STATUS command but somehow-someplace still thinks
6973                     * it is associated and thus will ignore select/reconnect command with
6974                     * following message:
6975                     * "Already associated with the selected network - do nothing"
6976                     *
6977                     * Hence, sends a disconnect to supplicant first.
6978                     */
6979                    didDisconnect = false;
6980                    if (getCurrentState() != mDisconnectedState) {
6981                        /** Supplicant will ignore the reconnect if we are currently associated,
6982                         * hence trigger a disconnect
6983                         */
6984                        didDisconnect = true;
6985                        mWifiNative.disconnect();
6986                    }
6987
6988                    /* connect command coming from auto-join */
6989                    config = (WifiConfiguration) message.obj;
6990                    netId = message.arg1;
6991                    int roam = message.arg2;
6992                    loge("CMD_AUTO_CONNECT sup state "
6993                            + mSupplicantStateTracker.getSupplicantStateName()
6994                            + " my state " + getCurrentState().getName()
6995                            + " nid=" + Integer.toString(netId)
6996                            + " roam=" + Integer.toString(roam));
6997                    if (config == null) {
6998                        loge("AUTO_CONNECT and no config, bail out...");
6999                        break;
7000                    }
7001
7002                    /* Make sure we cancel any previous roam request */
7003                    autoRoamSetBSSID(netId, config.BSSID);
7004
7005                    /* Save the network config */
7006                    loge("CMD_AUTO_CONNECT will save config -> " + config.SSID
7007                            + " nid=" + Integer.toString(netId));
7008                    result = mWifiConfigStore.saveNetwork(config, -1);
7009                    netId = result.getNetworkId();
7010                    loge("CMD_AUTO_CONNECT did save config -> "
7011                            + " nid=" + Integer.toString(netId));
7012
7013                    // Make sure the network is enabled, since supplicant will not reenable it
7014                    mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false);
7015
7016                    if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ false) &&
7017                            mWifiNative.reconnect()) {
7018                        lastConnectAttempt = System.currentTimeMillis();
7019                        targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId);
7020                        config = mWifiConfigStore.getWifiConfiguration(netId);
7021                        if (config != null
7022                                && !mWifiConfigStore.isLastSelectedConfiguration(config)) {
7023                            // If we autojoined a different config than the user selected one,
7024                            // it means we could not see the last user selection,
7025                            // or that the last user selection was faulty and ended up blacklisted
7026                            // for some reason (in which case the user is notified with an error
7027                            // message in the Wifi picker), and thus we managed to auto-join away
7028                            // from the selected  config. -> in that case we need to forget
7029                            // the selection because we don't want to abruptly switch back to it.
7030                            //
7031                            // Note that the user selection is also forgotten after a period of time
7032                            // during which the device has been disconnected.
7033                            // The default value is 30 minutes : see the code path at bottom of
7034                            // setScanResults() function.
7035                            mWifiConfigStore.
7036                                 setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID);
7037                        }
7038                        mAutoRoaming = roam;
7039                        if (isRoaming() || linkDebouncing) {
7040                            transitionTo(mRoamingState);
7041                        } else if (didDisconnect) {
7042                            transitionTo(mDisconnectingState);
7043                        } else {
7044                            /* Already in disconnected state, nothing to change */
7045                        }
7046                    } else {
7047                        loge("Failed to connect config: " + config + " netId: " + netId);
7048                        replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED,
7049                                WifiManager.ERROR);
7050                        break;
7051                    }
7052                    break;
7053                case WifiManager.CONNECT_NETWORK:
7054                    /**
7055                     *  The connect message can contain a network id passed as arg1 on message or
7056                     * or a config passed as obj on message.
7057                     * For a new network, a config is passed to create and connect.
7058                     * For an existing network, a network id is passed
7059                     */
7060                    netId = message.arg1;
7061                    config = (WifiConfiguration) message.obj;
7062                    mWifiConnectionStatistics.numWifiManagerJoinAttempt++;
7063                    boolean updatedExisting = false;
7064
7065                    /* Save the network config */
7066                    if (config != null) {
7067                        String configKey = config.configKey(true /* allowCached */);
7068                        WifiConfiguration savedConfig =
7069                                mWifiConfigStore.getWifiConfiguration(configKey);
7070                        if (savedConfig != null) {
7071                            // There is an existing config with this netId, but it wasn't exposed
7072                            // (either AUTO_JOIN_DELETED or ephemeral; see WifiConfigStore#
7073                            // getConfiguredNetworks). Remove those bits and update the config.
7074                            config = savedConfig;
7075                            loge("CONNECT_NETWORK updating existing config with id=" +
7076                                    config.networkId + " configKey=" + configKey);
7077                            config.ephemeral = false;
7078                            config.autoJoinStatus = WifiConfiguration.AUTO_JOIN_ENABLED;
7079                            updatedExisting = true;
7080                        }
7081
7082                        result = mWifiConfigStore.saveNetwork(config, message.sendingUid);
7083                        netId = result.getNetworkId();
7084                    }
7085                    config = mWifiConfigStore.getWifiConfiguration(netId);
7086
7087                    if (config == null) {
7088                        loge("CONNECT_NETWORK no config for id=" + Integer.toString(netId) + " "
7089                                + mSupplicantStateTracker.getSupplicantStateName() + " my state "
7090                                + getCurrentState().getName());
7091                        replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED,
7092                                WifiManager.ERROR);
7093                        break;
7094                    } else {
7095                        String wasSkipped = config.autoJoinBailedDueToLowRssi ? " skipped" : "";
7096                        loge("CONNECT_NETWORK id=" + Integer.toString(netId)
7097                                + " config=" + config.SSID
7098                                + " cnid=" + config.networkId
7099                                + " supstate=" + mSupplicantStateTracker.getSupplicantStateName()
7100                                + " my state " + getCurrentState().getName()
7101                                + " uid = " + message.sendingUid
7102                                + wasSkipped);
7103                    }
7104
7105                    autoRoamSetBSSID(netId, "any");
7106
7107                    if (message.sendingUid == Process.WIFI_UID
7108                        || message.sendingUid == Process.SYSTEM_UID) {
7109                        // As a sanity measure, clear the BSSID in the supplicant network block.
7110                        // If system or Wifi Settings want to connect, they will not
7111                        // specify the BSSID.
7112                        // If an app however had added a BSSID to this configuration, and the BSSID
7113                        // was wrong, Then we would forever fail to connect until that BSSID
7114                        // is cleaned up.
7115                        clearConfigBSSID(config, "CONNECT_NETWORK");
7116                    }
7117
7118                    mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE;
7119
7120                    /* Tell autojoin the user did try to connect to that network */
7121                    mWifiAutoJoinController.updateConfigurationHistory(netId, true, true);
7122
7123                    mWifiConfigStore.setLastSelectedConfiguration(netId);
7124
7125                    didDisconnect = false;
7126                    if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID
7127                            && mLastNetworkId != netId) {
7128                        /** Supplicant will ignore the reconnect if we are currently associated,
7129                         * hence trigger a disconnect
7130                         */
7131                        didDisconnect = true;
7132                        mWifiNative.disconnect();
7133                    }
7134
7135                    // Make sure the network is enabled, since supplicant will not reenable it
7136                    mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false);
7137
7138                    if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ true) &&
7139                            mWifiNative.reconnect()) {
7140                        lastConnectAttempt = System.currentTimeMillis();
7141                        targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId);
7142
7143                        /* The state tracker handles enabling networks upon completion/failure */
7144                        mSupplicantStateTracker.sendMessage(WifiManager.CONNECT_NETWORK);
7145                        replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED);
7146                        if (didDisconnect) {
7147                            /* Expect a disconnection from the old connection */
7148                            transitionTo(mDisconnectingState);
7149                        } else if (updatedExisting && getCurrentState() == mConnectedState &&
7150                                getCurrentWifiConfiguration().networkId == netId) {
7151                            // Update the current set of network capabilities, but stay in the
7152                            // current state.
7153                            updateCapabilities(config);
7154                        } else {
7155                            /**
7156                             *  Directly go to disconnected state where we
7157                             * process the connection events from supplicant
7158                             **/
7159                            transitionTo(mDisconnectedState);
7160                        }
7161                    } else {
7162                        loge("Failed to connect config: " + config + " netId: " + netId);
7163                        replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED,
7164                                WifiManager.ERROR);
7165                        break;
7166                    }
7167                    break;
7168                case WifiManager.SAVE_NETWORK:
7169                    mWifiConnectionStatistics.numWifiManagerJoinAttempt++;
7170                    // Fall thru
7171                case WifiStateMachine.CMD_AUTO_SAVE_NETWORK:
7172                    lastSavedConfigurationAttempt = null; // Used for debug
7173                    config = (WifiConfiguration) message.obj;
7174                    if (config == null) {
7175                        loge("ERROR: SAVE_NETWORK with null configuration"
7176                                + mSupplicantStateTracker.getSupplicantStateName()
7177                                + " my state " + getCurrentState().getName());
7178                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
7179                        replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED,
7180                                WifiManager.ERROR);
7181                        break;
7182                    }
7183                    lastSavedConfigurationAttempt = new WifiConfiguration(config);
7184                    int nid = config.networkId;
7185                    loge("SAVE_NETWORK id=" + Integer.toString(nid)
7186                                + " config=" + config.SSID
7187                                + " nid=" + config.networkId
7188                                + " supstate=" + mSupplicantStateTracker.getSupplicantStateName()
7189                                + " my state " + getCurrentState().getName());
7190
7191                    result = mWifiConfigStore.saveNetwork(config, -1);
7192                    if (result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID) {
7193                        if (mWifiInfo.getNetworkId() == result.getNetworkId()) {
7194                            if (result.hasIpChanged()) {
7195                                // The currently connection configuration was changed
7196                                // We switched from DHCP to static or from static to DHCP, or the
7197                                // static IP address has changed.
7198                                log("Reconfiguring IP on connection");
7199                                // TODO: clear addresses and disable IPv6
7200                                // to simplify obtainingIpState.
7201                                transitionTo(mObtainingIpState);
7202                            }
7203                            if (result.hasProxyChanged()) {
7204                                log("Reconfiguring proxy on connection");
7205                                updateLinkProperties(CMD_UPDATE_LINKPROPERTIES);
7206                            }
7207                        }
7208                        replyToMessage(message, WifiManager.SAVE_NETWORK_SUCCEEDED);
7209                        if (VDBG) {
7210                           loge("Success save network nid="
7211                                        + Integer.toString(result.getNetworkId()));
7212                        }
7213
7214                        synchronized(mScanResultCache) {
7215                            /**
7216                             * If the command comes from WifiManager, then
7217                             * tell autojoin the user did try to modify and save that network,
7218                             * and interpret the SAVE_NETWORK as a request to connect
7219                             */
7220                            boolean user = message.what == WifiManager.SAVE_NETWORK;
7221                            mWifiAutoJoinController.updateConfigurationHistory(result.getNetworkId()
7222                                    , user, true);
7223                            mWifiAutoJoinController.attemptAutoJoin();
7224                        }
7225                    } else {
7226                        loge("Failed to save network");
7227                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
7228                        replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED,
7229                                WifiManager.ERROR);
7230                    }
7231                    break;
7232                case WifiManager.FORGET_NETWORK:
7233                    // Debug only, remember last configuration that was forgotten
7234                    WifiConfiguration toRemove
7235                            = mWifiConfigStore.getWifiConfiguration(message.arg1);
7236                    if (toRemove == null) {
7237                        lastForgetConfigurationAttempt = null;
7238                    } else {
7239                        lastForgetConfigurationAttempt = new WifiConfiguration(toRemove);
7240                    }
7241                    if (mWifiConfigStore.forgetNetwork(message.arg1)) {
7242                        replyToMessage(message, WifiManager.FORGET_NETWORK_SUCCEEDED);
7243                    } else {
7244                        loge("Failed to forget network");
7245                        replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED,
7246                                WifiManager.ERROR);
7247                    }
7248                    break;
7249                case WifiManager.START_WPS:
7250                    WpsInfo wpsInfo = (WpsInfo) message.obj;
7251                    WpsResult wpsResult;
7252                    switch (wpsInfo.setup) {
7253                        case WpsInfo.PBC:
7254                            wpsResult = mWifiConfigStore.startWpsPbc(wpsInfo);
7255                            break;
7256                        case WpsInfo.KEYPAD:
7257                            wpsResult = mWifiConfigStore.startWpsWithPinFromAccessPoint(wpsInfo);
7258                            break;
7259                        case WpsInfo.DISPLAY:
7260                            wpsResult = mWifiConfigStore.startWpsWithPinFromDevice(wpsInfo);
7261                            break;
7262                        default:
7263                            wpsResult = new WpsResult(Status.FAILURE);
7264                            loge("Invalid setup for WPS");
7265                            break;
7266                    }
7267                    mWifiConfigStore.setLastSelectedConfiguration
7268                            (WifiConfiguration.INVALID_NETWORK_ID);
7269                    if (wpsResult.status == Status.SUCCESS) {
7270                        replyToMessage(message, WifiManager.START_WPS_SUCCEEDED, wpsResult);
7271                        transitionTo(mWpsRunningState);
7272                    } else {
7273                        loge("Failed to start WPS with config " + wpsInfo.toString());
7274                        replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.ERROR);
7275                    }
7276                    break;
7277                case WifiMonitor.NETWORK_CONNECTION_EVENT:
7278                    if (DBG) log("Network connection established");
7279                    mLastNetworkId = message.arg1;
7280                    mLastBssid = (String) message.obj;
7281
7282                    mWifiInfo.setBSSID(mLastBssid);
7283                    mWifiInfo.setNetworkId(mLastNetworkId);
7284
7285                    sendNetworkStateChangeBroadcast(mLastBssid);
7286                    transitionTo(mObtainingIpState);
7287                    break;
7288                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
7289                    // Calling handleNetworkDisconnect here is redundant because we might already
7290                    // have called it when leaving L2ConnectedState to go to disconnecting state
7291                    // or thru other path
7292                    // We should normally check the mWifiInfo or mLastNetworkId so as to check
7293                    // if they are valid, and only in this case call handleNEtworkDisconnect,
7294                    // TODO: this should be fixed for a L MR release
7295                    // The side effect of calling handleNetworkDisconnect twice is that a bunch of
7296                    // idempotent commands are executed twice (stopping Dhcp, enabling the SPS mode
7297                    // at the chip etc...
7298                    if (DBG) log("ConnectModeState: Network connection lost ");
7299                    handleNetworkDisconnect();
7300                    transitionTo(mDisconnectedState);
7301                    break;
7302                case CMD_PNO_NETWORK_FOUND:
7303                    processPnoNetworkFound((ScanResult[])message.obj);
7304                    break;
7305                default:
7306                    return NOT_HANDLED;
7307            }
7308            return HANDLED;
7309        }
7310    }
7311
7312    private void updateCapabilities(WifiConfiguration config) {
7313        if (config.ephemeral) {
7314            mNetworkCapabilities.removeCapability(
7315                    NetworkCapabilities.NET_CAPABILITY_TRUSTED);
7316        } else {
7317            mNetworkCapabilities.addCapability(
7318                    NetworkCapabilities.NET_CAPABILITY_TRUSTED);
7319        }
7320        mNetworkAgent.sendNetworkCapabilities(mNetworkCapabilities);
7321    }
7322
7323    private class WifiNetworkAgent extends NetworkAgent {
7324        public WifiNetworkAgent(Looper l, Context c, String TAG, NetworkInfo ni,
7325                NetworkCapabilities nc, LinkProperties lp, int score) {
7326            super(l, c, TAG, ni, nc, lp, score);
7327        }
7328        protected void unwanted() {
7329            // Ignore if we're not the current networkAgent.
7330            if (this != mNetworkAgent) return;
7331            if (DBG) log("WifiNetworkAgent -> Wifi unwanted score "
7332                    + Integer.toString(mWifiInfo.score));
7333            unwantedNetwork(network_status_unwanted_disconnect);
7334        }
7335
7336        protected void networkStatus(int status) {
7337            if (status == NetworkAgent.INVALID_NETWORK) {
7338                if (DBG) log("WifiNetworkAgent -> Wifi networkStatus invalid, score="
7339                        + Integer.toString(mWifiInfo.score));
7340                unwantedNetwork(network_status_unwanted_disable_autojoin);
7341            } else if (status == NetworkAgent.VALID_NETWORK) {
7342                if (DBG && mWifiInfo != null) log("WifiNetworkAgent -> Wifi networkStatus valid, score= "
7343                        + Integer.toString(mWifiInfo.score));
7344                doNetworkStatus(status);
7345            }
7346        }
7347    }
7348
7349    void unwantedNetwork(int reason) {
7350        sendMessage(CMD_UNWANTED_NETWORK, reason);
7351    }
7352
7353    void doNetworkStatus(int status) {
7354        sendMessage(CMD_NETWORK_STATUS, status);
7355    }
7356
7357    // rfc4186 & rfc4187:
7358    // create Permanent Identity base on IMSI,
7359    // identity = usernam@realm
7360    // with username = prefix | IMSI
7361    // and realm is derived MMC/MNC tuple according 3GGP spec(TS23.003)
7362    private String buildIdentity(int eapMethod, String imsi, String mccMnc) {
7363        String mcc;
7364        String mnc;
7365        String prefix;
7366
7367        if (imsi == null || imsi.isEmpty())
7368            return "";
7369
7370        if (eapMethod == WifiEnterpriseConfig.Eap.SIM)
7371            prefix = "1";
7372        else if (eapMethod == WifiEnterpriseConfig.Eap.AKA)
7373            prefix = "0";
7374        else if (eapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME)
7375            prefix = "6";
7376        else  // not a valide EapMethod
7377            return "";
7378
7379        /* extract mcc & mnc from mccMnc */
7380        if (mccMnc != null && !mccMnc.isEmpty()) {
7381            mcc = mccMnc.substring(0, 3);
7382            mnc = mccMnc.substring(3);
7383            if (mnc.length() == 2)
7384                mnc = "0" + mnc;
7385        } else {
7386            // extract mcc & mnc from IMSI, assume mnc size is 3
7387            mcc = imsi.substring(0, 3);
7388            mnc = imsi.substring(3, 6);
7389        }
7390
7391        return prefix + imsi + "@wlan.mnc" + mnc + ".mcc" + mcc + ".3gppnetwork.org";
7392    }
7393
7394    boolean startScanForConfiguration(WifiConfiguration config, boolean restrictChannelList) {
7395        if (config == null)
7396            return false;
7397
7398        // We are still seeing a fairly high power consumption triggered by autojoin scans
7399        // Hence do partial scans only for PSK configuration that are roamable since the
7400        // primary purpose of the partial scans is roaming.
7401        // Full badn scans with exponential backoff for the purpose or extended roaming and
7402        // network switching are performed unconditionally.
7403        ScanDetailCache scanDetailCache =
7404                mWifiConfigStore.getScanDetailCache(config);
7405        if (scanDetailCache == null
7406                || !config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)
7407                || scanDetailCache.size() > 6) {
7408            //return true but to not trigger the scan
7409            return true;
7410        }
7411        HashSet<Integer> channels = mWifiConfigStore.makeChannelList(config,
7412                ONE_HOUR_MILLI, restrictChannelList);
7413        if (channels != null && channels.size() != 0) {
7414            StringBuilder freqs = new StringBuilder();
7415            boolean first = true;
7416            for (Integer channel : channels) {
7417                if (!first)
7418                    freqs.append(",");
7419                freqs.append(channel.toString());
7420                first = false;
7421            }
7422            //if (DBG) {
7423            loge("WifiStateMachine starting scan for " + config.configKey() + " with " + freqs);
7424            //}
7425            // Call wifi native to start the scan
7426            if (startScanNative(
7427                    WifiNative.SCAN_WITHOUT_CONNECTION_SETUP,
7428                    freqs.toString())) {
7429                // Only count battery consumption if scan request is accepted
7430                noteScanStart(SCAN_ALARM_SOURCE, null);
7431                messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK;
7432            } else {
7433                // used for debug only, mark scan as failed
7434                messageHandlingStatus = MESSAGE_HANDLING_STATUS_HANDLING_ERROR;
7435            }
7436            return true;
7437        } else {
7438            if (DBG) loge("WifiStateMachine no channels for " + config.configKey());
7439            return false;
7440        }
7441    }
7442
7443    void clearCurrentConfigBSSID(String dbg) {
7444        // Clear the bssid in the current config's network block
7445        WifiConfiguration config = getCurrentWifiConfiguration();
7446        if (config == null)
7447            return;
7448        clearConfigBSSID(config, dbg);
7449    }
7450    void clearConfigBSSID(WifiConfiguration config, String dbg) {
7451        if (config == null)
7452            return;
7453        if (DBG) {
7454            loge(dbg + " " + mTargetRoamBSSID + " config " + config.configKey()
7455                    + " config.bssid " + config.BSSID);
7456        }
7457        config.autoJoinBSSID = "any";
7458        config.BSSID = "any";
7459        if (DBG) {
7460           loge(dbg + " " + config.SSID
7461                    + " nid=" + Integer.toString(config.networkId));
7462        }
7463        mWifiConfigStore.saveWifiConfigBSSID(config);
7464    }
7465
7466    class L2ConnectedState extends State {
7467        @Override
7468        public void enter() {
7469            mRssiPollToken++;
7470            if (mEnableRssiPolling) {
7471                sendMessage(CMD_RSSI_POLL, mRssiPollToken, 0);
7472            }
7473            if (mNetworkAgent != null) {
7474                loge("Have NetworkAgent when entering L2Connected");
7475                setNetworkDetailedState(DetailedState.DISCONNECTED);
7476            }
7477            setNetworkDetailedState(DetailedState.CONNECTING);
7478
7479            if (TextUtils.isEmpty(mTcpBufferSizes) == false) {
7480                mLinkProperties.setTcpBufferSizes(mTcpBufferSizes);
7481            }
7482            mNetworkAgent = new WifiNetworkAgent(getHandler().getLooper(), mContext,
7483                    "WifiNetworkAgent", mNetworkInfo, mNetworkCapabilitiesFilter,
7484                    mLinkProperties, 60);
7485
7486            // We must clear the config BSSID, as the wifi chipset may decide to roam
7487            // from this point on and having the BSSID specified in the network block would
7488            // cause the roam to faile and the device to disconnect
7489            clearCurrentConfigBSSID("L2ConnectedState");
7490        }
7491
7492        @Override
7493        public void exit() {
7494            // This is handled by receiving a NETWORK_DISCONNECTION_EVENT in ConnectModeState
7495            // Bug: 15347363
7496            // For paranoia's sake, call handleNetworkDisconnect
7497            // only if BSSID is null or last networkId
7498            // is not invalid.
7499            if (DBG) {
7500                StringBuilder sb = new StringBuilder();
7501                sb.append("leaving L2ConnectedState state nid=" + Integer.toString(mLastNetworkId));
7502                if (mLastBssid !=null) {
7503                    sb.append(" ").append(mLastBssid);
7504                }
7505            }
7506            if (mLastBssid != null || mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) {
7507                handleNetworkDisconnect();
7508            }
7509        }
7510
7511        @Override
7512        public boolean processMessage(Message message) {
7513            logStateAndMessage(message, getClass().getSimpleName());
7514
7515            switch (message.what) {
7516              case DhcpStateMachine.CMD_PRE_DHCP_ACTION:
7517                  handlePreDhcpSetup();
7518                  break;
7519              case DhcpStateMachine.CMD_POST_DHCP_ACTION:
7520                  handlePostDhcpSetup();
7521                  if (message.arg1 == DhcpStateMachine.DHCP_SUCCESS) {
7522                      if (DBG) log("WifiStateMachine DHCP successful");
7523                      handleIPv4Success((DhcpResults) message.obj, DhcpStateMachine.DHCP_SUCCESS);
7524                      // We advance to mVerifyingLinkState because handleIPv4Success will call
7525                      // updateLinkProperties, which then sends CMD_IP_CONFIGURATION_SUCCESSFUL.
7526                  } else if (message.arg1 == DhcpStateMachine.DHCP_FAILURE) {
7527                      mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_DHCP_FAILURE);
7528                      if (DBG) {
7529                          int count = -1;
7530                          WifiConfiguration config = getCurrentWifiConfiguration();
7531                          if (config != null) {
7532                              count = config.numConnectionFailures;
7533                          }
7534                          log("WifiStateMachine DHCP failure count=" + count);
7535                      }
7536                      handleIPv4Failure(DhcpStateMachine.DHCP_FAILURE);
7537                      // As above, we transition to mDisconnectingState via updateLinkProperties.
7538                  }
7539                  break;
7540                case CMD_IP_CONFIGURATION_SUCCESSFUL:
7541                    handleSuccessfulIpConfiguration();
7542                    sendConnectedState();
7543                    transitionTo(mConnectedState);
7544                    break;
7545                case CMD_IP_CONFIGURATION_LOST:
7546                    // Get Link layer stats so as we get fresh tx packet counters
7547                    getWifiLinkLayerStats(true);
7548                    handleIpConfigurationLost();
7549                    transitionTo(mDisconnectingState);
7550                    break;
7551                case CMD_DISCONNECT:
7552                    mWifiNative.disconnect();
7553                    transitionTo(mDisconnectingState);
7554                    break;
7555                case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST:
7556                    if (message.arg1 == 1) {
7557                        mWifiNative.disconnect();
7558                        mTemporarilyDisconnectWifi = true;
7559                        transitionTo(mDisconnectingState);
7560                    }
7561                    break;
7562                case CMD_SET_OPERATIONAL_MODE:
7563                    if (message.arg1 != CONNECT_MODE) {
7564                        sendMessage(CMD_DISCONNECT);
7565                        deferMessage(message);
7566                        if (message.arg1 == SCAN_ONLY_WITH_WIFI_OFF_MODE) {
7567                            noteWifiDisabledWhileAssociated();
7568                        }
7569                    }
7570                    mWifiConfigStore.
7571                                setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID);
7572                    break;
7573                case CMD_SET_COUNTRY_CODE:
7574                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
7575                    deferMessage(message);
7576                    break;
7577                case CMD_START_SCAN:
7578                    //if (DBG) {
7579                        loge("WifiStateMachine CMD_START_SCAN source " + message.arg1
7580                              + " txSuccessRate="+String.format( "%.2f", mWifiInfo.txSuccessRate)
7581                              + " rxSuccessRate="+String.format( "%.2f", mWifiInfo.rxSuccessRate)
7582                              + " targetRoamBSSID=" + mTargetRoamBSSID
7583                              + " RSSI=" + mWifiInfo.getRssi());
7584                    //}
7585                    if (message.arg1 == SCAN_ALARM_SOURCE) {
7586                        // Check if the CMD_START_SCAN message is obsolete (and thus if it should
7587                        // not be processed) and restart the scan if needed
7588                        boolean shouldScan =
7589                                mScreenOn && mWifiConfigStore.enableAutoJoinScanWhenAssociated.get();
7590                        if (!checkAndRestartDelayedScan(message.arg2,
7591                                shouldScan,
7592                                mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(),
7593                                null, null)) {
7594                            messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE;
7595                            loge("WifiStateMachine L2Connected CMD_START_SCAN source "
7596                                    + message.arg1
7597                                    + " " + message.arg2 + ", " + mDelayedScanCounter
7598                                    + " -> obsolete");
7599                            return HANDLED;
7600                        }
7601                        if (mP2pConnected.get()) {
7602                            loge("WifiStateMachine L2Connected CMD_START_SCAN source "
7603                                    + message.arg1
7604                                    + " " + message.arg2 + ", " + mDelayedScanCounter
7605                                    + " ignore because P2P is connected");
7606                            messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
7607                            return HANDLED;
7608                        }
7609                        boolean tryFullBandScan = false;
7610                        boolean restrictChannelList = false;
7611                        long now_ms = System.currentTimeMillis();
7612                        if (DBG) {
7613                            loge("WifiStateMachine CMD_START_SCAN with age="
7614                                    + Long.toString(now_ms - lastFullBandConnectedTimeMilli)
7615                                    + " interval=" + fullBandConnectedTimeIntervalMilli
7616                                    + " maxinterval=" + maxFullBandConnectedTimeIntervalMilli);
7617                        }
7618                        if (mWifiInfo != null) {
7619                            if (mWifiConfigStore.enableFullBandScanWhenAssociated.get() &&
7620                                    (now_ms - lastFullBandConnectedTimeMilli)
7621                                    > fullBandConnectedTimeIntervalMilli) {
7622                                if (DBG) {
7623                                    loge("WifiStateMachine CMD_START_SCAN try full band scan age="
7624                                         + Long.toString(now_ms - lastFullBandConnectedTimeMilli)
7625                                         + " interval=" + fullBandConnectedTimeIntervalMilli
7626                                         + " maxinterval=" + maxFullBandConnectedTimeIntervalMilli);
7627                                }
7628                                tryFullBandScan = true;
7629                            }
7630
7631                            if (mWifiInfo.txSuccessRate >
7632                                    mWifiConfigStore.maxTxPacketForFullScans
7633                                    || mWifiInfo.rxSuccessRate >
7634                                    mWifiConfigStore.maxRxPacketForFullScans) {
7635                                // Too much traffic at the interface, hence no full band scan
7636                                if (DBG) {
7637                                    loge("WifiStateMachine CMD_START_SCAN " +
7638                                            "prevent full band scan due to pkt rate");
7639                                }
7640                                tryFullBandScan = false;
7641                            }
7642
7643                            if (mWifiInfo.txSuccessRate >
7644                                    mWifiConfigStore.maxTxPacketForPartialScans
7645                                    || mWifiInfo.rxSuccessRate >
7646                                    mWifiConfigStore.maxRxPacketForPartialScans) {
7647                                // Don't scan if lots of packets are being sent
7648                                restrictChannelList = true;
7649                                if (mWifiConfigStore.alwaysEnableScansWhileAssociated.get() == 0) {
7650                                    if (DBG) {
7651                                     loge("WifiStateMachine CMD_START_SCAN source " + message.arg1
7652                                        + " ...and ignore scans"
7653                                        + " tx=" + String.format("%.2f", mWifiInfo.txSuccessRate)
7654                                        + " rx=" + String.format("%.2f", mWifiInfo.rxSuccessRate));
7655                                    }
7656                                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_REFUSED;
7657                                    return HANDLED;
7658                                }
7659                            }
7660                        }
7661
7662                        WifiConfiguration currentConfiguration = getCurrentWifiConfiguration();
7663                        if (DBG) {
7664                            loge("WifiStateMachine CMD_START_SCAN full=" +
7665                                    tryFullBandScan);
7666                        }
7667                        if (currentConfiguration != null) {
7668                            if (fullBandConnectedTimeIntervalMilli
7669                                    < mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get()) {
7670                                // Sanity
7671                                fullBandConnectedTimeIntervalMilli
7672                                        = mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get();
7673                            }
7674                            if (tryFullBandScan) {
7675                                lastFullBandConnectedTimeMilli = now_ms;
7676                                if (fullBandConnectedTimeIntervalMilli
7677                                        < mWifiConfigStore.associatedFullScanMaxIntervalMilli) {
7678                                    // Increase the interval
7679                                    fullBandConnectedTimeIntervalMilli
7680                                            = fullBandConnectedTimeIntervalMilli
7681                                            * mWifiConfigStore.associatedFullScanBackoff.get() / 8;
7682
7683                                    if (DBG) {
7684                                        loge("WifiStateMachine CMD_START_SCAN bump interval ="
7685                                        + fullBandConnectedTimeIntervalMilli);
7686                                    }
7687                                }
7688                                handleScanRequest(
7689                                        WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message);
7690                            } else {
7691                                if (!startScanForConfiguration(
7692                                        currentConfiguration, restrictChannelList)) {
7693                                    if (DBG) {
7694                                        loge("WifiStateMachine starting scan, " +
7695                                                " did not find channels -> full");
7696                                    }
7697                                    lastFullBandConnectedTimeMilli = now_ms;
7698                                    if (fullBandConnectedTimeIntervalMilli
7699                                            < mWifiConfigStore.associatedFullScanMaxIntervalMilli) {
7700                                        // Increase the interval
7701                                        fullBandConnectedTimeIntervalMilli
7702                                                = fullBandConnectedTimeIntervalMilli
7703                                                * mWifiConfigStore.associatedFullScanBackoff.get() / 8;
7704
7705                                        if (DBG) {
7706                                            loge("WifiStateMachine CMD_START_SCAN bump interval ="
7707                                                    + fullBandConnectedTimeIntervalMilli);
7708                                        }
7709                                    }
7710                                    handleScanRequest(
7711                                                WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message);
7712                                }
7713                            }
7714
7715                        } else {
7716                            loge("CMD_START_SCAN : connected mode and no configuration");
7717                            messageHandlingStatus = MESSAGE_HANDLING_STATUS_HANDLING_ERROR;
7718                        }
7719                    } else {
7720                        // Not scan alarm source
7721                        return NOT_HANDLED;
7722                    }
7723                    break;
7724                    /* Ignore connection to same network */
7725                case WifiManager.CONNECT_NETWORK:
7726                    int netId = message.arg1;
7727                    if (mWifiInfo.getNetworkId() == netId) {
7728                        break;
7729                    }
7730                    return NOT_HANDLED;
7731                    /* Ignore */
7732                case WifiMonitor.NETWORK_CONNECTION_EVENT:
7733                    break;
7734                case CMD_RSSI_POLL:
7735                    if (message.arg1 == mRssiPollToken) {
7736                        if (mWifiConfigStore.enableChipWakeUpWhenAssociated.get()) {
7737                            if (VVDBG) log(" get link layer stats " + mWifiLinkLayerStatsSupported);
7738                            WifiLinkLayerStats stats = getWifiLinkLayerStats(VDBG);
7739                            if (stats != null) {
7740                                // Sanity check the results provided by driver
7741                                if (mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI
7742                                        && (stats.rssi_mgmt == 0
7743                                        || stats.beacon_rx == 0)) {
7744                                    stats = null;
7745                                }
7746                            }
7747                            // Get Info and continue polling
7748                            fetchRssiLinkSpeedAndFrequencyNative();
7749                            calculateWifiScore(stats);
7750                        }
7751                        sendMessageDelayed(obtainMessage(CMD_RSSI_POLL,
7752                                mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS);
7753
7754                        if (DBG) sendRssiChangeBroadcast(mWifiInfo.getRssi());
7755                    } else {
7756                        // Polling has completed
7757                    }
7758                    break;
7759                case CMD_ENABLE_RSSI_POLL:
7760                    cleanWifiScore();
7761                    if (mWifiConfigStore.enableRssiPollWhenAssociated.get()) {
7762                        mEnableRssiPolling = (message.arg1 == 1);
7763                    } else {
7764                        mEnableRssiPolling = false;
7765                    }
7766                    mRssiPollToken++;
7767                    if (mEnableRssiPolling) {
7768                        // First poll
7769                        fetchRssiLinkSpeedAndFrequencyNative();
7770                        sendMessageDelayed(obtainMessage(CMD_RSSI_POLL,
7771                                mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS);
7772                    }
7773                    break;
7774                case WifiManager.RSSI_PKTCNT_FETCH:
7775                    RssiPacketCountInfo info = new RssiPacketCountInfo();
7776                    fetchRssiLinkSpeedAndFrequencyNative();
7777                    info.rssi = mWifiInfo.getRssi();
7778                    fetchPktcntNative(info);
7779                    replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED, info);
7780                    break;
7781                case CMD_DELAYED_NETWORK_DISCONNECT:
7782                    if (!linkDebouncing && mWifiConfigStore.enableLinkDebouncing) {
7783
7784                        // Ignore if we are not debouncing
7785                        loge("CMD_DELAYED_NETWORK_DISCONNECT and not debouncing - ignore "
7786                                + message.arg1);
7787                        return HANDLED;
7788                    } else {
7789                        loge("CMD_DELAYED_NETWORK_DISCONNECT and debouncing - disconnect "
7790                                + message.arg1);
7791
7792                        linkDebouncing = false;
7793                        // If we are still debouncing while this message comes,
7794                        // it means we were not able to reconnect within the alloted time
7795                        // = LINK_FLAPPING_DEBOUNCE_MSEC
7796                        // and thus, trigger a real disconnect
7797                        handleNetworkDisconnect();
7798                        transitionTo(mDisconnectedState);
7799                    }
7800                    break;
7801                case CMD_ASSOCIATED_BSSID:
7802                    if ((String) message.obj == null) {
7803                        loge("Associated command w/o BSSID");
7804                        break;
7805                    }
7806                    mLastBssid = (String) message.obj;
7807                    if (mLastBssid != null
7808                            && (mWifiInfo.getBSSID() == null
7809                            || !mLastBssid.equals(mWifiInfo.getBSSID()))) {
7810                        mWifiInfo.setBSSID((String) message.obj);
7811                        sendNetworkStateChangeBroadcast(mLastBssid);
7812                    }
7813                    break;
7814                default:
7815                    return NOT_HANDLED;
7816            }
7817
7818            return HANDLED;
7819        }
7820    }
7821
7822    class ObtainingIpState extends State {
7823        @Override
7824        public void enter() {
7825            if (DBG) {
7826                String key = "";
7827                if (getCurrentWifiConfiguration() != null) {
7828                    key = getCurrentWifiConfiguration().configKey();
7829                }
7830                log("enter ObtainingIpState netId=" + Integer.toString(mLastNetworkId)
7831                        + " " + key + " "
7832                        + " roam=" + mAutoRoaming
7833                        + " static=" + mWifiConfigStore.isUsingStaticIp(mLastNetworkId)
7834                        + " watchdog= " + obtainingIpWatchdogCount);
7835            }
7836
7837            // Reset link Debouncing, indicating we have successfully re-connected to the AP
7838            // We might still be roaming
7839            linkDebouncing = false;
7840
7841            // Send event to CM & network change broadcast
7842            setNetworkDetailedState(DetailedState.OBTAINING_IPADDR);
7843
7844            // We must clear the config BSSID, as the wifi chipset may decide to roam
7845            // from this point on and having the BSSID specified in the network block would
7846            // cause the roam to faile and the device to disconnect
7847            clearCurrentConfigBSSID("ObtainingIpAddress");
7848
7849            try {
7850                mNwService.enableIpv6(mInterfaceName);
7851            } catch (RemoteException re) {
7852                loge("Failed to enable IPv6: " + re);
7853            } catch (IllegalStateException e) {
7854                loge("Failed to enable IPv6: " + e);
7855            }
7856
7857            if (!mWifiConfigStore.isUsingStaticIp(mLastNetworkId)) {
7858                if (isRoaming()) {
7859                    renewDhcp();
7860                } else {
7861                    // Remove any IP address on the interface in case we're switching from static
7862                    // IP configuration to DHCP. This is safe because if we get here when not
7863                    // roaming, we don't have a usable address.
7864                    clearIPv4Address(mInterfaceName);
7865                    startDhcp();
7866                }
7867                obtainingIpWatchdogCount++;
7868                loge("Start Dhcp Watchdog " + obtainingIpWatchdogCount);
7869                // Get Link layer stats so as we get fresh tx packet counters
7870                getWifiLinkLayerStats(true);
7871                sendMessageDelayed(obtainMessage(CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER,
7872                        obtainingIpWatchdogCount, 0), OBTAINING_IP_ADDRESS_GUARD_TIMER_MSEC);
7873            } else {
7874                // stop any running dhcp before assigning static IP
7875                stopDhcp();
7876                StaticIpConfiguration config = mWifiConfigStore.getStaticIpConfiguration(
7877                        mLastNetworkId);
7878                if (config.ipAddress == null) {
7879                    loge("Static IP lacks address");
7880                    sendMessage(CMD_STATIC_IP_FAILURE);
7881                } else {
7882                    InterfaceConfiguration ifcg = new InterfaceConfiguration();
7883                    ifcg.setLinkAddress(config.ipAddress);
7884                    ifcg.setInterfaceUp();
7885                    try {
7886                        mNwService.setInterfaceConfig(mInterfaceName, ifcg);
7887                        if (DBG) log("Static IP configuration succeeded");
7888                        DhcpResults dhcpResults = new DhcpResults(config);
7889                        sendMessage(CMD_STATIC_IP_SUCCESS, dhcpResults);
7890                    } catch (RemoteException re) {
7891                        loge("Static IP configuration failed: " + re);
7892                        sendMessage(CMD_STATIC_IP_FAILURE);
7893                    } catch (IllegalStateException e) {
7894                        loge("Static IP configuration failed: " + e);
7895                        sendMessage(CMD_STATIC_IP_FAILURE);
7896                    }
7897                }
7898            }
7899        }
7900      @Override
7901      public boolean processMessage(Message message) {
7902          logStateAndMessage(message, getClass().getSimpleName());
7903
7904          switch(message.what) {
7905              case CMD_STATIC_IP_SUCCESS:
7906                  handleIPv4Success((DhcpResults) message.obj, CMD_STATIC_IP_SUCCESS);
7907                  break;
7908              case CMD_STATIC_IP_FAILURE:
7909                  handleIPv4Failure(CMD_STATIC_IP_FAILURE);
7910                  break;
7911              case CMD_AUTO_CONNECT:
7912              case CMD_AUTO_ROAM:
7913                  messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
7914                  break;
7915              case WifiManager.SAVE_NETWORK:
7916              case WifiStateMachine.CMD_AUTO_SAVE_NETWORK:
7917                  messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
7918                  deferMessage(message);
7919                  break;
7920                  /* Defer any power mode changes since we must keep active power mode at DHCP */
7921              case CMD_SET_HIGH_PERF_MODE:
7922                  messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
7923                  deferMessage(message);
7924                  break;
7925                  /* Defer scan request since we should not switch to other channels at DHCP */
7926              case CMD_START_SCAN:
7927                  messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
7928                  deferMessage(message);
7929                  break;
7930              case CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER:
7931                  if (message.arg1 == obtainingIpWatchdogCount) {
7932                      loge("ObtainingIpAddress: Watchdog Triggered, count="
7933                              + obtainingIpWatchdogCount);
7934                      handleIpConfigurationLost();
7935                      transitionTo(mDisconnectingState);
7936                      break;
7937                  }
7938                  messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
7939                  break;
7940              default:
7941                  return NOT_HANDLED;
7942          }
7943          return HANDLED;
7944      }
7945    }
7946
7947    class VerifyingLinkState extends State {
7948        @Override
7949        public void enter() {
7950            log(getName() + " enter");
7951            setNetworkDetailedState(DetailedState.VERIFYING_POOR_LINK);
7952            mWifiConfigStore.updateStatus(mLastNetworkId, DetailedState.VERIFYING_POOR_LINK);
7953            sendNetworkStateChangeBroadcast(mLastBssid);
7954            // End roaming
7955            mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE;
7956        }
7957        @Override
7958        public boolean processMessage(Message message) {
7959            logStateAndMessage(message, getClass().getSimpleName());
7960
7961            switch (message.what) {
7962                case WifiWatchdogStateMachine.POOR_LINK_DETECTED:
7963                    // Stay here
7964                    log(getName() + " POOR_LINK_DETECTED: no transition");
7965                    break;
7966                case WifiWatchdogStateMachine.GOOD_LINK_DETECTED:
7967                    log(getName() + " GOOD_LINK_DETECTED: transition to captive portal check");
7968
7969                    log(getName() + " GOOD_LINK_DETECTED: transition to CONNECTED");
7970                    sendConnectedState();
7971                    transitionTo(mConnectedState);
7972                    break;
7973                default:
7974                    if (DBG) log(getName() + " what=" + message.what + " NOT_HANDLED");
7975                    return NOT_HANDLED;
7976            }
7977            return HANDLED;
7978        }
7979    }
7980
7981    private void sendConnectedState() {
7982        // Send out a broadcast with the CAPTIVE_PORTAL_CHECK to preserve
7983        // existing behaviour. The captive portal check really happens after we
7984        // transition into DetailedState.CONNECTED.
7985        setNetworkDetailedState(DetailedState.CAPTIVE_PORTAL_CHECK);
7986        mWifiConfigStore.updateStatus(mLastNetworkId,
7987        DetailedState.CAPTIVE_PORTAL_CHECK);
7988        sendNetworkStateChangeBroadcast(mLastBssid);
7989
7990        if (mWifiConfigStore.getLastSelectedConfiguration() != null) {
7991            if (mNetworkAgent != null) mNetworkAgent.explicitlySelected();
7992        }
7993
7994        setNetworkDetailedState(DetailedState.CONNECTED);
7995        mWifiConfigStore.updateStatus(mLastNetworkId, DetailedState.CONNECTED);
7996        sendNetworkStateChangeBroadcast(mLastBssid);
7997    }
7998
7999    class RoamingState extends State {
8000        boolean mAssociated;
8001        @Override
8002        public void enter() {
8003            if (DBG) {
8004                log("RoamingState Enter"
8005                        + " mScreenOn=" + mScreenOn );
8006            }
8007            setScanAlarm(false);
8008
8009            // Make sure we disconnect if roaming fails
8010            roamWatchdogCount++;
8011            loge("Start Roam Watchdog " + roamWatchdogCount);
8012            sendMessageDelayed(obtainMessage(CMD_ROAM_WATCHDOG_TIMER,
8013                    roamWatchdogCount, 0), ROAM_GUARD_TIMER_MSEC);
8014            mAssociated = false;
8015        }
8016        @Override
8017        public boolean processMessage(Message message) {
8018            logStateAndMessage(message, getClass().getSimpleName());
8019            WifiConfiguration config;
8020            switch (message.what) {
8021                case CMD_IP_CONFIGURATION_LOST:
8022                    config = getCurrentWifiConfiguration();
8023                    if (config != null) {
8024                        mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_AUTOROAM_FAILURE);
8025                        mWifiConfigStore.noteRoamingFailure(config,
8026                                WifiConfiguration.ROAMING_FAILURE_IP_CONFIG);
8027                    }
8028                    return NOT_HANDLED;
8029               case WifiWatchdogStateMachine.POOR_LINK_DETECTED:
8030                    if (DBG) log("Roaming and Watchdog reports poor link -> ignore");
8031                    return HANDLED;
8032               case CMD_UNWANTED_NETWORK:
8033                    if (DBG) log("Roaming and CS doesnt want the network -> ignore");
8034                    return HANDLED;
8035               case CMD_SET_OPERATIONAL_MODE:
8036                    if (message.arg1 != CONNECT_MODE) {
8037                        deferMessage(message);
8038                    }
8039                    break;
8040               case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
8041                    /**
8042                     * If we get a SUPPLICANT_STATE_CHANGE_EVENT indicating a DISCONNECT
8043                     * before NETWORK_DISCONNECTION_EVENT
8044                     * And there is an associated BSSID corresponding to our target BSSID, then
8045                     * we have missed the network disconnection, transition to mDisconnectedState
8046                     * and handle the rest of the events there.
8047                     */
8048                    StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
8049                    if (stateChangeResult.state == SupplicantState.DISCONNECTED
8050                            || stateChangeResult.state == SupplicantState.INACTIVE
8051                            || stateChangeResult.state == SupplicantState.INTERFACE_DISABLED) {
8052                        if (DBG) {
8053                            log("STATE_CHANGE_EVENT in roaming state "
8054                                    + stateChangeResult.toString() );
8055                        }
8056                        if (stateChangeResult.BSSID != null
8057                                && stateChangeResult.BSSID.equals(mTargetRoamBSSID)) {
8058                            handleNetworkDisconnect();
8059                            transitionTo(mDisconnectedState);
8060                        }
8061                    }
8062                    if (stateChangeResult.state == SupplicantState.ASSOCIATED) {
8063                        // We completed the layer2 roaming part
8064                        mAssociated = true;
8065                        if (stateChangeResult.BSSID != null) {
8066                            mTargetRoamBSSID = (String) stateChangeResult.BSSID;
8067                        }
8068                    }
8069                    break;
8070                case CMD_ROAM_WATCHDOG_TIMER:
8071                    if (roamWatchdogCount == message.arg1) {
8072                        if (DBG) log("roaming watchdog! -> disconnect");
8073                        mRoamFailCount++;
8074                        handleNetworkDisconnect();
8075                        mWifiNative.disconnect();
8076                        transitionTo(mDisconnectedState);
8077                    }
8078                    break;
8079               case WifiMonitor.NETWORK_CONNECTION_EVENT:
8080                   if (mAssociated) {
8081                       if (DBG) log("roaming and Network connection established");
8082                       mLastNetworkId = message.arg1;
8083                       mLastBssid = (String) message.obj;
8084                       mWifiInfo.setBSSID(mLastBssid);
8085                       mWifiInfo.setNetworkId(mLastNetworkId);
8086                       mWifiConfigStore.handleBSSIDBlackList(mLastNetworkId, mLastBssid, true);
8087                       sendNetworkStateChangeBroadcast(mLastBssid);
8088                       transitionTo(mObtainingIpState);
8089                   } else {
8090                       messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
8091                   }
8092                   break;
8093               case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
8094                   // Throw away but only if it corresponds to the network we're roaming to
8095                   String bssid = (String)message.obj;
8096                   if (true) {
8097                       String target = "";
8098                       if (mTargetRoamBSSID != null) target = mTargetRoamBSSID;
8099                       log("NETWORK_DISCONNECTION_EVENT in roaming state"
8100                               + " BSSID=" + bssid
8101                               + " target=" + target);
8102                   }
8103                   if (bssid != null && bssid.equals(mTargetRoamBSSID)) {
8104                       handleNetworkDisconnect();
8105                       transitionTo(mDisconnectedState);
8106                   }
8107                   break;
8108                case WifiMonitor.SSID_TEMP_DISABLED:
8109                    // Auth error while roaming
8110                    loge("SSID_TEMP_DISABLED nid=" + Integer.toString(mLastNetworkId)
8111                            + " id=" + Integer.toString(message.arg1)
8112                            + " isRoaming=" + isRoaming()
8113                            + " roam=" + Integer.toString(mAutoRoaming));
8114                    if (message.arg1 == mLastNetworkId) {
8115                        config = getCurrentWifiConfiguration();
8116                        if (config != null) {
8117                            mWifiLogger.captureBugReportData(
8118                                    WifiLogger.REPORT_REASON_AUTOROAM_FAILURE);
8119                            mWifiConfigStore.noteRoamingFailure(config,
8120                                    WifiConfiguration.ROAMING_FAILURE_AUTH_FAILURE);
8121                        }
8122                        handleNetworkDisconnect();
8123                        transitionTo(mDisconnectingState);
8124                    }
8125                    return NOT_HANDLED;
8126                case CMD_START_SCAN:
8127                    deferMessage(message);
8128                    break;
8129                default:
8130                    return NOT_HANDLED;
8131            }
8132            return HANDLED;
8133        }
8134
8135        @Override
8136        public void exit() {
8137            loge("WifiStateMachine: Leaving Roaming state");
8138        }
8139    }
8140
8141    class ConnectedState extends State {
8142        @Override
8143        public void enter() {
8144            String address;
8145            updateDefaultRouteMacAddress(1000);
8146            if (DBG) {
8147                log("Enter ConnectedState "
8148                       + " mScreenOn=" + mScreenOn
8149                       + " scanperiod="
8150                       + Integer.toString(mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get())
8151                       + " useGscan=" + mHalBasedPnoDriverSupported + "/"
8152                        + mWifiConfigStore.enableHalBasedPno.get()
8153                        + " mHalBasedPnoEnableInDevSettings " + mHalBasedPnoEnableInDevSettings);
8154            }
8155            if (mScreenOn
8156                    && mWifiConfigStore.enableAutoJoinScanWhenAssociated.get()) {
8157                if (useHalBasedAutoJoinOffload()) {
8158                    startGScanConnectedModeOffload("connectedEnter");
8159                } else {
8160                    // restart scan alarm
8161                    startDelayedScan(mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(),
8162                            null, null);
8163                }
8164            }
8165            registerConnected();
8166            lastConnectAttempt = 0;
8167            targetWificonfiguration = null;
8168            // Paranoia
8169            linkDebouncing = false;
8170
8171            // Not roaming anymore
8172            mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE;
8173
8174            if (testNetworkDisconnect) {
8175                testNetworkDisconnectCounter++;
8176                loge("ConnectedState Enter start disconnect test " +
8177                        testNetworkDisconnectCounter);
8178                sendMessageDelayed(obtainMessage(CMD_TEST_NETWORK_DISCONNECT,
8179                        testNetworkDisconnectCounter, 0), 15000);
8180            }
8181
8182            // Reenable all networks, allow for hidden networks to be scanned
8183            mWifiConfigStore.enableAllNetworks();
8184
8185            mLastDriverRoamAttempt = 0;
8186
8187            //startLazyRoam();
8188        }
8189        @Override
8190        public boolean processMessage(Message message) {
8191            WifiConfiguration config = null;
8192            logStateAndMessage(message, getClass().getSimpleName());
8193
8194            switch (message.what) {
8195                case CMD_RESTART_AUTOJOIN_OFFLOAD:
8196                    if ( (int)message.arg2 < mRestartAutoJoinOffloadCounter ) {
8197                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE;
8198                        return HANDLED;
8199                    }
8200                    /* If we are still in Disconnected state after having discovered a valid
8201                     * network this means autojoin didnt managed to associate to the network,
8202                     * then restart PNO so as we will try associating to it again.
8203                     */
8204                    if (useHalBasedAutoJoinOffload()) {
8205                        if (mGScanStartTimeMilli == 0) {
8206                            // If offload is not started, then start it...
8207                            startGScanConnectedModeOffload("connectedRestart");
8208                        } else {
8209                            // If offload is already started, then check if we need to increase
8210                            // the scan period and restart the Gscan
8211                            long now = System.currentTimeMillis();
8212                            if (mGScanStartTimeMilli != 0 && now > mGScanStartTimeMilli
8213                                    && ((now - mGScanStartTimeMilli)
8214                                    > DISCONNECTED_SHORT_SCANS_DURATION_MILLI)
8215                                && (mGScanPeriodMilli
8216                                    < mWifiConfigStore.wifiDisconnectedLongScanIntervalMilli.get()))
8217                            {
8218                                startConnectedGScan("Connected restart gscan");
8219                            }
8220                        }
8221                    }
8222                    break;
8223                case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION:
8224                    updateAssociatedScanPermission();
8225                    break;
8226                case WifiWatchdogStateMachine.POOR_LINK_DETECTED:
8227                    if (DBG) log("Watchdog reports poor link");
8228                    transitionTo(mVerifyingLinkState);
8229                    break;
8230                case CMD_UNWANTED_NETWORK:
8231                    if (message.arg1 == network_status_unwanted_disconnect) {
8232                        mWifiConfigStore.handleBadNetworkDisconnectReport(mLastNetworkId, mWifiInfo);
8233                        mWifiNative.disconnect();
8234                        transitionTo(mDisconnectingState);
8235                    } else if (message.arg1 == network_status_unwanted_disable_autojoin) {
8236                        config = getCurrentWifiConfiguration();
8237                        if (config != null) {
8238                            // Disable autojoin
8239                            config.numNoInternetAccessReports += 1;
8240                            config.dirty = true;
8241                            mWifiConfigStore.writeKnownNetworkHistory(false);
8242                        }
8243                    }
8244                    return HANDLED;
8245                case CMD_NETWORK_STATUS:
8246                    if (message.arg1 == NetworkAgent.VALID_NETWORK) {
8247                        config = getCurrentWifiConfiguration();
8248                        if (config != null) {
8249                            if (!config.validatedInternetAccess
8250                                    || config.numNoInternetAccessReports != 0) {
8251                                config.dirty = true;
8252                            }
8253                            // re-enable autojoin
8254                            config.numNoInternetAccessReports = 0;
8255                            config.validatedInternetAccess = true;
8256                            mWifiConfigStore.writeKnownNetworkHistory(false);
8257                        }
8258                    }
8259                    return HANDLED;
8260                case CMD_TEST_NETWORK_DISCONNECT:
8261                    // Force a disconnect
8262                    if (message.arg1 == testNetworkDisconnectCounter) {
8263                        mWifiNative.disconnect();
8264                    }
8265                    break;
8266                case CMD_ASSOCIATED_BSSID:
8267                    // ASSOCIATING to a new BSSID while already connected, indicates
8268                    // that driver is roaming
8269                    mLastDriverRoamAttempt = System.currentTimeMillis();
8270                    String toBSSID = (String)message.obj;
8271                    if (toBSSID != null && !toBSSID.equals(mWifiInfo.getBSSID())) {
8272                        mWifiConfigStore.driverRoamedFrom(mWifiInfo);
8273                    }
8274                    return NOT_HANDLED;
8275                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
8276                    long lastRoam = 0;
8277                    if (mLastDriverRoamAttempt != 0) {
8278                        // Calculate time since last driver roam attempt
8279                        lastRoam = System.currentTimeMillis() - mLastDriverRoamAttempt;
8280                        mLastDriverRoamAttempt = 0;
8281                    }
8282                    if (unexpectedDisconnectedReason(message.arg2)) {
8283                        mWifiLogger.captureBugReportData(
8284                                WifiLogger.REPORT_REASON_UNEXPECTED_DISCONNECT);
8285                    }
8286                    config = getCurrentWifiConfiguration();
8287                    if (mScreenOn
8288                            && !linkDebouncing
8289                            && config != null
8290                            && config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_ENABLED
8291                            && !mWifiConfigStore.isLastSelectedConfiguration(config)
8292                            && (message.arg2 != 3 /* reason cannot be 3, i.e. locally generated */
8293                                || (lastRoam > 0 && lastRoam < 2000) /* unless driver is roaming */)
8294                            && ((ScanResult.is24GHz(mWifiInfo.getFrequency())
8295                                    && mWifiInfo.getRssi() >
8296                                    WifiConfiguration.BAD_RSSI_24)
8297                                    || (ScanResult.is5GHz(mWifiInfo.getFrequency())
8298                                    && mWifiInfo.getRssi() >
8299                                    WifiConfiguration.BAD_RSSI_5))) {
8300                        // Start de-bouncing the L2 disconnection:
8301                        // this L2 disconnection might be spurious.
8302                        // Hence we allow 7 seconds for the state machine to try
8303                        // to reconnect, go thru the
8304                        // roaming cycle and enter Obtaining IP address
8305                        // before signalling the disconnect to ConnectivityService and L3
8306                        startScanForConfiguration(getCurrentWifiConfiguration(), false);
8307                        linkDebouncing = true;
8308
8309                        sendMessageDelayed(obtainMessage(CMD_DELAYED_NETWORK_DISCONNECT,
8310                                0, mLastNetworkId), LINK_FLAPPING_DEBOUNCE_MSEC);
8311                        if (DBG) {
8312                            log("NETWORK_DISCONNECTION_EVENT in connected state"
8313                                    + " BSSID=" + mWifiInfo.getBSSID()
8314                                    + " RSSI=" + mWifiInfo.getRssi()
8315                                    + " freq=" + mWifiInfo.getFrequency()
8316                                    + " reason=" + message.arg2
8317                                    + " -> debounce");
8318                        }
8319                        return HANDLED;
8320                    } else {
8321                        if (DBG) {
8322                            int ajst = -1;
8323                            if (config != null) ajst = config.autoJoinStatus;
8324                            log("NETWORK_DISCONNECTION_EVENT in connected state"
8325                                    + " BSSID=" + mWifiInfo.getBSSID()
8326                                    + " RSSI=" + mWifiInfo.getRssi()
8327                                    + " freq=" + mWifiInfo.getFrequency()
8328                                    + " was debouncing=" + linkDebouncing
8329                                    + " reason=" + message.arg2
8330                                    + " ajst=" + ajst);
8331                        }
8332                    }
8333                    break;
8334                case CMD_AUTO_ROAM:
8335                    // Clear the driver roam indication since we are attempting a framerwork roam
8336                    mLastDriverRoamAttempt = 0;
8337
8338                    /* Connect command coming from auto-join */
8339                    ScanResult candidate = (ScanResult)message.obj;
8340                    String bssid = "any";
8341                    if (candidate != null && candidate.is5GHz()) {
8342                        // Only lock BSSID for 5GHz networks
8343                        bssid = candidate.BSSID;
8344                    }
8345                    int netId = mLastNetworkId;
8346                    config = getCurrentWifiConfiguration();
8347
8348
8349                    if (config == null) {
8350                        loge("AUTO_ROAM and no config, bail out...");
8351                        break;
8352                    }
8353
8354                    loge("CMD_AUTO_ROAM sup state "
8355                            + mSupplicantStateTracker.getSupplicantStateName()
8356                            + " my state " + getCurrentState().getName()
8357                            + " nid=" + Integer.toString(netId)
8358                            + " config " + config.configKey()
8359                            + " roam=" + Integer.toString(message.arg2)
8360                            + " to " + bssid
8361                            + " targetRoamBSSID " + mTargetRoamBSSID);
8362
8363                    /* Save the BSSID so as to lock it @ firmware */
8364                    if (!autoRoamSetBSSID(config, bssid) && !linkDebouncing) {
8365                        loge("AUTO_ROAM nothing to do");
8366                        // Same BSSID, nothing to do
8367                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
8368                        break;
8369                    };
8370
8371                    // Make sure the network is enabled, since supplicant will not reenable it
8372                    mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false);
8373
8374                    boolean ret = false;
8375                    if (mLastNetworkId != netId) {
8376                       if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ false) &&
8377                           mWifiNative.reconnect()) {
8378                           ret = true;
8379                       }
8380                    } else {
8381                         ret = mWifiNative.reassociate();
8382                    }
8383                    if (ret) {
8384                        lastConnectAttempt = System.currentTimeMillis();
8385                        targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId);
8386
8387                        // replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED);
8388                        mAutoRoaming = message.arg2;
8389                        transitionTo(mRoamingState);
8390
8391                    } else {
8392                        loge("Failed to connect config: " + config + " netId: " + netId);
8393                        replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED,
8394                                WifiManager.ERROR);
8395                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
8396                        break;
8397                    }
8398                    break;
8399                default:
8400                    return NOT_HANDLED;
8401            }
8402            return HANDLED;
8403        }
8404
8405        @Override
8406        public void exit() {
8407            loge("WifiStateMachine: Leaving Connected state");
8408            setScanAlarm(false);
8409            mLastDriverRoamAttempt = 0;
8410
8411            stopLazyRoam();
8412
8413            mWhiteListedSsids = null;
8414        }
8415    }
8416
8417    class DisconnectingState extends State {
8418
8419        @Override
8420        public void enter() {
8421
8422            if (PDBG) {
8423                loge(" Enter DisconnectingState State scan interval "
8424                        + mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get()
8425                        + " mLegacyPnoEnabled= " + mLegacyPnoEnabled
8426                        + " screenOn=" + mScreenOn);
8427            }
8428
8429            // Make sure we disconnect: we enter this state prior connecting to a new
8430            // network, waiting for either a DISCONECT event or a SUPPLICANT_STATE_CHANGE
8431            // event which in this case will be indicating that supplicant started to associate.
8432            // In some cases supplicant doesn't ignore the connect requests (it might not
8433            // find the target SSID in its cache),
8434            // Therefore we end up stuck that state, hence the need for the watchdog.
8435            disconnectingWatchdogCount++;
8436            loge("Start Disconnecting Watchdog " + disconnectingWatchdogCount);
8437            sendMessageDelayed(obtainMessage(CMD_DISCONNECTING_WATCHDOG_TIMER,
8438                    disconnectingWatchdogCount, 0), DISCONNECTING_GUARD_TIMER_MSEC);
8439        }
8440
8441        @Override
8442        public boolean processMessage(Message message) {
8443            logStateAndMessage(message, getClass().getSimpleName());
8444            switch (message.what) {
8445                case CMD_SET_OPERATIONAL_MODE:
8446                    if (message.arg1 != CONNECT_MODE) {
8447                        deferMessage(message);
8448                    }
8449                    break;
8450                case CMD_START_SCAN:
8451                    deferMessage(message);
8452                    return HANDLED;
8453                case CMD_DISCONNECTING_WATCHDOG_TIMER:
8454                    if (disconnectingWatchdogCount == message.arg1) {
8455                        if (DBG) log("disconnecting watchdog! -> disconnect");
8456                        handleNetworkDisconnect();
8457                        transitionTo(mDisconnectedState);
8458                    }
8459                    break;
8460                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
8461                    /**
8462                     * If we get a SUPPLICANT_STATE_CHANGE_EVENT before NETWORK_DISCONNECTION_EVENT
8463                     * we have missed the network disconnection, transition to mDisconnectedState
8464                     * and handle the rest of the events there
8465                     */
8466                    deferMessage(message);
8467                    handleNetworkDisconnect();
8468                    transitionTo(mDisconnectedState);
8469                    break;
8470                default:
8471                    return NOT_HANDLED;
8472            }
8473            return HANDLED;
8474        }
8475    }
8476
8477    class DisconnectedState extends State {
8478        @Override
8479        public void enter() {
8480            // We dont scan frequently if this is a temporary disconnect
8481            // due to p2p
8482            if (mTemporarilyDisconnectWifi) {
8483                mWifiP2pChannel.sendMessage(WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE);
8484                return;
8485            }
8486
8487            if (PDBG) {
8488                loge(" Enter DisconnectedState scan interval "
8489                        + mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get()
8490                        + " mLegacyPnoEnabled= " + mLegacyPnoEnabled
8491                        + " screenOn=" + mScreenOn
8492                        + " useGscan=" + mHalBasedPnoDriverSupported + "/"
8493                        + mWifiConfigStore.enableHalBasedPno.get());
8494            }
8495
8496            /** clear the roaming state, if we were roaming, we failed */
8497            mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE;
8498
8499            if (useHalBasedAutoJoinOffload()) {
8500                startGScanDisconnectedModeOffload("disconnectedEnter");
8501            } else {
8502                if (mScreenOn) {
8503                    /**
8504                     * screen lit and => delayed timer
8505                     */
8506                    startDelayedScan(mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get(),
8507                            null, null);
8508                } else {
8509                    /**
8510                     * screen dark and PNO supported => scan alarm disabled
8511                     */
8512                    if (mBackgroundScanSupported) {
8513                        /* If a regular scan result is pending, do not initiate background
8514                         * scan until the scan results are returned. This is needed because
8515                        * initiating a background scan will cancel the regular scan and
8516                        * scan results will not be returned until background scanning is
8517                        * cleared
8518                        */
8519                        if (!mIsScanOngoing) {
8520                            enableBackgroundScan(true);
8521                        }
8522                    } else {
8523                        setScanAlarm(true);
8524                    }
8525                }
8526            }
8527
8528            /**
8529             * If we have no networks saved, the supplicant stops doing the periodic scan.
8530             * The scans are useful to notify the user of the presence of an open network.
8531             * Note that these are not wake up scans.
8532             */
8533            if (mNoNetworksPeriodicScan != 0 && !mP2pConnected.get()
8534                    && mWifiConfigStore.getConfiguredNetworks().size() == 0) {
8535                sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN,
8536                        ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan);
8537            }
8538
8539            mDisconnectedTimeStamp = System.currentTimeMillis();
8540
8541        }
8542        @Override
8543        public boolean processMessage(Message message) {
8544            boolean ret = HANDLED;
8545
8546            logStateAndMessage(message, getClass().getSimpleName());
8547
8548            switch (message.what) {
8549                case CMD_NO_NETWORKS_PERIODIC_SCAN:
8550                    if (mP2pConnected.get()) break;
8551                    if (mNoNetworksPeriodicScan != 0 && message.arg1 == mPeriodicScanToken &&
8552                            mWifiConfigStore.getConfiguredNetworks().size() == 0) {
8553                        startScan(UNKNOWN_SCAN_SOURCE, -1, null, null);
8554                        sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN,
8555                                    ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan);
8556                    }
8557                    break;
8558                case WifiManager.FORGET_NETWORK:
8559                case CMD_REMOVE_NETWORK:
8560                    // Set up a delayed message here. After the forget/remove is handled
8561                    // the handled delayed message will determine if there is a need to
8562                    // scan and continue
8563                    sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN,
8564                                ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan);
8565                    ret = NOT_HANDLED;
8566                    break;
8567                case CMD_SET_OPERATIONAL_MODE:
8568                    if (message.arg1 != CONNECT_MODE) {
8569                        mOperationalMode = message.arg1;
8570
8571                        mWifiConfigStore.disableAllNetworks();
8572                        if (mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) {
8573                            mWifiP2pChannel.sendMessage(CMD_DISABLE_P2P_REQ);
8574                            setWifiState(WIFI_STATE_DISABLED);
8575                        }
8576                        transitionTo(mScanModeState);
8577                    }
8578                    mWifiConfigStore.
8579                            setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID);
8580                    break;
8581                    /* Ignore network disconnect */
8582                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
8583                    break;
8584                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
8585                    StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
8586                    if (DBG) {
8587                        loge("SUPPLICANT_STATE_CHANGE_EVENT state=" + stateChangeResult.state +
8588                                " -> state= " + WifiInfo.getDetailedStateOf(stateChangeResult.state)
8589                                + " debouncing=" + linkDebouncing);
8590                    }
8591                    setNetworkDetailedState(WifiInfo.getDetailedStateOf(stateChangeResult.state));
8592                    /* ConnectModeState does the rest of the handling */
8593                    ret = NOT_HANDLED;
8594                    break;
8595                case CMD_START_SCAN:
8596                    if (!checkOrDeferScanAllowed(message)) {
8597                        // The scan request was rescheduled
8598                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_REFUSED;
8599                        return HANDLED;
8600                    }
8601                    if (message.arg1 == SCAN_ALARM_SOURCE) {
8602                        // Check if the CMD_START_SCAN message is obsolete (and thus if it should
8603                        // not be processed) and restart the scan
8604                        int period =  mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get();
8605                        if (mP2pConnected.get()) {
8606                           period = (int)Settings.Global.getLong(mContext.getContentResolver(),
8607                                    Settings.Global.WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS,
8608                                    period);
8609                        }
8610                        if (!checkAndRestartDelayedScan(message.arg2,
8611                                true, period, null, null)) {
8612                            messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE;
8613                            loge("WifiStateMachine Disconnected CMD_START_SCAN source "
8614                                    + message.arg1
8615                                    + " " + message.arg2 + ", " + mDelayedScanCounter
8616                                    + " -> obsolete");
8617                            return HANDLED;
8618                        }
8619                        /* Disable background scan temporarily during a regular scan */
8620                        if (mLegacyPnoEnabled) {
8621                            enableBackgroundScan(false);
8622                        }
8623                        handleScanRequest(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message);
8624                        ret = HANDLED;
8625                    } else {
8626
8627                        /*
8628                         * The SCAN request is not handled in this state and
8629                         * would eventually might/will get handled in the
8630                         * parent's state. The PNO, if already enabled had to
8631                         * get disabled before the SCAN trigger. Hence, stop
8632                         * the PNO if already enabled in this state, though the
8633                         * SCAN request is not handled(PNO disable before the
8634                         * SCAN trigger in any other state is not the right
8635                         * place to issue).
8636                         */
8637
8638                        if (mLegacyPnoEnabled) {
8639                            enableBackgroundScan(false);
8640                        }
8641                        ret = NOT_HANDLED;
8642                    }
8643                    break;
8644                case CMD_RESTART_AUTOJOIN_OFFLOAD:
8645                    if ( (int)message.arg2 < mRestartAutoJoinOffloadCounter ) {
8646                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE;
8647                        return HANDLED;
8648                    }
8649                    /* If we are still in Disconnected state after having discovered a valid
8650                     * network this means autojoin didnt managed to associate to the network,
8651                     * then restart PNO so as we will try associating to it again.
8652                     */
8653                    if (useHalBasedAutoJoinOffload()) {
8654                        if (mGScanStartTimeMilli == 0) {
8655                            // If offload is not started, then start it...
8656                            startGScanDisconnectedModeOffload("disconnectedRestart");
8657                        } else {
8658                            // If offload is already started, then check if we need to increase
8659                            // the scan period and restart the Gscan
8660                            long now = System.currentTimeMillis();
8661                            if (mGScanStartTimeMilli != 0 && now > mGScanStartTimeMilli
8662                                    && ((now - mGScanStartTimeMilli)
8663                                    > DISCONNECTED_SHORT_SCANS_DURATION_MILLI)
8664                                    && (mGScanPeriodMilli
8665                                    < mWifiConfigStore.wifiDisconnectedLongScanIntervalMilli.get()))
8666                            {
8667                                startDisconnectedGScan("disconnected restart gscan");
8668                            }
8669                        }
8670                    }
8671                    break;
8672                case WifiMonitor.SCAN_RESULTS_EVENT:
8673                case WifiMonitor.SCAN_FAILED_EVENT:
8674                    /* Re-enable background scan when a pending scan result is received */
8675                    if (!mScreenOn && mIsScanOngoing
8676                            && mBackgroundScanSupported
8677                            && !useHalBasedAutoJoinOffload()) {
8678                        enableBackgroundScan(true);
8679                    }
8680                    /* Handled in parent state */
8681                    ret = NOT_HANDLED;
8682                    break;
8683                case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED:
8684                    NetworkInfo info = (NetworkInfo) message.obj;
8685                    mP2pConnected.set(info.isConnected());
8686                    if (mP2pConnected.get()) {
8687                        int defaultInterval = mContext.getResources().getInteger(
8688                                R.integer.config_wifi_scan_interval_p2p_connected);
8689                        long scanIntervalMs = Settings.Global.getLong(mContext.getContentResolver(),
8690                                Settings.Global.WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS,
8691                                defaultInterval);
8692                        mWifiNative.setScanInterval((int) scanIntervalMs/1000);
8693                    } else if (mWifiConfigStore.getConfiguredNetworks().size() == 0) {
8694                        if (DBG) log("Turn on scanning after p2p disconnected");
8695                        sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN,
8696                                    ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan);
8697                    } else {
8698                        // If P2P is not connected and there are saved networks, then restart
8699                        // scanning at the normal period. This is necessary because scanning might
8700                        // have been disabled altogether if WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS
8701                        // was set to zero.
8702                        if (useHalBasedAutoJoinOffload()) {
8703                            startGScanDisconnectedModeOffload("p2pRestart");
8704                        } else {
8705                            startDelayedScan(
8706                                    mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get(),
8707                                    null, null);
8708                        }
8709                    }
8710                    break;
8711                case CMD_RECONNECT:
8712                case CMD_REASSOCIATE:
8713                    if (mTemporarilyDisconnectWifi) {
8714                        // Drop a third party reconnect/reassociate if STA is
8715                        // temporarily disconnected for p2p
8716                        break;
8717                    } else {
8718                        // ConnectModeState handles it
8719                        ret = NOT_HANDLED;
8720                    }
8721                    break;
8722                case CMD_SCREEN_STATE_CHANGED:
8723                    handleScreenStateChanged(message.arg1 != 0);
8724                    break;
8725                default:
8726                    ret = NOT_HANDLED;
8727            }
8728            return ret;
8729        }
8730
8731        @Override
8732        public void exit() {
8733            /* No need for a background scan upon exit from a disconnected state */
8734            if (mLegacyPnoEnabled) {
8735                enableBackgroundScan(false);
8736            }
8737            setScanAlarm(false);
8738        }
8739    }
8740
8741    class WpsRunningState extends State {
8742        // Tracks the source to provide a reply
8743        private Message mSourceMessage;
8744        @Override
8745        public void enter() {
8746            mSourceMessage = Message.obtain(getCurrentMessage());
8747        }
8748        @Override
8749        public boolean processMessage(Message message) {
8750            logStateAndMessage(message, getClass().getSimpleName());
8751
8752            switch (message.what) {
8753                case WifiMonitor.WPS_SUCCESS_EVENT:
8754                    // Ignore intermediate success, wait for full connection
8755                    break;
8756                case WifiMonitor.NETWORK_CONNECTION_EVENT:
8757                    replyToMessage(mSourceMessage, WifiManager.WPS_COMPLETED);
8758                    mSourceMessage.recycle();
8759                    mSourceMessage = null;
8760                    deferMessage(message);
8761                    transitionTo(mDisconnectedState);
8762                    break;
8763                case WifiMonitor.WPS_OVERLAP_EVENT:
8764                    replyToMessage(mSourceMessage, WifiManager.WPS_FAILED,
8765                            WifiManager.WPS_OVERLAP_ERROR);
8766                    mSourceMessage.recycle();
8767                    mSourceMessage = null;
8768                    transitionTo(mDisconnectedState);
8769                    break;
8770                case WifiMonitor.WPS_FAIL_EVENT:
8771                    // Arg1 has the reason for the failure
8772                    if ((message.arg1 != WifiManager.ERROR) || (message.arg2 != 0)) {
8773                        replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, message.arg1);
8774                        mSourceMessage.recycle();
8775                        mSourceMessage = null;
8776                        transitionTo(mDisconnectedState);
8777                    } else {
8778                        if (DBG) log("Ignore unspecified fail event during WPS connection");
8779                    }
8780                    break;
8781                case WifiMonitor.WPS_TIMEOUT_EVENT:
8782                    replyToMessage(mSourceMessage, WifiManager.WPS_FAILED,
8783                            WifiManager.WPS_TIMED_OUT);
8784                    mSourceMessage.recycle();
8785                    mSourceMessage = null;
8786                    transitionTo(mDisconnectedState);
8787                    break;
8788                case WifiManager.START_WPS:
8789                    replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.IN_PROGRESS);
8790                    break;
8791                case WifiManager.CANCEL_WPS:
8792                    if (mWifiNative.cancelWps()) {
8793                        replyToMessage(message, WifiManager.CANCEL_WPS_SUCCEDED);
8794                    } else {
8795                        replyToMessage(message, WifiManager.CANCEL_WPS_FAILED, WifiManager.ERROR);
8796                    }
8797                    transitionTo(mDisconnectedState);
8798                    break;
8799                /**
8800                 * Defer all commands that can cause connections to a different network
8801                 * or put the state machine out of connect mode
8802                 */
8803                case CMD_STOP_DRIVER:
8804                case CMD_SET_OPERATIONAL_MODE:
8805                case WifiManager.CONNECT_NETWORK:
8806                case CMD_ENABLE_NETWORK:
8807                case CMD_RECONNECT:
8808                case CMD_REASSOCIATE:
8809                    deferMessage(message);
8810                    break;
8811                case CMD_AUTO_CONNECT:
8812                case CMD_AUTO_ROAM:
8813                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
8814                    return HANDLED;
8815                case CMD_START_SCAN:
8816                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
8817                    return HANDLED;
8818                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
8819                    if (DBG) log("Network connection lost");
8820                    handleNetworkDisconnect();
8821                    break;
8822                case WifiMonitor.ASSOCIATION_REJECTION_EVENT:
8823                    if (DBG) log("Ignore Assoc reject event during WPS Connection");
8824                    break;
8825                case WifiMonitor.AUTHENTICATION_FAILURE_EVENT:
8826                    // Disregard auth failure events during WPS connection. The
8827                    // EAP sequence is retried several times, and there might be
8828                    // failures (especially for wps pin). We will get a WPS_XXX
8829                    // event at the end of the sequence anyway.
8830                    if (DBG) log("Ignore auth failure during WPS connection");
8831                    break;
8832                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
8833                    // Throw away supplicant state changes when WPS is running.
8834                    // We will start getting supplicant state changes once we get
8835                    // a WPS success or failure
8836                    break;
8837                default:
8838                    return NOT_HANDLED;
8839            }
8840            return HANDLED;
8841        }
8842
8843        @Override
8844        public void exit() {
8845            mWifiConfigStore.enableAllNetworks();
8846            mWifiConfigStore.loadConfiguredNetworks();
8847        }
8848    }
8849
8850    class SoftApStartingState extends State {
8851        @Override
8852        public void enter() {
8853            final Message message = getCurrentMessage();
8854            if (message.what == CMD_START_AP) {
8855                final WifiConfiguration config = (WifiConfiguration) message.obj;
8856
8857                if (config == null) {
8858                    mWifiApConfigChannel.sendMessage(CMD_REQUEST_AP_CONFIG);
8859                } else {
8860                    mWifiApConfigChannel.sendMessage(CMD_SET_AP_CONFIG, config);
8861                    startSoftApWithConfig(config);
8862                }
8863            } else {
8864                throw new RuntimeException("Illegal transition to SoftApStartingState: " + message);
8865            }
8866        }
8867        @Override
8868        public boolean processMessage(Message message) {
8869            logStateAndMessage(message, getClass().getSimpleName());
8870
8871            switch(message.what) {
8872                case CMD_START_SUPPLICANT:
8873                case CMD_STOP_SUPPLICANT:
8874                case CMD_START_AP:
8875                case CMD_STOP_AP:
8876                case CMD_START_DRIVER:
8877                case CMD_STOP_DRIVER:
8878                case CMD_SET_OPERATIONAL_MODE:
8879                case CMD_SET_COUNTRY_CODE:
8880                case CMD_SET_FREQUENCY_BAND:
8881                case CMD_START_PACKET_FILTERING:
8882                case CMD_STOP_PACKET_FILTERING:
8883                case CMD_TETHER_STATE_CHANGE:
8884                    deferMessage(message);
8885                    break;
8886                case WifiStateMachine.CMD_RESPONSE_AP_CONFIG:
8887                    WifiConfiguration config = (WifiConfiguration) message.obj;
8888                    if (config != null) {
8889                        startSoftApWithConfig(config);
8890                    } else {
8891                        loge("Softap config is null!");
8892                        sendMessage(CMD_START_AP_FAILURE);
8893                    }
8894                    break;
8895                case CMD_START_AP_SUCCESS:
8896                    setWifiApState(WIFI_AP_STATE_ENABLED);
8897                    transitionTo(mSoftApStartedState);
8898                    break;
8899                case CMD_START_AP_FAILURE:
8900                    setWifiApState(WIFI_AP_STATE_FAILED);
8901                    transitionTo(mInitialState);
8902                    break;
8903                default:
8904                    return NOT_HANDLED;
8905            }
8906            return HANDLED;
8907        }
8908    }
8909
8910    class SoftApStartedState extends State {
8911        @Override
8912        public boolean processMessage(Message message) {
8913            logStateAndMessage(message, getClass().getSimpleName());
8914
8915            switch(message.what) {
8916                case CMD_STOP_AP:
8917                    if (DBG) log("Stopping Soft AP");
8918                    /* We have not tethered at this point, so we just shutdown soft Ap */
8919                    try {
8920                        mNwService.stopAccessPoint(mInterfaceName);
8921                    } catch(Exception e) {
8922                        loge("Exception in stopAccessPoint()");
8923                    }
8924                    setWifiApState(WIFI_AP_STATE_DISABLED);
8925                    transitionTo(mInitialState);
8926                    break;
8927                case CMD_START_AP:
8928                    // Ignore a start on a running access point
8929                    break;
8930                    // Fail client mode operation when soft AP is enabled
8931                case CMD_START_SUPPLICANT:
8932                    loge("Cannot start supplicant with a running soft AP");
8933                    setWifiState(WIFI_STATE_UNKNOWN);
8934                    break;
8935                case CMD_TETHER_STATE_CHANGE:
8936                    TetherStateChange stateChange = (TetherStateChange) message.obj;
8937                    if (startTethering(stateChange.available)) {
8938                        transitionTo(mTetheringState);
8939                    }
8940                    break;
8941                default:
8942                    return NOT_HANDLED;
8943            }
8944            return HANDLED;
8945        }
8946    }
8947
8948    class TetheringState extends State {
8949        @Override
8950        public void enter() {
8951            /* Send ourselves a delayed message to shut down if tethering fails to notify */
8952            sendMessageDelayed(obtainMessage(CMD_TETHER_NOTIFICATION_TIMED_OUT,
8953                    ++mTetherToken, 0), TETHER_NOTIFICATION_TIME_OUT_MSECS);
8954        }
8955        @Override
8956        public boolean processMessage(Message message) {
8957            logStateAndMessage(message, getClass().getSimpleName());
8958
8959            switch(message.what) {
8960                case CMD_TETHER_STATE_CHANGE:
8961                    TetherStateChange stateChange = (TetherStateChange) message.obj;
8962                    if (isWifiTethered(stateChange.active)) {
8963                        transitionTo(mTetheredState);
8964                    }
8965                    return HANDLED;
8966                case CMD_TETHER_NOTIFICATION_TIMED_OUT:
8967                    if (message.arg1 == mTetherToken) {
8968                        loge("Failed to get tether update, shutdown soft access point");
8969                        transitionTo(mSoftApStartedState);
8970                        // Needs to be first thing handled
8971                        sendMessageAtFrontOfQueue(CMD_STOP_AP);
8972                    }
8973                    break;
8974                case CMD_START_SUPPLICANT:
8975                case CMD_STOP_SUPPLICANT:
8976                case CMD_START_AP:
8977                case CMD_STOP_AP:
8978                case CMD_START_DRIVER:
8979                case CMD_STOP_DRIVER:
8980                case CMD_SET_OPERATIONAL_MODE:
8981                case CMD_SET_COUNTRY_CODE:
8982                case CMD_SET_FREQUENCY_BAND:
8983                case CMD_START_PACKET_FILTERING:
8984                case CMD_STOP_PACKET_FILTERING:
8985                    deferMessage(message);
8986                    break;
8987                default:
8988                    return NOT_HANDLED;
8989            }
8990            return HANDLED;
8991        }
8992    }
8993
8994    class TetheredState extends State {
8995        @Override
8996        public boolean processMessage(Message message) {
8997            logStateAndMessage(message, getClass().getSimpleName());
8998
8999            switch(message.what) {
9000                case CMD_TETHER_STATE_CHANGE:
9001                    TetherStateChange stateChange = (TetherStateChange) message.obj;
9002                    if (!isWifiTethered(stateChange.active)) {
9003                        loge("Tethering reports wifi as untethered!, shut down soft Ap");
9004                        setHostApRunning(null, false);
9005                        setHostApRunning(null, true);
9006                    }
9007                    return HANDLED;
9008                case CMD_STOP_AP:
9009                    if (DBG) log("Untethering before stopping AP");
9010                    setWifiApState(WIFI_AP_STATE_DISABLING);
9011                    stopTethering();
9012                    transitionTo(mUntetheringState);
9013                    // More work to do after untethering
9014                    deferMessage(message);
9015                    break;
9016                default:
9017                    return NOT_HANDLED;
9018            }
9019            return HANDLED;
9020        }
9021    }
9022
9023    class UntetheringState extends State {
9024        @Override
9025        public void enter() {
9026            /* Send ourselves a delayed message to shut down if tethering fails to notify */
9027            sendMessageDelayed(obtainMessage(CMD_TETHER_NOTIFICATION_TIMED_OUT,
9028                    ++mTetherToken, 0), TETHER_NOTIFICATION_TIME_OUT_MSECS);
9029
9030        }
9031        @Override
9032        public boolean processMessage(Message message) {
9033            logStateAndMessage(message, getClass().getSimpleName());
9034
9035            switch(message.what) {
9036                case CMD_TETHER_STATE_CHANGE:
9037                    TetherStateChange stateChange = (TetherStateChange) message.obj;
9038
9039                    /* Wait till wifi is untethered */
9040                    if (isWifiTethered(stateChange.active)) break;
9041
9042                    transitionTo(mSoftApStartedState);
9043                    break;
9044                case CMD_TETHER_NOTIFICATION_TIMED_OUT:
9045                    if (message.arg1 == mTetherToken) {
9046                        loge("Failed to get tether update, force stop access point");
9047                        transitionTo(mSoftApStartedState);
9048                    }
9049                    break;
9050                case CMD_START_SUPPLICANT:
9051                case CMD_STOP_SUPPLICANT:
9052                case CMD_START_AP:
9053                case CMD_STOP_AP:
9054                case CMD_START_DRIVER:
9055                case CMD_STOP_DRIVER:
9056                case CMD_SET_OPERATIONAL_MODE:
9057                case CMD_SET_COUNTRY_CODE:
9058                case CMD_SET_FREQUENCY_BAND:
9059                case CMD_START_PACKET_FILTERING:
9060                case CMD_STOP_PACKET_FILTERING:
9061                    deferMessage(message);
9062                    break;
9063                default:
9064                    return NOT_HANDLED;
9065            }
9066            return HANDLED;
9067        }
9068    }
9069
9070    //State machine initiated requests can have replyTo set to null indicating
9071    //there are no recepients, we ignore those reply actions
9072    private void replyToMessage(Message msg, int what) {
9073        if (msg.replyTo == null) return;
9074        Message dstMsg = obtainMessageWithArg2(msg);
9075        dstMsg.what = what;
9076        mReplyChannel.replyToMessage(msg, dstMsg);
9077    }
9078
9079    private void replyToMessage(Message msg, int what, int arg1) {
9080        if (msg.replyTo == null) return;
9081        Message dstMsg = obtainMessageWithArg2(msg);
9082        dstMsg.what = what;
9083        dstMsg.arg1 = arg1;
9084        mReplyChannel.replyToMessage(msg, dstMsg);
9085    }
9086
9087    private void replyToMessage(Message msg, int what, Object obj) {
9088        if (msg.replyTo == null) return;
9089        Message dstMsg = obtainMessageWithArg2(msg);
9090        dstMsg.what = what;
9091        dstMsg.obj = obj;
9092        mReplyChannel.replyToMessage(msg, dstMsg);
9093    }
9094
9095    /**
9096     * arg2 on the source message has a unique id that needs to be retained in replies
9097     * to match the request
9098
9099     * see WifiManager for details
9100     */
9101    private Message obtainMessageWithArg2(Message srcMsg) {
9102        Message msg = Message.obtain();
9103        msg.arg2 = srcMsg.arg2;
9104        return msg;
9105    }
9106
9107    private static int parseHex(char ch) {
9108        if ('0' <= ch && ch <= '9') {
9109            return ch - '0';
9110        } else if ('a' <= ch && ch <= 'f') {
9111            return ch - 'a' + 10;
9112        } else if ('A' <= ch && ch <= 'F') {
9113            return ch - 'A' + 10;
9114        } else {
9115            throw new NumberFormatException("" + ch + " is not a valid hex digit");
9116        }
9117    }
9118
9119    private byte[] parseHex(String hex) {
9120        /* This only works for good input; don't throw bad data at it */
9121        if (hex == null) {
9122            return new byte[0];
9123        }
9124
9125        if (hex.length() % 2 != 0) {
9126            throw new NumberFormatException(hex + " is not a valid hex string");
9127        }
9128
9129        byte[] result = new byte[(hex.length())/2 + 1];
9130        result[0] = (byte) ((hex.length())/2);
9131        for (int i = 0, j = 1; i < hex.length(); i += 2, j++) {
9132            int val = parseHex(hex.charAt(i)) * 16 + parseHex(hex.charAt(i+1));
9133            byte b = (byte) (val & 0xFF);
9134            result[j] = b;
9135        }
9136
9137        return result;
9138    }
9139
9140    private static String makeHex(byte[] bytes) {
9141        StringBuilder sb = new StringBuilder();
9142        for (byte b : bytes) {
9143            sb.append(String.format("%02x", b));
9144        }
9145        return sb.toString();
9146    }
9147
9148    private static String makeHex(byte[] bytes, int from, int len) {
9149        StringBuilder sb = new StringBuilder();
9150        for (int i = 0; i < len; i++) {
9151            sb.append(String.format("%02x", bytes[from+i]));
9152        }
9153        return sb.toString();
9154    }
9155
9156    private static byte[] concat(byte[] array1, byte[] array2, byte[] array3) {
9157
9158        int len = array1.length + array2.length + array3.length;
9159
9160        if (array1.length != 0) {
9161            len++;                      /* add another byte for size */
9162        }
9163
9164        if (array2.length != 0) {
9165            len++;                      /* add another byte for size */
9166        }
9167
9168        if (array3.length != 0) {
9169            len++;                      /* add another byte for size */
9170        }
9171
9172        byte[] result = new byte[len];
9173
9174        int index = 0;
9175        if (array1.length != 0) {
9176            result[index] = (byte) (array1.length & 0xFF);
9177            index++;
9178            for (byte b : array1) {
9179                result[index] = b;
9180                index++;
9181            }
9182        }
9183
9184        if (array2.length != 0) {
9185            result[index] = (byte) (array2.length & 0xFF);
9186            index++;
9187            for (byte b : array2) {
9188                result[index] = b;
9189                index++;
9190            }
9191        }
9192
9193        if (array3.length != 0) {
9194            result[index] = (byte) (array3.length & 0xFF);
9195            index++;
9196            for (byte b : array3) {
9197                result[index] = b;
9198                index++;
9199            }
9200        }
9201        return result;
9202    }
9203
9204    private static byte[] concatHex(byte[] array1, byte[] array2) {
9205
9206        int len = array1.length + array2.length;
9207
9208        byte[] result = new byte[len];
9209
9210        int index = 0;
9211        if (array1.length != 0) {
9212            for (byte b : array1) {
9213                result[index] = b;
9214                index++;
9215            }
9216        }
9217
9218        if (array2.length != 0) {
9219            for (byte b : array2) {
9220                result[index] = b;
9221                index++;
9222            }
9223        }
9224
9225        return result;
9226    }
9227
9228    void handleGsmAuthRequest(SimAuthRequestData requestData) {
9229        if (targetWificonfiguration == null
9230                || targetWificonfiguration.networkId == requestData.networkId) {
9231            logd("id matches targetWifiConfiguration");
9232        } else {
9233            logd("id does not match targetWifiConfiguration");
9234            return;
9235        }
9236
9237        TelephonyManager tm = (TelephonyManager)
9238                mContext.getSystemService(Context.TELEPHONY_SERVICE);
9239
9240        if (tm != null) {
9241            StringBuilder sb = new StringBuilder();
9242            for (String challenge : requestData.data) {
9243
9244                if (challenge == null || challenge.isEmpty())
9245                    continue;
9246                logd("RAND = " + challenge);
9247
9248                byte[] rand = null;
9249                try {
9250                    rand = parseHex(challenge);
9251                } catch (NumberFormatException e) {
9252                    loge("malformed challenge");
9253                    continue;
9254                }
9255
9256                String base64Challenge = android.util.Base64.encodeToString(
9257                        rand, android.util.Base64.NO_WRAP);
9258                /*
9259                 * First, try with appType = 2 => USIM according to
9260                 * com.android.internal.telephony.PhoneConstants#APPTYPE_xxx
9261                 */
9262                int appType = 2;
9263                String tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge);
9264                if (tmResponse == null) {
9265                    /* Then, in case of failure, issue may be due to sim type, retry as a simple sim
9266                     * appType = 1 => SIM
9267                     */
9268                    appType = 1;
9269                    tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge);
9270                }
9271                logv("Raw Response - " + tmResponse);
9272
9273                if (tmResponse != null && tmResponse.length() > 4) {
9274                    byte[] result = android.util.Base64.decode(tmResponse,
9275                            android.util.Base64.DEFAULT);
9276                    logv("Hex Response -" + makeHex(result));
9277                    int sres_len = result[0];
9278                    String sres = makeHex(result, 1, sres_len);
9279                    int kc_offset = 1+sres_len;
9280                    int kc_len = result[kc_offset];
9281                    String kc = makeHex(result, 1+kc_offset, kc_len);
9282                    sb.append(":" + kc + ":" + sres);
9283                    logv("kc:" + kc + " sres:" + sres);
9284                } else {
9285                    loge("bad response - " + tmResponse);
9286                }
9287            }
9288
9289            String response = sb.toString();
9290            logv("Supplicant Response -" + response);
9291            mWifiNative.simAuthResponse(requestData.networkId, "GSM-AUTH", response);
9292        } else {
9293            loge("could not get telephony manager");
9294        }
9295    }
9296
9297    void handle3GAuthRequest(SimAuthRequestData requestData) {
9298        StringBuilder sb = new StringBuilder();
9299        byte[] rand = null;
9300        byte[] authn = null;
9301        String res_type = "UMTS-AUTH";
9302
9303        if (targetWificonfiguration == null
9304                || targetWificonfiguration.networkId == requestData.networkId) {
9305            logd("id matches targetWifiConfiguration");
9306        } else {
9307            logd("id does not match targetWifiConfiguration");
9308            return;
9309        }
9310        if (requestData.data.length == 2) {
9311            try {
9312                rand = parseHex(requestData.data[0]);
9313                authn = parseHex(requestData.data[1]);
9314            } catch (NumberFormatException e) {
9315                loge("malformed challenge");
9316            }
9317        } else {
9318               loge("malformed challenge");
9319        }
9320
9321        String tmResponse = "";
9322        if (rand != null && authn != null) {
9323            String base64Challenge = android.util.Base64.encodeToString(
9324                    concatHex(rand,authn), android.util.Base64.NO_WRAP);
9325
9326            TelephonyManager tm = (TelephonyManager)
9327                    mContext.getSystemService(Context.TELEPHONY_SERVICE);
9328            if (tm != null) {
9329                int appType = 2; // 2 => USIM
9330                tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge);
9331                logv("Raw Response - " + tmResponse);
9332            } else {
9333                loge("could not get telephony manager");
9334            }
9335        }
9336
9337        if (tmResponse != null && tmResponse.length() > 4) {
9338            byte[] result = android.util.Base64.decode(tmResponse,
9339                    android.util.Base64.DEFAULT);
9340            loge("Hex Response - " + makeHex(result));
9341            byte tag = result[0];
9342            if (tag == (byte) 0xdb) {
9343                logv("successful 3G authentication ");
9344                int res_len = result[1];
9345                String res = makeHex(result, 2, res_len);
9346                int ck_len = result[res_len + 2];
9347                String ck = makeHex(result, res_len + 3, ck_len);
9348                int ik_len = result[res_len + ck_len + 3];
9349                String ik = makeHex(result, res_len + ck_len + 4, ik_len);
9350                sb.append(":" + ik + ":" + ck + ":" + res);
9351                logv("ik:" + ik + "ck:" + ck + " res:" + res);
9352            } else if (tag == (byte) 0xdc) {
9353                loge("synchronisation failure");
9354                int auts_len = result[1];
9355                String auts = makeHex(result, 2, auts_len);
9356                res_type = "UMTS-AUTS";
9357                sb.append(":" + auts);
9358                logv("auts:" + auts);
9359            } else {
9360                loge("bad response - unknown tag = " + tag);
9361                return;
9362            }
9363        } else {
9364            loge("bad response - " + tmResponse);
9365            return;
9366        }
9367
9368        String response = sb.toString();
9369        logv("Supplicant Response -" + response);
9370        mWifiNative.simAuthResponse(requestData.networkId, res_type, response);
9371    }
9372
9373    /**
9374     * @param reason reason code from supplicant on network disconnected event
9375     * @return true if this is a suspicious disconnect
9376     */
9377    static boolean unexpectedDisconnectedReason(int reason) {
9378        return reason == 2              // PREV_AUTH_NOT_VALID
9379                || reason == 6          // CLASS2_FRAME_FROM_NONAUTH_STA
9380                || reason == 7          // FRAME_FROM_NONASSOC_STA
9381                || reason == 8          // STA_HAS_LEFT
9382                || reason == 9          // STA_REQ_ASSOC_WITHOUT_AUTH
9383                || reason == 14         // MICHAEL_MIC_FAILURE
9384                || reason == 15         // 4WAY_HANDSHAKE_TIMEOUT
9385                || reason == 16         // GROUP_KEY_UPDATE_TIMEOUT
9386                || reason == 18         // GROUP_CIPHER_NOT_VALID
9387                || reason == 19         // PAIRWISE_CIPHER_NOT_VALID
9388                || reason == 23         // IEEE_802_1X_AUTH_FAILED
9389                || reason == 34;        // DISASSOC_LOW_ACK
9390    }
9391}
9392