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