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