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