WifiStateMachine.java revision f91a96259d1fbdfb9af907dd20cf905a8da3a119
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;
28import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN;
29
30import android.Manifest;
31import android.app.ActivityManager;
32import android.app.PendingIntent;
33import android.bluetooth.BluetoothAdapter;
34import android.content.BroadcastReceiver;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.pm.ApplicationInfo;
39import android.content.pm.IPackageManager;
40import android.content.pm.PackageManager;
41import android.database.ContentObserver;
42import android.net.ConnectivityManager;
43import android.net.DhcpResults;
44import android.net.IpConfiguration;
45import android.net.LinkProperties;
46import android.net.Network;
47import android.net.NetworkAgent;
48import android.net.NetworkCapabilities;
49import android.net.NetworkFactory;
50import android.net.NetworkInfo;
51import android.net.NetworkInfo.DetailedState;
52import android.net.NetworkMisc;
53import android.net.NetworkRequest;
54import android.net.NetworkUtils;
55import android.net.RouteInfo;
56import android.net.StaticIpConfiguration;
57import android.net.TrafficStats;
58import android.net.dhcp.DhcpClient;
59import android.net.ip.IpManager;
60import android.net.wifi.IApInterface;
61import android.net.wifi.IClientInterface;
62import android.net.wifi.RssiPacketCountInfo;
63import android.net.wifi.ScanResult;
64import android.net.wifi.ScanSettings;
65import android.net.wifi.SupplicantState;
66import android.net.wifi.WifiChannel;
67import android.net.wifi.WifiConfiguration;
68import android.net.wifi.WifiConnectionStatistics;
69import android.net.wifi.WifiEnterpriseConfig;
70import android.net.wifi.WifiInfo;
71import android.net.wifi.WifiLinkLayerStats;
72import android.net.wifi.WifiManager;
73import android.net.wifi.WifiScanner;
74import android.net.wifi.WifiSsid;
75import android.net.wifi.WpsInfo;
76import android.net.wifi.WpsResult;
77import android.net.wifi.WpsResult.Status;
78import android.net.wifi.p2p.IWifiP2pManager;
79import android.os.BatteryStats;
80import android.os.Binder;
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.UserHandle;
91import android.os.UserManager;
92import android.os.WorkSource;
93import android.provider.Settings;
94import android.telephony.TelephonyManager;
95import android.text.TextUtils;
96import android.util.Log;
97import android.util.SparseArray;
98
99import com.android.internal.R;
100import com.android.internal.annotations.GuardedBy;
101import com.android.internal.annotations.VisibleForTesting;
102import com.android.internal.app.IBatteryStats;
103import com.android.internal.util.AsyncChannel;
104import com.android.internal.util.MessageUtils;
105import com.android.internal.util.Protocol;
106import com.android.internal.util.State;
107import com.android.internal.util.StateMachine;
108import com.android.server.connectivity.KeepalivePacketData;
109import com.android.server.wifi.hotspot2.AnqpEvent;
110import com.android.server.wifi.hotspot2.IconEvent;
111import com.android.server.wifi.hotspot2.NetworkDetail;
112import com.android.server.wifi.hotspot2.PasspointManager;
113import com.android.server.wifi.hotspot2.Utils;
114import com.android.server.wifi.hotspot2.WnmData;
115import com.android.server.wifi.p2p.WifiP2pServiceImpl;
116import com.android.server.wifi.util.NativeUtil;
117import com.android.server.wifi.util.TelephonyUtil;
118import com.android.server.wifi.util.TelephonyUtil.SimAuthRequestData;
119import com.android.server.wifi.util.TelephonyUtil.SimAuthResponseData;
120
121import java.io.BufferedReader;
122import java.io.FileDescriptor;
123import java.io.FileNotFoundException;
124import java.io.FileReader;
125import java.io.IOException;
126import java.io.PrintWriter;
127import java.net.Inet4Address;
128import java.net.InetAddress;
129import java.util.ArrayList;
130import java.util.Arrays;
131import java.util.HashSet;
132import java.util.LinkedList;
133import java.util.List;
134import java.util.Queue;
135import java.util.Set;
136import java.util.concurrent.atomic.AtomicBoolean;
137import java.util.concurrent.atomic.AtomicInteger;
138
139/**
140 * TODO:
141 * Deprecate WIFI_STATE_UNKNOWN
142 */
143
144/**
145 * Track the state of Wifi connectivity. All event handling is done here,
146 * and all changes in connectivity state are initiated here.
147 *
148 * Wi-Fi now supports three modes of operation: Client, SoftAp and p2p
149 * In the current implementation, we support concurrent wifi p2p and wifi operation.
150 * The WifiStateMachine handles SoftAp and Client operations while WifiP2pService
151 * handles p2p operation.
152 *
153 * @hide
154 */
155public class WifiStateMachine extends StateMachine implements WifiNative.WifiRssiEventHandler,
156        WifiMulticastLockManager.FilterController {
157
158    private static final String NETWORKTYPE = "WIFI";
159    private static final String NETWORKTYPE_UNTRUSTED = "WIFI_UT";
160    @VisibleForTesting public static final short NUM_LOG_RECS_NORMAL = 100;
161    @VisibleForTesting public static final short NUM_LOG_RECS_VERBOSE_LOW_MEMORY = 200;
162    @VisibleForTesting public static final short NUM_LOG_RECS_VERBOSE = 3000;
163    private static final String TAG = "WifiStateMachine";
164
165    private static final int ONE_HOUR_MILLI = 1000 * 60 * 60;
166
167    private static final String GOOGLE_OUI = "DA-A1-19";
168
169    private static final String EXTRA_OSU_ICON_QUERY_BSSID = "BSSID";
170    private static final String EXTRA_OSU_ICON_QUERY_FILENAME = "FILENAME";
171
172    private boolean mVerboseLoggingEnabled = false;
173
174    /* debug flag, indicating if handling of ASSOCIATION_REJECT ended up blacklisting
175     * the corresponding BSSID.
176     */
177    private boolean didBlackListBSSID = false;
178
179    /**
180     * Log with error attribute
181     *
182     * @param s is string log
183     */
184    @Override
185    protected void loge(String s) {
186        Log.e(getName(), s);
187    }
188    @Override
189    protected void logd(String s) {
190        Log.d(getName(), s);
191    }
192    @Override
193    protected void log(String s) {
194        Log.d(getName(), s);
195    }
196    private WifiMetrics mWifiMetrics;
197    private WifiInjector mWifiInjector;
198    private WifiMonitor mWifiMonitor;
199    private WifiNative mWifiNative;
200    private WifiConfigManager mWifiConfigManager;
201    private WifiConnectivityManager mWifiConnectivityManager;
202    private WifiNetworkSelector mWifiNetworkSelector;
203    private INetworkManagementService mNwService;
204    private IClientInterface mClientInterface;
205    private ConnectivityManager mCm;
206    private BaseWifiDiagnostics mWifiDiagnostics;
207    private WifiApConfigStore mWifiApConfigStore;
208    private final boolean mP2pSupported;
209    private final AtomicBoolean mP2pConnected = new AtomicBoolean(false);
210    private boolean mTemporarilyDisconnectWifi = false;
211    private final String mPrimaryDeviceType;
212    private final Clock mClock;
213    private final PropertyService mPropertyService;
214    private final BuildProperties mBuildProperties;
215    private final WifiCountryCode mCountryCode;
216    // Object holding most recent wifi score report and bad Linkspeed count
217    private final WifiScoreReport mWifiScoreReport;
218    private final PasspointManager mPasspointManager;
219
220    /* Scan results handling */
221    private List<ScanDetail> mScanResults = new ArrayList<>();
222    private final Object mScanResultsLock = new Object();
223
224    // For debug, number of known scan results that were found as part of last scan result event,
225    // as well the number of scans results returned by the supplicant with that message
226    private int mNumScanResultsKnown;
227    private int mNumScanResultsReturned;
228
229    private boolean mScreenOn = false;
230
231    private final String mInterfaceName;
232
233    private int mLastSignalLevel = -1;
234    private String mLastBssid;
235    private int mLastNetworkId; // The network Id we successfully joined
236    private boolean mIsLinkDebouncing = false;
237    private final StateMachineDeathRecipient mDeathRecipient =
238            new StateMachineDeathRecipient(this, CMD_CLIENT_INTERFACE_BINDER_DEATH);
239    private boolean mIpReachabilityDisconnectEnabled = true;
240
241    @Override
242    public void onRssiThresholdBreached(byte curRssi) {
243        if (mVerboseLoggingEnabled) {
244            Log.e(TAG, "onRssiThresholdBreach event. Cur Rssi = " + curRssi);
245        }
246        sendMessage(CMD_RSSI_THRESHOLD_BREACH, curRssi);
247    }
248
249    public void processRssiThreshold(byte curRssi, int reason) {
250        if (curRssi == Byte.MAX_VALUE || curRssi == Byte.MIN_VALUE) {
251            Log.wtf(TAG, "processRssiThreshold: Invalid rssi " + curRssi);
252            return;
253        }
254        for (int i = 0; i < mRssiRanges.length; i++) {
255            if (curRssi < mRssiRanges[i]) {
256                // Assume sorted values(ascending order) for rssi,
257                // bounded by high(127) and low(-128) at extremeties
258                byte maxRssi = mRssiRanges[i];
259                byte minRssi = mRssiRanges[i-1];
260                // This value of hw has to be believed as this value is averaged and has breached
261                // the rssi thresholds and raised event to host. This would be eggregious if this
262                // value is invalid
263                mWifiInfo.setRssi(curRssi);
264                updateCapabilities(getCurrentWifiConfiguration());
265                int ret = startRssiMonitoringOffload(maxRssi, minRssi);
266                Log.d(TAG, "Re-program RSSI thresholds for " + smToString(reason) +
267                        ": [" + minRssi + ", " + maxRssi + "], curRssi=" + curRssi + " ret=" + ret);
268                break;
269            }
270        }
271    }
272
273    // Testing various network disconnect cases by sending lots of spurious
274    // disconnect to supplicant
275    private boolean testNetworkDisconnect = false;
276
277    private boolean mEnableRssiPolling = false;
278    private int mRssiPollToken = 0;
279    /* 3 operational states for STA operation: CONNECT_MODE, SCAN_ONLY_MODE, SCAN_ONLY_WIFI_OFF_MODE
280    * In CONNECT_MODE, the STA can scan and connect to an access point
281    * In SCAN_ONLY_MODE, the STA can only scan for access points
282    * In SCAN_ONLY_WIFI_OFF_MODE, the STA can only scan for access points with wifi toggle being off
283    */
284    private int mOperationalMode = CONNECT_MODE;
285    private boolean mIsScanOngoing = false;
286    private boolean mIsFullScanOngoing = false;
287
288    private final Queue<Message> mBufferedScanMsg = new LinkedList<>();
289    private static final int UNKNOWN_SCAN_SOURCE = -1;
290    private static final int ADD_OR_UPDATE_SOURCE = -3;
291
292    private static final int SCAN_REQUEST_BUFFER_MAX_SIZE = 10;
293    private static final String CUSTOMIZED_SCAN_SETTING = "customized_scan_settings";
294    private static final String CUSTOMIZED_SCAN_WORKSOURCE = "customized_scan_worksource";
295    private static final String SCAN_REQUEST_TIME = "scan_request_time";
296
297    private boolean mBluetoothConnectionActive = false;
298
299    private PowerManager.WakeLock mSuspendWakeLock;
300
301    /**
302     * Interval in milliseconds between polling for RSSI
303     * and linkspeed information
304     */
305    private static final int POLL_RSSI_INTERVAL_MSECS = 3000;
306
307    /**
308     * Interval in milliseconds between receiving a disconnect event
309     * while connected to a good AP, and handling the disconnect proper
310     */
311    private static final int LINK_FLAPPING_DEBOUNCE_MSEC = 4000;
312
313    /**
314     * Delay between supplicant restarts upon failure to establish connection
315     */
316    private static final int SUPPLICANT_RESTART_INTERVAL_MSECS = 5000;
317
318    /**
319     * Number of times we attempt to restart supplicant
320     */
321    private static final int SUPPLICANT_RESTART_TRIES = 5;
322
323    /**
324     * Value to set in wpa_supplicant "bssid" field when we don't want to restrict connection to
325     * a specific AP.
326     */
327    private static final String SUPPLICANT_BSSID_ANY = "any";
328
329    private int mSupplicantRestartCount = 0;
330    /* Tracks sequence number on stop failure message */
331    private int mSupplicantStopFailureToken = 0;
332
333    /**
334     * The link properties of the wifi interface.
335     * Do not modify this directly; use updateLinkProperties instead.
336     */
337    private LinkProperties mLinkProperties;
338
339    /* Tracks sequence number on a periodic scan message */
340    private int mPeriodicScanToken = 0;
341
342    // Wakelock held during wifi start/stop and driver load/unload
343    private PowerManager.WakeLock mWakeLock;
344
345    private Context mContext;
346
347    private final Object mDhcpResultsLock = new Object();
348    private DhcpResults mDhcpResults;
349
350    // NOTE: Do not return to clients - use #getWiFiInfoForUid(int)
351    private final WifiInfo mWifiInfo;
352    private NetworkInfo mNetworkInfo;
353    private final NetworkCapabilities mDfltNetworkCapabilities;
354    private SupplicantStateTracker mSupplicantStateTracker;
355
356    private int mWifiLinkLayerStatsSupported = 4; // Temporary disable
357
358    // Whether the state machine goes thru the Disconnecting->Disconnected->ObtainingIpAddress
359    private boolean mAutoRoaming = false;
360
361    // Roaming failure count
362    private int mRoamFailCount = 0;
363
364    // This is the BSSID we are trying to associate to, it can be set to SUPPLICANT_BSSID_ANY
365    // if we havent selected a BSSID for joining.
366    private String mTargetRoamBSSID = SUPPLICANT_BSSID_ANY;
367    // This one is used to track whta is the current target network ID. This is used for error
368    // handling during connection setup since many error message from supplicant does not report
369    // SSID Once connected, it will be set to invalid
370    private int mTargetNetworkId = WifiConfiguration.INVALID_NETWORK_ID;
371    private long mLastDriverRoamAttempt = 0;
372    private WifiConfiguration targetWificonfiguration = null;
373
374    boolean isRoaming() {
375        return mAutoRoaming;
376    }
377
378    /**
379     * Method to clear {@link #mTargetRoamBSSID} and reset the the current connected network's
380     * bssid in wpa_supplicant after a roam/connect attempt.
381     */
382    public boolean clearTargetBssid(String dbg) {
383        WifiConfiguration config = mWifiConfigManager.getConfiguredNetwork(mTargetNetworkId);
384        if (config == null) {
385            return false;
386        }
387        String bssid = SUPPLICANT_BSSID_ANY;
388        if (config.BSSID != null) {
389            bssid = config.BSSID;
390            if (mVerboseLoggingEnabled) {
391                Log.d(TAG, "force BSSID to " + bssid + "due to config");
392            }
393        }
394        if (mVerboseLoggingEnabled) {
395            logd(dbg + " clearTargetBssid " + bssid + " key=" + config.configKey());
396        }
397        mTargetRoamBSSID = bssid;
398        return mWifiNative.setConfiguredNetworkBSSID(bssid);
399    }
400
401    /**
402     * Set Config's default BSSID (for association purpose) and {@link #mTargetRoamBSSID}
403     * @param config config need set BSSID
404     * @param bssid  default BSSID to assocaite with when connect to this network
405     * @return false -- does not change the current default BSSID of the configure
406     *         true -- change the  current default BSSID of the configur
407     */
408    private boolean setTargetBssid(WifiConfiguration config, String bssid) {
409        if (config == null || bssid == null) {
410            return false;
411        }
412        if (config.BSSID != null) {
413            bssid = config.BSSID;
414            if (mVerboseLoggingEnabled) {
415                Log.d(TAG, "force BSSID to " + bssid + "due to config");
416            }
417        }
418        if (mVerboseLoggingEnabled) {
419            Log.d(TAG, "setTargetBssid set to " + bssid + " key=" + config.configKey());
420        }
421        mTargetRoamBSSID = bssid;
422        config.getNetworkSelectionStatus().setNetworkSelectionBSSID(bssid);
423        return true;
424    }
425
426    private final IpManager mIpManager;
427
428    // Channel for sending replies.
429    private AsyncChannel mReplyChannel = new AsyncChannel();
430
431    // Used to initiate a connection with WifiP2pService
432    private AsyncChannel mWifiP2pChannel;
433
434    private WifiScanner mWifiScanner;
435
436    @GuardedBy("mWifiReqCountLock")
437    private int mConnectionReqCount = 0;
438    private WifiNetworkFactory mNetworkFactory;
439    @GuardedBy("mWifiReqCountLock")
440    private int mUntrustedReqCount = 0;
441    private UntrustedWifiNetworkFactory mUntrustedNetworkFactory;
442    private WifiNetworkAgent mNetworkAgent;
443    private final Object mWifiReqCountLock = new Object();
444
445    private byte[] mRssiRanges;
446
447    // Keep track of various statistics, for retrieval by System Apps, i.e. under @SystemApi
448    // We should really persist that into the networkHistory.txt file, and read it back when
449    // WifiStateMachine starts up
450    private WifiConnectionStatistics mWifiConnectionStatistics = new WifiConnectionStatistics();
451
452    // Used to filter out requests we couldn't possibly satisfy.
453    private final NetworkCapabilities mNetworkCapabilitiesFilter = new NetworkCapabilities();
454
455    // Provide packet filter capabilities to ConnectivityService.
456    private final NetworkMisc mNetworkMisc = new NetworkMisc();
457
458    /* The base for wifi message types */
459    static final int BASE = Protocol.BASE_WIFI;
460    /* Start the supplicant */
461    static final int CMD_START_SUPPLICANT                               = BASE + 11;
462    /* Stop the supplicant */
463    static final int CMD_STOP_SUPPLICANT                                = BASE + 12;
464    /* Indicates Static IP succeeded */
465    static final int CMD_STATIC_IP_SUCCESS                              = BASE + 15;
466    /* Indicates Static IP failed */
467    static final int CMD_STATIC_IP_FAILURE                              = BASE + 16;
468    /* Indicates supplicant stop failed */
469    static final int CMD_STOP_SUPPLICANT_FAILED                         = BASE + 17;
470    /* A delayed message sent to start driver when it fail to come up */
471    static final int CMD_DRIVER_START_TIMED_OUT                         = BASE + 19;
472
473    /* Start the soft access point */
474    static final int CMD_START_AP                                       = BASE + 21;
475    /* Indicates soft ap start failed */
476    static final int CMD_START_AP_FAILURE                               = BASE + 22;
477    /* Stop the soft access point */
478    static final int CMD_STOP_AP                                        = BASE + 23;
479    /* Soft access point teardown is completed. */
480    static final int CMD_AP_STOPPED                                     = BASE + 24;
481
482    static final int CMD_BLUETOOTH_ADAPTER_STATE_CHANGE                 = BASE + 31;
483
484    /* Supplicant commands */
485    /* Is supplicant alive ? */
486    static final int CMD_PING_SUPPLICANT                                = BASE + 51;
487    /* Add/update a network configuration */
488    static final int CMD_ADD_OR_UPDATE_NETWORK                          = BASE + 52;
489    /* Delete a network */
490    static final int CMD_REMOVE_NETWORK                                 = BASE + 53;
491    /* Enable a network. The device will attempt a connection to the given network. */
492    static final int CMD_ENABLE_NETWORK                                 = BASE + 54;
493    /* Save configuration */
494    static final int CMD_SAVE_CONFIG                                    = BASE + 58;
495    /* Get configured networks */
496    static final int CMD_GET_CONFIGURED_NETWORKS                        = BASE + 59;
497    /* Get adaptors */
498    static final int CMD_GET_SUPPORTED_FEATURES                         = BASE + 61;
499    /* Get configured networks with real preSharedKey */
500    static final int CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS             = BASE + 62;
501    /* Get Link Layer Stats thru HAL */
502    static final int CMD_GET_LINK_LAYER_STATS                           = BASE + 63;
503    /* Supplicant commands after driver start*/
504    /* Initiate a scan */
505    static final int CMD_START_SCAN                                     = BASE + 71;
506    /* Set operational mode. CONNECT, SCAN ONLY, SCAN_ONLY with Wi-Fi off mode */
507    static final int CMD_SET_OPERATIONAL_MODE                           = BASE + 72;
508    /* Disconnect from a network */
509    static final int CMD_DISCONNECT                                     = BASE + 73;
510    /* Reconnect to a network */
511    static final int CMD_RECONNECT                                      = BASE + 74;
512    /* Reassociate to a network */
513    static final int CMD_REASSOCIATE                                    = BASE + 75;
514    /* Get Connection Statistis */
515    static final int CMD_GET_CONNECTION_STATISTICS                      = BASE + 76;
516
517    /* Controls suspend mode optimizations
518     *
519     * When high perf mode is enabled, suspend mode optimizations are disabled
520     *
521     * When high perf mode is disabled, suspend mode optimizations are enabled
522     *
523     * Suspend mode optimizations include:
524     * - packet filtering
525     * - turn off roaming
526     * - DTIM wake up settings
527     */
528    static final int CMD_SET_HIGH_PERF_MODE                             = BASE + 77;
529    /* Enables RSSI poll */
530    static final int CMD_ENABLE_RSSI_POLL                               = BASE + 82;
531    /* RSSI poll */
532    static final int CMD_RSSI_POLL                                      = BASE + 83;
533    /* Enable suspend mode optimizations in the driver */
534    static final int CMD_SET_SUSPEND_OPT_ENABLED                        = BASE + 86;
535    /* Delayed NETWORK_DISCONNECT */
536    static final int CMD_DELAYED_NETWORK_DISCONNECT                     = BASE + 87;
537    /* When there are no saved networks, we do a periodic scan to notify user of
538     * an open network */
539    static final int CMD_NO_NETWORKS_PERIODIC_SCAN                      = BASE + 88;
540    /* Test network Disconnection NETWORK_DISCONNECT */
541    static final int CMD_TEST_NETWORK_DISCONNECT                        = BASE + 89;
542
543    private int testNetworkDisconnectCounter = 0;
544
545    /* Enable TDLS on a specific MAC address */
546    static final int CMD_ENABLE_TDLS                                    = BASE + 92;
547
548    /**
549     * Watchdog for protecting against b/16823537
550     * Leave time for 4-way handshake to succeed
551     */
552    static final int ROAM_GUARD_TIMER_MSEC = 15000;
553
554    int roamWatchdogCount = 0;
555    /* Roam state watchdog */
556    static final int CMD_ROAM_WATCHDOG_TIMER                            = BASE + 94;
557    /* Screen change intent handling */
558    static final int CMD_SCREEN_STATE_CHANGED                           = BASE + 95;
559
560    /* Disconnecting state watchdog */
561    static final int CMD_DISCONNECTING_WATCHDOG_TIMER                   = BASE + 96;
562
563    /* Remove a packages associated configrations */
564    static final int CMD_REMOVE_APP_CONFIGURATIONS                      = BASE + 97;
565
566    /* Disable an ephemeral network */
567    static final int CMD_DISABLE_EPHEMERAL_NETWORK                      = BASE + 98;
568
569    /* Get matching network */
570    static final int CMD_GET_MATCHING_CONFIG                            = BASE + 99;
571
572    /* alert from firmware */
573    static final int CMD_FIRMWARE_ALERT                                 = BASE + 100;
574
575    /* SIM is removed; reset any cached data for it */
576    static final int CMD_RESET_SIM_NETWORKS                             = BASE + 101;
577
578    /* OSU APIs */
579    static final int CMD_QUERY_OSU_ICON                                 = BASE + 104;
580
581    /* try to match a provider with current network */
582    static final int CMD_MATCH_PROVIDER_NETWORK                         = BASE + 105;
583
584    /* Commands from/to the SupplicantStateTracker */
585    /* Reset the supplicant state tracker */
586    static final int CMD_RESET_SUPPLICANT_STATE                         = BASE + 111;
587
588    int disconnectingWatchdogCount = 0;
589    static final int DISCONNECTING_GUARD_TIMER_MSEC = 5000;
590
591    /* P2p commands */
592    /* We are ok with no response here since we wont do much with it anyway */
593    public static final int CMD_ENABLE_P2P                              = BASE + 131;
594    /* In order to shut down supplicant cleanly, we wait till p2p has
595     * been disabled */
596    public static final int CMD_DISABLE_P2P_REQ                         = BASE + 132;
597    public static final int CMD_DISABLE_P2P_RSP                         = BASE + 133;
598
599    /**
600     * Indicates the end of boot process, should be used to trigger load from config store,
601     * initiate connection attempt, etc.
602     * */
603    static final int CMD_BOOT_COMPLETED                                 = BASE + 134;
604    /**
605     * Initialize the WifiStateMachine. This is currently used to initialize the
606     * {@link HalDeviceManager} module.
607     */
608    static final int CMD_INITIALIZE                                     = BASE + 135;
609
610    /* We now have a valid IP configuration. */
611    static final int CMD_IP_CONFIGURATION_SUCCESSFUL                    = BASE + 138;
612    /* We no longer have a valid IP configuration. */
613    static final int CMD_IP_CONFIGURATION_LOST                          = BASE + 139;
614    /* Link configuration (IP address, DNS, ...) changes notified via netlink */
615    static final int CMD_UPDATE_LINKPROPERTIES                          = BASE + 140;
616
617    /* Supplicant is trying to associate to a given BSSID */
618    static final int CMD_TARGET_BSSID                                   = BASE + 141;
619
620    /* Reload all networks and reconnect */
621    static final int CMD_RELOAD_TLS_AND_RECONNECT                       = BASE + 142;
622
623    static final int CMD_START_CONNECT                                  = BASE + 143;
624
625    private static final int NETWORK_STATUS_UNWANTED_DISCONNECT         = 0;
626    private static final int NETWORK_STATUS_UNWANTED_VALIDATION_FAILED  = 1;
627    private static final int NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN   = 2;
628
629    static final int CMD_UNWANTED_NETWORK                               = BASE + 144;
630
631    static final int CMD_START_ROAM                                     = BASE + 145;
632
633    static final int CMD_ASSOCIATED_BSSID                               = BASE + 147;
634
635    static final int CMD_NETWORK_STATUS                                 = BASE + 148;
636
637    /* A layer 3 neighbor on the Wi-Fi link became unreachable. */
638    static final int CMD_IP_REACHABILITY_LOST                           = BASE + 149;
639
640    /* Remove a packages associated configrations */
641    static final int CMD_REMOVE_USER_CONFIGURATIONS                     = BASE + 152;
642
643    static final int CMD_ACCEPT_UNVALIDATED                             = BASE + 153;
644
645    /* used to offload sending IP packet */
646    static final int CMD_START_IP_PACKET_OFFLOAD                        = BASE + 160;
647
648    /* used to stop offload sending IP packet */
649    static final int CMD_STOP_IP_PACKET_OFFLOAD                         = BASE + 161;
650
651    /* used to start rssi monitoring in hw */
652    static final int CMD_START_RSSI_MONITORING_OFFLOAD                  = BASE + 162;
653
654    /* used to stop rssi moniroting in hw */
655    static final int CMD_STOP_RSSI_MONITORING_OFFLOAD                   = BASE + 163;
656
657    /* used to indicated RSSI threshold breach in hw */
658    static final int CMD_RSSI_THRESHOLD_BREACH                          = BASE + 164;
659
660    /* Enable/Disable WifiConnectivityManager */
661    static final int CMD_ENABLE_WIFI_CONNECTIVITY_MANAGER               = BASE + 166;
662
663    /* Enable/Disable AutoJoin when associated */
664    static final int CMD_ENABLE_AUTOJOIN_WHEN_ASSOCIATED                = BASE + 167;
665
666    /**
667     * Used to handle messages bounced between WifiStateMachine and IpManager.
668     */
669    static final int CMD_IPV4_PROVISIONING_SUCCESS                      = BASE + 200;
670    static final int CMD_IPV4_PROVISIONING_FAILURE                      = BASE + 201;
671
672    /* Push a new APF program to the HAL */
673    static final int CMD_INSTALL_PACKET_FILTER                          = BASE + 202;
674
675    /* Enable/disable fallback packet filtering */
676    static final int CMD_SET_FALLBACK_PACKET_FILTERING                  = BASE + 203;
677
678    /* Enable/disable Neighbor Discovery offload functionality. */
679    static final int CMD_CONFIG_ND_OFFLOAD                              = BASE + 204;
680
681    /* used to indicate that the foreground user was switched */
682    static final int CMD_USER_SWITCH                                    = BASE + 205;
683
684    /* used to indicate that the foreground user was switched */
685    static final int CMD_USER_UNLOCK                                    = BASE + 206;
686
687    /* used to indicate that the foreground user was switched */
688    static final int CMD_USER_STOP                                      = BASE + 207;
689
690    /* Signals that IClientInterface instance underpinning our state is dead. */
691    private static final int CMD_CLIENT_INTERFACE_BINDER_DEATH          = BASE + 250;
692
693    /* Indicates that diagnostics should time out a connection start event. */
694    private static final int CMD_DIAGS_CONNECT_TIMEOUT                  = BASE + 251;
695
696    // For message logging.
697    private static final Class[] sMessageClasses = {
698            AsyncChannel.class, WifiStateMachine.class, DhcpClient.class };
699    private static final SparseArray<String> sSmToString =
700            MessageUtils.findMessageNames(sMessageClasses);
701
702
703    /* Wifi state machine modes of operation */
704    /* CONNECT_MODE - connect to any 'known' AP when it becomes available */
705    public static final int CONNECT_MODE = 1;
706    /* SCAN_ONLY_MODE - don't connect to any APs; scan, but only while apps hold lock */
707    public static final int SCAN_ONLY_MODE = 2;
708    /* SCAN_ONLY_WITH_WIFI_OFF - scan, but don't connect to any APs */
709    public static final int SCAN_ONLY_WITH_WIFI_OFF_MODE = 3;
710    /* DISABLED_MODE - Don't connect, don't scan, don't be an AP */
711    public static final int DISABLED_MODE = 4;
712
713    private static final int SUCCESS = 1;
714    private static final int FAILURE = -1;
715
716    /* Tracks if suspend optimizations need to be disabled by DHCP,
717     * screen or due to high perf mode.
718     * When any of them needs to disable it, we keep the suspend optimizations
719     * disabled
720     */
721    private int mSuspendOptNeedsDisabled = 0;
722
723    private static final int SUSPEND_DUE_TO_DHCP = 1;
724    private static final int SUSPEND_DUE_TO_HIGH_PERF = 1 << 1;
725    private static final int SUSPEND_DUE_TO_SCREEN = 1 << 2;
726
727    /* Tracks if user has enabled suspend optimizations through settings */
728    private AtomicBoolean mUserWantsSuspendOpt = new AtomicBoolean(true);
729
730    /**
731     * Scan period for the NO_NETWORKS_PERIIDOC_SCAN_FEATURE
732     */
733    private final int mNoNetworksPeriodicScan;
734
735    /**
736     * Supplicant scan interval in milliseconds.
737     * Comes from {@link Settings.Global#WIFI_SUPPLICANT_SCAN_INTERVAL_MS} or
738     * from the default config if the setting is not set
739     */
740    private long mSupplicantScanIntervalMs;
741
742    private boolean mEnableAutoJoinWhenAssociated;
743    private int mAlwaysEnableScansWhileAssociated;
744    private final int mThresholdQualifiedRssi24;
745    private final int mThresholdQualifiedRssi5;
746    private final int mThresholdSaturatedRssi24;
747    private final int mThresholdSaturatedRssi5;
748    private final int mThresholdMinimumRssi5;
749    private final int mThresholdMinimumRssi24;
750    private final boolean mEnableLinkDebouncing;
751    private final boolean mEnableChipWakeUpWhenAssociated;
752    private final boolean mEnableRssiPollWhenAssociated;
753
754    int mRunningBeaconCount = 0;
755
756    /* Default parent state */
757    private State mDefaultState = new DefaultState();
758    /* Temporary initial state */
759    private State mInitialState = new InitialState();
760    /* Driver loaded, waiting for supplicant to start */
761    private State mSupplicantStartingState = new SupplicantStartingState();
762    /* Driver loaded and supplicant ready */
763    private State mSupplicantStartedState = new SupplicantStartedState();
764    /* Waiting for supplicant to stop and monitor to exit */
765    private State mSupplicantStoppingState = new SupplicantStoppingState();
766    /* Wait until p2p is disabled
767     * This is a special state which is entered right after we exit out of DriverStartedState
768     * before transitioning to another state.
769     */
770    private State mWaitForP2pDisableState = new WaitForP2pDisableState();
771    /* Scan for networks, no connection will be established */
772    private State mScanModeState = new ScanModeState();
773    /* Connecting to an access point */
774    private State mConnectModeState = new ConnectModeState();
775    /* Connected at 802.11 (L2) level */
776    private State mL2ConnectedState = new L2ConnectedState();
777    /* fetching IP after connection to access point (assoc+auth complete) */
778    private State mObtainingIpState = new ObtainingIpState();
779    /* Connected with IP addr */
780    private State mConnectedState = new ConnectedState();
781    /* Roaming */
782    private State mRoamingState = new RoamingState();
783    /* disconnect issued, waiting for network disconnect confirmation */
784    private State mDisconnectingState = new DisconnectingState();
785    /* Network is not connected, supplicant assoc+auth is not complete */
786    private State mDisconnectedState = new DisconnectedState();
787    /* Waiting for WPS to be completed*/
788    private State mWpsRunningState = new WpsRunningState();
789    /* Soft ap state */
790    private State mSoftApState = new SoftApState();
791
792    /**
793     * One of  {@link WifiManager#WIFI_STATE_DISABLED},
794     * {@link WifiManager#WIFI_STATE_DISABLING},
795     * {@link WifiManager#WIFI_STATE_ENABLED},
796     * {@link WifiManager#WIFI_STATE_ENABLING},
797     * {@link WifiManager#WIFI_STATE_UNKNOWN}
798     */
799    private final AtomicInteger mWifiState = new AtomicInteger(WIFI_STATE_DISABLED);
800
801    /**
802     * One of  {@link WifiManager#WIFI_AP_STATE_DISABLED},
803     * {@link WifiManager#WIFI_AP_STATE_DISABLING},
804     * {@link WifiManager#WIFI_AP_STATE_ENABLED},
805     * {@link WifiManager#WIFI_AP_STATE_ENABLING},
806     * {@link WifiManager#WIFI_AP_STATE_FAILED}
807     */
808    private final AtomicInteger mWifiApState = new AtomicInteger(WIFI_AP_STATE_DISABLED);
809
810    /**
811     * Work source to use to blame usage on the WiFi service
812     */
813    public static final WorkSource WIFI_WORK_SOURCE = new WorkSource(Process.WIFI_UID);
814
815    /**
816     * Keep track of whether WIFI is running.
817     */
818    private boolean mIsRunning = false;
819
820    /**
821     * Keep track of whether we last told the battery stats we had started.
822     */
823    private boolean mReportedRunning = false;
824
825    /**
826     * Most recently set source of starting WIFI.
827     */
828    private final WorkSource mRunningWifiUids = new WorkSource();
829
830    /**
831     * The last reported UIDs that were responsible for starting WIFI.
832     */
833    private final WorkSource mLastRunningWifiUids = new WorkSource();
834
835    private TelephonyManager mTelephonyManager;
836    private TelephonyManager getTelephonyManager() {
837        if (mTelephonyManager == null) {
838            mTelephonyManager = mWifiInjector.makeTelephonyManager();
839        }
840        return mTelephonyManager;
841    }
842
843    private final IBatteryStats mBatteryStats;
844
845    private final String mTcpBufferSizes;
846
847    // Used for debug and stats gathering
848    private static int sScanAlarmIntentCount = 0;
849
850    private FrameworkFacade mFacade;
851    private WifiStateTracker mWifiStateTracker;
852    private final BackupManagerProxy mBackupManagerProxy;
853
854    public WifiStateMachine(Context context, FrameworkFacade facade, Looper looper,
855                            UserManager userManager, WifiInjector wifiInjector,
856                            BackupManagerProxy backupManagerProxy, WifiCountryCode countryCode,
857                            WifiNative wifiNative) {
858        super("WifiStateMachine", looper);
859        mWifiInjector = wifiInjector;
860        mWifiMetrics = mWifiInjector.getWifiMetrics();
861        mClock = wifiInjector.getClock();
862        mPropertyService = wifiInjector.getPropertyService();
863        mBuildProperties = wifiInjector.getBuildProperties();
864        mContext = context;
865        mFacade = facade;
866        mWifiNative = wifiNative;
867        mBackupManagerProxy = backupManagerProxy;
868
869        // TODO refactor WifiNative use of context out into it's own class
870        mWifiNative.initContext(mContext);
871        mInterfaceName = mWifiNative.getInterfaceName();
872        mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, NETWORKTYPE, "");
873        mBatteryStats = IBatteryStats.Stub.asInterface(mFacade.getService(
874                BatteryStats.SERVICE_NAME));
875        mWifiStateTracker = wifiInjector.getWifiStateTracker();
876        IBinder b = mFacade.getService(Context.NETWORKMANAGEMENT_SERVICE);
877        mNwService = INetworkManagementService.Stub.asInterface(b);
878
879        mP2pSupported = mContext.getPackageManager().hasSystemFeature(
880                PackageManager.FEATURE_WIFI_DIRECT);
881
882        mWifiConfigManager = mWifiInjector.getWifiConfigManager();
883        mWifiApConfigStore = mWifiInjector.getWifiApConfigStore();
884        mWifiNative.setSystemSupportsFastBssTransition(
885                mContext.getResources().getBoolean(R.bool.config_wifi_fast_bss_transition_enabled));
886
887        mPasspointManager = mWifiInjector.getPasspointManager();
888
889        mWifiMonitor = WifiMonitor.getInstance();
890        mWifiDiagnostics = mWifiInjector.makeWifiDiagnostics(mWifiNative);
891
892        mWifiInfo = new WifiInfo();
893        mWifiNetworkSelector = mWifiInjector.getWifiNetworkSelector();
894        mSupplicantStateTracker =
895                mFacade.makeSupplicantStateTracker(context, mWifiConfigManager, getHandler());
896
897        mLinkProperties = new LinkProperties();
898
899        mNetworkInfo.setIsAvailable(false);
900        mLastBssid = null;
901        mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID;
902        mLastSignalLevel = -1;
903
904        mIpManager = mFacade.makeIpManager(mContext, mInterfaceName, new IpManagerCallback());
905        mIpManager.setMulticastFilter(true);
906
907        mNoNetworksPeriodicScan = mContext.getResources().getInteger(
908                R.integer.config_wifi_no_network_periodic_scan_interval);
909
910        // TODO: remove these settings from the config file since we no longer obey them
911        // mContext.getResources().getInteger(R.integer.config_wifi_framework_scan_interval);
912        // mContext.getResources().getBoolean(R.bool.config_wifi_background_scan_support);
913
914        mPrimaryDeviceType = mContext.getResources().getString(
915                R.string.config_wifi_p2p_device_type);
916
917        mCountryCode = countryCode;
918
919        mWifiScoreReport = new WifiScoreReport(mContext, mWifiConfigManager);
920
921        mUserWantsSuspendOpt.set(mFacade.getIntegerSetting(mContext,
922                Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED, 1) == 1);
923
924        mNetworkCapabilitiesFilter.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
925        mNetworkCapabilitiesFilter.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
926        mNetworkCapabilitiesFilter.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
927        mNetworkCapabilitiesFilter.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
928        mNetworkCapabilitiesFilter.setLinkUpstreamBandwidthKbps(1024 * 1024);
929        mNetworkCapabilitiesFilter.setLinkDownstreamBandwidthKbps(1024 * 1024);
930        // TODO - needs to be a bit more dynamic
931        mDfltNetworkCapabilities = new NetworkCapabilities(mNetworkCapabilitiesFilter);
932
933        IntentFilter filter = new IntentFilter();
934        filter.addAction(Intent.ACTION_SCREEN_ON);
935        filter.addAction(Intent.ACTION_SCREEN_OFF);
936        mContext.registerReceiver(
937                new BroadcastReceiver() {
938                    @Override
939                    public void onReceive(Context context, Intent intent) {
940                        String action = intent.getAction();
941
942                        if (action.equals(Intent.ACTION_SCREEN_ON)) {
943                            sendMessage(CMD_SCREEN_STATE_CHANGED, 1);
944                        } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
945                            sendMessage(CMD_SCREEN_STATE_CHANGED, 0);
946                        }
947                    }
948                }, filter);
949
950        mContext.getContentResolver().registerContentObserver(Settings.Global.getUriFor(
951                        Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED), false,
952                new ContentObserver(getHandler()) {
953                    @Override
954                    public void onChange(boolean selfChange) {
955                        mUserWantsSuspendOpt.set(mFacade.getIntegerSetting(mContext,
956                                Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED, 1) == 1);
957                    }
958                });
959
960        mContext.registerReceiver(
961                new BroadcastReceiver() {
962                    @Override
963                    public void onReceive(Context context, Intent intent) {
964                        sendMessage(CMD_BOOT_COMPLETED);
965                    }
966                },
967                new IntentFilter(Intent.ACTION_LOCKED_BOOT_COMPLETED));
968
969        PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
970        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getName());
971
972        mSuspendWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WifiSuspend");
973        mSuspendWakeLock.setReferenceCounted(false);
974
975        mTcpBufferSizes = mContext.getResources().getString(
976                com.android.internal.R.string.config_wifi_tcp_buffers);
977
978        // Load Device configs
979        mEnableAutoJoinWhenAssociated = context.getResources().getBoolean(
980                R.bool.config_wifi_framework_enable_associated_network_selection);
981        mThresholdQualifiedRssi24 = context.getResources().getInteger(
982                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_24GHz);
983        mThresholdQualifiedRssi5 = context.getResources().getInteger(
984                R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_5GHz);
985        mThresholdSaturatedRssi24 = context.getResources().getInteger(
986                R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_24GHz);
987        mThresholdSaturatedRssi5 = context.getResources().getInteger(
988                R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_5GHz);
989        mThresholdMinimumRssi5 = context.getResources().getInteger(
990                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_5GHz);
991        mThresholdMinimumRssi24 = context.getResources().getInteger(
992                R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_24GHz);
993        mEnableLinkDebouncing = mContext.getResources().getBoolean(
994                R.bool.config_wifi_enable_disconnection_debounce);
995        mEnableChipWakeUpWhenAssociated = true;
996        mEnableRssiPollWhenAssociated = true;
997
998        // CHECKSTYLE:OFF IndentationCheck
999        addState(mDefaultState);
1000            addState(mInitialState, mDefaultState);
1001            addState(mSupplicantStartingState, mDefaultState);
1002            addState(mSupplicantStartedState, mDefaultState);
1003                    addState(mScanModeState, mSupplicantStartedState);
1004                    addState(mConnectModeState, mSupplicantStartedState);
1005                        addState(mL2ConnectedState, mConnectModeState);
1006                            addState(mObtainingIpState, mL2ConnectedState);
1007                            addState(mConnectedState, mL2ConnectedState);
1008                            addState(mRoamingState, mL2ConnectedState);
1009                        addState(mDisconnectingState, mConnectModeState);
1010                        addState(mDisconnectedState, mConnectModeState);
1011                        addState(mWpsRunningState, mConnectModeState);
1012                addState(mWaitForP2pDisableState, mSupplicantStartedState);
1013            addState(mSupplicantStoppingState, mDefaultState);
1014            addState(mSoftApState, mDefaultState);
1015        // CHECKSTYLE:ON IndentationCheck
1016
1017        setInitialState(mInitialState);
1018
1019        setLogRecSize(NUM_LOG_RECS_NORMAL);
1020        setLogOnlyTransitions(false);
1021
1022        //start the state machine
1023        start();
1024
1025        // Learn the initial state of whether the screen is on.
1026        // We update this field when we receive broadcasts from the system.
1027        handleScreenStateChanged(powerManager.isInteractive());
1028
1029        mWifiMonitor.registerHandler(mInterfaceName, CMD_TARGET_BSSID, getHandler());
1030        mWifiMonitor.registerHandler(mInterfaceName, CMD_ASSOCIATED_BSSID, getHandler());
1031        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.ANQP_DONE_EVENT, getHandler());
1032        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.ASSOCIATION_REJECTION_EVENT,
1033                getHandler());
1034        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.AUTHENTICATION_FAILURE_EVENT,
1035                getHandler());
1036        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.DRIVER_HUNG_EVENT, getHandler());
1037        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.GAS_QUERY_DONE_EVENT, getHandler());
1038        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.GAS_QUERY_START_EVENT,
1039                getHandler());
1040        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.HS20_REMEDIATION_EVENT,
1041                getHandler());
1042        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.NETWORK_CONNECTION_EVENT,
1043                getHandler());
1044        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.NETWORK_DISCONNECTION_EVENT,
1045                getHandler());
1046        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.RX_HS20_ANQP_ICON_EVENT,
1047                getHandler());
1048        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SCAN_FAILED_EVENT, getHandler());
1049        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SCAN_RESULTS_EVENT, getHandler());
1050        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SSID_REENABLED, getHandler());
1051        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SSID_TEMP_DISABLED, getHandler());
1052        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_CONNECTION_EVENT, getHandler());
1053        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_DISCONNECTION_EVENT,
1054                getHandler());
1055        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT,
1056                getHandler());
1057        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_REQUEST_IDENTITY, getHandler());
1058        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_REQUEST_SIM_AUTH, getHandler());
1059        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_FAIL_EVENT, getHandler());
1060        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_OVERLAP_EVENT, getHandler());
1061        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_SUCCESS_EVENT, getHandler());
1062        mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_TIMEOUT_EVENT, getHandler());
1063
1064        final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE);
1065        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1066        intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED);
1067        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1068    }
1069
1070    class IpManagerCallback extends IpManager.Callback {
1071        @Override
1072        public void onPreDhcpAction() {
1073            sendMessage(DhcpClient.CMD_PRE_DHCP_ACTION);
1074        }
1075
1076        @Override
1077        public void onPostDhcpAction() {
1078            sendMessage(DhcpClient.CMD_POST_DHCP_ACTION);
1079        }
1080
1081        @Override
1082        public void onNewDhcpResults(DhcpResults dhcpResults) {
1083            if (dhcpResults != null) {
1084                sendMessage(CMD_IPV4_PROVISIONING_SUCCESS, dhcpResults);
1085            } else {
1086                sendMessage(CMD_IPV4_PROVISIONING_FAILURE);
1087                mWifiInjector.getWifiLastResortWatchdog().noteConnectionFailureAndTriggerIfNeeded(
1088                        getTargetSsid(), mTargetRoamBSSID,
1089                        WifiLastResortWatchdog.FAILURE_CODE_DHCP);
1090            }
1091        }
1092
1093        @Override
1094        public void onProvisioningSuccess(LinkProperties newLp) {
1095            sendMessage(CMD_UPDATE_LINKPROPERTIES, newLp);
1096            sendMessage(CMD_IP_CONFIGURATION_SUCCESSFUL);
1097        }
1098
1099        @Override
1100        public void onProvisioningFailure(LinkProperties newLp) {
1101            sendMessage(CMD_IP_CONFIGURATION_LOST);
1102        }
1103
1104        @Override
1105        public void onLinkPropertiesChange(LinkProperties newLp) {
1106            sendMessage(CMD_UPDATE_LINKPROPERTIES, newLp);
1107        }
1108
1109        @Override
1110        public void onReachabilityLost(String logMsg) {
1111            sendMessage(CMD_IP_REACHABILITY_LOST, logMsg);
1112        }
1113
1114        @Override
1115        public void installPacketFilter(byte[] filter) {
1116            sendMessage(CMD_INSTALL_PACKET_FILTER, filter);
1117        }
1118
1119        @Override
1120        public void setFallbackMulticastFilter(boolean enabled) {
1121            sendMessage(CMD_SET_FALLBACK_PACKET_FILTERING, enabled);
1122        }
1123
1124        @Override
1125        public void setNeighborDiscoveryOffload(boolean enabled) {
1126            sendMessage(CMD_CONFIG_ND_OFFLOAD, (enabled ? 1 : 0));
1127        }
1128    }
1129
1130    private void stopIpManager() {
1131        /* Restore power save and suspend optimizations */
1132        handlePostDhcpSetup();
1133        mIpManager.stop();
1134    }
1135
1136    PendingIntent getPrivateBroadcast(String action, int requestCode) {
1137        Intent intent = new Intent(action, null);
1138        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1139        intent.setPackage("android");
1140        return mFacade.getBroadcast(mContext, requestCode, intent, 0);
1141    }
1142
1143    /**
1144     * Set wpa_supplicant log level using |mVerboseLoggingLevel| flag.
1145     */
1146    void setSupplicantLogLevel() {
1147        mWifiNative.setSupplicantLogLevel(mVerboseLoggingEnabled);
1148    }
1149
1150    /**
1151     * Method to update logging level in wifi service related classes.
1152     *
1153     * @param verbose int logging level to use
1154     */
1155    public void enableVerboseLogging(int verbose) {
1156        if (verbose > 0) {
1157            mVerboseLoggingEnabled = true;
1158            setLogRecSize(ActivityManager.isLowRamDeviceStatic()
1159                    ? NUM_LOG_RECS_VERBOSE_LOW_MEMORY : NUM_LOG_RECS_VERBOSE);
1160        } else {
1161            mVerboseLoggingEnabled = false;
1162            setLogRecSize(NUM_LOG_RECS_NORMAL);
1163        }
1164        configureVerboseHalLogging(mVerboseLoggingEnabled);
1165        setSupplicantLogLevel();
1166        mCountryCode.enableVerboseLogging(verbose);
1167        mWifiScoreReport.enableVerboseLogging(mVerboseLoggingEnabled);
1168        mWifiDiagnostics.startLogging(mVerboseLoggingEnabled);
1169        mWifiMonitor.enableVerboseLogging(verbose);
1170        mWifiNative.enableVerboseLogging(verbose);
1171        mWifiConfigManager.enableVerboseLogging(verbose);
1172        mSupplicantStateTracker.enableVerboseLogging(verbose);
1173    }
1174
1175    private static final String SYSTEM_PROPERTY_LOG_CONTROL_WIFIHAL = "log.tag.WifiHAL";
1176    private static final String LOGD_LEVEL_DEBUG = "D";
1177    private static final String LOGD_LEVEL_VERBOSE = "V";
1178    private void configureVerboseHalLogging(boolean enableVerbose) {
1179        if (mBuildProperties.isUserBuild()) {  // Verbose HAL logging not supported on user builds.
1180            return;
1181        }
1182        mPropertyService.set(SYSTEM_PROPERTY_LOG_CONTROL_WIFIHAL,
1183                enableVerbose ? LOGD_LEVEL_VERBOSE : LOGD_LEVEL_DEBUG);
1184    }
1185
1186    private int mAggressiveHandover = 0;
1187
1188    int getAggressiveHandover() {
1189        return mAggressiveHandover;
1190    }
1191
1192    void enableAggressiveHandover(int enabled) {
1193        mAggressiveHandover = enabled;
1194    }
1195
1196    public void clearANQPCache() {
1197        // TODO(b/31065385)
1198        // mWifiConfigManager.trimANQPCache(true);
1199    }
1200
1201    public void setAllowScansWithTraffic(int enabled) {
1202        mAlwaysEnableScansWhileAssociated = enabled;
1203    }
1204
1205    public int getAllowScansWithTraffic() {
1206        return mAlwaysEnableScansWhileAssociated;
1207    }
1208
1209    /*
1210     * Dynamically turn on/off if switching networks while connected is allowd.
1211     */
1212    public boolean setEnableAutoJoinWhenAssociated(boolean enabled) {
1213        sendMessage(CMD_ENABLE_AUTOJOIN_WHEN_ASSOCIATED, enabled ? 1 : 0);
1214        return true;
1215    }
1216
1217    public boolean getEnableAutoJoinWhenAssociated() {
1218        return mEnableAutoJoinWhenAssociated;
1219    }
1220
1221    private boolean setRandomMacOui() {
1222        String oui = mContext.getResources().getString(R.string.config_wifi_random_mac_oui);
1223        if (TextUtils.isEmpty(oui)) {
1224            oui = GOOGLE_OUI;
1225        }
1226        String[] ouiParts = oui.split("-");
1227        byte[] ouiBytes = new byte[3];
1228        ouiBytes[0] = (byte) (Integer.parseInt(ouiParts[0], 16) & 0xFF);
1229        ouiBytes[1] = (byte) (Integer.parseInt(ouiParts[1], 16) & 0xFF);
1230        ouiBytes[2] = (byte) (Integer.parseInt(ouiParts[2], 16) & 0xFF);
1231
1232        logd("Setting OUI to " + oui);
1233        return mWifiNative.setScanningMacOui(ouiBytes);
1234    }
1235
1236    /**
1237     * Helper method to lookup the framework network ID of the network currently configured in
1238     * wpa_supplicant using the provided supplicant network ID. This is needed for translating the
1239     * networkID received from all {@link WifiMonitor} events.
1240     *
1241     * @param supplicantNetworkId Network ID of network in wpa_supplicant.
1242     * @return Corresponding Internal configured network ID
1243     * TODO(b/31080843): This is ugly! We need to hide this translation of networkId's. This will
1244     * be handled once we move all of this connection logic to wificond.
1245     */
1246    private int lookupFrameworkNetworkId(int supplicantNetworkId) {
1247        return mWifiNative.getFrameworkNetworkId(supplicantNetworkId);
1248    }
1249
1250    /**
1251     * Initiates connection to a network specified by the user/app. This method checks if the
1252     * requesting app holds the WIFI_CONFIG_OVERRIDE permission.
1253     */
1254    private boolean connectToUserSelectNetwork(int netId, int uid) {
1255        if (!mWifiConfigManager.enableNetwork(netId, true, uid)) {
1256            loge("connectToUserSelectNetwork uid " + uid
1257                    + " did not have the permissions to enable=" + netId);
1258            return false;
1259        }
1260        if (!mWifiConfigManager.checkAndUpdateLastConnectUid(netId, uid)) {
1261            logi("connectToUserSelectNetwork Allowing uid " + uid
1262                    + " with insufficient permissions to connect=" + netId);
1263        }
1264        // Trigger an immediate connection to the specified network. We're also noting the user
1265        // connect choice here, so that it will be considered in the next network selection.
1266        mWifiConnectivityManager.setUserConnectChoice(netId);
1267        if (mWifiInfo.getNetworkId() == netId) {
1268            // We're already connected to the user specified network, don't trigger a
1269            // reconnection.
1270            logi("connectToUserSelectNetwork already connecting/connected=" + netId);
1271        } else {
1272            startConnectToNetwork(netId, SUPPLICANT_BSSID_ANY);
1273        }
1274        return true;
1275    }
1276
1277    /**
1278     * ******************************************************
1279     * Methods exposed for public use
1280     * ******************************************************
1281     */
1282
1283    public Messenger getMessenger() {
1284        return new Messenger(getHandler());
1285    }
1286
1287    /**
1288     * TODO: doc
1289     */
1290    public boolean syncPingSupplicant(AsyncChannel channel) {
1291        Message resultMsg = channel.sendMessageSynchronously(CMD_PING_SUPPLICANT);
1292        boolean result = (resultMsg.arg1 != FAILURE);
1293        resultMsg.recycle();
1294        return result;
1295    }
1296
1297    /**
1298     * Initiate a wifi scan. If workSource is not null, blame is given to it, otherwise blame is
1299     * given to callingUid.
1300     *
1301     * @param callingUid The uid initiating the wifi scan. Blame will be given here unless
1302     *                   workSource is specified.
1303     * @param workSource If not null, blame is given to workSource.
1304     * @param settings   Scan settings, see {@link ScanSettings}.
1305     */
1306    public void startScan(int callingUid, int scanCounter,
1307                          ScanSettings settings, WorkSource workSource) {
1308        Bundle bundle = new Bundle();
1309        bundle.putParcelable(CUSTOMIZED_SCAN_SETTING, settings);
1310        bundle.putParcelable(CUSTOMIZED_SCAN_WORKSOURCE, workSource);
1311        bundle.putLong(SCAN_REQUEST_TIME, mClock.getWallClockMillis());
1312        sendMessage(CMD_START_SCAN, callingUid, scanCounter, bundle);
1313    }
1314
1315    private long mDisconnectedTimeStamp = 0;
1316
1317    public long getDisconnectedTimeMilli() {
1318        if (getCurrentState() == mDisconnectedState
1319                && mDisconnectedTimeStamp != 0) {
1320            long now_ms = mClock.getWallClockMillis();
1321            return now_ms - mDisconnectedTimeStamp;
1322        }
1323        return 0;
1324    }
1325
1326    // Last connect attempt is used to prevent scan requests:
1327    //  - for a period of 10 seconds after attempting to connect
1328    private long lastConnectAttemptTimestamp = 0;
1329    private Set<Integer> lastScanFreqs = null;
1330
1331    // For debugging, keep track of last message status handling
1332    // TODO, find an equivalent mechanism as part of parent class
1333    private static final int MESSAGE_HANDLING_STATUS_PROCESSED = 2;
1334    private static final int MESSAGE_HANDLING_STATUS_OK = 1;
1335    private static final int MESSAGE_HANDLING_STATUS_UNKNOWN = 0;
1336    private static final int MESSAGE_HANDLING_STATUS_REFUSED = -1;
1337    private static final int MESSAGE_HANDLING_STATUS_FAIL = -2;
1338    private static final int MESSAGE_HANDLING_STATUS_OBSOLETE = -3;
1339    private static final int MESSAGE_HANDLING_STATUS_DEFERRED = -4;
1340    private static final int MESSAGE_HANDLING_STATUS_DISCARD = -5;
1341    private static final int MESSAGE_HANDLING_STATUS_LOOPED = -6;
1342    private static final int MESSAGE_HANDLING_STATUS_HANDLING_ERROR = -7;
1343
1344    private int messageHandlingStatus = 0;
1345
1346    //TODO: this is used only to track connection attempts, however the link state and packet per
1347    //TODO: second logic should be folded into that
1348    private boolean checkOrDeferScanAllowed(Message msg) {
1349        long now = mClock.getWallClockMillis();
1350        if (lastConnectAttemptTimestamp != 0 && (now - lastConnectAttemptTimestamp) < 10000) {
1351            Message dmsg = Message.obtain(msg);
1352            sendMessageDelayed(dmsg, 11000 - (now - lastConnectAttemptTimestamp));
1353            return false;
1354        }
1355        return true;
1356    }
1357
1358    private int mOnTime = 0;
1359    private int mTxTime = 0;
1360    private int mRxTime = 0;
1361
1362    private int mOnTimeScreenStateChange = 0;
1363    private long lastOntimeReportTimeStamp = 0;
1364    private long lastScreenStateChangeTimeStamp = 0;
1365    private int mOnTimeLastReport = 0;
1366    private int mTxTimeLastReport = 0;
1367    private int mRxTimeLastReport = 0;
1368
1369    private long lastLinkLayerStatsUpdate = 0;
1370
1371    String reportOnTime() {
1372        long now = mClock.getWallClockMillis();
1373        StringBuilder sb = new StringBuilder();
1374        // Report stats since last report
1375        int on = mOnTime - mOnTimeLastReport;
1376        mOnTimeLastReport = mOnTime;
1377        int tx = mTxTime - mTxTimeLastReport;
1378        mTxTimeLastReport = mTxTime;
1379        int rx = mRxTime - mRxTimeLastReport;
1380        mRxTimeLastReport = mRxTime;
1381        int period = (int) (now - lastOntimeReportTimeStamp);
1382        lastOntimeReportTimeStamp = now;
1383        sb.append(String.format("[on:%d tx:%d rx:%d period:%d]", on, tx, rx, period));
1384        // Report stats since Screen State Changed
1385        on = mOnTime - mOnTimeScreenStateChange;
1386        period = (int) (now - lastScreenStateChangeTimeStamp);
1387        sb.append(String.format(" from screen [on:%d period:%d]", on, period));
1388        return sb.toString();
1389    }
1390
1391    WifiLinkLayerStats getWifiLinkLayerStats() {
1392        WifiLinkLayerStats stats = null;
1393        if (mWifiLinkLayerStatsSupported > 0) {
1394            String name = "wlan0";
1395            stats = mWifiNative.getWifiLinkLayerStats(name);
1396            if (name != null && stats == null && mWifiLinkLayerStatsSupported > 0) {
1397                mWifiLinkLayerStatsSupported -= 1;
1398            } else if (stats != null) {
1399                lastLinkLayerStatsUpdate = mClock.getWallClockMillis();
1400                mOnTime = stats.on_time;
1401                mTxTime = stats.tx_time;
1402                mRxTime = stats.rx_time;
1403                mRunningBeaconCount = stats.beacon_rx;
1404            }
1405        }
1406        if (stats == null || mWifiLinkLayerStatsSupported <= 0) {
1407            long mTxPkts = mFacade.getTxPackets(mInterfaceName);
1408            long mRxPkts = mFacade.getRxPackets(mInterfaceName);
1409            mWifiInfo.updatePacketRates(mTxPkts, mRxPkts);
1410        } else {
1411            mWifiInfo.updatePacketRates(stats, lastLinkLayerStatsUpdate);
1412        }
1413        return stats;
1414    }
1415
1416    int startWifiIPPacketOffload(int slot, KeepalivePacketData packetData, int intervalSeconds) {
1417        int ret = mWifiNative.startSendingOffloadedPacket(slot, packetData, intervalSeconds * 1000);
1418        if (ret != 0) {
1419            loge("startWifiIPPacketOffload(" + slot + ", " + intervalSeconds +
1420                    "): hardware error " + ret);
1421            return ConnectivityManager.PacketKeepalive.ERROR_HARDWARE_ERROR;
1422        } else {
1423            return ConnectivityManager.PacketKeepalive.SUCCESS;
1424        }
1425    }
1426
1427    int stopWifiIPPacketOffload(int slot) {
1428        int ret = mWifiNative.stopSendingOffloadedPacket(slot);
1429        if (ret != 0) {
1430            loge("stopWifiIPPacketOffload(" + slot + "): hardware error " + ret);
1431            return ConnectivityManager.PacketKeepalive.ERROR_HARDWARE_ERROR;
1432        } else {
1433            return ConnectivityManager.PacketKeepalive.SUCCESS;
1434        }
1435    }
1436
1437    int startRssiMonitoringOffload(byte maxRssi, byte minRssi) {
1438        return mWifiNative.startRssiMonitoring(maxRssi, minRssi, WifiStateMachine.this);
1439    }
1440
1441    int stopRssiMonitoringOffload() {
1442        return mWifiNative.stopRssiMonitoring();
1443    }
1444
1445    private void handleScanRequest(Message message) {
1446        ScanSettings settings = null;
1447        WorkSource workSource = null;
1448
1449        // unbundle parameters
1450        Bundle bundle = (Bundle) message.obj;
1451
1452        if (bundle != null) {
1453            settings = bundle.getParcelable(CUSTOMIZED_SCAN_SETTING);
1454            workSource = bundle.getParcelable(CUSTOMIZED_SCAN_WORKSOURCE);
1455        }
1456
1457        Set<Integer> freqs = null;
1458        if (settings != null && settings.channelSet != null) {
1459            freqs = new HashSet<>();
1460            for (WifiChannel channel : settings.channelSet) {
1461                freqs.add(channel.freqMHz);
1462            }
1463        }
1464
1465        // Retrieve the list of hidden network SSIDs to scan for.
1466        List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks =
1467                mWifiConfigManager.retrieveHiddenNetworkList();
1468
1469        // call wifi native to start the scan
1470        if (startScanNative(freqs, hiddenNetworks, workSource)) {
1471            // a full scan covers everything, clearing scan request buffer
1472            if (freqs == null)
1473                mBufferedScanMsg.clear();
1474            messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK;
1475            return;
1476        }
1477
1478        // if reach here, scan request is rejected
1479
1480        if (!mIsScanOngoing) {
1481            // if rejection is NOT due to ongoing scan (e.g. bad scan parameters),
1482
1483            // discard this request and pop up the next one
1484            if (mBufferedScanMsg.size() > 0) {
1485                sendMessage(mBufferedScanMsg.remove());
1486            }
1487            messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
1488        } else if (!mIsFullScanOngoing) {
1489            // if rejection is due to an ongoing scan, and the ongoing one is NOT a full scan,
1490            // buffer the scan request to make sure specified channels will be scanned eventually
1491            if (freqs == null)
1492                mBufferedScanMsg.clear();
1493            if (mBufferedScanMsg.size() < SCAN_REQUEST_BUFFER_MAX_SIZE) {
1494                Message msg = obtainMessage(CMD_START_SCAN,
1495                        message.arg1, message.arg2, bundle);
1496                mBufferedScanMsg.add(msg);
1497            } else {
1498                // if too many requests in buffer, combine them into a single full scan
1499                bundle = new Bundle();
1500                bundle.putParcelable(CUSTOMIZED_SCAN_SETTING, null);
1501                bundle.putParcelable(CUSTOMIZED_SCAN_WORKSOURCE, workSource);
1502                Message msg = obtainMessage(CMD_START_SCAN, message.arg1, message.arg2, bundle);
1503                mBufferedScanMsg.clear();
1504                mBufferedScanMsg.add(msg);
1505            }
1506            messageHandlingStatus = MESSAGE_HANDLING_STATUS_LOOPED;
1507        } else {
1508            // mIsScanOngoing and mIsFullScanOngoing
1509            messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
1510        }
1511    }
1512
1513
1514    // TODO this is a temporary measure to bridge between WifiScanner and WifiStateMachine until
1515    // scan functionality is refactored out of WifiStateMachine.
1516    /**
1517     * return true iff scan request is accepted
1518     */
1519    private boolean startScanNative(final Set<Integer> freqs,
1520            List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworkList,
1521            WorkSource workSource) {
1522        WifiScanner.ScanSettings settings = new WifiScanner.ScanSettings();
1523        if (freqs == null) {
1524            settings.band = WifiScanner.WIFI_BAND_BOTH_WITH_DFS;
1525        } else {
1526            settings.band = WifiScanner.WIFI_BAND_UNSPECIFIED;
1527            int index = 0;
1528            settings.channels = new WifiScanner.ChannelSpec[freqs.size()];
1529            for (Integer freq : freqs) {
1530                settings.channels[index++] = new WifiScanner.ChannelSpec(freq);
1531            }
1532        }
1533        settings.reportEvents = WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN
1534                | WifiScanner.REPORT_EVENT_FULL_SCAN_RESULT;
1535
1536        settings.hiddenNetworks =
1537                hiddenNetworkList.toArray(
1538                        new WifiScanner.ScanSettings.HiddenNetwork[hiddenNetworkList.size()]);
1539
1540        WifiScanner.ScanListener nativeScanListener = new WifiScanner.ScanListener() {
1541                // ignore all events since WifiStateMachine is registered for the supplicant events
1542                @Override
1543                public void onSuccess() {
1544                }
1545                @Override
1546                public void onFailure(int reason, String description) {
1547                    mIsScanOngoing = false;
1548                    mIsFullScanOngoing = false;
1549                }
1550                @Override
1551                public void onResults(WifiScanner.ScanData[] results) {
1552                }
1553                @Override
1554                public void onFullResult(ScanResult fullScanResult) {
1555                }
1556                @Override
1557                public void onPeriodChanged(int periodInMs) {
1558                }
1559            };
1560        mWifiScanner.startScan(settings, nativeScanListener, workSource);
1561        mIsScanOngoing = true;
1562        mIsFullScanOngoing = (freqs == null);
1563        lastScanFreqs = freqs;
1564        return true;
1565    }
1566
1567    /**
1568     * TODO: doc
1569     */
1570    public void setSupplicantRunning(boolean enable) {
1571        if (enable) {
1572            sendMessage(CMD_START_SUPPLICANT);
1573        } else {
1574            sendMessage(CMD_STOP_SUPPLICANT);
1575        }
1576    }
1577
1578    /**
1579     * TODO: doc
1580     */
1581    public void setHostApRunning(WifiConfiguration wifiConfig, boolean enable) {
1582        if (enable) {
1583            sendMessage(CMD_START_AP, wifiConfig);
1584        } else {
1585            sendMessage(CMD_STOP_AP);
1586        }
1587    }
1588
1589    public void setWifiApConfiguration(WifiConfiguration config) {
1590        mWifiApConfigStore.setApConfiguration(config);
1591    }
1592
1593    public WifiConfiguration syncGetWifiApConfiguration() {
1594        return mWifiApConfigStore.getApConfiguration();
1595    }
1596
1597    /**
1598     * TODO: doc
1599     */
1600    public int syncGetWifiState() {
1601        return mWifiState.get();
1602    }
1603
1604    /**
1605     * TODO: doc
1606     */
1607    public String syncGetWifiStateByName() {
1608        switch (mWifiState.get()) {
1609            case WIFI_STATE_DISABLING:
1610                return "disabling";
1611            case WIFI_STATE_DISABLED:
1612                return "disabled";
1613            case WIFI_STATE_ENABLING:
1614                return "enabling";
1615            case WIFI_STATE_ENABLED:
1616                return "enabled";
1617            case WIFI_STATE_UNKNOWN:
1618                return "unknown state";
1619            default:
1620                return "[invalid state]";
1621        }
1622    }
1623
1624    /**
1625     * TODO: doc
1626     */
1627    public int syncGetWifiApState() {
1628        return mWifiApState.get();
1629    }
1630
1631    /**
1632     * TODO: doc
1633     */
1634    public String syncGetWifiApStateByName() {
1635        switch (mWifiApState.get()) {
1636            case WIFI_AP_STATE_DISABLING:
1637                return "disabling";
1638            case WIFI_AP_STATE_DISABLED:
1639                return "disabled";
1640            case WIFI_AP_STATE_ENABLING:
1641                return "enabling";
1642            case WIFI_AP_STATE_ENABLED:
1643                return "enabled";
1644            case WIFI_AP_STATE_FAILED:
1645                return "failed";
1646            default:
1647                return "[invalid state]";
1648        }
1649    }
1650
1651    public boolean isConnected() {
1652        return getCurrentState() == mConnectedState;
1653    }
1654
1655    public boolean isDisconnected() {
1656        return getCurrentState() == mDisconnectedState;
1657    }
1658
1659    public boolean isSupplicantTransientState() {
1660        SupplicantState supplicantState = mWifiInfo.getSupplicantState();
1661        if (supplicantState == SupplicantState.ASSOCIATING
1662                || supplicantState == SupplicantState.AUTHENTICATING
1663                || supplicantState == SupplicantState.FOUR_WAY_HANDSHAKE
1664                || supplicantState == SupplicantState.GROUP_HANDSHAKE) {
1665
1666            if (mVerboseLoggingEnabled) {
1667                Log.d(TAG, "Supplicant is under transient state: " + supplicantState);
1668            }
1669            return true;
1670        } else {
1671            if (mVerboseLoggingEnabled) {
1672                Log.d(TAG, "Supplicant is under steady state: " + supplicantState);
1673            }
1674        }
1675
1676        return false;
1677    }
1678
1679    public boolean isLinkDebouncing() {
1680        return mIsLinkDebouncing;
1681    }
1682
1683    /**
1684     * Get status information for the current connection, if any.
1685     *
1686     * @return a {@link WifiInfo} object containing information about the current connection
1687     */
1688    public WifiInfo syncRequestConnectionInfo() {
1689        return getWiFiInfoForUid(Binder.getCallingUid());
1690    }
1691
1692    public WifiInfo getWifiInfo() {
1693        return mWifiInfo;
1694    }
1695
1696    public DhcpResults syncGetDhcpResults() {
1697        synchronized (mDhcpResultsLock) {
1698            return new DhcpResults(mDhcpResults);
1699        }
1700    }
1701
1702    /**
1703     * TODO: doc
1704     */
1705    public void setOperationalMode(int mode) {
1706        if (mVerboseLoggingEnabled) log("setting operational mode to " + String.valueOf(mode));
1707        sendMessage(CMD_SET_OPERATIONAL_MODE, mode, 0);
1708    }
1709
1710    /**
1711     * Allow tests to confirm the operational mode for WSM.
1712     */
1713    @VisibleForTesting
1714    protected int getOperationalModeForTest() {
1715        return mOperationalMode;
1716    }
1717
1718    /**
1719     * TODO: doc
1720     */
1721    public List<ScanResult> syncGetScanResultsList() {
1722        synchronized (mScanResultsLock) {
1723            List<ScanResult> scanList = new ArrayList<>();
1724            for (ScanDetail result : mScanResults) {
1725                scanList.add(new ScanResult(result.getScanResult()));
1726            }
1727            return scanList;
1728        }
1729    }
1730
1731    public boolean syncQueryPasspointIcon(AsyncChannel channel, long bssid, String fileName) {
1732        Bundle bundle = new Bundle();
1733        bundle.putLong(EXTRA_OSU_ICON_QUERY_BSSID, bssid);
1734        bundle.putString(EXTRA_OSU_ICON_QUERY_FILENAME, fileName);
1735        Message resultMsg = channel.sendMessageSynchronously(CMD_QUERY_OSU_ICON, bundle);
1736        int result = resultMsg.arg1;
1737        resultMsg.recycle();
1738        return result == 1;
1739    }
1740
1741    public int matchProviderWithCurrentNetwork(AsyncChannel channel, String fqdn) {
1742        Message resultMsg = channel.sendMessageSynchronously(CMD_MATCH_PROVIDER_NETWORK, fqdn);
1743        int result = resultMsg.arg1;
1744        resultMsg.recycle();
1745        return result;
1746    }
1747
1748    /**
1749     * Deauthenticate and set the re-authentication hold off time for the current network
1750     * @param holdoff hold off time in milliseconds
1751     * @param ess set if the hold off pertains to an ESS rather than a BSS
1752     */
1753    public void deauthenticateNetwork(AsyncChannel channel, long holdoff, boolean ess) {
1754        // TODO: This needs an implementation
1755    }
1756
1757    public void disableEphemeralNetwork(String SSID) {
1758        if (SSID != null) {
1759            sendMessage(CMD_DISABLE_EPHEMERAL_NETWORK, SSID);
1760        }
1761    }
1762
1763    /**
1764     * Disconnect from Access Point
1765     */
1766    public void disconnectCommand() {
1767        sendMessage(CMD_DISCONNECT);
1768    }
1769
1770    public void disconnectCommand(int uid, int reason) {
1771        sendMessage(CMD_DISCONNECT, uid, reason);
1772    }
1773
1774    /**
1775     * Initiate a reconnection to AP
1776     */
1777    public void reconnectCommand() {
1778        sendMessage(CMD_RECONNECT);
1779    }
1780
1781    /**
1782     * Initiate a re-association to AP
1783     */
1784    public void reassociateCommand() {
1785        sendMessage(CMD_REASSOCIATE);
1786    }
1787
1788    /**
1789     * Reload networks and then reconnect; helps load correct data for TLS networks
1790     */
1791
1792    public void reloadTlsNetworksAndReconnect() {
1793        sendMessage(CMD_RELOAD_TLS_AND_RECONNECT);
1794    }
1795
1796    /**
1797     * Add a network synchronously
1798     *
1799     * @return network id of the new network
1800     */
1801    public int syncAddOrUpdateNetwork(AsyncChannel channel, WifiConfiguration config) {
1802        Message resultMsg = channel.sendMessageSynchronously(CMD_ADD_OR_UPDATE_NETWORK, config);
1803        int result = resultMsg.arg1;
1804        resultMsg.recycle();
1805        return result;
1806    }
1807
1808    /**
1809     * Get configured networks synchronously
1810     *
1811     * @param channel
1812     * @return
1813     */
1814
1815    public List<WifiConfiguration> syncGetConfiguredNetworks(int uuid, AsyncChannel channel) {
1816        Message resultMsg = channel.sendMessageSynchronously(CMD_GET_CONFIGURED_NETWORKS, uuid);
1817        List<WifiConfiguration> result = (List<WifiConfiguration>) resultMsg.obj;
1818        resultMsg.recycle();
1819        return result;
1820    }
1821
1822    public List<WifiConfiguration> syncGetPrivilegedConfiguredNetwork(AsyncChannel channel) {
1823        Message resultMsg = channel.sendMessageSynchronously(
1824                CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS);
1825        List<WifiConfiguration> result = (List<WifiConfiguration>) resultMsg.obj;
1826        resultMsg.recycle();
1827        return result;
1828    }
1829
1830    public WifiConfiguration syncGetMatchingWifiConfig(ScanResult scanResult, AsyncChannel channel) {
1831        Message resultMsg = channel.sendMessageSynchronously(CMD_GET_MATCHING_CONFIG, scanResult);
1832        return (WifiConfiguration) resultMsg.obj;
1833    }
1834
1835    /**
1836     * Get connection statistics synchronously
1837     *
1838     * @param channel
1839     * @return
1840     */
1841
1842    public WifiConnectionStatistics syncGetConnectionStatistics(AsyncChannel channel) {
1843        Message resultMsg = channel.sendMessageSynchronously(CMD_GET_CONNECTION_STATISTICS);
1844        WifiConnectionStatistics result = (WifiConnectionStatistics) resultMsg.obj;
1845        resultMsg.recycle();
1846        return result;
1847    }
1848
1849    /**
1850     * Get adaptors synchronously
1851     */
1852
1853    public int syncGetSupportedFeatures(AsyncChannel channel) {
1854        Message resultMsg = channel.sendMessageSynchronously(CMD_GET_SUPPORTED_FEATURES);
1855        int supportedFeatureSet = resultMsg.arg1;
1856        resultMsg.recycle();
1857
1858        // Mask the feature set against system properties.
1859        boolean disableRtt = mPropertyService.getBoolean("config.disable_rtt", false);
1860        if (disableRtt) {
1861            supportedFeatureSet &=
1862                    ~(WifiManager.WIFI_FEATURE_D2D_RTT | WifiManager.WIFI_FEATURE_D2AP_RTT);
1863        }
1864
1865        return supportedFeatureSet;
1866    }
1867
1868    /**
1869     * Get link layers stats for adapter synchronously
1870     */
1871    public WifiLinkLayerStats syncGetLinkLayerStats(AsyncChannel channel) {
1872        Message resultMsg = channel.sendMessageSynchronously(CMD_GET_LINK_LAYER_STATS);
1873        WifiLinkLayerStats result = (WifiLinkLayerStats) resultMsg.obj;
1874        resultMsg.recycle();
1875        return result;
1876    }
1877
1878    /**
1879     * Delete a network
1880     *
1881     * @param networkId id of the network to be removed
1882     */
1883    public boolean syncRemoveNetwork(AsyncChannel channel, int networkId) {
1884        Message resultMsg = channel.sendMessageSynchronously(CMD_REMOVE_NETWORK, networkId);
1885        boolean result = (resultMsg.arg1 != FAILURE);
1886        resultMsg.recycle();
1887        return result;
1888    }
1889
1890    /**
1891     * Enable a network
1892     *
1893     * @param netId         network id of the network
1894     * @param disableOthers true, if all other networks have to be disabled
1895     * @return {@code true} if the operation succeeds, {@code false} otherwise
1896     */
1897    public boolean syncEnableNetwork(AsyncChannel channel, int netId, boolean disableOthers) {
1898        Message resultMsg = channel.sendMessageSynchronously(CMD_ENABLE_NETWORK, netId,
1899                disableOthers ? 1 : 0);
1900        boolean result = (resultMsg.arg1 != FAILURE);
1901        resultMsg.recycle();
1902        return result;
1903    }
1904
1905    /**
1906     * Disable a network
1907     *
1908     * @param netId network id of the network
1909     * @return {@code true} if the operation succeeds, {@code false} otherwise
1910     */
1911    public boolean syncDisableNetwork(AsyncChannel channel, int netId) {
1912        Message resultMsg = channel.sendMessageSynchronously(WifiManager.DISABLE_NETWORK, netId);
1913        boolean result = (resultMsg.arg1 != WifiManager.DISABLE_NETWORK_FAILED);
1914        resultMsg.recycle();
1915        return result;
1916    }
1917
1918    /**
1919     * Retrieves a WPS-NFC configuration token for the specified network
1920     *
1921     * @return a hex string representation of the WPS-NFC configuration token
1922     */
1923    public String syncGetWpsNfcConfigurationToken(int netId) {
1924        return mWifiNative.getNfcWpsConfigurationToken(netId);
1925    }
1926
1927    public void enableRssiPolling(boolean enabled) {
1928        sendMessage(CMD_ENABLE_RSSI_POLL, enabled ? 1 : 0, 0);
1929    }
1930
1931    /**
1932     * Start filtering Multicast v4 packets
1933     */
1934    public void startFilteringMulticastPackets() {
1935        mIpManager.setMulticastFilter(true);
1936    }
1937
1938    /**
1939     * Stop filtering Multicast v4 packets
1940     */
1941    public void stopFilteringMulticastPackets() {
1942        mIpManager.setMulticastFilter(false);
1943    }
1944
1945    /**
1946     * Set high performance mode of operation.
1947     * Enabling would set active power mode and disable suspend optimizations;
1948     * disabling would set auto power mode and enable suspend optimizations
1949     *
1950     * @param enable true if enable, false otherwise
1951     */
1952    public void setHighPerfModeEnabled(boolean enable) {
1953        sendMessage(CMD_SET_HIGH_PERF_MODE, enable ? 1 : 0, 0);
1954    }
1955
1956
1957    /**
1958     * reset cached SIM credential data
1959     */
1960    public synchronized void resetSimAuthNetworks(boolean simPresent) {
1961        sendMessage(CMD_RESET_SIM_NETWORKS, simPresent ? 1 : 0);
1962    }
1963
1964    /**
1965     * Get Network object of current wifi network
1966     * @return Network object of current wifi network
1967     */
1968    public Network getCurrentNetwork() {
1969        if (mNetworkAgent != null) {
1970            return new Network(mNetworkAgent.netId);
1971        } else {
1972            return null;
1973        }
1974    }
1975
1976    /**
1977     * Enable TDLS for a specific MAC address
1978     */
1979    public void enableTdls(String remoteMacAddress, boolean enable) {
1980        int enabler = enable ? 1 : 0;
1981        sendMessage(CMD_ENABLE_TDLS, enabler, 0, remoteMacAddress);
1982    }
1983
1984    /**
1985     * Send a message indicating bluetooth adapter connection state changed
1986     */
1987    public void sendBluetoothAdapterStateChange(int state) {
1988        sendMessage(CMD_BLUETOOTH_ADAPTER_STATE_CHANGE, state, 0);
1989    }
1990
1991    /**
1992     * Send a message indicating a package has been uninstalled.
1993     */
1994    public void removeAppConfigs(String packageName, int uid) {
1995        // Build partial AppInfo manually - package may not exist in database any more
1996        ApplicationInfo ai = new ApplicationInfo();
1997        ai.packageName = packageName;
1998        ai.uid = uid;
1999        sendMessage(CMD_REMOVE_APP_CONFIGURATIONS, ai);
2000    }
2001
2002    /**
2003     * Send a message indicating a user has been removed.
2004     */
2005    public void removeUserConfigs(int userId) {
2006        sendMessage(CMD_REMOVE_USER_CONFIGURATIONS, userId);
2007    }
2008
2009    /**
2010     * Save configuration on supplicant
2011     *
2012     * @return {@code true} if the operation succeeds, {@code false} otherwise
2013     * <p/>
2014     * TODO: deprecate this
2015     */
2016    public boolean syncSaveConfig(AsyncChannel channel) {
2017        Message resultMsg = channel.sendMessageSynchronously(CMD_SAVE_CONFIG);
2018        boolean result = (resultMsg.arg1 != FAILURE);
2019        resultMsg.recycle();
2020        return result;
2021    }
2022
2023    public void updateBatteryWorkSource(WorkSource newSource) {
2024        synchronized (mRunningWifiUids) {
2025            try {
2026                if (newSource != null) {
2027                    mRunningWifiUids.set(newSource);
2028                }
2029                if (mIsRunning) {
2030                    if (mReportedRunning) {
2031                        // If the work source has changed since last time, need
2032                        // to remove old work from battery stats.
2033                        if (mLastRunningWifiUids.diff(mRunningWifiUids)) {
2034                            mBatteryStats.noteWifiRunningChanged(mLastRunningWifiUids,
2035                                    mRunningWifiUids);
2036                            mLastRunningWifiUids.set(mRunningWifiUids);
2037                        }
2038                    } else {
2039                        // Now being started, report it.
2040                        mBatteryStats.noteWifiRunning(mRunningWifiUids);
2041                        mLastRunningWifiUids.set(mRunningWifiUids);
2042                        mReportedRunning = true;
2043                    }
2044                } else {
2045                    if (mReportedRunning) {
2046                        // Last reported we were running, time to stop.
2047                        mBatteryStats.noteWifiStopped(mLastRunningWifiUids);
2048                        mLastRunningWifiUids.clear();
2049                        mReportedRunning = false;
2050                    }
2051                }
2052                mWakeLock.setWorkSource(newSource);
2053            } catch (RemoteException ignore) {
2054            }
2055        }
2056    }
2057
2058    public void dumpIpManager(FileDescriptor fd, PrintWriter pw, String[] args) {
2059        mIpManager.dump(fd, pw, args);
2060    }
2061
2062    @Override
2063    public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2064        super.dump(fd, pw, args);
2065        mSupplicantStateTracker.dump(fd, pw, args);
2066        pw.println("mLinkProperties " + mLinkProperties);
2067        pw.println("mWifiInfo " + mWifiInfo);
2068        pw.println("mDhcpResults " + mDhcpResults);
2069        pw.println("mNetworkInfo " + mNetworkInfo);
2070        pw.println("mLastSignalLevel " + mLastSignalLevel);
2071        pw.println("mLastBssid " + mLastBssid);
2072        pw.println("mLastNetworkId " + mLastNetworkId);
2073        pw.println("mOperationalMode " + mOperationalMode);
2074        pw.println("mUserWantsSuspendOpt " + mUserWantsSuspendOpt);
2075        pw.println("mSuspendOptNeedsDisabled " + mSuspendOptNeedsDisabled);
2076        pw.println("mSystemSupportsFastBssTransition "
2077                + mWifiNative.getSystemSupportsFastBssTransition());
2078        if (mCountryCode.getCountryCodeSentToDriver() != null) {
2079            pw.println("CountryCode sent to driver " + mCountryCode.getCountryCodeSentToDriver());
2080        } else {
2081            if (mCountryCode.getCountryCode() != null) {
2082                pw.println("CountryCode: " +
2083                        mCountryCode.getCountryCode() + " was not sent to driver");
2084            } else {
2085                pw.println("CountryCode was not initialized");
2086            }
2087        }
2088        if (mNetworkFactory != null) {
2089            mNetworkFactory.dump(fd, pw, args);
2090        } else {
2091            pw.println("mNetworkFactory is not initialized");
2092        }
2093
2094        if (mUntrustedNetworkFactory != null) {
2095            mUntrustedNetworkFactory.dump(fd, pw, args);
2096        } else {
2097            pw.println("mUntrustedNetworkFactory is not initialized");
2098        }
2099        pw.println("Wlan Wake Reasons:" + mWifiNative.getWlanWakeReasonCount());
2100        pw.println();
2101
2102        mWifiConfigManager.dump(fd, pw, args);
2103        pw.println();
2104        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_USER_ACTION);
2105        mWifiDiagnostics.dump(fd, pw, args);
2106        dumpIpManager(fd, pw, args);
2107        mWifiNetworkSelector.dump(fd, pw, args);
2108    }
2109
2110    public void handleUserSwitch(int userId) {
2111        sendMessage(CMD_USER_SWITCH, userId);
2112    }
2113
2114    public void handleUserUnlock(int userId) {
2115        sendMessage(CMD_USER_UNLOCK, userId);
2116    }
2117
2118    public void handleUserStop(int userId) {
2119        sendMessage(CMD_USER_STOP, userId);
2120    }
2121
2122    /**
2123     * ******************************************************
2124     * Internal private functions
2125     * ******************************************************
2126     */
2127
2128    private void logStateAndMessage(Message message, State state) {
2129        messageHandlingStatus = 0;
2130        if (mVerboseLoggingEnabled) {
2131            logd(" " + state.getClass().getSimpleName() + " " + getLogRecString(message));
2132        }
2133    }
2134
2135    /**
2136     * Return the additional string to be logged by LogRec, default
2137     *
2138     * @param msg that was processed
2139     * @return information to be logged as a String
2140     */
2141    @Override
2142    protected String getLogRecString(Message msg) {
2143        WifiConfiguration config;
2144        Long now;
2145        String report;
2146        String key;
2147        StringBuilder sb = new StringBuilder();
2148        if (mScreenOn) {
2149            sb.append("!");
2150        }
2151        if (messageHandlingStatus != MESSAGE_HANDLING_STATUS_UNKNOWN) {
2152            sb.append("(").append(messageHandlingStatus).append(")");
2153        }
2154        sb.append(smToString(msg));
2155        if (msg.sendingUid > 0 && msg.sendingUid != Process.WIFI_UID) {
2156            sb.append(" uid=" + msg.sendingUid);
2157        }
2158        sb.append(" rt=").append(mClock.getUptimeSinceBootMillis());
2159        sb.append("/").append(mClock.getElapsedSinceBootMillis());
2160        switch (msg.what) {
2161            case CMD_START_SCAN:
2162                now = mClock.getWallClockMillis();
2163                sb.append(" ");
2164                sb.append(Integer.toString(msg.arg1));
2165                sb.append(" ");
2166                sb.append(Integer.toString(msg.arg2));
2167                sb.append(" ic=");
2168                sb.append(Integer.toString(sScanAlarmIntentCount));
2169                if (msg.obj != null) {
2170                    Bundle bundle = (Bundle) msg.obj;
2171                    Long request = bundle.getLong(SCAN_REQUEST_TIME, 0);
2172                    if (request != 0) {
2173                        sb.append(" proc(ms):").append(now - request);
2174                    }
2175                }
2176                if (mIsScanOngoing) sb.append(" onGoing");
2177                if (mIsFullScanOngoing) sb.append(" full");
2178                sb.append(" rssi=").append(mWifiInfo.getRssi());
2179                sb.append(" f=").append(mWifiInfo.getFrequency());
2180                sb.append(" sc=").append(mWifiInfo.score);
2181                sb.append(" link=").append(mWifiInfo.getLinkSpeed());
2182                sb.append(String.format(" tx=%.1f,", mWifiInfo.txSuccessRate));
2183                sb.append(String.format(" %.1f,", mWifiInfo.txRetriesRate));
2184                sb.append(String.format(" %.1f ", mWifiInfo.txBadRate));
2185                sb.append(String.format(" rx=%.1f", mWifiInfo.rxSuccessRate));
2186                if (lastScanFreqs != null) {
2187                    sb.append(" list=");
2188                    for(int freq : lastScanFreqs) {
2189                        sb.append(freq).append(",");
2190                    }
2191                }
2192                report = reportOnTime();
2193                if (report != null) {
2194                    sb.append(" ").append(report);
2195                }
2196                break;
2197            case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
2198                sb.append(" ");
2199                sb.append(Integer.toString(msg.arg1));
2200                sb.append(" ");
2201                sb.append(Integer.toString(msg.arg2));
2202                StateChangeResult stateChangeResult = (StateChangeResult) msg.obj;
2203                if (stateChangeResult != null) {
2204                    sb.append(stateChangeResult.toString());
2205                }
2206                break;
2207            case WifiManager.SAVE_NETWORK:
2208                sb.append(" ");
2209                sb.append(Integer.toString(msg.arg1));
2210                sb.append(" ");
2211                sb.append(Integer.toString(msg.arg2));
2212                config = (WifiConfiguration) msg.obj;
2213                if (config != null) {
2214                    sb.append(" ").append(config.configKey());
2215                    sb.append(" nid=").append(config.networkId);
2216                    if (config.hiddenSSID) {
2217                        sb.append(" hidden");
2218                    }
2219                    if (config.preSharedKey != null
2220                            && !config.preSharedKey.equals("*")) {
2221                        sb.append(" hasPSK");
2222                    }
2223                    if (config.ephemeral) {
2224                        sb.append(" ephemeral");
2225                    }
2226                    if (config.selfAdded) {
2227                        sb.append(" selfAdded");
2228                    }
2229                    sb.append(" cuid=").append(config.creatorUid);
2230                    sb.append(" suid=").append(config.lastUpdateUid);
2231                }
2232                break;
2233            case WifiManager.FORGET_NETWORK:
2234                sb.append(" ");
2235                sb.append(Integer.toString(msg.arg1));
2236                sb.append(" ");
2237                sb.append(Integer.toString(msg.arg2));
2238                config = (WifiConfiguration) msg.obj;
2239                if (config != null) {
2240                    sb.append(" ").append(config.configKey());
2241                    sb.append(" nid=").append(config.networkId);
2242                    if (config.hiddenSSID) {
2243                        sb.append(" hidden");
2244                    }
2245                    if (config.preSharedKey != null) {
2246                        sb.append(" hasPSK");
2247                    }
2248                    if (config.ephemeral) {
2249                        sb.append(" ephemeral");
2250                    }
2251                    if (config.selfAdded) {
2252                        sb.append(" selfAdded");
2253                    }
2254                    sb.append(" cuid=").append(config.creatorUid);
2255                    sb.append(" suid=").append(config.lastUpdateUid);
2256                    WifiConfiguration.NetworkSelectionStatus netWorkSelectionStatus =
2257                            config.getNetworkSelectionStatus();
2258                    sb.append(" ajst=").append(
2259                            netWorkSelectionStatus.getNetworkStatusString());
2260                }
2261                break;
2262            case WifiMonitor.ASSOCIATION_REJECTION_EVENT:
2263                sb.append(" ");
2264                sb.append(Integer.toString(msg.arg1));
2265                sb.append(" ");
2266                sb.append(Integer.toString(msg.arg2));
2267                String bssid = (String) msg.obj;
2268                if (bssid != null && bssid.length() > 0) {
2269                    sb.append(" ");
2270                    sb.append(bssid);
2271                }
2272                sb.append(" blacklist=" + Boolean.toString(didBlackListBSSID));
2273                break;
2274            case WifiMonitor.SCAN_RESULTS_EVENT:
2275                sb.append(" ");
2276                sb.append(Integer.toString(msg.arg1));
2277                sb.append(" ");
2278                sb.append(Integer.toString(msg.arg2));
2279                if (mScanResults != null) {
2280                    sb.append(" found=");
2281                    sb.append(mScanResults.size());
2282                }
2283                sb.append(" known=").append(mNumScanResultsKnown);
2284                sb.append(" got=").append(mNumScanResultsReturned);
2285                sb.append(String.format(" bcn=%d", mRunningBeaconCount));
2286                sb.append(String.format(" con=%d", mConnectionReqCount));
2287                sb.append(String.format(" untrustedcn=%d", mUntrustedReqCount));
2288                key = mWifiConfigManager.getLastSelectedNetworkConfigKey();
2289                if (key != null) {
2290                    sb.append(" last=").append(key);
2291                }
2292                break;
2293            case WifiMonitor.SCAN_FAILED_EVENT:
2294                break;
2295            case WifiMonitor.NETWORK_CONNECTION_EVENT:
2296                sb.append(" ");
2297                sb.append(Integer.toString(msg.arg1));
2298                sb.append(" ");
2299                sb.append(Integer.toString(msg.arg2));
2300                sb.append(" ").append(mLastBssid);
2301                sb.append(" nid=").append(mLastNetworkId);
2302                config = getCurrentWifiConfiguration();
2303                if (config != null) {
2304                    sb.append(" ").append(config.configKey());
2305                }
2306                key = mWifiConfigManager.getLastSelectedNetworkConfigKey();
2307                if (key != null) {
2308                    sb.append(" last=").append(key);
2309                }
2310                break;
2311            case CMD_TARGET_BSSID:
2312            case CMD_ASSOCIATED_BSSID:
2313                sb.append(" ");
2314                sb.append(Integer.toString(msg.arg1));
2315                sb.append(" ");
2316                sb.append(Integer.toString(msg.arg2));
2317                if (msg.obj != null) {
2318                    sb.append(" BSSID=").append((String) msg.obj);
2319                }
2320                if (mTargetRoamBSSID != null) {
2321                    sb.append(" Target=").append(mTargetRoamBSSID);
2322                }
2323                sb.append(" roam=").append(Boolean.toString(mAutoRoaming));
2324                break;
2325            case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
2326                if (msg.obj != null) {
2327                    sb.append(" ").append((String) msg.obj);
2328                }
2329                sb.append(" nid=").append(msg.arg1);
2330                sb.append(" reason=").append(msg.arg2);
2331                if (mLastBssid != null) {
2332                    sb.append(" lastbssid=").append(mLastBssid);
2333                }
2334                if (mWifiInfo.getFrequency() != -1) {
2335                    sb.append(" freq=").append(mWifiInfo.getFrequency());
2336                    sb.append(" rssi=").append(mWifiInfo.getRssi());
2337                }
2338                if (isLinkDebouncing()) {
2339                    sb.append(" debounce");
2340                }
2341                break;
2342            case WifiMonitor.SSID_TEMP_DISABLED:
2343            case WifiMonitor.SSID_REENABLED:
2344                sb.append(" nid=").append(msg.arg1);
2345                if (msg.obj != null) {
2346                    sb.append(" ").append((String) msg.obj);
2347                }
2348                config = getCurrentWifiConfiguration();
2349                if (config != null) {
2350                    WifiConfiguration.NetworkSelectionStatus netWorkSelectionStatus =
2351                            config.getNetworkSelectionStatus();
2352                    sb.append(" cur=").append(config.configKey());
2353                    sb.append(" ajst=").append(netWorkSelectionStatus.getNetworkStatusString());
2354                    if (config.selfAdded) {
2355                        sb.append(" selfAdded");
2356                    }
2357                    if (config.status != 0) {
2358                        sb.append(" st=").append(config.status);
2359                        sb.append(" rs=").append(
2360                                netWorkSelectionStatus.getNetworkDisableReasonString());
2361                    }
2362                    if (config.lastConnected != 0) {
2363                        now = mClock.getWallClockMillis();
2364                        sb.append(" lastconn=").append(now - config.lastConnected).append("(ms)");
2365                    }
2366                    if (mLastBssid != null) {
2367                        sb.append(" lastbssid=").append(mLastBssid);
2368                    }
2369                    if (mWifiInfo.getFrequency() != -1) {
2370                        sb.append(" freq=").append(mWifiInfo.getFrequency());
2371                        sb.append(" rssi=").append(mWifiInfo.getRssi());
2372                        sb.append(" bssid=").append(mWifiInfo.getBSSID());
2373                    }
2374                }
2375                break;
2376            case CMD_RSSI_POLL:
2377            case CMD_UNWANTED_NETWORK:
2378            case WifiManager.RSSI_PKTCNT_FETCH:
2379                sb.append(" ");
2380                sb.append(Integer.toString(msg.arg1));
2381                sb.append(" ");
2382                sb.append(Integer.toString(msg.arg2));
2383                if (mWifiInfo.getSSID() != null)
2384                    if (mWifiInfo.getSSID() != null)
2385                        sb.append(" ").append(mWifiInfo.getSSID());
2386                if (mWifiInfo.getBSSID() != null)
2387                    sb.append(" ").append(mWifiInfo.getBSSID());
2388                sb.append(" rssi=").append(mWifiInfo.getRssi());
2389                sb.append(" f=").append(mWifiInfo.getFrequency());
2390                sb.append(" sc=").append(mWifiInfo.score);
2391                sb.append(" link=").append(mWifiInfo.getLinkSpeed());
2392                sb.append(String.format(" tx=%.1f,", mWifiInfo.txSuccessRate));
2393                sb.append(String.format(" %.1f,", mWifiInfo.txRetriesRate));
2394                sb.append(String.format(" %.1f ", mWifiInfo.txBadRate));
2395                sb.append(String.format(" rx=%.1f", mWifiInfo.rxSuccessRate));
2396                sb.append(String.format(" bcn=%d", mRunningBeaconCount));
2397                report = reportOnTime();
2398                if (report != null) {
2399                    sb.append(" ").append(report);
2400                }
2401                if (mWifiScoreReport.isLastReportValid()) {
2402                    sb.append(mWifiScoreReport.getLastReport());
2403                }
2404                break;
2405            case CMD_START_CONNECT:
2406            case WifiManager.CONNECT_NETWORK:
2407                sb.append(" ");
2408                sb.append(Integer.toString(msg.arg1));
2409                sb.append(" ");
2410                sb.append(Integer.toString(msg.arg2));
2411                config = mWifiConfigManager.getConfiguredNetwork(msg.arg1);
2412                if (config != null) {
2413                    sb.append(" ").append(config.configKey());
2414                    if (config.visibility != null) {
2415                        sb.append(" ").append(config.visibility.toString());
2416                    }
2417                }
2418                if (mTargetRoamBSSID != null) {
2419                    sb.append(" ").append(mTargetRoamBSSID);
2420                }
2421                sb.append(" roam=").append(Boolean.toString(mAutoRoaming));
2422                config = getCurrentWifiConfiguration();
2423                if (config != null) {
2424                    sb.append(config.configKey());
2425                    if (config.visibility != null) {
2426                        sb.append(" ").append(config.visibility.toString());
2427                    }
2428                }
2429                break;
2430            case CMD_START_ROAM:
2431                sb.append(" ");
2432                sb.append(Integer.toString(msg.arg1));
2433                sb.append(" ");
2434                sb.append(Integer.toString(msg.arg2));
2435                ScanResult result = (ScanResult) msg.obj;
2436                if (result != null) {
2437                    now = mClock.getWallClockMillis();
2438                    sb.append(" bssid=").append(result.BSSID);
2439                    sb.append(" rssi=").append(result.level);
2440                    sb.append(" freq=").append(result.frequency);
2441                    if (result.seen > 0 && result.seen < now) {
2442                        sb.append(" seen=").append(now - result.seen);
2443                    } else {
2444                        // Somehow the timestamp for this scan result is inconsistent
2445                        sb.append(" !seen=").append(result.seen);
2446                    }
2447                }
2448                if (mTargetRoamBSSID != null) {
2449                    sb.append(" ").append(mTargetRoamBSSID);
2450                }
2451                sb.append(" roam=").append(Boolean.toString(mAutoRoaming));
2452                sb.append(" fail count=").append(Integer.toString(mRoamFailCount));
2453                break;
2454            case CMD_ADD_OR_UPDATE_NETWORK:
2455                sb.append(" ");
2456                sb.append(Integer.toString(msg.arg1));
2457                sb.append(" ");
2458                sb.append(Integer.toString(msg.arg2));
2459                if (msg.obj != null) {
2460                    config = (WifiConfiguration) msg.obj;
2461                    sb.append(" ").append(config.configKey());
2462                    sb.append(" prio=").append(config.priority);
2463                    sb.append(" status=").append(config.status);
2464                    if (config.BSSID != null) {
2465                        sb.append(" ").append(config.BSSID);
2466                    }
2467                    WifiConfiguration curConfig = getCurrentWifiConfiguration();
2468                    if (curConfig != null) {
2469                        if (curConfig.configKey().equals(config.configKey())) {
2470                            sb.append(" is current");
2471                        } else {
2472                            sb.append(" current=").append(curConfig.configKey());
2473                            sb.append(" prio=").append(curConfig.priority);
2474                            sb.append(" status=").append(curConfig.status);
2475                        }
2476                    }
2477                }
2478                break;
2479            case WifiManager.DISABLE_NETWORK:
2480            case CMD_ENABLE_NETWORK:
2481                sb.append(" ");
2482                sb.append(Integer.toString(msg.arg1));
2483                sb.append(" ");
2484                sb.append(Integer.toString(msg.arg2));
2485                key = mWifiConfigManager.getLastSelectedNetworkConfigKey();
2486                if (key != null) {
2487                    sb.append(" last=").append(key);
2488                }
2489                config = mWifiConfigManager.getConfiguredNetwork(msg.arg1);
2490                if (config != null && (key == null || !config.configKey().equals(key))) {
2491                    sb.append(" target=").append(key);
2492                }
2493                break;
2494            case CMD_GET_CONFIGURED_NETWORKS:
2495                sb.append(" ");
2496                sb.append(Integer.toString(msg.arg1));
2497                sb.append(" ");
2498                sb.append(Integer.toString(msg.arg2));
2499                sb.append(" num=").append(mWifiConfigManager.getConfiguredNetworks().size());
2500                break;
2501            case DhcpClient.CMD_PRE_DHCP_ACTION:
2502                sb.append(" ");
2503                sb.append(Integer.toString(msg.arg1));
2504                sb.append(" ");
2505                sb.append(Integer.toString(msg.arg2));
2506                sb.append(" txpkts=").append(mWifiInfo.txSuccess);
2507                sb.append(",").append(mWifiInfo.txBad);
2508                sb.append(",").append(mWifiInfo.txRetries);
2509                break;
2510            case DhcpClient.CMD_POST_DHCP_ACTION:
2511                sb.append(" ");
2512                sb.append(Integer.toString(msg.arg1));
2513                sb.append(" ");
2514                sb.append(Integer.toString(msg.arg2));
2515                if (msg.arg1 == DhcpClient.DHCP_SUCCESS) {
2516                    sb.append(" OK ");
2517                } else if (msg.arg1 == DhcpClient.DHCP_FAILURE) {
2518                    sb.append(" FAIL ");
2519                }
2520                if (mLinkProperties != null) {
2521                    sb.append(" ");
2522                    sb.append(getLinkPropertiesSummary(mLinkProperties));
2523                }
2524                break;
2525            case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED:
2526                sb.append(" ");
2527                sb.append(Integer.toString(msg.arg1));
2528                sb.append(" ");
2529                sb.append(Integer.toString(msg.arg2));
2530                if (msg.obj != null) {
2531                    NetworkInfo info = (NetworkInfo) msg.obj;
2532                    NetworkInfo.State state = info.getState();
2533                    NetworkInfo.DetailedState detailedState = info.getDetailedState();
2534                    if (state != null) {
2535                        sb.append(" st=").append(state);
2536                    }
2537                    if (detailedState != null) {
2538                        sb.append("/").append(detailedState);
2539                    }
2540                }
2541                break;
2542            case CMD_IP_CONFIGURATION_LOST:
2543                int count = -1;
2544                WifiConfiguration c = getCurrentWifiConfiguration();
2545                if (c != null) {
2546                    count = c.getNetworkSelectionStatus().getDisableReasonCounter(
2547                            WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE);
2548                }
2549                sb.append(" ");
2550                sb.append(Integer.toString(msg.arg1));
2551                sb.append(" ");
2552                sb.append(Integer.toString(msg.arg2));
2553                sb.append(" failures: ");
2554                sb.append(Integer.toString(count));
2555                sb.append("/");
2556                sb.append(Integer.toString(mFacade.getIntegerSetting(
2557                        mContext, Settings.Global.WIFI_MAX_DHCP_RETRY_COUNT, 0)));
2558                if (mWifiInfo.getBSSID() != null) {
2559                    sb.append(" ").append(mWifiInfo.getBSSID());
2560                }
2561                sb.append(String.format(" bcn=%d", mRunningBeaconCount));
2562                break;
2563            case CMD_UPDATE_LINKPROPERTIES:
2564                sb.append(" ");
2565                sb.append(Integer.toString(msg.arg1));
2566                sb.append(" ");
2567                sb.append(Integer.toString(msg.arg2));
2568                if (mLinkProperties != null) {
2569                    sb.append(" ");
2570                    sb.append(getLinkPropertiesSummary(mLinkProperties));
2571                }
2572                break;
2573            case CMD_IP_REACHABILITY_LOST:
2574                if (msg.obj != null) {
2575                    sb.append(" ").append((String) msg.obj);
2576                }
2577                break;
2578            case CMD_INSTALL_PACKET_FILTER:
2579                sb.append(" len=" + ((byte[])msg.obj).length);
2580                break;
2581            case CMD_SET_FALLBACK_PACKET_FILTERING:
2582                sb.append(" enabled=" + (boolean)msg.obj);
2583                break;
2584            case CMD_ROAM_WATCHDOG_TIMER:
2585                sb.append(" ");
2586                sb.append(Integer.toString(msg.arg1));
2587                sb.append(" ");
2588                sb.append(Integer.toString(msg.arg2));
2589                sb.append(" cur=").append(roamWatchdogCount);
2590                break;
2591            case CMD_DISCONNECTING_WATCHDOG_TIMER:
2592                sb.append(" ");
2593                sb.append(Integer.toString(msg.arg1));
2594                sb.append(" ");
2595                sb.append(Integer.toString(msg.arg2));
2596                sb.append(" cur=").append(disconnectingWatchdogCount);
2597                break;
2598            case CMD_START_RSSI_MONITORING_OFFLOAD:
2599            case CMD_STOP_RSSI_MONITORING_OFFLOAD:
2600            case CMD_RSSI_THRESHOLD_BREACH:
2601                sb.append(" rssi=");
2602                sb.append(Integer.toString(msg.arg1));
2603                sb.append(" thresholds=");
2604                sb.append(Arrays.toString(mRssiRanges));
2605                break;
2606            case CMD_USER_SWITCH:
2607                sb.append(" userId=");
2608                sb.append(Integer.toString(msg.arg1));
2609                break;
2610            case CMD_IPV4_PROVISIONING_SUCCESS:
2611                sb.append(" ");
2612                if (msg.arg1 == DhcpClient.DHCP_SUCCESS) {
2613                    sb.append("DHCP_OK");
2614                } else if (msg.arg1 == CMD_STATIC_IP_SUCCESS) {
2615                    sb.append("STATIC_OK");
2616                } else {
2617                    sb.append(Integer.toString(msg.arg1));
2618                }
2619                break;
2620            case CMD_IPV4_PROVISIONING_FAILURE:
2621                sb.append(" ");
2622                if (msg.arg1 == DhcpClient.DHCP_FAILURE) {
2623                    sb.append("DHCP_FAIL");
2624                } else if (msg.arg1 == CMD_STATIC_IP_FAILURE) {
2625                    sb.append("STATIC_FAIL");
2626                } else {
2627                    sb.append(Integer.toString(msg.arg1));
2628                }
2629                break;
2630            default:
2631                sb.append(" ");
2632                sb.append(Integer.toString(msg.arg1));
2633                sb.append(" ");
2634                sb.append(Integer.toString(msg.arg2));
2635                break;
2636        }
2637
2638        return sb.toString();
2639    }
2640
2641    private void handleScreenStateChanged(boolean screenOn) {
2642        mScreenOn = screenOn;
2643        if (mVerboseLoggingEnabled) {
2644            logd(" handleScreenStateChanged Enter: screenOn=" + screenOn
2645                    + " mUserWantsSuspendOpt=" + mUserWantsSuspendOpt
2646                    + " state " + getCurrentState().getName()
2647                    + " suppState:" + mSupplicantStateTracker.getSupplicantStateName());
2648        }
2649        enableRssiPolling(screenOn);
2650        if (mUserWantsSuspendOpt.get()) {
2651            int shouldReleaseWakeLock = 0;
2652            if (screenOn) {
2653                sendMessage(CMD_SET_SUSPEND_OPT_ENABLED, 0, shouldReleaseWakeLock);
2654            } else {
2655                if (isConnected()) {
2656                    // Allow 2s for suspend optimizations to be set
2657                    mSuspendWakeLock.acquire(2000);
2658                    shouldReleaseWakeLock = 1;
2659                }
2660                sendMessage(CMD_SET_SUSPEND_OPT_ENABLED, 1, shouldReleaseWakeLock);
2661            }
2662        }
2663
2664        getWifiLinkLayerStats();
2665        mOnTimeScreenStateChange = mOnTime;
2666        lastScreenStateChangeTimeStamp = lastLinkLayerStatsUpdate;
2667
2668        mWifiMetrics.setScreenState(screenOn);
2669
2670        if (mWifiConnectivityManager != null) {
2671            mWifiConnectivityManager.handleScreenStateChanged(screenOn);
2672        }
2673
2674        if (mVerboseLoggingEnabled) log("handleScreenStateChanged Exit: " + screenOn);
2675    }
2676
2677    private void checkAndSetConnectivityInstance() {
2678        if (mCm == null) {
2679            mCm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
2680        }
2681    }
2682
2683    private void setSuspendOptimizationsNative(int reason, boolean enabled) {
2684        if (mVerboseLoggingEnabled) {
2685            log("setSuspendOptimizationsNative: " + reason + " " + enabled
2686                    + " -want " + mUserWantsSuspendOpt.get()
2687                    + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
2688                    + " - " + Thread.currentThread().getStackTrace()[3].getMethodName()
2689                    + " - " + Thread.currentThread().getStackTrace()[4].getMethodName()
2690                    + " - " + Thread.currentThread().getStackTrace()[5].getMethodName());
2691        }
2692        //mWifiNative.setSuspendOptimizations(enabled);
2693
2694        if (enabled) {
2695            mSuspendOptNeedsDisabled &= ~reason;
2696            /* None of dhcp, screen or highperf need it disabled and user wants it enabled */
2697            if (mSuspendOptNeedsDisabled == 0 && mUserWantsSuspendOpt.get()) {
2698                if (mVerboseLoggingEnabled) {
2699                    log("setSuspendOptimizationsNative do it " + reason + " " + enabled
2700                            + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
2701                            + " - " + Thread.currentThread().getStackTrace()[3].getMethodName()
2702                            + " - " + Thread.currentThread().getStackTrace()[4].getMethodName()
2703                            + " - " + Thread.currentThread().getStackTrace()[5].getMethodName());
2704                }
2705                mWifiNative.setSuspendOptimizations(true);
2706            }
2707        } else {
2708            mSuspendOptNeedsDisabled |= reason;
2709            mWifiNative.setSuspendOptimizations(false);
2710        }
2711    }
2712
2713    private void setSuspendOptimizations(int reason, boolean enabled) {
2714        if (mVerboseLoggingEnabled) log("setSuspendOptimizations: " + reason + " " + enabled);
2715        if (enabled) {
2716            mSuspendOptNeedsDisabled &= ~reason;
2717        } else {
2718            mSuspendOptNeedsDisabled |= reason;
2719        }
2720        if (mVerboseLoggingEnabled) log("mSuspendOptNeedsDisabled " + mSuspendOptNeedsDisabled);
2721    }
2722
2723    private void setWifiState(int wifiState) {
2724        final int previousWifiState = mWifiState.get();
2725
2726        try {
2727            if (wifiState == WIFI_STATE_ENABLED) {
2728                mBatteryStats.noteWifiOn();
2729            } else if (wifiState == WIFI_STATE_DISABLED) {
2730                mBatteryStats.noteWifiOff();
2731            }
2732        } catch (RemoteException e) {
2733            loge("Failed to note battery stats in wifi");
2734        }
2735
2736        mWifiState.set(wifiState);
2737
2738        if (mVerboseLoggingEnabled) log("setWifiState: " + syncGetWifiStateByName());
2739
2740        final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION);
2741        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2742        intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState);
2743        intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState);
2744        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2745    }
2746
2747    private void setWifiApState(int wifiApState, int reason) {
2748        final int previousWifiApState = mWifiApState.get();
2749
2750        try {
2751            if (wifiApState == WIFI_AP_STATE_ENABLED) {
2752                mBatteryStats.noteWifiOn();
2753            } else if (wifiApState == WIFI_AP_STATE_DISABLED) {
2754                mBatteryStats.noteWifiOff();
2755            }
2756        } catch (RemoteException e) {
2757            loge("Failed to note battery stats in wifi");
2758        }
2759
2760        // Update state
2761        mWifiApState.set(wifiApState);
2762
2763        if (mVerboseLoggingEnabled) log("setWifiApState: " + syncGetWifiApStateByName());
2764
2765        final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
2766        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2767        intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiApState);
2768        intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState);
2769        if (wifiApState == WifiManager.WIFI_AP_STATE_FAILED) {
2770            //only set reason number when softAP start failed
2771            intent.putExtra(WifiManager.EXTRA_WIFI_AP_FAILURE_REASON, reason);
2772        }
2773
2774        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2775    }
2776
2777    private void setScanResults() {
2778        mNumScanResultsKnown = 0;
2779        mNumScanResultsReturned = 0;
2780
2781        ArrayList<ScanDetail> scanResults = mWifiNative.getScanResults();
2782
2783        if (scanResults.isEmpty()) {
2784            mScanResults = new ArrayList<>();
2785            return;
2786        }
2787
2788        // TODO(b/31065385): mWifiConfigManager.trimANQPCache(false);
2789
2790        boolean connected = mLastBssid != null;
2791        long activeBssid = 0L;
2792        if (connected) {
2793            try {
2794                activeBssid = Utils.parseMac(mLastBssid);
2795            } catch (IllegalArgumentException iae) {
2796                connected = false;
2797            }
2798        }
2799
2800        synchronized (mScanResultsLock) {
2801            mScanResults = scanResults;
2802            mNumScanResultsReturned = mScanResults.size();
2803        }
2804
2805        if (isLinkDebouncing()) {
2806            // If debouncing, we dont re-select a SSID or BSSID hence
2807            // there is no need to call the network selection code
2808            // in WifiAutoJoinController, instead,
2809            // just try to reconnect to the same SSID by triggering a roam
2810            // The third parameter 1 means roam not from network selection but debouncing
2811            sendMessage(CMD_START_ROAM, mLastNetworkId, 1, null);
2812        }
2813    }
2814
2815    /*
2816     * Fetch RSSI, linkspeed, and frequency on current connection
2817     */
2818    private void fetchRssiLinkSpeedAndFrequencyNative() {
2819        Integer newRssi = null;
2820        Integer newLinkSpeed = null;
2821        Integer newFrequency = null;
2822        WifiNative.SignalPollResult pollResult = mWifiNative.signalPoll();
2823        if (pollResult == null) {
2824            return;
2825        }
2826
2827        newRssi = pollResult.currentRssi;
2828        newLinkSpeed = pollResult.txBitrate;
2829        newFrequency = pollResult.associationFrequency;
2830
2831        if (mVerboseLoggingEnabled) {
2832            logd("fetchRssiLinkSpeedAndFrequencyNative rssi=" + newRssi +
2833                 " linkspeed=" + newLinkSpeed + " freq=" + newFrequency);
2834        }
2835
2836        if (newRssi != null && newRssi > WifiInfo.INVALID_RSSI && newRssi < WifiInfo.MAX_RSSI) {
2837            // screen out invalid values
2838            /* some implementations avoid negative values by adding 256
2839             * so we need to adjust for that here.
2840             */
2841            if (newRssi > 0) newRssi -= 256;
2842            mWifiInfo.setRssi(newRssi);
2843            /*
2844             * Log the rssi poll value in metrics
2845             */
2846            mWifiMetrics.incrementRssiPollRssiCount(newRssi);
2847            /*
2848             * Rather then sending the raw RSSI out every time it
2849             * changes, we precalculate the signal level that would
2850             * be displayed in the status bar, and only send the
2851             * broadcast if that much more coarse-grained number
2852             * changes. This cuts down greatly on the number of
2853             * broadcasts, at the cost of not informing others
2854             * interested in RSSI of all the changes in signal
2855             * level.
2856             */
2857            int newSignalLevel = WifiManager.calculateSignalLevel(newRssi, WifiManager.RSSI_LEVELS);
2858            if (newSignalLevel != mLastSignalLevel) {
2859                updateCapabilities(getCurrentWifiConfiguration());
2860                sendRssiChangeBroadcast(newRssi);
2861            }
2862            mLastSignalLevel = newSignalLevel;
2863        } else {
2864            mWifiInfo.setRssi(WifiInfo.INVALID_RSSI);
2865            updateCapabilities(getCurrentWifiConfiguration());
2866        }
2867
2868        if (newLinkSpeed != null) {
2869            mWifiInfo.setLinkSpeed(newLinkSpeed);
2870        }
2871        if (newFrequency != null && newFrequency > 0) {
2872            if (ScanResult.is5GHz(newFrequency)) {
2873                mWifiConnectionStatistics.num5GhzConnected++;
2874            }
2875            if (ScanResult.is24GHz(newFrequency)) {
2876                mWifiConnectionStatistics.num24GhzConnected++;
2877            }
2878            mWifiInfo.setFrequency(newFrequency);
2879        }
2880        mWifiConfigManager.updateScanDetailCacheFromWifiInfo(mWifiInfo);
2881    }
2882
2883    // Polling has completed, hence we wont have a score anymore
2884    private void cleanWifiScore() {
2885        mWifiInfo.txBadRate = 0;
2886        mWifiInfo.txSuccessRate = 0;
2887        mWifiInfo.txRetriesRate = 0;
2888        mWifiInfo.rxSuccessRate = 0;
2889        mWifiScoreReport.reset();
2890    }
2891
2892    private void updateLinkProperties(LinkProperties newLp) {
2893        if (mVerboseLoggingEnabled) {
2894            log("Link configuration changed for netId: " + mLastNetworkId
2895                    + " old: " + mLinkProperties + " new: " + newLp);
2896        }
2897        // We own this instance of LinkProperties because IpManager passes us a copy.
2898        mLinkProperties = newLp;
2899        if (mNetworkAgent != null) {
2900            mNetworkAgent.sendLinkProperties(mLinkProperties);
2901        }
2902
2903        if (getNetworkDetailedState() == DetailedState.CONNECTED) {
2904            // If anything has changed and we're already connected, send out a notification.
2905            // TODO: Update all callers to use NetworkCallbacks and delete this.
2906            sendLinkConfigurationChangedBroadcast();
2907        }
2908
2909        if (mVerboseLoggingEnabled) {
2910            StringBuilder sb = new StringBuilder();
2911            sb.append("updateLinkProperties nid: " + mLastNetworkId);
2912            sb.append(" state: " + getNetworkDetailedState());
2913
2914            if (mLinkProperties != null) {
2915                sb.append(" ");
2916                sb.append(getLinkPropertiesSummary(mLinkProperties));
2917            }
2918            logd(sb.toString());
2919        }
2920    }
2921
2922    /**
2923     * Clears all our link properties.
2924     */
2925    private void clearLinkProperties() {
2926        // Clear the link properties obtained from DHCP. The only caller of this
2927        // function has already called IpManager#stop(), which clears its state.
2928        synchronized (mDhcpResultsLock) {
2929            if (mDhcpResults != null) {
2930                mDhcpResults.clear();
2931            }
2932        }
2933
2934        // Now clear the merged link properties.
2935        mLinkProperties.clear();
2936        if (mNetworkAgent != null) mNetworkAgent.sendLinkProperties(mLinkProperties);
2937    }
2938
2939    /**
2940     * try to update default route MAC address.
2941     */
2942    private String updateDefaultRouteMacAddress(int timeout) {
2943        String address = null;
2944        for (RouteInfo route : mLinkProperties.getRoutes()) {
2945            if (route.isDefaultRoute() && route.hasGateway()) {
2946                InetAddress gateway = route.getGateway();
2947                if (gateway instanceof Inet4Address) {
2948                    if (mVerboseLoggingEnabled) {
2949                        logd("updateDefaultRouteMacAddress found Ipv4 default :"
2950                                + gateway.getHostAddress());
2951                    }
2952                    address = macAddressFromRoute(gateway.getHostAddress());
2953                    /* The gateway's MAC address is known */
2954                    if ((address == null) && (timeout > 0)) {
2955                        boolean reachable = false;
2956                        TrafficStats.setThreadStatsTag(TrafficStats.TAG_SYSTEM_PROBE);
2957                        try {
2958                            reachable = gateway.isReachable(timeout);
2959                        } catch (Exception e) {
2960                            loge("updateDefaultRouteMacAddress exception reaching :"
2961                                    + gateway.getHostAddress());
2962
2963                        } finally {
2964                            TrafficStats.clearThreadStatsTag();
2965                            if (reachable == true) {
2966
2967                                address = macAddressFromRoute(gateway.getHostAddress());
2968                                if (mVerboseLoggingEnabled) {
2969                                    logd("updateDefaultRouteMacAddress reachable (tried again) :"
2970                                            + gateway.getHostAddress() + " found " + address);
2971                                }
2972                            }
2973                        }
2974                    }
2975                    if (address != null) {
2976                        mWifiConfigManager.setNetworkDefaultGwMacAddress(mLastNetworkId, address);
2977                    }
2978                }
2979            }
2980        }
2981        return address;
2982    }
2983
2984    private void sendRssiChangeBroadcast(final int newRssi) {
2985        try {
2986            mBatteryStats.noteWifiRssiChanged(newRssi);
2987        } catch (RemoteException e) {
2988            // Won't happen.
2989        }
2990        Intent intent = new Intent(WifiManager.RSSI_CHANGED_ACTION);
2991        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2992        intent.putExtra(WifiManager.EXTRA_NEW_RSSI, newRssi);
2993        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2994    }
2995
2996    private void sendNetworkStateChangeBroadcast(String bssid) {
2997        Intent intent = new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION);
2998        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2999        intent.putExtra(WifiManager.EXTRA_NETWORK_INFO, new NetworkInfo(mNetworkInfo));
3000        intent.putExtra(WifiManager.EXTRA_LINK_PROPERTIES, new LinkProperties(mLinkProperties));
3001        if (bssid != null)
3002            intent.putExtra(WifiManager.EXTRA_BSSID, bssid);
3003        if (mNetworkInfo.getDetailedState() == DetailedState.VERIFYING_POOR_LINK ||
3004                mNetworkInfo.getDetailedState() == DetailedState.CONNECTED) {
3005            // We no longer report MAC address to third-parties and our code does
3006            // not rely on this broadcast, so just send the default MAC address.
3007            fetchRssiLinkSpeedAndFrequencyNative();
3008            WifiInfo sentWifiInfo = new WifiInfo(mWifiInfo);
3009            sentWifiInfo.setMacAddress(WifiInfo.DEFAULT_MAC_ADDRESS);
3010            intent.putExtra(WifiManager.EXTRA_WIFI_INFO, sentWifiInfo);
3011        }
3012        mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3013    }
3014
3015    private WifiInfo getWiFiInfoForUid(int uid) {
3016        if (Binder.getCallingUid() == Process.myUid()) {
3017            return mWifiInfo;
3018        }
3019
3020        WifiInfo result = new WifiInfo(mWifiInfo);
3021        result.setMacAddress(WifiInfo.DEFAULT_MAC_ADDRESS);
3022
3023        IBinder binder = mFacade.getService("package");
3024        IPackageManager packageManager = IPackageManager.Stub.asInterface(binder);
3025
3026        try {
3027            if (packageManager.checkUidPermission(Manifest.permission.LOCAL_MAC_ADDRESS,
3028                    uid) == PackageManager.PERMISSION_GRANTED) {
3029                result.setMacAddress(mWifiInfo.getMacAddress());
3030            }
3031        } catch (RemoteException e) {
3032            Log.e(TAG, "Error checking receiver permission", e);
3033        }
3034
3035        return result;
3036    }
3037
3038    private void sendLinkConfigurationChangedBroadcast() {
3039        Intent intent = new Intent(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION);
3040        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3041        intent.putExtra(WifiManager.EXTRA_LINK_PROPERTIES, new LinkProperties(mLinkProperties));
3042        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3043    }
3044
3045    private void sendSupplicantConnectionChangedBroadcast(boolean connected) {
3046        Intent intent = new Intent(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
3047        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3048        intent.putExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, connected);
3049        mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3050    }
3051
3052    /**
3053     * Record the detailed state of a network.
3054     *
3055     * @param state the new {@code DetailedState}
3056     */
3057    private boolean setNetworkDetailedState(NetworkInfo.DetailedState state) {
3058        boolean hidden = false;
3059
3060        if (isLinkDebouncing() || isRoaming()) {
3061            // There is generally a confusion in the system about colluding
3062            // WiFi Layer 2 state (as reported by supplicant) and the Network state
3063            // which leads to multiple confusion.
3064            //
3065            // If link is de-bouncing or roaming, we already have an IP address
3066            // as well we were connected and are doing L2 cycles of
3067            // reconnecting or renewing IP address to check that we still have it
3068            // This L2 link flapping should ne be reflected into the Network state
3069            // which is the state of the WiFi Network visible to Layer 3 and applications
3070            // Note that once debouncing and roaming are completed, we will
3071            // set the Network state to where it should be, or leave it as unchanged
3072            //
3073            hidden = true;
3074        }
3075        if (mVerboseLoggingEnabled) {
3076            log("setDetailed state, old ="
3077                    + mNetworkInfo.getDetailedState() + " and new state=" + state
3078                    + " hidden=" + hidden);
3079        }
3080        if (mNetworkInfo.getExtraInfo() != null && mWifiInfo.getSSID() != null
3081                && !mWifiInfo.getSSID().equals(WifiSsid.NONE)) {
3082            // Always indicate that SSID has changed
3083            if (!mNetworkInfo.getExtraInfo().equals(mWifiInfo.getSSID())) {
3084                if (mVerboseLoggingEnabled) {
3085                    log("setDetailed state send new extra info" + mWifiInfo.getSSID());
3086                }
3087                mNetworkInfo.setExtraInfo(mWifiInfo.getSSID());
3088                sendNetworkStateChangeBroadcast(null);
3089            }
3090        }
3091        if (hidden == true) {
3092            return false;
3093        }
3094
3095        if (state != mNetworkInfo.getDetailedState()) {
3096            mNetworkInfo.setDetailedState(state, null, mWifiInfo.getSSID());
3097            if (mNetworkAgent != null) {
3098                mNetworkAgent.sendNetworkInfo(mNetworkInfo);
3099            }
3100            sendNetworkStateChangeBroadcast(null);
3101            return true;
3102        }
3103        return false;
3104    }
3105
3106    private DetailedState getNetworkDetailedState() {
3107        return mNetworkInfo.getDetailedState();
3108    }
3109
3110    private SupplicantState handleSupplicantStateChange(Message message) {
3111        StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
3112        SupplicantState state = stateChangeResult.state;
3113        // Supplicant state change
3114        // [31-13] Reserved for future use
3115        // [8 - 0] Supplicant state (as defined in SupplicantState.java)
3116        // 50023 supplicant_state_changed (custom|1|5)
3117        mWifiInfo.setSupplicantState(state);
3118        // If we receive a supplicant state change with an empty SSID,
3119        // this implies that wpa_supplicant is already disconnected.
3120        // We should pretend we are still connected when linkDebouncing is on.
3121        if ((stateChangeResult.wifiSsid == null
3122                || stateChangeResult.wifiSsid.toString().isEmpty()) && isLinkDebouncing()) {
3123            return state;
3124        }
3125        // Network id is only valid when we start connecting
3126        if (SupplicantState.isConnecting(state)) {
3127            mWifiInfo.setNetworkId(lookupFrameworkNetworkId(stateChangeResult.networkId));
3128        } else {
3129            mWifiInfo.setNetworkId(WifiConfiguration.INVALID_NETWORK_ID);
3130        }
3131
3132        mWifiInfo.setBSSID(stateChangeResult.BSSID);
3133
3134        mWifiInfo.setSSID(stateChangeResult.wifiSsid);
3135        WifiConfiguration config = getCurrentWifiConfiguration();
3136        if (config != null) {
3137            // Set meteredHint to true if the access network type of the connecting/connected AP
3138            // is a chargeable public network.
3139            ScanDetailCache scanDetailCache = mWifiConfigManager.getScanDetailCacheForNetwork(
3140                    config.networkId);
3141            if (scanDetailCache != null) {
3142                ScanDetail scanDetail = scanDetailCache.getScanDetail(stateChangeResult.BSSID);
3143                if (scanDetail != null) {
3144                    NetworkDetail networkDetail = scanDetail.getNetworkDetail();
3145                    if (networkDetail != null
3146                            && networkDetail.getAnt() == NetworkDetail.Ant.ChargeablePublic) {
3147                        mWifiInfo.setMeteredHint(true);
3148                    }
3149                }
3150            }
3151
3152            mWifiInfo.setEphemeral(config.ephemeral);
3153            if (!mWifiInfo.getMeteredHint()) { // don't override the value if already set.
3154                mWifiInfo.setMeteredHint(config.meteredHint);
3155            }
3156        }
3157
3158        mSupplicantStateTracker.sendMessage(Message.obtain(message));
3159
3160        return state;
3161    }
3162
3163    /**
3164     * Resets the Wi-Fi Connections by clearing any state, resetting any sockets
3165     * using the interface, stopping DHCP & disabling interface
3166     */
3167    private void handleNetworkDisconnect() {
3168        if (mVerboseLoggingEnabled) {
3169            log("handleNetworkDisconnect: Stopping DHCP and clearing IP"
3170                    + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName()
3171                    + " - " + Thread.currentThread().getStackTrace()[3].getMethodName()
3172                    + " - " + Thread.currentThread().getStackTrace()[4].getMethodName()
3173                    + " - " + Thread.currentThread().getStackTrace()[5].getMethodName());
3174        }
3175
3176        stopRssiMonitoringOffload();
3177
3178        clearTargetBssid("handleNetworkDisconnect");
3179
3180        stopIpManager();
3181
3182        /* Reset data structures */
3183        mWifiScoreReport.reset();
3184        mWifiInfo.reset();
3185        mIsLinkDebouncing = false;
3186        /* Reset roaming parameters */
3187        mAutoRoaming = false;
3188
3189        setNetworkDetailedState(DetailedState.DISCONNECTED);
3190        if (mNetworkAgent != null) {
3191            mNetworkAgent.sendNetworkInfo(mNetworkInfo);
3192            mNetworkAgent = null;
3193        }
3194
3195        /* Clear network properties */
3196        clearLinkProperties();
3197
3198        /* Cend event to CM & network change broadcast */
3199        sendNetworkStateChangeBroadcast(mLastBssid);
3200
3201        mLastBssid = null;
3202        registerDisconnected();
3203        mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID;
3204    }
3205
3206    private void handleSupplicantConnectionLoss(boolean killSupplicant) {
3207        /* Socket connection can be lost when we do a graceful shutdown
3208        * or when the driver is hung. Ensure supplicant is stopped here.
3209        */
3210        if (killSupplicant) {
3211            mWifiMonitor.stopAllMonitoring();
3212            if (!mWifiNative.disableSupplicant()) {
3213                loge("Failed to disable supplicant after connection loss");
3214            }
3215        }
3216        mWifiNative.closeSupplicantConnection();
3217        sendSupplicantConnectionChangedBroadcast(false);
3218        setWifiState(WIFI_STATE_DISABLED);
3219    }
3220
3221    void handlePreDhcpSetup() {
3222        if (!mBluetoothConnectionActive) {
3223            /*
3224             * There are problems setting the Wi-Fi driver's power
3225             * mode to active when bluetooth coexistence mode is
3226             * enabled or sense.
3227             * <p>
3228             * We set Wi-Fi to active mode when
3229             * obtaining an IP address because we've found
3230             * compatibility issues with some routers with low power
3231             * mode.
3232             * <p>
3233             * In order for this active power mode to properly be set,
3234             * we disable coexistence mode until we're done with
3235             * obtaining an IP address.  One exception is if we
3236             * are currently connected to a headset, since disabling
3237             * coexistence would interrupt that connection.
3238             */
3239            // Disable the coexistence mode
3240            mWifiNative.setBluetoothCoexistenceMode(
3241                    WifiNative.BLUETOOTH_COEXISTENCE_MODE_DISABLED);
3242        }
3243
3244        // Disable power save and suspend optimizations during DHCP
3245        // Note: The order here is important for now. Brcm driver changes
3246        // power settings when we control suspend mode optimizations.
3247        // TODO: Remove this comment when the driver is fixed.
3248        setSuspendOptimizationsNative(SUSPEND_DUE_TO_DHCP, false);
3249        mWifiNative.setPowerSave(false);
3250
3251        // Update link layer stats
3252        getWifiLinkLayerStats();
3253
3254        if (mWifiP2pChannel != null) {
3255            /* P2p discovery breaks dhcp, shut it down in order to get through this */
3256            Message msg = new Message();
3257            msg.what = WifiP2pServiceImpl.BLOCK_DISCOVERY;
3258            msg.arg1 = WifiP2pServiceImpl.ENABLED;
3259            msg.arg2 = DhcpClient.CMD_PRE_DHCP_ACTION_COMPLETE;
3260            msg.obj = WifiStateMachine.this;
3261            mWifiP2pChannel.sendMessage(msg);
3262        } else {
3263            // If the p2p service is not running, we can proceed directly.
3264            sendMessage(DhcpClient.CMD_PRE_DHCP_ACTION_COMPLETE);
3265        }
3266    }
3267
3268    void handlePostDhcpSetup() {
3269        /* Restore power save and suspend optimizations */
3270        setSuspendOptimizationsNative(SUSPEND_DUE_TO_DHCP, true);
3271        mWifiNative.setPowerSave(true);
3272
3273        p2pSendMessage(WifiP2pServiceImpl.BLOCK_DISCOVERY, WifiP2pServiceImpl.DISABLED);
3274
3275        // Set the coexistence mode back to its default value
3276        mWifiNative.setBluetoothCoexistenceMode(
3277                WifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE);
3278    }
3279
3280    private static final long DIAGS_CONNECT_TIMEOUT_MILLIS = 60 * 1000;
3281    private long mDiagsConnectionStartMillis = -1;
3282    /**
3283     * Inform other components that a new connection attempt is starting.
3284     */
3285    private void reportConnectionAttemptStart(
3286            WifiConfiguration config, String targetBSSID, int roamType) {
3287        mWifiMetrics.startConnectionEvent(config, targetBSSID, roamType);
3288        mDiagsConnectionStartMillis = mClock.getElapsedSinceBootMillis();
3289        mWifiDiagnostics.reportConnectionEvent(
3290                mDiagsConnectionStartMillis, WifiDiagnostics.CONNECTION_EVENT_STARTED);
3291        // TODO(b/35329124): Remove CMD_DIAGS_CONNECT_TIMEOUT, once WifiStateMachine
3292        // grows a proper CONNECTING state.
3293        sendMessageDelayed(CMD_DIAGS_CONNECT_TIMEOUT,
3294                mDiagsConnectionStartMillis, DIAGS_CONNECT_TIMEOUT_MILLIS);
3295    }
3296
3297    /**
3298     * Inform other components (WifiMetrics, WifiDiagnostics, etc.) that the current connection attempt
3299     * has concluded.
3300     */
3301    private void reportConnectionAttemptEnd(int level2FailureCode, int connectivityFailureCode) {
3302        mWifiMetrics.endConnectionEvent(level2FailureCode, connectivityFailureCode);
3303        switch (level2FailureCode) {
3304            case WifiMetrics.ConnectionEvent.FAILURE_NONE:
3305                // Ideally, we'd wait until IP reachability has been confirmed. this code falls
3306                // short in two ways:
3307                // - at the time of the CMD_IP_CONFIGURATION_SUCCESSFUL event, we don't know if we
3308                //   actually have ARP reachability. it might be better to wait until the wifi
3309                //   network has been validated by IpManager.
3310                // - in the case of a roaming event (intra-SSID), we probably trigger when L2 is
3311                //   complete.
3312                //
3313                // TODO(b/34181219): Fix the above.
3314                mWifiDiagnostics.reportConnectionEvent(
3315                        mDiagsConnectionStartMillis, WifiDiagnostics.CONNECTION_EVENT_SUCCEEDED);
3316                break;
3317            case WifiMetrics.ConnectionEvent.FAILURE_REDUNDANT_CONNECTION_ATTEMPT:
3318            case WifiMetrics.ConnectionEvent.FAILURE_CONNECT_NETWORK_FAILED:
3319                // WifiDiagnostics doesn't care about pre-empted connections, or cases
3320                // where we failed to initiate a connection attempt with supplicant.
3321                break;
3322            default:
3323                mWifiDiagnostics.reportConnectionEvent(
3324                        mDiagsConnectionStartMillis, WifiDiagnostics.CONNECTION_EVENT_FAILED);
3325        }
3326        mDiagsConnectionStartMillis = -1;
3327    }
3328
3329    private void handleIPv4Success(DhcpResults dhcpResults) {
3330        if (mVerboseLoggingEnabled) {
3331            logd("handleIPv4Success <" + dhcpResults.toString() + ">");
3332            logd("link address " + dhcpResults.ipAddress);
3333        }
3334
3335        Inet4Address addr;
3336        synchronized (mDhcpResultsLock) {
3337            mDhcpResults = dhcpResults;
3338            addr = (Inet4Address) dhcpResults.ipAddress.getAddress();
3339        }
3340
3341        if (isRoaming()) {
3342            int previousAddress = mWifiInfo.getIpAddress();
3343            int newAddress = NetworkUtils.inetAddressToInt(addr);
3344            if (previousAddress != newAddress) {
3345                logd("handleIPv4Success, roaming and address changed" +
3346                        mWifiInfo + " got: " + addr);
3347            }
3348        }
3349        mWifiInfo.setInetAddress(addr);
3350        if (!mWifiInfo.getMeteredHint()) { // don't override the value if already set.
3351            mWifiInfo.setMeteredHint(dhcpResults.hasMeteredHint());
3352            updateCapabilities(getCurrentWifiConfiguration());
3353        }
3354    }
3355
3356    private void handleSuccessfulIpConfiguration() {
3357        mLastSignalLevel = -1; // Force update of signal strength
3358        WifiConfiguration c = getCurrentWifiConfiguration();
3359        if (c != null) {
3360            // Reset IP failure tracking
3361            c.getNetworkSelectionStatus().clearDisableReasonCounter(
3362                    WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE);
3363
3364            // Tell the framework whether the newly connected network is trusted or untrusted.
3365            updateCapabilities(c);
3366        }
3367        if (c != null) {
3368            ScanResult result = getCurrentScanResult();
3369            if (result == null) {
3370                logd("WifiStateMachine: handleSuccessfulIpConfiguration and no scan results" +
3371                        c.configKey());
3372            } else {
3373                // Clear the per BSSID failure count
3374                result.numIpConfigFailures = 0;
3375            }
3376        }
3377    }
3378
3379    private void handleIPv4Failure() {
3380        // TODO: Move this to provisioning failure, not DHCP failure.
3381        // DHCPv4 failure is expected on an IPv6-only network.
3382        mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_DHCP_FAILURE);
3383        if (mVerboseLoggingEnabled) {
3384            int count = -1;
3385            WifiConfiguration config = getCurrentWifiConfiguration();
3386            if (config != null) {
3387                count = config.getNetworkSelectionStatus().getDisableReasonCounter(
3388                        WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE);
3389            }
3390            log("DHCP failure count=" + count);
3391        }
3392        reportConnectionAttemptEnd(
3393                WifiMetrics.ConnectionEvent.FAILURE_DHCP,
3394                WifiMetricsProto.ConnectionEvent.HLF_DHCP);
3395        synchronized(mDhcpResultsLock) {
3396             if (mDhcpResults != null) {
3397                 mDhcpResults.clear();
3398             }
3399        }
3400        if (mVerboseLoggingEnabled) {
3401            logd("handleIPv4Failure");
3402        }
3403    }
3404
3405    private void handleIpConfigurationLost() {
3406        mWifiInfo.setInetAddress(null);
3407        mWifiInfo.setMeteredHint(false);
3408
3409        mWifiConfigManager.updateNetworkSelectionStatus(mLastNetworkId,
3410                WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE);
3411
3412        /* DHCP times out after about 30 seconds, we do a
3413         * disconnect thru supplicant, we will let autojoin retry connecting to the network
3414         */
3415        mWifiNative.disconnect();
3416    }
3417
3418    // TODO: De-duplicated this and handleIpConfigurationLost().
3419    private void handleIpReachabilityLost() {
3420        mWifiInfo.setInetAddress(null);
3421        mWifiInfo.setMeteredHint(false);
3422
3423        // TODO: Determine whether to call some form of mWifiConfigManager.handleSSIDStateChange().
3424
3425        // Disconnect via supplicant, and let autojoin retry connecting to the network.
3426        mWifiNative.disconnect();
3427    }
3428
3429    /*
3430     * Read a MAC address in /proc/arp/table, used by WifistateMachine
3431     * so as to record MAC address of default gateway.
3432     **/
3433    private String macAddressFromRoute(String ipAddress) {
3434        String macAddress = null;
3435        BufferedReader reader = null;
3436        try {
3437            reader = new BufferedReader(new FileReader("/proc/net/arp"));
3438
3439            // Skip over the line bearing colum titles
3440            String line = reader.readLine();
3441
3442            while ((line = reader.readLine()) != null) {
3443                String[] tokens = line.split("[ ]+");
3444                if (tokens.length < 6) {
3445                    continue;
3446                }
3447
3448                // ARP column format is
3449                // Address HWType HWAddress Flags Mask IFace
3450                String ip = tokens[0];
3451                String mac = tokens[3];
3452
3453                if (ipAddress.equals(ip)) {
3454                    macAddress = mac;
3455                    break;
3456                }
3457            }
3458
3459            if (macAddress == null) {
3460                loge("Did not find remoteAddress {" + ipAddress + "} in " +
3461                        "/proc/net/arp");
3462            }
3463
3464        } catch (FileNotFoundException e) {
3465            loge("Could not open /proc/net/arp to lookup mac address");
3466        } catch (IOException e) {
3467            loge("Could not read /proc/net/arp to lookup mac address");
3468        } finally {
3469            try {
3470                if (reader != null) {
3471                    reader.close();
3472                }
3473            } catch (IOException e) {
3474                // Do nothing
3475            }
3476        }
3477        return macAddress;
3478
3479    }
3480
3481    private class WifiNetworkFactory extends NetworkFactory {
3482        public WifiNetworkFactory(Looper l, Context c, String TAG, NetworkCapabilities f) {
3483            super(l, c, TAG, f);
3484        }
3485
3486        @Override
3487        protected void needNetworkFor(NetworkRequest networkRequest, int score) {
3488            synchronized (mWifiReqCountLock) {
3489                if (++mConnectionReqCount == 1) {
3490                    if (mWifiConnectivityManager != null && mUntrustedReqCount == 0) {
3491                        mWifiConnectivityManager.enable(true);
3492                    }
3493                }
3494            }
3495        }
3496
3497        @Override
3498        protected void releaseNetworkFor(NetworkRequest networkRequest) {
3499            synchronized (mWifiReqCountLock) {
3500                if (--mConnectionReqCount == 0) {
3501                    if (mWifiConnectivityManager != null && mUntrustedReqCount == 0) {
3502                        mWifiConnectivityManager.enable(false);
3503                    }
3504                }
3505            }
3506        }
3507
3508        @Override
3509        public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3510            pw.println("mConnectionReqCount " + mConnectionReqCount);
3511        }
3512
3513    }
3514
3515    private class UntrustedWifiNetworkFactory extends NetworkFactory {
3516        public UntrustedWifiNetworkFactory(Looper l, Context c, String tag, NetworkCapabilities f) {
3517            super(l, c, tag, f);
3518        }
3519
3520        @Override
3521        protected void needNetworkFor(NetworkRequest networkRequest, int score) {
3522            if (!networkRequest.networkCapabilities.hasCapability(
3523                    NetworkCapabilities.NET_CAPABILITY_TRUSTED)) {
3524                synchronized (mWifiReqCountLock) {
3525                    if (++mUntrustedReqCount == 1) {
3526                        if (mWifiConnectivityManager != null) {
3527                            if (mConnectionReqCount == 0) {
3528                                mWifiConnectivityManager.enable(true);
3529                            }
3530                            mWifiConnectivityManager.setUntrustedConnectionAllowed(true);
3531                        }
3532                    }
3533                }
3534            }
3535        }
3536
3537        @Override
3538        protected void releaseNetworkFor(NetworkRequest networkRequest) {
3539            if (!networkRequest.networkCapabilities.hasCapability(
3540                    NetworkCapabilities.NET_CAPABILITY_TRUSTED)) {
3541                synchronized (mWifiReqCountLock) {
3542                    if (--mUntrustedReqCount == 0) {
3543                        if (mWifiConnectivityManager != null) {
3544                            mWifiConnectivityManager.setUntrustedConnectionAllowed(false);
3545                            if (mConnectionReqCount == 0) {
3546                                mWifiConnectivityManager.enable(false);
3547                            }
3548                        }
3549                    }
3550                }
3551            }
3552        }
3553
3554        @Override
3555        public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
3556            pw.println("mUntrustedReqCount " + mUntrustedReqCount);
3557        }
3558    }
3559
3560    void maybeRegisterNetworkFactory() {
3561        if (mNetworkFactory == null) {
3562            checkAndSetConnectivityInstance();
3563            if (mCm != null) {
3564                mNetworkFactory = new WifiNetworkFactory(getHandler().getLooper(), mContext,
3565                        NETWORKTYPE, mNetworkCapabilitiesFilter);
3566                mNetworkFactory.setScoreFilter(60);
3567                mNetworkFactory.register();
3568
3569                // We can't filter untrusted network in the capabilities filter because a trusted
3570                // network would still satisfy a request that accepts untrusted ones.
3571                mUntrustedNetworkFactory = new UntrustedWifiNetworkFactory(getHandler().getLooper(),
3572                        mContext, NETWORKTYPE_UNTRUSTED, mNetworkCapabilitiesFilter);
3573                mUntrustedNetworkFactory.setScoreFilter(Integer.MAX_VALUE);
3574                mUntrustedNetworkFactory.register();
3575            }
3576        }
3577    }
3578
3579    /**
3580     * WifiStateMachine needs to enable/disable other services when wifi is in client mode.  This
3581     * method allows WifiStateMachine to get these additional system services.
3582     *
3583     * At this time, this method is used to setup variables for P2P service and Wifi Aware.
3584     */
3585    private void getAdditionalWifiServiceInterfaces() {
3586        // First set up Wifi Direct
3587        if (mP2pSupported) {
3588            IBinder s1 = mFacade.getService(Context.WIFI_P2P_SERVICE);
3589            WifiP2pServiceImpl wifiP2pServiceImpl =
3590                    (WifiP2pServiceImpl) IWifiP2pManager.Stub.asInterface(s1);
3591
3592            if (wifiP2pServiceImpl != null) {
3593                mWifiP2pChannel = new AsyncChannel();
3594                mWifiP2pChannel.connect(mContext, getHandler(),
3595                        wifiP2pServiceImpl.getP2pStateMachineMessenger());
3596            }
3597        }
3598    }
3599
3600    /********************************************************
3601     * HSM states
3602     *******************************************************/
3603
3604    class DefaultState extends State {
3605
3606        @Override
3607        public boolean processMessage(Message message) {
3608            logStateAndMessage(message, this);
3609
3610            switch (message.what) {
3611                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
3612                    AsyncChannel ac = (AsyncChannel) message.obj;
3613                    if (ac == mWifiP2pChannel) {
3614                        if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
3615                            p2pSendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
3616                            // since the p2p channel is connected, we should enable p2p if we are in
3617                            // connect mode.  We may not be in connect mode yet, we may have just
3618                            // set the operational mode and started to set up for connect mode.
3619                            if (mOperationalMode == CONNECT_MODE) {
3620                                // This message will only be handled if we are in Connect mode.
3621                                // If we are not in connect mode yet, this will be dropped and the
3622                                // ConnectMode.enter method will call to enable p2p.
3623                                sendMessage(CMD_ENABLE_P2P);
3624                            }
3625                        } else {
3626                            // TODO: We should probably do some cleanup or attempt a retry
3627                            // b/34283611
3628                            loge("WifiP2pService connection failure, error=" + message.arg1);
3629                        }
3630                    } else {
3631                        loge("got HALF_CONNECTED for unknown channel");
3632                    }
3633                    break;
3634                }
3635                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
3636                    AsyncChannel ac = (AsyncChannel) message.obj;
3637                    if (ac == mWifiP2pChannel) {
3638                        loge("WifiP2pService channel lost, message.arg1 =" + message.arg1);
3639                        //TODO: Re-establish connection to state machine after a delay (b/34283611)
3640                        // mWifiP2pChannel.connect(mContext, getHandler(),
3641                        // mWifiP2pManager.getMessenger());
3642                    }
3643                    break;
3644                }
3645                case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE:
3646                    mBluetoothConnectionActive = (message.arg1 !=
3647                            BluetoothAdapter.STATE_DISCONNECTED);
3648                    break;
3649                    /* Synchronous call returns */
3650                case CMD_PING_SUPPLICANT:
3651                case CMD_ENABLE_NETWORK:
3652                case CMD_ADD_OR_UPDATE_NETWORK:
3653                case CMD_SAVE_CONFIG:
3654                    replyToMessage(message, message.what, FAILURE);
3655                    break;
3656                case CMD_REMOVE_NETWORK:
3657                    deleteNetworkConfigAndSendReply(message, false);
3658                    break;
3659                case CMD_GET_CONFIGURED_NETWORKS:
3660                    replyToMessage(message, message.what, mWifiConfigManager.getSavedNetworks());
3661                    break;
3662                case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS:
3663                    replyToMessage(message, message.what,
3664                            mWifiConfigManager.getConfiguredNetworksWithPasswords());
3665                    break;
3666                case CMD_ENABLE_RSSI_POLL:
3667                    mEnableRssiPolling = (message.arg1 == 1);
3668                    break;
3669                case CMD_SET_HIGH_PERF_MODE:
3670                    if (message.arg1 == 1) {
3671                        setSuspendOptimizations(SUSPEND_DUE_TO_HIGH_PERF, false);
3672                    } else {
3673                        setSuspendOptimizations(SUSPEND_DUE_TO_HIGH_PERF, true);
3674                    }
3675                    break;
3676                case CMD_INITIALIZE:
3677                    boolean ok = mWifiNative.initializeVendorHal();
3678                    replyToMessage(message, message.what, ok ? SUCCESS : FAILURE);
3679                    break;
3680                case CMD_BOOT_COMPLETED:
3681                    // get other services that we need to manage
3682                    getAdditionalWifiServiceInterfaces();
3683                    if (!mWifiConfigManager.loadFromStore()) {
3684                        Log.e(TAG, "Failed to load from config store");
3685                    }
3686                    maybeRegisterNetworkFactory();
3687                    break;
3688                case CMD_SCREEN_STATE_CHANGED:
3689                    handleScreenStateChanged(message.arg1 != 0);
3690                    break;
3691                    /* Discard */
3692                case CMD_START_SCAN:
3693                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
3694                    break;
3695                case CMD_START_SUPPLICANT:
3696                case CMD_STOP_SUPPLICANT:
3697                case CMD_STOP_SUPPLICANT_FAILED:
3698                case CMD_DRIVER_START_TIMED_OUT:
3699                case CMD_START_AP:
3700                case CMD_START_AP_FAILURE:
3701                case CMD_STOP_AP:
3702                case CMD_AP_STOPPED:
3703                case CMD_DISCONNECT:
3704                case CMD_RECONNECT:
3705                case CMD_REASSOCIATE:
3706                case CMD_RELOAD_TLS_AND_RECONNECT:
3707                case WifiMonitor.SUP_CONNECTION_EVENT:
3708                case WifiMonitor.SUP_DISCONNECTION_EVENT:
3709                case WifiMonitor.NETWORK_CONNECTION_EVENT:
3710                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
3711                case WifiMonitor.SCAN_RESULTS_EVENT:
3712                case WifiMonitor.SCAN_FAILED_EVENT:
3713                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
3714                case WifiMonitor.AUTHENTICATION_FAILURE_EVENT:
3715                case WifiMonitor.ASSOCIATION_REJECTION_EVENT:
3716                case WifiMonitor.WPS_OVERLAP_EVENT:
3717                case CMD_SET_OPERATIONAL_MODE:
3718                case CMD_RSSI_POLL:
3719                case DhcpClient.CMD_PRE_DHCP_ACTION:
3720                case DhcpClient.CMD_PRE_DHCP_ACTION_COMPLETE:
3721                case DhcpClient.CMD_POST_DHCP_ACTION:
3722                case CMD_NO_NETWORKS_PERIODIC_SCAN:
3723                case CMD_ENABLE_P2P:
3724                case CMD_DISABLE_P2P_RSP:
3725                case WifiMonitor.SUP_REQUEST_IDENTITY:
3726                case CMD_TEST_NETWORK_DISCONNECT:
3727                case WifiMonitor.SUP_REQUEST_SIM_AUTH:
3728                case CMD_TARGET_BSSID:
3729                case CMD_START_CONNECT:
3730                case CMD_START_ROAM:
3731                case CMD_ASSOCIATED_BSSID:
3732                case CMD_UNWANTED_NETWORK:
3733                case CMD_DISCONNECTING_WATCHDOG_TIMER:
3734                case CMD_ROAM_WATCHDOG_TIMER:
3735                case CMD_DISABLE_EPHEMERAL_NETWORK:
3736                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
3737                    break;
3738                case CMD_SET_SUSPEND_OPT_ENABLED:
3739                    if (message.arg1 == 1) {
3740                        if (message.arg2 == 1) {
3741                            mSuspendWakeLock.release();
3742                        }
3743                        setSuspendOptimizations(SUSPEND_DUE_TO_SCREEN, true);
3744                    } else {
3745                        setSuspendOptimizations(SUSPEND_DUE_TO_SCREEN, false);
3746                    }
3747                    break;
3748                case WifiMonitor.DRIVER_HUNG_EVENT:
3749                    setSupplicantRunning(false);
3750                    setSupplicantRunning(true);
3751                    break;
3752                case WifiManager.CONNECT_NETWORK:
3753                    replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED,
3754                            WifiManager.BUSY);
3755                    break;
3756                case WifiManager.FORGET_NETWORK:
3757                    deleteNetworkConfigAndSendReply(message, true);
3758                    break;
3759                case WifiManager.SAVE_NETWORK:
3760                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
3761                    replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED,
3762                            WifiManager.BUSY);
3763                    break;
3764                case WifiManager.START_WPS:
3765                    replyToMessage(message, WifiManager.WPS_FAILED,
3766                            WifiManager.BUSY);
3767                    break;
3768                case WifiManager.CANCEL_WPS:
3769                    replyToMessage(message, WifiManager.CANCEL_WPS_FAILED,
3770                            WifiManager.BUSY);
3771                    break;
3772                case WifiManager.DISABLE_NETWORK:
3773                    replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED,
3774                            WifiManager.BUSY);
3775                    break;
3776                case WifiManager.RSSI_PKTCNT_FETCH:
3777                    replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_FAILED,
3778                            WifiManager.BUSY);
3779                    break;
3780                case CMD_GET_SUPPORTED_FEATURES:
3781                    int featureSet = mWifiNative.getSupportedFeatureSet();
3782                    replyToMessage(message, message.what, featureSet);
3783                    break;
3784                case CMD_FIRMWARE_ALERT:
3785                    if (mWifiDiagnostics != null) {
3786                        byte[] buffer = (byte[])message.obj;
3787                        int alertReason = message.arg1;
3788                        mWifiDiagnostics.captureAlertData(alertReason, buffer);
3789                        mWifiMetrics.incrementAlertReasonCount(alertReason);
3790                    }
3791                    break;
3792                case CMD_GET_LINK_LAYER_STATS:
3793                    // Not supported hence reply with error message
3794                    replyToMessage(message, message.what, null);
3795                    break;
3796                case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED:
3797                    NetworkInfo info = (NetworkInfo) message.obj;
3798                    mP2pConnected.set(info.isConnected());
3799                    break;
3800                case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST:
3801                    mTemporarilyDisconnectWifi = (message.arg1 == 1);
3802                    replyToMessage(message, WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE);
3803                    break;
3804                /* Link configuration (IP address, DNS, ...) changes notified via netlink */
3805                case CMD_UPDATE_LINKPROPERTIES:
3806                    updateLinkProperties((LinkProperties) message.obj);
3807                    break;
3808                case CMD_GET_MATCHING_CONFIG:
3809                    replyToMessage(message, message.what);
3810                    break;
3811                case CMD_IP_CONFIGURATION_SUCCESSFUL:
3812                case CMD_IP_CONFIGURATION_LOST:
3813                case CMD_IP_REACHABILITY_LOST:
3814                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
3815                    break;
3816                case CMD_GET_CONNECTION_STATISTICS:
3817                    replyToMessage(message, message.what, mWifiConnectionStatistics);
3818                    break;
3819                case CMD_REMOVE_APP_CONFIGURATIONS:
3820                    deferMessage(message);
3821                    break;
3822                case CMD_REMOVE_USER_CONFIGURATIONS:
3823                    deferMessage(message);
3824                    break;
3825                case CMD_START_IP_PACKET_OFFLOAD:
3826                    if (mNetworkAgent != null) mNetworkAgent.onPacketKeepaliveEvent(
3827                            message.arg1,
3828                            ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
3829                    break;
3830                case CMD_STOP_IP_PACKET_OFFLOAD:
3831                    if (mNetworkAgent != null) mNetworkAgent.onPacketKeepaliveEvent(
3832                            message.arg1,
3833                            ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
3834                    break;
3835                case CMD_START_RSSI_MONITORING_OFFLOAD:
3836                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
3837                    break;
3838                case CMD_STOP_RSSI_MONITORING_OFFLOAD:
3839                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
3840                    break;
3841                case CMD_USER_SWITCH:
3842                    Set<Integer> removedNetworkIds =
3843                            mWifiConfigManager.handleUserSwitch(message.arg1);
3844                    if (removedNetworkIds.contains(mTargetNetworkId) ||
3845                            removedNetworkIds.contains(mLastNetworkId)) {
3846                        // Disconnect and let autojoin reselect a new network
3847                        sendMessage(CMD_DISCONNECT);
3848                    }
3849                    break;
3850                case CMD_USER_UNLOCK:
3851                    mWifiConfigManager.handleUserUnlock(message.arg1);
3852                    break;
3853                case CMD_USER_STOP:
3854                    mWifiConfigManager.handleUserStop(message.arg1);
3855                    break;
3856                case CMD_QUERY_OSU_ICON:
3857                case CMD_MATCH_PROVIDER_NETWORK:
3858                    /* reply with arg1 = 0 - it returns API failure to the calling app
3859                     * (message.what is not looked at)
3860                     */
3861                    replyToMessage(message, message.what);
3862                    break;
3863                case CMD_RESET_SIM_NETWORKS:
3864                    /* Defer this message until supplicant is started. */
3865                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
3866                    deferMessage(message);
3867                    break;
3868                case CMD_INSTALL_PACKET_FILTER:
3869                    mWifiNative.installPacketFilter((byte[]) message.obj);
3870                    break;
3871                case CMD_SET_FALLBACK_PACKET_FILTERING:
3872                    if ((boolean) message.obj) {
3873                        mWifiNative.startFilteringMulticastV4Packets();
3874                    } else {
3875                        mWifiNative.stopFilteringMulticastV4Packets();
3876                    }
3877                    break;
3878                case CMD_CLIENT_INTERFACE_BINDER_DEATH:
3879                    // We have lost contact with a client interface, which means that we cannot
3880                    // trust that the driver is up or that the interface is ready.  We are fit
3881                    // for no WiFi related work.
3882                    transitionTo(mInitialState);
3883                    break;
3884                case CMD_DIAGS_CONNECT_TIMEOUT:
3885                    mWifiDiagnostics.reportConnectionEvent(
3886                            (Long) message.obj, BaseWifiDiagnostics.CONNECTION_EVENT_FAILED);
3887                    break;
3888                default:
3889                    loge("Error! unhandled message" + message);
3890                    break;
3891            }
3892            return HANDLED;
3893        }
3894    }
3895
3896    class InitialState extends State {
3897
3898        private void cleanup() {
3899            // Tearing down the client interfaces below is going to stop our supplicant.
3900            mWifiMonitor.stopAllMonitoring();
3901
3902            mDeathRecipient.unlinkToDeath();
3903            mWifiNative.tearDownInterfaces();
3904
3905            mWifiNative.stopHal();
3906        }
3907
3908        @Override
3909        public void enter() {
3910            mWifiStateTracker.updateState(WifiStateTracker.INVALID);
3911            cleanup();
3912        }
3913
3914        @Override
3915        public boolean processMessage(Message message) {
3916            logStateAndMessage(message, this);
3917            switch (message.what) {
3918                case CMD_START_SUPPLICANT:
3919                    mClientInterface = mWifiNative.setupDriverForClientMode();
3920                    if (mClientInterface == null
3921                            || !mDeathRecipient.linkToDeath(mClientInterface.asBinder())) {
3922                        setWifiState(WifiManager.WIFI_STATE_UNKNOWN);
3923                        cleanup();
3924                        break;
3925                    }
3926
3927                    try {
3928                        // A runtime crash or shutting down AP mode can leave
3929                        // IP addresses configured, and this affects
3930                        // connectivity when supplicant starts up.
3931                        // Ensure we have no IP addresses before a supplicant start.
3932                        mNwService.clearInterfaceAddresses(mInterfaceName);
3933
3934                        // Set privacy extensions
3935                        mNwService.setInterfaceIpv6PrivacyExtensions(mInterfaceName, true);
3936
3937                        // IPv6 is enabled only as long as access point is connected since:
3938                        // - IPv6 addresses and routes stick around after disconnection
3939                        // - kernel is unaware when connected and fails to start IPv6 negotiation
3940                        // - kernel can start autoconfiguration when 802.1x is not complete
3941                        mNwService.disableIpv6(mInterfaceName);
3942                    } catch (RemoteException re) {
3943                        loge("Unable to change interface settings: " + re);
3944                    } catch (IllegalStateException ie) {
3945                        loge("Unable to change interface settings: " + ie);
3946                    }
3947
3948                    if (!mWifiNative.enableSupplicant()) {
3949                        loge("Failed to start supplicant!");
3950                        setWifiState(WifiManager.WIFI_STATE_UNKNOWN);
3951                        cleanup();
3952                        break;
3953                    }
3954                    setSupplicantLogLevel();
3955                    setWifiState(WIFI_STATE_ENABLING);
3956                    if (mVerboseLoggingEnabled) log("Supplicant start successful");
3957                    mWifiMonitor.startMonitoring(mInterfaceName);
3958                    transitionTo(mSupplicantStartingState);
3959                    break;
3960                case CMD_START_AP:
3961                    transitionTo(mSoftApState);
3962                    break;
3963                case CMD_SET_OPERATIONAL_MODE:
3964                    mOperationalMode = message.arg1;
3965                    if (mOperationalMode != DISABLED_MODE) {
3966                        sendMessage(CMD_START_SUPPLICANT);
3967                    }
3968                    break;
3969                default:
3970                    return NOT_HANDLED;
3971            }
3972            return HANDLED;
3973        }
3974    }
3975
3976    class SupplicantStartingState extends State {
3977        private void initializeWpsDetails() {
3978            String detail;
3979            detail = mPropertyService.get("ro.product.name", "");
3980            if (!mWifiNative.setDeviceName(detail)) {
3981                loge("Failed to set device name " +  detail);
3982            }
3983            detail = mPropertyService.get("ro.product.manufacturer", "");
3984            if (!mWifiNative.setManufacturer(detail)) {
3985                loge("Failed to set manufacturer " + detail);
3986            }
3987            detail = mPropertyService.get("ro.product.model", "");
3988            if (!mWifiNative.setModelName(detail)) {
3989                loge("Failed to set model name " + detail);
3990            }
3991            detail = mPropertyService.get("ro.product.model", "");
3992            if (!mWifiNative.setModelNumber(detail)) {
3993                loge("Failed to set model number " + detail);
3994            }
3995            detail = mPropertyService.get("ro.serialno", "");
3996            if (!mWifiNative.setSerialNumber(detail)) {
3997                loge("Failed to set serial number " + detail);
3998            }
3999            if (!mWifiNative.setConfigMethods("physical_display virtual_push_button")) {
4000                loge("Failed to set WPS config methods");
4001            }
4002            if (!mWifiNative.setDeviceType(mPrimaryDeviceType)) {
4003                loge("Failed to set primary device type " + mPrimaryDeviceType);
4004            }
4005        }
4006
4007        @Override
4008        public boolean processMessage(Message message) {
4009            logStateAndMessage(message, this);
4010
4011            switch(message.what) {
4012                case WifiMonitor.SUP_CONNECTION_EVENT:
4013                    if (mVerboseLoggingEnabled) log("Supplicant connection established");
4014
4015                    mSupplicantRestartCount = 0;
4016                    /* Reset the supplicant state to indicate the supplicant
4017                     * state is not known at this time */
4018                    mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE);
4019                    /* Initialize data structures */
4020                    mLastBssid = null;
4021                    mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID;
4022                    mLastSignalLevel = -1;
4023
4024                    mWifiInfo.setMacAddress(mWifiNative.getMacAddress());
4025                    // Attempt to migrate data out of legacy store.
4026                    if (!mWifiConfigManager.migrateFromLegacyStore()) {
4027                        Log.e(TAG, "Failed to migrate from legacy config store");
4028                    }
4029                    initializeWpsDetails();
4030                    sendSupplicantConnectionChangedBroadcast(true);
4031                    transitionTo(mSupplicantStartedState);
4032                    break;
4033                case WifiMonitor.SUP_DISCONNECTION_EVENT:
4034                    if (++mSupplicantRestartCount <= SUPPLICANT_RESTART_TRIES) {
4035                        loge("Failed to setup control channel, restart supplicant");
4036                        mWifiMonitor.stopAllMonitoring();
4037                        mWifiNative.disableSupplicant();
4038                        transitionTo(mInitialState);
4039                        sendMessageDelayed(CMD_START_SUPPLICANT, SUPPLICANT_RESTART_INTERVAL_MSECS);
4040                    } else {
4041                        loge("Failed " + mSupplicantRestartCount +
4042                                " times to start supplicant, unload driver");
4043                        mSupplicantRestartCount = 0;
4044                        setWifiState(WIFI_STATE_UNKNOWN);
4045                        transitionTo(mInitialState);
4046                    }
4047                    break;
4048                case CMD_START_SUPPLICANT:
4049                case CMD_STOP_SUPPLICANT:
4050                case CMD_START_AP:
4051                case CMD_STOP_AP:
4052                case CMD_SET_OPERATIONAL_MODE:
4053                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
4054                    deferMessage(message);
4055                    break;
4056                default:
4057                    return NOT_HANDLED;
4058            }
4059            return HANDLED;
4060        }
4061    }
4062
4063    class SupplicantStartedState extends State {
4064        @Override
4065        public void enter() {
4066            if (mVerboseLoggingEnabled) {
4067                logd("SupplicantStartedState enter");
4068            }
4069
4070            mWifiNative.setExternalSim(true);
4071
4072            /* turn on use of DFS channels */
4073            mWifiNative.setDfsFlag(true);
4074
4075            setRandomMacOui();
4076            mCountryCode.setReadyForChange(true);
4077
4078            // We can't do this in the constructor because WifiStateMachine is created before the
4079            // wifi scanning service is initialized
4080            if (mWifiScanner == null) {
4081                mWifiScanner = mWifiInjector.getWifiScanner();
4082
4083                synchronized (mWifiReqCountLock) {
4084                    mWifiConnectivityManager =
4085                            mWifiInjector.makeWifiConnectivityManager(mWifiInfo,
4086                                                                      hasConnectionRequests());
4087                    mWifiConnectivityManager.setUntrustedConnectionAllowed(mUntrustedReqCount > 0);
4088                    mWifiConnectivityManager.handleScreenStateChanged(mScreenOn);
4089                }
4090            }
4091
4092            mWifiDiagnostics.startLogging(mVerboseLoggingEnabled);
4093            mIsRunning = true;
4094            updateBatteryWorkSource(null);
4095            /**
4096             * Enable bluetooth coexistence scan mode when bluetooth connection is active.
4097             * When this mode is on, some of the low-level scan parameters used by the
4098             * driver are changed to reduce interference with bluetooth
4099             */
4100            mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive);
4101            // initialize network state
4102            setNetworkDetailedState(DetailedState.DISCONNECTED);
4103
4104            // Disable legacy multicast filtering, which on some chipsets defaults to enabled.
4105            // Legacy IPv6 multicast filtering blocks ICMPv6 router advertisements which breaks IPv6
4106            // provisioning. Legacy IPv4 multicast filtering may be re-enabled later via
4107            // IpManager.Callback.setFallbackMulticastFilter()
4108            mWifiNative.stopFilteringMulticastV4Packets();
4109            mWifiNative.stopFilteringMulticastV6Packets();
4110
4111            if (mOperationalMode == SCAN_ONLY_MODE ||
4112                    mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) {
4113                mWifiNative.disconnect();
4114                setWifiState(WIFI_STATE_DISABLED);
4115                transitionTo(mScanModeState);
4116            } else if (mOperationalMode == CONNECT_MODE) {
4117
4118                // Status pulls in the current supplicant state and network connection state
4119                // events over the monitor connection. This helps framework sync up with
4120                // current supplicant state
4121                // TODO: actually check the supplicant status string and make sure the supplicant
4122                // is in disconnecte4d state.
4123                mWifiNative.status();
4124                // Transitioning to Disconnected state will trigger a scan and subsequently AutoJoin
4125                transitionTo(mDisconnectedState);
4126            } else if (mOperationalMode == DISABLED_MODE) {
4127                transitionTo(mSupplicantStoppingState);
4128            }
4129
4130            // Set the right suspend mode settings
4131            mWifiNative.setSuspendOptimizations(mSuspendOptNeedsDisabled == 0
4132                    && mUserWantsSuspendOpt.get());
4133
4134            mWifiNative.setPowerSave(true);
4135
4136            if (mP2pSupported) {
4137                if (mOperationalMode == CONNECT_MODE) {
4138                    p2pSendMessage(WifiStateMachine.CMD_ENABLE_P2P);
4139                } else {
4140                    // P2P state machine starts in disabled state, and is not enabled until
4141                    // CMD_ENABLE_P2P is sent from here; so, nothing needs to be done to
4142                    // keep it disabled.
4143                }
4144            }
4145
4146            final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE);
4147            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
4148            intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_ENABLED);
4149            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
4150
4151            // Enable link layer stats gathering
4152            mWifiNative.setWifiLinkLayerStats("wlan0", 1);
4153        }
4154
4155        @Override
4156        public boolean processMessage(Message message) {
4157            logStateAndMessage(message, this);
4158
4159            switch(message.what) {
4160                case CMD_STOP_SUPPLICANT:   /* Supplicant stopped by user */
4161                    if (mP2pSupported) {
4162                        transitionTo(mWaitForP2pDisableState);
4163                    } else {
4164                        transitionTo(mSupplicantStoppingState);
4165                    }
4166                    break;
4167                case WifiMonitor.SUP_DISCONNECTION_EVENT:  /* Supplicant connection lost */
4168                    loge("Connection lost, restart supplicant");
4169                    handleSupplicantConnectionLoss(true);
4170                    handleNetworkDisconnect();
4171                    mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE);
4172                    if (mP2pSupported) {
4173                        transitionTo(mWaitForP2pDisableState);
4174                    } else {
4175                        transitionTo(mInitialState);
4176                    }
4177                    sendMessageDelayed(CMD_START_SUPPLICANT, SUPPLICANT_RESTART_INTERVAL_MSECS);
4178                    break;
4179                case CMD_START_SCAN:
4180                    // TODO: remove scan request path (b/31445200)
4181                    handleScanRequest(message);
4182                    break;
4183                case WifiMonitor.SCAN_RESULTS_EVENT:
4184                case WifiMonitor.SCAN_FAILED_EVENT:
4185                    // TODO: remove handing of SCAN_RESULTS_EVENT and SCAN_FAILED_EVENT when scan
4186                    // results are retrieved from WifiScanner (b/31444878)
4187                    maybeRegisterNetworkFactory(); // Make sure our NetworkFactory is registered
4188                    setScanResults();
4189                    mIsScanOngoing = false;
4190                    mIsFullScanOngoing = false;
4191                    if (mBufferedScanMsg.size() > 0)
4192                        sendMessage(mBufferedScanMsg.remove());
4193                    break;
4194                case CMD_PING_SUPPLICANT:
4195                    // TODO (b/35620640): Remove this command since the API is deprecated.
4196                    replyToMessage(message, message.what, FAILURE);
4197                    break;
4198                case CMD_START_AP:
4199                    /* Cannot start soft AP while in client mode */
4200                    loge("Failed to start soft AP with a running supplicant");
4201                    setWifiApState(WIFI_AP_STATE_FAILED, WifiManager.SAP_START_FAILURE_GENERAL);
4202                    break;
4203                case CMD_SET_OPERATIONAL_MODE:
4204                    mOperationalMode = message.arg1;
4205                    if (mOperationalMode == DISABLED_MODE) {
4206                        transitionTo(mSupplicantStoppingState);
4207                    }
4208                    break;
4209                case CMD_TARGET_BSSID:
4210                    // Trying to associate to this BSSID
4211                    if (message.obj != null) {
4212                        mTargetRoamBSSID = (String) message.obj;
4213                    }
4214                    break;
4215                case CMD_GET_LINK_LAYER_STATS:
4216                    WifiLinkLayerStats stats = getWifiLinkLayerStats();
4217                    replyToMessage(message, message.what, stats);
4218                    break;
4219                case CMD_RESET_SIM_NETWORKS:
4220                    log("resetting EAP-SIM/AKA/AKA' networks since SIM was changed");
4221                    mWifiConfigManager.resetSimNetworks();
4222                    break;
4223                case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE:
4224                    mBluetoothConnectionActive = (message.arg1 !=
4225                            BluetoothAdapter.STATE_DISCONNECTED);
4226                    mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive);
4227                    break;
4228                case CMD_SET_SUSPEND_OPT_ENABLED:
4229                    if (message.arg1 == 1) {
4230                        setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, true);
4231                        if (message.arg2 == 1) {
4232                            mSuspendWakeLock.release();
4233                        }
4234                    } else {
4235                        setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, false);
4236                    }
4237                    break;
4238                case CMD_SET_HIGH_PERF_MODE:
4239                    if (message.arg1 == 1) {
4240                        setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, false);
4241                    } else {
4242                        setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, true);
4243                    }
4244                    break;
4245                case CMD_ENABLE_TDLS:
4246                    if (message.obj != null) {
4247                        String remoteAddress = (String) message.obj;
4248                        boolean enable = (message.arg1 == 1);
4249                        mWifiNative.startTdls(remoteAddress, enable);
4250                    }
4251                    break;
4252                case WifiMonitor.ANQP_DONE_EVENT:
4253                    // TODO(zqiu): remove this when switch over to wificond for ANQP requests.
4254                    mPasspointManager.notifyANQPDone((AnqpEvent) message.obj);
4255                    break;
4256                case CMD_STOP_IP_PACKET_OFFLOAD: {
4257                    int slot = message.arg1;
4258                    int ret = stopWifiIPPacketOffload(slot);
4259                    if (mNetworkAgent != null) {
4260                        mNetworkAgent.onPacketKeepaliveEvent(slot, ret);
4261                    }
4262                    break;
4263                }
4264                case WifiMonitor.RX_HS20_ANQP_ICON_EVENT:
4265                    // TODO(zqiu): remove this when switch over to wificond for icon requests.
4266                    mPasspointManager.notifyIconDone((IconEvent) message.obj);
4267                    break;
4268                case WifiMonitor.HS20_REMEDIATION_EVENT:
4269                    // TODO(zqiu): remove this when switch over to wificond for WNM frames
4270                    // monitoring.
4271                    mPasspointManager.receivedWnmFrame((WnmData) message.obj);
4272                    break;
4273                case CMD_CONFIG_ND_OFFLOAD:
4274                    final boolean enabled = (message.arg1 > 0);
4275                    mWifiNative.configureNeighborDiscoveryOffload(enabled);
4276                    break;
4277                case CMD_ENABLE_WIFI_CONNECTIVITY_MANAGER:
4278                    mWifiConnectivityManager.enable(message.arg1 == 1 ? true : false);
4279                    break;
4280                case CMD_ENABLE_AUTOJOIN_WHEN_ASSOCIATED:
4281                    final boolean allowed = (message.arg1 > 0);
4282                    boolean old_state = mEnableAutoJoinWhenAssociated;
4283                    mEnableAutoJoinWhenAssociated = allowed;
4284                    if (!old_state && allowed && mScreenOn
4285                            && getCurrentState() == mConnectedState) {
4286                        mWifiConnectivityManager.forceConnectivityScan();
4287                    }
4288                    break;
4289                default:
4290                    return NOT_HANDLED;
4291            }
4292            return HANDLED;
4293        }
4294
4295        @Override
4296        public void exit() {
4297            mWifiDiagnostics.stopLogging();
4298
4299            mIsRunning = false;
4300            updateBatteryWorkSource(null);
4301            mScanResults = new ArrayList<>();
4302
4303            final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE);
4304            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
4305            intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED);
4306            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
4307            mBufferedScanMsg.clear();
4308
4309            mNetworkInfo.setIsAvailable(false);
4310            if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo);
4311            mCountryCode.setReadyForChange(false);
4312        }
4313    }
4314
4315    class SupplicantStoppingState extends State {
4316        @Override
4317        public void enter() {
4318            /* Send any reset commands to supplicant before shutting it down */
4319            handleNetworkDisconnect();
4320
4321            String suppState = System.getProperty("init.svc.wpa_supplicant");
4322            if (suppState == null) suppState = "unknown";
4323
4324            logd("SupplicantStoppingState: stopSupplicant "
4325                    + " init.svc.wpa_supplicant=" + suppState);
4326            mWifiMonitor.stopSupplicant();
4327
4328            /* Send ourselves a delayed message to indicate failure after a wait time */
4329            sendMessageDelayed(obtainMessage(CMD_STOP_SUPPLICANT_FAILED,
4330                    ++mSupplicantStopFailureToken, 0), SUPPLICANT_RESTART_INTERVAL_MSECS);
4331            setWifiState(WIFI_STATE_DISABLING);
4332            mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE);
4333        }
4334        @Override
4335        public boolean processMessage(Message message) {
4336            logStateAndMessage(message, this);
4337
4338            switch(message.what) {
4339                case WifiMonitor.SUP_CONNECTION_EVENT:
4340                    loge("Supplicant connection received while stopping");
4341                    break;
4342                case WifiMonitor.SUP_DISCONNECTION_EVENT:
4343                    if (mVerboseLoggingEnabled) log("Supplicant connection lost");
4344                    handleSupplicantConnectionLoss(false);
4345                    transitionTo(mInitialState);
4346                    break;
4347                case CMD_STOP_SUPPLICANT_FAILED:
4348                    if (message.arg1 == mSupplicantStopFailureToken) {
4349                        loge("Timed out on a supplicant stop, kill and proceed");
4350                        handleSupplicantConnectionLoss(true);
4351                        transitionTo(mInitialState);
4352                    }
4353                    break;
4354                case CMD_START_SUPPLICANT:
4355                case CMD_STOP_SUPPLICANT:
4356                case CMD_START_AP:
4357                case CMD_STOP_AP:
4358                case CMD_SET_OPERATIONAL_MODE:
4359                    deferMessage(message);
4360                    break;
4361                default:
4362                    return NOT_HANDLED;
4363            }
4364            return HANDLED;
4365        }
4366    }
4367
4368    class WaitForP2pDisableState extends State {
4369        private State mTransitionToState;
4370        @Override
4371        public void enter() {
4372            switch (getCurrentMessage().what) {
4373                case WifiMonitor.SUP_DISCONNECTION_EVENT:
4374                    mTransitionToState = mInitialState;
4375                    break;
4376                case CMD_STOP_SUPPLICANT:
4377                default:
4378                    mTransitionToState = mSupplicantStoppingState;
4379                    break;
4380            }
4381            p2pSendMessage(WifiStateMachine.CMD_DISABLE_P2P_REQ);
4382        }
4383        @Override
4384        public boolean processMessage(Message message) {
4385            logStateAndMessage(message, this);
4386
4387            switch(message.what) {
4388                case WifiStateMachine.CMD_DISABLE_P2P_RSP:
4389                    transitionTo(mTransitionToState);
4390                    break;
4391                /* Defer wifi start/shut and driver commands */
4392                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
4393                case CMD_START_SUPPLICANT:
4394                case CMD_STOP_SUPPLICANT:
4395                case CMD_START_AP:
4396                case CMD_STOP_AP:
4397                case CMD_SET_OPERATIONAL_MODE:
4398                case CMD_START_SCAN:
4399                case CMD_DISCONNECT:
4400                case CMD_REASSOCIATE:
4401                case CMD_RECONNECT:
4402                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
4403                    deferMessage(message);
4404                    break;
4405                default:
4406                    return NOT_HANDLED;
4407            }
4408            return HANDLED;
4409        }
4410    }
4411
4412    class ScanModeState extends State {
4413        private int mLastOperationMode;
4414        @Override
4415        public void enter() {
4416            mLastOperationMode = mOperationalMode;
4417            mWifiStateTracker.updateState(WifiStateTracker.SCAN_MODE);
4418        }
4419        @Override
4420        public boolean processMessage(Message message) {
4421            logStateAndMessage(message, this);
4422
4423            switch(message.what) {
4424                case CMD_SET_OPERATIONAL_MODE:
4425                    if (message.arg1 == CONNECT_MODE) {
4426                        mOperationalMode = CONNECT_MODE;
4427                        transitionTo(mDisconnectedState);
4428                    } else if (message.arg1 == DISABLED_MODE) {
4429                        transitionTo(mSupplicantStoppingState);
4430                    }
4431                    // Nothing to do
4432                    break;
4433                // Handle scan. All the connection related commands are
4434                // handled only in ConnectModeState
4435                case CMD_START_SCAN:
4436                    handleScanRequest(message);
4437                    break;
4438                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
4439                    SupplicantState state = handleSupplicantStateChange(message);
4440                    if (mVerboseLoggingEnabled) log("SupplicantState= " + state);
4441                    break;
4442                default:
4443                    return NOT_HANDLED;
4444            }
4445            return HANDLED;
4446        }
4447    }
4448
4449
4450    String smToString(Message message) {
4451        return smToString(message.what);
4452    }
4453
4454    String smToString(int what) {
4455        String s = sSmToString.get(what);
4456        if (s != null) {
4457            return s;
4458        }
4459        switch (what) {
4460            case WifiMonitor.DRIVER_HUNG_EVENT:
4461                s = "DRIVER_HUNG_EVENT";
4462                break;
4463            case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED:
4464                s = "AsyncChannel.CMD_CHANNEL_HALF_CONNECTED";
4465                break;
4466            case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
4467                s = "AsyncChannel.CMD_CHANNEL_DISCONNECTED";
4468                break;
4469            case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST:
4470                s = "WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST";
4471                break;
4472            case WifiManager.DISABLE_NETWORK:
4473                s = "WifiManager.DISABLE_NETWORK";
4474                break;
4475            case WifiManager.CONNECT_NETWORK:
4476                s = "CONNECT_NETWORK";
4477                break;
4478            case WifiManager.SAVE_NETWORK:
4479                s = "SAVE_NETWORK";
4480                break;
4481            case WifiManager.FORGET_NETWORK:
4482                s = "FORGET_NETWORK";
4483                break;
4484            case WifiMonitor.SUP_CONNECTION_EVENT:
4485                s = "SUP_CONNECTION_EVENT";
4486                break;
4487            case WifiMonitor.SUP_DISCONNECTION_EVENT:
4488                s = "SUP_DISCONNECTION_EVENT";
4489                break;
4490            case WifiMonitor.SCAN_RESULTS_EVENT:
4491                s = "SCAN_RESULTS_EVENT";
4492                break;
4493            case WifiMonitor.SCAN_FAILED_EVENT:
4494                s = "SCAN_FAILED_EVENT";
4495                break;
4496            case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
4497                s = "SUPPLICANT_STATE_CHANGE_EVENT";
4498                break;
4499            case WifiMonitor.AUTHENTICATION_FAILURE_EVENT:
4500                s = "AUTHENTICATION_FAILURE_EVENT";
4501                break;
4502            case WifiMonitor.SSID_TEMP_DISABLED:
4503                s = "SSID_TEMP_DISABLED";
4504                break;
4505            case WifiMonitor.SSID_REENABLED:
4506                s = "SSID_REENABLED";
4507                break;
4508            case WifiMonitor.WPS_SUCCESS_EVENT:
4509                s = "WPS_SUCCESS_EVENT";
4510                break;
4511            case WifiMonitor.WPS_FAIL_EVENT:
4512                s = "WPS_FAIL_EVENT";
4513                break;
4514            case WifiMonitor.SUP_REQUEST_IDENTITY:
4515                s = "SUP_REQUEST_IDENTITY";
4516                break;
4517            case WifiMonitor.NETWORK_CONNECTION_EVENT:
4518                s = "NETWORK_CONNECTION_EVENT";
4519                break;
4520            case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
4521                s = "NETWORK_DISCONNECTION_EVENT";
4522                break;
4523            case WifiMonitor.ASSOCIATION_REJECTION_EVENT:
4524                s = "ASSOCIATION_REJECTION_EVENT";
4525                break;
4526            case WifiMonitor.ANQP_DONE_EVENT:
4527                s = "WifiMonitor.ANQP_DONE_EVENT";
4528                break;
4529            case WifiMonitor.RX_HS20_ANQP_ICON_EVENT:
4530                s = "WifiMonitor.RX_HS20_ANQP_ICON_EVENT";
4531                break;
4532            case WifiMonitor.GAS_QUERY_DONE_EVENT:
4533                s = "WifiMonitor.GAS_QUERY_DONE_EVENT";
4534                break;
4535            case WifiMonitor.HS20_REMEDIATION_EVENT:
4536                s = "WifiMonitor.HS20_REMEDIATION_EVENT";
4537                break;
4538            case WifiMonitor.GAS_QUERY_START_EVENT:
4539                s = "WifiMonitor.GAS_QUERY_START_EVENT";
4540                break;
4541            case WifiP2pServiceImpl.GROUP_CREATING_TIMED_OUT:
4542                s = "GROUP_CREATING_TIMED_OUT";
4543                break;
4544            case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED:
4545                s = "P2P_CONNECTION_CHANGED";
4546                break;
4547            case WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE:
4548                s = "P2P.DISCONNECT_WIFI_RESPONSE";
4549                break;
4550            case WifiP2pServiceImpl.SET_MIRACAST_MODE:
4551                s = "P2P.SET_MIRACAST_MODE";
4552                break;
4553            case WifiP2pServiceImpl.BLOCK_DISCOVERY:
4554                s = "P2P.BLOCK_DISCOVERY";
4555                break;
4556            case WifiManager.CANCEL_WPS:
4557                s = "CANCEL_WPS";
4558                break;
4559            case WifiManager.CANCEL_WPS_FAILED:
4560                s = "CANCEL_WPS_FAILED";
4561                break;
4562            case WifiManager.CANCEL_WPS_SUCCEDED:
4563                s = "CANCEL_WPS_SUCCEDED";
4564                break;
4565            case WifiManager.START_WPS:
4566                s = "START_WPS";
4567                break;
4568            case WifiManager.START_WPS_SUCCEEDED:
4569                s = "START_WPS_SUCCEEDED";
4570                break;
4571            case WifiManager.WPS_FAILED:
4572                s = "WPS_FAILED";
4573                break;
4574            case WifiManager.WPS_COMPLETED:
4575                s = "WPS_COMPLETED";
4576                break;
4577            case WifiManager.RSSI_PKTCNT_FETCH:
4578                s = "RSSI_PKTCNT_FETCH";
4579                break;
4580            default:
4581                s = "what:" + Integer.toString(what);
4582                break;
4583        }
4584        return s;
4585    }
4586
4587    void registerConnected() {
4588        if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) {
4589            mWifiConfigManager.updateNetworkAfterConnect(mLastNetworkId);
4590            // On connect, reset wifiScoreReport
4591            mWifiScoreReport.reset();
4592       }
4593    }
4594
4595    void registerDisconnected() {
4596        if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) {
4597            mWifiConfigManager.updateNetworkAfterDisconnect(mLastNetworkId);
4598            // We are switching away from this configuration,
4599            // hence record the time we were connected last
4600            WifiConfiguration config = mWifiConfigManager.getConfiguredNetwork(mLastNetworkId);
4601            if (config != null) {
4602                // Remove WifiConfiguration for ephemeral or Passpoint networks, since they're
4603                // temporary networks.
4604                if (config.ephemeral || config.isPasspoint()) {
4605                    mWifiConfigManager.removeNetwork(mLastNetworkId, Process.WIFI_UID);
4606                }
4607            }
4608        }
4609    }
4610
4611    /**
4612     * Returns Wificonfiguration object correponding to the currently connected network, null if
4613     * not connected.
4614     */
4615    public WifiConfiguration getCurrentWifiConfiguration() {
4616        if (mLastNetworkId == WifiConfiguration.INVALID_NETWORK_ID) {
4617            return null;
4618        }
4619        return mWifiConfigManager.getConfiguredNetwork(mLastNetworkId);
4620    }
4621
4622    ScanResult getCurrentScanResult() {
4623        WifiConfiguration config = getCurrentWifiConfiguration();
4624        if (config == null) {
4625            return null;
4626        }
4627        String BSSID = mWifiInfo.getBSSID();
4628        if (BSSID == null) {
4629            BSSID = mTargetRoamBSSID;
4630        }
4631        ScanDetailCache scanDetailCache =
4632                mWifiConfigManager.getScanDetailCacheForNetwork(config.networkId);
4633
4634        if (scanDetailCache == null) {
4635            return null;
4636        }
4637
4638        return scanDetailCache.get(BSSID);
4639    }
4640
4641    String getCurrentBSSID() {
4642        if (isLinkDebouncing()) {
4643            return null;
4644        }
4645        return mLastBssid;
4646    }
4647
4648    class ConnectModeState extends State {
4649
4650        @Override
4651        public void enter() {
4652            // Let the system know that wifi is available in client mode.
4653            setWifiState(WIFI_STATE_ENABLED);
4654
4655            mNetworkInfo.setIsAvailable(true);
4656            if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo);
4657
4658            // initialize network state
4659            setNetworkDetailedState(DetailedState.DISCONNECTED);
4660
4661
4662            // Inform WifiConnectivityManager that Wifi is enabled
4663            mWifiConnectivityManager.setWifiEnabled(true);
4664            // Inform metrics that Wifi is Enabled (but not yet connected)
4665            mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_DISCONNECTED);
4666            // Inform p2p service that wifi is up and ready when applicable
4667            p2pSendMessage(WifiStateMachine.CMD_ENABLE_P2P);
4668        }
4669
4670        @Override
4671        public void exit() {
4672            // Let the system know that wifi is not available since we are exiting client mode.
4673            mNetworkInfo.setIsAvailable(false);
4674            if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo);
4675            // Inform WifiConnectivityManager that Wifi is disabled
4676            mWifiConnectivityManager.setWifiEnabled(false);
4677            // Inform metrics that Wifi is being disabled (Toggled, airplane enabled, etc)
4678            mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_DISABLED);
4679        }
4680
4681        @Override
4682        public boolean processMessage(Message message) {
4683            WifiConfiguration config;
4684            int netId;
4685            boolean ok;
4686            boolean didDisconnect;
4687            String bssid;
4688            String ssid;
4689            NetworkUpdateResult result;
4690            Set<Integer> removedNetworkIds;
4691            int reasonCode;
4692            logStateAndMessage(message, this);
4693
4694            switch (message.what) {
4695                case WifiMonitor.ASSOCIATION_REJECTION_EVENT:
4696                    mWifiDiagnostics.captureBugReportData(
4697                            WifiDiagnostics.REPORT_REASON_ASSOC_FAILURE);
4698                    didBlackListBSSID = false;
4699                    bssid = (String) message.obj;
4700                    reasonCode = message.arg2;
4701                    if (bssid == null || TextUtils.isEmpty(bssid)) {
4702                        // If BSSID is null, use the target roam BSSID
4703                        bssid = mTargetRoamBSSID;
4704                    }
4705                    if (bssid != null) {
4706                        // If we have a BSSID, tell configStore to black list it
4707                        didBlackListBSSID = mWifiConnectivityManager.trackBssid(bssid, false,
4708                            reasonCode);
4709                    }
4710                    mWifiConfigManager.updateNetworkSelectionStatus(mTargetNetworkId,
4711                            WifiConfiguration.NetworkSelectionStatus
4712                            .DISABLED_ASSOCIATION_REJECTION);
4713                    mSupplicantStateTracker.sendMessage(WifiMonitor.ASSOCIATION_REJECTION_EVENT);
4714                    //If rejection occurred while Metrics is tracking a ConnnectionEvent, end it.
4715                    reportConnectionAttemptEnd(
4716                            WifiMetrics.ConnectionEvent.FAILURE_ASSOCIATION_REJECTION,
4717                            WifiMetricsProto.ConnectionEvent.HLF_NONE);
4718                    mWifiInjector.getWifiLastResortWatchdog()
4719                            .noteConnectionFailureAndTriggerIfNeeded(
4720                                    getTargetSsid(), bssid,
4721                                    WifiLastResortWatchdog.FAILURE_CODE_ASSOCIATION);
4722                    break;
4723                case WifiMonitor.AUTHENTICATION_FAILURE_EVENT:
4724                    mWifiDiagnostics.captureBugReportData(
4725                            WifiDiagnostics.REPORT_REASON_AUTH_FAILURE);
4726                    mSupplicantStateTracker.sendMessage(WifiMonitor.AUTHENTICATION_FAILURE_EVENT);
4727                    // In case of wrong password, rely on SSID_TEMP_DISABLE event to update
4728                    // the WifiConfigManager
4729                    if ((message.arg2 != WifiMonitor.AUTHENTICATION_FAILURE_REASON_WRONG_PSWD)
4730                            && (mTargetNetworkId != WifiConfiguration.INVALID_NETWORK_ID)) {
4731                        mWifiConfigManager.updateNetworkSelectionStatus(mTargetNetworkId,
4732                                WifiConfiguration.NetworkSelectionStatus
4733                                        .DISABLED_AUTHENTICATION_FAILURE);
4734                    }
4735                    //If failure occurred while Metrics is tracking a ConnnectionEvent, end it.
4736                    reportConnectionAttemptEnd(
4737                            WifiMetrics.ConnectionEvent.FAILURE_AUTHENTICATION_FAILURE,
4738                            WifiMetricsProto.ConnectionEvent.HLF_NONE);
4739                    mWifiInjector.getWifiLastResortWatchdog()
4740                            .noteConnectionFailureAndTriggerIfNeeded(
4741                                    getTargetSsid(), mTargetRoamBSSID,
4742                                    WifiLastResortWatchdog.FAILURE_CODE_AUTHENTICATION);
4743                    break;
4744                case WifiMonitor.SSID_TEMP_DISABLED:
4745                    netId = lookupFrameworkNetworkId(message.arg1);
4746                    Log.e(TAG, "Supplicant SSID temporary disabled:"
4747                            + mWifiConfigManager.getConfiguredNetwork(netId));
4748                    mWifiConfigManager.updateNetworkSelectionStatus(
4749                            netId,
4750                            WifiConfiguration.NetworkSelectionStatus
4751                            .DISABLED_AUTHENTICATION_FAILURE);
4752                    reportConnectionAttemptEnd(
4753                            WifiMetrics.ConnectionEvent.FAILURE_SSID_TEMP_DISABLED,
4754                            WifiMetricsProto.ConnectionEvent.HLF_NONE);
4755                    mWifiInjector.getWifiLastResortWatchdog()
4756                            .noteConnectionFailureAndTriggerIfNeeded(
4757                                    getTargetSsid(), mTargetRoamBSSID,
4758                                    WifiLastResortWatchdog.FAILURE_CODE_AUTHENTICATION);
4759                    break;
4760                case WifiMonitor.SSID_REENABLED:
4761                    netId = lookupFrameworkNetworkId(message.arg1);
4762                    Log.d(TAG, "Supplicant SSID reenable:"
4763                            + mWifiConfigManager.getConfiguredNetwork(netId));
4764                    // Do not re-enable it in Quality Network Selection since framework has its own
4765                    // Algorithm of disable/enable
4766                    break;
4767                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
4768                    SupplicantState state = handleSupplicantStateChange(message);
4769                    // A driver/firmware hang can now put the interface in a down state.
4770                    // We detect the interface going down and recover from it
4771                    if (!SupplicantState.isDriverActive(state)) {
4772                        if (mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) {
4773                            handleNetworkDisconnect();
4774                        }
4775                        log("Detected an interface down, restart driver");
4776                        // Rely on the fact that this will force us into killing supplicant and then
4777                        // restart supplicant from a clean state.
4778                        transitionTo(mSupplicantStoppingState);
4779                        sendMessage(CMD_START_SUPPLICANT);
4780                        break;
4781                    }
4782
4783                    // Supplicant can fail to report a NETWORK_DISCONNECTION_EVENT
4784                    // when authentication times out after a successful connection,
4785                    // we can figure this from the supplicant state. If supplicant
4786                    // state is DISCONNECTED, but the mNetworkInfo says we are not
4787                    // disconnected, we need to handle a disconnection
4788                    if (!isLinkDebouncing() && state == SupplicantState.DISCONNECTED &&
4789                            mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) {
4790                        if (mVerboseLoggingEnabled) {
4791                            log("Missed CTRL-EVENT-DISCONNECTED, disconnect");
4792                        }
4793                        handleNetworkDisconnect();
4794                        transitionTo(mDisconnectedState);
4795                    }
4796
4797                    // If we have COMPLETED a connection to a BSSID, start doing
4798                    // DNAv4/DNAv6 -style probing for on-link neighbors of
4799                    // interest (e.g. routers); harmless if none are configured.
4800                    if (state == SupplicantState.COMPLETED) {
4801                        mIpManager.confirmConfiguration();
4802                    }
4803                    break;
4804                case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST:
4805                    if (message.arg1 == 1) {
4806                        mWifiNative.disconnect();
4807                        mTemporarilyDisconnectWifi = true;
4808                    } else {
4809                        mWifiNative.reconnect();
4810                        mTemporarilyDisconnectWifi = false;
4811                    }
4812                    break;
4813                case CMD_ADD_OR_UPDATE_NETWORK:
4814                    config = (WifiConfiguration) message.obj;
4815                    result = mWifiConfigManager.addOrUpdateNetwork(config, message.sendingUid);
4816                    if (!result.isSuccess()) {
4817                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
4818                    }
4819                    replyToMessage(message, message.what, result.getNetworkId());
4820                    break;
4821                case CMD_REMOVE_NETWORK:
4822                    if (!deleteNetworkConfigAndSendReply(message, false)) {
4823                        // failed to remove the config and caller was notified
4824                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
4825                        break;
4826                    }
4827                    //  we successfully deleted the network config
4828                    netId = message.arg1;
4829                    if (netId == mTargetNetworkId || netId == mLastNetworkId) {
4830                        // Disconnect and let autojoin reselect a new network
4831                        sendMessage(CMD_DISCONNECT);
4832                    }
4833                    break;
4834                case CMD_ENABLE_NETWORK:
4835                    boolean disableOthers = message.arg2 == 1;
4836                    netId = message.arg1;
4837                    if (disableOthers) {
4838                        // If the app has all the necessary permissions, this will trigger a connect
4839                        // attempt.
4840                        ok = connectToUserSelectNetwork(netId, message.sendingUid);
4841                    } else {
4842                        ok = mWifiConfigManager.enableNetwork(netId, false, message.sendingUid);
4843                    }
4844                    if (!ok) {
4845                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
4846                    }
4847                    replyToMessage(message, message.what, ok ? SUCCESS : FAILURE);
4848                    break;
4849                case WifiManager.DISABLE_NETWORK:
4850                    netId = message.arg1;
4851                    if (mWifiConfigManager.disableNetwork(netId, message.sendingUid)) {
4852                        replyToMessage(message, WifiManager.DISABLE_NETWORK_SUCCEEDED);
4853                        if (netId == mTargetNetworkId || netId == mLastNetworkId) {
4854                            // Disconnect and let autojoin reselect a new network
4855                            sendMessage(CMD_DISCONNECT);
4856                        }
4857                    } else {
4858                        loge("Failed to remove network");
4859                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
4860                        replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED,
4861                                WifiManager.ERROR);
4862                    }
4863                    break;
4864                case CMD_DISABLE_EPHEMERAL_NETWORK:
4865                    config = mWifiConfigManager.disableEphemeralNetwork((String)message.obj);
4866                    if (config != null) {
4867                        if (config.networkId == mTargetNetworkId
4868                                || config.networkId == mLastNetworkId) {
4869                            // Disconnect and let autojoin reselect a new network
4870                            sendMessage(CMD_DISCONNECT);
4871                        }
4872                    }
4873                    break;
4874                case CMD_SAVE_CONFIG:
4875                    ok = mWifiConfigManager.saveToStore(true);
4876                    replyToMessage(message, CMD_SAVE_CONFIG, ok ? SUCCESS : FAILURE);
4877                    // Inform the backup manager about a data change
4878                    mBackupManagerProxy.notifyDataChanged();
4879                    break;
4880                case WifiMonitor.SUP_REQUEST_IDENTITY:
4881                    int supplicantNetworkId = message.arg2;
4882                    netId = lookupFrameworkNetworkId(supplicantNetworkId);
4883                    boolean identitySent = false;
4884                    // For SIM & AKA/AKA' EAP method Only, get identity from ICC
4885                    if (targetWificonfiguration != null
4886                            && targetWificonfiguration.networkId == netId
4887                            && TelephonyUtil.isSimConfig(targetWificonfiguration)) {
4888                        String identity =
4889                                TelephonyUtil.getSimIdentity(getTelephonyManager(),
4890                                        targetWificonfiguration);
4891                        if (identity != null) {
4892                            mWifiNative.simIdentityResponse(supplicantNetworkId, identity);
4893                            identitySent = true;
4894                        } else {
4895                            Log.e(TAG, "Unable to retrieve identity from Telephony");
4896                        }
4897                    }
4898                    if (!identitySent) {
4899                        // Supplicant lacks credentials to connect to that network, hence black list
4900                        ssid = (String) message.obj;
4901                        if (targetWificonfiguration != null && ssid != null
4902                                && targetWificonfiguration.SSID != null
4903                                && targetWificonfiguration.SSID.equals("\"" + ssid + "\"")) {
4904                            mWifiConfigManager.updateNetworkSelectionStatus(
4905                                    targetWificonfiguration.networkId,
4906                                    WifiConfiguration.NetworkSelectionStatus
4907                                            .DISABLED_AUTHENTICATION_NO_CREDENTIALS);
4908                        }
4909                        mWifiNative.disconnect();
4910                    }
4911                    break;
4912                case WifiMonitor.SUP_REQUEST_SIM_AUTH:
4913                    logd("Received SUP_REQUEST_SIM_AUTH");
4914                    SimAuthRequestData requestData = (SimAuthRequestData) message.obj;
4915                    if (requestData != null) {
4916                        if (requestData.protocol == WifiEnterpriseConfig.Eap.SIM) {
4917                            handleGsmAuthRequest(requestData);
4918                        } else if (requestData.protocol == WifiEnterpriseConfig.Eap.AKA
4919                            || requestData.protocol == WifiEnterpriseConfig.Eap.AKA_PRIME) {
4920                            handle3GAuthRequest(requestData);
4921                        }
4922                    } else {
4923                        loge("Invalid sim auth request");
4924                    }
4925                    break;
4926                case CMD_GET_MATCHING_CONFIG:
4927                    // TODO(b/31065385)
4928                    replyToMessage(message, message.what, null);
4929                    break;
4930                case CMD_RECONNECT:
4931                    mWifiConnectivityManager.forceConnectivityScan();
4932                    break;
4933                case CMD_REASSOCIATE:
4934                    lastConnectAttemptTimestamp = mClock.getWallClockMillis();
4935                    mWifiNative.reassociate();
4936                    break;
4937                case CMD_RELOAD_TLS_AND_RECONNECT:
4938                    if (mWifiConfigManager.needsUnlockedKeyStore()) {
4939                        logd("Reconnecting to give a chance to un-connected TLS networks");
4940                        mWifiNative.disconnect();
4941                        lastConnectAttemptTimestamp = mClock.getWallClockMillis();
4942                        mWifiNative.reconnect();
4943                    }
4944                    break;
4945                case CMD_START_ROAM:
4946                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
4947                    return HANDLED;
4948                case CMD_START_CONNECT:
4949                    /* connect command coming from auto-join */
4950                    netId = message.arg1;
4951                    bssid = (String) message.obj;
4952                    config = mWifiConfigManager.getConfiguredNetworkWithPassword(netId);
4953                    logd("CMD_START_CONNECT sup state "
4954                            + mSupplicantStateTracker.getSupplicantStateName()
4955                            + " my state " + getCurrentState().getName()
4956                            + " nid=" + Integer.toString(netId)
4957                            + " roam=" + Boolean.toString(mAutoRoaming));
4958                    if (config == null) {
4959                        loge("CMD_START_CONNECT and no config, bail out...");
4960                        break;
4961                    }
4962                    mTargetNetworkId = netId;
4963                    setTargetBssid(config, bssid);
4964
4965                    reportConnectionAttemptStart(config, mTargetRoamBSSID,
4966                            WifiMetricsProto.ConnectionEvent.ROAM_UNRELATED);
4967                    boolean shouldDisconnect = (getCurrentState() != mDisconnectedState);
4968                    if (mWifiNative.connectToNetwork(config, shouldDisconnect)) {
4969                        lastConnectAttemptTimestamp = mClock.getWallClockMillis();
4970                        targetWificonfiguration = config;
4971                        mAutoRoaming = false;
4972                        if (isRoaming() || isLinkDebouncing()) {
4973                            transitionTo(mRoamingState);
4974                        } else if (shouldDisconnect) {
4975                            transitionTo(mDisconnectingState);
4976                        } else {
4977                            transitionTo(mDisconnectedState);
4978                        }
4979                    } else {
4980                        loge("CMD_START_CONNECT Failed to start connection to network " + config);
4981                        reportConnectionAttemptEnd(
4982                                WifiMetrics.ConnectionEvent.FAILURE_CONNECT_NETWORK_FAILED,
4983                                WifiMetricsProto.ConnectionEvent.HLF_NONE);
4984                        replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED,
4985                                WifiManager.ERROR);
4986                        break;
4987                    }
4988                    break;
4989                case CMD_REMOVE_APP_CONFIGURATIONS:
4990                    removedNetworkIds =
4991                            mWifiConfigManager.removeNetworksForApp((ApplicationInfo) message.obj);
4992                    if (removedNetworkIds.contains(mTargetNetworkId) ||
4993                            removedNetworkIds.contains(mLastNetworkId)) {
4994                        // Disconnect and let autojoin reselect a new network.
4995                        sendMessage(CMD_DISCONNECT);
4996                    }
4997                    break;
4998                case CMD_REMOVE_USER_CONFIGURATIONS:
4999                    removedNetworkIds =
5000                            mWifiConfigManager.removeNetworksForUser((Integer) message.arg1);
5001                    if (removedNetworkIds.contains(mTargetNetworkId) ||
5002                            removedNetworkIds.contains(mLastNetworkId)) {
5003                        // Disconnect and let autojoin reselect a new network.
5004                        sendMessage(CMD_DISCONNECT);
5005                    }
5006                    break;
5007                case WifiManager.CONNECT_NETWORK:
5008                    /**
5009                     * The connect message can contain a network id passed as arg1 on message or
5010                     * or a config passed as obj on message.
5011                     * For a new network, a config is passed to create and connect.
5012                     * For an existing network, a network id is passed
5013                     */
5014                    netId = message.arg1;
5015                    config = (WifiConfiguration) message.obj;
5016                    mWifiConnectionStatistics.numWifiManagerJoinAttempt++;
5017                    // New network addition.
5018                    if (config != null) {
5019                        result = mWifiConfigManager.addOrUpdateNetwork(config, message.sendingUid);
5020                        if (!result.isSuccess()) {
5021                            loge("CONNECT_NETWORK adding/updating config=" + config + " failed");
5022                            messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
5023                            replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED,
5024                                    WifiManager.ERROR);
5025                            break;
5026                        }
5027                        netId = result.getNetworkId();
5028                    }
5029                    if (!connectToUserSelectNetwork(netId, message.sendingUid)) {
5030                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
5031                        replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED,
5032                                WifiManager.NOT_AUTHORIZED);
5033                        break;
5034                    }
5035                    broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_SAVED, config);
5036                    replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED);
5037                    break;
5038                case WifiManager.SAVE_NETWORK:
5039                    config = (WifiConfiguration) message.obj;
5040                    mWifiConnectionStatistics.numWifiManagerJoinAttempt++;
5041                    if (config == null) {
5042                        loge("SAVE_NETWORK with null configuration"
5043                                + mSupplicantStateTracker.getSupplicantStateName()
5044                                + " my state " + getCurrentState().getName());
5045                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
5046                        replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED,
5047                                WifiManager.ERROR);
5048                        break;
5049                    }
5050                    result = mWifiConfigManager.addOrUpdateNetwork(config, message.sendingUid);
5051                    if (!result.isSuccess()) {
5052                        loge("SAVE_NETWORK adding/updating config=" + config + " failed");
5053                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
5054                        replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED,
5055                                WifiManager.ERROR);
5056                        break;
5057                    }
5058                    netId = result.getNetworkId();
5059                    if (mWifiInfo.getNetworkId() == netId) {
5060                        if (result.hasIpChanged()) {
5061                            // The currently connection configuration was changed
5062                            // We switched from DHCP to static or from static to DHCP, or the
5063                            // static IP address has changed.
5064                            log("Reconfiguring IP on connection");
5065                            // TODO: clear addresses and disable IPv6
5066                            // to simplify obtainingIpState.
5067                            transitionTo(mObtainingIpState);
5068                        }
5069                        if (result.hasProxyChanged()) {
5070                            log("Reconfiguring proxy on connection");
5071                            mIpManager.setHttpProxy(
5072                                    getCurrentWifiConfiguration().getHttpProxy());
5073                        }
5074                    } else {
5075                        if (!connectToUserSelectNetwork(netId, message.sendingUid)) {
5076                            messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
5077                            replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED,
5078                                    WifiManager.NOT_AUTHORIZED);
5079                            break;
5080                        }
5081                    }
5082                    broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_SAVED, config);
5083                    replyToMessage(message, WifiManager.SAVE_NETWORK_SUCCEEDED);
5084                    break;
5085                case WifiManager.FORGET_NETWORK:
5086                    if (!deleteNetworkConfigAndSendReply(message, true)) {
5087                        // Caller was notified of failure, nothing else to do
5088                        break;
5089                    }
5090                    // the network was deleted
5091                    netId = message.arg1;
5092                    if (netId == mTargetNetworkId || netId == mLastNetworkId) {
5093                        // Disconnect and let autojoin reselect a new network
5094                        sendMessage(CMD_DISCONNECT);
5095                    }
5096                    break;
5097                case WifiManager.START_WPS:
5098                    WpsInfo wpsInfo = (WpsInfo) message.obj;
5099                    WpsResult wpsResult = new WpsResult();
5100                    switch (wpsInfo.setup) {
5101                        case WpsInfo.PBC:
5102                            if (mWifiNative.startWpsPbc(wpsInfo.BSSID)) {
5103                                wpsResult.status = WpsResult.Status.SUCCESS;
5104                            } else {
5105                                Log.e(TAG, "Failed to start WPS push button configuration");
5106                                wpsResult.status = WpsResult.Status.FAILURE;
5107                            }
5108                            break;
5109                        case WpsInfo.KEYPAD:
5110                            if (mWifiNative.startWpsRegistrar(wpsInfo.BSSID, wpsInfo.pin)) {
5111                                wpsResult.status = WpsResult.Status.SUCCESS;
5112                            } else {
5113                                Log.e(TAG, "Failed to start WPS push button configuration");
5114                                wpsResult.status = WpsResult.Status.FAILURE;
5115                            }
5116                            break;
5117                        case WpsInfo.DISPLAY:
5118                            wpsResult.pin = mWifiNative.startWpsPinDisplay(wpsInfo.BSSID);
5119                            if (!TextUtils.isEmpty(wpsResult.pin)) {
5120                                wpsResult.status = WpsResult.Status.SUCCESS;
5121                            } else {
5122                                Log.e(TAG, "Failed to start WPS pin method configuration");
5123                                wpsResult.status = WpsResult.Status.FAILURE;
5124                            }
5125                            break;
5126                        default:
5127                            wpsResult = new WpsResult(Status.FAILURE);
5128                            loge("Invalid setup for WPS");
5129                            break;
5130                    }
5131                    if (wpsResult.status == Status.SUCCESS) {
5132                        replyToMessage(message, WifiManager.START_WPS_SUCCEEDED, wpsResult);
5133                        transitionTo(mWpsRunningState);
5134                    } else {
5135                        loge("Failed to start WPS with config " + wpsInfo.toString());
5136                        replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.ERROR);
5137                    }
5138                    break;
5139                case CMD_ASSOCIATED_BSSID:
5140                    // This is where we can confirm the connection BSSID. Use it to find the
5141                    // right ScanDetail to populate metrics.
5142                    String someBssid = (String) message.obj;
5143                    if (someBssid != null) {
5144                        // Get the ScanDetail associated with this BSSID.
5145                        ScanDetailCache scanDetailCache =
5146                                mWifiConfigManager.getScanDetailCacheForNetwork(mTargetNetworkId);
5147                        if (scanDetailCache != null) {
5148                            mWifiMetrics.setConnectionScanDetail(scanDetailCache.getScanDetail(
5149                                    someBssid));
5150                        }
5151                    }
5152                    return NOT_HANDLED;
5153                case WifiMonitor.NETWORK_CONNECTION_EVENT:
5154                    if (mVerboseLoggingEnabled) log("Network connection established");
5155                    mLastNetworkId = lookupFrameworkNetworkId(message.arg1);
5156                    mLastBssid = (String) message.obj;
5157                    reasonCode = message.arg2;
5158                    // TODO: This check should not be needed after WifiStateMachinePrime refactor.
5159                    // Currently, the last connected network configuration is left in
5160                    // wpa_supplicant, this may result in wpa_supplicant initiating connection
5161                    // to it after a config store reload. Hence the old network Id lookups may not
5162                    // work, so disconnect the network and let network selector reselect a new
5163                    // network.
5164                    if (getCurrentWifiConfiguration() != null) {
5165                        mWifiInfo.setBSSID(mLastBssid);
5166                        mWifiInfo.setNetworkId(mLastNetworkId);
5167                        mWifiConnectivityManager.trackBssid(mLastBssid, true, reasonCode);
5168                        sendNetworkStateChangeBroadcast(mLastBssid);
5169                        transitionTo(mObtainingIpState);
5170                    } else {
5171                        logw("Connected to unknown networkId " + mLastNetworkId
5172                                + ", disconnecting...");
5173                        sendMessage(CMD_DISCONNECT);
5174                    }
5175                    break;
5176                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
5177                    // Calling handleNetworkDisconnect here is redundant because we might already
5178                    // have called it when leaving L2ConnectedState to go to disconnecting state
5179                    // or thru other path
5180                    // We should normally check the mWifiInfo or mLastNetworkId so as to check
5181                    // if they are valid, and only in this case call handleNEtworkDisconnect,
5182                    // TODO: this should be fixed for a L MR release
5183                    // The side effect of calling handleNetworkDisconnect twice is that a bunch of
5184                    // idempotent commands are executed twice (stopping Dhcp, enabling the SPS mode
5185                    // at the chip etc...
5186                    if (mVerboseLoggingEnabled) log("ConnectModeState: Network connection lost ");
5187                    handleNetworkDisconnect();
5188                    transitionTo(mDisconnectedState);
5189                    break;
5190                case CMD_QUERY_OSU_ICON:
5191                    mPasspointManager.queryPasspointIcon(
5192                            ((Bundle) message.obj).getLong(EXTRA_OSU_ICON_QUERY_BSSID),
5193                            ((Bundle) message.obj).getString(EXTRA_OSU_ICON_QUERY_FILENAME));
5194                    break;
5195                case CMD_MATCH_PROVIDER_NETWORK:
5196                    // TODO(b/31065385): Passpoint config management.
5197                    replyToMessage(message, message.what, 0);
5198                    break;
5199                case CMD_ENABLE_P2P:
5200                    p2pSendMessage(WifiStateMachine.CMD_ENABLE_P2P);
5201                    break;
5202                default:
5203                    return NOT_HANDLED;
5204            }
5205            return HANDLED;
5206        }
5207    }
5208
5209    private void updateCapabilities(WifiConfiguration config) {
5210        NetworkCapabilities networkCapabilities = new NetworkCapabilities(mDfltNetworkCapabilities);
5211        if (config != null) {
5212            if (config.ephemeral) {
5213                networkCapabilities.removeCapability(
5214                        NetworkCapabilities.NET_CAPABILITY_TRUSTED);
5215            } else {
5216                networkCapabilities.addCapability(
5217                        NetworkCapabilities.NET_CAPABILITY_TRUSTED);
5218            }
5219
5220            networkCapabilities.setSignalStrength(
5221                    (mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI)
5222                    ? mWifiInfo.getRssi()
5223                    : NetworkCapabilities.SIGNAL_STRENGTH_UNSPECIFIED);
5224        }
5225
5226        if (mWifiInfo.getMeteredHint()) {
5227            networkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
5228        }
5229
5230        mNetworkAgent.sendNetworkCapabilities(networkCapabilities);
5231    }
5232
5233    private class WifiNetworkAgent extends NetworkAgent {
5234        public WifiNetworkAgent(Looper l, Context c, String TAG, NetworkInfo ni,
5235                NetworkCapabilities nc, LinkProperties lp, int score, NetworkMisc misc) {
5236            super(l, c, TAG, ni, nc, lp, score, misc);
5237        }
5238
5239        @Override
5240        protected void unwanted() {
5241            // Ignore if we're not the current networkAgent.
5242            if (this != mNetworkAgent) return;
5243            if (mVerboseLoggingEnabled) {
5244                log("WifiNetworkAgent -> Wifi unwanted score " + Integer.toString(mWifiInfo.score));
5245            }
5246            unwantedNetwork(NETWORK_STATUS_UNWANTED_DISCONNECT);
5247        }
5248
5249        @Override
5250        protected void networkStatus(int status, String redirectUrl) {
5251            if (this != mNetworkAgent) return;
5252            if (status == NetworkAgent.INVALID_NETWORK) {
5253                if (mVerboseLoggingEnabled) {
5254                    log("WifiNetworkAgent -> Wifi networkStatus invalid, score="
5255                            + Integer.toString(mWifiInfo.score));
5256                }
5257                unwantedNetwork(NETWORK_STATUS_UNWANTED_VALIDATION_FAILED);
5258            } else if (status == NetworkAgent.VALID_NETWORK) {
5259                if (mVerboseLoggingEnabled) {
5260                    log("WifiNetworkAgent -> Wifi networkStatus valid, score= "
5261                            + Integer.toString(mWifiInfo.score));
5262                }
5263                doNetworkStatus(status);
5264            }
5265        }
5266
5267        @Override
5268        protected void saveAcceptUnvalidated(boolean accept) {
5269            if (this != mNetworkAgent) return;
5270            WifiStateMachine.this.sendMessage(CMD_ACCEPT_UNVALIDATED, accept ? 1 : 0);
5271        }
5272
5273        @Override
5274        protected void startPacketKeepalive(Message msg) {
5275            WifiStateMachine.this.sendMessage(
5276                    CMD_START_IP_PACKET_OFFLOAD, msg.arg1, msg.arg2, msg.obj);
5277        }
5278
5279        @Override
5280        protected void stopPacketKeepalive(Message msg) {
5281            WifiStateMachine.this.sendMessage(
5282                    CMD_STOP_IP_PACKET_OFFLOAD, msg.arg1, msg.arg2, msg.obj);
5283        }
5284
5285        @Override
5286        protected void setSignalStrengthThresholds(int[] thresholds) {
5287            // 0. If there are no thresholds, or if the thresholds are invalid, stop RSSI monitoring.
5288            // 1. Tell the hardware to start RSSI monitoring here, possibly adding MIN_VALUE and
5289            //    MAX_VALUE at the start/end of the thresholds array if necessary.
5290            // 2. Ensure that when the hardware event fires, we fetch the RSSI from the hardware
5291            //    event, call mWifiInfo.setRssi() with it, and call updateCapabilities(), and then
5292            //    re-arm the hardware event. This needs to be done on the state machine thread to
5293            //    avoid race conditions. The RSSI used to re-arm the event (and perhaps also the one
5294            //    sent in the NetworkCapabilities) must be the one received from the hardware event
5295            //    received, or we might skip callbacks.
5296            // 3. Ensure that when we disconnect, RSSI monitoring is stopped.
5297            log("Received signal strength thresholds: " + Arrays.toString(thresholds));
5298            if (thresholds.length == 0) {
5299                WifiStateMachine.this.sendMessage(CMD_STOP_RSSI_MONITORING_OFFLOAD,
5300                        mWifiInfo.getRssi());
5301                return;
5302            }
5303            int [] rssiVals = Arrays.copyOf(thresholds, thresholds.length + 2);
5304            rssiVals[rssiVals.length - 2] = Byte.MIN_VALUE;
5305            rssiVals[rssiVals.length - 1] = Byte.MAX_VALUE;
5306            Arrays.sort(rssiVals);
5307            byte[] rssiRange = new byte[rssiVals.length];
5308            for (int i = 0; i < rssiVals.length; i++) {
5309                int val = rssiVals[i];
5310                if (val <= Byte.MAX_VALUE && val >= Byte.MIN_VALUE) {
5311                    rssiRange[i] = (byte) val;
5312                } else {
5313                    Log.e(TAG, "Illegal value " + val + " for RSSI thresholds: "
5314                            + Arrays.toString(rssiVals));
5315                    WifiStateMachine.this.sendMessage(CMD_STOP_RSSI_MONITORING_OFFLOAD,
5316                            mWifiInfo.getRssi());
5317                    return;
5318                }
5319            }
5320            // TODO: Do we quash rssi values in this sorted array which are very close?
5321            mRssiRanges = rssiRange;
5322            WifiStateMachine.this.sendMessage(CMD_START_RSSI_MONITORING_OFFLOAD,
5323                    mWifiInfo.getRssi());
5324        }
5325
5326        @Override
5327        protected void preventAutomaticReconnect() {
5328            if (this != mNetworkAgent) return;
5329            unwantedNetwork(NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN);
5330        }
5331    }
5332
5333    void unwantedNetwork(int reason) {
5334        sendMessage(CMD_UNWANTED_NETWORK, reason);
5335    }
5336
5337    void doNetworkStatus(int status) {
5338        sendMessage(CMD_NETWORK_STATUS, status);
5339    }
5340
5341    // rfc4186 & rfc4187:
5342    // create Permanent Identity base on IMSI,
5343    // identity = usernam@realm
5344    // with username = prefix | IMSI
5345    // and realm is derived MMC/MNC tuple according 3GGP spec(TS23.003)
5346    private String buildIdentity(int eapMethod, String imsi, String mccMnc) {
5347        String mcc;
5348        String mnc;
5349        String prefix;
5350
5351        if (imsi == null || imsi.isEmpty())
5352            return "";
5353
5354        if (eapMethod == WifiEnterpriseConfig.Eap.SIM)
5355            prefix = "1";
5356        else if (eapMethod == WifiEnterpriseConfig.Eap.AKA)
5357            prefix = "0";
5358        else if (eapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME)
5359            prefix = "6";
5360        else  // not a valide EapMethod
5361            return "";
5362
5363        /* extract mcc & mnc from mccMnc */
5364        if (mccMnc != null && !mccMnc.isEmpty()) {
5365            mcc = mccMnc.substring(0, 3);
5366            mnc = mccMnc.substring(3);
5367            if (mnc.length() == 2)
5368                mnc = "0" + mnc;
5369        } else {
5370            // extract mcc & mnc from IMSI, assume mnc size is 3
5371            mcc = imsi.substring(0, 3);
5372            mnc = imsi.substring(3, 6);
5373        }
5374
5375        return prefix + imsi + "@wlan.mnc" + mnc + ".mcc" + mcc + ".3gppnetwork.org";
5376    }
5377
5378    boolean startScanForConfiguration(WifiConfiguration config) {
5379        if (config == null)
5380            return false;
5381
5382        // We are still seeing a fairly high power consumption triggered by autojoin scans
5383        // Hence do partial scans only for PSK configuration that are roamable since the
5384        // primary purpose of the partial scans is roaming.
5385        // Full badn scans with exponential backoff for the purpose or extended roaming and
5386        // network switching are performed unconditionally.
5387        ScanDetailCache scanDetailCache =
5388                mWifiConfigManager.getScanDetailCacheForNetwork(config.networkId);
5389        if (scanDetailCache == null
5390                || !config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)
5391                || scanDetailCache.size() > 6) {
5392            //return true but to not trigger the scan
5393            return true;
5394        }
5395        Set<Integer> freqs =
5396                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(
5397                        config.networkId, ONE_HOUR_MILLI, mWifiInfo.getFrequency());
5398        if (freqs != null && freqs.size() != 0) {
5399            //if (mVerboseLoggingEnabled) {
5400            logd("starting scan for " + config.configKey() + " with " + freqs);
5401            //}
5402            List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks = new ArrayList<>();
5403            if (config.hiddenSSID) {
5404                hiddenNetworks.add(new WifiScanner.ScanSettings.HiddenNetwork(config.SSID));
5405            }
5406            // Call wifi native to start the scan
5407            if (startScanNative(freqs, hiddenNetworks, WIFI_WORK_SOURCE)) {
5408                messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK;
5409            } else {
5410                // used for debug only, mark scan as failed
5411                messageHandlingStatus = MESSAGE_HANDLING_STATUS_HANDLING_ERROR;
5412            }
5413            return true;
5414        } else {
5415            if (mVerboseLoggingEnabled) logd("no channels for " + config.configKey());
5416            return false;
5417        }
5418    }
5419
5420    class L2ConnectedState extends State {
5421        @Override
5422        public void enter() {
5423            mRssiPollToken++;
5424            if (mEnableRssiPolling) {
5425                sendMessage(CMD_RSSI_POLL, mRssiPollToken, 0);
5426            }
5427            if (mNetworkAgent != null) {
5428                loge("Have NetworkAgent when entering L2Connected");
5429                setNetworkDetailedState(DetailedState.DISCONNECTED);
5430            }
5431            setNetworkDetailedState(DetailedState.CONNECTING);
5432
5433            mNetworkAgent = new WifiNetworkAgent(getHandler().getLooper(), mContext,
5434                    "WifiNetworkAgent", mNetworkInfo, mNetworkCapabilitiesFilter,
5435                    mLinkProperties, 60, mNetworkMisc);
5436
5437            // We must clear the config BSSID, as the wifi chipset may decide to roam
5438            // from this point on and having the BSSID specified in the network block would
5439            // cause the roam to faile and the device to disconnect
5440            clearTargetBssid("L2ConnectedState");
5441            mCountryCode.setReadyForChange(false);
5442            mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_ASSOCIATED);
5443        }
5444
5445        @Override
5446        public void exit() {
5447            mIpManager.stop();
5448
5449            // This is handled by receiving a NETWORK_DISCONNECTION_EVENT in ConnectModeState
5450            // Bug: 15347363
5451            // For paranoia's sake, call handleNetworkDisconnect
5452            // only if BSSID is null or last networkId
5453            // is not invalid.
5454            if (mVerboseLoggingEnabled) {
5455                StringBuilder sb = new StringBuilder();
5456                sb.append("leaving L2ConnectedState state nid=" + Integer.toString(mLastNetworkId));
5457                if (mLastBssid !=null) {
5458                    sb.append(" ").append(mLastBssid);
5459                }
5460            }
5461            if (mLastBssid != null || mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) {
5462                handleNetworkDisconnect();
5463            }
5464            mCountryCode.setReadyForChange(true);
5465            mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_DISCONNECTED);
5466        }
5467
5468        @Override
5469        public boolean processMessage(Message message) {
5470            logStateAndMessage(message, this);
5471
5472            switch (message.what) {
5473                case DhcpClient.CMD_PRE_DHCP_ACTION:
5474                    handlePreDhcpSetup();
5475                    break;
5476                case DhcpClient.CMD_PRE_DHCP_ACTION_COMPLETE:
5477                    mIpManager.completedPreDhcpAction();
5478                    break;
5479                case DhcpClient.CMD_POST_DHCP_ACTION:
5480                    handlePostDhcpSetup();
5481                    // We advance to mConnectedState because IpManager will also send a
5482                    // CMD_IPV4_PROVISIONING_SUCCESS message, which calls handleIPv4Success(),
5483                    // which calls updateLinkProperties, which then sends
5484                    // CMD_IP_CONFIGURATION_SUCCESSFUL.
5485                    //
5486                    // In the event of failure, we transition to mDisconnectingState
5487                    // similarly--via messages sent back from IpManager.
5488                    break;
5489                case CMD_IPV4_PROVISIONING_SUCCESS: {
5490                    handleIPv4Success((DhcpResults) message.obj);
5491                    sendNetworkStateChangeBroadcast(mLastBssid);
5492                    break;
5493                }
5494                case CMD_IPV4_PROVISIONING_FAILURE: {
5495                    handleIPv4Failure();
5496                    break;
5497                }
5498                case CMD_IP_CONFIGURATION_SUCCESSFUL:
5499                    handleSuccessfulIpConfiguration();
5500                    reportConnectionAttemptEnd(
5501                            WifiMetrics.ConnectionEvent.FAILURE_NONE,
5502                            WifiMetricsProto.ConnectionEvent.HLF_NONE);
5503                    sendConnectedState();
5504                    transitionTo(mConnectedState);
5505                    break;
5506                case CMD_IP_CONFIGURATION_LOST:
5507                    // Get Link layer stats so that we get fresh tx packet counters.
5508                    getWifiLinkLayerStats();
5509                    handleIpConfigurationLost();
5510                    reportConnectionAttemptEnd(
5511                            WifiMetrics.ConnectionEvent.FAILURE_DHCP,
5512                            WifiMetricsProto.ConnectionEvent.HLF_NONE);
5513                    transitionTo(mDisconnectingState);
5514                    break;
5515                case CMD_IP_REACHABILITY_LOST:
5516                    if (mVerboseLoggingEnabled && message.obj != null) log((String) message.obj);
5517                    if (mIpReachabilityDisconnectEnabled) {
5518                        handleIpReachabilityLost();
5519                        transitionTo(mDisconnectingState);
5520                    } else {
5521                        logd("CMD_IP_REACHABILITY_LOST but disconnect disabled -- ignore");
5522                    }
5523                    break;
5524                case CMD_DISCONNECT:
5525                    mWifiNative.disconnect();
5526                    transitionTo(mDisconnectingState);
5527                    break;
5528                case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST:
5529                    if (message.arg1 == 1) {
5530                        mWifiNative.disconnect();
5531                        mTemporarilyDisconnectWifi = true;
5532                        transitionTo(mDisconnectingState);
5533                    }
5534                    break;
5535                case CMD_SET_OPERATIONAL_MODE:
5536                    if (message.arg1 != CONNECT_MODE) {
5537                        sendMessage(CMD_DISCONNECT);
5538                        deferMessage(message);
5539                    }
5540                    break;
5541                    /* Ignore connection to same network */
5542                case WifiManager.CONNECT_NETWORK:
5543                    int netId = message.arg1;
5544                    if (mWifiInfo.getNetworkId() == netId) {
5545                        replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED);
5546                        break;
5547                    }
5548                    return NOT_HANDLED;
5549                case WifiMonitor.NETWORK_CONNECTION_EVENT:
5550                    mWifiInfo.setBSSID((String) message.obj);
5551                    mLastNetworkId = lookupFrameworkNetworkId(message.arg1);
5552                    mWifiInfo.setNetworkId(mLastNetworkId);
5553                    if(!mLastBssid.equals(message.obj)) {
5554                        mLastBssid = (String) message.obj;
5555                        sendNetworkStateChangeBroadcast(mLastBssid);
5556                    }
5557                    break;
5558                case CMD_RSSI_POLL:
5559                    if (message.arg1 == mRssiPollToken) {
5560                        if (mEnableChipWakeUpWhenAssociated) {
5561                            if (mVerboseLoggingEnabled) {
5562                                log(" get link layer stats " + mWifiLinkLayerStatsSupported);
5563                            }
5564                            WifiLinkLayerStats stats = getWifiLinkLayerStats();
5565                            if (stats != null) {
5566                                // Sanity check the results provided by driver
5567                                if (mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI
5568                                        && (stats.rssi_mgmt == 0
5569                                        || stats.beacon_rx == 0)) {
5570                                    stats = null;
5571                                }
5572                            }
5573                            // Get Info and continue polling
5574                            fetchRssiLinkSpeedAndFrequencyNative();
5575                            // Send the update score to network agent.
5576                            mWifiScoreReport.calculateAndReportScore(
5577                                    mWifiInfo, mNetworkAgent, mAggressiveHandover,
5578                                    mWifiMetrics);
5579                        }
5580                        sendMessageDelayed(obtainMessage(CMD_RSSI_POLL,
5581                                mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS);
5582                        if (mVerboseLoggingEnabled) sendRssiChangeBroadcast(mWifiInfo.getRssi());
5583                    } else {
5584                        // Polling has completed
5585                    }
5586                    break;
5587                case CMD_ENABLE_RSSI_POLL:
5588                    cleanWifiScore();
5589                    if (mEnableRssiPollWhenAssociated) {
5590                        mEnableRssiPolling = (message.arg1 == 1);
5591                    } else {
5592                        mEnableRssiPolling = false;
5593                    }
5594                    mRssiPollToken++;
5595                    if (mEnableRssiPolling) {
5596                        // First poll
5597                        fetchRssiLinkSpeedAndFrequencyNative();
5598                        sendMessageDelayed(obtainMessage(CMD_RSSI_POLL,
5599                                mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS);
5600                    }
5601                    break;
5602                case WifiManager.RSSI_PKTCNT_FETCH:
5603                    RssiPacketCountInfo info = new RssiPacketCountInfo();
5604                    fetchRssiLinkSpeedAndFrequencyNative();
5605                    info.rssi = mWifiInfo.getRssi();
5606                    WifiNative.TxPacketCounters counters = mWifiNative.getTxPacketCounters();
5607                    if (counters != null) {
5608                        info.txgood = counters.txSucceeded;
5609                        info.txbad = counters.txFailed;
5610                        replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED, info);
5611                    } else {
5612                        replyToMessage(message,
5613                                WifiManager.RSSI_PKTCNT_FETCH_FAILED, WifiManager.ERROR);
5614                    }
5615                    break;
5616                case CMD_DELAYED_NETWORK_DISCONNECT:
5617                    if (!isLinkDebouncing()) {
5618
5619                        // Ignore if we are not debouncing
5620                        logd("CMD_DELAYED_NETWORK_DISCONNECT and not debouncing - ignore "
5621                                + message.arg1);
5622                        return HANDLED;
5623                    } else {
5624                        logd("CMD_DELAYED_NETWORK_DISCONNECT and debouncing - disconnect "
5625                                + message.arg1);
5626
5627                        mIsLinkDebouncing = false;
5628                        // If we are still debouncing while this message comes,
5629                        // it means we were not able to reconnect within the alloted time
5630                        // = LINK_FLAPPING_DEBOUNCE_MSEC
5631                        // and thus, trigger a real disconnect
5632                        handleNetworkDisconnect();
5633                        transitionTo(mDisconnectedState);
5634                    }
5635                    break;
5636                case CMD_ASSOCIATED_BSSID:
5637                    if ((String) message.obj == null) {
5638                        logw("Associated command w/o BSSID");
5639                        break;
5640                    }
5641                    mLastBssid = (String) message.obj;
5642                    if (mLastBssid != null && (mWifiInfo.getBSSID() == null
5643                            || !mLastBssid.equals(mWifiInfo.getBSSID()))) {
5644                        mWifiInfo.setBSSID((String) message.obj);
5645                        sendNetworkStateChangeBroadcast(mLastBssid);
5646                    }
5647                    break;
5648                case CMD_START_RSSI_MONITORING_OFFLOAD:
5649                case CMD_RSSI_THRESHOLD_BREACH:
5650                    byte currRssi = (byte) message.arg1;
5651                    processRssiThreshold(currRssi, message.what);
5652                    break;
5653                case CMD_STOP_RSSI_MONITORING_OFFLOAD:
5654                    stopRssiMonitoringOffload();
5655                    break;
5656                case CMD_RESET_SIM_NETWORKS:
5657                    if (message.arg1 == 0 // sim was removed
5658                            && mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) {
5659                        WifiConfiguration config =
5660                                mWifiConfigManager.getConfiguredNetwork(mLastNetworkId);
5661                        if (TelephonyUtil.isSimConfig(config)) {
5662                            mWifiNative.disconnect();
5663                            transitionTo(mDisconnectingState);
5664                        }
5665                    }
5666                    /* allow parent state to reset data for other networks */
5667                    return NOT_HANDLED;
5668                default:
5669                    return NOT_HANDLED;
5670            }
5671
5672            return HANDLED;
5673        }
5674    }
5675
5676    class ObtainingIpState extends State {
5677        @Override
5678        public void enter() {
5679            WifiConfiguration currentConfig = getCurrentWifiConfiguration();
5680            boolean isUsingStaticIp =
5681                    (currentConfig.getIpAssignment() == IpConfiguration.IpAssignment.STATIC);
5682            if (mVerboseLoggingEnabled) {
5683                String key = "";
5684                if (getCurrentWifiConfiguration() != null) {
5685                    key = getCurrentWifiConfiguration().configKey();
5686                }
5687                log("enter ObtainingIpState netId=" + Integer.toString(mLastNetworkId)
5688                        + " " + key + " "
5689                        + " roam=" + mAutoRoaming
5690                        + " static=" + isUsingStaticIp);
5691            }
5692
5693            // Reset link Debouncing, indicating we have successfully re-connected to the AP
5694            // We might still be roaming
5695            mIsLinkDebouncing = false;
5696
5697            // Send event to CM & network change broadcast
5698            setNetworkDetailedState(DetailedState.OBTAINING_IPADDR);
5699
5700            // We must clear the config BSSID, as the wifi chipset may decide to roam
5701            // from this point on and having the BSSID specified in the network block would
5702            // cause the roam to fail and the device to disconnect.
5703            clearTargetBssid("ObtainingIpAddress");
5704
5705            // Stop IpManager in case we're switching from DHCP to static
5706            // configuration or vice versa.
5707            //
5708            // TODO: Only ever enter this state the first time we connect to a
5709            // network, never on switching between static configuration and
5710            // DHCP. When we transition from static configuration to DHCP in
5711            // particular, we must tell ConnectivityService that we're
5712            // disconnected, because DHCP might take a long time during which
5713            // connectivity APIs such as getActiveNetworkInfo should not return
5714            // CONNECTED.
5715            stopIpManager();
5716
5717            mIpManager.setHttpProxy(currentConfig.getHttpProxy());
5718            if (!TextUtils.isEmpty(mTcpBufferSizes)) {
5719                mIpManager.setTcpBufferSizes(mTcpBufferSizes);
5720            }
5721
5722            if (!isUsingStaticIp) {
5723                final IpManager.ProvisioningConfiguration prov =
5724                        IpManager.buildProvisioningConfiguration()
5725                            .withPreDhcpAction()
5726                            .withApfCapabilities(mWifiNative.getApfCapabilities())
5727                            .build();
5728                mIpManager.startProvisioning(prov);
5729                // Get Link layer stats so as we get fresh tx packet counters
5730                getWifiLinkLayerStats();
5731            } else {
5732                StaticIpConfiguration config = currentConfig.getStaticIpConfiguration();
5733                if (config.ipAddress == null) {
5734                    logd("Static IP lacks address");
5735                    sendMessage(CMD_IPV4_PROVISIONING_FAILURE);
5736                } else {
5737                    final IpManager.ProvisioningConfiguration prov =
5738                            IpManager.buildProvisioningConfiguration()
5739                                .withStaticConfiguration(config)
5740                                .withApfCapabilities(mWifiNative.getApfCapabilities())
5741                                .build();
5742                    mIpManager.startProvisioning(prov);
5743                }
5744            }
5745        }
5746
5747        @Override
5748        public boolean processMessage(Message message) {
5749            logStateAndMessage(message, this);
5750
5751            switch(message.what) {
5752                case CMD_START_CONNECT:
5753                case CMD_START_ROAM:
5754                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
5755                    break;
5756                case WifiManager.SAVE_NETWORK:
5757                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
5758                    deferMessage(message);
5759                    break;
5760                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
5761                    reportConnectionAttemptEnd(
5762                            WifiMetrics.ConnectionEvent.FAILURE_NETWORK_DISCONNECTION,
5763                            WifiMetricsProto.ConnectionEvent.HLF_NONE);
5764                    return NOT_HANDLED;
5765                case CMD_SET_HIGH_PERF_MODE:
5766                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
5767                    deferMessage(message);
5768                    break;
5769                    /* Defer scan request since we should not switch to other channels at DHCP */
5770                case CMD_START_SCAN:
5771                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED;
5772                    deferMessage(message);
5773                    break;
5774                default:
5775                    return NOT_HANDLED;
5776            }
5777            return HANDLED;
5778        }
5779    }
5780
5781    private void sendConnectedState() {
5782        // If this network was explicitly selected by the user, evaluate whether to call
5783        // explicitlySelected() so the system can treat it appropriately.
5784        WifiConfiguration config = getCurrentWifiConfiguration();
5785        if (mWifiConfigManager.getLastSelectedNetwork() == config.networkId) {
5786            boolean prompt =
5787                    mWifiConfigManager.checkConfigOverridePermission(config.lastConnectUid);
5788            if (mVerboseLoggingEnabled) {
5789                log("Network selected by UID " + config.lastConnectUid + " prompt=" + prompt);
5790            }
5791            if (prompt) {
5792                // Selected by the user via Settings or QuickSettings. If this network has Internet
5793                // access, switch to it. Otherwise, switch to it only if the user confirms that they
5794                // really want to switch, or has already confirmed and selected "Don't ask again".
5795                if (mVerboseLoggingEnabled) {
5796                    log("explictlySelected acceptUnvalidated=" + config.noInternetAccessExpected);
5797                }
5798                mNetworkAgent.explicitlySelected(config.noInternetAccessExpected);
5799            }
5800        }
5801
5802        setNetworkDetailedState(DetailedState.CONNECTED);
5803        mWifiConfigManager.updateNetworkAfterConnect(mLastNetworkId);
5804        sendNetworkStateChangeBroadcast(mLastBssid);
5805    }
5806
5807    class RoamingState extends State {
5808        boolean mAssociated;
5809        @Override
5810        public void enter() {
5811            if (mVerboseLoggingEnabled) {
5812                log("RoamingState Enter"
5813                        + " mScreenOn=" + mScreenOn );
5814            }
5815
5816            // Make sure we disconnect if roaming fails
5817            roamWatchdogCount++;
5818            logd("Start Roam Watchdog " + roamWatchdogCount);
5819            sendMessageDelayed(obtainMessage(CMD_ROAM_WATCHDOG_TIMER,
5820                    roamWatchdogCount, 0), ROAM_GUARD_TIMER_MSEC);
5821            mAssociated = false;
5822        }
5823        @Override
5824        public boolean processMessage(Message message) {
5825            logStateAndMessage(message, this);
5826            WifiConfiguration config;
5827            switch (message.what) {
5828                case CMD_IP_CONFIGURATION_LOST:
5829                    config = getCurrentWifiConfiguration();
5830                    if (config != null) {
5831                        mWifiDiagnostics.captureBugReportData(
5832                                WifiDiagnostics.REPORT_REASON_AUTOROAM_FAILURE);
5833                    }
5834                    return NOT_HANDLED;
5835                case CMD_UNWANTED_NETWORK:
5836                    if (mVerboseLoggingEnabled) {
5837                        log("Roaming and CS doesnt want the network -> ignore");
5838                    }
5839                    return HANDLED;
5840                case CMD_SET_OPERATIONAL_MODE:
5841                    if (message.arg1 != CONNECT_MODE) {
5842                        deferMessage(message);
5843                    }
5844                    break;
5845                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
5846                    /**
5847                     * If we get a SUPPLICANT_STATE_CHANGE_EVENT indicating a DISCONNECT
5848                     * before NETWORK_DISCONNECTION_EVENT
5849                     * And there is an associated BSSID corresponding to our target BSSID, then
5850                     * we have missed the network disconnection, transition to mDisconnectedState
5851                     * and handle the rest of the events there.
5852                     */
5853                    StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
5854                    if (stateChangeResult.state == SupplicantState.DISCONNECTED
5855                            || stateChangeResult.state == SupplicantState.INACTIVE
5856                            || stateChangeResult.state == SupplicantState.INTERFACE_DISABLED) {
5857                        if (mVerboseLoggingEnabled) {
5858                            log("STATE_CHANGE_EVENT in roaming state "
5859                                    + stateChangeResult.toString() );
5860                        }
5861                        if (stateChangeResult.BSSID != null
5862                                && stateChangeResult.BSSID.equals(mTargetRoamBSSID)) {
5863                            handleNetworkDisconnect();
5864                            transitionTo(mDisconnectedState);
5865                        }
5866                    }
5867                    if (stateChangeResult.state == SupplicantState.ASSOCIATED) {
5868                        // We completed the layer2 roaming part
5869                        mAssociated = true;
5870                        if (stateChangeResult.BSSID != null) {
5871                            mTargetRoamBSSID = stateChangeResult.BSSID;
5872                        }
5873                    }
5874                    break;
5875                case CMD_ROAM_WATCHDOG_TIMER:
5876                    if (roamWatchdogCount == message.arg1) {
5877                        if (mVerboseLoggingEnabled) log("roaming watchdog! -> disconnect");
5878                        mWifiMetrics.endConnectionEvent(
5879                                WifiMetrics.ConnectionEvent.FAILURE_ROAM_TIMEOUT,
5880                                WifiMetricsProto.ConnectionEvent.HLF_NONE);
5881                        mRoamFailCount++;
5882                        handleNetworkDisconnect();
5883                        mWifiNative.disconnect();
5884                        transitionTo(mDisconnectedState);
5885                    }
5886                    break;
5887                case WifiMonitor.NETWORK_CONNECTION_EVENT:
5888                    if (mAssociated) {
5889                        if (mVerboseLoggingEnabled) {
5890                            log("roaming and Network connection established");
5891                        }
5892                        mLastNetworkId = lookupFrameworkNetworkId(message.arg1);
5893                        mLastBssid = (String) message.obj;
5894                        mWifiInfo.setBSSID(mLastBssid);
5895                        mWifiInfo.setNetworkId(mLastNetworkId);
5896                        int reasonCode = message.arg2;
5897                        mWifiConnectivityManager.trackBssid(mLastBssid, true, reasonCode);
5898                        sendNetworkStateChangeBroadcast(mLastBssid);
5899
5900                        // Successful framework roam! (probably)
5901                        reportConnectionAttemptEnd(
5902                                WifiMetrics.ConnectionEvent.FAILURE_NONE,
5903                                WifiMetricsProto.ConnectionEvent.HLF_NONE);
5904
5905                        // We must clear the config BSSID, as the wifi chipset may decide to roam
5906                        // from this point on and having the BSSID specified by QNS would cause
5907                        // the roam to fail and the device to disconnect.
5908                        // When transition from RoamingState to DisconnectingState or
5909                        // DisconnectedState, the config BSSID is cleared by
5910                        // handleNetworkDisconnect().
5911                        clearTargetBssid("RoamingCompleted");
5912
5913                        // We used to transition to ObtainingIpState in an
5914                        // attempt to do DHCPv4 RENEWs on framework roams.
5915                        // DHCP can take too long to time out, and we now rely
5916                        // upon IpManager's use of IpReachabilityMonitor to
5917                        // confirm our current network configuration.
5918                        //
5919                        // mIpManager.confirmConfiguration() is called within
5920                        // the handling of SupplicantState.COMPLETED.
5921                        transitionTo(mConnectedState);
5922                    } else {
5923                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
5924                    }
5925                    break;
5926                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
5927                    // Throw away but only if it corresponds to the network we're roaming to
5928                    String bssid = (String) message.obj;
5929                    if (true) {
5930                        String target = "";
5931                        if (mTargetRoamBSSID != null) target = mTargetRoamBSSID;
5932                        log("NETWORK_DISCONNECTION_EVENT in roaming state"
5933                                + " BSSID=" + bssid
5934                                + " target=" + target);
5935                    }
5936                    if (bssid != null && bssid.equals(mTargetRoamBSSID)) {
5937                        handleNetworkDisconnect();
5938                        transitionTo(mDisconnectedState);
5939                    }
5940                    break;
5941                case WifiMonitor.SSID_TEMP_DISABLED:
5942                    // Auth error while roaming
5943                    int netId = lookupFrameworkNetworkId(message.arg1);
5944                    logd("SSID_TEMP_DISABLED nid=" + Integer.toString(mLastNetworkId)
5945                            + " id=" + netId
5946                            + " isRoaming=" + isRoaming()
5947                            + " roam=" + mAutoRoaming);
5948                    if (netId == mLastNetworkId) {
5949                        config = getCurrentWifiConfiguration();
5950                        if (config != null) {
5951                            mWifiDiagnostics.captureBugReportData(
5952                                    WifiDiagnostics.REPORT_REASON_AUTOROAM_FAILURE);
5953                        }
5954                        handleNetworkDisconnect();
5955                        transitionTo(mDisconnectingState);
5956                    }
5957                    return NOT_HANDLED;
5958                case CMD_START_SCAN:
5959                    deferMessage(message);
5960                    break;
5961                default:
5962                    return NOT_HANDLED;
5963            }
5964            return HANDLED;
5965        }
5966
5967        @Override
5968        public void exit() {
5969            logd("WifiStateMachine: Leaving Roaming state");
5970        }
5971    }
5972
5973    class ConnectedState extends State {
5974        @Override
5975        public void enter() {
5976            updateDefaultRouteMacAddress(1000);
5977            if (mVerboseLoggingEnabled) {
5978                log("Enter ConnectedState "
5979                       + " mScreenOn=" + mScreenOn);
5980            }
5981
5982            mWifiConnectivityManager.handleConnectionStateChanged(
5983                    WifiConnectivityManager.WIFI_STATE_CONNECTED);
5984            registerConnected();
5985            lastConnectAttemptTimestamp = 0;
5986            targetWificonfiguration = null;
5987            // Paranoia
5988            mIsLinkDebouncing = false;
5989
5990            // Not roaming anymore
5991            mAutoRoaming = false;
5992
5993            if (testNetworkDisconnect) {
5994                testNetworkDisconnectCounter++;
5995                logd("ConnectedState Enter start disconnect test " +
5996                        testNetworkDisconnectCounter);
5997                sendMessageDelayed(obtainMessage(CMD_TEST_NETWORK_DISCONNECT,
5998                        testNetworkDisconnectCounter, 0), 15000);
5999            }
6000
6001            mLastDriverRoamAttempt = 0;
6002            mTargetNetworkId = WifiConfiguration.INVALID_NETWORK_ID;
6003            mWifiInjector.getWifiLastResortWatchdog().connectedStateTransition(true);
6004            mWifiStateTracker.updateState(WifiStateTracker.CONNECTED);
6005        }
6006        @Override
6007        public boolean processMessage(Message message) {
6008            WifiConfiguration config = null;
6009            logStateAndMessage(message, this);
6010
6011            switch (message.what) {
6012                case CMD_UNWANTED_NETWORK:
6013                    if (message.arg1 == NETWORK_STATUS_UNWANTED_DISCONNECT) {
6014                        mWifiNative.disconnect();
6015                        transitionTo(mDisconnectingState);
6016                    } else if (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN ||
6017                            message.arg1 == NETWORK_STATUS_UNWANTED_VALIDATION_FAILED) {
6018                        Log.d(TAG, (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN
6019                                ? "NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN"
6020                                : "NETWORK_STATUS_UNWANTED_VALIDATION_FAILED"));
6021                        config = getCurrentWifiConfiguration();
6022                        if (config != null) {
6023                            // Disable autojoin
6024                            if (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN) {
6025                                mWifiConfigManager.setNetworkValidatedInternetAccess(
6026                                        config.networkId, false);
6027                                mWifiConfigManager.updateNetworkSelectionStatus(config.networkId,
6028                                        WifiConfiguration.NetworkSelectionStatus
6029                                        .DISABLED_NO_INTERNET);
6030                            }
6031                            mWifiConfigManager.incrementNetworkNoInternetAccessReports(
6032                                    config.networkId);
6033                        }
6034                    }
6035                    return HANDLED;
6036                case CMD_NETWORK_STATUS:
6037                    if (message.arg1 == NetworkAgent.VALID_NETWORK) {
6038                        config = getCurrentWifiConfiguration();
6039                        if (config != null) {
6040                            // re-enable autojoin
6041                            mWifiConfigManager.setNetworkValidatedInternetAccess(
6042                                    config.networkId, true);
6043                        }
6044                    }
6045                    return HANDLED;
6046                case CMD_ACCEPT_UNVALIDATED:
6047                    boolean accept = (message.arg1 != 0);
6048                    mWifiConfigManager.setNetworkNoInternetAccessExpected(mLastNetworkId, accept);
6049                    return HANDLED;
6050                case CMD_TEST_NETWORK_DISCONNECT:
6051                    // Force a disconnect
6052                    if (message.arg1 == testNetworkDisconnectCounter) {
6053                        mWifiNative.disconnect();
6054                    }
6055                    break;
6056                case CMD_ASSOCIATED_BSSID:
6057                    // ASSOCIATING to a new BSSID while already connected, indicates
6058                    // that driver is roaming
6059                    mLastDriverRoamAttempt = mClock.getWallClockMillis();
6060                    return NOT_HANDLED;
6061                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
6062                    long lastRoam = 0;
6063                    reportConnectionAttemptEnd(
6064                            WifiMetrics.ConnectionEvent.FAILURE_NETWORK_DISCONNECTION,
6065                            WifiMetricsProto.ConnectionEvent.HLF_NONE);
6066                    if (mLastDriverRoamAttempt != 0) {
6067                        // Calculate time since last driver roam attempt
6068                        lastRoam = mClock.getWallClockMillis() - mLastDriverRoamAttempt;
6069                        mLastDriverRoamAttempt = 0;
6070                    }
6071                    if (unexpectedDisconnectedReason(message.arg2)) {
6072                        mWifiDiagnostics.captureBugReportData(
6073                                WifiDiagnostics.REPORT_REASON_UNEXPECTED_DISCONNECT);
6074                    }
6075                    config = getCurrentWifiConfiguration();
6076                    if (mEnableLinkDebouncing
6077                            && mScreenOn
6078                            && !isLinkDebouncing()
6079                            && config != null
6080                            && config.getNetworkSelectionStatus().isNetworkEnabled()
6081                            && config.networkId != mWifiConfigManager.getLastSelectedNetwork()
6082                            && (message.arg2 != 3 /* reason cannot be 3, i.e. locally generated */
6083                                || (lastRoam > 0 && lastRoam < 2000) /* unless driver is roaming */)
6084                            && ((ScanResult.is24GHz(mWifiInfo.getFrequency())
6085                                    && mWifiInfo.getRssi() >
6086                                     mThresholdQualifiedRssi5)
6087                                    || (ScanResult.is5GHz(mWifiInfo.getFrequency())
6088                                    && mWifiInfo.getRssi() >
6089                                    mThresholdQualifiedRssi5))) {
6090                        // Start de-bouncing the L2 disconnection:
6091                        // this L2 disconnection might be spurious.
6092                        // Hence we allow 4 seconds for the state machine to try
6093                        // to reconnect, go thru the
6094                        // roaming cycle and enter Obtaining IP address
6095                        // before signalling the disconnect to ConnectivityService and L3
6096                        startScanForConfiguration(getCurrentWifiConfiguration());
6097                        mIsLinkDebouncing = true;
6098
6099                        sendMessageDelayed(obtainMessage(CMD_DELAYED_NETWORK_DISCONNECT,
6100                                0, mLastNetworkId), LINK_FLAPPING_DEBOUNCE_MSEC);
6101                        if (mVerboseLoggingEnabled) {
6102                            log("NETWORK_DISCONNECTION_EVENT in connected state"
6103                                    + " BSSID=" + mWifiInfo.getBSSID()
6104                                    + " RSSI=" + mWifiInfo.getRssi()
6105                                    + " freq=" + mWifiInfo.getFrequency()
6106                                    + " reason=" + message.arg2
6107                                    + " -> debounce");
6108                        }
6109                        return HANDLED;
6110                    } else {
6111                        if (mVerboseLoggingEnabled) {
6112                            log("NETWORK_DISCONNECTION_EVENT in connected state"
6113                                    + " BSSID=" + mWifiInfo.getBSSID()
6114                                    + " RSSI=" + mWifiInfo.getRssi()
6115                                    + " freq=" + mWifiInfo.getFrequency()
6116                                    + " was debouncing=" + isLinkDebouncing()
6117                                    + " reason=" + message.arg2
6118                                    + " Network Selection Status=" + (config == null ? "Unavailable"
6119                                    : config.getNetworkSelectionStatus().getNetworkStatusString()));
6120                        }
6121                    }
6122                    break;
6123                case CMD_START_ROAM:
6124                    // Clear the driver roam indication since we are attempting a framework roam
6125                    mLastDriverRoamAttempt = 0;
6126
6127                    /* Connect command coming from auto-join */
6128                    int netId = message.arg1;
6129                    ScanResult candidate = (ScanResult)message.obj;
6130                    String bssid = SUPPLICANT_BSSID_ANY;
6131                    if (candidate != null) {
6132                        bssid = candidate.BSSID;
6133                    }
6134                    config = mWifiConfigManager.getConfiguredNetworkWithPassword(netId);
6135                    if (config == null) {
6136                        loge("CMD_START_ROAM and no config, bail out...");
6137                        break;
6138                    }
6139
6140                    setTargetBssid(config, bssid);
6141                    mTargetNetworkId = netId;
6142
6143                    logd("CMD_START_ROAM sup state "
6144                            + mSupplicantStateTracker.getSupplicantStateName()
6145                            + " my state " + getCurrentState().getName()
6146                            + " nid=" + Integer.toString(netId)
6147                            + " config " + config.configKey()
6148                            + " targetRoamBSSID " + mTargetRoamBSSID);
6149
6150                    reportConnectionAttemptStart(config, mTargetRoamBSSID,
6151                            WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE);
6152                    if (mWifiNative.roamToNetwork(config)) {
6153                        lastConnectAttemptTimestamp = mClock.getWallClockMillis();
6154                        targetWificonfiguration = config;
6155                        mAutoRoaming = true;
6156                        transitionTo(mRoamingState);
6157                    } else {
6158                        loge("CMD_START_ROAM Failed to start roaming to network " + config);
6159                        reportConnectionAttemptEnd(
6160                                WifiMetrics.ConnectionEvent.FAILURE_CONNECT_NETWORK_FAILED,
6161                                WifiMetricsProto.ConnectionEvent.HLF_NONE);
6162                        replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED,
6163                                WifiManager.ERROR);
6164                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
6165                        break;
6166                    }
6167                    break;
6168                case CMD_START_IP_PACKET_OFFLOAD: {
6169                    int slot = message.arg1;
6170                    int intervalSeconds = message.arg2;
6171                    KeepalivePacketData pkt = (KeepalivePacketData) message.obj;
6172                    byte[] dstMac;
6173                    try {
6174                        InetAddress gateway = RouteInfo.selectBestRoute(
6175                                mLinkProperties.getRoutes(), pkt.dstAddress).getGateway();
6176                        String dstMacStr = macAddressFromRoute(gateway.getHostAddress());
6177                        dstMac = NativeUtil.macAddressToByteArray(dstMacStr);
6178                    } catch (NullPointerException | IllegalArgumentException e) {
6179                        loge("Can't find MAC address for next hop to " + pkt.dstAddress);
6180                        mNetworkAgent.onPacketKeepaliveEvent(slot,
6181                                ConnectivityManager.PacketKeepalive.ERROR_INVALID_IP_ADDRESS);
6182                        break;
6183                    }
6184                    pkt.dstMac = dstMac;
6185                    int result = startWifiIPPacketOffload(slot, pkt, intervalSeconds);
6186                    mNetworkAgent.onPacketKeepaliveEvent(slot, result);
6187                    break;
6188                }
6189                default:
6190                    return NOT_HANDLED;
6191            }
6192            return HANDLED;
6193        }
6194
6195        @Override
6196        public void exit() {
6197            logd("WifiStateMachine: Leaving Connected state");
6198            mWifiConnectivityManager.handleConnectionStateChanged(
6199                     WifiConnectivityManager.WIFI_STATE_TRANSITIONING);
6200
6201            mLastDriverRoamAttempt = 0;
6202            mWifiInjector.getWifiLastResortWatchdog().connectedStateTransition(false);
6203        }
6204    }
6205
6206    class DisconnectingState extends State {
6207
6208        @Override
6209        public void enter() {
6210
6211            if (mVerboseLoggingEnabled) {
6212                logd(" Enter DisconnectingState State screenOn=" + mScreenOn);
6213            }
6214
6215            // Make sure we disconnect: we enter this state prior to connecting to a new
6216            // network, waiting for either a DISCONNECT event or a SUPPLICANT_STATE_CHANGE
6217            // event which in this case will be indicating that supplicant started to associate.
6218            // In some cases supplicant doesn't ignore the connect requests (it might not
6219            // find the target SSID in its cache),
6220            // Therefore we end up stuck that state, hence the need for the watchdog.
6221            disconnectingWatchdogCount++;
6222            logd("Start Disconnecting Watchdog " + disconnectingWatchdogCount);
6223            sendMessageDelayed(obtainMessage(CMD_DISCONNECTING_WATCHDOG_TIMER,
6224                    disconnectingWatchdogCount, 0), DISCONNECTING_GUARD_TIMER_MSEC);
6225        }
6226
6227        @Override
6228        public boolean processMessage(Message message) {
6229            logStateAndMessage(message, this);
6230            switch (message.what) {
6231                case CMD_SET_OPERATIONAL_MODE:
6232                    if (message.arg1 != CONNECT_MODE) {
6233                        deferMessage(message);
6234                    }
6235                    break;
6236                case CMD_START_SCAN:
6237                    deferMessage(message);
6238                    return HANDLED;
6239                case CMD_DISCONNECT:
6240                    if (mVerboseLoggingEnabled) log("Ignore CMD_DISCONNECT when already disconnecting.");
6241                    break;
6242                case CMD_DISCONNECTING_WATCHDOG_TIMER:
6243                    if (disconnectingWatchdogCount == message.arg1) {
6244                        if (mVerboseLoggingEnabled) log("disconnecting watchdog! -> disconnect");
6245                        handleNetworkDisconnect();
6246                        transitionTo(mDisconnectedState);
6247                    }
6248                    break;
6249                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
6250                    /**
6251                     * If we get a SUPPLICANT_STATE_CHANGE_EVENT before NETWORK_DISCONNECTION_EVENT
6252                     * we have missed the network disconnection, transition to mDisconnectedState
6253                     * and handle the rest of the events there
6254                     */
6255                    deferMessage(message);
6256                    handleNetworkDisconnect();
6257                    transitionTo(mDisconnectedState);
6258                    break;
6259                default:
6260                    return NOT_HANDLED;
6261            }
6262            return HANDLED;
6263        }
6264    }
6265
6266    class DisconnectedState extends State {
6267        @Override
6268        public void enter() {
6269            // We dont scan frequently if this is a temporary disconnect
6270            // due to p2p
6271            if (mTemporarilyDisconnectWifi) {
6272                p2pSendMessage(WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE);
6273                return;
6274            }
6275
6276            if (mVerboseLoggingEnabled) {
6277                logd(" Enter DisconnectedState screenOn=" + mScreenOn);
6278            }
6279
6280            /** clear the roaming state, if we were roaming, we failed */
6281            mAutoRoaming = false;
6282
6283            mWifiConnectivityManager.handleConnectionStateChanged(
6284                    WifiConnectivityManager.WIFI_STATE_DISCONNECTED);
6285
6286            /**
6287             * If we have no networks saved, the supplicant stops doing the periodic scan.
6288             * The scans are useful to notify the user of the presence of an open network.
6289             * Note that these are not wake up scans.
6290             */
6291            if (mNoNetworksPeriodicScan != 0 && !mP2pConnected.get()
6292                    && mWifiConfigManager.getSavedNetworks().size() == 0) {
6293                sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN,
6294                        ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan);
6295            }
6296
6297            mDisconnectedTimeStamp = mClock.getWallClockMillis();
6298            mWifiStateTracker.updateState(WifiStateTracker.DISCONNECTED);
6299        }
6300        @Override
6301        public boolean processMessage(Message message) {
6302            boolean ret = HANDLED;
6303
6304            logStateAndMessage(message, this);
6305
6306            switch (message.what) {
6307                case CMD_NO_NETWORKS_PERIODIC_SCAN:
6308                    if (mP2pConnected.get()) break;
6309                    if (mNoNetworksPeriodicScan != 0 && message.arg1 == mPeriodicScanToken &&
6310                            mWifiConfigManager.getSavedNetworks().size() == 0) {
6311                        startScan(UNKNOWN_SCAN_SOURCE, -1, null, WIFI_WORK_SOURCE);
6312                        sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN,
6313                                    ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan);
6314                    }
6315                    break;
6316                case WifiManager.FORGET_NETWORK:
6317                case CMD_REMOVE_NETWORK:
6318                case CMD_REMOVE_APP_CONFIGURATIONS:
6319                case CMD_REMOVE_USER_CONFIGURATIONS:
6320                    // Set up a delayed message here. After the forget/remove is handled
6321                    // the handled delayed message will determine if there is a need to
6322                    // scan and continue
6323                    sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN,
6324                                ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan);
6325                    ret = NOT_HANDLED;
6326                    break;
6327                case CMD_SET_OPERATIONAL_MODE:
6328                    if (message.arg1 != CONNECT_MODE) {
6329                        mOperationalMode = message.arg1;
6330                        if (mOperationalMode == DISABLED_MODE) {
6331                            transitionTo(mSupplicantStoppingState);
6332                        } else if (mOperationalMode == SCAN_ONLY_MODE
6333                                || mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) {
6334                            p2pSendMessage(CMD_DISABLE_P2P_REQ);
6335                            setWifiState(WIFI_STATE_DISABLED);
6336                            transitionTo(mScanModeState);
6337                        }
6338                    }
6339                    break;
6340                case CMD_DISCONNECT:
6341                    mWifiNative.disconnect();
6342                    break;
6343                /* Ignore network disconnect */
6344                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
6345                    // Interpret this as an L2 connection failure
6346                    break;
6347                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
6348                    StateChangeResult stateChangeResult = (StateChangeResult) message.obj;
6349                    if (mVerboseLoggingEnabled) {
6350                        logd("SUPPLICANT_STATE_CHANGE_EVENT state=" + stateChangeResult.state +
6351                                " -> state= " + WifiInfo.getDetailedStateOf(stateChangeResult.state)
6352                                + " debouncing=" + isLinkDebouncing());
6353                    }
6354                    setNetworkDetailedState(WifiInfo.getDetailedStateOf(stateChangeResult.state));
6355                    /* ConnectModeState does the rest of the handling */
6356                    ret = NOT_HANDLED;
6357                    break;
6358                case CMD_START_SCAN:
6359                    if (!checkOrDeferScanAllowed(message)) {
6360                        // The scan request was rescheduled
6361                        messageHandlingStatus = MESSAGE_HANDLING_STATUS_REFUSED;
6362                        return HANDLED;
6363                    }
6364
6365                    ret = NOT_HANDLED;
6366                    break;
6367                case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED:
6368                    NetworkInfo info = (NetworkInfo) message.obj;
6369                    mP2pConnected.set(info.isConnected());
6370                    if (!mP2pConnected.get() && mWifiConfigManager.getSavedNetworks().size() == 0) {
6371                        if (mVerboseLoggingEnabled) log("Turn on scanning after p2p disconnected");
6372                        sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN,
6373                                    ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan);
6374                    }
6375                    break;
6376                case CMD_RECONNECT:
6377                case CMD_REASSOCIATE:
6378                    if (mTemporarilyDisconnectWifi) {
6379                        // Drop a third party reconnect/reassociate if STA is
6380                        // temporarily disconnected for p2p
6381                        break;
6382                    } else {
6383                        // ConnectModeState handles it
6384                        ret = NOT_HANDLED;
6385                    }
6386                    break;
6387                case CMD_SCREEN_STATE_CHANGED:
6388                    handleScreenStateChanged(message.arg1 != 0);
6389                    break;
6390                default:
6391                    ret = NOT_HANDLED;
6392            }
6393            return ret;
6394        }
6395
6396        @Override
6397        public void exit() {
6398            mWifiConnectivityManager.handleConnectionStateChanged(
6399                     WifiConnectivityManager.WIFI_STATE_TRANSITIONING);
6400        }
6401    }
6402
6403    class WpsRunningState extends State {
6404        // Tracks the source to provide a reply
6405        private Message mSourceMessage;
6406        @Override
6407        public void enter() {
6408            mSourceMessage = Message.obtain(getCurrentMessage());
6409        }
6410        @Override
6411        public boolean processMessage(Message message) {
6412            logStateAndMessage(message, this);
6413
6414            switch (message.what) {
6415                case WifiMonitor.WPS_SUCCESS_EVENT:
6416                    // Ignore intermediate success, wait for full connection
6417                    break;
6418                case WifiMonitor.NETWORK_CONNECTION_EVENT:
6419                    replyToMessage(mSourceMessage, WifiManager.WPS_COMPLETED);
6420                    mSourceMessage.recycle();
6421                    mSourceMessage = null;
6422                    deferMessage(message);
6423                    transitionTo(mDisconnectedState);
6424                    break;
6425                case WifiMonitor.WPS_OVERLAP_EVENT:
6426                    replyToMessage(mSourceMessage, WifiManager.WPS_FAILED,
6427                            WifiManager.WPS_OVERLAP_ERROR);
6428                    mSourceMessage.recycle();
6429                    mSourceMessage = null;
6430                    transitionTo(mDisconnectedState);
6431                    break;
6432                case WifiMonitor.WPS_FAIL_EVENT:
6433                    // Arg1 has the reason for the failure
6434                    if ((message.arg1 != WifiManager.ERROR) || (message.arg2 != 0)) {
6435                        replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, message.arg1);
6436                        mSourceMessage.recycle();
6437                        mSourceMessage = null;
6438                        transitionTo(mDisconnectedState);
6439                    } else {
6440                        if (mVerboseLoggingEnabled) {
6441                            log("Ignore unspecified fail event during WPS connection");
6442                        }
6443                    }
6444                    break;
6445                case WifiMonitor.WPS_TIMEOUT_EVENT:
6446                    replyToMessage(mSourceMessage, WifiManager.WPS_FAILED,
6447                            WifiManager.WPS_TIMED_OUT);
6448                    mSourceMessage.recycle();
6449                    mSourceMessage = null;
6450                    transitionTo(mDisconnectedState);
6451                    break;
6452                case WifiManager.START_WPS:
6453                    replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.IN_PROGRESS);
6454                    break;
6455                case WifiManager.CANCEL_WPS:
6456                    if (mWifiNative.cancelWps()) {
6457                        replyToMessage(message, WifiManager.CANCEL_WPS_SUCCEDED);
6458                    } else {
6459                        replyToMessage(message, WifiManager.CANCEL_WPS_FAILED, WifiManager.ERROR);
6460                    }
6461                    transitionTo(mDisconnectedState);
6462                    break;
6463                /**
6464                 * Defer all commands that can cause connections to a different network
6465                 * or put the state machine out of connect mode
6466                 */
6467                case CMD_SET_OPERATIONAL_MODE:
6468                case WifiManager.CONNECT_NETWORK:
6469                case CMD_ENABLE_NETWORK:
6470                case CMD_RECONNECT:
6471                case CMD_REASSOCIATE:
6472                    deferMessage(message);
6473                    break;
6474                case CMD_START_CONNECT:
6475                case CMD_START_ROAM:
6476                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
6477                    return HANDLED;
6478                case CMD_START_SCAN:
6479                    messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD;
6480                    return HANDLED;
6481                case WifiMonitor.NETWORK_DISCONNECTION_EVENT:
6482                    if (mVerboseLoggingEnabled) log("Network connection lost");
6483                    handleNetworkDisconnect();
6484                    break;
6485                case WifiMonitor.ASSOCIATION_REJECTION_EVENT:
6486                    if (mVerboseLoggingEnabled) {
6487                        log("Ignore Assoc reject event during WPS Connection");
6488                    }
6489                    break;
6490                case WifiMonitor.AUTHENTICATION_FAILURE_EVENT:
6491                    // Disregard auth failure events during WPS connection. The
6492                    // EAP sequence is retried several times, and there might be
6493                    // failures (especially for wps pin). We will get a WPS_XXX
6494                    // event at the end of the sequence anyway.
6495                    if (mVerboseLoggingEnabled) log("Ignore auth failure during WPS connection");
6496                    break;
6497                case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT:
6498                    // Throw away supplicant state changes when WPS is running.
6499                    // We will start getting supplicant state changes once we get
6500                    // a WPS success or failure
6501                    break;
6502                default:
6503                    return NOT_HANDLED;
6504            }
6505            return HANDLED;
6506        }
6507
6508        @Override
6509        public void exit() {
6510            mWifiConfigManager.loadFromStore();
6511        }
6512    }
6513
6514    class SoftApState extends State {
6515        private SoftApManager mSoftApManager;
6516
6517        private class SoftApListener implements SoftApManager.Listener {
6518            @Override
6519            public void onStateChanged(int state, int reason) {
6520                if (state == WIFI_AP_STATE_DISABLED) {
6521                    sendMessage(CMD_AP_STOPPED);
6522                } else if (state == WIFI_AP_STATE_FAILED) {
6523                    sendMessage(CMD_START_AP_FAILURE);
6524                }
6525
6526                setWifiApState(state, reason);
6527            }
6528        }
6529
6530        @Override
6531        public void enter() {
6532            final Message message = getCurrentMessage();
6533            if (message.what != CMD_START_AP) {
6534                throw new RuntimeException("Illegal transition to SoftApState: " + message);
6535            }
6536
6537            IApInterface apInterface = mWifiNative.setupDriverForSoftApMode();
6538            if (apInterface == null) {
6539                setWifiApState(WIFI_AP_STATE_FAILED,
6540                        WifiManager.SAP_START_FAILURE_GENERAL);
6541                /**
6542                 * Transition to InitialState to reset the
6543                 * driver/HAL back to the initial state.
6544                 */
6545                transitionTo(mInitialState);
6546                return;
6547            }
6548
6549            WifiConfiguration config = (WifiConfiguration) message.obj;
6550
6551            checkAndSetConnectivityInstance();
6552            mSoftApManager = mWifiInjector.makeSoftApManager(mNwService,
6553                                                             new SoftApListener(),
6554                                                             apInterface,
6555                                                             config);
6556            mSoftApManager.start();
6557            mWifiStateTracker.updateState(WifiStateTracker.SOFT_AP);
6558        }
6559
6560        @Override
6561        public void exit() {
6562            mSoftApManager = null;
6563        }
6564
6565        @Override
6566        public boolean processMessage(Message message) {
6567            logStateAndMessage(message, this);
6568
6569            switch(message.what) {
6570                case CMD_START_AP:
6571                    /* Ignore start command when it is starting/started. */
6572                    break;
6573                case CMD_STOP_AP:
6574                    mSoftApManager.stop();
6575                    break;
6576                case CMD_START_AP_FAILURE:
6577                    transitionTo(mInitialState);
6578                    break;
6579                case CMD_AP_STOPPED:
6580                    transitionTo(mInitialState);
6581                    break;
6582                default:
6583                    return NOT_HANDLED;
6584            }
6585            return HANDLED;
6586        }
6587    }
6588
6589    /**
6590     * State machine initiated requests can have replyTo set to null indicating
6591     * there are no recepients, we ignore those reply actions.
6592     */
6593    private void replyToMessage(Message msg, int what) {
6594        if (msg.replyTo == null) return;
6595        Message dstMsg = obtainMessageWithWhatAndArg2(msg, what);
6596        mReplyChannel.replyToMessage(msg, dstMsg);
6597    }
6598
6599    private void replyToMessage(Message msg, int what, int arg1) {
6600        if (msg.replyTo == null) return;
6601        Message dstMsg = obtainMessageWithWhatAndArg2(msg, what);
6602        dstMsg.arg1 = arg1;
6603        mReplyChannel.replyToMessage(msg, dstMsg);
6604    }
6605
6606    private void replyToMessage(Message msg, int what, Object obj) {
6607        if (msg.replyTo == null) return;
6608        Message dstMsg = obtainMessageWithWhatAndArg2(msg, what);
6609        dstMsg.obj = obj;
6610        mReplyChannel.replyToMessage(msg, dstMsg);
6611    }
6612
6613    /**
6614     * arg2 on the source message has a unique id that needs to be retained in replies
6615     * to match the request
6616     * <p>see WifiManager for details
6617     */
6618    private Message obtainMessageWithWhatAndArg2(Message srcMsg, int what) {
6619        Message msg = Message.obtain();
6620        msg.what = what;
6621        msg.arg2 = srcMsg.arg2;
6622        return msg;
6623    }
6624
6625    /**
6626     * Notify interested parties if a wifi config has been changed.
6627     *
6628     * @param wifiCredentialEventType WIFI_CREDENTIAL_SAVED or WIFI_CREDENTIAL_FORGOT
6629     * @param config Must have a WifiConfiguration object to succeed
6630     * TODO: b/35258354 investigate if this can be removed.  Is the broadcast sent by
6631     * WifiConfigManager sufficient?
6632     */
6633    private void broadcastWifiCredentialChanged(int wifiCredentialEventType,
6634            WifiConfiguration config) {
6635        if (config != null && config.preSharedKey != null) {
6636            Intent intent = new Intent(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION);
6637            intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID, config.SSID);
6638            intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE,
6639                    wifiCredentialEventType);
6640            mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT,
6641                    android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE);
6642        }
6643    }
6644
6645    void handleGsmAuthRequest(SimAuthRequestData requestData) {
6646        if (targetWificonfiguration == null
6647                || targetWificonfiguration.networkId
6648                == lookupFrameworkNetworkId(requestData.networkId)) {
6649            logd("id matches targetWifiConfiguration");
6650        } else {
6651            logd("id does not match targetWifiConfiguration");
6652            return;
6653        }
6654
6655        String response =
6656                TelephonyUtil.getGsmSimAuthResponse(requestData.data, getTelephonyManager());
6657        if (response == null) {
6658            mWifiNative.simAuthFailedResponse(requestData.networkId);
6659        } else {
6660            logv("Supplicant Response -" + response);
6661            mWifiNative.simAuthResponse(requestData.networkId, "GSM-AUTH", response);
6662        }
6663    }
6664
6665    void handle3GAuthRequest(SimAuthRequestData requestData) {
6666        if (targetWificonfiguration == null
6667                || targetWificonfiguration.networkId
6668                == lookupFrameworkNetworkId(requestData.networkId)) {
6669            logd("id matches targetWifiConfiguration");
6670        } else {
6671            logd("id does not match targetWifiConfiguration");
6672            return;
6673        }
6674
6675        SimAuthResponseData response =
6676                TelephonyUtil.get3GAuthResponse(requestData, getTelephonyManager());
6677        if (response != null) {
6678            mWifiNative.simAuthResponse(requestData.networkId, response.type, response.response);
6679        } else {
6680            mWifiNative.umtsAuthFailedResponse(requestData.networkId);
6681        }
6682    }
6683
6684    /**
6685     * Automatically connect to the network specified
6686     *
6687     * @param networkId ID of the network to connect to
6688     * @param bssid BSSID of the network
6689     */
6690    public void startConnectToNetwork(int networkId, String bssid) {
6691        synchronized (mWifiReqCountLock) {
6692            if (hasConnectionRequests()) {
6693                sendMessage(CMD_START_CONNECT, networkId, 0, bssid);
6694            }
6695        }
6696    }
6697
6698    /**
6699     * Automatically roam to the network specified
6700     *
6701     * @param networkId ID of the network to roam to
6702     * @param scanResult scan result which identifies the network to roam to
6703     */
6704    public void startRoamToNetwork(int networkId, ScanResult scanResult) {
6705        sendMessage(CMD_START_ROAM, networkId, 0, scanResult);
6706    }
6707
6708    /**
6709     * Dynamically turn on/off WifiConnectivityManager
6710     *
6711     * @param enabled true-enable; false-disable
6712     */
6713    public void enableWifiConnectivityManager(boolean enabled) {
6714        sendMessage(CMD_ENABLE_WIFI_CONNECTIVITY_MANAGER, enabled ? 1 : 0);
6715    }
6716
6717    /**
6718     * @param reason reason code from supplicant on network disconnected event
6719     * @return true if this is a suspicious disconnect
6720     */
6721    static boolean unexpectedDisconnectedReason(int reason) {
6722        return reason == 2              // PREV_AUTH_NOT_VALID
6723                || reason == 6          // CLASS2_FRAME_FROM_NONAUTH_STA
6724                || reason == 7          // FRAME_FROM_NONASSOC_STA
6725                || reason == 8          // STA_HAS_LEFT
6726                || reason == 9          // STA_REQ_ASSOC_WITHOUT_AUTH
6727                || reason == 14         // MICHAEL_MIC_FAILURE
6728                || reason == 15         // 4WAY_HANDSHAKE_TIMEOUT
6729                || reason == 16         // GROUP_KEY_UPDATE_TIMEOUT
6730                || reason == 18         // GROUP_CIPHER_NOT_VALID
6731                || reason == 19         // PAIRWISE_CIPHER_NOT_VALID
6732                || reason == 23         // IEEE_802_1X_AUTH_FAILED
6733                || reason == 34;        // DISASSOC_LOW_ACK
6734    }
6735
6736    /**
6737     * Update WifiMetrics before dumping
6738     */
6739    public void updateWifiMetrics() {
6740        mWifiMetrics.updateSavedNetworks(mWifiConfigManager.getSavedNetworks());
6741    }
6742
6743    /**
6744     * Private method to handle calling WifiConfigManager to forget/remove network configs and reply
6745     * to the message from the sender of the outcome.
6746     *
6747     * The current implementation requires that forget and remove be handled in different ways
6748     * (responses are handled differently).  In the interests of organization, the handling is all
6749     * now in this helper method.  TODO: b/35257965 is filed to track the possibility of merging
6750     * the two call paths.
6751     */
6752    private boolean deleteNetworkConfigAndSendReply(Message message, boolean calledFromForget) {
6753        boolean success = mWifiConfigManager.removeNetwork(message.arg1, message.sendingUid);
6754        if (!success) {
6755            loge("Failed to remove network");
6756        }
6757
6758        if (calledFromForget) {
6759            if (success) {
6760                replyToMessage(message, WifiManager.FORGET_NETWORK_SUCCEEDED);
6761                broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_FORGOT,
6762                                               (WifiConfiguration) message.obj);
6763                return true;
6764            }
6765            replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, WifiManager.ERROR);
6766            return false;
6767        } else {
6768            // Remaining calls are from the removeNetwork path
6769            if (success) {
6770                replyToMessage(message, message.what, SUCCESS);
6771                return true;
6772            }
6773            messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL;
6774            replyToMessage(message, message.what, FAILURE);
6775            return false;
6776        }
6777    }
6778
6779    private static String getLinkPropertiesSummary(LinkProperties lp) {
6780        List<String> attributes = new ArrayList<>(6);
6781        if (lp.hasIPv4Address()) {
6782            attributes.add("v4");
6783        }
6784        if (lp.hasIPv4DefaultRoute()) {
6785            attributes.add("v4r");
6786        }
6787        if (lp.hasIPv4DnsServer()) {
6788            attributes.add("v4dns");
6789        }
6790        if (lp.hasGlobalIPv6Address()) {
6791            attributes.add("v6");
6792        }
6793        if (lp.hasIPv6DefaultRoute()) {
6794            attributes.add("v6r");
6795        }
6796        if (lp.hasIPv6DnsServer()) {
6797            attributes.add("v6dns");
6798        }
6799
6800        return TextUtils.join(" ", attributes);
6801    }
6802
6803    /**
6804     * Gets the SSID from the WifiConfiguration pointed at by 'mTargetNetworkId'
6805     * This should match the network config framework is attempting to connect to.
6806     */
6807    private String getTargetSsid() {
6808        WifiConfiguration currentConfig = mWifiConfigManager.getConfiguredNetwork(mTargetNetworkId);
6809        if (currentConfig != null) {
6810            return currentConfig.SSID;
6811        }
6812        return null;
6813    }
6814
6815    private void p2pSendMessage(int what) {
6816        if (mWifiP2pChannel != null) {
6817            mWifiP2pChannel.sendMessage(what);
6818        }
6819    }
6820
6821    private void p2pSendMessage(int what, int arg1) {
6822        if (mWifiP2pChannel != null) {
6823            mWifiP2pChannel.sendMessage(what, arg1);
6824        }
6825    }
6826
6827    /**
6828     * Check if there is any connection request for WiFi network.
6829     * Note, caller of this helper function must acquire mWifiReqCountLock.
6830     */
6831    private boolean hasConnectionRequests() {
6832        return mConnectionReqCount > 0 || mUntrustedReqCount > 0;
6833    }
6834
6835    /**
6836     * Returns whether CMD_IP_REACHABILITY_LOST events should trigger disconnects.
6837     */
6838    public boolean getIpReachabilityDisconnectEnabled() {
6839        return mIpReachabilityDisconnectEnabled;
6840    }
6841
6842    /**
6843     * Sets whether CMD_IP_REACHABILITY_LOST events should trigger disconnects.
6844     */
6845    public void setIpReachabilityDisconnectEnabled(boolean enabled) {
6846        mIpReachabilityDisconnectEnabled = enabled;
6847    }
6848
6849    /**
6850     * Sends a message to initialize the WifiStateMachine.
6851     *
6852     * @return true if succeeded, false otherwise.
6853     */
6854    public boolean syncInitialize(AsyncChannel channel) {
6855        Message resultMsg = channel.sendMessageSynchronously(CMD_INITIALIZE);
6856        boolean result = (resultMsg.arg1 != FAILURE);
6857        resultMsg.recycle();
6858        return result;
6859    }
6860}
6861