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