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