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