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