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