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