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