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