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