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