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