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