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