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