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