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