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