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