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