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