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