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