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