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