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