WifiStateMachine.java revision 163f9765f9e4c3f868b1e0d630b6adeaa115fb4a
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; 28import static android.net.wifi.WifiManager.WIFI_STATE_UNKNOWN; 29 30import android.Manifest; 31import android.app.ActivityManager; 32import android.app.PendingIntent; 33import android.bluetooth.BluetoothAdapter; 34import android.content.BroadcastReceiver; 35import android.content.Context; 36import android.content.Intent; 37import android.content.IntentFilter; 38import android.content.pm.ApplicationInfo; 39import android.content.pm.IPackageManager; 40import android.content.pm.PackageManager; 41import android.database.ContentObserver; 42import android.net.ConnectivityManager; 43import android.net.DhcpResults; 44import android.net.IpConfiguration; 45import android.net.LinkProperties; 46import android.net.Network; 47import android.net.NetworkAgent; 48import android.net.NetworkCapabilities; 49import android.net.NetworkFactory; 50import android.net.NetworkInfo; 51import android.net.NetworkInfo.DetailedState; 52import android.net.NetworkMisc; 53import android.net.NetworkRequest; 54import android.net.NetworkUtils; 55import android.net.RouteInfo; 56import android.net.StaticIpConfiguration; 57import android.net.TrafficStats; 58import android.net.dhcp.DhcpClient; 59import android.net.ip.IpManager; 60import android.net.wifi.IApInterface; 61import android.net.wifi.IClientInterface; 62import android.net.wifi.RssiPacketCountInfo; 63import android.net.wifi.ScanResult; 64import android.net.wifi.ScanSettings; 65import android.net.wifi.SupplicantState; 66import android.net.wifi.WifiChannel; 67import android.net.wifi.WifiConfiguration; 68import android.net.wifi.WifiConnectionStatistics; 69import android.net.wifi.WifiEnterpriseConfig; 70import android.net.wifi.WifiInfo; 71import android.net.wifi.WifiLinkLayerStats; 72import android.net.wifi.WifiManager; 73import android.net.wifi.WifiScanner; 74import android.net.wifi.WifiSsid; 75import android.net.wifi.WpsInfo; 76import android.net.wifi.WpsResult; 77import android.net.wifi.WpsResult.Status; 78import android.net.wifi.hotspot2.PasspointConfiguration; 79import android.net.wifi.p2p.IWifiP2pManager; 80import android.os.BatteryStats; 81import android.os.Binder; 82import android.os.Bundle; 83import android.os.IBinder; 84import android.os.INetworkManagementService; 85import android.os.Looper; 86import android.os.Message; 87import android.os.Messenger; 88import android.os.PowerManager; 89import android.os.Process; 90import android.os.RemoteException; 91import android.os.UserHandle; 92import android.os.UserManager; 93import android.os.WorkSource; 94import android.provider.Settings; 95import android.telephony.TelephonyManager; 96import android.text.TextUtils; 97import android.util.Log; 98import android.util.SparseArray; 99 100import com.android.internal.R; 101import com.android.internal.annotations.GuardedBy; 102import com.android.internal.annotations.VisibleForTesting; 103import com.android.internal.app.IBatteryStats; 104import com.android.internal.util.AsyncChannel; 105import com.android.internal.util.MessageUtils; 106import com.android.internal.util.Protocol; 107import com.android.internal.util.State; 108import com.android.internal.util.StateMachine; 109import com.android.server.connectivity.KeepalivePacketData; 110import com.android.server.wifi.hotspot2.AnqpEvent; 111import com.android.server.wifi.hotspot2.IconEvent; 112import com.android.server.wifi.hotspot2.NetworkDetail; 113import com.android.server.wifi.hotspot2.PasspointManager; 114import com.android.server.wifi.hotspot2.Utils; 115import com.android.server.wifi.hotspot2.WnmData; 116import com.android.server.wifi.p2p.WifiP2pServiceImpl; 117import com.android.server.wifi.util.NativeUtil; 118import com.android.server.wifi.util.TelephonyUtil; 119import com.android.server.wifi.util.TelephonyUtil.SimAuthRequestData; 120import com.android.server.wifi.util.TelephonyUtil.SimAuthResponseData; 121import com.android.server.wifi.util.WifiPermissionsUtil; 122 123import java.io.BufferedReader; 124import java.io.FileDescriptor; 125import java.io.FileNotFoundException; 126import java.io.FileReader; 127import java.io.IOException; 128import java.io.PrintWriter; 129import java.net.Inet4Address; 130import java.net.InetAddress; 131import java.util.ArrayList; 132import java.util.Arrays; 133import java.util.HashMap; 134import java.util.HashSet; 135import java.util.LinkedList; 136import java.util.List; 137import java.util.Map; 138import java.util.Queue; 139import java.util.Set; 140import java.util.concurrent.atomic.AtomicBoolean; 141import java.util.concurrent.atomic.AtomicInteger; 142 143/** 144 * TODO: 145 * Deprecate WIFI_STATE_UNKNOWN 146 */ 147 148/** 149 * Track the state of Wifi connectivity. All event handling is done here, 150 * and all changes in connectivity state are initiated here. 151 * 152 * Wi-Fi now supports three modes of operation: Client, SoftAp and p2p 153 * In the current implementation, we support concurrent wifi p2p and wifi operation. 154 * The WifiStateMachine handles SoftAp and Client operations while WifiP2pService 155 * handles p2p operation. 156 * 157 * @hide 158 */ 159public class WifiStateMachine extends StateMachine implements WifiNative.WifiRssiEventHandler, 160 WifiMulticastLockManager.FilterController { 161 162 private static final String NETWORKTYPE = "WIFI"; 163 private static final String NETWORKTYPE_UNTRUSTED = "WIFI_UT"; 164 @VisibleForTesting public static final short NUM_LOG_RECS_NORMAL = 100; 165 @VisibleForTesting public static final short NUM_LOG_RECS_VERBOSE_LOW_MEMORY = 200; 166 @VisibleForTesting public static final short NUM_LOG_RECS_VERBOSE = 3000; 167 private static final String TAG = "WifiStateMachine"; 168 169 private static final int ONE_HOUR_MILLI = 1000 * 60 * 60; 170 171 private static final String GOOGLE_OUI = "DA-A1-19"; 172 173 private static final String EXTRA_OSU_ICON_QUERY_BSSID = "BSSID"; 174 private static final String EXTRA_OSU_ICON_QUERY_FILENAME = "FILENAME"; 175 176 private boolean mVerboseLoggingEnabled = false; 177 178 /* debug flag, indicating if handling of ASSOCIATION_REJECT ended up blacklisting 179 * the corresponding BSSID. 180 */ 181 private boolean didBlackListBSSID = false; 182 183 /** 184 * Log with error attribute 185 * 186 * @param s is string log 187 */ 188 @Override 189 protected void loge(String s) { 190 Log.e(getName(), s); 191 } 192 @Override 193 protected void logd(String s) { 194 Log.d(getName(), s); 195 } 196 @Override 197 protected void log(String s) { 198 Log.d(getName(), s); 199 } 200 private WifiMetrics mWifiMetrics; 201 private WifiInjector mWifiInjector; 202 private WifiMonitor mWifiMonitor; 203 private WifiNative mWifiNative; 204 private WifiPermissionsUtil mWifiPermissionsUtil; 205 private WifiConfigManager mWifiConfigManager; 206 private WifiConnectivityManager mWifiConnectivityManager; 207 private WifiNetworkSelector mWifiNetworkSelector; 208 private INetworkManagementService mNwService; 209 private IClientInterface mClientInterface; 210 private ConnectivityManager mCm; 211 private BaseWifiDiagnostics mWifiDiagnostics; 212 private WifiApConfigStore mWifiApConfigStore; 213 private final boolean mP2pSupported; 214 private final AtomicBoolean mP2pConnected = new AtomicBoolean(false); 215 private boolean mTemporarilyDisconnectWifi = false; 216 private final String mPrimaryDeviceType; 217 private final Clock mClock; 218 private final PropertyService mPropertyService; 219 private final BuildProperties mBuildProperties; 220 private final WifiCountryCode mCountryCode; 221 // Object holding most recent wifi score report and bad Linkspeed count 222 private final WifiScoreReport mWifiScoreReport; 223 private final PasspointManager mPasspointManager; 224 225 /* Scan results handling */ 226 private List<ScanDetail> mScanResults = new ArrayList<>(); 227 private final Object mScanResultsLock = new Object(); 228 229 // For debug, number of known scan results that were found as part of last scan result event, 230 // as well the number of scans results returned by the supplicant with that message 231 private int mNumScanResultsKnown; 232 private int mNumScanResultsReturned; 233 234 private boolean mScreenOn = false; 235 236 private final String mInterfaceName; 237 238 private int mLastSignalLevel = -1; 239 private String mLastBssid; 240 private int mLastNetworkId; // The network Id we successfully joined 241 private boolean mIsLinkDebouncing = false; 242 private final StateMachineDeathRecipient mDeathRecipient = 243 new StateMachineDeathRecipient(this, CMD_CLIENT_INTERFACE_BINDER_DEATH); 244 private boolean mIpReachabilityDisconnectEnabled = true; 245 246 @Override 247 public void onRssiThresholdBreached(byte curRssi) { 248 if (mVerboseLoggingEnabled) { 249 Log.e(TAG, "onRssiThresholdBreach event. Cur Rssi = " + curRssi); 250 } 251 sendMessage(CMD_RSSI_THRESHOLD_BREACH, curRssi); 252 } 253 254 public void processRssiThreshold(byte curRssi, int reason) { 255 if (curRssi == Byte.MAX_VALUE || curRssi == Byte.MIN_VALUE) { 256 Log.wtf(TAG, "processRssiThreshold: Invalid rssi " + curRssi); 257 return; 258 } 259 for (int i = 0; i < mRssiRanges.length; i++) { 260 if (curRssi < mRssiRanges[i]) { 261 // Assume sorted values(ascending order) for rssi, 262 // bounded by high(127) and low(-128) at extremeties 263 byte maxRssi = mRssiRanges[i]; 264 byte minRssi = mRssiRanges[i-1]; 265 // This value of hw has to be believed as this value is averaged and has breached 266 // the rssi thresholds and raised event to host. This would be eggregious if this 267 // value is invalid 268 mWifiInfo.setRssi(curRssi); 269 updateCapabilities(getCurrentWifiConfiguration()); 270 int ret = startRssiMonitoringOffload(maxRssi, minRssi); 271 Log.d(TAG, "Re-program RSSI thresholds for " + smToString(reason) + 272 ": [" + minRssi + ", " + maxRssi + "], curRssi=" + curRssi + " ret=" + ret); 273 break; 274 } 275 } 276 } 277 278 // Testing various network disconnect cases by sending lots of spurious 279 // disconnect to supplicant 280 private boolean testNetworkDisconnect = false; 281 282 private boolean mEnableRssiPolling = false; 283 private int mRssiPollToken = 0; 284 /* 3 operational states for STA operation: CONNECT_MODE, SCAN_ONLY_MODE, SCAN_ONLY_WIFI_OFF_MODE 285 * In CONNECT_MODE, the STA can scan and connect to an access point 286 * In SCAN_ONLY_MODE, the STA can only scan for access points 287 * In SCAN_ONLY_WIFI_OFF_MODE, the STA can only scan for access points with wifi toggle being off 288 */ 289 private int mOperationalMode = CONNECT_MODE; 290 private boolean mIsScanOngoing = false; 291 private boolean mIsFullScanOngoing = false; 292 293 private final Queue<Message> mBufferedScanMsg = new LinkedList<>(); 294 private static final int UNKNOWN_SCAN_SOURCE = -1; 295 private static final int ADD_OR_UPDATE_SOURCE = -3; 296 297 private static final int SCAN_REQUEST_BUFFER_MAX_SIZE = 10; 298 private static final String CUSTOMIZED_SCAN_SETTING = "customized_scan_settings"; 299 private static final String CUSTOMIZED_SCAN_WORKSOURCE = "customized_scan_worksource"; 300 private static final String SCAN_REQUEST_TIME = "scan_request_time"; 301 302 private boolean mBluetoothConnectionActive = false; 303 304 private PowerManager.WakeLock mSuspendWakeLock; 305 306 /** 307 * Interval in milliseconds between polling for RSSI 308 * and linkspeed information 309 */ 310 private static final int POLL_RSSI_INTERVAL_MSECS = 3000; 311 312 /** 313 * Interval in milliseconds between receiving a disconnect event 314 * while connected to a good AP, and handling the disconnect proper 315 */ 316 private static final int LINK_FLAPPING_DEBOUNCE_MSEC = 4000; 317 318 /** 319 * Delay between supplicant restarts upon failure to establish connection 320 */ 321 private static final int SUPPLICANT_RESTART_INTERVAL_MSECS = 5000; 322 323 /** 324 * Number of times we attempt to restart supplicant 325 */ 326 private static final int SUPPLICANT_RESTART_TRIES = 5; 327 328 /** 329 * Value to set in wpa_supplicant "bssid" field when we don't want to restrict connection to 330 * a specific AP. 331 */ 332 private static final String SUPPLICANT_BSSID_ANY = "any"; 333 334 private int mSupplicantRestartCount = 0; 335 336 /** 337 * The link properties of the wifi interface. 338 * Do not modify this directly; use updateLinkProperties instead. 339 */ 340 private LinkProperties mLinkProperties; 341 342 /* Tracks sequence number on a periodic scan message */ 343 private int mPeriodicScanToken = 0; 344 345 // Wakelock held during wifi start/stop and driver load/unload 346 private PowerManager.WakeLock mWakeLock; 347 348 private Context mContext; 349 350 private final Object mDhcpResultsLock = new Object(); 351 private DhcpResults mDhcpResults; 352 353 // NOTE: Do not return to clients - use #getWiFiInfoForUid(int) 354 private final WifiInfo mWifiInfo; 355 private NetworkInfo mNetworkInfo; 356 private final NetworkCapabilities mDfltNetworkCapabilities; 357 private SupplicantStateTracker mSupplicantStateTracker; 358 359 private int mWifiLinkLayerStatsSupported = 4; // Temporary disable 360 361 // Whether the state machine goes thru the Disconnecting->Disconnected->ObtainingIpAddress 362 private boolean mAutoRoaming = false; 363 364 // Roaming failure count 365 private int mRoamFailCount = 0; 366 367 // This is the BSSID we are trying to associate to, it can be set to SUPPLICANT_BSSID_ANY 368 // if we havent selected a BSSID for joining. 369 private String mTargetRoamBSSID = SUPPLICANT_BSSID_ANY; 370 // This one is used to track whta is the current target network ID. This is used for error 371 // handling during connection setup since many error message from supplicant does not report 372 // SSID Once connected, it will be set to invalid 373 private int mTargetNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 374 private long mLastDriverRoamAttempt = 0; 375 private WifiConfiguration targetWificonfiguration = null; 376 377 boolean isRoaming() { 378 return mAutoRoaming; 379 } 380 381 /** 382 * Method to clear {@link #mTargetRoamBSSID} and reset the the current connected network's 383 * bssid in wpa_supplicant after a roam/connect attempt. 384 */ 385 public boolean clearTargetBssid(String dbg) { 386 WifiConfiguration config = mWifiConfigManager.getConfiguredNetwork(mTargetNetworkId); 387 if (config == null) { 388 return false; 389 } 390 String bssid = SUPPLICANT_BSSID_ANY; 391 if (config.BSSID != null) { 392 bssid = config.BSSID; 393 if (mVerboseLoggingEnabled) { 394 Log.d(TAG, "force BSSID to " + bssid + "due to config"); 395 } 396 } 397 if (mVerboseLoggingEnabled) { 398 logd(dbg + " clearTargetBssid " + bssid + " key=" + config.configKey()); 399 } 400 mTargetRoamBSSID = bssid; 401 return mWifiNative.setConfiguredNetworkBSSID(bssid); 402 } 403 404 /** 405 * Set Config's default BSSID (for association purpose) and {@link #mTargetRoamBSSID} 406 * @param config config need set BSSID 407 * @param bssid default BSSID to assocaite with when connect to this network 408 * @return false -- does not change the current default BSSID of the configure 409 * true -- change the current default BSSID of the configur 410 */ 411 private boolean setTargetBssid(WifiConfiguration config, String bssid) { 412 if (config == null || bssid == null) { 413 return false; 414 } 415 if (config.BSSID != null) { 416 bssid = config.BSSID; 417 if (mVerboseLoggingEnabled) { 418 Log.d(TAG, "force BSSID to " + bssid + "due to config"); 419 } 420 } 421 if (mVerboseLoggingEnabled) { 422 Log.d(TAG, "setTargetBssid set to " + bssid + " key=" + config.configKey()); 423 } 424 mTargetRoamBSSID = bssid; 425 config.getNetworkSelectionStatus().setNetworkSelectionBSSID(bssid); 426 return true; 427 } 428 429 private final IpManager mIpManager; 430 431 // Channel for sending replies. 432 private AsyncChannel mReplyChannel = new AsyncChannel(); 433 434 // Used to initiate a connection with WifiP2pService 435 private AsyncChannel mWifiP2pChannel; 436 437 private WifiScanner mWifiScanner; 438 439 @GuardedBy("mWifiReqCountLock") 440 private int mConnectionReqCount = 0; 441 private WifiNetworkFactory mNetworkFactory; 442 @GuardedBy("mWifiReqCountLock") 443 private int mUntrustedReqCount = 0; 444 private UntrustedWifiNetworkFactory mUntrustedNetworkFactory; 445 private WifiNetworkAgent mNetworkAgent; 446 private final Object mWifiReqCountLock = new Object(); 447 448 private byte[] mRssiRanges; 449 450 // Keep track of various statistics, for retrieval by System Apps, i.e. under @SystemApi 451 // We should really persist that into the networkHistory.txt file, and read it back when 452 // WifiStateMachine starts up 453 private WifiConnectionStatistics mWifiConnectionStatistics = new WifiConnectionStatistics(); 454 455 // Used to filter out requests we couldn't possibly satisfy. 456 private final NetworkCapabilities mNetworkCapabilitiesFilter = new NetworkCapabilities(); 457 458 // Provide packet filter capabilities to ConnectivityService. 459 private final NetworkMisc mNetworkMisc = new NetworkMisc(); 460 461 /* The base for wifi message types */ 462 static final int BASE = Protocol.BASE_WIFI; 463 /* Start the supplicant */ 464 static final int CMD_START_SUPPLICANT = BASE + 11; 465 /* Stop the supplicant */ 466 static final int CMD_STOP_SUPPLICANT = BASE + 12; 467 /* Indicates Static IP succeeded */ 468 static final int CMD_STATIC_IP_SUCCESS = BASE + 15; 469 /* Indicates Static IP failed */ 470 static final int CMD_STATIC_IP_FAILURE = BASE + 16; 471 /* A delayed message sent to start driver when it fail to come up */ 472 static final int CMD_DRIVER_START_TIMED_OUT = BASE + 19; 473 474 /* Start the soft access point */ 475 static final int CMD_START_AP = BASE + 21; 476 /* Indicates soft ap start failed */ 477 static final int CMD_START_AP_FAILURE = BASE + 22; 478 /* Stop the soft access point */ 479 static final int CMD_STOP_AP = BASE + 23; 480 /* Soft access point teardown is completed. */ 481 static final int CMD_AP_STOPPED = BASE + 24; 482 483 static final int CMD_BLUETOOTH_ADAPTER_STATE_CHANGE = BASE + 31; 484 485 /* Supplicant commands */ 486 /* Is supplicant alive ? */ 487 static final int CMD_PING_SUPPLICANT = BASE + 51; 488 /* Add/update a network configuration */ 489 static final int CMD_ADD_OR_UPDATE_NETWORK = BASE + 52; 490 /* Delete a network */ 491 static final int CMD_REMOVE_NETWORK = BASE + 53; 492 /* Enable a network. The device will attempt a connection to the given network. */ 493 static final int CMD_ENABLE_NETWORK = BASE + 54; 494 /* Save configuration */ 495 static final int CMD_SAVE_CONFIG = BASE + 58; 496 /* Get configured networks */ 497 static final int CMD_GET_CONFIGURED_NETWORKS = BASE + 59; 498 /* Get adaptors */ 499 static final int CMD_GET_SUPPORTED_FEATURES = BASE + 61; 500 /* Get configured networks with real preSharedKey */ 501 static final int CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS = BASE + 62; 502 /* Get Link Layer Stats thru HAL */ 503 static final int CMD_GET_LINK_LAYER_STATS = BASE + 63; 504 /* Supplicant commands after driver start*/ 505 /* Initiate a scan */ 506 static final int CMD_START_SCAN = BASE + 71; 507 /* Set operational mode. CONNECT, SCAN ONLY, SCAN_ONLY with Wi-Fi off mode */ 508 static final int CMD_SET_OPERATIONAL_MODE = BASE + 72; 509 /* Disconnect from a network */ 510 static final int CMD_DISCONNECT = BASE + 73; 511 /* Reconnect to a network */ 512 static final int CMD_RECONNECT = BASE + 74; 513 /* Reassociate to a network */ 514 static final int CMD_REASSOCIATE = BASE + 75; 515 /* Get Connection Statistis */ 516 static final int CMD_GET_CONNECTION_STATISTICS = BASE + 76; 517 518 /* Controls suspend mode optimizations 519 * 520 * When high perf mode is enabled, suspend mode optimizations are disabled 521 * 522 * When high perf mode is disabled, suspend mode optimizations are enabled 523 * 524 * Suspend mode optimizations include: 525 * - packet filtering 526 * - turn off roaming 527 * - DTIM wake up settings 528 */ 529 static final int CMD_SET_HIGH_PERF_MODE = BASE + 77; 530 /* Enables RSSI poll */ 531 static final int CMD_ENABLE_RSSI_POLL = BASE + 82; 532 /* RSSI poll */ 533 static final int CMD_RSSI_POLL = BASE + 83; 534 /* Enable suspend mode optimizations in the driver */ 535 static final int CMD_SET_SUSPEND_OPT_ENABLED = BASE + 86; 536 /* Delayed NETWORK_DISCONNECT */ 537 static final int CMD_DELAYED_NETWORK_DISCONNECT = BASE + 87; 538 /* When there are no saved networks, we do a periodic scan to notify user of 539 * an open network */ 540 static final int CMD_NO_NETWORKS_PERIODIC_SCAN = BASE + 88; 541 /* Test network Disconnection NETWORK_DISCONNECT */ 542 static final int CMD_TEST_NETWORK_DISCONNECT = BASE + 89; 543 544 private int testNetworkDisconnectCounter = 0; 545 546 /* Enable TDLS on a specific MAC address */ 547 static final int CMD_ENABLE_TDLS = BASE + 92; 548 549 /** 550 * Watchdog for protecting against b/16823537 551 * Leave time for 4-way handshake to succeed 552 */ 553 static final int ROAM_GUARD_TIMER_MSEC = 15000; 554 555 int roamWatchdogCount = 0; 556 /* Roam state watchdog */ 557 static final int CMD_ROAM_WATCHDOG_TIMER = BASE + 94; 558 /* Screen change intent handling */ 559 static final int CMD_SCREEN_STATE_CHANGED = BASE + 95; 560 561 /* Disconnecting state watchdog */ 562 static final int CMD_DISCONNECTING_WATCHDOG_TIMER = BASE + 96; 563 564 /* Remove a packages associated configrations */ 565 static final int CMD_REMOVE_APP_CONFIGURATIONS = BASE + 97; 566 567 /* Disable an ephemeral network */ 568 static final int CMD_DISABLE_EPHEMERAL_NETWORK = BASE + 98; 569 570 /* Get matching network */ 571 static final int CMD_GET_MATCHING_CONFIG = BASE + 99; 572 573 /* alert from firmware */ 574 static final int CMD_FIRMWARE_ALERT = BASE + 100; 575 576 /* SIM is removed; reset any cached data for it */ 577 static final int CMD_RESET_SIM_NETWORKS = BASE + 101; 578 579 /* OSU APIs */ 580 static final int CMD_QUERY_OSU_ICON = BASE + 104; 581 582 /* try to match a provider with current network */ 583 static final int CMD_MATCH_PROVIDER_NETWORK = BASE + 105; 584 585 // Add or update a Passpoint configuration. 586 static final int CMD_ADD_OR_UPDATE_PASSPOINT_CONFIG = BASE + 106; 587 588 // Remove a Passpoint configuration. 589 static final int CMD_REMOVE_PASSPOINT_CONFIG = BASE + 107; 590 591 // Get the list of installed Passpoint configurations. 592 static final int CMD_GET_PASSPOINT_CONFIGS = BASE + 108; 593 594 /* Commands from/to the SupplicantStateTracker */ 595 /* Reset the supplicant state tracker */ 596 static final int CMD_RESET_SUPPLICANT_STATE = BASE + 111; 597 598 int disconnectingWatchdogCount = 0; 599 static final int DISCONNECTING_GUARD_TIMER_MSEC = 5000; 600 601 /* P2p commands */ 602 /* We are ok with no response here since we wont do much with it anyway */ 603 public static final int CMD_ENABLE_P2P = BASE + 131; 604 /* In order to shut down supplicant cleanly, we wait till p2p has 605 * been disabled */ 606 public static final int CMD_DISABLE_P2P_REQ = BASE + 132; 607 public static final int CMD_DISABLE_P2P_RSP = BASE + 133; 608 609 /** 610 * Indicates the end of boot process, should be used to trigger load from config store, 611 * initiate connection attempt, etc. 612 * */ 613 static final int CMD_BOOT_COMPLETED = BASE + 134; 614 /** 615 * Initialize the WifiStateMachine. This is currently used to initialize the 616 * {@link HalDeviceManager} module. 617 */ 618 static final int CMD_INITIALIZE = BASE + 135; 619 620 /* We now have a valid IP configuration. */ 621 static final int CMD_IP_CONFIGURATION_SUCCESSFUL = BASE + 138; 622 /* We no longer have a valid IP configuration. */ 623 static final int CMD_IP_CONFIGURATION_LOST = BASE + 139; 624 /* Link configuration (IP address, DNS, ...) changes notified via netlink */ 625 static final int CMD_UPDATE_LINKPROPERTIES = BASE + 140; 626 627 /* Supplicant is trying to associate to a given BSSID */ 628 static final int CMD_TARGET_BSSID = BASE + 141; 629 630 /* Reload all networks and reconnect */ 631 static final int CMD_RELOAD_TLS_AND_RECONNECT = BASE + 142; 632 633 static final int CMD_START_CONNECT = BASE + 143; 634 635 private static final int NETWORK_STATUS_UNWANTED_DISCONNECT = 0; 636 private static final int NETWORK_STATUS_UNWANTED_VALIDATION_FAILED = 1; 637 private static final int NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN = 2; 638 639 static final int CMD_UNWANTED_NETWORK = BASE + 144; 640 641 static final int CMD_START_ROAM = BASE + 145; 642 643 static final int CMD_ASSOCIATED_BSSID = BASE + 147; 644 645 static final int CMD_NETWORK_STATUS = BASE + 148; 646 647 /* A layer 3 neighbor on the Wi-Fi link became unreachable. */ 648 static final int CMD_IP_REACHABILITY_LOST = BASE + 149; 649 650 /* Remove a packages associated configrations */ 651 static final int CMD_REMOVE_USER_CONFIGURATIONS = BASE + 152; 652 653 static final int CMD_ACCEPT_UNVALIDATED = BASE + 153; 654 655 /* used to offload sending IP packet */ 656 static final int CMD_START_IP_PACKET_OFFLOAD = BASE + 160; 657 658 /* used to stop offload sending IP packet */ 659 static final int CMD_STOP_IP_PACKET_OFFLOAD = BASE + 161; 660 661 /* used to start rssi monitoring in hw */ 662 static final int CMD_START_RSSI_MONITORING_OFFLOAD = BASE + 162; 663 664 /* used to stop rssi moniroting in hw */ 665 static final int CMD_STOP_RSSI_MONITORING_OFFLOAD = BASE + 163; 666 667 /* used to indicated RSSI threshold breach in hw */ 668 static final int CMD_RSSI_THRESHOLD_BREACH = BASE + 164; 669 670 /* Enable/Disable WifiConnectivityManager */ 671 static final int CMD_ENABLE_WIFI_CONNECTIVITY_MANAGER = BASE + 166; 672 673 /* Enable/Disable AutoJoin when associated */ 674 static final int CMD_ENABLE_AUTOJOIN_WHEN_ASSOCIATED = BASE + 167; 675 676 /** 677 * Used to handle messages bounced between WifiStateMachine and IpManager. 678 */ 679 static final int CMD_IPV4_PROVISIONING_SUCCESS = BASE + 200; 680 static final int CMD_IPV4_PROVISIONING_FAILURE = BASE + 201; 681 682 /* Push a new APF program to the HAL */ 683 static final int CMD_INSTALL_PACKET_FILTER = BASE + 202; 684 685 /* Enable/disable fallback packet filtering */ 686 static final int CMD_SET_FALLBACK_PACKET_FILTERING = BASE + 203; 687 688 /* Enable/disable Neighbor Discovery offload functionality. */ 689 static final int CMD_CONFIG_ND_OFFLOAD = BASE + 204; 690 691 /* used to indicate that the foreground user was switched */ 692 static final int CMD_USER_SWITCH = BASE + 205; 693 694 /* used to indicate that the foreground user was switched */ 695 static final int CMD_USER_UNLOCK = BASE + 206; 696 697 /* used to indicate that the foreground user was switched */ 698 static final int CMD_USER_STOP = BASE + 207; 699 700 /* Signals that IClientInterface instance underpinning our state is dead. */ 701 private static final int CMD_CLIENT_INTERFACE_BINDER_DEATH = BASE + 250; 702 703 /* Indicates that diagnostics should time out a connection start event. */ 704 private static final int CMD_DIAGS_CONNECT_TIMEOUT = BASE + 251; 705 706 // For message logging. 707 private static final Class[] sMessageClasses = { 708 AsyncChannel.class, WifiStateMachine.class, DhcpClient.class }; 709 private static final SparseArray<String> sSmToString = 710 MessageUtils.findMessageNames(sMessageClasses); 711 712 713 /* Wifi state machine modes of operation */ 714 /* CONNECT_MODE - connect to any 'known' AP when it becomes available */ 715 public static final int CONNECT_MODE = 1; 716 /* SCAN_ONLY_MODE - don't connect to any APs; scan, but only while apps hold lock */ 717 public static final int SCAN_ONLY_MODE = 2; 718 /* SCAN_ONLY_WITH_WIFI_OFF - scan, but don't connect to any APs */ 719 public static final int SCAN_ONLY_WITH_WIFI_OFF_MODE = 3; 720 /* DISABLED_MODE - Don't connect, don't scan, don't be an AP */ 721 public static final int DISABLED_MODE = 4; 722 723 private static final int SUCCESS = 1; 724 private static final int FAILURE = -1; 725 726 /* Tracks if suspend optimizations need to be disabled by DHCP, 727 * screen or due to high perf mode. 728 * When any of them needs to disable it, we keep the suspend optimizations 729 * disabled 730 */ 731 private int mSuspendOptNeedsDisabled = 0; 732 733 private static final int SUSPEND_DUE_TO_DHCP = 1; 734 private static final int SUSPEND_DUE_TO_HIGH_PERF = 1 << 1; 735 private static final int SUSPEND_DUE_TO_SCREEN = 1 << 2; 736 737 /* Tracks if user has enabled suspend optimizations through settings */ 738 private AtomicBoolean mUserWantsSuspendOpt = new AtomicBoolean(true); 739 740 /** 741 * Scan period for the NO_NETWORKS_PERIIDOC_SCAN_FEATURE 742 */ 743 private final int mNoNetworksPeriodicScan; 744 745 /** 746 * Supplicant scan interval in milliseconds. 747 * Comes from {@link Settings.Global#WIFI_SUPPLICANT_SCAN_INTERVAL_MS} or 748 * from the default config if the setting is not set 749 */ 750 private long mSupplicantScanIntervalMs; 751 752 private boolean mEnableAutoJoinWhenAssociated; 753 private int mAlwaysEnableScansWhileAssociated; 754 private final int mThresholdQualifiedRssi24; 755 private final int mThresholdQualifiedRssi5; 756 private final int mThresholdSaturatedRssi24; 757 private final int mThresholdSaturatedRssi5; 758 private final int mThresholdMinimumRssi5; 759 private final int mThresholdMinimumRssi24; 760 private final boolean mEnableLinkDebouncing; 761 private final boolean mEnableChipWakeUpWhenAssociated; 762 private final boolean mEnableRssiPollWhenAssociated; 763 764 int mRunningBeaconCount = 0; 765 766 /* Default parent state */ 767 private State mDefaultState = new DefaultState(); 768 /* Temporary initial state */ 769 private State mInitialState = new InitialState(); 770 /* Driver loaded, waiting for supplicant to start */ 771 private State mSupplicantStartingState = new SupplicantStartingState(); 772 /* Driver loaded and supplicant ready */ 773 private State mSupplicantStartedState = new SupplicantStartedState(); 774 /* Waiting for supplicant to stop and monitor to exit */ 775 private State mSupplicantStoppingState = new SupplicantStoppingState(); 776 /* Wait until p2p is disabled 777 * This is a special state which is entered right after we exit out of DriverStartedState 778 * before transitioning to another state. 779 */ 780 private State mWaitForP2pDisableState = new WaitForP2pDisableState(); 781 /* Scan for networks, no connection will be established */ 782 private State mScanModeState = new ScanModeState(); 783 /* Connecting to an access point */ 784 private State mConnectModeState = new ConnectModeState(); 785 /* Connected at 802.11 (L2) level */ 786 private State mL2ConnectedState = new L2ConnectedState(); 787 /* fetching IP after connection to access point (assoc+auth complete) */ 788 private State mObtainingIpState = new ObtainingIpState(); 789 /* Connected with IP addr */ 790 private State mConnectedState = new ConnectedState(); 791 /* Roaming */ 792 private State mRoamingState = new RoamingState(); 793 /* disconnect issued, waiting for network disconnect confirmation */ 794 private State mDisconnectingState = new DisconnectingState(); 795 /* Network is not connected, supplicant assoc+auth is not complete */ 796 private State mDisconnectedState = new DisconnectedState(); 797 /* Waiting for WPS to be completed*/ 798 private State mWpsRunningState = new WpsRunningState(); 799 /* Soft ap state */ 800 private State mSoftApState = new SoftApState(); 801 802 /** 803 * One of {@link WifiManager#WIFI_STATE_DISABLED}, 804 * {@link WifiManager#WIFI_STATE_DISABLING}, 805 * {@link WifiManager#WIFI_STATE_ENABLED}, 806 * {@link WifiManager#WIFI_STATE_ENABLING}, 807 * {@link WifiManager#WIFI_STATE_UNKNOWN} 808 */ 809 private final AtomicInteger mWifiState = new AtomicInteger(WIFI_STATE_DISABLED); 810 811 /** 812 * One of {@link WifiManager#WIFI_AP_STATE_DISABLED}, 813 * {@link WifiManager#WIFI_AP_STATE_DISABLING}, 814 * {@link WifiManager#WIFI_AP_STATE_ENABLED}, 815 * {@link WifiManager#WIFI_AP_STATE_ENABLING}, 816 * {@link WifiManager#WIFI_AP_STATE_FAILED} 817 */ 818 private final AtomicInteger mWifiApState = new AtomicInteger(WIFI_AP_STATE_DISABLED); 819 820 /** 821 * Work source to use to blame usage on the WiFi service 822 */ 823 public static final WorkSource WIFI_WORK_SOURCE = new WorkSource(Process.WIFI_UID); 824 825 /** 826 * Keep track of whether WIFI is running. 827 */ 828 private boolean mIsRunning = false; 829 830 /** 831 * Keep track of whether we last told the battery stats we had started. 832 */ 833 private boolean mReportedRunning = false; 834 835 /** 836 * Most recently set source of starting WIFI. 837 */ 838 private final WorkSource mRunningWifiUids = new WorkSource(); 839 840 /** 841 * The last reported UIDs that were responsible for starting WIFI. 842 */ 843 private final WorkSource mLastRunningWifiUids = new WorkSource(); 844 845 private TelephonyManager mTelephonyManager; 846 private TelephonyManager getTelephonyManager() { 847 if (mTelephonyManager == null) { 848 mTelephonyManager = mWifiInjector.makeTelephonyManager(); 849 } 850 return mTelephonyManager; 851 } 852 853 private final IBatteryStats mBatteryStats; 854 855 private final String mTcpBufferSizes; 856 857 // Used for debug and stats gathering 858 private static int sScanAlarmIntentCount = 0; 859 860 private FrameworkFacade mFacade; 861 private WifiStateTracker mWifiStateTracker; 862 private final BackupManagerProxy mBackupManagerProxy; 863 864 public WifiStateMachine(Context context, FrameworkFacade facade, Looper looper, 865 UserManager userManager, WifiInjector wifiInjector, 866 BackupManagerProxy backupManagerProxy, WifiCountryCode countryCode, 867 WifiNative wifiNative) { 868 super("WifiStateMachine", looper); 869 mWifiInjector = wifiInjector; 870 mWifiMetrics = mWifiInjector.getWifiMetrics(); 871 mClock = wifiInjector.getClock(); 872 mPropertyService = wifiInjector.getPropertyService(); 873 mBuildProperties = wifiInjector.getBuildProperties(); 874 mContext = context; 875 mFacade = facade; 876 mWifiNative = wifiNative; 877 mBackupManagerProxy = backupManagerProxy; 878 879 // TODO refactor WifiNative use of context out into it's own class 880 mInterfaceName = mWifiNative.getInterfaceName(); 881 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, NETWORKTYPE, ""); 882 mBatteryStats = IBatteryStats.Stub.asInterface(mFacade.getService( 883 BatteryStats.SERVICE_NAME)); 884 mWifiStateTracker = wifiInjector.getWifiStateTracker(); 885 IBinder b = mFacade.getService(Context.NETWORKMANAGEMENT_SERVICE); 886 mNwService = INetworkManagementService.Stub.asInterface(b); 887 888 mP2pSupported = mContext.getPackageManager().hasSystemFeature( 889 PackageManager.FEATURE_WIFI_DIRECT); 890 891 mWifiPermissionsUtil = mWifiInjector.getWifiPermissionsUtil(); 892 mWifiConfigManager = mWifiInjector.getWifiConfigManager(); 893 mWifiApConfigStore = mWifiInjector.getWifiApConfigStore(); 894 895 mPasspointManager = mWifiInjector.getPasspointManager(); 896 897 mWifiMonitor = mWifiInjector.getWifiMonitor(); 898 mWifiDiagnostics = mWifiInjector.makeWifiDiagnostics(mWifiNative); 899 900 mWifiInfo = new WifiInfo(); 901 mWifiNetworkSelector = mWifiInjector.getWifiNetworkSelector(); 902 mSupplicantStateTracker = 903 mFacade.makeSupplicantStateTracker(context, mWifiConfigManager, getHandler()); 904 905 mLinkProperties = new LinkProperties(); 906 907 mNetworkInfo.setIsAvailable(false); 908 mLastBssid = null; 909 mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 910 mLastSignalLevel = -1; 911 912 mIpManager = mFacade.makeIpManager(mContext, mInterfaceName, new IpManagerCallback()); 913 mIpManager.setMulticastFilter(true); 914 915 mNoNetworksPeriodicScan = mContext.getResources().getInteger( 916 R.integer.config_wifi_no_network_periodic_scan_interval); 917 918 // TODO: remove these settings from the config file since we no longer obey them 919 // mContext.getResources().getInteger(R.integer.config_wifi_framework_scan_interval); 920 // mContext.getResources().getBoolean(R.bool.config_wifi_background_scan_support); 921 922 mPrimaryDeviceType = mContext.getResources().getString( 923 R.string.config_wifi_p2p_device_type); 924 925 mCountryCode = countryCode; 926 927 mWifiScoreReport = new WifiScoreReport(mContext, mWifiConfigManager); 928 929 mUserWantsSuspendOpt.set(mFacade.getIntegerSetting(mContext, 930 Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED, 1) == 1); 931 932 mNetworkCapabilitiesFilter.addTransportType(NetworkCapabilities.TRANSPORT_WIFI); 933 mNetworkCapabilitiesFilter.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); 934 mNetworkCapabilitiesFilter.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED); 935 mNetworkCapabilitiesFilter.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED); 936 mNetworkCapabilitiesFilter.setLinkUpstreamBandwidthKbps(1024 * 1024); 937 mNetworkCapabilitiesFilter.setLinkDownstreamBandwidthKbps(1024 * 1024); 938 // TODO - needs to be a bit more dynamic 939 mDfltNetworkCapabilities = new NetworkCapabilities(mNetworkCapabilitiesFilter); 940 941 IntentFilter filter = new IntentFilter(); 942 filter.addAction(Intent.ACTION_SCREEN_ON); 943 filter.addAction(Intent.ACTION_SCREEN_OFF); 944 mContext.registerReceiver( 945 new BroadcastReceiver() { 946 @Override 947 public void onReceive(Context context, Intent intent) { 948 String action = intent.getAction(); 949 950 if (action.equals(Intent.ACTION_SCREEN_ON)) { 951 sendMessage(CMD_SCREEN_STATE_CHANGED, 1); 952 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { 953 sendMessage(CMD_SCREEN_STATE_CHANGED, 0); 954 } 955 } 956 }, filter); 957 958 mContext.getContentResolver().registerContentObserver(Settings.Global.getUriFor( 959 Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED), false, 960 new ContentObserver(getHandler()) { 961 @Override 962 public void onChange(boolean selfChange) { 963 mUserWantsSuspendOpt.set(mFacade.getIntegerSetting(mContext, 964 Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED, 1) == 1); 965 } 966 }); 967 968 mContext.registerReceiver( 969 new BroadcastReceiver() { 970 @Override 971 public void onReceive(Context context, Intent intent) { 972 sendMessage(CMD_BOOT_COMPLETED); 973 } 974 }, 975 new IntentFilter(Intent.ACTION_LOCKED_BOOT_COMPLETED)); 976 977 PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); 978 mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getName()); 979 980 mSuspendWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WifiSuspend"); 981 mSuspendWakeLock.setReferenceCounted(false); 982 983 mTcpBufferSizes = mContext.getResources().getString( 984 com.android.internal.R.string.config_wifi_tcp_buffers); 985 986 // Load Device configs 987 mEnableAutoJoinWhenAssociated = context.getResources().getBoolean( 988 R.bool.config_wifi_framework_enable_associated_network_selection); 989 mThresholdQualifiedRssi24 = context.getResources().getInteger( 990 R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_24GHz); 991 mThresholdQualifiedRssi5 = context.getResources().getInteger( 992 R.integer.config_wifi_framework_wifi_score_low_rssi_threshold_5GHz); 993 mThresholdSaturatedRssi24 = context.getResources().getInteger( 994 R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_24GHz); 995 mThresholdSaturatedRssi5 = context.getResources().getInteger( 996 R.integer.config_wifi_framework_wifi_score_good_rssi_threshold_5GHz); 997 mThresholdMinimumRssi5 = context.getResources().getInteger( 998 R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_5GHz); 999 mThresholdMinimumRssi24 = context.getResources().getInteger( 1000 R.integer.config_wifi_framework_wifi_score_bad_rssi_threshold_24GHz); 1001 mEnableLinkDebouncing = mContext.getResources().getBoolean( 1002 R.bool.config_wifi_enable_disconnection_debounce); 1003 mEnableChipWakeUpWhenAssociated = true; 1004 mEnableRssiPollWhenAssociated = true; 1005 1006 // CHECKSTYLE:OFF IndentationCheck 1007 addState(mDefaultState); 1008 addState(mInitialState, mDefaultState); 1009 addState(mSupplicantStartingState, mDefaultState); 1010 addState(mSupplicantStartedState, mDefaultState); 1011 addState(mScanModeState, mSupplicantStartedState); 1012 addState(mConnectModeState, mSupplicantStartedState); 1013 addState(mL2ConnectedState, mConnectModeState); 1014 addState(mObtainingIpState, mL2ConnectedState); 1015 addState(mConnectedState, mL2ConnectedState); 1016 addState(mRoamingState, mL2ConnectedState); 1017 addState(mDisconnectingState, mConnectModeState); 1018 addState(mDisconnectedState, mConnectModeState); 1019 addState(mWpsRunningState, mConnectModeState); 1020 addState(mWaitForP2pDisableState, mSupplicantStartedState); 1021 addState(mSupplicantStoppingState, mDefaultState); 1022 addState(mSoftApState, mDefaultState); 1023 // CHECKSTYLE:ON IndentationCheck 1024 1025 setInitialState(mInitialState); 1026 1027 setLogRecSize(NUM_LOG_RECS_NORMAL); 1028 setLogOnlyTransitions(false); 1029 1030 //start the state machine 1031 start(); 1032 1033 // Learn the initial state of whether the screen is on. 1034 // We update this field when we receive broadcasts from the system. 1035 handleScreenStateChanged(powerManager.isInteractive()); 1036 1037 mWifiMonitor.registerHandler(mInterfaceName, CMD_TARGET_BSSID, getHandler()); 1038 mWifiMonitor.registerHandler(mInterfaceName, CMD_ASSOCIATED_BSSID, getHandler()); 1039 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.ANQP_DONE_EVENT, getHandler()); 1040 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.ASSOCIATION_REJECTION_EVENT, 1041 getHandler()); 1042 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.AUTHENTICATION_FAILURE_EVENT, 1043 getHandler()); 1044 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.DRIVER_HUNG_EVENT, getHandler()); 1045 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.GAS_QUERY_DONE_EVENT, getHandler()); 1046 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.GAS_QUERY_START_EVENT, 1047 getHandler()); 1048 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.HS20_REMEDIATION_EVENT, 1049 getHandler()); 1050 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.NETWORK_CONNECTION_EVENT, 1051 getHandler()); 1052 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.NETWORK_DISCONNECTION_EVENT, 1053 getHandler()); 1054 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.RX_HS20_ANQP_ICON_EVENT, 1055 getHandler()); 1056 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SCAN_FAILED_EVENT, getHandler()); 1057 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SCAN_RESULTS_EVENT, getHandler()); 1058 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SSID_REENABLED, getHandler()); 1059 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SSID_TEMP_DISABLED, getHandler()); 1060 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_CONNECTION_EVENT, getHandler()); 1061 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_DISCONNECTION_EVENT, 1062 getHandler()); 1063 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 1064 getHandler()); 1065 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_REQUEST_IDENTITY, getHandler()); 1066 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_REQUEST_SIM_AUTH, getHandler()); 1067 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_FAIL_EVENT, getHandler()); 1068 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_OVERLAP_EVENT, getHandler()); 1069 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_SUCCESS_EVENT, getHandler()); 1070 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_TIMEOUT_EVENT, getHandler()); 1071 1072 final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE); 1073 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1074 intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED); 1075 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 1076 } 1077 1078 class IpManagerCallback extends IpManager.Callback { 1079 @Override 1080 public void onPreDhcpAction() { 1081 sendMessage(DhcpClient.CMD_PRE_DHCP_ACTION); 1082 } 1083 1084 @Override 1085 public void onPostDhcpAction() { 1086 sendMessage(DhcpClient.CMD_POST_DHCP_ACTION); 1087 } 1088 1089 @Override 1090 public void onNewDhcpResults(DhcpResults dhcpResults) { 1091 if (dhcpResults != null) { 1092 sendMessage(CMD_IPV4_PROVISIONING_SUCCESS, dhcpResults); 1093 } else { 1094 sendMessage(CMD_IPV4_PROVISIONING_FAILURE); 1095 mWifiInjector.getWifiLastResortWatchdog().noteConnectionFailureAndTriggerIfNeeded( 1096 getTargetSsid(), mTargetRoamBSSID, 1097 WifiLastResortWatchdog.FAILURE_CODE_DHCP); 1098 } 1099 } 1100 1101 @Override 1102 public void onProvisioningSuccess(LinkProperties newLp) { 1103 sendMessage(CMD_UPDATE_LINKPROPERTIES, newLp); 1104 sendMessage(CMD_IP_CONFIGURATION_SUCCESSFUL); 1105 } 1106 1107 @Override 1108 public void onProvisioningFailure(LinkProperties newLp) { 1109 sendMessage(CMD_IP_CONFIGURATION_LOST); 1110 } 1111 1112 @Override 1113 public void onLinkPropertiesChange(LinkProperties newLp) { 1114 sendMessage(CMD_UPDATE_LINKPROPERTIES, newLp); 1115 } 1116 1117 @Override 1118 public void onReachabilityLost(String logMsg) { 1119 sendMessage(CMD_IP_REACHABILITY_LOST, logMsg); 1120 } 1121 1122 @Override 1123 public void installPacketFilter(byte[] filter) { 1124 sendMessage(CMD_INSTALL_PACKET_FILTER, filter); 1125 } 1126 1127 @Override 1128 public void setFallbackMulticastFilter(boolean enabled) { 1129 sendMessage(CMD_SET_FALLBACK_PACKET_FILTERING, enabled); 1130 } 1131 1132 @Override 1133 public void setNeighborDiscoveryOffload(boolean enabled) { 1134 sendMessage(CMD_CONFIG_ND_OFFLOAD, (enabled ? 1 : 0)); 1135 } 1136 } 1137 1138 private void stopIpManager() { 1139 /* Restore power save and suspend optimizations */ 1140 handlePostDhcpSetup(); 1141 mIpManager.stop(); 1142 } 1143 1144 PendingIntent getPrivateBroadcast(String action, int requestCode) { 1145 Intent intent = new Intent(action, null); 1146 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1147 intent.setPackage("android"); 1148 return mFacade.getBroadcast(mContext, requestCode, intent, 0); 1149 } 1150 1151 /** 1152 * Set wpa_supplicant log level using |mVerboseLoggingLevel| flag. 1153 */ 1154 void setSupplicantLogLevel() { 1155 mWifiNative.setSupplicantLogLevel(mVerboseLoggingEnabled); 1156 } 1157 1158 /** 1159 * Method to update logging level in wifi service related classes. 1160 * 1161 * @param verbose int logging level to use 1162 */ 1163 public void enableVerboseLogging(int verbose) { 1164 if (verbose > 0) { 1165 mVerboseLoggingEnabled = true; 1166 setLogRecSize(ActivityManager.isLowRamDeviceStatic() 1167 ? NUM_LOG_RECS_VERBOSE_LOW_MEMORY : NUM_LOG_RECS_VERBOSE); 1168 } else { 1169 mVerboseLoggingEnabled = false; 1170 setLogRecSize(NUM_LOG_RECS_NORMAL); 1171 } 1172 configureVerboseHalLogging(mVerboseLoggingEnabled); 1173 setSupplicantLogLevel(); 1174 mCountryCode.enableVerboseLogging(verbose); 1175 mWifiScoreReport.enableVerboseLogging(mVerboseLoggingEnabled); 1176 mWifiDiagnostics.startLogging(mVerboseLoggingEnabled); 1177 mWifiMonitor.enableVerboseLogging(verbose); 1178 mWifiNative.enableVerboseLogging(verbose); 1179 mWifiConfigManager.enableVerboseLogging(verbose); 1180 mSupplicantStateTracker.enableVerboseLogging(verbose); 1181 } 1182 1183 private static final String SYSTEM_PROPERTY_LOG_CONTROL_WIFIHAL = "log.tag.WifiHAL"; 1184 private static final String LOGD_LEVEL_DEBUG = "D"; 1185 private static final String LOGD_LEVEL_VERBOSE = "V"; 1186 private void configureVerboseHalLogging(boolean enableVerbose) { 1187 if (mBuildProperties.isUserBuild()) { // Verbose HAL logging not supported on user builds. 1188 return; 1189 } 1190 mPropertyService.set(SYSTEM_PROPERTY_LOG_CONTROL_WIFIHAL, 1191 enableVerbose ? LOGD_LEVEL_VERBOSE : LOGD_LEVEL_DEBUG); 1192 } 1193 1194 private int mAggressiveHandover = 0; 1195 1196 int getAggressiveHandover() { 1197 return mAggressiveHandover; 1198 } 1199 1200 void enableAggressiveHandover(int enabled) { 1201 mAggressiveHandover = enabled; 1202 } 1203 1204 public void clearANQPCache() { 1205 // TODO(b/31065385) 1206 // mWifiConfigManager.trimANQPCache(true); 1207 } 1208 1209 public void setAllowScansWithTraffic(int enabled) { 1210 mAlwaysEnableScansWhileAssociated = enabled; 1211 } 1212 1213 public int getAllowScansWithTraffic() { 1214 return mAlwaysEnableScansWhileAssociated; 1215 } 1216 1217 /* 1218 * Dynamically turn on/off if switching networks while connected is allowd. 1219 */ 1220 public boolean setEnableAutoJoinWhenAssociated(boolean enabled) { 1221 sendMessage(CMD_ENABLE_AUTOJOIN_WHEN_ASSOCIATED, enabled ? 1 : 0); 1222 return true; 1223 } 1224 1225 public boolean getEnableAutoJoinWhenAssociated() { 1226 return mEnableAutoJoinWhenAssociated; 1227 } 1228 1229 private boolean setRandomMacOui() { 1230 String oui = mContext.getResources().getString(R.string.config_wifi_random_mac_oui); 1231 if (TextUtils.isEmpty(oui)) { 1232 oui = GOOGLE_OUI; 1233 } 1234 String[] ouiParts = oui.split("-"); 1235 byte[] ouiBytes = new byte[3]; 1236 ouiBytes[0] = (byte) (Integer.parseInt(ouiParts[0], 16) & 0xFF); 1237 ouiBytes[1] = (byte) (Integer.parseInt(ouiParts[1], 16) & 0xFF); 1238 ouiBytes[2] = (byte) (Integer.parseInt(ouiParts[2], 16) & 0xFF); 1239 1240 logd("Setting OUI to " + oui); 1241 return mWifiNative.setScanningMacOui(ouiBytes); 1242 } 1243 1244 /** 1245 * Helper method to lookup the framework network ID of the network currently configured in 1246 * wpa_supplicant using the provided supplicant network ID. This is needed for translating the 1247 * networkID received from all {@link WifiMonitor} events. 1248 * 1249 * @param supplicantNetworkId Network ID of network in wpa_supplicant. 1250 * @return Corresponding Internal configured network ID 1251 * TODO(b/31080843): This is ugly! We need to hide this translation of networkId's. This will 1252 * be handled once we move all of this connection logic to wificond. 1253 */ 1254 private int lookupFrameworkNetworkId(int supplicantNetworkId) { 1255 return mWifiNative.getFrameworkNetworkId(supplicantNetworkId); 1256 } 1257 1258 /** 1259 * Initiates connection to a network specified by the user/app. This method checks if the 1260 * requesting app holds the WIFI_CONFIG_OVERRIDE permission. 1261 */ 1262 private boolean connectToUserSelectNetwork(int netId, int uid) { 1263 if (mWifiConfigManager.getConfiguredNetwork(netId) == null) { 1264 loge("connectToUserSelectNetwork Invalid network Id=" + netId); 1265 return false; 1266 } 1267 if (!mWifiConfigManager.enableNetwork(netId, true, uid) 1268 || !mWifiConfigManager.checkAndUpdateLastConnectUid(netId, uid)) { 1269 logi("connectToUserSelectNetwork Allowing uid " + uid 1270 + " with insufficient permissions to connect=" + netId); 1271 } else { 1272 // Note user connect choice here, so that it will be considered in the next network 1273 // selection. 1274 mWifiConnectivityManager.setUserConnectChoice(netId); 1275 } 1276 if (mWifiInfo.getNetworkId() == netId) { 1277 // We're already connected to the user specified network, don't trigger a 1278 // reconnection. 1279 logi("connectToUserSelectNetwork already connecting/connected=" + netId); 1280 } else { 1281 startConnectToNetwork(netId, SUPPLICANT_BSSID_ANY); 1282 } 1283 return true; 1284 } 1285 1286 /** 1287 * ****************************************************** 1288 * Methods exposed for public use 1289 * ****************************************************** 1290 */ 1291 1292 public Messenger getMessenger() { 1293 return new Messenger(getHandler()); 1294 } 1295 1296 /** 1297 * TODO: doc 1298 */ 1299 public boolean syncPingSupplicant(AsyncChannel channel) { 1300 Message resultMsg = channel.sendMessageSynchronously(CMD_PING_SUPPLICANT); 1301 boolean result = (resultMsg.arg1 != FAILURE); 1302 resultMsg.recycle(); 1303 return result; 1304 } 1305 1306 /** 1307 * Initiate a wifi scan. If workSource is not null, blame is given to it, otherwise blame is 1308 * given to callingUid. 1309 * 1310 * @param callingUid The uid initiating the wifi scan. Blame will be given here unless 1311 * workSource is specified. 1312 * @param workSource If not null, blame is given to workSource. 1313 * @param settings Scan settings, see {@link ScanSettings}. 1314 */ 1315 public void startScan(int callingUid, int scanCounter, 1316 ScanSettings settings, WorkSource workSource) { 1317 Bundle bundle = new Bundle(); 1318 bundle.putParcelable(CUSTOMIZED_SCAN_SETTING, settings); 1319 bundle.putParcelable(CUSTOMIZED_SCAN_WORKSOURCE, workSource); 1320 bundle.putLong(SCAN_REQUEST_TIME, mClock.getWallClockMillis()); 1321 sendMessage(CMD_START_SCAN, callingUid, scanCounter, bundle); 1322 } 1323 1324 private long mDisconnectedTimeStamp = 0; 1325 1326 public long getDisconnectedTimeMilli() { 1327 if (getCurrentState() == mDisconnectedState 1328 && mDisconnectedTimeStamp != 0) { 1329 long now_ms = mClock.getWallClockMillis(); 1330 return now_ms - mDisconnectedTimeStamp; 1331 } 1332 return 0; 1333 } 1334 1335 // Last connect attempt is used to prevent scan requests: 1336 // - for a period of 10 seconds after attempting to connect 1337 private long lastConnectAttemptTimestamp = 0; 1338 private Set<Integer> lastScanFreqs = null; 1339 1340 // For debugging, keep track of last message status handling 1341 // TODO, find an equivalent mechanism as part of parent class 1342 private static final int MESSAGE_HANDLING_STATUS_PROCESSED = 2; 1343 private static final int MESSAGE_HANDLING_STATUS_OK = 1; 1344 private static final int MESSAGE_HANDLING_STATUS_UNKNOWN = 0; 1345 private static final int MESSAGE_HANDLING_STATUS_REFUSED = -1; 1346 private static final int MESSAGE_HANDLING_STATUS_FAIL = -2; 1347 private static final int MESSAGE_HANDLING_STATUS_OBSOLETE = -3; 1348 private static final int MESSAGE_HANDLING_STATUS_DEFERRED = -4; 1349 private static final int MESSAGE_HANDLING_STATUS_DISCARD = -5; 1350 private static final int MESSAGE_HANDLING_STATUS_LOOPED = -6; 1351 private static final int MESSAGE_HANDLING_STATUS_HANDLING_ERROR = -7; 1352 1353 private int messageHandlingStatus = 0; 1354 1355 //TODO: this is used only to track connection attempts, however the link state and packet per 1356 //TODO: second logic should be folded into that 1357 private boolean checkOrDeferScanAllowed(Message msg) { 1358 long now = mClock.getWallClockMillis(); 1359 if (lastConnectAttemptTimestamp != 0 && (now - lastConnectAttemptTimestamp) < 10000) { 1360 Message dmsg = Message.obtain(msg); 1361 sendMessageDelayed(dmsg, 11000 - (now - lastConnectAttemptTimestamp)); 1362 return false; 1363 } 1364 return true; 1365 } 1366 1367 private int mOnTime = 0; 1368 private int mTxTime = 0; 1369 private int mRxTime = 0; 1370 1371 private int mOnTimeScreenStateChange = 0; 1372 private long lastOntimeReportTimeStamp = 0; 1373 private long lastScreenStateChangeTimeStamp = 0; 1374 private int mOnTimeLastReport = 0; 1375 private int mTxTimeLastReport = 0; 1376 private int mRxTimeLastReport = 0; 1377 1378 private long lastLinkLayerStatsUpdate = 0; 1379 1380 String reportOnTime() { 1381 long now = mClock.getWallClockMillis(); 1382 StringBuilder sb = new StringBuilder(); 1383 // Report stats since last report 1384 int on = mOnTime - mOnTimeLastReport; 1385 mOnTimeLastReport = mOnTime; 1386 int tx = mTxTime - mTxTimeLastReport; 1387 mTxTimeLastReport = mTxTime; 1388 int rx = mRxTime - mRxTimeLastReport; 1389 mRxTimeLastReport = mRxTime; 1390 int period = (int) (now - lastOntimeReportTimeStamp); 1391 lastOntimeReportTimeStamp = now; 1392 sb.append(String.format("[on:%d tx:%d rx:%d period:%d]", on, tx, rx, period)); 1393 // Report stats since Screen State Changed 1394 on = mOnTime - mOnTimeScreenStateChange; 1395 period = (int) (now - lastScreenStateChangeTimeStamp); 1396 sb.append(String.format(" from screen [on:%d period:%d]", on, period)); 1397 return sb.toString(); 1398 } 1399 1400 WifiLinkLayerStats getWifiLinkLayerStats() { 1401 WifiLinkLayerStats stats = null; 1402 if (mWifiLinkLayerStatsSupported > 0) { 1403 String name = "wlan0"; 1404 stats = mWifiNative.getWifiLinkLayerStats(name); 1405 if (name != null && stats == null && mWifiLinkLayerStatsSupported > 0) { 1406 mWifiLinkLayerStatsSupported -= 1; 1407 } else if (stats != null) { 1408 lastLinkLayerStatsUpdate = mClock.getWallClockMillis(); 1409 mOnTime = stats.on_time; 1410 mTxTime = stats.tx_time; 1411 mRxTime = stats.rx_time; 1412 mRunningBeaconCount = stats.beacon_rx; 1413 } 1414 } 1415 if (stats == null || mWifiLinkLayerStatsSupported <= 0) { 1416 long mTxPkts = mFacade.getTxPackets(mInterfaceName); 1417 long mRxPkts = mFacade.getRxPackets(mInterfaceName); 1418 mWifiInfo.updatePacketRates(mTxPkts, mRxPkts); 1419 } else { 1420 mWifiInfo.updatePacketRates(stats, lastLinkLayerStatsUpdate); 1421 } 1422 return stats; 1423 } 1424 1425 int startWifiIPPacketOffload(int slot, KeepalivePacketData packetData, int intervalSeconds) { 1426 int ret = mWifiNative.startSendingOffloadedPacket(slot, packetData, intervalSeconds * 1000); 1427 if (ret != 0) { 1428 loge("startWifiIPPacketOffload(" + slot + ", " + intervalSeconds + 1429 "): hardware error " + ret); 1430 return ConnectivityManager.PacketKeepalive.ERROR_HARDWARE_ERROR; 1431 } else { 1432 return ConnectivityManager.PacketKeepalive.SUCCESS; 1433 } 1434 } 1435 1436 int stopWifiIPPacketOffload(int slot) { 1437 int ret = mWifiNative.stopSendingOffloadedPacket(slot); 1438 if (ret != 0) { 1439 loge("stopWifiIPPacketOffload(" + slot + "): hardware error " + ret); 1440 return ConnectivityManager.PacketKeepalive.ERROR_HARDWARE_ERROR; 1441 } else { 1442 return ConnectivityManager.PacketKeepalive.SUCCESS; 1443 } 1444 } 1445 1446 int startRssiMonitoringOffload(byte maxRssi, byte minRssi) { 1447 return mWifiNative.startRssiMonitoring(maxRssi, minRssi, WifiStateMachine.this); 1448 } 1449 1450 int stopRssiMonitoringOffload() { 1451 return mWifiNative.stopRssiMonitoring(); 1452 } 1453 1454 private void handleScanRequest(Message message) { 1455 ScanSettings settings = null; 1456 WorkSource workSource = null; 1457 1458 // unbundle parameters 1459 Bundle bundle = (Bundle) message.obj; 1460 1461 if (bundle != null) { 1462 settings = bundle.getParcelable(CUSTOMIZED_SCAN_SETTING); 1463 workSource = bundle.getParcelable(CUSTOMIZED_SCAN_WORKSOURCE); 1464 } 1465 1466 Set<Integer> freqs = null; 1467 if (settings != null && settings.channelSet != null) { 1468 freqs = new HashSet<>(); 1469 for (WifiChannel channel : settings.channelSet) { 1470 freqs.add(channel.freqMHz); 1471 } 1472 } 1473 1474 // Retrieve the list of hidden network SSIDs to scan for. 1475 List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks = 1476 mWifiConfigManager.retrieveHiddenNetworkList(); 1477 1478 // call wifi native to start the scan 1479 if (startScanNative(freqs, hiddenNetworks, workSource)) { 1480 // a full scan covers everything, clearing scan request buffer 1481 if (freqs == null) 1482 mBufferedScanMsg.clear(); 1483 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK; 1484 return; 1485 } 1486 1487 // if reach here, scan request is rejected 1488 1489 if (!mIsScanOngoing) { 1490 // if rejection is NOT due to ongoing scan (e.g. bad scan parameters), 1491 1492 // discard this request and pop up the next one 1493 if (mBufferedScanMsg.size() > 0) { 1494 sendMessage(mBufferedScanMsg.remove()); 1495 } 1496 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 1497 } else if (!mIsFullScanOngoing) { 1498 // if rejection is due to an ongoing scan, and the ongoing one is NOT a full scan, 1499 // buffer the scan request to make sure specified channels will be scanned eventually 1500 if (freqs == null) 1501 mBufferedScanMsg.clear(); 1502 if (mBufferedScanMsg.size() < SCAN_REQUEST_BUFFER_MAX_SIZE) { 1503 Message msg = obtainMessage(CMD_START_SCAN, 1504 message.arg1, message.arg2, bundle); 1505 mBufferedScanMsg.add(msg); 1506 } else { 1507 // if too many requests in buffer, combine them into a single full scan 1508 bundle = new Bundle(); 1509 bundle.putParcelable(CUSTOMIZED_SCAN_SETTING, null); 1510 bundle.putParcelable(CUSTOMIZED_SCAN_WORKSOURCE, workSource); 1511 Message msg = obtainMessage(CMD_START_SCAN, message.arg1, message.arg2, bundle); 1512 mBufferedScanMsg.clear(); 1513 mBufferedScanMsg.add(msg); 1514 } 1515 messageHandlingStatus = MESSAGE_HANDLING_STATUS_LOOPED; 1516 } else { 1517 // mIsScanOngoing and mIsFullScanOngoing 1518 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 1519 } 1520 } 1521 1522 1523 // TODO this is a temporary measure to bridge between WifiScanner and WifiStateMachine until 1524 // scan functionality is refactored out of WifiStateMachine. 1525 /** 1526 * return true iff scan request is accepted 1527 */ 1528 private boolean startScanNative(final Set<Integer> freqs, 1529 List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworkList, 1530 WorkSource workSource) { 1531 WifiScanner.ScanSettings settings = new WifiScanner.ScanSettings(); 1532 if (freqs == null) { 1533 settings.band = WifiScanner.WIFI_BAND_BOTH_WITH_DFS; 1534 } else { 1535 settings.band = WifiScanner.WIFI_BAND_UNSPECIFIED; 1536 int index = 0; 1537 settings.channels = new WifiScanner.ChannelSpec[freqs.size()]; 1538 for (Integer freq : freqs) { 1539 settings.channels[index++] = new WifiScanner.ChannelSpec(freq); 1540 } 1541 } 1542 settings.reportEvents = WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN 1543 | WifiScanner.REPORT_EVENT_FULL_SCAN_RESULT; 1544 1545 settings.hiddenNetworks = 1546 hiddenNetworkList.toArray( 1547 new WifiScanner.ScanSettings.HiddenNetwork[hiddenNetworkList.size()]); 1548 1549 WifiScanner.ScanListener nativeScanListener = new WifiScanner.ScanListener() { 1550 // ignore all events since WifiStateMachine is registered for the supplicant events 1551 @Override 1552 public void onSuccess() { 1553 } 1554 @Override 1555 public void onFailure(int reason, String description) { 1556 mIsScanOngoing = false; 1557 mIsFullScanOngoing = false; 1558 } 1559 @Override 1560 public void onResults(WifiScanner.ScanData[] results) { 1561 } 1562 @Override 1563 public void onFullResult(ScanResult fullScanResult) { 1564 } 1565 @Override 1566 public void onPeriodChanged(int periodInMs) { 1567 } 1568 }; 1569 mWifiScanner.startScan(settings, nativeScanListener, workSource); 1570 mIsScanOngoing = true; 1571 mIsFullScanOngoing = (freqs == null); 1572 lastScanFreqs = freqs; 1573 return true; 1574 } 1575 1576 /** 1577 * TODO: doc 1578 */ 1579 public void setSupplicantRunning(boolean enable) { 1580 if (enable) { 1581 sendMessage(CMD_START_SUPPLICANT); 1582 } else { 1583 sendMessage(CMD_STOP_SUPPLICANT); 1584 } 1585 } 1586 1587 /** 1588 * TODO: doc 1589 */ 1590 public void setHostApRunning(WifiConfiguration wifiConfig, boolean enable) { 1591 if (enable) { 1592 sendMessage(CMD_START_AP, wifiConfig); 1593 } else { 1594 sendMessage(CMD_STOP_AP); 1595 } 1596 } 1597 1598 public void setWifiApConfiguration(WifiConfiguration config) { 1599 mWifiApConfigStore.setApConfiguration(config); 1600 } 1601 1602 public WifiConfiguration syncGetWifiApConfiguration() { 1603 return mWifiApConfigStore.getApConfiguration(); 1604 } 1605 1606 /** 1607 * TODO: doc 1608 */ 1609 public int syncGetWifiState() { 1610 return mWifiState.get(); 1611 } 1612 1613 /** 1614 * TODO: doc 1615 */ 1616 public String syncGetWifiStateByName() { 1617 switch (mWifiState.get()) { 1618 case WIFI_STATE_DISABLING: 1619 return "disabling"; 1620 case WIFI_STATE_DISABLED: 1621 return "disabled"; 1622 case WIFI_STATE_ENABLING: 1623 return "enabling"; 1624 case WIFI_STATE_ENABLED: 1625 return "enabled"; 1626 case WIFI_STATE_UNKNOWN: 1627 return "unknown state"; 1628 default: 1629 return "[invalid state]"; 1630 } 1631 } 1632 1633 /** 1634 * TODO: doc 1635 */ 1636 public int syncGetWifiApState() { 1637 return mWifiApState.get(); 1638 } 1639 1640 /** 1641 * TODO: doc 1642 */ 1643 public String syncGetWifiApStateByName() { 1644 switch (mWifiApState.get()) { 1645 case WIFI_AP_STATE_DISABLING: 1646 return "disabling"; 1647 case WIFI_AP_STATE_DISABLED: 1648 return "disabled"; 1649 case WIFI_AP_STATE_ENABLING: 1650 return "enabling"; 1651 case WIFI_AP_STATE_ENABLED: 1652 return "enabled"; 1653 case WIFI_AP_STATE_FAILED: 1654 return "failed"; 1655 default: 1656 return "[invalid state]"; 1657 } 1658 } 1659 1660 public boolean isConnected() { 1661 return getCurrentState() == mConnectedState; 1662 } 1663 1664 public boolean isDisconnected() { 1665 return getCurrentState() == mDisconnectedState; 1666 } 1667 1668 public boolean isSupplicantTransientState() { 1669 SupplicantState supplicantState = mWifiInfo.getSupplicantState(); 1670 if (supplicantState == SupplicantState.ASSOCIATING 1671 || supplicantState == SupplicantState.AUTHENTICATING 1672 || supplicantState == SupplicantState.FOUR_WAY_HANDSHAKE 1673 || supplicantState == SupplicantState.GROUP_HANDSHAKE) { 1674 1675 if (mVerboseLoggingEnabled) { 1676 Log.d(TAG, "Supplicant is under transient state: " + supplicantState); 1677 } 1678 return true; 1679 } else { 1680 if (mVerboseLoggingEnabled) { 1681 Log.d(TAG, "Supplicant is under steady state: " + supplicantState); 1682 } 1683 } 1684 1685 return false; 1686 } 1687 1688 public boolean isLinkDebouncing() { 1689 return mIsLinkDebouncing; 1690 } 1691 1692 /** 1693 * Get status information for the current connection, if any. 1694 * 1695 * @return a {@link WifiInfo} object containing information about the current connection 1696 */ 1697 public WifiInfo syncRequestConnectionInfo() { 1698 return getWiFiInfoForUid(Binder.getCallingUid()); 1699 } 1700 1701 public WifiInfo getWifiInfo() { 1702 return mWifiInfo; 1703 } 1704 1705 public DhcpResults syncGetDhcpResults() { 1706 synchronized (mDhcpResultsLock) { 1707 return new DhcpResults(mDhcpResults); 1708 } 1709 } 1710 1711 /** 1712 * TODO: doc 1713 */ 1714 public void setOperationalMode(int mode) { 1715 if (mVerboseLoggingEnabled) log("setting operational mode to " + String.valueOf(mode)); 1716 sendMessage(CMD_SET_OPERATIONAL_MODE, mode, 0); 1717 } 1718 1719 /** 1720 * Allow tests to confirm the operational mode for WSM. 1721 */ 1722 @VisibleForTesting 1723 protected int getOperationalModeForTest() { 1724 return mOperationalMode; 1725 } 1726 1727 /** 1728 * TODO: doc 1729 */ 1730 public List<ScanResult> syncGetScanResultsList() { 1731 synchronized (mScanResultsLock) { 1732 List<ScanResult> scanList = new ArrayList<>(); 1733 for (ScanDetail result : mScanResults) { 1734 scanList.add(new ScanResult(result.getScanResult())); 1735 } 1736 return scanList; 1737 } 1738 } 1739 1740 public boolean syncQueryPasspointIcon(AsyncChannel channel, long bssid, String fileName) { 1741 Bundle bundle = new Bundle(); 1742 bundle.putLong(EXTRA_OSU_ICON_QUERY_BSSID, bssid); 1743 bundle.putString(EXTRA_OSU_ICON_QUERY_FILENAME, fileName); 1744 Message resultMsg = channel.sendMessageSynchronously(CMD_QUERY_OSU_ICON, bundle); 1745 int result = resultMsg.arg1; 1746 resultMsg.recycle(); 1747 return result == 1; 1748 } 1749 1750 public int matchProviderWithCurrentNetwork(AsyncChannel channel, String fqdn) { 1751 Message resultMsg = channel.sendMessageSynchronously(CMD_MATCH_PROVIDER_NETWORK, fqdn); 1752 int result = resultMsg.arg1; 1753 resultMsg.recycle(); 1754 return result; 1755 } 1756 1757 /** 1758 * Deauthenticate and set the re-authentication hold off time for the current network 1759 * @param holdoff hold off time in milliseconds 1760 * @param ess set if the hold off pertains to an ESS rather than a BSS 1761 */ 1762 public void deauthenticateNetwork(AsyncChannel channel, long holdoff, boolean ess) { 1763 // TODO: This needs an implementation 1764 } 1765 1766 public void disableEphemeralNetwork(String SSID) { 1767 if (SSID != null) { 1768 sendMessage(CMD_DISABLE_EPHEMERAL_NETWORK, SSID); 1769 } 1770 } 1771 1772 /** 1773 * Disconnect from Access Point 1774 */ 1775 public void disconnectCommand() { 1776 sendMessage(CMD_DISCONNECT); 1777 } 1778 1779 public void disconnectCommand(int uid, int reason) { 1780 sendMessage(CMD_DISCONNECT, uid, reason); 1781 } 1782 1783 /** 1784 * Initiate a reconnection to AP 1785 */ 1786 public void reconnectCommand() { 1787 sendMessage(CMD_RECONNECT); 1788 } 1789 1790 /** 1791 * Initiate a re-association to AP 1792 */ 1793 public void reassociateCommand() { 1794 sendMessage(CMD_REASSOCIATE); 1795 } 1796 1797 /** 1798 * Reload networks and then reconnect; helps load correct data for TLS networks 1799 */ 1800 1801 public void reloadTlsNetworksAndReconnect() { 1802 sendMessage(CMD_RELOAD_TLS_AND_RECONNECT); 1803 } 1804 1805 /** 1806 * Add a network synchronously 1807 * 1808 * @return network id of the new network 1809 */ 1810 public int syncAddOrUpdateNetwork(AsyncChannel channel, WifiConfiguration config) { 1811 Message resultMsg = channel.sendMessageSynchronously(CMD_ADD_OR_UPDATE_NETWORK, config); 1812 int result = resultMsg.arg1; 1813 resultMsg.recycle(); 1814 return result; 1815 } 1816 1817 /** 1818 * Get configured networks synchronously 1819 * 1820 * @param channel 1821 * @return 1822 */ 1823 1824 public List<WifiConfiguration> syncGetConfiguredNetworks(int uuid, AsyncChannel channel) { 1825 Message resultMsg = channel.sendMessageSynchronously(CMD_GET_CONFIGURED_NETWORKS, uuid); 1826 List<WifiConfiguration> result = (List<WifiConfiguration>) resultMsg.obj; 1827 resultMsg.recycle(); 1828 return result; 1829 } 1830 1831 public List<WifiConfiguration> syncGetPrivilegedConfiguredNetwork(AsyncChannel channel) { 1832 Message resultMsg = channel.sendMessageSynchronously( 1833 CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS); 1834 List<WifiConfiguration> result = (List<WifiConfiguration>) resultMsg.obj; 1835 resultMsg.recycle(); 1836 return result; 1837 } 1838 1839 public WifiConfiguration syncGetMatchingWifiConfig(ScanResult scanResult, AsyncChannel channel) { 1840 Message resultMsg = channel.sendMessageSynchronously(CMD_GET_MATCHING_CONFIG, scanResult); 1841 WifiConfiguration config = (WifiConfiguration) resultMsg.obj; 1842 resultMsg.recycle(); 1843 return config; 1844 } 1845 1846 /** 1847 * Add or update a Passpoint configuration synchronously. 1848 * 1849 * @param channel Channel for communicating with the state machine 1850 * @param config The configuration to add or update 1851 * @return true on success 1852 */ 1853 public boolean syncAddOrUpdatePasspointConfig(AsyncChannel channel, 1854 PasspointConfiguration config) { 1855 Message resultMsg = channel.sendMessageSynchronously(CMD_ADD_OR_UPDATE_PASSPOINT_CONFIG, 1856 config); 1857 boolean result = (resultMsg.arg1 == SUCCESS); 1858 resultMsg.recycle(); 1859 return result; 1860 } 1861 1862 /** 1863 * Remove a Passpoint configuration synchronously. 1864 * 1865 * @param channel Channel for communicating with the state machine 1866 * @param fqdn The FQDN of the Passpoint configuration to remove 1867 * @return true on success 1868 */ 1869 public boolean syncRemovePasspointConfig(AsyncChannel channel, String fqdn) { 1870 Message resultMsg = channel.sendMessageSynchronously(CMD_REMOVE_PASSPOINT_CONFIG, 1871 fqdn); 1872 boolean result = (resultMsg.arg1 == SUCCESS); 1873 resultMsg.recycle(); 1874 return result; 1875 } 1876 1877 /** 1878 * Get the list of installed Passpoint configurations synchronously. 1879 * 1880 * @param channel Channel for communicating with the state machine 1881 * @return List of {@link PasspointConfiguration} 1882 */ 1883 public List<PasspointConfiguration> syncGetPasspointConfigs(AsyncChannel channel) { 1884 Message resultMsg = channel.sendMessageSynchronously(CMD_GET_PASSPOINT_CONFIGS); 1885 List<PasspointConfiguration> result = (List<PasspointConfiguration>) resultMsg.obj; 1886 resultMsg.recycle(); 1887 return result; 1888 } 1889 1890 /** 1891 * Get connection statistics synchronously 1892 * 1893 * @param channel 1894 * @return 1895 */ 1896 1897 public WifiConnectionStatistics syncGetConnectionStatistics(AsyncChannel channel) { 1898 Message resultMsg = channel.sendMessageSynchronously(CMD_GET_CONNECTION_STATISTICS); 1899 WifiConnectionStatistics result = (WifiConnectionStatistics) resultMsg.obj; 1900 resultMsg.recycle(); 1901 return result; 1902 } 1903 1904 /** 1905 * Get adaptors synchronously 1906 */ 1907 1908 public int syncGetSupportedFeatures(AsyncChannel channel) { 1909 Message resultMsg = channel.sendMessageSynchronously(CMD_GET_SUPPORTED_FEATURES); 1910 int supportedFeatureSet = resultMsg.arg1; 1911 resultMsg.recycle(); 1912 1913 // Mask the feature set against system properties. 1914 boolean disableRtt = mPropertyService.getBoolean("config.disable_rtt", false); 1915 if (disableRtt) { 1916 supportedFeatureSet &= 1917 ~(WifiManager.WIFI_FEATURE_D2D_RTT | WifiManager.WIFI_FEATURE_D2AP_RTT); 1918 } 1919 1920 return supportedFeatureSet; 1921 } 1922 1923 /** 1924 * Get link layers stats for adapter synchronously 1925 */ 1926 public WifiLinkLayerStats syncGetLinkLayerStats(AsyncChannel channel) { 1927 Message resultMsg = channel.sendMessageSynchronously(CMD_GET_LINK_LAYER_STATS); 1928 WifiLinkLayerStats result = (WifiLinkLayerStats) resultMsg.obj; 1929 resultMsg.recycle(); 1930 return result; 1931 } 1932 1933 /** 1934 * Delete a network 1935 * 1936 * @param networkId id of the network to be removed 1937 */ 1938 public boolean syncRemoveNetwork(AsyncChannel channel, int networkId) { 1939 Message resultMsg = channel.sendMessageSynchronously(CMD_REMOVE_NETWORK, networkId); 1940 boolean result = (resultMsg.arg1 != FAILURE); 1941 resultMsg.recycle(); 1942 return result; 1943 } 1944 1945 /** 1946 * Enable a network 1947 * 1948 * @param netId network id of the network 1949 * @param disableOthers true, if all other networks have to be disabled 1950 * @return {@code true} if the operation succeeds, {@code false} otherwise 1951 */ 1952 public boolean syncEnableNetwork(AsyncChannel channel, int netId, boolean disableOthers) { 1953 Message resultMsg = channel.sendMessageSynchronously(CMD_ENABLE_NETWORK, netId, 1954 disableOthers ? 1 : 0); 1955 boolean result = (resultMsg.arg1 != FAILURE); 1956 resultMsg.recycle(); 1957 return result; 1958 } 1959 1960 /** 1961 * Disable a network 1962 * 1963 * @param netId network id of the network 1964 * @return {@code true} if the operation succeeds, {@code false} otherwise 1965 */ 1966 public boolean syncDisableNetwork(AsyncChannel channel, int netId) { 1967 Message resultMsg = channel.sendMessageSynchronously(WifiManager.DISABLE_NETWORK, netId); 1968 boolean result = (resultMsg.arg1 != WifiManager.DISABLE_NETWORK_FAILED); 1969 resultMsg.recycle(); 1970 return result; 1971 } 1972 1973 /** 1974 * Retrieves a WPS-NFC configuration token for the specified network 1975 * 1976 * @return a hex string representation of the WPS-NFC configuration token 1977 */ 1978 public String syncGetWpsNfcConfigurationToken(int netId) { 1979 return mWifiNative.getNfcWpsConfigurationToken(netId); 1980 } 1981 1982 public void enableRssiPolling(boolean enabled) { 1983 sendMessage(CMD_ENABLE_RSSI_POLL, enabled ? 1 : 0, 0); 1984 } 1985 1986 /** 1987 * Start filtering Multicast v4 packets 1988 */ 1989 public void startFilteringMulticastPackets() { 1990 mIpManager.setMulticastFilter(true); 1991 } 1992 1993 /** 1994 * Stop filtering Multicast v4 packets 1995 */ 1996 public void stopFilteringMulticastPackets() { 1997 mIpManager.setMulticastFilter(false); 1998 } 1999 2000 /** 2001 * Set high performance mode of operation. 2002 * Enabling would set active power mode and disable suspend optimizations; 2003 * disabling would set auto power mode and enable suspend optimizations 2004 * 2005 * @param enable true if enable, false otherwise 2006 */ 2007 public void setHighPerfModeEnabled(boolean enable) { 2008 sendMessage(CMD_SET_HIGH_PERF_MODE, enable ? 1 : 0, 0); 2009 } 2010 2011 2012 /** 2013 * reset cached SIM credential data 2014 */ 2015 public synchronized void resetSimAuthNetworks(boolean simPresent) { 2016 sendMessage(CMD_RESET_SIM_NETWORKS, simPresent ? 1 : 0); 2017 } 2018 2019 /** 2020 * Get Network object of current wifi network 2021 * @return Network object of current wifi network 2022 */ 2023 public Network getCurrentNetwork() { 2024 if (mNetworkAgent != null) { 2025 return new Network(mNetworkAgent.netId); 2026 } else { 2027 return null; 2028 } 2029 } 2030 2031 /** 2032 * Enable TDLS for a specific MAC address 2033 */ 2034 public void enableTdls(String remoteMacAddress, boolean enable) { 2035 int enabler = enable ? 1 : 0; 2036 sendMessage(CMD_ENABLE_TDLS, enabler, 0, remoteMacAddress); 2037 } 2038 2039 /** 2040 * Send a message indicating bluetooth adapter connection state changed 2041 */ 2042 public void sendBluetoothAdapterStateChange(int state) { 2043 sendMessage(CMD_BLUETOOTH_ADAPTER_STATE_CHANGE, state, 0); 2044 } 2045 2046 /** 2047 * Send a message indicating a package has been uninstalled. 2048 */ 2049 public void removeAppConfigs(String packageName, int uid) { 2050 // Build partial AppInfo manually - package may not exist in database any more 2051 ApplicationInfo ai = new ApplicationInfo(); 2052 ai.packageName = packageName; 2053 ai.uid = uid; 2054 sendMessage(CMD_REMOVE_APP_CONFIGURATIONS, ai); 2055 } 2056 2057 /** 2058 * Send a message indicating a user has been removed. 2059 */ 2060 public void removeUserConfigs(int userId) { 2061 sendMessage(CMD_REMOVE_USER_CONFIGURATIONS, userId); 2062 } 2063 2064 /** 2065 * Save configuration on supplicant 2066 * 2067 * @return {@code true} if the operation succeeds, {@code false} otherwise 2068 * <p/> 2069 * TODO: deprecate this 2070 */ 2071 public boolean syncSaveConfig(AsyncChannel channel) { 2072 Message resultMsg = channel.sendMessageSynchronously(CMD_SAVE_CONFIG); 2073 boolean result = (resultMsg.arg1 != FAILURE); 2074 resultMsg.recycle(); 2075 return result; 2076 } 2077 2078 public void updateBatteryWorkSource(WorkSource newSource) { 2079 synchronized (mRunningWifiUids) { 2080 try { 2081 if (newSource != null) { 2082 mRunningWifiUids.set(newSource); 2083 } 2084 if (mIsRunning) { 2085 if (mReportedRunning) { 2086 // If the work source has changed since last time, need 2087 // to remove old work from battery stats. 2088 if (mLastRunningWifiUids.diff(mRunningWifiUids)) { 2089 mBatteryStats.noteWifiRunningChanged(mLastRunningWifiUids, 2090 mRunningWifiUids); 2091 mLastRunningWifiUids.set(mRunningWifiUids); 2092 } 2093 } else { 2094 // Now being started, report it. 2095 mBatteryStats.noteWifiRunning(mRunningWifiUids); 2096 mLastRunningWifiUids.set(mRunningWifiUids); 2097 mReportedRunning = true; 2098 } 2099 } else { 2100 if (mReportedRunning) { 2101 // Last reported we were running, time to stop. 2102 mBatteryStats.noteWifiStopped(mLastRunningWifiUids); 2103 mLastRunningWifiUids.clear(); 2104 mReportedRunning = false; 2105 } 2106 } 2107 mWakeLock.setWorkSource(newSource); 2108 } catch (RemoteException ignore) { 2109 } 2110 } 2111 } 2112 2113 public void dumpIpManager(FileDescriptor fd, PrintWriter pw, String[] args) { 2114 mIpManager.dump(fd, pw, args); 2115 } 2116 2117 @Override 2118 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2119 super.dump(fd, pw, args); 2120 mSupplicantStateTracker.dump(fd, pw, args); 2121 pw.println("mLinkProperties " + mLinkProperties); 2122 pw.println("mWifiInfo " + mWifiInfo); 2123 pw.println("mDhcpResults " + mDhcpResults); 2124 pw.println("mNetworkInfo " + mNetworkInfo); 2125 pw.println("mLastSignalLevel " + mLastSignalLevel); 2126 pw.println("mLastBssid " + mLastBssid); 2127 pw.println("mLastNetworkId " + mLastNetworkId); 2128 pw.println("mOperationalMode " + mOperationalMode); 2129 pw.println("mUserWantsSuspendOpt " + mUserWantsSuspendOpt); 2130 pw.println("mSuspendOptNeedsDisabled " + mSuspendOptNeedsDisabled); 2131 if (mCountryCode.getCountryCodeSentToDriver() != null) { 2132 pw.println("CountryCode sent to driver " + mCountryCode.getCountryCodeSentToDriver()); 2133 } else { 2134 if (mCountryCode.getCountryCode() != null) { 2135 pw.println("CountryCode: " + 2136 mCountryCode.getCountryCode() + " was not sent to driver"); 2137 } else { 2138 pw.println("CountryCode was not initialized"); 2139 } 2140 } 2141 if (mNetworkFactory != null) { 2142 mNetworkFactory.dump(fd, pw, args); 2143 } else { 2144 pw.println("mNetworkFactory is not initialized"); 2145 } 2146 2147 if (mUntrustedNetworkFactory != null) { 2148 mUntrustedNetworkFactory.dump(fd, pw, args); 2149 } else { 2150 pw.println("mUntrustedNetworkFactory is not initialized"); 2151 } 2152 pw.println("Wlan Wake Reasons:" + mWifiNative.getWlanWakeReasonCount()); 2153 pw.println(); 2154 2155 mWifiConfigManager.dump(fd, pw, args); 2156 pw.println(); 2157 mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_USER_ACTION); 2158 mWifiDiagnostics.dump(fd, pw, args); 2159 dumpIpManager(fd, pw, args); 2160 mWifiNetworkSelector.dump(fd, pw, args); 2161 } 2162 2163 public void handleUserSwitch(int userId) { 2164 sendMessage(CMD_USER_SWITCH, userId); 2165 } 2166 2167 public void handleUserUnlock(int userId) { 2168 sendMessage(CMD_USER_UNLOCK, userId); 2169 } 2170 2171 public void handleUserStop(int userId) { 2172 sendMessage(CMD_USER_STOP, userId); 2173 } 2174 2175 /** 2176 * ****************************************************** 2177 * Internal private functions 2178 * ****************************************************** 2179 */ 2180 2181 private void logStateAndMessage(Message message, State state) { 2182 messageHandlingStatus = 0; 2183 if (mVerboseLoggingEnabled) { 2184 logd(" " + state.getClass().getSimpleName() + " " + getLogRecString(message)); 2185 } 2186 } 2187 2188 /** 2189 * Return the additional string to be logged by LogRec, default 2190 * 2191 * @param msg that was processed 2192 * @return information to be logged as a String 2193 */ 2194 @Override 2195 protected String getLogRecString(Message msg) { 2196 WifiConfiguration config; 2197 Long now; 2198 String report; 2199 String key; 2200 StringBuilder sb = new StringBuilder(); 2201 if (mScreenOn) { 2202 sb.append("!"); 2203 } 2204 if (messageHandlingStatus != MESSAGE_HANDLING_STATUS_UNKNOWN) { 2205 sb.append("(").append(messageHandlingStatus).append(")"); 2206 } 2207 sb.append(smToString(msg)); 2208 if (msg.sendingUid > 0 && msg.sendingUid != Process.WIFI_UID) { 2209 sb.append(" uid=" + msg.sendingUid); 2210 } 2211 sb.append(" rt=").append(mClock.getUptimeSinceBootMillis()); 2212 sb.append("/").append(mClock.getElapsedSinceBootMillis()); 2213 switch (msg.what) { 2214 case CMD_START_SCAN: 2215 now = mClock.getWallClockMillis(); 2216 sb.append(" "); 2217 sb.append(Integer.toString(msg.arg1)); 2218 sb.append(" "); 2219 sb.append(Integer.toString(msg.arg2)); 2220 sb.append(" ic="); 2221 sb.append(Integer.toString(sScanAlarmIntentCount)); 2222 if (msg.obj != null) { 2223 Bundle bundle = (Bundle) msg.obj; 2224 Long request = bundle.getLong(SCAN_REQUEST_TIME, 0); 2225 if (request != 0) { 2226 sb.append(" proc(ms):").append(now - request); 2227 } 2228 } 2229 if (mIsScanOngoing) sb.append(" onGoing"); 2230 if (mIsFullScanOngoing) sb.append(" full"); 2231 sb.append(" rssi=").append(mWifiInfo.getRssi()); 2232 sb.append(" f=").append(mWifiInfo.getFrequency()); 2233 sb.append(" sc=").append(mWifiInfo.score); 2234 sb.append(" link=").append(mWifiInfo.getLinkSpeed()); 2235 sb.append(String.format(" tx=%.1f,", mWifiInfo.txSuccessRate)); 2236 sb.append(String.format(" %.1f,", mWifiInfo.txRetriesRate)); 2237 sb.append(String.format(" %.1f ", mWifiInfo.txBadRate)); 2238 sb.append(String.format(" rx=%.1f", mWifiInfo.rxSuccessRate)); 2239 if (lastScanFreqs != null) { 2240 sb.append(" list="); 2241 for(int freq : lastScanFreqs) { 2242 sb.append(freq).append(","); 2243 } 2244 } 2245 report = reportOnTime(); 2246 if (report != null) { 2247 sb.append(" ").append(report); 2248 } 2249 break; 2250 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 2251 sb.append(" "); 2252 sb.append(Integer.toString(msg.arg1)); 2253 sb.append(" "); 2254 sb.append(Integer.toString(msg.arg2)); 2255 StateChangeResult stateChangeResult = (StateChangeResult) msg.obj; 2256 if (stateChangeResult != null) { 2257 sb.append(stateChangeResult.toString()); 2258 } 2259 break; 2260 case WifiManager.SAVE_NETWORK: 2261 sb.append(" "); 2262 sb.append(Integer.toString(msg.arg1)); 2263 sb.append(" "); 2264 sb.append(Integer.toString(msg.arg2)); 2265 config = (WifiConfiguration) msg.obj; 2266 if (config != null) { 2267 sb.append(" ").append(config.configKey()); 2268 sb.append(" nid=").append(config.networkId); 2269 if (config.hiddenSSID) { 2270 sb.append(" hidden"); 2271 } 2272 if (config.preSharedKey != null 2273 && !config.preSharedKey.equals("*")) { 2274 sb.append(" hasPSK"); 2275 } 2276 if (config.ephemeral) { 2277 sb.append(" ephemeral"); 2278 } 2279 if (config.selfAdded) { 2280 sb.append(" selfAdded"); 2281 } 2282 sb.append(" cuid=").append(config.creatorUid); 2283 sb.append(" suid=").append(config.lastUpdateUid); 2284 } 2285 break; 2286 case WifiManager.FORGET_NETWORK: 2287 sb.append(" "); 2288 sb.append(Integer.toString(msg.arg1)); 2289 sb.append(" "); 2290 sb.append(Integer.toString(msg.arg2)); 2291 config = (WifiConfiguration) msg.obj; 2292 if (config != null) { 2293 sb.append(" ").append(config.configKey()); 2294 sb.append(" nid=").append(config.networkId); 2295 if (config.hiddenSSID) { 2296 sb.append(" hidden"); 2297 } 2298 if (config.preSharedKey != null) { 2299 sb.append(" hasPSK"); 2300 } 2301 if (config.ephemeral) { 2302 sb.append(" ephemeral"); 2303 } 2304 if (config.selfAdded) { 2305 sb.append(" selfAdded"); 2306 } 2307 sb.append(" cuid=").append(config.creatorUid); 2308 sb.append(" suid=").append(config.lastUpdateUid); 2309 WifiConfiguration.NetworkSelectionStatus netWorkSelectionStatus = 2310 config.getNetworkSelectionStatus(); 2311 sb.append(" ajst=").append( 2312 netWorkSelectionStatus.getNetworkStatusString()); 2313 } 2314 break; 2315 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 2316 sb.append(" "); 2317 sb.append(" timedOut=" + Integer.toString(msg.arg1)); 2318 sb.append(" "); 2319 sb.append(Integer.toString(msg.arg2)); 2320 String bssid = (String) msg.obj; 2321 if (bssid != null && bssid.length() > 0) { 2322 sb.append(" "); 2323 sb.append(bssid); 2324 } 2325 sb.append(" blacklist=" + Boolean.toString(didBlackListBSSID)); 2326 break; 2327 case WifiMonitor.SCAN_RESULTS_EVENT: 2328 sb.append(" "); 2329 sb.append(Integer.toString(msg.arg1)); 2330 sb.append(" "); 2331 sb.append(Integer.toString(msg.arg2)); 2332 if (mScanResults != null) { 2333 sb.append(" found="); 2334 sb.append(mScanResults.size()); 2335 } 2336 sb.append(" known=").append(mNumScanResultsKnown); 2337 sb.append(" got=").append(mNumScanResultsReturned); 2338 sb.append(String.format(" bcn=%d", mRunningBeaconCount)); 2339 sb.append(String.format(" con=%d", mConnectionReqCount)); 2340 sb.append(String.format(" untrustedcn=%d", mUntrustedReqCount)); 2341 key = mWifiConfigManager.getLastSelectedNetworkConfigKey(); 2342 if (key != null) { 2343 sb.append(" last=").append(key); 2344 } 2345 break; 2346 case WifiMonitor.SCAN_FAILED_EVENT: 2347 break; 2348 case WifiMonitor.NETWORK_CONNECTION_EVENT: 2349 sb.append(" "); 2350 sb.append(Integer.toString(msg.arg1)); 2351 sb.append(" "); 2352 sb.append(Integer.toString(msg.arg2)); 2353 sb.append(" ").append(mLastBssid); 2354 sb.append(" nid=").append(mLastNetworkId); 2355 config = getCurrentWifiConfiguration(); 2356 if (config != null) { 2357 sb.append(" ").append(config.configKey()); 2358 } 2359 key = mWifiConfigManager.getLastSelectedNetworkConfigKey(); 2360 if (key != null) { 2361 sb.append(" last=").append(key); 2362 } 2363 break; 2364 case CMD_TARGET_BSSID: 2365 case CMD_ASSOCIATED_BSSID: 2366 sb.append(" "); 2367 sb.append(Integer.toString(msg.arg1)); 2368 sb.append(" "); 2369 sb.append(Integer.toString(msg.arg2)); 2370 if (msg.obj != null) { 2371 sb.append(" BSSID=").append((String) msg.obj); 2372 } 2373 if (mTargetRoamBSSID != null) { 2374 sb.append(" Target=").append(mTargetRoamBSSID); 2375 } 2376 sb.append(" roam=").append(Boolean.toString(mAutoRoaming)); 2377 break; 2378 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 2379 if (msg.obj != null) { 2380 sb.append(" ").append((String) msg.obj); 2381 } 2382 sb.append(" nid=").append(msg.arg1); 2383 sb.append(" reason=").append(msg.arg2); 2384 if (mLastBssid != null) { 2385 sb.append(" lastbssid=").append(mLastBssid); 2386 } 2387 if (mWifiInfo.getFrequency() != -1) { 2388 sb.append(" freq=").append(mWifiInfo.getFrequency()); 2389 sb.append(" rssi=").append(mWifiInfo.getRssi()); 2390 } 2391 if (isLinkDebouncing()) { 2392 sb.append(" debounce"); 2393 } 2394 break; 2395 case WifiMonitor.SSID_TEMP_DISABLED: 2396 case WifiMonitor.SSID_REENABLED: 2397 sb.append(" nid=").append(msg.arg1); 2398 if (msg.obj != null) { 2399 sb.append(" ").append((String) msg.obj); 2400 } 2401 config = getCurrentWifiConfiguration(); 2402 if (config != null) { 2403 WifiConfiguration.NetworkSelectionStatus netWorkSelectionStatus = 2404 config.getNetworkSelectionStatus(); 2405 sb.append(" cur=").append(config.configKey()); 2406 sb.append(" ajst=").append(netWorkSelectionStatus.getNetworkStatusString()); 2407 if (config.selfAdded) { 2408 sb.append(" selfAdded"); 2409 } 2410 if (config.status != 0) { 2411 sb.append(" st=").append(config.status); 2412 sb.append(" rs=").append( 2413 netWorkSelectionStatus.getNetworkDisableReasonString()); 2414 } 2415 if (config.lastConnected != 0) { 2416 now = mClock.getWallClockMillis(); 2417 sb.append(" lastconn=").append(now - config.lastConnected).append("(ms)"); 2418 } 2419 if (mLastBssid != null) { 2420 sb.append(" lastbssid=").append(mLastBssid); 2421 } 2422 if (mWifiInfo.getFrequency() != -1) { 2423 sb.append(" freq=").append(mWifiInfo.getFrequency()); 2424 sb.append(" rssi=").append(mWifiInfo.getRssi()); 2425 sb.append(" bssid=").append(mWifiInfo.getBSSID()); 2426 } 2427 } 2428 break; 2429 case CMD_RSSI_POLL: 2430 case CMD_UNWANTED_NETWORK: 2431 case WifiManager.RSSI_PKTCNT_FETCH: 2432 sb.append(" "); 2433 sb.append(Integer.toString(msg.arg1)); 2434 sb.append(" "); 2435 sb.append(Integer.toString(msg.arg2)); 2436 if (mWifiInfo.getSSID() != null) 2437 if (mWifiInfo.getSSID() != null) 2438 sb.append(" ").append(mWifiInfo.getSSID()); 2439 if (mWifiInfo.getBSSID() != null) 2440 sb.append(" ").append(mWifiInfo.getBSSID()); 2441 sb.append(" rssi=").append(mWifiInfo.getRssi()); 2442 sb.append(" f=").append(mWifiInfo.getFrequency()); 2443 sb.append(" sc=").append(mWifiInfo.score); 2444 sb.append(" link=").append(mWifiInfo.getLinkSpeed()); 2445 sb.append(String.format(" tx=%.1f,", mWifiInfo.txSuccessRate)); 2446 sb.append(String.format(" %.1f,", mWifiInfo.txRetriesRate)); 2447 sb.append(String.format(" %.1f ", mWifiInfo.txBadRate)); 2448 sb.append(String.format(" rx=%.1f", mWifiInfo.rxSuccessRate)); 2449 sb.append(String.format(" bcn=%d", mRunningBeaconCount)); 2450 report = reportOnTime(); 2451 if (report != null) { 2452 sb.append(" ").append(report); 2453 } 2454 if (mWifiScoreReport.isLastReportValid()) { 2455 sb.append(mWifiScoreReport.getLastReport()); 2456 } 2457 break; 2458 case CMD_START_CONNECT: 2459 case WifiManager.CONNECT_NETWORK: 2460 sb.append(" "); 2461 sb.append(Integer.toString(msg.arg1)); 2462 sb.append(" "); 2463 sb.append(Integer.toString(msg.arg2)); 2464 config = mWifiConfigManager.getConfiguredNetwork(msg.arg1); 2465 if (config != null) { 2466 sb.append(" ").append(config.configKey()); 2467 if (config.visibility != null) { 2468 sb.append(" ").append(config.visibility.toString()); 2469 } 2470 } 2471 if (mTargetRoamBSSID != null) { 2472 sb.append(" ").append(mTargetRoamBSSID); 2473 } 2474 sb.append(" roam=").append(Boolean.toString(mAutoRoaming)); 2475 config = getCurrentWifiConfiguration(); 2476 if (config != null) { 2477 sb.append(config.configKey()); 2478 if (config.visibility != null) { 2479 sb.append(" ").append(config.visibility.toString()); 2480 } 2481 } 2482 break; 2483 case CMD_START_ROAM: 2484 sb.append(" "); 2485 sb.append(Integer.toString(msg.arg1)); 2486 sb.append(" "); 2487 sb.append(Integer.toString(msg.arg2)); 2488 ScanResult result = (ScanResult) msg.obj; 2489 if (result != null) { 2490 now = mClock.getWallClockMillis(); 2491 sb.append(" bssid=").append(result.BSSID); 2492 sb.append(" rssi=").append(result.level); 2493 sb.append(" freq=").append(result.frequency); 2494 if (result.seen > 0 && result.seen < now) { 2495 sb.append(" seen=").append(now - result.seen); 2496 } else { 2497 // Somehow the timestamp for this scan result is inconsistent 2498 sb.append(" !seen=").append(result.seen); 2499 } 2500 } 2501 if (mTargetRoamBSSID != null) { 2502 sb.append(" ").append(mTargetRoamBSSID); 2503 } 2504 sb.append(" roam=").append(Boolean.toString(mAutoRoaming)); 2505 sb.append(" fail count=").append(Integer.toString(mRoamFailCount)); 2506 break; 2507 case CMD_ADD_OR_UPDATE_NETWORK: 2508 sb.append(" "); 2509 sb.append(Integer.toString(msg.arg1)); 2510 sb.append(" "); 2511 sb.append(Integer.toString(msg.arg2)); 2512 if (msg.obj != null) { 2513 config = (WifiConfiguration) msg.obj; 2514 sb.append(" ").append(config.configKey()); 2515 sb.append(" prio=").append(config.priority); 2516 sb.append(" status=").append(config.status); 2517 if (config.BSSID != null) { 2518 sb.append(" ").append(config.BSSID); 2519 } 2520 WifiConfiguration curConfig = getCurrentWifiConfiguration(); 2521 if (curConfig != null) { 2522 if (curConfig.configKey().equals(config.configKey())) { 2523 sb.append(" is current"); 2524 } else { 2525 sb.append(" current=").append(curConfig.configKey()); 2526 sb.append(" prio=").append(curConfig.priority); 2527 sb.append(" status=").append(curConfig.status); 2528 } 2529 } 2530 } 2531 break; 2532 case WifiManager.DISABLE_NETWORK: 2533 case CMD_ENABLE_NETWORK: 2534 sb.append(" "); 2535 sb.append(Integer.toString(msg.arg1)); 2536 sb.append(" "); 2537 sb.append(Integer.toString(msg.arg2)); 2538 key = mWifiConfigManager.getLastSelectedNetworkConfigKey(); 2539 if (key != null) { 2540 sb.append(" last=").append(key); 2541 } 2542 config = mWifiConfigManager.getConfiguredNetwork(msg.arg1); 2543 if (config != null && (key == null || !config.configKey().equals(key))) { 2544 sb.append(" target=").append(key); 2545 } 2546 break; 2547 case CMD_GET_CONFIGURED_NETWORKS: 2548 sb.append(" "); 2549 sb.append(Integer.toString(msg.arg1)); 2550 sb.append(" "); 2551 sb.append(Integer.toString(msg.arg2)); 2552 sb.append(" num=").append(mWifiConfigManager.getConfiguredNetworks().size()); 2553 break; 2554 case DhcpClient.CMD_PRE_DHCP_ACTION: 2555 sb.append(" "); 2556 sb.append(Integer.toString(msg.arg1)); 2557 sb.append(" "); 2558 sb.append(Integer.toString(msg.arg2)); 2559 sb.append(" txpkts=").append(mWifiInfo.txSuccess); 2560 sb.append(",").append(mWifiInfo.txBad); 2561 sb.append(",").append(mWifiInfo.txRetries); 2562 break; 2563 case DhcpClient.CMD_POST_DHCP_ACTION: 2564 sb.append(" "); 2565 sb.append(Integer.toString(msg.arg1)); 2566 sb.append(" "); 2567 sb.append(Integer.toString(msg.arg2)); 2568 if (msg.arg1 == DhcpClient.DHCP_SUCCESS) { 2569 sb.append(" OK "); 2570 } else if (msg.arg1 == DhcpClient.DHCP_FAILURE) { 2571 sb.append(" FAIL "); 2572 } 2573 if (mLinkProperties != null) { 2574 sb.append(" "); 2575 sb.append(getLinkPropertiesSummary(mLinkProperties)); 2576 } 2577 break; 2578 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 2579 sb.append(" "); 2580 sb.append(Integer.toString(msg.arg1)); 2581 sb.append(" "); 2582 sb.append(Integer.toString(msg.arg2)); 2583 if (msg.obj != null) { 2584 NetworkInfo info = (NetworkInfo) msg.obj; 2585 NetworkInfo.State state = info.getState(); 2586 NetworkInfo.DetailedState detailedState = info.getDetailedState(); 2587 if (state != null) { 2588 sb.append(" st=").append(state); 2589 } 2590 if (detailedState != null) { 2591 sb.append("/").append(detailedState); 2592 } 2593 } 2594 break; 2595 case CMD_IP_CONFIGURATION_LOST: 2596 int count = -1; 2597 WifiConfiguration c = getCurrentWifiConfiguration(); 2598 if (c != null) { 2599 count = c.getNetworkSelectionStatus().getDisableReasonCounter( 2600 WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE); 2601 } 2602 sb.append(" "); 2603 sb.append(Integer.toString(msg.arg1)); 2604 sb.append(" "); 2605 sb.append(Integer.toString(msg.arg2)); 2606 sb.append(" failures: "); 2607 sb.append(Integer.toString(count)); 2608 sb.append("/"); 2609 sb.append(Integer.toString(mFacade.getIntegerSetting( 2610 mContext, Settings.Global.WIFI_MAX_DHCP_RETRY_COUNT, 0))); 2611 if (mWifiInfo.getBSSID() != null) { 2612 sb.append(" ").append(mWifiInfo.getBSSID()); 2613 } 2614 sb.append(String.format(" bcn=%d", mRunningBeaconCount)); 2615 break; 2616 case CMD_UPDATE_LINKPROPERTIES: 2617 sb.append(" "); 2618 sb.append(Integer.toString(msg.arg1)); 2619 sb.append(" "); 2620 sb.append(Integer.toString(msg.arg2)); 2621 if (mLinkProperties != null) { 2622 sb.append(" "); 2623 sb.append(getLinkPropertiesSummary(mLinkProperties)); 2624 } 2625 break; 2626 case CMD_IP_REACHABILITY_LOST: 2627 if (msg.obj != null) { 2628 sb.append(" ").append((String) msg.obj); 2629 } 2630 break; 2631 case CMD_INSTALL_PACKET_FILTER: 2632 sb.append(" len=" + ((byte[])msg.obj).length); 2633 break; 2634 case CMD_SET_FALLBACK_PACKET_FILTERING: 2635 sb.append(" enabled=" + (boolean)msg.obj); 2636 break; 2637 case CMD_ROAM_WATCHDOG_TIMER: 2638 sb.append(" "); 2639 sb.append(Integer.toString(msg.arg1)); 2640 sb.append(" "); 2641 sb.append(Integer.toString(msg.arg2)); 2642 sb.append(" cur=").append(roamWatchdogCount); 2643 break; 2644 case CMD_DISCONNECTING_WATCHDOG_TIMER: 2645 sb.append(" "); 2646 sb.append(Integer.toString(msg.arg1)); 2647 sb.append(" "); 2648 sb.append(Integer.toString(msg.arg2)); 2649 sb.append(" cur=").append(disconnectingWatchdogCount); 2650 break; 2651 case CMD_START_RSSI_MONITORING_OFFLOAD: 2652 case CMD_STOP_RSSI_MONITORING_OFFLOAD: 2653 case CMD_RSSI_THRESHOLD_BREACH: 2654 sb.append(" rssi="); 2655 sb.append(Integer.toString(msg.arg1)); 2656 sb.append(" thresholds="); 2657 sb.append(Arrays.toString(mRssiRanges)); 2658 break; 2659 case CMD_USER_SWITCH: 2660 sb.append(" userId="); 2661 sb.append(Integer.toString(msg.arg1)); 2662 break; 2663 case CMD_IPV4_PROVISIONING_SUCCESS: 2664 sb.append(" "); 2665 if (msg.arg1 == DhcpClient.DHCP_SUCCESS) { 2666 sb.append("DHCP_OK"); 2667 } else if (msg.arg1 == CMD_STATIC_IP_SUCCESS) { 2668 sb.append("STATIC_OK"); 2669 } else { 2670 sb.append(Integer.toString(msg.arg1)); 2671 } 2672 break; 2673 case CMD_IPV4_PROVISIONING_FAILURE: 2674 sb.append(" "); 2675 if (msg.arg1 == DhcpClient.DHCP_FAILURE) { 2676 sb.append("DHCP_FAIL"); 2677 } else if (msg.arg1 == CMD_STATIC_IP_FAILURE) { 2678 sb.append("STATIC_FAIL"); 2679 } else { 2680 sb.append(Integer.toString(msg.arg1)); 2681 } 2682 break; 2683 default: 2684 sb.append(" "); 2685 sb.append(Integer.toString(msg.arg1)); 2686 sb.append(" "); 2687 sb.append(Integer.toString(msg.arg2)); 2688 break; 2689 } 2690 2691 return sb.toString(); 2692 } 2693 2694 private void handleScreenStateChanged(boolean screenOn) { 2695 mScreenOn = screenOn; 2696 if (mVerboseLoggingEnabled) { 2697 logd(" handleScreenStateChanged Enter: screenOn=" + screenOn 2698 + " mUserWantsSuspendOpt=" + mUserWantsSuspendOpt 2699 + " state " + getCurrentState().getName() 2700 + " suppState:" + mSupplicantStateTracker.getSupplicantStateName()); 2701 } 2702 enableRssiPolling(screenOn); 2703 if (mUserWantsSuspendOpt.get()) { 2704 int shouldReleaseWakeLock = 0; 2705 if (screenOn) { 2706 sendMessage(CMD_SET_SUSPEND_OPT_ENABLED, 0, shouldReleaseWakeLock); 2707 } else { 2708 if (isConnected()) { 2709 // Allow 2s for suspend optimizations to be set 2710 mSuspendWakeLock.acquire(2000); 2711 shouldReleaseWakeLock = 1; 2712 } 2713 sendMessage(CMD_SET_SUSPEND_OPT_ENABLED, 1, shouldReleaseWakeLock); 2714 } 2715 } 2716 2717 getWifiLinkLayerStats(); 2718 mOnTimeScreenStateChange = mOnTime; 2719 lastScreenStateChangeTimeStamp = lastLinkLayerStatsUpdate; 2720 2721 mWifiMetrics.setScreenState(screenOn); 2722 2723 if (mWifiConnectivityManager != null) { 2724 mWifiConnectivityManager.handleScreenStateChanged(screenOn); 2725 } 2726 2727 if (mVerboseLoggingEnabled) log("handleScreenStateChanged Exit: " + screenOn); 2728 } 2729 2730 private void checkAndSetConnectivityInstance() { 2731 if (mCm == null) { 2732 mCm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 2733 } 2734 } 2735 2736 private void setSuspendOptimizationsNative(int reason, boolean enabled) { 2737 if (mVerboseLoggingEnabled) { 2738 log("setSuspendOptimizationsNative: " + reason + " " + enabled 2739 + " -want " + mUserWantsSuspendOpt.get() 2740 + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName() 2741 + " - " + Thread.currentThread().getStackTrace()[3].getMethodName() 2742 + " - " + Thread.currentThread().getStackTrace()[4].getMethodName() 2743 + " - " + Thread.currentThread().getStackTrace()[5].getMethodName()); 2744 } 2745 //mWifiNative.setSuspendOptimizations(enabled); 2746 2747 if (enabled) { 2748 mSuspendOptNeedsDisabled &= ~reason; 2749 /* None of dhcp, screen or highperf need it disabled and user wants it enabled */ 2750 if (mSuspendOptNeedsDisabled == 0 && mUserWantsSuspendOpt.get()) { 2751 if (mVerboseLoggingEnabled) { 2752 log("setSuspendOptimizationsNative do it " + reason + " " + enabled 2753 + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName() 2754 + " - " + Thread.currentThread().getStackTrace()[3].getMethodName() 2755 + " - " + Thread.currentThread().getStackTrace()[4].getMethodName() 2756 + " - " + Thread.currentThread().getStackTrace()[5].getMethodName()); 2757 } 2758 mWifiNative.setSuspendOptimizations(true); 2759 } 2760 } else { 2761 mSuspendOptNeedsDisabled |= reason; 2762 mWifiNative.setSuspendOptimizations(false); 2763 } 2764 } 2765 2766 private void setSuspendOptimizations(int reason, boolean enabled) { 2767 if (mVerboseLoggingEnabled) log("setSuspendOptimizations: " + reason + " " + enabled); 2768 if (enabled) { 2769 mSuspendOptNeedsDisabled &= ~reason; 2770 } else { 2771 mSuspendOptNeedsDisabled |= reason; 2772 } 2773 if (mVerboseLoggingEnabled) log("mSuspendOptNeedsDisabled " + mSuspendOptNeedsDisabled); 2774 } 2775 2776 private void setWifiState(int wifiState) { 2777 final int previousWifiState = mWifiState.get(); 2778 2779 try { 2780 if (wifiState == WIFI_STATE_ENABLED) { 2781 mBatteryStats.noteWifiOn(); 2782 } else if (wifiState == WIFI_STATE_DISABLED) { 2783 mBatteryStats.noteWifiOff(); 2784 } 2785 } catch (RemoteException e) { 2786 loge("Failed to note battery stats in wifi"); 2787 } 2788 2789 mWifiState.set(wifiState); 2790 2791 if (mVerboseLoggingEnabled) log("setWifiState: " + syncGetWifiStateByName()); 2792 2793 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION); 2794 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 2795 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState); 2796 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState); 2797 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 2798 } 2799 2800 private void setWifiApState(int wifiApState, int reason) { 2801 final int previousWifiApState = mWifiApState.get(); 2802 2803 try { 2804 if (wifiApState == WIFI_AP_STATE_ENABLED) { 2805 mBatteryStats.noteWifiOn(); 2806 } else if (wifiApState == WIFI_AP_STATE_DISABLED) { 2807 mBatteryStats.noteWifiOff(); 2808 } 2809 } catch (RemoteException e) { 2810 loge("Failed to note battery stats in wifi"); 2811 } 2812 2813 // Update state 2814 mWifiApState.set(wifiApState); 2815 2816 if (mVerboseLoggingEnabled) log("setWifiApState: " + syncGetWifiApStateByName()); 2817 2818 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION); 2819 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 2820 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiApState); 2821 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState); 2822 if (wifiApState == WifiManager.WIFI_AP_STATE_FAILED) { 2823 //only set reason number when softAP start failed 2824 intent.putExtra(WifiManager.EXTRA_WIFI_AP_FAILURE_REASON, reason); 2825 } 2826 2827 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 2828 } 2829 2830 private void setScanResults() { 2831 mNumScanResultsKnown = 0; 2832 mNumScanResultsReturned = 0; 2833 2834 ArrayList<ScanDetail> scanResults = mWifiNative.getScanResults(); 2835 2836 if (scanResults.isEmpty()) { 2837 mScanResults = new ArrayList<>(); 2838 return; 2839 } 2840 2841 // TODO(b/31065385): mWifiConfigManager.trimANQPCache(false); 2842 2843 boolean connected = mLastBssid != null; 2844 long activeBssid = 0L; 2845 if (connected) { 2846 try { 2847 activeBssid = Utils.parseMac(mLastBssid); 2848 } catch (IllegalArgumentException iae) { 2849 connected = false; 2850 } 2851 } 2852 2853 synchronized (mScanResultsLock) { 2854 mScanResults = scanResults; 2855 mNumScanResultsReturned = mScanResults.size(); 2856 } 2857 2858 if (isLinkDebouncing()) { 2859 // If debouncing, we dont re-select a SSID or BSSID hence 2860 // there is no need to call the network selection code 2861 // in WifiAutoJoinController, instead, 2862 // just try to reconnect to the same SSID by triggering a roam 2863 // The third parameter 1 means roam not from network selection but debouncing 2864 sendMessage(CMD_START_ROAM, mLastNetworkId, 1, null); 2865 } 2866 } 2867 2868 /* 2869 * Fetch RSSI, linkspeed, and frequency on current connection 2870 */ 2871 private void fetchRssiLinkSpeedAndFrequencyNative() { 2872 Integer newRssi = null; 2873 Integer newLinkSpeed = null; 2874 Integer newFrequency = null; 2875 WifiNative.SignalPollResult pollResult = mWifiNative.signalPoll(); 2876 if (pollResult == null) { 2877 return; 2878 } 2879 2880 newRssi = pollResult.currentRssi; 2881 newLinkSpeed = pollResult.txBitrate; 2882 newFrequency = pollResult.associationFrequency; 2883 2884 if (mVerboseLoggingEnabled) { 2885 logd("fetchRssiLinkSpeedAndFrequencyNative rssi=" + newRssi + 2886 " linkspeed=" + newLinkSpeed + " freq=" + newFrequency); 2887 } 2888 2889 if (newRssi != null && newRssi > WifiInfo.INVALID_RSSI && newRssi < WifiInfo.MAX_RSSI) { 2890 // screen out invalid values 2891 /* some implementations avoid negative values by adding 256 2892 * so we need to adjust for that here. 2893 */ 2894 if (newRssi > 0) newRssi -= 256; 2895 mWifiInfo.setRssi(newRssi); 2896 /* 2897 * Log the rssi poll value in metrics 2898 */ 2899 mWifiMetrics.incrementRssiPollRssiCount(newRssi); 2900 /* 2901 * Rather then sending the raw RSSI out every time it 2902 * changes, we precalculate the signal level that would 2903 * be displayed in the status bar, and only send the 2904 * broadcast if that much more coarse-grained number 2905 * changes. This cuts down greatly on the number of 2906 * broadcasts, at the cost of not informing others 2907 * interested in RSSI of all the changes in signal 2908 * level. 2909 */ 2910 int newSignalLevel = WifiManager.calculateSignalLevel(newRssi, WifiManager.RSSI_LEVELS); 2911 if (newSignalLevel != mLastSignalLevel) { 2912 updateCapabilities(getCurrentWifiConfiguration()); 2913 sendRssiChangeBroadcast(newRssi); 2914 } 2915 mLastSignalLevel = newSignalLevel; 2916 } else { 2917 mWifiInfo.setRssi(WifiInfo.INVALID_RSSI); 2918 updateCapabilities(getCurrentWifiConfiguration()); 2919 } 2920 2921 if (newLinkSpeed != null) { 2922 mWifiInfo.setLinkSpeed(newLinkSpeed); 2923 } 2924 if (newFrequency != null && newFrequency > 0) { 2925 if (ScanResult.is5GHz(newFrequency)) { 2926 mWifiConnectionStatistics.num5GhzConnected++; 2927 } 2928 if (ScanResult.is24GHz(newFrequency)) { 2929 mWifiConnectionStatistics.num24GhzConnected++; 2930 } 2931 mWifiInfo.setFrequency(newFrequency); 2932 } 2933 mWifiConfigManager.updateScanDetailCacheFromWifiInfo(mWifiInfo); 2934 } 2935 2936 // Polling has completed, hence we wont have a score anymore 2937 private void cleanWifiScore() { 2938 mWifiInfo.txBadRate = 0; 2939 mWifiInfo.txSuccessRate = 0; 2940 mWifiInfo.txRetriesRate = 0; 2941 mWifiInfo.rxSuccessRate = 0; 2942 mWifiScoreReport.reset(); 2943 } 2944 2945 private void updateLinkProperties(LinkProperties newLp) { 2946 if (mVerboseLoggingEnabled) { 2947 log("Link configuration changed for netId: " + mLastNetworkId 2948 + " old: " + mLinkProperties + " new: " + newLp); 2949 } 2950 // We own this instance of LinkProperties because IpManager passes us a copy. 2951 mLinkProperties = newLp; 2952 if (mNetworkAgent != null) { 2953 mNetworkAgent.sendLinkProperties(mLinkProperties); 2954 } 2955 2956 if (getNetworkDetailedState() == DetailedState.CONNECTED) { 2957 // If anything has changed and we're already connected, send out a notification. 2958 // TODO: Update all callers to use NetworkCallbacks and delete this. 2959 sendLinkConfigurationChangedBroadcast(); 2960 } 2961 2962 if (mVerboseLoggingEnabled) { 2963 StringBuilder sb = new StringBuilder(); 2964 sb.append("updateLinkProperties nid: " + mLastNetworkId); 2965 sb.append(" state: " + getNetworkDetailedState()); 2966 2967 if (mLinkProperties != null) { 2968 sb.append(" "); 2969 sb.append(getLinkPropertiesSummary(mLinkProperties)); 2970 } 2971 logd(sb.toString()); 2972 } 2973 } 2974 2975 /** 2976 * Clears all our link properties. 2977 */ 2978 private void clearLinkProperties() { 2979 // Clear the link properties obtained from DHCP. The only caller of this 2980 // function has already called IpManager#stop(), which clears its state. 2981 synchronized (mDhcpResultsLock) { 2982 if (mDhcpResults != null) { 2983 mDhcpResults.clear(); 2984 } 2985 } 2986 2987 // Now clear the merged link properties. 2988 mLinkProperties.clear(); 2989 if (mNetworkAgent != null) mNetworkAgent.sendLinkProperties(mLinkProperties); 2990 } 2991 2992 /** 2993 * try to update default route MAC address. 2994 */ 2995 private String updateDefaultRouteMacAddress(int timeout) { 2996 String address = null; 2997 for (RouteInfo route : mLinkProperties.getRoutes()) { 2998 if (route.isDefaultRoute() && route.hasGateway()) { 2999 InetAddress gateway = route.getGateway(); 3000 if (gateway instanceof Inet4Address) { 3001 if (mVerboseLoggingEnabled) { 3002 logd("updateDefaultRouteMacAddress found Ipv4 default :" 3003 + gateway.getHostAddress()); 3004 } 3005 address = macAddressFromRoute(gateway.getHostAddress()); 3006 /* The gateway's MAC address is known */ 3007 if ((address == null) && (timeout > 0)) { 3008 boolean reachable = false; 3009 TrafficStats.setThreadStatsTag(TrafficStats.TAG_SYSTEM_PROBE); 3010 try { 3011 reachable = gateway.isReachable(timeout); 3012 } catch (Exception e) { 3013 loge("updateDefaultRouteMacAddress exception reaching :" 3014 + gateway.getHostAddress()); 3015 3016 } finally { 3017 TrafficStats.clearThreadStatsTag(); 3018 if (reachable == true) { 3019 3020 address = macAddressFromRoute(gateway.getHostAddress()); 3021 if (mVerboseLoggingEnabled) { 3022 logd("updateDefaultRouteMacAddress reachable (tried again) :" 3023 + gateway.getHostAddress() + " found " + address); 3024 } 3025 } 3026 } 3027 } 3028 if (address != null) { 3029 mWifiConfigManager.setNetworkDefaultGwMacAddress(mLastNetworkId, address); 3030 } 3031 } 3032 } 3033 } 3034 return address; 3035 } 3036 3037 private void sendRssiChangeBroadcast(final int newRssi) { 3038 try { 3039 mBatteryStats.noteWifiRssiChanged(newRssi); 3040 } catch (RemoteException e) { 3041 // Won't happen. 3042 } 3043 Intent intent = new Intent(WifiManager.RSSI_CHANGED_ACTION); 3044 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3045 intent.putExtra(WifiManager.EXTRA_NEW_RSSI, newRssi); 3046 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 3047 } 3048 3049 private void sendNetworkStateChangeBroadcast(String bssid) { 3050 Intent intent = new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION); 3051 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3052 intent.putExtra(WifiManager.EXTRA_NETWORK_INFO, new NetworkInfo(mNetworkInfo)); 3053 intent.putExtra(WifiManager.EXTRA_LINK_PROPERTIES, new LinkProperties(mLinkProperties)); 3054 if (bssid != null) 3055 intent.putExtra(WifiManager.EXTRA_BSSID, bssid); 3056 if (mNetworkInfo.getDetailedState() == DetailedState.VERIFYING_POOR_LINK || 3057 mNetworkInfo.getDetailedState() == DetailedState.CONNECTED) { 3058 // We no longer report MAC address to third-parties and our code does 3059 // not rely on this broadcast, so just send the default MAC address. 3060 fetchRssiLinkSpeedAndFrequencyNative(); 3061 WifiInfo sentWifiInfo = new WifiInfo(mWifiInfo); 3062 sentWifiInfo.setMacAddress(WifiInfo.DEFAULT_MAC_ADDRESS); 3063 intent.putExtra(WifiManager.EXTRA_WIFI_INFO, sentWifiInfo); 3064 } 3065 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 3066 } 3067 3068 private WifiInfo getWiFiInfoForUid(int uid) { 3069 if (Binder.getCallingUid() == Process.myUid()) { 3070 return mWifiInfo; 3071 } 3072 3073 WifiInfo result = new WifiInfo(mWifiInfo); 3074 result.setMacAddress(WifiInfo.DEFAULT_MAC_ADDRESS); 3075 3076 IBinder binder = mFacade.getService("package"); 3077 IPackageManager packageManager = IPackageManager.Stub.asInterface(binder); 3078 3079 try { 3080 if (packageManager.checkUidPermission(Manifest.permission.LOCAL_MAC_ADDRESS, 3081 uid) == PackageManager.PERMISSION_GRANTED) { 3082 result.setMacAddress(mWifiInfo.getMacAddress()); 3083 } 3084 } catch (RemoteException e) { 3085 Log.e(TAG, "Error checking receiver permission", e); 3086 } 3087 3088 return result; 3089 } 3090 3091 private void sendLinkConfigurationChangedBroadcast() { 3092 Intent intent = new Intent(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION); 3093 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3094 intent.putExtra(WifiManager.EXTRA_LINK_PROPERTIES, new LinkProperties(mLinkProperties)); 3095 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 3096 } 3097 3098 private void sendSupplicantConnectionChangedBroadcast(boolean connected) { 3099 Intent intent = new Intent(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION); 3100 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3101 intent.putExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, connected); 3102 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 3103 } 3104 3105 /** 3106 * Record the detailed state of a network. 3107 * 3108 * @param state the new {@code DetailedState} 3109 */ 3110 private boolean setNetworkDetailedState(NetworkInfo.DetailedState state) { 3111 boolean hidden = false; 3112 3113 if (isLinkDebouncing() || isRoaming()) { 3114 // There is generally a confusion in the system about colluding 3115 // WiFi Layer 2 state (as reported by supplicant) and the Network state 3116 // which leads to multiple confusion. 3117 // 3118 // If link is de-bouncing or roaming, we already have an IP address 3119 // as well we were connected and are doing L2 cycles of 3120 // reconnecting or renewing IP address to check that we still have it 3121 // This L2 link flapping should ne be reflected into the Network state 3122 // which is the state of the WiFi Network visible to Layer 3 and applications 3123 // Note that once debouncing and roaming are completed, we will 3124 // set the Network state to where it should be, or leave it as unchanged 3125 // 3126 hidden = true; 3127 } 3128 if (mVerboseLoggingEnabled) { 3129 log("setDetailed state, old =" 3130 + mNetworkInfo.getDetailedState() + " and new state=" + state 3131 + " hidden=" + hidden); 3132 } 3133 if (mNetworkInfo.getExtraInfo() != null && mWifiInfo.getSSID() != null 3134 && !mWifiInfo.getSSID().equals(WifiSsid.NONE)) { 3135 // Always indicate that SSID has changed 3136 if (!mNetworkInfo.getExtraInfo().equals(mWifiInfo.getSSID())) { 3137 if (mVerboseLoggingEnabled) { 3138 log("setDetailed state send new extra info" + mWifiInfo.getSSID()); 3139 } 3140 mNetworkInfo.setExtraInfo(mWifiInfo.getSSID()); 3141 sendNetworkStateChangeBroadcast(null); 3142 } 3143 } 3144 if (hidden == true) { 3145 return false; 3146 } 3147 3148 if (state != mNetworkInfo.getDetailedState()) { 3149 mNetworkInfo.setDetailedState(state, null, mWifiInfo.getSSID()); 3150 if (mNetworkAgent != null) { 3151 mNetworkAgent.sendNetworkInfo(mNetworkInfo); 3152 } 3153 sendNetworkStateChangeBroadcast(null); 3154 return true; 3155 } 3156 return false; 3157 } 3158 3159 private DetailedState getNetworkDetailedState() { 3160 return mNetworkInfo.getDetailedState(); 3161 } 3162 3163 private SupplicantState handleSupplicantStateChange(Message message) { 3164 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 3165 SupplicantState state = stateChangeResult.state; 3166 // Supplicant state change 3167 // [31-13] Reserved for future use 3168 // [8 - 0] Supplicant state (as defined in SupplicantState.java) 3169 // 50023 supplicant_state_changed (custom|1|5) 3170 mWifiInfo.setSupplicantState(state); 3171 // If we receive a supplicant state change with an empty SSID, 3172 // this implies that wpa_supplicant is already disconnected. 3173 // We should pretend we are still connected when linkDebouncing is on. 3174 if ((stateChangeResult.wifiSsid == null 3175 || stateChangeResult.wifiSsid.toString().isEmpty()) && isLinkDebouncing()) { 3176 return state; 3177 } 3178 // Network id is only valid when we start connecting 3179 if (SupplicantState.isConnecting(state)) { 3180 mWifiInfo.setNetworkId(lookupFrameworkNetworkId(stateChangeResult.networkId)); 3181 } else { 3182 mWifiInfo.setNetworkId(WifiConfiguration.INVALID_NETWORK_ID); 3183 } 3184 3185 mWifiInfo.setBSSID(stateChangeResult.BSSID); 3186 3187 mWifiInfo.setSSID(stateChangeResult.wifiSsid); 3188 WifiConfiguration config = getCurrentWifiConfiguration(); 3189 if (config != null) { 3190 // Set meteredHint to true if the access network type of the connecting/connected AP 3191 // is a chargeable public network. 3192 ScanDetailCache scanDetailCache = mWifiConfigManager.getScanDetailCacheForNetwork( 3193 config.networkId); 3194 if (scanDetailCache != null) { 3195 ScanDetail scanDetail = scanDetailCache.getScanDetail(stateChangeResult.BSSID); 3196 if (scanDetail != null) { 3197 NetworkDetail networkDetail = scanDetail.getNetworkDetail(); 3198 if (networkDetail != null 3199 && networkDetail.getAnt() == NetworkDetail.Ant.ChargeablePublic) { 3200 mWifiInfo.setMeteredHint(true); 3201 } 3202 } 3203 } 3204 3205 mWifiInfo.setEphemeral(config.ephemeral); 3206 if (!mWifiInfo.getMeteredHint()) { // don't override the value if already set. 3207 mWifiInfo.setMeteredHint(config.meteredHint); 3208 } 3209 } 3210 3211 mSupplicantStateTracker.sendMessage(Message.obtain(message)); 3212 3213 return state; 3214 } 3215 3216 /** 3217 * Resets the Wi-Fi Connections by clearing any state, resetting any sockets 3218 * using the interface, stopping DHCP & disabling interface 3219 */ 3220 private void handleNetworkDisconnect() { 3221 if (mVerboseLoggingEnabled) { 3222 log("handleNetworkDisconnect: Stopping DHCP and clearing IP" 3223 + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName() 3224 + " - " + Thread.currentThread().getStackTrace()[3].getMethodName() 3225 + " - " + Thread.currentThread().getStackTrace()[4].getMethodName() 3226 + " - " + Thread.currentThread().getStackTrace()[5].getMethodName()); 3227 } 3228 3229 stopRssiMonitoringOffload(); 3230 3231 clearTargetBssid("handleNetworkDisconnect"); 3232 3233 stopIpManager(); 3234 3235 /* Reset data structures */ 3236 mWifiScoreReport.reset(); 3237 mWifiInfo.reset(); 3238 mIsLinkDebouncing = false; 3239 /* Reset roaming parameters */ 3240 mAutoRoaming = false; 3241 3242 setNetworkDetailedState(DetailedState.DISCONNECTED); 3243 if (mNetworkAgent != null) { 3244 mNetworkAgent.sendNetworkInfo(mNetworkInfo); 3245 mNetworkAgent = null; 3246 } 3247 3248 /* Clear network properties */ 3249 clearLinkProperties(); 3250 3251 /* Cend event to CM & network change broadcast */ 3252 sendNetworkStateChangeBroadcast(mLastBssid); 3253 3254 mLastBssid = null; 3255 registerDisconnected(); 3256 mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 3257 } 3258 3259 private void handleSupplicantConnectionLoss(boolean killSupplicant) { 3260 /* Socket connection can be lost when we do a graceful shutdown 3261 * or when the driver is hung. Ensure supplicant is stopped here. 3262 */ 3263 if (killSupplicant) { 3264 mWifiMonitor.stopAllMonitoring(); 3265 if (!mWifiNative.disableSupplicant()) { 3266 loge("Failed to disable supplicant after connection loss"); 3267 } 3268 } 3269 mWifiNative.closeSupplicantConnection(); 3270 sendSupplicantConnectionChangedBroadcast(false); 3271 setWifiState(WIFI_STATE_DISABLED); 3272 } 3273 3274 void handlePreDhcpSetup() { 3275 if (!mBluetoothConnectionActive) { 3276 /* 3277 * There are problems setting the Wi-Fi driver's power 3278 * mode to active when bluetooth coexistence mode is 3279 * enabled or sense. 3280 * <p> 3281 * We set Wi-Fi to active mode when 3282 * obtaining an IP address because we've found 3283 * compatibility issues with some routers with low power 3284 * mode. 3285 * <p> 3286 * In order for this active power mode to properly be set, 3287 * we disable coexistence mode until we're done with 3288 * obtaining an IP address. One exception is if we 3289 * are currently connected to a headset, since disabling 3290 * coexistence would interrupt that connection. 3291 */ 3292 // Disable the coexistence mode 3293 mWifiNative.setBluetoothCoexistenceMode( 3294 WifiNative.BLUETOOTH_COEXISTENCE_MODE_DISABLED); 3295 } 3296 3297 // Disable power save and suspend optimizations during DHCP 3298 // Note: The order here is important for now. Brcm driver changes 3299 // power settings when we control suspend mode optimizations. 3300 // TODO: Remove this comment when the driver is fixed. 3301 setSuspendOptimizationsNative(SUSPEND_DUE_TO_DHCP, false); 3302 mWifiNative.setPowerSave(false); 3303 3304 // Update link layer stats 3305 getWifiLinkLayerStats(); 3306 3307 if (mWifiP2pChannel != null) { 3308 /* P2p discovery breaks dhcp, shut it down in order to get through this */ 3309 Message msg = new Message(); 3310 msg.what = WifiP2pServiceImpl.BLOCK_DISCOVERY; 3311 msg.arg1 = WifiP2pServiceImpl.ENABLED; 3312 msg.arg2 = DhcpClient.CMD_PRE_DHCP_ACTION_COMPLETE; 3313 msg.obj = WifiStateMachine.this; 3314 mWifiP2pChannel.sendMessage(msg); 3315 } else { 3316 // If the p2p service is not running, we can proceed directly. 3317 sendMessage(DhcpClient.CMD_PRE_DHCP_ACTION_COMPLETE); 3318 } 3319 } 3320 3321 void handlePostDhcpSetup() { 3322 /* Restore power save and suspend optimizations */ 3323 setSuspendOptimizationsNative(SUSPEND_DUE_TO_DHCP, true); 3324 mWifiNative.setPowerSave(true); 3325 3326 p2pSendMessage(WifiP2pServiceImpl.BLOCK_DISCOVERY, WifiP2pServiceImpl.DISABLED); 3327 3328 // Set the coexistence mode back to its default value 3329 mWifiNative.setBluetoothCoexistenceMode( 3330 WifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE); 3331 } 3332 3333 private static final long DIAGS_CONNECT_TIMEOUT_MILLIS = 60 * 1000; 3334 private long mDiagsConnectionStartMillis = -1; 3335 /** 3336 * Inform other components that a new connection attempt is starting. 3337 */ 3338 private void reportConnectionAttemptStart( 3339 WifiConfiguration config, String targetBSSID, int roamType) { 3340 mWifiMetrics.startConnectionEvent(config, targetBSSID, roamType); 3341 mDiagsConnectionStartMillis = mClock.getElapsedSinceBootMillis(); 3342 mWifiDiagnostics.reportConnectionEvent( 3343 mDiagsConnectionStartMillis, WifiDiagnostics.CONNECTION_EVENT_STARTED); 3344 // TODO(b/35329124): Remove CMD_DIAGS_CONNECT_TIMEOUT, once WifiStateMachine 3345 // grows a proper CONNECTING state. 3346 sendMessageDelayed(CMD_DIAGS_CONNECT_TIMEOUT, 3347 mDiagsConnectionStartMillis, DIAGS_CONNECT_TIMEOUT_MILLIS); 3348 } 3349 3350 /** 3351 * Inform other components (WifiMetrics, WifiDiagnostics, etc.) that the current connection attempt 3352 * has concluded. 3353 */ 3354 private void reportConnectionAttemptEnd(int level2FailureCode, int connectivityFailureCode) { 3355 mWifiMetrics.endConnectionEvent(level2FailureCode, connectivityFailureCode); 3356 switch (level2FailureCode) { 3357 case WifiMetrics.ConnectionEvent.FAILURE_NONE: 3358 // Ideally, we'd wait until IP reachability has been confirmed. this code falls 3359 // short in two ways: 3360 // - at the time of the CMD_IP_CONFIGURATION_SUCCESSFUL event, we don't know if we 3361 // actually have ARP reachability. it might be better to wait until the wifi 3362 // network has been validated by IpManager. 3363 // - in the case of a roaming event (intra-SSID), we probably trigger when L2 is 3364 // complete. 3365 // 3366 // TODO(b/34181219): Fix the above. 3367 mWifiDiagnostics.reportConnectionEvent( 3368 mDiagsConnectionStartMillis, WifiDiagnostics.CONNECTION_EVENT_SUCCEEDED); 3369 break; 3370 case WifiMetrics.ConnectionEvent.FAILURE_REDUNDANT_CONNECTION_ATTEMPT: 3371 case WifiMetrics.ConnectionEvent.FAILURE_CONNECT_NETWORK_FAILED: 3372 // WifiDiagnostics doesn't care about pre-empted connections, or cases 3373 // where we failed to initiate a connection attempt with supplicant. 3374 break; 3375 default: 3376 mWifiDiagnostics.reportConnectionEvent( 3377 mDiagsConnectionStartMillis, WifiDiagnostics.CONNECTION_EVENT_FAILED); 3378 } 3379 mDiagsConnectionStartMillis = -1; 3380 } 3381 3382 private void handleIPv4Success(DhcpResults dhcpResults) { 3383 if (mVerboseLoggingEnabled) { 3384 logd("handleIPv4Success <" + dhcpResults.toString() + ">"); 3385 logd("link address " + dhcpResults.ipAddress); 3386 } 3387 3388 Inet4Address addr; 3389 synchronized (mDhcpResultsLock) { 3390 mDhcpResults = dhcpResults; 3391 addr = (Inet4Address) dhcpResults.ipAddress.getAddress(); 3392 } 3393 3394 if (isRoaming()) { 3395 int previousAddress = mWifiInfo.getIpAddress(); 3396 int newAddress = NetworkUtils.inetAddressToInt(addr); 3397 if (previousAddress != newAddress) { 3398 logd("handleIPv4Success, roaming and address changed" + 3399 mWifiInfo + " got: " + addr); 3400 } 3401 } 3402 mWifiInfo.setInetAddress(addr); 3403 if (!mWifiInfo.getMeteredHint()) { // don't override the value if already set. 3404 mWifiInfo.setMeteredHint(dhcpResults.hasMeteredHint()); 3405 updateCapabilities(getCurrentWifiConfiguration()); 3406 } 3407 } 3408 3409 private void handleSuccessfulIpConfiguration() { 3410 mLastSignalLevel = -1; // Force update of signal strength 3411 WifiConfiguration c = getCurrentWifiConfiguration(); 3412 if (c != null) { 3413 // Reset IP failure tracking 3414 c.getNetworkSelectionStatus().clearDisableReasonCounter( 3415 WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE); 3416 3417 // Tell the framework whether the newly connected network is trusted or untrusted. 3418 updateCapabilities(c); 3419 } 3420 if (c != null) { 3421 ScanResult result = getCurrentScanResult(); 3422 if (result == null) { 3423 logd("WifiStateMachine: handleSuccessfulIpConfiguration and no scan results" + 3424 c.configKey()); 3425 } else { 3426 // Clear the per BSSID failure count 3427 result.numIpConfigFailures = 0; 3428 } 3429 } 3430 } 3431 3432 private void handleIPv4Failure() { 3433 // TODO: Move this to provisioning failure, not DHCP failure. 3434 // DHCPv4 failure is expected on an IPv6-only network. 3435 mWifiDiagnostics.captureBugReportData(WifiDiagnostics.REPORT_REASON_DHCP_FAILURE); 3436 if (mVerboseLoggingEnabled) { 3437 int count = -1; 3438 WifiConfiguration config = getCurrentWifiConfiguration(); 3439 if (config != null) { 3440 count = config.getNetworkSelectionStatus().getDisableReasonCounter( 3441 WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE); 3442 } 3443 log("DHCP failure count=" + count); 3444 } 3445 reportConnectionAttemptEnd( 3446 WifiMetrics.ConnectionEvent.FAILURE_DHCP, 3447 WifiMetricsProto.ConnectionEvent.HLF_DHCP); 3448 synchronized(mDhcpResultsLock) { 3449 if (mDhcpResults != null) { 3450 mDhcpResults.clear(); 3451 } 3452 } 3453 if (mVerboseLoggingEnabled) { 3454 logd("handleIPv4Failure"); 3455 } 3456 } 3457 3458 private void handleIpConfigurationLost() { 3459 mWifiInfo.setInetAddress(null); 3460 mWifiInfo.setMeteredHint(false); 3461 3462 mWifiConfigManager.updateNetworkSelectionStatus(mLastNetworkId, 3463 WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE); 3464 3465 /* DHCP times out after about 30 seconds, we do a 3466 * disconnect thru supplicant, we will let autojoin retry connecting to the network 3467 */ 3468 mWifiNative.disconnect(); 3469 } 3470 3471 // TODO: De-duplicated this and handleIpConfigurationLost(). 3472 private void handleIpReachabilityLost() { 3473 mWifiInfo.setInetAddress(null); 3474 mWifiInfo.setMeteredHint(false); 3475 3476 // TODO: Determine whether to call some form of mWifiConfigManager.handleSSIDStateChange(). 3477 3478 // Disconnect via supplicant, and let autojoin retry connecting to the network. 3479 mWifiNative.disconnect(); 3480 } 3481 3482 /* 3483 * Read a MAC address in /proc/arp/table, used by WifistateMachine 3484 * so as to record MAC address of default gateway. 3485 **/ 3486 private String macAddressFromRoute(String ipAddress) { 3487 String macAddress = null; 3488 BufferedReader reader = null; 3489 try { 3490 reader = new BufferedReader(new FileReader("/proc/net/arp")); 3491 3492 // Skip over the line bearing colum titles 3493 String line = reader.readLine(); 3494 3495 while ((line = reader.readLine()) != null) { 3496 String[] tokens = line.split("[ ]+"); 3497 if (tokens.length < 6) { 3498 continue; 3499 } 3500 3501 // ARP column format is 3502 // Address HWType HWAddress Flags Mask IFace 3503 String ip = tokens[0]; 3504 String mac = tokens[3]; 3505 3506 if (ipAddress.equals(ip)) { 3507 macAddress = mac; 3508 break; 3509 } 3510 } 3511 3512 if (macAddress == null) { 3513 loge("Did not find remoteAddress {" + ipAddress + "} in " + 3514 "/proc/net/arp"); 3515 } 3516 3517 } catch (FileNotFoundException e) { 3518 loge("Could not open /proc/net/arp to lookup mac address"); 3519 } catch (IOException e) { 3520 loge("Could not read /proc/net/arp to lookup mac address"); 3521 } finally { 3522 try { 3523 if (reader != null) { 3524 reader.close(); 3525 } 3526 } catch (IOException e) { 3527 // Do nothing 3528 } 3529 } 3530 return macAddress; 3531 3532 } 3533 3534 private class WifiNetworkFactory extends NetworkFactory { 3535 public WifiNetworkFactory(Looper l, Context c, String TAG, NetworkCapabilities f) { 3536 super(l, c, TAG, f); 3537 } 3538 3539 @Override 3540 protected void needNetworkFor(NetworkRequest networkRequest, int score) { 3541 synchronized (mWifiReqCountLock) { 3542 if (++mConnectionReqCount == 1) { 3543 if (mWifiConnectivityManager != null && mUntrustedReqCount == 0) { 3544 mWifiConnectivityManager.enable(true); 3545 } 3546 } 3547 } 3548 } 3549 3550 @Override 3551 protected void releaseNetworkFor(NetworkRequest networkRequest) { 3552 synchronized (mWifiReqCountLock) { 3553 if (--mConnectionReqCount == 0) { 3554 if (mWifiConnectivityManager != null && mUntrustedReqCount == 0) { 3555 mWifiConnectivityManager.enable(false); 3556 } 3557 } 3558 } 3559 } 3560 3561 @Override 3562 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3563 pw.println("mConnectionReqCount " + mConnectionReqCount); 3564 } 3565 3566 } 3567 3568 private class UntrustedWifiNetworkFactory extends NetworkFactory { 3569 public UntrustedWifiNetworkFactory(Looper l, Context c, String tag, NetworkCapabilities f) { 3570 super(l, c, tag, f); 3571 } 3572 3573 @Override 3574 protected void needNetworkFor(NetworkRequest networkRequest, int score) { 3575 if (!networkRequest.networkCapabilities.hasCapability( 3576 NetworkCapabilities.NET_CAPABILITY_TRUSTED)) { 3577 synchronized (mWifiReqCountLock) { 3578 if (++mUntrustedReqCount == 1) { 3579 if (mWifiConnectivityManager != null) { 3580 if (mConnectionReqCount == 0) { 3581 mWifiConnectivityManager.enable(true); 3582 } 3583 mWifiConnectivityManager.setUntrustedConnectionAllowed(true); 3584 } 3585 } 3586 } 3587 } 3588 } 3589 3590 @Override 3591 protected void releaseNetworkFor(NetworkRequest networkRequest) { 3592 if (!networkRequest.networkCapabilities.hasCapability( 3593 NetworkCapabilities.NET_CAPABILITY_TRUSTED)) { 3594 synchronized (mWifiReqCountLock) { 3595 if (--mUntrustedReqCount == 0) { 3596 if (mWifiConnectivityManager != null) { 3597 mWifiConnectivityManager.setUntrustedConnectionAllowed(false); 3598 if (mConnectionReqCount == 0) { 3599 mWifiConnectivityManager.enable(false); 3600 } 3601 } 3602 } 3603 } 3604 } 3605 } 3606 3607 @Override 3608 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 3609 pw.println("mUntrustedReqCount " + mUntrustedReqCount); 3610 } 3611 } 3612 3613 void maybeRegisterNetworkFactory() { 3614 if (mNetworkFactory == null) { 3615 checkAndSetConnectivityInstance(); 3616 if (mCm != null) { 3617 mNetworkFactory = new WifiNetworkFactory(getHandler().getLooper(), mContext, 3618 NETWORKTYPE, mNetworkCapabilitiesFilter); 3619 mNetworkFactory.setScoreFilter(60); 3620 mNetworkFactory.register(); 3621 3622 // We can't filter untrusted network in the capabilities filter because a trusted 3623 // network would still satisfy a request that accepts untrusted ones. 3624 mUntrustedNetworkFactory = new UntrustedWifiNetworkFactory(getHandler().getLooper(), 3625 mContext, NETWORKTYPE_UNTRUSTED, mNetworkCapabilitiesFilter); 3626 mUntrustedNetworkFactory.setScoreFilter(Integer.MAX_VALUE); 3627 mUntrustedNetworkFactory.register(); 3628 } 3629 } 3630 } 3631 3632 /** 3633 * WifiStateMachine needs to enable/disable other services when wifi is in client mode. This 3634 * method allows WifiStateMachine to get these additional system services. 3635 * 3636 * At this time, this method is used to setup variables for P2P service and Wifi Aware. 3637 */ 3638 private void getAdditionalWifiServiceInterfaces() { 3639 // First set up Wifi Direct 3640 if (mP2pSupported) { 3641 IBinder s1 = mFacade.getService(Context.WIFI_P2P_SERVICE); 3642 WifiP2pServiceImpl wifiP2pServiceImpl = 3643 (WifiP2pServiceImpl) IWifiP2pManager.Stub.asInterface(s1); 3644 3645 if (wifiP2pServiceImpl != null) { 3646 mWifiP2pChannel = new AsyncChannel(); 3647 mWifiP2pChannel.connect(mContext, getHandler(), 3648 wifiP2pServiceImpl.getP2pStateMachineMessenger()); 3649 } 3650 } 3651 } 3652 3653 /******************************************************** 3654 * HSM states 3655 *******************************************************/ 3656 3657 class DefaultState extends State { 3658 3659 @Override 3660 public boolean processMessage(Message message) { 3661 logStateAndMessage(message, this); 3662 3663 switch (message.what) { 3664 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: { 3665 AsyncChannel ac = (AsyncChannel) message.obj; 3666 if (ac == mWifiP2pChannel) { 3667 if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 3668 p2pSendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION); 3669 // since the p2p channel is connected, we should enable p2p if we are in 3670 // connect mode. We may not be in connect mode yet, we may have just 3671 // set the operational mode and started to set up for connect mode. 3672 if (mOperationalMode == CONNECT_MODE) { 3673 // This message will only be handled if we are in Connect mode. 3674 // If we are not in connect mode yet, this will be dropped and the 3675 // ConnectMode.enter method will call to enable p2p. 3676 sendMessage(CMD_ENABLE_P2P); 3677 } 3678 } else { 3679 // TODO: We should probably do some cleanup or attempt a retry 3680 // b/34283611 3681 loge("WifiP2pService connection failure, error=" + message.arg1); 3682 } 3683 } else { 3684 loge("got HALF_CONNECTED for unknown channel"); 3685 } 3686 break; 3687 } 3688 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: { 3689 AsyncChannel ac = (AsyncChannel) message.obj; 3690 if (ac == mWifiP2pChannel) { 3691 loge("WifiP2pService channel lost, message.arg1 =" + message.arg1); 3692 //TODO: Re-establish connection to state machine after a delay (b/34283611) 3693 // mWifiP2pChannel.connect(mContext, getHandler(), 3694 // mWifiP2pManager.getMessenger()); 3695 } 3696 break; 3697 } 3698 case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE: 3699 mBluetoothConnectionActive = (message.arg1 != 3700 BluetoothAdapter.STATE_DISCONNECTED); 3701 break; 3702 /* Synchronous call returns */ 3703 case CMD_PING_SUPPLICANT: 3704 case CMD_ENABLE_NETWORK: 3705 case CMD_ADD_OR_UPDATE_NETWORK: 3706 case CMD_SAVE_CONFIG: 3707 replyToMessage(message, message.what, FAILURE); 3708 break; 3709 case CMD_REMOVE_NETWORK: 3710 deleteNetworkConfigAndSendReply(message, false); 3711 break; 3712 case CMD_GET_CONFIGURED_NETWORKS: 3713 replyToMessage(message, message.what, mWifiConfigManager.getSavedNetworks()); 3714 break; 3715 case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS: 3716 replyToMessage(message, message.what, 3717 mWifiConfigManager.getConfiguredNetworksWithPasswords()); 3718 break; 3719 case CMD_ENABLE_RSSI_POLL: 3720 mEnableRssiPolling = (message.arg1 == 1); 3721 break; 3722 case CMD_SET_HIGH_PERF_MODE: 3723 if (message.arg1 == 1) { 3724 setSuspendOptimizations(SUSPEND_DUE_TO_HIGH_PERF, false); 3725 } else { 3726 setSuspendOptimizations(SUSPEND_DUE_TO_HIGH_PERF, true); 3727 } 3728 break; 3729 case CMD_INITIALIZE: 3730 boolean ok = mWifiNative.initializeVendorHal(); 3731 replyToMessage(message, message.what, ok ? SUCCESS : FAILURE); 3732 break; 3733 case CMD_BOOT_COMPLETED: 3734 // get other services that we need to manage 3735 getAdditionalWifiServiceInterfaces(); 3736 if (!mWifiConfigManager.loadFromStore()) { 3737 Log.e(TAG, "Failed to load from config store"); 3738 } 3739 maybeRegisterNetworkFactory(); 3740 break; 3741 case CMD_SCREEN_STATE_CHANGED: 3742 handleScreenStateChanged(message.arg1 != 0); 3743 break; 3744 /* Discard */ 3745 case CMD_START_SCAN: 3746 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 3747 break; 3748 case CMD_START_SUPPLICANT: 3749 case CMD_STOP_SUPPLICANT: 3750 case CMD_DRIVER_START_TIMED_OUT: 3751 case CMD_START_AP: 3752 case CMD_START_AP_FAILURE: 3753 case CMD_STOP_AP: 3754 case CMD_AP_STOPPED: 3755 case CMD_DISCONNECT: 3756 case CMD_RECONNECT: 3757 case CMD_REASSOCIATE: 3758 case CMD_RELOAD_TLS_AND_RECONNECT: 3759 case WifiMonitor.SUP_CONNECTION_EVENT: 3760 case WifiMonitor.SUP_DISCONNECTION_EVENT: 3761 case WifiMonitor.NETWORK_CONNECTION_EVENT: 3762 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 3763 case WifiMonitor.SCAN_RESULTS_EVENT: 3764 case WifiMonitor.SCAN_FAILED_EVENT: 3765 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 3766 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 3767 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 3768 case WifiMonitor.WPS_OVERLAP_EVENT: 3769 case CMD_SET_OPERATIONAL_MODE: 3770 case CMD_RSSI_POLL: 3771 case DhcpClient.CMD_PRE_DHCP_ACTION: 3772 case DhcpClient.CMD_PRE_DHCP_ACTION_COMPLETE: 3773 case DhcpClient.CMD_POST_DHCP_ACTION: 3774 case CMD_NO_NETWORKS_PERIODIC_SCAN: 3775 case CMD_ENABLE_P2P: 3776 case CMD_DISABLE_P2P_RSP: 3777 case WifiMonitor.SUP_REQUEST_IDENTITY: 3778 case CMD_TEST_NETWORK_DISCONNECT: 3779 case WifiMonitor.SUP_REQUEST_SIM_AUTH: 3780 case CMD_TARGET_BSSID: 3781 case CMD_START_CONNECT: 3782 case CMD_START_ROAM: 3783 case CMD_ASSOCIATED_BSSID: 3784 case CMD_UNWANTED_NETWORK: 3785 case CMD_DISCONNECTING_WATCHDOG_TIMER: 3786 case CMD_ROAM_WATCHDOG_TIMER: 3787 case CMD_DISABLE_EPHEMERAL_NETWORK: 3788 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 3789 break; 3790 case CMD_SET_SUSPEND_OPT_ENABLED: 3791 if (message.arg1 == 1) { 3792 if (message.arg2 == 1) { 3793 mSuspendWakeLock.release(); 3794 } 3795 setSuspendOptimizations(SUSPEND_DUE_TO_SCREEN, true); 3796 } else { 3797 setSuspendOptimizations(SUSPEND_DUE_TO_SCREEN, false); 3798 } 3799 break; 3800 case WifiMonitor.DRIVER_HUNG_EVENT: 3801 setSupplicantRunning(false); 3802 setSupplicantRunning(true); 3803 break; 3804 case WifiManager.CONNECT_NETWORK: 3805 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 3806 WifiManager.BUSY); 3807 break; 3808 case WifiManager.FORGET_NETWORK: 3809 deleteNetworkConfigAndSendReply(message, true); 3810 break; 3811 case WifiManager.SAVE_NETWORK: 3812 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 3813 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 3814 WifiManager.BUSY); 3815 break; 3816 case WifiManager.START_WPS: 3817 replyToMessage(message, WifiManager.WPS_FAILED, 3818 WifiManager.BUSY); 3819 break; 3820 case WifiManager.CANCEL_WPS: 3821 replyToMessage(message, WifiManager.CANCEL_WPS_FAILED, 3822 WifiManager.BUSY); 3823 break; 3824 case WifiManager.DISABLE_NETWORK: 3825 replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED, 3826 WifiManager.BUSY); 3827 break; 3828 case WifiManager.RSSI_PKTCNT_FETCH: 3829 replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_FAILED, 3830 WifiManager.BUSY); 3831 break; 3832 case CMD_GET_SUPPORTED_FEATURES: 3833 int featureSet = mWifiNative.getSupportedFeatureSet(); 3834 replyToMessage(message, message.what, featureSet); 3835 break; 3836 case CMD_FIRMWARE_ALERT: 3837 if (mWifiDiagnostics != null) { 3838 byte[] buffer = (byte[])message.obj; 3839 int alertReason = message.arg1; 3840 mWifiDiagnostics.captureAlertData(alertReason, buffer); 3841 mWifiMetrics.incrementAlertReasonCount(alertReason); 3842 } 3843 break; 3844 case CMD_GET_LINK_LAYER_STATS: 3845 // Not supported hence reply with error message 3846 replyToMessage(message, message.what, null); 3847 break; 3848 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 3849 NetworkInfo info = (NetworkInfo) message.obj; 3850 mP2pConnected.set(info.isConnected()); 3851 break; 3852 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 3853 mTemporarilyDisconnectWifi = (message.arg1 == 1); 3854 replyToMessage(message, WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE); 3855 break; 3856 /* Link configuration (IP address, DNS, ...) changes notified via netlink */ 3857 case CMD_UPDATE_LINKPROPERTIES: 3858 updateLinkProperties((LinkProperties) message.obj); 3859 break; 3860 case CMD_GET_MATCHING_CONFIG: 3861 replyToMessage(message, message.what); 3862 break; 3863 case CMD_IP_CONFIGURATION_SUCCESSFUL: 3864 case CMD_IP_CONFIGURATION_LOST: 3865 case CMD_IP_REACHABILITY_LOST: 3866 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 3867 break; 3868 case CMD_GET_CONNECTION_STATISTICS: 3869 replyToMessage(message, message.what, mWifiConnectionStatistics); 3870 break; 3871 case CMD_REMOVE_APP_CONFIGURATIONS: 3872 deferMessage(message); 3873 break; 3874 case CMD_REMOVE_USER_CONFIGURATIONS: 3875 deferMessage(message); 3876 break; 3877 case CMD_START_IP_PACKET_OFFLOAD: 3878 if (mNetworkAgent != null) mNetworkAgent.onPacketKeepaliveEvent( 3879 message.arg1, 3880 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK); 3881 break; 3882 case CMD_STOP_IP_PACKET_OFFLOAD: 3883 if (mNetworkAgent != null) mNetworkAgent.onPacketKeepaliveEvent( 3884 message.arg1, 3885 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK); 3886 break; 3887 case CMD_START_RSSI_MONITORING_OFFLOAD: 3888 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 3889 break; 3890 case CMD_STOP_RSSI_MONITORING_OFFLOAD: 3891 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 3892 break; 3893 case CMD_USER_SWITCH: 3894 Set<Integer> removedNetworkIds = 3895 mWifiConfigManager.handleUserSwitch(message.arg1); 3896 if (removedNetworkIds.contains(mTargetNetworkId) || 3897 removedNetworkIds.contains(mLastNetworkId)) { 3898 // Disconnect and let autojoin reselect a new network 3899 sendMessage(CMD_DISCONNECT); 3900 } 3901 break; 3902 case CMD_USER_UNLOCK: 3903 mWifiConfigManager.handleUserUnlock(message.arg1); 3904 break; 3905 case CMD_USER_STOP: 3906 mWifiConfigManager.handleUserStop(message.arg1); 3907 break; 3908 case CMD_QUERY_OSU_ICON: 3909 case CMD_MATCH_PROVIDER_NETWORK: 3910 /* reply with arg1 = 0 - it returns API failure to the calling app 3911 * (message.what is not looked at) 3912 */ 3913 replyToMessage(message, message.what); 3914 break; 3915 case CMD_ADD_OR_UPDATE_PASSPOINT_CONFIG: 3916 int addResult = mPasspointManager.addOrUpdateProvider( 3917 (PasspointConfiguration) message.obj) ? SUCCESS : FAILURE; 3918 replyToMessage(message, message.what, addResult); 3919 break; 3920 case CMD_REMOVE_PASSPOINT_CONFIG: 3921 int removeResult = mPasspointManager.removeProvider( 3922 (String) message.obj) ? SUCCESS : FAILURE; 3923 replyToMessage(message, message.what, removeResult); 3924 break; 3925 case CMD_GET_PASSPOINT_CONFIGS: 3926 replyToMessage(message, message.what, mPasspointManager.getProviderConfigs()); 3927 break; 3928 case CMD_RESET_SIM_NETWORKS: 3929 /* Defer this message until supplicant is started. */ 3930 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 3931 deferMessage(message); 3932 break; 3933 case CMD_INSTALL_PACKET_FILTER: 3934 mWifiNative.installPacketFilter((byte[]) message.obj); 3935 break; 3936 case CMD_SET_FALLBACK_PACKET_FILTERING: 3937 if ((boolean) message.obj) { 3938 mWifiNative.startFilteringMulticastV4Packets(); 3939 } else { 3940 mWifiNative.stopFilteringMulticastV4Packets(); 3941 } 3942 break; 3943 case CMD_CLIENT_INTERFACE_BINDER_DEATH: 3944 // We have lost contact with a client interface, which means that we cannot 3945 // trust that the driver is up or that the interface is ready. We are fit 3946 // for no WiFi related work. 3947 transitionTo(mInitialState); 3948 break; 3949 case CMD_DIAGS_CONNECT_TIMEOUT: 3950 mWifiDiagnostics.reportConnectionEvent( 3951 (Long) message.obj, BaseWifiDiagnostics.CONNECTION_EVENT_FAILED); 3952 break; 3953 default: 3954 loge("Error! unhandled message" + message); 3955 break; 3956 } 3957 return HANDLED; 3958 } 3959 } 3960 3961 class InitialState extends State { 3962 3963 private void cleanup() { 3964 // Tearing down the client interfaces below is going to stop our supplicant. 3965 mWifiMonitor.stopAllMonitoring(); 3966 3967 mDeathRecipient.unlinkToDeath(); 3968 mWifiNative.tearDown(); 3969 } 3970 3971 @Override 3972 public void enter() { 3973 mWifiStateTracker.updateState(WifiStateTracker.INVALID); 3974 cleanup(); 3975 } 3976 3977 @Override 3978 public boolean processMessage(Message message) { 3979 logStateAndMessage(message, this); 3980 switch (message.what) { 3981 case CMD_START_SUPPLICANT: 3982 mClientInterface = mWifiNative.setupForClientMode(); 3983 if (mClientInterface == null 3984 || !mDeathRecipient.linkToDeath(mClientInterface.asBinder())) { 3985 setWifiState(WifiManager.WIFI_STATE_UNKNOWN); 3986 cleanup(); 3987 break; 3988 } 3989 3990 try { 3991 // A runtime crash or shutting down AP mode can leave 3992 // IP addresses configured, and this affects 3993 // connectivity when supplicant starts up. 3994 // Ensure we have no IP addresses before a supplicant start. 3995 mNwService.clearInterfaceAddresses(mInterfaceName); 3996 3997 // Set privacy extensions 3998 mNwService.setInterfaceIpv6PrivacyExtensions(mInterfaceName, true); 3999 4000 // IPv6 is enabled only as long as access point is connected since: 4001 // - IPv6 addresses and routes stick around after disconnection 4002 // - kernel is unaware when connected and fails to start IPv6 negotiation 4003 // - kernel can start autoconfiguration when 802.1x is not complete 4004 mNwService.disableIpv6(mInterfaceName); 4005 } catch (RemoteException re) { 4006 loge("Unable to change interface settings: " + re); 4007 } catch (IllegalStateException ie) { 4008 loge("Unable to change interface settings: " + ie); 4009 } 4010 4011 if (!mWifiNative.enableSupplicant()) { 4012 loge("Failed to start supplicant!"); 4013 setWifiState(WifiManager.WIFI_STATE_UNKNOWN); 4014 cleanup(); 4015 break; 4016 } 4017 setWifiState(WIFI_STATE_ENABLING); 4018 if (mVerboseLoggingEnabled) log("Supplicant start successful"); 4019 mWifiMonitor.startMonitoring(mInterfaceName, true); 4020 setSupplicantLogLevel(); 4021 transitionTo(mSupplicantStartingState); 4022 break; 4023 case CMD_START_AP: 4024 transitionTo(mSoftApState); 4025 break; 4026 case CMD_SET_OPERATIONAL_MODE: 4027 mOperationalMode = message.arg1; 4028 if (mOperationalMode != DISABLED_MODE) { 4029 sendMessage(CMD_START_SUPPLICANT); 4030 } 4031 break; 4032 default: 4033 return NOT_HANDLED; 4034 } 4035 return HANDLED; 4036 } 4037 } 4038 4039 class SupplicantStartingState extends State { 4040 private void initializeWpsDetails() { 4041 String detail; 4042 detail = mPropertyService.get("ro.product.name", ""); 4043 if (!mWifiNative.setDeviceName(detail)) { 4044 loge("Failed to set device name " + detail); 4045 } 4046 detail = mPropertyService.get("ro.product.manufacturer", ""); 4047 if (!mWifiNative.setManufacturer(detail)) { 4048 loge("Failed to set manufacturer " + detail); 4049 } 4050 detail = mPropertyService.get("ro.product.model", ""); 4051 if (!mWifiNative.setModelName(detail)) { 4052 loge("Failed to set model name " + detail); 4053 } 4054 detail = mPropertyService.get("ro.product.model", ""); 4055 if (!mWifiNative.setModelNumber(detail)) { 4056 loge("Failed to set model number " + detail); 4057 } 4058 detail = mPropertyService.get("ro.serialno", ""); 4059 if (!mWifiNative.setSerialNumber(detail)) { 4060 loge("Failed to set serial number " + detail); 4061 } 4062 if (!mWifiNative.setConfigMethods("physical_display virtual_push_button")) { 4063 loge("Failed to set WPS config methods"); 4064 } 4065 if (!mWifiNative.setDeviceType(mPrimaryDeviceType)) { 4066 loge("Failed to set primary device type " + mPrimaryDeviceType); 4067 } 4068 } 4069 4070 @Override 4071 public boolean processMessage(Message message) { 4072 logStateAndMessage(message, this); 4073 4074 switch(message.what) { 4075 case WifiMonitor.SUP_CONNECTION_EVENT: 4076 if (mVerboseLoggingEnabled) log("Supplicant connection established"); 4077 4078 mSupplicantRestartCount = 0; 4079 /* Reset the supplicant state to indicate the supplicant 4080 * state is not known at this time */ 4081 mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE); 4082 /* Initialize data structures */ 4083 mLastBssid = null; 4084 mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 4085 mLastSignalLevel = -1; 4086 4087 mWifiInfo.setMacAddress(mWifiNative.getMacAddress()); 4088 // Attempt to migrate data out of legacy store. 4089 if (!mWifiConfigManager.migrateFromLegacyStore()) { 4090 Log.e(TAG, "Failed to migrate from legacy config store"); 4091 } 4092 initializeWpsDetails(); 4093 sendSupplicantConnectionChangedBroadcast(true); 4094 transitionTo(mSupplicantStartedState); 4095 break; 4096 case WifiMonitor.SUP_DISCONNECTION_EVENT: 4097 if (++mSupplicantRestartCount <= SUPPLICANT_RESTART_TRIES) { 4098 loge("Failed to setup control channel, restart supplicant"); 4099 mWifiMonitor.stopAllMonitoring(); 4100 mWifiNative.disableSupplicant(); 4101 transitionTo(mInitialState); 4102 sendMessageDelayed(CMD_START_SUPPLICANT, SUPPLICANT_RESTART_INTERVAL_MSECS); 4103 } else { 4104 loge("Failed " + mSupplicantRestartCount + 4105 " times to start supplicant, unload driver"); 4106 mSupplicantRestartCount = 0; 4107 setWifiState(WIFI_STATE_UNKNOWN); 4108 transitionTo(mInitialState); 4109 } 4110 break; 4111 case CMD_START_SUPPLICANT: 4112 case CMD_STOP_SUPPLICANT: 4113 case CMD_START_AP: 4114 case CMD_STOP_AP: 4115 case CMD_SET_OPERATIONAL_MODE: 4116 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 4117 deferMessage(message); 4118 break; 4119 default: 4120 return NOT_HANDLED; 4121 } 4122 return HANDLED; 4123 } 4124 } 4125 4126 class SupplicantStartedState extends State { 4127 @Override 4128 public void enter() { 4129 if (mVerboseLoggingEnabled) { 4130 logd("SupplicantStartedState enter"); 4131 } 4132 4133 mWifiNative.setExternalSim(true); 4134 4135 /* turn on use of DFS channels */ 4136 mWifiNative.setDfsFlag(true); 4137 4138 setRandomMacOui(); 4139 mCountryCode.setReadyForChange(true); 4140 4141 // We can't do this in the constructor because WifiStateMachine is created before the 4142 // wifi scanning service is initialized 4143 if (mWifiScanner == null) { 4144 mWifiScanner = mWifiInjector.getWifiScanner(); 4145 4146 synchronized (mWifiReqCountLock) { 4147 mWifiConnectivityManager = 4148 mWifiInjector.makeWifiConnectivityManager(mWifiInfo, 4149 hasConnectionRequests()); 4150 mWifiConnectivityManager.setUntrustedConnectionAllowed(mUntrustedReqCount > 0); 4151 mWifiConnectivityManager.handleScreenStateChanged(mScreenOn); 4152 } 4153 } 4154 4155 mWifiDiagnostics.startLogging(mVerboseLoggingEnabled); 4156 mIsRunning = true; 4157 updateBatteryWorkSource(null); 4158 /** 4159 * Enable bluetooth coexistence scan mode when bluetooth connection is active. 4160 * When this mode is on, some of the low-level scan parameters used by the 4161 * driver are changed to reduce interference with bluetooth 4162 */ 4163 mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive); 4164 // initialize network state 4165 setNetworkDetailedState(DetailedState.DISCONNECTED); 4166 4167 // Disable legacy multicast filtering, which on some chipsets defaults to enabled. 4168 // Legacy IPv6 multicast filtering blocks ICMPv6 router advertisements which breaks IPv6 4169 // provisioning. Legacy IPv4 multicast filtering may be re-enabled later via 4170 // IpManager.Callback.setFallbackMulticastFilter() 4171 mWifiNative.stopFilteringMulticastV4Packets(); 4172 mWifiNative.stopFilteringMulticastV6Packets(); 4173 4174 if (mOperationalMode == SCAN_ONLY_MODE || 4175 mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 4176 mWifiNative.disconnect(); 4177 setWifiState(WIFI_STATE_DISABLED); 4178 transitionTo(mScanModeState); 4179 } else if (mOperationalMode == CONNECT_MODE) { 4180 // Transitioning to Disconnected state will trigger a scan and subsequently AutoJoin 4181 transitionTo(mDisconnectedState); 4182 } else if (mOperationalMode == DISABLED_MODE) { 4183 transitionTo(mSupplicantStoppingState); 4184 } 4185 4186 // Set the right suspend mode settings 4187 mWifiNative.setSuspendOptimizations(mSuspendOptNeedsDisabled == 0 4188 && mUserWantsSuspendOpt.get()); 4189 4190 mWifiNative.setPowerSave(true); 4191 4192 if (mP2pSupported) { 4193 if (mOperationalMode == CONNECT_MODE) { 4194 p2pSendMessage(WifiStateMachine.CMD_ENABLE_P2P); 4195 } else { 4196 // P2P state machine starts in disabled state, and is not enabled until 4197 // CMD_ENABLE_P2P is sent from here; so, nothing needs to be done to 4198 // keep it disabled. 4199 } 4200 } 4201 4202 final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE); 4203 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4204 intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_ENABLED); 4205 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 4206 4207 // Enable link layer stats gathering 4208 mWifiNative.setWifiLinkLayerStats("wlan0", 1); 4209 4210 // Disable wpa_supplicant from auto reconnecting. 4211 mWifiNative.enableStaAutoReconnect(false); 4212 // STA has higher priority over P2P 4213 mWifiNative.setConcurrencyPriority(true); 4214 } 4215 4216 @Override 4217 public boolean processMessage(Message message) { 4218 logStateAndMessage(message, this); 4219 4220 switch(message.what) { 4221 case CMD_STOP_SUPPLICANT: /* Supplicant stopped by user */ 4222 if (mP2pSupported) { 4223 transitionTo(mWaitForP2pDisableState); 4224 } else { 4225 transitionTo(mSupplicantStoppingState); 4226 } 4227 break; 4228 case WifiMonitor.SUP_DISCONNECTION_EVENT: /* Supplicant connection lost */ 4229 loge("Connection lost, restart supplicant"); 4230 handleSupplicantConnectionLoss(true); 4231 handleNetworkDisconnect(); 4232 mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE); 4233 if (mP2pSupported) { 4234 transitionTo(mWaitForP2pDisableState); 4235 } else { 4236 transitionTo(mInitialState); 4237 } 4238 sendMessageDelayed(CMD_START_SUPPLICANT, SUPPLICANT_RESTART_INTERVAL_MSECS); 4239 break; 4240 case CMD_START_SCAN: 4241 // TODO: remove scan request path (b/31445200) 4242 handleScanRequest(message); 4243 break; 4244 case WifiMonitor.SCAN_RESULTS_EVENT: 4245 case WifiMonitor.SCAN_FAILED_EVENT: 4246 // TODO: remove handing of SCAN_RESULTS_EVENT and SCAN_FAILED_EVENT when scan 4247 // results are retrieved from WifiScanner (b/31444878) 4248 maybeRegisterNetworkFactory(); // Make sure our NetworkFactory is registered 4249 setScanResults(); 4250 mIsScanOngoing = false; 4251 mIsFullScanOngoing = false; 4252 if (mBufferedScanMsg.size() > 0) 4253 sendMessage(mBufferedScanMsg.remove()); 4254 break; 4255 case CMD_PING_SUPPLICANT: 4256 // TODO (b/35620640): Remove this command since the API is deprecated. 4257 replyToMessage(message, message.what, FAILURE); 4258 break; 4259 case CMD_START_AP: 4260 /* Cannot start soft AP while in client mode */ 4261 loge("Failed to start soft AP with a running supplicant"); 4262 setWifiApState(WIFI_AP_STATE_FAILED, WifiManager.SAP_START_FAILURE_GENERAL); 4263 break; 4264 case CMD_SET_OPERATIONAL_MODE: 4265 mOperationalMode = message.arg1; 4266 if (mOperationalMode == DISABLED_MODE) { 4267 transitionTo(mSupplicantStoppingState); 4268 } 4269 break; 4270 case CMD_TARGET_BSSID: 4271 // Trying to associate to this BSSID 4272 if (message.obj != null) { 4273 mTargetRoamBSSID = (String) message.obj; 4274 } 4275 break; 4276 case CMD_GET_LINK_LAYER_STATS: 4277 WifiLinkLayerStats stats = getWifiLinkLayerStats(); 4278 replyToMessage(message, message.what, stats); 4279 break; 4280 case CMD_RESET_SIM_NETWORKS: 4281 log("resetting EAP-SIM/AKA/AKA' networks since SIM was changed"); 4282 mWifiConfigManager.resetSimNetworks(); 4283 break; 4284 case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE: 4285 mBluetoothConnectionActive = (message.arg1 != 4286 BluetoothAdapter.STATE_DISCONNECTED); 4287 mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive); 4288 break; 4289 case CMD_SET_SUSPEND_OPT_ENABLED: 4290 if (message.arg1 == 1) { 4291 setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, true); 4292 if (message.arg2 == 1) { 4293 mSuspendWakeLock.release(); 4294 } 4295 } else { 4296 setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, false); 4297 } 4298 break; 4299 case CMD_SET_HIGH_PERF_MODE: 4300 if (message.arg1 == 1) { 4301 setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, false); 4302 } else { 4303 setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, true); 4304 } 4305 break; 4306 case CMD_ENABLE_TDLS: 4307 if (message.obj != null) { 4308 String remoteAddress = (String) message.obj; 4309 boolean enable = (message.arg1 == 1); 4310 mWifiNative.startTdls(remoteAddress, enable); 4311 } 4312 break; 4313 case WifiMonitor.ANQP_DONE_EVENT: 4314 // TODO(zqiu): remove this when switch over to wificond for ANQP requests. 4315 mPasspointManager.notifyANQPDone((AnqpEvent) message.obj); 4316 break; 4317 case CMD_STOP_IP_PACKET_OFFLOAD: { 4318 int slot = message.arg1; 4319 int ret = stopWifiIPPacketOffload(slot); 4320 if (mNetworkAgent != null) { 4321 mNetworkAgent.onPacketKeepaliveEvent(slot, ret); 4322 } 4323 break; 4324 } 4325 case WifiMonitor.RX_HS20_ANQP_ICON_EVENT: 4326 // TODO(zqiu): remove this when switch over to wificond for icon requests. 4327 mPasspointManager.notifyIconDone((IconEvent) message.obj); 4328 break; 4329 case WifiMonitor.HS20_REMEDIATION_EVENT: 4330 // TODO(zqiu): remove this when switch over to wificond for WNM frames 4331 // monitoring. 4332 mPasspointManager.receivedWnmFrame((WnmData) message.obj); 4333 break; 4334 case CMD_CONFIG_ND_OFFLOAD: 4335 final boolean enabled = (message.arg1 > 0); 4336 mWifiNative.configureNeighborDiscoveryOffload(enabled); 4337 break; 4338 case CMD_ENABLE_WIFI_CONNECTIVITY_MANAGER: 4339 mWifiConnectivityManager.enable(message.arg1 == 1 ? true : false); 4340 break; 4341 case CMD_ENABLE_AUTOJOIN_WHEN_ASSOCIATED: 4342 final boolean allowed = (message.arg1 > 0); 4343 boolean old_state = mEnableAutoJoinWhenAssociated; 4344 mEnableAutoJoinWhenAssociated = allowed; 4345 if (!old_state && allowed && mScreenOn 4346 && getCurrentState() == mConnectedState) { 4347 mWifiConnectivityManager.forceConnectivityScan(); 4348 } 4349 break; 4350 default: 4351 return NOT_HANDLED; 4352 } 4353 return HANDLED; 4354 } 4355 4356 @Override 4357 public void exit() { 4358 mWifiDiagnostics.stopLogging(); 4359 4360 mIsRunning = false; 4361 updateBatteryWorkSource(null); 4362 mScanResults = new ArrayList<>(); 4363 4364 final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE); 4365 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4366 intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED); 4367 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 4368 mBufferedScanMsg.clear(); 4369 4370 mNetworkInfo.setIsAvailable(false); 4371 if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo); 4372 mCountryCode.setReadyForChange(false); 4373 } 4374 } 4375 4376 class SupplicantStoppingState extends State { 4377 @Override 4378 public void enter() { 4379 /* Send any reset commands to supplicant before shutting it down */ 4380 handleNetworkDisconnect(); 4381 4382 String suppState = System.getProperty("init.svc.wpa_supplicant"); 4383 if (suppState == null) suppState = "unknown"; 4384 4385 setWifiState(WIFI_STATE_DISABLING); 4386 mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE); 4387 logd("SupplicantStoppingState: disableSupplicant " 4388 + " init.svc.wpa_supplicant=" + suppState); 4389 if (mWifiNative.disableSupplicant()) { 4390 mWifiNative.closeSupplicantConnection(); 4391 sendSupplicantConnectionChangedBroadcast(false); 4392 setWifiState(WIFI_STATE_DISABLED); 4393 } else { 4394 // Failed to disable supplicant 4395 handleSupplicantConnectionLoss(true); 4396 } 4397 transitionTo(mInitialState); 4398 } 4399 } 4400 4401 class WaitForP2pDisableState extends State { 4402 private State mTransitionToState; 4403 @Override 4404 public void enter() { 4405 switch (getCurrentMessage().what) { 4406 case WifiMonitor.SUP_DISCONNECTION_EVENT: 4407 mTransitionToState = mInitialState; 4408 break; 4409 case CMD_STOP_SUPPLICANT: 4410 default: 4411 mTransitionToState = mSupplicantStoppingState; 4412 break; 4413 } 4414 p2pSendMessage(WifiStateMachine.CMD_DISABLE_P2P_REQ); 4415 } 4416 @Override 4417 public boolean processMessage(Message message) { 4418 logStateAndMessage(message, this); 4419 4420 switch(message.what) { 4421 case WifiStateMachine.CMD_DISABLE_P2P_RSP: 4422 transitionTo(mTransitionToState); 4423 break; 4424 /* Defer wifi start/shut and driver commands */ 4425 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 4426 case CMD_START_SUPPLICANT: 4427 case CMD_STOP_SUPPLICANT: 4428 case CMD_START_AP: 4429 case CMD_STOP_AP: 4430 case CMD_SET_OPERATIONAL_MODE: 4431 case CMD_START_SCAN: 4432 case CMD_DISCONNECT: 4433 case CMD_REASSOCIATE: 4434 case CMD_RECONNECT: 4435 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 4436 deferMessage(message); 4437 break; 4438 default: 4439 return NOT_HANDLED; 4440 } 4441 return HANDLED; 4442 } 4443 } 4444 4445 class ScanModeState extends State { 4446 private int mLastOperationMode; 4447 @Override 4448 public void enter() { 4449 mLastOperationMode = mOperationalMode; 4450 mWifiStateTracker.updateState(WifiStateTracker.SCAN_MODE); 4451 } 4452 @Override 4453 public boolean processMessage(Message message) { 4454 logStateAndMessage(message, this); 4455 4456 switch(message.what) { 4457 case CMD_SET_OPERATIONAL_MODE: 4458 if (message.arg1 == CONNECT_MODE) { 4459 mOperationalMode = CONNECT_MODE; 4460 transitionTo(mDisconnectedState); 4461 } else if (message.arg1 == DISABLED_MODE) { 4462 transitionTo(mSupplicantStoppingState); 4463 } 4464 // Nothing to do 4465 break; 4466 // Handle scan. All the connection related commands are 4467 // handled only in ConnectModeState 4468 case CMD_START_SCAN: 4469 handleScanRequest(message); 4470 break; 4471 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 4472 SupplicantState state = handleSupplicantStateChange(message); 4473 if (mVerboseLoggingEnabled) log("SupplicantState= " + state); 4474 break; 4475 default: 4476 return NOT_HANDLED; 4477 } 4478 return HANDLED; 4479 } 4480 } 4481 4482 4483 String smToString(Message message) { 4484 return smToString(message.what); 4485 } 4486 4487 String smToString(int what) { 4488 String s = sSmToString.get(what); 4489 if (s != null) { 4490 return s; 4491 } 4492 switch (what) { 4493 case WifiMonitor.DRIVER_HUNG_EVENT: 4494 s = "DRIVER_HUNG_EVENT"; 4495 break; 4496 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: 4497 s = "AsyncChannel.CMD_CHANNEL_HALF_CONNECTED"; 4498 break; 4499 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: 4500 s = "AsyncChannel.CMD_CHANNEL_DISCONNECTED"; 4501 break; 4502 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 4503 s = "WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST"; 4504 break; 4505 case WifiManager.DISABLE_NETWORK: 4506 s = "WifiManager.DISABLE_NETWORK"; 4507 break; 4508 case WifiManager.CONNECT_NETWORK: 4509 s = "CONNECT_NETWORK"; 4510 break; 4511 case WifiManager.SAVE_NETWORK: 4512 s = "SAVE_NETWORK"; 4513 break; 4514 case WifiManager.FORGET_NETWORK: 4515 s = "FORGET_NETWORK"; 4516 break; 4517 case WifiMonitor.SUP_CONNECTION_EVENT: 4518 s = "SUP_CONNECTION_EVENT"; 4519 break; 4520 case WifiMonitor.SUP_DISCONNECTION_EVENT: 4521 s = "SUP_DISCONNECTION_EVENT"; 4522 break; 4523 case WifiMonitor.SCAN_RESULTS_EVENT: 4524 s = "SCAN_RESULTS_EVENT"; 4525 break; 4526 case WifiMonitor.SCAN_FAILED_EVENT: 4527 s = "SCAN_FAILED_EVENT"; 4528 break; 4529 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 4530 s = "SUPPLICANT_STATE_CHANGE_EVENT"; 4531 break; 4532 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 4533 s = "AUTHENTICATION_FAILURE_EVENT"; 4534 break; 4535 case WifiMonitor.SSID_TEMP_DISABLED: 4536 s = "SSID_TEMP_DISABLED"; 4537 break; 4538 case WifiMonitor.SSID_REENABLED: 4539 s = "SSID_REENABLED"; 4540 break; 4541 case WifiMonitor.WPS_SUCCESS_EVENT: 4542 s = "WPS_SUCCESS_EVENT"; 4543 break; 4544 case WifiMonitor.WPS_FAIL_EVENT: 4545 s = "WPS_FAIL_EVENT"; 4546 break; 4547 case WifiMonitor.SUP_REQUEST_IDENTITY: 4548 s = "SUP_REQUEST_IDENTITY"; 4549 break; 4550 case WifiMonitor.NETWORK_CONNECTION_EVENT: 4551 s = "NETWORK_CONNECTION_EVENT"; 4552 break; 4553 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 4554 s = "NETWORK_DISCONNECTION_EVENT"; 4555 break; 4556 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 4557 s = "ASSOCIATION_REJECTION_EVENT"; 4558 break; 4559 case WifiMonitor.ANQP_DONE_EVENT: 4560 s = "WifiMonitor.ANQP_DONE_EVENT"; 4561 break; 4562 case WifiMonitor.RX_HS20_ANQP_ICON_EVENT: 4563 s = "WifiMonitor.RX_HS20_ANQP_ICON_EVENT"; 4564 break; 4565 case WifiMonitor.GAS_QUERY_DONE_EVENT: 4566 s = "WifiMonitor.GAS_QUERY_DONE_EVENT"; 4567 break; 4568 case WifiMonitor.HS20_REMEDIATION_EVENT: 4569 s = "WifiMonitor.HS20_REMEDIATION_EVENT"; 4570 break; 4571 case WifiMonitor.GAS_QUERY_START_EVENT: 4572 s = "WifiMonitor.GAS_QUERY_START_EVENT"; 4573 break; 4574 case WifiP2pServiceImpl.GROUP_CREATING_TIMED_OUT: 4575 s = "GROUP_CREATING_TIMED_OUT"; 4576 break; 4577 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 4578 s = "P2P_CONNECTION_CHANGED"; 4579 break; 4580 case WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE: 4581 s = "P2P.DISCONNECT_WIFI_RESPONSE"; 4582 break; 4583 case WifiP2pServiceImpl.SET_MIRACAST_MODE: 4584 s = "P2P.SET_MIRACAST_MODE"; 4585 break; 4586 case WifiP2pServiceImpl.BLOCK_DISCOVERY: 4587 s = "P2P.BLOCK_DISCOVERY"; 4588 break; 4589 case WifiManager.CANCEL_WPS: 4590 s = "CANCEL_WPS"; 4591 break; 4592 case WifiManager.CANCEL_WPS_FAILED: 4593 s = "CANCEL_WPS_FAILED"; 4594 break; 4595 case WifiManager.CANCEL_WPS_SUCCEDED: 4596 s = "CANCEL_WPS_SUCCEDED"; 4597 break; 4598 case WifiManager.START_WPS: 4599 s = "START_WPS"; 4600 break; 4601 case WifiManager.START_WPS_SUCCEEDED: 4602 s = "START_WPS_SUCCEEDED"; 4603 break; 4604 case WifiManager.WPS_FAILED: 4605 s = "WPS_FAILED"; 4606 break; 4607 case WifiManager.WPS_COMPLETED: 4608 s = "WPS_COMPLETED"; 4609 break; 4610 case WifiManager.RSSI_PKTCNT_FETCH: 4611 s = "RSSI_PKTCNT_FETCH"; 4612 break; 4613 default: 4614 s = "what:" + Integer.toString(what); 4615 break; 4616 } 4617 return s; 4618 } 4619 4620 void registerConnected() { 4621 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 4622 mWifiConfigManager.updateNetworkAfterConnect(mLastNetworkId); 4623 // On connect, reset wifiScoreReport 4624 mWifiScoreReport.reset(); 4625 } 4626 } 4627 4628 void registerDisconnected() { 4629 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 4630 mWifiConfigManager.updateNetworkAfterDisconnect(mLastNetworkId); 4631 // We are switching away from this configuration, 4632 // hence record the time we were connected last 4633 WifiConfiguration config = mWifiConfigManager.getConfiguredNetwork(mLastNetworkId); 4634 if (config != null) { 4635 // Remove WifiConfiguration for ephemeral or Passpoint networks, since they're 4636 // temporary networks. 4637 if (config.ephemeral || config.isPasspoint()) { 4638 mWifiConfigManager.removeNetwork(mLastNetworkId, Process.WIFI_UID); 4639 } 4640 } 4641 } 4642 } 4643 4644 /** 4645 * Returns Wificonfiguration object correponding to the currently connected network, null if 4646 * not connected. 4647 */ 4648 public WifiConfiguration getCurrentWifiConfiguration() { 4649 if (mLastNetworkId == WifiConfiguration.INVALID_NETWORK_ID) { 4650 return null; 4651 } 4652 return mWifiConfigManager.getConfiguredNetwork(mLastNetworkId); 4653 } 4654 4655 ScanResult getCurrentScanResult() { 4656 WifiConfiguration config = getCurrentWifiConfiguration(); 4657 if (config == null) { 4658 return null; 4659 } 4660 String BSSID = mWifiInfo.getBSSID(); 4661 if (BSSID == null) { 4662 BSSID = mTargetRoamBSSID; 4663 } 4664 ScanDetailCache scanDetailCache = 4665 mWifiConfigManager.getScanDetailCacheForNetwork(config.networkId); 4666 4667 if (scanDetailCache == null) { 4668 return null; 4669 } 4670 4671 return scanDetailCache.get(BSSID); 4672 } 4673 4674 String getCurrentBSSID() { 4675 if (isLinkDebouncing()) { 4676 return null; 4677 } 4678 return mLastBssid; 4679 } 4680 4681 class ConnectModeState extends State { 4682 4683 @Override 4684 public void enter() { 4685 // Let the system know that wifi is available in client mode. 4686 setWifiState(WIFI_STATE_ENABLED); 4687 4688 mNetworkInfo.setIsAvailable(true); 4689 if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo); 4690 4691 // initialize network state 4692 setNetworkDetailedState(DetailedState.DISCONNECTED); 4693 4694 4695 // Inform WifiConnectivityManager that Wifi is enabled 4696 mWifiConnectivityManager.setWifiEnabled(true); 4697 // Inform metrics that Wifi is Enabled (but not yet connected) 4698 mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_DISCONNECTED); 4699 // Inform p2p service that wifi is up and ready when applicable 4700 p2pSendMessage(WifiStateMachine.CMD_ENABLE_P2P); 4701 } 4702 4703 @Override 4704 public void exit() { 4705 // Let the system know that wifi is not available since we are exiting client mode. 4706 mNetworkInfo.setIsAvailable(false); 4707 if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo); 4708 // Inform WifiConnectivityManager that Wifi is disabled 4709 mWifiConnectivityManager.setWifiEnabled(false); 4710 // Inform metrics that Wifi is being disabled (Toggled, airplane enabled, etc) 4711 mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_DISABLED); 4712 } 4713 4714 @Override 4715 public boolean processMessage(Message message) { 4716 WifiConfiguration config; 4717 int netId; 4718 boolean ok; 4719 boolean didDisconnect; 4720 String bssid; 4721 String ssid; 4722 NetworkUpdateResult result; 4723 Set<Integer> removedNetworkIds; 4724 int reasonCode; 4725 boolean timedOut; 4726 logStateAndMessage(message, this); 4727 4728 switch (message.what) { 4729 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 4730 mWifiDiagnostics.captureBugReportData( 4731 WifiDiagnostics.REPORT_REASON_ASSOC_FAILURE); 4732 didBlackListBSSID = false; 4733 bssid = (String) message.obj; 4734 timedOut = message.arg1 > 0; 4735 reasonCode = message.arg2; 4736 Log.d(TAG, "Assocation Rejection event: bssid=" + bssid + " reason code=" 4737 + reasonCode + " timedOut=" + Boolean.toString(timedOut)); 4738 if (bssid == null || TextUtils.isEmpty(bssid)) { 4739 // If BSSID is null, use the target roam BSSID 4740 bssid = mTargetRoamBSSID; 4741 } 4742 if (bssid != null) { 4743 // If we have a BSSID, tell configStore to black list it 4744 didBlackListBSSID = mWifiConnectivityManager.trackBssid(bssid, false, 4745 reasonCode); 4746 } 4747 mWifiConfigManager.updateNetworkSelectionStatus(mTargetNetworkId, 4748 WifiConfiguration.NetworkSelectionStatus 4749 .DISABLED_ASSOCIATION_REJECTION); 4750 mSupplicantStateTracker.sendMessage(WifiMonitor.ASSOCIATION_REJECTION_EVENT); 4751 //If rejection occurred while Metrics is tracking a ConnnectionEvent, end it. 4752 reportConnectionAttemptEnd( 4753 WifiMetrics.ConnectionEvent.FAILURE_ASSOCIATION_REJECTION, 4754 WifiMetricsProto.ConnectionEvent.HLF_NONE); 4755 mWifiInjector.getWifiLastResortWatchdog() 4756 .noteConnectionFailureAndTriggerIfNeeded( 4757 getTargetSsid(), bssid, 4758 WifiLastResortWatchdog.FAILURE_CODE_ASSOCIATION); 4759 break; 4760 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 4761 mWifiDiagnostics.captureBugReportData( 4762 WifiDiagnostics.REPORT_REASON_AUTH_FAILURE); 4763 mSupplicantStateTracker.sendMessage(WifiMonitor.AUTHENTICATION_FAILURE_EVENT); 4764 // In case of wrong password, rely on SSID_TEMP_DISABLE event to update 4765 // the WifiConfigManager 4766 if ((message.arg2 != WifiMonitor.AUTHENTICATION_FAILURE_REASON_WRONG_PSWD) 4767 && (mTargetNetworkId != WifiConfiguration.INVALID_NETWORK_ID)) { 4768 mWifiConfigManager.updateNetworkSelectionStatus(mTargetNetworkId, 4769 WifiConfiguration.NetworkSelectionStatus 4770 .DISABLED_AUTHENTICATION_FAILURE); 4771 } 4772 //If failure occurred while Metrics is tracking a ConnnectionEvent, end it. 4773 reportConnectionAttemptEnd( 4774 WifiMetrics.ConnectionEvent.FAILURE_AUTHENTICATION_FAILURE, 4775 WifiMetricsProto.ConnectionEvent.HLF_NONE); 4776 mWifiInjector.getWifiLastResortWatchdog() 4777 .noteConnectionFailureAndTriggerIfNeeded( 4778 getTargetSsid(), mTargetRoamBSSID, 4779 WifiLastResortWatchdog.FAILURE_CODE_AUTHENTICATION); 4780 break; 4781 case WifiMonitor.SSID_TEMP_DISABLED: 4782 netId = lookupFrameworkNetworkId(message.arg1); 4783 Log.e(TAG, "Supplicant SSID temporary disabled:" 4784 + mWifiConfigManager.getConfiguredNetwork(netId)); 4785 mWifiConfigManager.updateNetworkSelectionStatus( 4786 netId, 4787 WifiConfiguration.NetworkSelectionStatus 4788 .DISABLED_AUTHENTICATION_FAILURE); 4789 reportConnectionAttemptEnd( 4790 WifiMetrics.ConnectionEvent.FAILURE_SSID_TEMP_DISABLED, 4791 WifiMetricsProto.ConnectionEvent.HLF_NONE); 4792 mWifiInjector.getWifiLastResortWatchdog() 4793 .noteConnectionFailureAndTriggerIfNeeded( 4794 getTargetSsid(), mTargetRoamBSSID, 4795 WifiLastResortWatchdog.FAILURE_CODE_AUTHENTICATION); 4796 break; 4797 case WifiMonitor.SSID_REENABLED: 4798 netId = lookupFrameworkNetworkId(message.arg1); 4799 Log.d(TAG, "Supplicant SSID reenable:" 4800 + mWifiConfigManager.getConfiguredNetwork(netId)); 4801 // Do not re-enable it in Quality Network Selection since framework has its own 4802 // Algorithm of disable/enable 4803 break; 4804 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 4805 SupplicantState state = handleSupplicantStateChange(message); 4806 // A driver/firmware hang can now put the interface in a down state. 4807 // We detect the interface going down and recover from it 4808 if (!SupplicantState.isDriverActive(state)) { 4809 if (mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) { 4810 handleNetworkDisconnect(); 4811 } 4812 log("Detected an interface down, restart driver"); 4813 // Rely on the fact that this will force us into killing supplicant and then 4814 // restart supplicant from a clean state. 4815 transitionTo(mSupplicantStoppingState); 4816 sendMessage(CMD_START_SUPPLICANT); 4817 break; 4818 } 4819 4820 // Supplicant can fail to report a NETWORK_DISCONNECTION_EVENT 4821 // when authentication times out after a successful connection, 4822 // we can figure this from the supplicant state. If supplicant 4823 // state is DISCONNECTED, but the mNetworkInfo says we are not 4824 // disconnected, we need to handle a disconnection 4825 if (!isLinkDebouncing() && state == SupplicantState.DISCONNECTED && 4826 mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) { 4827 if (mVerboseLoggingEnabled) { 4828 log("Missed CTRL-EVENT-DISCONNECTED, disconnect"); 4829 } 4830 handleNetworkDisconnect(); 4831 transitionTo(mDisconnectedState); 4832 } 4833 4834 // If we have COMPLETED a connection to a BSSID, start doing 4835 // DNAv4/DNAv6 -style probing for on-link neighbors of 4836 // interest (e.g. routers); harmless if none are configured. 4837 if (state == SupplicantState.COMPLETED) { 4838 mIpManager.confirmConfiguration(); 4839 } 4840 break; 4841 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 4842 if (message.arg1 == 1) { 4843 mWifiNative.disconnect(); 4844 mTemporarilyDisconnectWifi = true; 4845 } else { 4846 mWifiNative.reconnect(); 4847 mTemporarilyDisconnectWifi = false; 4848 } 4849 break; 4850 case CMD_ADD_OR_UPDATE_NETWORK: 4851 config = (WifiConfiguration) message.obj; 4852 result = mWifiConfigManager.addOrUpdateNetwork(config, message.sendingUid); 4853 if (!result.isSuccess()) { 4854 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 4855 } 4856 replyToMessage(message, message.what, result.getNetworkId()); 4857 break; 4858 case CMD_REMOVE_NETWORK: 4859 if (!deleteNetworkConfigAndSendReply(message, false)) { 4860 // failed to remove the config and caller was notified 4861 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 4862 break; 4863 } 4864 // we successfully deleted the network config 4865 netId = message.arg1; 4866 if (netId == mTargetNetworkId || netId == mLastNetworkId) { 4867 // Disconnect and let autojoin reselect a new network 4868 sendMessage(CMD_DISCONNECT); 4869 } 4870 break; 4871 case CMD_ENABLE_NETWORK: 4872 boolean disableOthers = message.arg2 == 1; 4873 netId = message.arg1; 4874 if (disableOthers) { 4875 // If the app has all the necessary permissions, this will trigger a connect 4876 // attempt. 4877 ok = connectToUserSelectNetwork(netId, message.sendingUid); 4878 } else { 4879 ok = mWifiConfigManager.enableNetwork(netId, false, message.sendingUid); 4880 } 4881 if (!ok) { 4882 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 4883 } 4884 replyToMessage(message, message.what, ok ? SUCCESS : FAILURE); 4885 break; 4886 case WifiManager.DISABLE_NETWORK: 4887 netId = message.arg1; 4888 if (mWifiConfigManager.disableNetwork(netId, message.sendingUid)) { 4889 replyToMessage(message, WifiManager.DISABLE_NETWORK_SUCCEEDED); 4890 if (netId == mTargetNetworkId || netId == mLastNetworkId) { 4891 // Disconnect and let autojoin reselect a new network 4892 sendMessage(CMD_DISCONNECT); 4893 } 4894 } else { 4895 loge("Failed to remove network"); 4896 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 4897 replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED, 4898 WifiManager.ERROR); 4899 } 4900 break; 4901 case CMD_DISABLE_EPHEMERAL_NETWORK: 4902 config = mWifiConfigManager.disableEphemeralNetwork((String)message.obj); 4903 if (config != null) { 4904 if (config.networkId == mTargetNetworkId 4905 || config.networkId == mLastNetworkId) { 4906 // Disconnect and let autojoin reselect a new network 4907 sendMessage(CMD_DISCONNECT); 4908 } 4909 } 4910 break; 4911 case CMD_SAVE_CONFIG: 4912 ok = mWifiConfigManager.saveToStore(true); 4913 replyToMessage(message, CMD_SAVE_CONFIG, ok ? SUCCESS : FAILURE); 4914 // Inform the backup manager about a data change 4915 mBackupManagerProxy.notifyDataChanged(); 4916 break; 4917 case WifiMonitor.SUP_REQUEST_IDENTITY: 4918 int supplicantNetworkId = message.arg2; 4919 netId = lookupFrameworkNetworkId(supplicantNetworkId); 4920 boolean identitySent = false; 4921 // For SIM & AKA/AKA' EAP method Only, get identity from ICC 4922 if (targetWificonfiguration != null 4923 && targetWificonfiguration.networkId == netId 4924 && TelephonyUtil.isSimConfig(targetWificonfiguration)) { 4925 String identity = 4926 TelephonyUtil.getSimIdentity(getTelephonyManager(), 4927 targetWificonfiguration); 4928 if (identity != null) { 4929 mWifiNative.simIdentityResponse(supplicantNetworkId, identity); 4930 identitySent = true; 4931 } else { 4932 Log.e(TAG, "Unable to retrieve identity from Telephony"); 4933 } 4934 } 4935 if (!identitySent) { 4936 // Supplicant lacks credentials to connect to that network, hence black list 4937 ssid = (String) message.obj; 4938 if (targetWificonfiguration != null && ssid != null 4939 && targetWificonfiguration.SSID != null 4940 && targetWificonfiguration.SSID.equals("\"" + ssid + "\"")) { 4941 mWifiConfigManager.updateNetworkSelectionStatus( 4942 targetWificonfiguration.networkId, 4943 WifiConfiguration.NetworkSelectionStatus 4944 .DISABLED_AUTHENTICATION_NO_CREDENTIALS); 4945 } 4946 mWifiNative.disconnect(); 4947 } 4948 break; 4949 case WifiMonitor.SUP_REQUEST_SIM_AUTH: 4950 logd("Received SUP_REQUEST_SIM_AUTH"); 4951 SimAuthRequestData requestData = (SimAuthRequestData) message.obj; 4952 if (requestData != null) { 4953 if (requestData.protocol == WifiEnterpriseConfig.Eap.SIM) { 4954 handleGsmAuthRequest(requestData); 4955 } else if (requestData.protocol == WifiEnterpriseConfig.Eap.AKA 4956 || requestData.protocol == WifiEnterpriseConfig.Eap.AKA_PRIME) { 4957 handle3GAuthRequest(requestData); 4958 } 4959 } else { 4960 loge("Invalid sim auth request"); 4961 } 4962 break; 4963 case CMD_GET_MATCHING_CONFIG: 4964 replyToMessage(message, message.what, 4965 mPasspointManager.getMatchingWifiConfig((ScanResult) message.obj)); 4966 break; 4967 case CMD_RECONNECT: 4968 mWifiConnectivityManager.forceConnectivityScan(); 4969 break; 4970 case CMD_REASSOCIATE: 4971 lastConnectAttemptTimestamp = mClock.getWallClockMillis(); 4972 mWifiNative.reassociate(); 4973 break; 4974 case CMD_RELOAD_TLS_AND_RECONNECT: 4975 if (mWifiConfigManager.needsUnlockedKeyStore()) { 4976 logd("Reconnecting to give a chance to un-connected TLS networks"); 4977 mWifiNative.disconnect(); 4978 lastConnectAttemptTimestamp = mClock.getWallClockMillis(); 4979 mWifiNative.reconnect(); 4980 } 4981 break; 4982 case CMD_START_ROAM: 4983 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 4984 return HANDLED; 4985 case CMD_START_CONNECT: 4986 /* connect command coming from auto-join */ 4987 netId = message.arg1; 4988 bssid = (String) message.obj; 4989 config = mWifiConfigManager.getConfiguredNetworkWithPassword(netId); 4990 logd("CMD_START_CONNECT sup state " 4991 + mSupplicantStateTracker.getSupplicantStateName() 4992 + " my state " + getCurrentState().getName() 4993 + " nid=" + Integer.toString(netId) 4994 + " roam=" + Boolean.toString(mAutoRoaming)); 4995 if (config == null) { 4996 loge("CMD_START_CONNECT and no config, bail out..."); 4997 break; 4998 } 4999 mTargetNetworkId = netId; 5000 setTargetBssid(config, bssid); 5001 5002 reportConnectionAttemptStart(config, mTargetRoamBSSID, 5003 WifiMetricsProto.ConnectionEvent.ROAM_UNRELATED); 5004 boolean shouldDisconnect = (getCurrentState() != mDisconnectedState); 5005 if (mWifiNative.connectToNetwork(config, shouldDisconnect)) { 5006 lastConnectAttemptTimestamp = mClock.getWallClockMillis(); 5007 targetWificonfiguration = config; 5008 mAutoRoaming = false; 5009 if (isRoaming() || isLinkDebouncing()) { 5010 transitionTo(mRoamingState); 5011 } else if (shouldDisconnect) { 5012 transitionTo(mDisconnectingState); 5013 } else { 5014 transitionTo(mDisconnectedState); 5015 } 5016 } else { 5017 loge("CMD_START_CONNECT Failed to start connection to network " + config); 5018 reportConnectionAttemptEnd( 5019 WifiMetrics.ConnectionEvent.FAILURE_CONNECT_NETWORK_FAILED, 5020 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5021 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 5022 WifiManager.ERROR); 5023 break; 5024 } 5025 break; 5026 case CMD_REMOVE_APP_CONFIGURATIONS: 5027 removedNetworkIds = 5028 mWifiConfigManager.removeNetworksForApp((ApplicationInfo) message.obj); 5029 if (removedNetworkIds.contains(mTargetNetworkId) || 5030 removedNetworkIds.contains(mLastNetworkId)) { 5031 // Disconnect and let autojoin reselect a new network. 5032 sendMessage(CMD_DISCONNECT); 5033 } 5034 break; 5035 case CMD_REMOVE_USER_CONFIGURATIONS: 5036 removedNetworkIds = 5037 mWifiConfigManager.removeNetworksForUser((Integer) message.arg1); 5038 if (removedNetworkIds.contains(mTargetNetworkId) || 5039 removedNetworkIds.contains(mLastNetworkId)) { 5040 // Disconnect and let autojoin reselect a new network. 5041 sendMessage(CMD_DISCONNECT); 5042 } 5043 break; 5044 case WifiManager.CONNECT_NETWORK: 5045 /** 5046 * The connect message can contain a network id passed as arg1 on message or 5047 * or a config passed as obj on message. 5048 * For a new network, a config is passed to create and connect. 5049 * For an existing network, a network id is passed 5050 */ 5051 netId = message.arg1; 5052 config = (WifiConfiguration) message.obj; 5053 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 5054 // New network addition. 5055 if (config != null) { 5056 result = mWifiConfigManager.addOrUpdateNetwork(config, message.sendingUid); 5057 if (!result.isSuccess()) { 5058 loge("CONNECT_NETWORK adding/updating config=" + config + " failed"); 5059 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5060 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 5061 WifiManager.ERROR); 5062 break; 5063 } 5064 netId = result.getNetworkId(); 5065 } 5066 if (!connectToUserSelectNetwork(netId, message.sendingUid)) { 5067 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5068 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 5069 WifiManager.NOT_AUTHORIZED); 5070 break; 5071 } 5072 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_SAVED, config); 5073 replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED); 5074 break; 5075 case WifiManager.SAVE_NETWORK: 5076 config = (WifiConfiguration) message.obj; 5077 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 5078 if (config == null) { 5079 loge("SAVE_NETWORK with null configuration" 5080 + mSupplicantStateTracker.getSupplicantStateName() 5081 + " my state " + getCurrentState().getName()); 5082 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5083 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 5084 WifiManager.ERROR); 5085 break; 5086 } 5087 result = mWifiConfigManager.addOrUpdateNetwork(config, message.sendingUid); 5088 if (!result.isSuccess()) { 5089 loge("SAVE_NETWORK adding/updating config=" + config + " failed"); 5090 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5091 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 5092 WifiManager.ERROR); 5093 break; 5094 } 5095 netId = result.getNetworkId(); 5096 if (mWifiInfo.getNetworkId() == netId) { 5097 if (result.hasIpChanged()) { 5098 // The currently connection configuration was changed 5099 // We switched from DHCP to static or from static to DHCP, or the 5100 // static IP address has changed. 5101 log("Reconfiguring IP on connection"); 5102 // TODO: clear addresses and disable IPv6 5103 // to simplify obtainingIpState. 5104 transitionTo(mObtainingIpState); 5105 } 5106 if (result.hasProxyChanged()) { 5107 log("Reconfiguring proxy on connection"); 5108 mIpManager.setHttpProxy( 5109 getCurrentWifiConfiguration().getHttpProxy()); 5110 } 5111 } else { 5112 if (!connectToUserSelectNetwork(netId, message.sendingUid)) { 5113 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5114 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 5115 WifiManager.NOT_AUTHORIZED); 5116 break; 5117 } 5118 } 5119 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_SAVED, config); 5120 replyToMessage(message, WifiManager.SAVE_NETWORK_SUCCEEDED); 5121 break; 5122 case WifiManager.FORGET_NETWORK: 5123 if (!deleteNetworkConfigAndSendReply(message, true)) { 5124 // Caller was notified of failure, nothing else to do 5125 break; 5126 } 5127 // the network was deleted 5128 netId = message.arg1; 5129 if (netId == mTargetNetworkId || netId == mLastNetworkId) { 5130 // Disconnect and let autojoin reselect a new network 5131 sendMessage(CMD_DISCONNECT); 5132 } 5133 break; 5134 case WifiManager.START_WPS: 5135 WpsInfo wpsInfo = (WpsInfo) message.obj; 5136 WpsResult wpsResult = new WpsResult(); 5137 // TODO(b/32898136): Not needed when we start deleting networks from supplicant 5138 // on disconnect. 5139 if (!mWifiNative.removeAllNetworks()) { 5140 loge("Failed to remove networks before WPS"); 5141 } 5142 switch (wpsInfo.setup) { 5143 case WpsInfo.PBC: 5144 if (mWifiNative.startWpsPbc(wpsInfo.BSSID)) { 5145 wpsResult.status = WpsResult.Status.SUCCESS; 5146 } else { 5147 Log.e(TAG, "Failed to start WPS push button configuration"); 5148 wpsResult.status = WpsResult.Status.FAILURE; 5149 } 5150 break; 5151 case WpsInfo.KEYPAD: 5152 if (mWifiNative.startWpsRegistrar(wpsInfo.BSSID, wpsInfo.pin)) { 5153 wpsResult.status = WpsResult.Status.SUCCESS; 5154 } else { 5155 Log.e(TAG, "Failed to start WPS push button configuration"); 5156 wpsResult.status = WpsResult.Status.FAILURE; 5157 } 5158 break; 5159 case WpsInfo.DISPLAY: 5160 wpsResult.pin = mWifiNative.startWpsPinDisplay(wpsInfo.BSSID); 5161 if (!TextUtils.isEmpty(wpsResult.pin)) { 5162 wpsResult.status = WpsResult.Status.SUCCESS; 5163 } else { 5164 Log.e(TAG, "Failed to start WPS pin method configuration"); 5165 wpsResult.status = WpsResult.Status.FAILURE; 5166 } 5167 break; 5168 default: 5169 wpsResult = new WpsResult(Status.FAILURE); 5170 loge("Invalid setup for WPS"); 5171 break; 5172 } 5173 if (wpsResult.status == Status.SUCCESS) { 5174 replyToMessage(message, WifiManager.START_WPS_SUCCEEDED, wpsResult); 5175 transitionTo(mWpsRunningState); 5176 } else { 5177 loge("Failed to start WPS with config " + wpsInfo.toString()); 5178 replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.ERROR); 5179 } 5180 break; 5181 case CMD_ASSOCIATED_BSSID: 5182 // This is where we can confirm the connection BSSID. Use it to find the 5183 // right ScanDetail to populate metrics. 5184 String someBssid = (String) message.obj; 5185 if (someBssid != null) { 5186 // Get the ScanDetail associated with this BSSID. 5187 ScanDetailCache scanDetailCache = 5188 mWifiConfigManager.getScanDetailCacheForNetwork(mTargetNetworkId); 5189 if (scanDetailCache != null) { 5190 mWifiMetrics.setConnectionScanDetail(scanDetailCache.getScanDetail( 5191 someBssid)); 5192 } 5193 } 5194 return NOT_HANDLED; 5195 case WifiMonitor.NETWORK_CONNECTION_EVENT: 5196 if (mVerboseLoggingEnabled) log("Network connection established"); 5197 mLastNetworkId = lookupFrameworkNetworkId(message.arg1); 5198 mLastBssid = (String) message.obj; 5199 reasonCode = message.arg2; 5200 // TODO: This check should not be needed after WifiStateMachinePrime refactor. 5201 // Currently, the last connected network configuration is left in 5202 // wpa_supplicant, this may result in wpa_supplicant initiating connection 5203 // to it after a config store reload. Hence the old network Id lookups may not 5204 // work, so disconnect the network and let network selector reselect a new 5205 // network. 5206 if (getCurrentWifiConfiguration() != null) { 5207 mWifiInfo.setBSSID(mLastBssid); 5208 mWifiInfo.setNetworkId(mLastNetworkId); 5209 mWifiConnectivityManager.trackBssid(mLastBssid, true, reasonCode); 5210 sendNetworkStateChangeBroadcast(mLastBssid); 5211 transitionTo(mObtainingIpState); 5212 } else { 5213 logw("Connected to unknown networkId " + mLastNetworkId 5214 + ", disconnecting..."); 5215 sendMessage(CMD_DISCONNECT); 5216 } 5217 break; 5218 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 5219 // Calling handleNetworkDisconnect here is redundant because we might already 5220 // have called it when leaving L2ConnectedState to go to disconnecting state 5221 // or thru other path 5222 // We should normally check the mWifiInfo or mLastNetworkId so as to check 5223 // if they are valid, and only in this case call handleNEtworkDisconnect, 5224 // TODO: this should be fixed for a L MR release 5225 // The side effect of calling handleNetworkDisconnect twice is that a bunch of 5226 // idempotent commands are executed twice (stopping Dhcp, enabling the SPS mode 5227 // at the chip etc... 5228 if (mVerboseLoggingEnabled) log("ConnectModeState: Network connection lost "); 5229 handleNetworkDisconnect(); 5230 transitionTo(mDisconnectedState); 5231 break; 5232 case CMD_QUERY_OSU_ICON: 5233 mPasspointManager.queryPasspointIcon( 5234 ((Bundle) message.obj).getLong(EXTRA_OSU_ICON_QUERY_BSSID), 5235 ((Bundle) message.obj).getString(EXTRA_OSU_ICON_QUERY_FILENAME)); 5236 break; 5237 case CMD_MATCH_PROVIDER_NETWORK: 5238 // TODO(b/31065385): Passpoint config management. 5239 replyToMessage(message, message.what, 0); 5240 break; 5241 case CMD_REMOVE_PASSPOINT_CONFIG: 5242 String fqdn = (String) message.obj; 5243 if (mPasspointManager.removeProvider(fqdn)) { 5244 if (isProviderOwnedNetwork(mTargetNetworkId, fqdn) 5245 || isProviderOwnedNetwork(mLastNetworkId, fqdn)) { 5246 logd("Disconnect from current network since its provider is removed"); 5247 sendMessage(CMD_DISCONNECT); 5248 } 5249 replyToMessage(message, message.what, SUCCESS); 5250 } else { 5251 replyToMessage(message, message.what, FAILURE); 5252 } 5253 break; 5254 case CMD_ENABLE_P2P: 5255 p2pSendMessage(WifiStateMachine.CMD_ENABLE_P2P); 5256 break; 5257 default: 5258 return NOT_HANDLED; 5259 } 5260 return HANDLED; 5261 } 5262 } 5263 5264 private void updateCapabilities(WifiConfiguration config) { 5265 NetworkCapabilities networkCapabilities = new NetworkCapabilities(mDfltNetworkCapabilities); 5266 if (config != null) { 5267 if (config.ephemeral) { 5268 networkCapabilities.removeCapability( 5269 NetworkCapabilities.NET_CAPABILITY_TRUSTED); 5270 } else { 5271 networkCapabilities.addCapability( 5272 NetworkCapabilities.NET_CAPABILITY_TRUSTED); 5273 } 5274 5275 networkCapabilities.setSignalStrength( 5276 (mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI) 5277 ? mWifiInfo.getRssi() 5278 : NetworkCapabilities.SIGNAL_STRENGTH_UNSPECIFIED); 5279 } 5280 5281 if (mWifiInfo.getMeteredHint()) { 5282 networkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED); 5283 } 5284 5285 mNetworkAgent.sendNetworkCapabilities(networkCapabilities); 5286 } 5287 5288 /** 5289 * Checks if the given network |networkdId| is provided by the given Passpoint provider with 5290 * |providerFqdn|. 5291 * 5292 * @param networkId The ID of the network to check 5293 * @param providerFqdn The FQDN of the Passpoint provider 5294 * @return true if the given network is provided by the given Passpoint provider 5295 */ 5296 private boolean isProviderOwnedNetwork(int networkId, String providerFqdn) { 5297 if (networkId == WifiConfiguration.INVALID_NETWORK_ID) { 5298 return false; 5299 } 5300 WifiConfiguration config = mWifiConfigManager.getConfiguredNetwork(networkId); 5301 if (config == null) { 5302 return false; 5303 } 5304 return TextUtils.equals(config.FQDN, providerFqdn); 5305 } 5306 5307 private class WifiNetworkAgent extends NetworkAgent { 5308 public WifiNetworkAgent(Looper l, Context c, String TAG, NetworkInfo ni, 5309 NetworkCapabilities nc, LinkProperties lp, int score, NetworkMisc misc) { 5310 super(l, c, TAG, ni, nc, lp, score, misc); 5311 } 5312 5313 @Override 5314 protected void unwanted() { 5315 // Ignore if we're not the current networkAgent. 5316 if (this != mNetworkAgent) return; 5317 if (mVerboseLoggingEnabled) { 5318 log("WifiNetworkAgent -> Wifi unwanted score " + Integer.toString(mWifiInfo.score)); 5319 } 5320 unwantedNetwork(NETWORK_STATUS_UNWANTED_DISCONNECT); 5321 } 5322 5323 @Override 5324 protected void networkStatus(int status, String redirectUrl) { 5325 if (this != mNetworkAgent) return; 5326 if (status == NetworkAgent.INVALID_NETWORK) { 5327 if (mVerboseLoggingEnabled) { 5328 log("WifiNetworkAgent -> Wifi networkStatus invalid, score=" 5329 + Integer.toString(mWifiInfo.score)); 5330 } 5331 unwantedNetwork(NETWORK_STATUS_UNWANTED_VALIDATION_FAILED); 5332 } else if (status == NetworkAgent.VALID_NETWORK) { 5333 if (mVerboseLoggingEnabled) { 5334 log("WifiNetworkAgent -> Wifi networkStatus valid, score= " 5335 + Integer.toString(mWifiInfo.score)); 5336 } 5337 doNetworkStatus(status); 5338 } 5339 } 5340 5341 @Override 5342 protected void saveAcceptUnvalidated(boolean accept) { 5343 if (this != mNetworkAgent) return; 5344 WifiStateMachine.this.sendMessage(CMD_ACCEPT_UNVALIDATED, accept ? 1 : 0); 5345 } 5346 5347 @Override 5348 protected void startPacketKeepalive(Message msg) { 5349 WifiStateMachine.this.sendMessage( 5350 CMD_START_IP_PACKET_OFFLOAD, msg.arg1, msg.arg2, msg.obj); 5351 } 5352 5353 @Override 5354 protected void stopPacketKeepalive(Message msg) { 5355 WifiStateMachine.this.sendMessage( 5356 CMD_STOP_IP_PACKET_OFFLOAD, msg.arg1, msg.arg2, msg.obj); 5357 } 5358 5359 @Override 5360 protected void setSignalStrengthThresholds(int[] thresholds) { 5361 // 0. If there are no thresholds, or if the thresholds are invalid, stop RSSI monitoring. 5362 // 1. Tell the hardware to start RSSI monitoring here, possibly adding MIN_VALUE and 5363 // MAX_VALUE at the start/end of the thresholds array if necessary. 5364 // 2. Ensure that when the hardware event fires, we fetch the RSSI from the hardware 5365 // event, call mWifiInfo.setRssi() with it, and call updateCapabilities(), and then 5366 // re-arm the hardware event. This needs to be done on the state machine thread to 5367 // avoid race conditions. The RSSI used to re-arm the event (and perhaps also the one 5368 // sent in the NetworkCapabilities) must be the one received from the hardware event 5369 // received, or we might skip callbacks. 5370 // 3. Ensure that when we disconnect, RSSI monitoring is stopped. 5371 log("Received signal strength thresholds: " + Arrays.toString(thresholds)); 5372 if (thresholds.length == 0) { 5373 WifiStateMachine.this.sendMessage(CMD_STOP_RSSI_MONITORING_OFFLOAD, 5374 mWifiInfo.getRssi()); 5375 return; 5376 } 5377 int [] rssiVals = Arrays.copyOf(thresholds, thresholds.length + 2); 5378 rssiVals[rssiVals.length - 2] = Byte.MIN_VALUE; 5379 rssiVals[rssiVals.length - 1] = Byte.MAX_VALUE; 5380 Arrays.sort(rssiVals); 5381 byte[] rssiRange = new byte[rssiVals.length]; 5382 for (int i = 0; i < rssiVals.length; i++) { 5383 int val = rssiVals[i]; 5384 if (val <= Byte.MAX_VALUE && val >= Byte.MIN_VALUE) { 5385 rssiRange[i] = (byte) val; 5386 } else { 5387 Log.e(TAG, "Illegal value " + val + " for RSSI thresholds: " 5388 + Arrays.toString(rssiVals)); 5389 WifiStateMachine.this.sendMessage(CMD_STOP_RSSI_MONITORING_OFFLOAD, 5390 mWifiInfo.getRssi()); 5391 return; 5392 } 5393 } 5394 // TODO: Do we quash rssi values in this sorted array which are very close? 5395 mRssiRanges = rssiRange; 5396 WifiStateMachine.this.sendMessage(CMD_START_RSSI_MONITORING_OFFLOAD, 5397 mWifiInfo.getRssi()); 5398 } 5399 5400 @Override 5401 protected void preventAutomaticReconnect() { 5402 if (this != mNetworkAgent) return; 5403 unwantedNetwork(NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN); 5404 } 5405 } 5406 5407 void unwantedNetwork(int reason) { 5408 sendMessage(CMD_UNWANTED_NETWORK, reason); 5409 } 5410 5411 void doNetworkStatus(int status) { 5412 sendMessage(CMD_NETWORK_STATUS, status); 5413 } 5414 5415 // rfc4186 & rfc4187: 5416 // create Permanent Identity base on IMSI, 5417 // identity = usernam@realm 5418 // with username = prefix | IMSI 5419 // and realm is derived MMC/MNC tuple according 3GGP spec(TS23.003) 5420 private String buildIdentity(int eapMethod, String imsi, String mccMnc) { 5421 String mcc; 5422 String mnc; 5423 String prefix; 5424 5425 if (imsi == null || imsi.isEmpty()) 5426 return ""; 5427 5428 if (eapMethod == WifiEnterpriseConfig.Eap.SIM) 5429 prefix = "1"; 5430 else if (eapMethod == WifiEnterpriseConfig.Eap.AKA) 5431 prefix = "0"; 5432 else if (eapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME) 5433 prefix = "6"; 5434 else // not a valide EapMethod 5435 return ""; 5436 5437 /* extract mcc & mnc from mccMnc */ 5438 if (mccMnc != null && !mccMnc.isEmpty()) { 5439 mcc = mccMnc.substring(0, 3); 5440 mnc = mccMnc.substring(3); 5441 if (mnc.length() == 2) 5442 mnc = "0" + mnc; 5443 } else { 5444 // extract mcc & mnc from IMSI, assume mnc size is 3 5445 mcc = imsi.substring(0, 3); 5446 mnc = imsi.substring(3, 6); 5447 } 5448 5449 return prefix + imsi + "@wlan.mnc" + mnc + ".mcc" + mcc + ".3gppnetwork.org"; 5450 } 5451 5452 boolean startScanForConfiguration(WifiConfiguration config) { 5453 if (config == null) 5454 return false; 5455 5456 // We are still seeing a fairly high power consumption triggered by autojoin scans 5457 // Hence do partial scans only for PSK configuration that are roamable since the 5458 // primary purpose of the partial scans is roaming. 5459 // Full badn scans with exponential backoff for the purpose or extended roaming and 5460 // network switching are performed unconditionally. 5461 ScanDetailCache scanDetailCache = 5462 mWifiConfigManager.getScanDetailCacheForNetwork(config.networkId); 5463 if (scanDetailCache == null 5464 || !config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK) 5465 || scanDetailCache.size() > 6) { 5466 //return true but to not trigger the scan 5467 return true; 5468 } 5469 Set<Integer> freqs = 5470 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 5471 config.networkId, ONE_HOUR_MILLI, mWifiInfo.getFrequency()); 5472 if (freqs != null && freqs.size() != 0) { 5473 //if (mVerboseLoggingEnabled) { 5474 logd("starting scan for " + config.configKey() + " with " + freqs); 5475 //} 5476 List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks = new ArrayList<>(); 5477 if (config.hiddenSSID) { 5478 hiddenNetworks.add(new WifiScanner.ScanSettings.HiddenNetwork(config.SSID)); 5479 } 5480 // Call wifi native to start the scan 5481 if (startScanNative(freqs, hiddenNetworks, WIFI_WORK_SOURCE)) { 5482 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK; 5483 } else { 5484 // used for debug only, mark scan as failed 5485 messageHandlingStatus = MESSAGE_HANDLING_STATUS_HANDLING_ERROR; 5486 } 5487 return true; 5488 } else { 5489 if (mVerboseLoggingEnabled) logd("no channels for " + config.configKey()); 5490 return false; 5491 } 5492 } 5493 5494 class L2ConnectedState extends State { 5495 @Override 5496 public void enter() { 5497 mRssiPollToken++; 5498 if (mEnableRssiPolling) { 5499 sendMessage(CMD_RSSI_POLL, mRssiPollToken, 0); 5500 } 5501 if (mNetworkAgent != null) { 5502 loge("Have NetworkAgent when entering L2Connected"); 5503 setNetworkDetailedState(DetailedState.DISCONNECTED); 5504 } 5505 setNetworkDetailedState(DetailedState.CONNECTING); 5506 5507 mNetworkAgent = new WifiNetworkAgent(getHandler().getLooper(), mContext, 5508 "WifiNetworkAgent", mNetworkInfo, mNetworkCapabilitiesFilter, 5509 mLinkProperties, 60, mNetworkMisc); 5510 5511 // We must clear the config BSSID, as the wifi chipset may decide to roam 5512 // from this point on and having the BSSID specified in the network block would 5513 // cause the roam to faile and the device to disconnect 5514 clearTargetBssid("L2ConnectedState"); 5515 mCountryCode.setReadyForChange(false); 5516 mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_ASSOCIATED); 5517 } 5518 5519 @Override 5520 public void exit() { 5521 mIpManager.stop(); 5522 5523 // This is handled by receiving a NETWORK_DISCONNECTION_EVENT in ConnectModeState 5524 // Bug: 15347363 5525 // For paranoia's sake, call handleNetworkDisconnect 5526 // only if BSSID is null or last networkId 5527 // is not invalid. 5528 if (mVerboseLoggingEnabled) { 5529 StringBuilder sb = new StringBuilder(); 5530 sb.append("leaving L2ConnectedState state nid=" + Integer.toString(mLastNetworkId)); 5531 if (mLastBssid !=null) { 5532 sb.append(" ").append(mLastBssid); 5533 } 5534 } 5535 if (mLastBssid != null || mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 5536 handleNetworkDisconnect(); 5537 } 5538 mCountryCode.setReadyForChange(true); 5539 mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_DISCONNECTED); 5540 } 5541 5542 @Override 5543 public boolean processMessage(Message message) { 5544 logStateAndMessage(message, this); 5545 5546 switch (message.what) { 5547 case DhcpClient.CMD_PRE_DHCP_ACTION: 5548 handlePreDhcpSetup(); 5549 break; 5550 case DhcpClient.CMD_PRE_DHCP_ACTION_COMPLETE: 5551 mIpManager.completedPreDhcpAction(); 5552 break; 5553 case DhcpClient.CMD_POST_DHCP_ACTION: 5554 handlePostDhcpSetup(); 5555 // We advance to mConnectedState because IpManager will also send a 5556 // CMD_IPV4_PROVISIONING_SUCCESS message, which calls handleIPv4Success(), 5557 // which calls updateLinkProperties, which then sends 5558 // CMD_IP_CONFIGURATION_SUCCESSFUL. 5559 // 5560 // In the event of failure, we transition to mDisconnectingState 5561 // similarly--via messages sent back from IpManager. 5562 break; 5563 case CMD_IPV4_PROVISIONING_SUCCESS: { 5564 handleIPv4Success((DhcpResults) message.obj); 5565 sendNetworkStateChangeBroadcast(mLastBssid); 5566 break; 5567 } 5568 case CMD_IPV4_PROVISIONING_FAILURE: { 5569 handleIPv4Failure(); 5570 break; 5571 } 5572 case CMD_IP_CONFIGURATION_SUCCESSFUL: 5573 handleSuccessfulIpConfiguration(); 5574 reportConnectionAttemptEnd( 5575 WifiMetrics.ConnectionEvent.FAILURE_NONE, 5576 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5577 sendConnectedState(); 5578 transitionTo(mConnectedState); 5579 break; 5580 case CMD_IP_CONFIGURATION_LOST: 5581 // Get Link layer stats so that we get fresh tx packet counters. 5582 getWifiLinkLayerStats(); 5583 handleIpConfigurationLost(); 5584 reportConnectionAttemptEnd( 5585 WifiMetrics.ConnectionEvent.FAILURE_DHCP, 5586 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5587 transitionTo(mDisconnectingState); 5588 break; 5589 case CMD_IP_REACHABILITY_LOST: 5590 if (mVerboseLoggingEnabled && message.obj != null) log((String) message.obj); 5591 if (mIpReachabilityDisconnectEnabled) { 5592 handleIpReachabilityLost(); 5593 transitionTo(mDisconnectingState); 5594 } else { 5595 logd("CMD_IP_REACHABILITY_LOST but disconnect disabled -- ignore"); 5596 } 5597 break; 5598 case CMD_DISCONNECT: 5599 mWifiNative.disconnect(); 5600 transitionTo(mDisconnectingState); 5601 break; 5602 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 5603 if (message.arg1 == 1) { 5604 mWifiNative.disconnect(); 5605 mTemporarilyDisconnectWifi = true; 5606 transitionTo(mDisconnectingState); 5607 } 5608 break; 5609 case CMD_SET_OPERATIONAL_MODE: 5610 if (message.arg1 != CONNECT_MODE) { 5611 sendMessage(CMD_DISCONNECT); 5612 deferMessage(message); 5613 } 5614 break; 5615 /* Ignore connection to same network */ 5616 case WifiManager.CONNECT_NETWORK: 5617 int netId = message.arg1; 5618 if (mWifiInfo.getNetworkId() == netId) { 5619 replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED); 5620 break; 5621 } 5622 return NOT_HANDLED; 5623 case WifiMonitor.NETWORK_CONNECTION_EVENT: 5624 mWifiInfo.setBSSID((String) message.obj); 5625 mLastNetworkId = lookupFrameworkNetworkId(message.arg1); 5626 mWifiInfo.setNetworkId(mLastNetworkId); 5627 if(!mLastBssid.equals(message.obj)) { 5628 mLastBssid = (String) message.obj; 5629 sendNetworkStateChangeBroadcast(mLastBssid); 5630 } 5631 break; 5632 case CMD_RSSI_POLL: 5633 if (message.arg1 == mRssiPollToken) { 5634 if (mEnableChipWakeUpWhenAssociated) { 5635 if (mVerboseLoggingEnabled) { 5636 log(" get link layer stats " + mWifiLinkLayerStatsSupported); 5637 } 5638 WifiLinkLayerStats stats = getWifiLinkLayerStats(); 5639 if (stats != null) { 5640 // Sanity check the results provided by driver 5641 if (mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI 5642 && (stats.rssi_mgmt == 0 5643 || stats.beacon_rx == 0)) { 5644 stats = null; 5645 } 5646 } 5647 // Get Info and continue polling 5648 fetchRssiLinkSpeedAndFrequencyNative(); 5649 // Send the update score to network agent. 5650 mWifiScoreReport.calculateAndReportScore( 5651 mWifiInfo, mNetworkAgent, mAggressiveHandover, 5652 mWifiMetrics); 5653 } 5654 sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, 5655 mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS); 5656 if (mVerboseLoggingEnabled) sendRssiChangeBroadcast(mWifiInfo.getRssi()); 5657 } else { 5658 // Polling has completed 5659 } 5660 break; 5661 case CMD_ENABLE_RSSI_POLL: 5662 cleanWifiScore(); 5663 if (mEnableRssiPollWhenAssociated) { 5664 mEnableRssiPolling = (message.arg1 == 1); 5665 } else { 5666 mEnableRssiPolling = false; 5667 } 5668 mRssiPollToken++; 5669 if (mEnableRssiPolling) { 5670 // First poll 5671 fetchRssiLinkSpeedAndFrequencyNative(); 5672 sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, 5673 mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS); 5674 } 5675 break; 5676 case WifiManager.RSSI_PKTCNT_FETCH: 5677 RssiPacketCountInfo info = new RssiPacketCountInfo(); 5678 fetchRssiLinkSpeedAndFrequencyNative(); 5679 info.rssi = mWifiInfo.getRssi(); 5680 WifiNative.TxPacketCounters counters = mWifiNative.getTxPacketCounters(); 5681 if (counters != null) { 5682 info.txgood = counters.txSucceeded; 5683 info.txbad = counters.txFailed; 5684 replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED, info); 5685 } else { 5686 replyToMessage(message, 5687 WifiManager.RSSI_PKTCNT_FETCH_FAILED, WifiManager.ERROR); 5688 } 5689 break; 5690 case CMD_DELAYED_NETWORK_DISCONNECT: 5691 if (!isLinkDebouncing()) { 5692 5693 // Ignore if we are not debouncing 5694 logd("CMD_DELAYED_NETWORK_DISCONNECT and not debouncing - ignore " 5695 + message.arg1); 5696 return HANDLED; 5697 } else { 5698 logd("CMD_DELAYED_NETWORK_DISCONNECT and debouncing - disconnect " 5699 + message.arg1); 5700 5701 mIsLinkDebouncing = false; 5702 // If we are still debouncing while this message comes, 5703 // it means we were not able to reconnect within the alloted time 5704 // = LINK_FLAPPING_DEBOUNCE_MSEC 5705 // and thus, trigger a real disconnect 5706 handleNetworkDisconnect(); 5707 transitionTo(mDisconnectedState); 5708 } 5709 break; 5710 case CMD_ASSOCIATED_BSSID: 5711 if ((String) message.obj == null) { 5712 logw("Associated command w/o BSSID"); 5713 break; 5714 } 5715 mLastBssid = (String) message.obj; 5716 if (mLastBssid != null && (mWifiInfo.getBSSID() == null 5717 || !mLastBssid.equals(mWifiInfo.getBSSID()))) { 5718 mWifiInfo.setBSSID((String) message.obj); 5719 sendNetworkStateChangeBroadcast(mLastBssid); 5720 } 5721 break; 5722 case CMD_START_RSSI_MONITORING_OFFLOAD: 5723 case CMD_RSSI_THRESHOLD_BREACH: 5724 byte currRssi = (byte) message.arg1; 5725 processRssiThreshold(currRssi, message.what); 5726 break; 5727 case CMD_STOP_RSSI_MONITORING_OFFLOAD: 5728 stopRssiMonitoringOffload(); 5729 break; 5730 case CMD_RESET_SIM_NETWORKS: 5731 if (message.arg1 == 0 // sim was removed 5732 && mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 5733 WifiConfiguration config = 5734 mWifiConfigManager.getConfiguredNetwork(mLastNetworkId); 5735 if (TelephonyUtil.isSimConfig(config)) { 5736 mWifiNative.disconnect(); 5737 transitionTo(mDisconnectingState); 5738 } 5739 } 5740 /* allow parent state to reset data for other networks */ 5741 return NOT_HANDLED; 5742 default: 5743 return NOT_HANDLED; 5744 } 5745 5746 return HANDLED; 5747 } 5748 } 5749 5750 class ObtainingIpState extends State { 5751 @Override 5752 public void enter() { 5753 WifiConfiguration currentConfig = getCurrentWifiConfiguration(); 5754 boolean isUsingStaticIp = 5755 (currentConfig.getIpAssignment() == IpConfiguration.IpAssignment.STATIC); 5756 if (mVerboseLoggingEnabled) { 5757 String key = ""; 5758 if (getCurrentWifiConfiguration() != null) { 5759 key = getCurrentWifiConfiguration().configKey(); 5760 } 5761 log("enter ObtainingIpState netId=" + Integer.toString(mLastNetworkId) 5762 + " " + key + " " 5763 + " roam=" + mAutoRoaming 5764 + " static=" + isUsingStaticIp); 5765 } 5766 5767 // Reset link Debouncing, indicating we have successfully re-connected to the AP 5768 // We might still be roaming 5769 mIsLinkDebouncing = false; 5770 5771 // Send event to CM & network change broadcast 5772 setNetworkDetailedState(DetailedState.OBTAINING_IPADDR); 5773 5774 // We must clear the config BSSID, as the wifi chipset may decide to roam 5775 // from this point on and having the BSSID specified in the network block would 5776 // cause the roam to fail and the device to disconnect. 5777 clearTargetBssid("ObtainingIpAddress"); 5778 5779 // Stop IpManager in case we're switching from DHCP to static 5780 // configuration or vice versa. 5781 // 5782 // TODO: Only ever enter this state the first time we connect to a 5783 // network, never on switching between static configuration and 5784 // DHCP. When we transition from static configuration to DHCP in 5785 // particular, we must tell ConnectivityService that we're 5786 // disconnected, because DHCP might take a long time during which 5787 // connectivity APIs such as getActiveNetworkInfo should not return 5788 // CONNECTED. 5789 stopIpManager(); 5790 5791 mIpManager.setHttpProxy(currentConfig.getHttpProxy()); 5792 if (!TextUtils.isEmpty(mTcpBufferSizes)) { 5793 mIpManager.setTcpBufferSizes(mTcpBufferSizes); 5794 } 5795 5796 if (!isUsingStaticIp) { 5797 final IpManager.ProvisioningConfiguration prov = 5798 IpManager.buildProvisioningConfiguration() 5799 .withPreDhcpAction() 5800 .withApfCapabilities(mWifiNative.getApfCapabilities()) 5801 .build(); 5802 mIpManager.startProvisioning(prov); 5803 // Get Link layer stats so as we get fresh tx packet counters 5804 getWifiLinkLayerStats(); 5805 } else { 5806 StaticIpConfiguration config = currentConfig.getStaticIpConfiguration(); 5807 if (config.ipAddress == null) { 5808 logd("Static IP lacks address"); 5809 sendMessage(CMD_IPV4_PROVISIONING_FAILURE); 5810 } else { 5811 final IpManager.ProvisioningConfiguration prov = 5812 IpManager.buildProvisioningConfiguration() 5813 .withStaticConfiguration(config) 5814 .withApfCapabilities(mWifiNative.getApfCapabilities()) 5815 .build(); 5816 mIpManager.startProvisioning(prov); 5817 } 5818 } 5819 } 5820 5821 @Override 5822 public boolean processMessage(Message message) { 5823 logStateAndMessage(message, this); 5824 5825 switch(message.what) { 5826 case CMD_START_CONNECT: 5827 case CMD_START_ROAM: 5828 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5829 break; 5830 case WifiManager.SAVE_NETWORK: 5831 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 5832 deferMessage(message); 5833 break; 5834 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 5835 reportConnectionAttemptEnd( 5836 WifiMetrics.ConnectionEvent.FAILURE_NETWORK_DISCONNECTION, 5837 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5838 return NOT_HANDLED; 5839 case CMD_SET_HIGH_PERF_MODE: 5840 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 5841 deferMessage(message); 5842 break; 5843 /* Defer scan request since we should not switch to other channels at DHCP */ 5844 case CMD_START_SCAN: 5845 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 5846 deferMessage(message); 5847 break; 5848 default: 5849 return NOT_HANDLED; 5850 } 5851 return HANDLED; 5852 } 5853 } 5854 5855 private void sendConnectedState() { 5856 // If this network was explicitly selected by the user, evaluate whether to call 5857 // explicitlySelected() so the system can treat it appropriately. 5858 WifiConfiguration config = getCurrentWifiConfiguration(); 5859 if (mWifiConfigManager.getLastSelectedNetwork() == config.networkId) { 5860 boolean prompt = 5861 mWifiPermissionsUtil.checkConfigOverridePermission(config.lastConnectUid); 5862 if (mVerboseLoggingEnabled) { 5863 log("Network selected by UID " + config.lastConnectUid + " prompt=" + prompt); 5864 } 5865 if (prompt) { 5866 // Selected by the user via Settings or QuickSettings. If this network has Internet 5867 // access, switch to it. Otherwise, switch to it only if the user confirms that they 5868 // really want to switch, or has already confirmed and selected "Don't ask again". 5869 if (mVerboseLoggingEnabled) { 5870 log("explictlySelected acceptUnvalidated=" + config.noInternetAccessExpected); 5871 } 5872 mNetworkAgent.explicitlySelected(config.noInternetAccessExpected); 5873 } 5874 } 5875 5876 setNetworkDetailedState(DetailedState.CONNECTED); 5877 mWifiConfigManager.updateNetworkAfterConnect(mLastNetworkId); 5878 sendNetworkStateChangeBroadcast(mLastBssid); 5879 } 5880 5881 class RoamingState extends State { 5882 boolean mAssociated; 5883 @Override 5884 public void enter() { 5885 if (mVerboseLoggingEnabled) { 5886 log("RoamingState Enter" 5887 + " mScreenOn=" + mScreenOn ); 5888 } 5889 5890 // Make sure we disconnect if roaming fails 5891 roamWatchdogCount++; 5892 logd("Start Roam Watchdog " + roamWatchdogCount); 5893 sendMessageDelayed(obtainMessage(CMD_ROAM_WATCHDOG_TIMER, 5894 roamWatchdogCount, 0), ROAM_GUARD_TIMER_MSEC); 5895 mAssociated = false; 5896 } 5897 @Override 5898 public boolean processMessage(Message message) { 5899 logStateAndMessage(message, this); 5900 WifiConfiguration config; 5901 switch (message.what) { 5902 case CMD_IP_CONFIGURATION_LOST: 5903 config = getCurrentWifiConfiguration(); 5904 if (config != null) { 5905 mWifiDiagnostics.captureBugReportData( 5906 WifiDiagnostics.REPORT_REASON_AUTOROAM_FAILURE); 5907 } 5908 return NOT_HANDLED; 5909 case CMD_UNWANTED_NETWORK: 5910 if (mVerboseLoggingEnabled) { 5911 log("Roaming and CS doesnt want the network -> ignore"); 5912 } 5913 return HANDLED; 5914 case CMD_SET_OPERATIONAL_MODE: 5915 if (message.arg1 != CONNECT_MODE) { 5916 deferMessage(message); 5917 } 5918 break; 5919 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 5920 /** 5921 * If we get a SUPPLICANT_STATE_CHANGE_EVENT indicating a DISCONNECT 5922 * before NETWORK_DISCONNECTION_EVENT 5923 * And there is an associated BSSID corresponding to our target BSSID, then 5924 * we have missed the network disconnection, transition to mDisconnectedState 5925 * and handle the rest of the events there. 5926 */ 5927 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 5928 if (stateChangeResult.state == SupplicantState.DISCONNECTED 5929 || stateChangeResult.state == SupplicantState.INACTIVE 5930 || stateChangeResult.state == SupplicantState.INTERFACE_DISABLED) { 5931 if (mVerboseLoggingEnabled) { 5932 log("STATE_CHANGE_EVENT in roaming state " 5933 + stateChangeResult.toString() ); 5934 } 5935 if (stateChangeResult.BSSID != null 5936 && stateChangeResult.BSSID.equals(mTargetRoamBSSID)) { 5937 handleNetworkDisconnect(); 5938 transitionTo(mDisconnectedState); 5939 } 5940 } 5941 if (stateChangeResult.state == SupplicantState.ASSOCIATED) { 5942 // We completed the layer2 roaming part 5943 mAssociated = true; 5944 if (stateChangeResult.BSSID != null) { 5945 mTargetRoamBSSID = stateChangeResult.BSSID; 5946 } 5947 } 5948 break; 5949 case CMD_ROAM_WATCHDOG_TIMER: 5950 if (roamWatchdogCount == message.arg1) { 5951 if (mVerboseLoggingEnabled) log("roaming watchdog! -> disconnect"); 5952 mWifiMetrics.endConnectionEvent( 5953 WifiMetrics.ConnectionEvent.FAILURE_ROAM_TIMEOUT, 5954 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5955 mRoamFailCount++; 5956 handleNetworkDisconnect(); 5957 mWifiNative.disconnect(); 5958 transitionTo(mDisconnectedState); 5959 } 5960 break; 5961 case WifiMonitor.NETWORK_CONNECTION_EVENT: 5962 if (mAssociated) { 5963 if (mVerboseLoggingEnabled) { 5964 log("roaming and Network connection established"); 5965 } 5966 mLastNetworkId = lookupFrameworkNetworkId(message.arg1); 5967 mLastBssid = (String) message.obj; 5968 mWifiInfo.setBSSID(mLastBssid); 5969 mWifiInfo.setNetworkId(mLastNetworkId); 5970 int reasonCode = message.arg2; 5971 mWifiConnectivityManager.trackBssid(mLastBssid, true, reasonCode); 5972 sendNetworkStateChangeBroadcast(mLastBssid); 5973 5974 // Successful framework roam! (probably) 5975 reportConnectionAttemptEnd( 5976 WifiMetrics.ConnectionEvent.FAILURE_NONE, 5977 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5978 5979 // We must clear the config BSSID, as the wifi chipset may decide to roam 5980 // from this point on and having the BSSID specified by QNS would cause 5981 // the roam to fail and the device to disconnect. 5982 // When transition from RoamingState to DisconnectingState or 5983 // DisconnectedState, the config BSSID is cleared by 5984 // handleNetworkDisconnect(). 5985 clearTargetBssid("RoamingCompleted"); 5986 5987 // We used to transition to ObtainingIpState in an 5988 // attempt to do DHCPv4 RENEWs on framework roams. 5989 // DHCP can take too long to time out, and we now rely 5990 // upon IpManager's use of IpReachabilityMonitor to 5991 // confirm our current network configuration. 5992 // 5993 // mIpManager.confirmConfiguration() is called within 5994 // the handling of SupplicantState.COMPLETED. 5995 transitionTo(mConnectedState); 5996 } else { 5997 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5998 } 5999 break; 6000 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6001 // Throw away but only if it corresponds to the network we're roaming to 6002 String bssid = (String) message.obj; 6003 if (true) { 6004 String target = ""; 6005 if (mTargetRoamBSSID != null) target = mTargetRoamBSSID; 6006 log("NETWORK_DISCONNECTION_EVENT in roaming state" 6007 + " BSSID=" + bssid 6008 + " target=" + target); 6009 } 6010 if (bssid != null && bssid.equals(mTargetRoamBSSID)) { 6011 handleNetworkDisconnect(); 6012 transitionTo(mDisconnectedState); 6013 } 6014 break; 6015 case WifiMonitor.SSID_TEMP_DISABLED: 6016 // Auth error while roaming 6017 int netId = lookupFrameworkNetworkId(message.arg1); 6018 logd("SSID_TEMP_DISABLED nid=" + Integer.toString(mLastNetworkId) 6019 + " id=" + netId 6020 + " isRoaming=" + isRoaming() 6021 + " roam=" + mAutoRoaming); 6022 if (netId == mLastNetworkId) { 6023 config = getCurrentWifiConfiguration(); 6024 if (config != null) { 6025 mWifiDiagnostics.captureBugReportData( 6026 WifiDiagnostics.REPORT_REASON_AUTOROAM_FAILURE); 6027 } 6028 handleNetworkDisconnect(); 6029 transitionTo(mDisconnectingState); 6030 } 6031 return NOT_HANDLED; 6032 case CMD_START_SCAN: 6033 deferMessage(message); 6034 break; 6035 default: 6036 return NOT_HANDLED; 6037 } 6038 return HANDLED; 6039 } 6040 6041 @Override 6042 public void exit() { 6043 logd("WifiStateMachine: Leaving Roaming state"); 6044 } 6045 } 6046 6047 class ConnectedState extends State { 6048 @Override 6049 public void enter() { 6050 updateDefaultRouteMacAddress(1000); 6051 if (mVerboseLoggingEnabled) { 6052 log("Enter ConnectedState " 6053 + " mScreenOn=" + mScreenOn); 6054 } 6055 6056 mWifiConnectivityManager.handleConnectionStateChanged( 6057 WifiConnectivityManager.WIFI_STATE_CONNECTED); 6058 registerConnected(); 6059 lastConnectAttemptTimestamp = 0; 6060 targetWificonfiguration = null; 6061 // Paranoia 6062 mIsLinkDebouncing = false; 6063 6064 // Not roaming anymore 6065 mAutoRoaming = false; 6066 6067 if (testNetworkDisconnect) { 6068 testNetworkDisconnectCounter++; 6069 logd("ConnectedState Enter start disconnect test " + 6070 testNetworkDisconnectCounter); 6071 sendMessageDelayed(obtainMessage(CMD_TEST_NETWORK_DISCONNECT, 6072 testNetworkDisconnectCounter, 0), 15000); 6073 } 6074 6075 mLastDriverRoamAttempt = 0; 6076 mTargetNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 6077 mWifiInjector.getWifiLastResortWatchdog().connectedStateTransition(true); 6078 mWifiStateTracker.updateState(WifiStateTracker.CONNECTED); 6079 } 6080 @Override 6081 public boolean processMessage(Message message) { 6082 WifiConfiguration config = null; 6083 logStateAndMessage(message, this); 6084 6085 switch (message.what) { 6086 case CMD_UNWANTED_NETWORK: 6087 if (message.arg1 == NETWORK_STATUS_UNWANTED_DISCONNECT) { 6088 mWifiNative.disconnect(); 6089 transitionTo(mDisconnectingState); 6090 } else if (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN || 6091 message.arg1 == NETWORK_STATUS_UNWANTED_VALIDATION_FAILED) { 6092 Log.d(TAG, (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN 6093 ? "NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN" 6094 : "NETWORK_STATUS_UNWANTED_VALIDATION_FAILED")); 6095 config = getCurrentWifiConfiguration(); 6096 if (config != null) { 6097 // Disable autojoin 6098 if (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN) { 6099 mWifiConfigManager.setNetworkValidatedInternetAccess( 6100 config.networkId, false); 6101 mWifiConfigManager.updateNetworkSelectionStatus(config.networkId, 6102 WifiConfiguration.NetworkSelectionStatus 6103 .DISABLED_NO_INTERNET); 6104 } 6105 mWifiConfigManager.incrementNetworkNoInternetAccessReports( 6106 config.networkId); 6107 } 6108 } 6109 return HANDLED; 6110 case CMD_NETWORK_STATUS: 6111 if (message.arg1 == NetworkAgent.VALID_NETWORK) { 6112 config = getCurrentWifiConfiguration(); 6113 if (config != null) { 6114 // re-enable autojoin 6115 mWifiConfigManager.setNetworkValidatedInternetAccess( 6116 config.networkId, true); 6117 } 6118 } 6119 return HANDLED; 6120 case CMD_ACCEPT_UNVALIDATED: 6121 boolean accept = (message.arg1 != 0); 6122 mWifiConfigManager.setNetworkNoInternetAccessExpected(mLastNetworkId, accept); 6123 return HANDLED; 6124 case CMD_TEST_NETWORK_DISCONNECT: 6125 // Force a disconnect 6126 if (message.arg1 == testNetworkDisconnectCounter) { 6127 mWifiNative.disconnect(); 6128 } 6129 break; 6130 case CMD_ASSOCIATED_BSSID: 6131 // ASSOCIATING to a new BSSID while already connected, indicates 6132 // that driver is roaming 6133 mLastDriverRoamAttempt = mClock.getWallClockMillis(); 6134 return NOT_HANDLED; 6135 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6136 long lastRoam = 0; 6137 reportConnectionAttemptEnd( 6138 WifiMetrics.ConnectionEvent.FAILURE_NETWORK_DISCONNECTION, 6139 WifiMetricsProto.ConnectionEvent.HLF_NONE); 6140 if (mLastDriverRoamAttempt != 0) { 6141 // Calculate time since last driver roam attempt 6142 lastRoam = mClock.getWallClockMillis() - mLastDriverRoamAttempt; 6143 mLastDriverRoamAttempt = 0; 6144 } 6145 if (unexpectedDisconnectedReason(message.arg2)) { 6146 mWifiDiagnostics.captureBugReportData( 6147 WifiDiagnostics.REPORT_REASON_UNEXPECTED_DISCONNECT); 6148 } 6149 config = getCurrentWifiConfiguration(); 6150 if (mEnableLinkDebouncing 6151 && mScreenOn 6152 && !isLinkDebouncing() 6153 && config != null 6154 && config.getNetworkSelectionStatus().isNetworkEnabled() 6155 && config.networkId != mWifiConfigManager.getLastSelectedNetwork() 6156 && (message.arg2 != 3 /* reason cannot be 3, i.e. locally generated */ 6157 || (lastRoam > 0 && lastRoam < 2000) /* unless driver is roaming */) 6158 && ((ScanResult.is24GHz(mWifiInfo.getFrequency()) 6159 && mWifiInfo.getRssi() > 6160 mThresholdQualifiedRssi5) 6161 || (ScanResult.is5GHz(mWifiInfo.getFrequency()) 6162 && mWifiInfo.getRssi() > 6163 mThresholdQualifiedRssi5))) { 6164 // Start de-bouncing the L2 disconnection: 6165 // this L2 disconnection might be spurious. 6166 // Hence we allow 4 seconds for the state machine to try 6167 // to reconnect, go thru the 6168 // roaming cycle and enter Obtaining IP address 6169 // before signalling the disconnect to ConnectivityService and L3 6170 startScanForConfiguration(getCurrentWifiConfiguration()); 6171 mIsLinkDebouncing = true; 6172 6173 sendMessageDelayed(obtainMessage(CMD_DELAYED_NETWORK_DISCONNECT, 6174 0, mLastNetworkId), LINK_FLAPPING_DEBOUNCE_MSEC); 6175 if (mVerboseLoggingEnabled) { 6176 log("NETWORK_DISCONNECTION_EVENT in connected state" 6177 + " BSSID=" + mWifiInfo.getBSSID() 6178 + " RSSI=" + mWifiInfo.getRssi() 6179 + " freq=" + mWifiInfo.getFrequency() 6180 + " reason=" + message.arg2 6181 + " -> debounce"); 6182 } 6183 return HANDLED; 6184 } else { 6185 if (mVerboseLoggingEnabled) { 6186 log("NETWORK_DISCONNECTION_EVENT in connected state" 6187 + " BSSID=" + mWifiInfo.getBSSID() 6188 + " RSSI=" + mWifiInfo.getRssi() 6189 + " freq=" + mWifiInfo.getFrequency() 6190 + " was debouncing=" + isLinkDebouncing() 6191 + " reason=" + message.arg2 6192 + " Network Selection Status=" + (config == null ? "Unavailable" 6193 : config.getNetworkSelectionStatus().getNetworkStatusString())); 6194 } 6195 } 6196 break; 6197 case CMD_START_ROAM: 6198 // Clear the driver roam indication since we are attempting a framework roam 6199 mLastDriverRoamAttempt = 0; 6200 6201 /* Connect command coming from auto-join */ 6202 int netId = message.arg1; 6203 ScanResult candidate = (ScanResult)message.obj; 6204 String bssid = SUPPLICANT_BSSID_ANY; 6205 if (candidate != null) { 6206 bssid = candidate.BSSID; 6207 } 6208 config = mWifiConfigManager.getConfiguredNetworkWithPassword(netId); 6209 if (config == null) { 6210 loge("CMD_START_ROAM and no config, bail out..."); 6211 break; 6212 } 6213 6214 setTargetBssid(config, bssid); 6215 mTargetNetworkId = netId; 6216 6217 logd("CMD_START_ROAM sup state " 6218 + mSupplicantStateTracker.getSupplicantStateName() 6219 + " my state " + getCurrentState().getName() 6220 + " nid=" + Integer.toString(netId) 6221 + " config " + config.configKey() 6222 + " targetRoamBSSID " + mTargetRoamBSSID); 6223 6224 reportConnectionAttemptStart(config, mTargetRoamBSSID, 6225 WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE); 6226 if (mWifiNative.roamToNetwork(config)) { 6227 lastConnectAttemptTimestamp = mClock.getWallClockMillis(); 6228 targetWificonfiguration = config; 6229 mAutoRoaming = true; 6230 transitionTo(mRoamingState); 6231 } else { 6232 loge("CMD_START_ROAM Failed to start roaming to network " + config); 6233 reportConnectionAttemptEnd( 6234 WifiMetrics.ConnectionEvent.FAILURE_CONNECT_NETWORK_FAILED, 6235 WifiMetricsProto.ConnectionEvent.HLF_NONE); 6236 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 6237 WifiManager.ERROR); 6238 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 6239 break; 6240 } 6241 break; 6242 case CMD_START_IP_PACKET_OFFLOAD: { 6243 int slot = message.arg1; 6244 int intervalSeconds = message.arg2; 6245 KeepalivePacketData pkt = (KeepalivePacketData) message.obj; 6246 byte[] dstMac; 6247 try { 6248 InetAddress gateway = RouteInfo.selectBestRoute( 6249 mLinkProperties.getRoutes(), pkt.dstAddress).getGateway(); 6250 String dstMacStr = macAddressFromRoute(gateway.getHostAddress()); 6251 dstMac = NativeUtil.macAddressToByteArray(dstMacStr); 6252 } catch (NullPointerException | IllegalArgumentException e) { 6253 loge("Can't find MAC address for next hop to " + pkt.dstAddress); 6254 mNetworkAgent.onPacketKeepaliveEvent(slot, 6255 ConnectivityManager.PacketKeepalive.ERROR_INVALID_IP_ADDRESS); 6256 break; 6257 } 6258 pkt.dstMac = dstMac; 6259 int result = startWifiIPPacketOffload(slot, pkt, intervalSeconds); 6260 mNetworkAgent.onPacketKeepaliveEvent(slot, result); 6261 break; 6262 } 6263 default: 6264 return NOT_HANDLED; 6265 } 6266 return HANDLED; 6267 } 6268 6269 @Override 6270 public void exit() { 6271 logd("WifiStateMachine: Leaving Connected state"); 6272 mWifiConnectivityManager.handleConnectionStateChanged( 6273 WifiConnectivityManager.WIFI_STATE_TRANSITIONING); 6274 6275 mLastDriverRoamAttempt = 0; 6276 mWifiInjector.getWifiLastResortWatchdog().connectedStateTransition(false); 6277 } 6278 } 6279 6280 class DisconnectingState extends State { 6281 6282 @Override 6283 public void enter() { 6284 6285 if (mVerboseLoggingEnabled) { 6286 logd(" Enter DisconnectingState State screenOn=" + mScreenOn); 6287 } 6288 6289 // Make sure we disconnect: we enter this state prior to connecting to a new 6290 // network, waiting for either a DISCONNECT event or a SUPPLICANT_STATE_CHANGE 6291 // event which in this case will be indicating that supplicant started to associate. 6292 // In some cases supplicant doesn't ignore the connect requests (it might not 6293 // find the target SSID in its cache), 6294 // Therefore we end up stuck that state, hence the need for the watchdog. 6295 disconnectingWatchdogCount++; 6296 logd("Start Disconnecting Watchdog " + disconnectingWatchdogCount); 6297 sendMessageDelayed(obtainMessage(CMD_DISCONNECTING_WATCHDOG_TIMER, 6298 disconnectingWatchdogCount, 0), DISCONNECTING_GUARD_TIMER_MSEC); 6299 } 6300 6301 @Override 6302 public boolean processMessage(Message message) { 6303 logStateAndMessage(message, this); 6304 switch (message.what) { 6305 case CMD_SET_OPERATIONAL_MODE: 6306 if (message.arg1 != CONNECT_MODE) { 6307 deferMessage(message); 6308 } 6309 break; 6310 case CMD_START_SCAN: 6311 deferMessage(message); 6312 return HANDLED; 6313 case CMD_DISCONNECT: 6314 if (mVerboseLoggingEnabled) log("Ignore CMD_DISCONNECT when already disconnecting."); 6315 break; 6316 case CMD_DISCONNECTING_WATCHDOG_TIMER: 6317 if (disconnectingWatchdogCount == message.arg1) { 6318 if (mVerboseLoggingEnabled) log("disconnecting watchdog! -> disconnect"); 6319 handleNetworkDisconnect(); 6320 transitionTo(mDisconnectedState); 6321 } 6322 break; 6323 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6324 /** 6325 * If we get a SUPPLICANT_STATE_CHANGE_EVENT before NETWORK_DISCONNECTION_EVENT 6326 * we have missed the network disconnection, transition to mDisconnectedState 6327 * and handle the rest of the events there 6328 */ 6329 deferMessage(message); 6330 handleNetworkDisconnect(); 6331 transitionTo(mDisconnectedState); 6332 break; 6333 default: 6334 return NOT_HANDLED; 6335 } 6336 return HANDLED; 6337 } 6338 } 6339 6340 class DisconnectedState extends State { 6341 @Override 6342 public void enter() { 6343 // We dont scan frequently if this is a temporary disconnect 6344 // due to p2p 6345 if (mTemporarilyDisconnectWifi) { 6346 p2pSendMessage(WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE); 6347 return; 6348 } 6349 6350 if (mVerboseLoggingEnabled) { 6351 logd(" Enter DisconnectedState screenOn=" + mScreenOn); 6352 } 6353 6354 /** clear the roaming state, if we were roaming, we failed */ 6355 mAutoRoaming = false; 6356 6357 mWifiConnectivityManager.handleConnectionStateChanged( 6358 WifiConnectivityManager.WIFI_STATE_DISCONNECTED); 6359 6360 /** 6361 * If we have no networks saved, the supplicant stops doing the periodic scan. 6362 * The scans are useful to notify the user of the presence of an open network. 6363 * Note that these are not wake up scans. 6364 */ 6365 if (mNoNetworksPeriodicScan != 0 && !mP2pConnected.get() 6366 && mWifiConfigManager.getSavedNetworks().size() == 0) { 6367 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 6368 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 6369 } 6370 6371 mDisconnectedTimeStamp = mClock.getWallClockMillis(); 6372 mWifiStateTracker.updateState(WifiStateTracker.DISCONNECTED); 6373 } 6374 @Override 6375 public boolean processMessage(Message message) { 6376 boolean ret = HANDLED; 6377 6378 logStateAndMessage(message, this); 6379 6380 switch (message.what) { 6381 case CMD_NO_NETWORKS_PERIODIC_SCAN: 6382 if (mP2pConnected.get()) break; 6383 if (mNoNetworksPeriodicScan != 0 && message.arg1 == mPeriodicScanToken && 6384 mWifiConfigManager.getSavedNetworks().size() == 0) { 6385 startScan(UNKNOWN_SCAN_SOURCE, -1, null, WIFI_WORK_SOURCE); 6386 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 6387 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 6388 } 6389 break; 6390 case WifiManager.FORGET_NETWORK: 6391 case CMD_REMOVE_NETWORK: 6392 case CMD_REMOVE_APP_CONFIGURATIONS: 6393 case CMD_REMOVE_USER_CONFIGURATIONS: 6394 // Set up a delayed message here. After the forget/remove is handled 6395 // the handled delayed message will determine if there is a need to 6396 // scan and continue 6397 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 6398 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 6399 ret = NOT_HANDLED; 6400 break; 6401 case CMD_SET_OPERATIONAL_MODE: 6402 if (message.arg1 != CONNECT_MODE) { 6403 mOperationalMode = message.arg1; 6404 if (mOperationalMode == DISABLED_MODE) { 6405 transitionTo(mSupplicantStoppingState); 6406 } else if (mOperationalMode == SCAN_ONLY_MODE 6407 || mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 6408 p2pSendMessage(CMD_DISABLE_P2P_REQ); 6409 setWifiState(WIFI_STATE_DISABLED); 6410 transitionTo(mScanModeState); 6411 } 6412 } 6413 break; 6414 case CMD_DISCONNECT: 6415 mWifiNative.disconnect(); 6416 break; 6417 /* Ignore network disconnect */ 6418 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6419 // Interpret this as an L2 connection failure 6420 break; 6421 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6422 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 6423 if (mVerboseLoggingEnabled) { 6424 logd("SUPPLICANT_STATE_CHANGE_EVENT state=" + stateChangeResult.state + 6425 " -> state= " + WifiInfo.getDetailedStateOf(stateChangeResult.state) 6426 + " debouncing=" + isLinkDebouncing()); 6427 } 6428 setNetworkDetailedState(WifiInfo.getDetailedStateOf(stateChangeResult.state)); 6429 /* ConnectModeState does the rest of the handling */ 6430 ret = NOT_HANDLED; 6431 break; 6432 case CMD_START_SCAN: 6433 if (!checkOrDeferScanAllowed(message)) { 6434 // The scan request was rescheduled 6435 messageHandlingStatus = MESSAGE_HANDLING_STATUS_REFUSED; 6436 return HANDLED; 6437 } 6438 6439 ret = NOT_HANDLED; 6440 break; 6441 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 6442 NetworkInfo info = (NetworkInfo) message.obj; 6443 mP2pConnected.set(info.isConnected()); 6444 if (!mP2pConnected.get() && mWifiConfigManager.getSavedNetworks().size() == 0) { 6445 if (mVerboseLoggingEnabled) log("Turn on scanning after p2p disconnected"); 6446 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 6447 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 6448 } 6449 break; 6450 case CMD_RECONNECT: 6451 case CMD_REASSOCIATE: 6452 if (mTemporarilyDisconnectWifi) { 6453 // Drop a third party reconnect/reassociate if STA is 6454 // temporarily disconnected for p2p 6455 break; 6456 } else { 6457 // ConnectModeState handles it 6458 ret = NOT_HANDLED; 6459 } 6460 break; 6461 case CMD_SCREEN_STATE_CHANGED: 6462 handleScreenStateChanged(message.arg1 != 0); 6463 break; 6464 default: 6465 ret = NOT_HANDLED; 6466 } 6467 return ret; 6468 } 6469 6470 @Override 6471 public void exit() { 6472 mWifiConnectivityManager.handleConnectionStateChanged( 6473 WifiConnectivityManager.WIFI_STATE_TRANSITIONING); 6474 } 6475 } 6476 6477 /** 6478 * WPS connection flow: 6479 * 1. WifiStateMachine receive WPS_START message from WifiManager API. 6480 * 2. WifiStateMachine initiates the appropriate WPS operation using WifiNative methods: 6481 * {@link WifiNative#startWpsPbc(String)}, {@link WifiNative#startWpsPinDisplay(String)}, etc. 6482 * 3. WifiStateMachine then transitions to this WpsRunningState. 6483 * 4a. Once WifiStateMachine receive the connected event: 6484 * {@link WifiMonitor#NETWORK_CONNECTION_EVENT}, 6485 * 4a.1 Load the network params out of wpa_supplicant. 6486 * 4a.2 Add the network with params to WifiConfigManager. 6487 * 4a.3 Enable the network with |disableOthers| set to true. 6488 * 4a.4 Send a response to the original source of WifiManager API using {@link #mSourceMessage}. 6489 * 4b. Any failures are notified to the original source of WifiManager API 6490 * using {@link #mSourceMessage}. 6491 * 5. We then transition to disconnected state and let network selection reconnect to the newly 6492 * added network. 6493 */ 6494 class WpsRunningState extends State { 6495 // Tracks the source to provide a reply 6496 private Message mSourceMessage; 6497 @Override 6498 public void enter() { 6499 mSourceMessage = Message.obtain(getCurrentMessage()); 6500 } 6501 @Override 6502 public boolean processMessage(Message message) { 6503 logStateAndMessage(message, this); 6504 6505 switch (message.what) { 6506 case WifiMonitor.WPS_SUCCESS_EVENT: 6507 // Ignore intermediate success, wait for full connection 6508 break; 6509 case WifiMonitor.NETWORK_CONNECTION_EVENT: 6510 if (loadNetworksFromSupplicantAfterWps()) { 6511 replyToMessage(mSourceMessage, WifiManager.WPS_COMPLETED); 6512 } else { 6513 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 6514 WifiManager.ERROR); 6515 } 6516 mSourceMessage.recycle(); 6517 mSourceMessage = null; 6518 deferMessage(message); 6519 transitionTo(mDisconnectedState); 6520 break; 6521 case WifiMonitor.WPS_OVERLAP_EVENT: 6522 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 6523 WifiManager.WPS_OVERLAP_ERROR); 6524 mSourceMessage.recycle(); 6525 mSourceMessage = null; 6526 transitionTo(mDisconnectedState); 6527 break; 6528 case WifiMonitor.WPS_FAIL_EVENT: 6529 // Arg1 has the reason for the failure 6530 if ((message.arg1 != WifiManager.ERROR) || (message.arg2 != 0)) { 6531 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, message.arg1); 6532 mSourceMessage.recycle(); 6533 mSourceMessage = null; 6534 transitionTo(mDisconnectedState); 6535 } else { 6536 if (mVerboseLoggingEnabled) { 6537 log("Ignore unspecified fail event during WPS connection"); 6538 } 6539 } 6540 break; 6541 case WifiMonitor.WPS_TIMEOUT_EVENT: 6542 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 6543 WifiManager.WPS_TIMED_OUT); 6544 mSourceMessage.recycle(); 6545 mSourceMessage = null; 6546 transitionTo(mDisconnectedState); 6547 break; 6548 case WifiManager.START_WPS: 6549 replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.IN_PROGRESS); 6550 break; 6551 case WifiManager.CANCEL_WPS: 6552 if (mWifiNative.cancelWps()) { 6553 replyToMessage(message, WifiManager.CANCEL_WPS_SUCCEDED); 6554 } else { 6555 replyToMessage(message, WifiManager.CANCEL_WPS_FAILED, WifiManager.ERROR); 6556 } 6557 transitionTo(mDisconnectedState); 6558 break; 6559 /** 6560 * Defer all commands that can cause connections to a different network 6561 * or put the state machine out of connect mode 6562 */ 6563 case CMD_SET_OPERATIONAL_MODE: 6564 case WifiManager.CONNECT_NETWORK: 6565 case CMD_ENABLE_NETWORK: 6566 case CMD_RECONNECT: 6567 case CMD_REASSOCIATE: 6568 deferMessage(message); 6569 break; 6570 case CMD_START_CONNECT: 6571 case CMD_START_ROAM: 6572 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 6573 return HANDLED; 6574 case CMD_START_SCAN: 6575 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 6576 return HANDLED; 6577 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6578 if (mVerboseLoggingEnabled) log("Network connection lost"); 6579 handleNetworkDisconnect(); 6580 break; 6581 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 6582 if (mVerboseLoggingEnabled) { 6583 log("Ignore Assoc reject event during WPS Connection"); 6584 } 6585 break; 6586 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 6587 // Disregard auth failure events during WPS connection. The 6588 // EAP sequence is retried several times, and there might be 6589 // failures (especially for wps pin). We will get a WPS_XXX 6590 // event at the end of the sequence anyway. 6591 if (mVerboseLoggingEnabled) log("Ignore auth failure during WPS connection"); 6592 break; 6593 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6594 // Throw away supplicant state changes when WPS is running. 6595 // We will start getting supplicant state changes once we get 6596 // a WPS success or failure 6597 break; 6598 default: 6599 return NOT_HANDLED; 6600 } 6601 return HANDLED; 6602 } 6603 6604 /** 6605 * Load network config from wpa_supplicant after WPS is complete. 6606 */ 6607 private boolean loadNetworksFromSupplicantAfterWps() { 6608 Map<String, WifiConfiguration> configs = new HashMap<>(); 6609 SparseArray<Map<String, String>> extras = new SparseArray<>(); 6610 if (!mWifiNative.migrateNetworksFromSupplicant(configs, extras)) { 6611 loge("Failed to load networks from wpa_supplicant after Wps"); 6612 return false; 6613 } 6614 for (Map.Entry<String, WifiConfiguration> entry : configs.entrySet()) { 6615 NetworkUpdateResult result = mWifiConfigManager.addOrUpdateNetwork( 6616 entry.getValue(), mSourceMessage.sendingUid); 6617 if (!result.isSuccess()) { 6618 loge("Failed to add network after WPS: " + entry.getValue()); 6619 return false; 6620 } 6621 if (!mWifiConfigManager.enableNetwork( 6622 result.getNetworkId(), true, mSourceMessage.sendingUid)) { 6623 loge("Failed to enable network after WPS: " + entry.getValue()); 6624 return false; 6625 } 6626 } 6627 return true; 6628 } 6629 } 6630 6631 class SoftApState extends State { 6632 private SoftApManager mSoftApManager; 6633 6634 private class SoftApListener implements SoftApManager.Listener { 6635 @Override 6636 public void onStateChanged(int state, int reason) { 6637 if (state == WIFI_AP_STATE_DISABLED) { 6638 sendMessage(CMD_AP_STOPPED); 6639 } else if (state == WIFI_AP_STATE_FAILED) { 6640 sendMessage(CMD_START_AP_FAILURE); 6641 } 6642 6643 setWifiApState(state, reason); 6644 } 6645 } 6646 6647 @Override 6648 public void enter() { 6649 final Message message = getCurrentMessage(); 6650 if (message.what != CMD_START_AP) { 6651 throw new RuntimeException("Illegal transition to SoftApState: " + message); 6652 } 6653 6654 IApInterface apInterface = mWifiNative.setupForSoftApMode(); 6655 if (apInterface == null) { 6656 setWifiApState(WIFI_AP_STATE_FAILED, 6657 WifiManager.SAP_START_FAILURE_GENERAL); 6658 /** 6659 * Transition to InitialState to reset the 6660 * driver/HAL back to the initial state. 6661 */ 6662 transitionTo(mInitialState); 6663 return; 6664 } 6665 6666 WifiConfiguration config = (WifiConfiguration) message.obj; 6667 6668 checkAndSetConnectivityInstance(); 6669 mSoftApManager = mWifiInjector.makeSoftApManager(mNwService, 6670 new SoftApListener(), 6671 apInterface, 6672 config); 6673 mSoftApManager.start(); 6674 mWifiStateTracker.updateState(WifiStateTracker.SOFT_AP); 6675 } 6676 6677 @Override 6678 public void exit() { 6679 mSoftApManager = null; 6680 } 6681 6682 @Override 6683 public boolean processMessage(Message message) { 6684 logStateAndMessage(message, this); 6685 6686 switch(message.what) { 6687 case CMD_START_AP: 6688 /* Ignore start command when it is starting/started. */ 6689 break; 6690 case CMD_STOP_AP: 6691 mSoftApManager.stop(); 6692 break; 6693 case CMD_START_AP_FAILURE: 6694 transitionTo(mInitialState); 6695 break; 6696 case CMD_AP_STOPPED: 6697 transitionTo(mInitialState); 6698 break; 6699 default: 6700 return NOT_HANDLED; 6701 } 6702 return HANDLED; 6703 } 6704 } 6705 6706 /** 6707 * State machine initiated requests can have replyTo set to null indicating 6708 * there are no recepients, we ignore those reply actions. 6709 */ 6710 private void replyToMessage(Message msg, int what) { 6711 if (msg.replyTo == null) return; 6712 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 6713 mReplyChannel.replyToMessage(msg, dstMsg); 6714 } 6715 6716 private void replyToMessage(Message msg, int what, int arg1) { 6717 if (msg.replyTo == null) return; 6718 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 6719 dstMsg.arg1 = arg1; 6720 mReplyChannel.replyToMessage(msg, dstMsg); 6721 } 6722 6723 private void replyToMessage(Message msg, int what, Object obj) { 6724 if (msg.replyTo == null) return; 6725 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 6726 dstMsg.obj = obj; 6727 mReplyChannel.replyToMessage(msg, dstMsg); 6728 } 6729 6730 /** 6731 * arg2 on the source message has a unique id that needs to be retained in replies 6732 * to match the request 6733 * <p>see WifiManager for details 6734 */ 6735 private Message obtainMessageWithWhatAndArg2(Message srcMsg, int what) { 6736 Message msg = Message.obtain(); 6737 msg.what = what; 6738 msg.arg2 = srcMsg.arg2; 6739 return msg; 6740 } 6741 6742 /** 6743 * Notify interested parties if a wifi config has been changed. 6744 * 6745 * @param wifiCredentialEventType WIFI_CREDENTIAL_SAVED or WIFI_CREDENTIAL_FORGOT 6746 * @param config Must have a WifiConfiguration object to succeed 6747 * TODO: b/35258354 investigate if this can be removed. Is the broadcast sent by 6748 * WifiConfigManager sufficient? 6749 */ 6750 private void broadcastWifiCredentialChanged(int wifiCredentialEventType, 6751 WifiConfiguration config) { 6752 if (config != null && config.preSharedKey != null) { 6753 Intent intent = new Intent(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION); 6754 intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID, config.SSID); 6755 intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, 6756 wifiCredentialEventType); 6757 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT, 6758 android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE); 6759 } 6760 } 6761 6762 void handleGsmAuthRequest(SimAuthRequestData requestData) { 6763 if (targetWificonfiguration == null 6764 || targetWificonfiguration.networkId 6765 == lookupFrameworkNetworkId(requestData.networkId)) { 6766 logd("id matches targetWifiConfiguration"); 6767 } else { 6768 logd("id does not match targetWifiConfiguration"); 6769 return; 6770 } 6771 6772 String response = 6773 TelephonyUtil.getGsmSimAuthResponse(requestData.data, getTelephonyManager()); 6774 if (response == null) { 6775 mWifiNative.simAuthFailedResponse(requestData.networkId); 6776 } else { 6777 logv("Supplicant Response -" + response); 6778 mWifiNative.simAuthResponse(requestData.networkId, 6779 WifiNative.SIM_AUTH_RESP_TYPE_GSM_AUTH, response); 6780 } 6781 } 6782 6783 void handle3GAuthRequest(SimAuthRequestData requestData) { 6784 if (targetWificonfiguration == null 6785 || targetWificonfiguration.networkId 6786 == lookupFrameworkNetworkId(requestData.networkId)) { 6787 logd("id matches targetWifiConfiguration"); 6788 } else { 6789 logd("id does not match targetWifiConfiguration"); 6790 return; 6791 } 6792 6793 SimAuthResponseData response = 6794 TelephonyUtil.get3GAuthResponse(requestData, getTelephonyManager()); 6795 if (response != null) { 6796 mWifiNative.simAuthResponse(requestData.networkId, response.type, response.response); 6797 } else { 6798 mWifiNative.umtsAuthFailedResponse(requestData.networkId); 6799 } 6800 } 6801 6802 /** 6803 * Automatically connect to the network specified 6804 * 6805 * @param networkId ID of the network to connect to 6806 * @param bssid BSSID of the network 6807 */ 6808 public void startConnectToNetwork(int networkId, String bssid) { 6809 synchronized (mWifiReqCountLock) { 6810 if (hasConnectionRequests()) { 6811 sendMessage(CMD_START_CONNECT, networkId, 0, bssid); 6812 } 6813 } 6814 } 6815 6816 /** 6817 * Automatically roam to the network specified 6818 * 6819 * @param networkId ID of the network to roam to 6820 * @param scanResult scan result which identifies the network to roam to 6821 */ 6822 public void startRoamToNetwork(int networkId, ScanResult scanResult) { 6823 sendMessage(CMD_START_ROAM, networkId, 0, scanResult); 6824 } 6825 6826 /** 6827 * Dynamically turn on/off WifiConnectivityManager 6828 * 6829 * @param enabled true-enable; false-disable 6830 */ 6831 public void enableWifiConnectivityManager(boolean enabled) { 6832 sendMessage(CMD_ENABLE_WIFI_CONNECTIVITY_MANAGER, enabled ? 1 : 0); 6833 } 6834 6835 /** 6836 * @param reason reason code from supplicant on network disconnected event 6837 * @return true if this is a suspicious disconnect 6838 */ 6839 static boolean unexpectedDisconnectedReason(int reason) { 6840 return reason == 2 // PREV_AUTH_NOT_VALID 6841 || reason == 6 // CLASS2_FRAME_FROM_NONAUTH_STA 6842 || reason == 7 // FRAME_FROM_NONASSOC_STA 6843 || reason == 8 // STA_HAS_LEFT 6844 || reason == 9 // STA_REQ_ASSOC_WITHOUT_AUTH 6845 || reason == 14 // MICHAEL_MIC_FAILURE 6846 || reason == 15 // 4WAY_HANDSHAKE_TIMEOUT 6847 || reason == 16 // GROUP_KEY_UPDATE_TIMEOUT 6848 || reason == 18 // GROUP_CIPHER_NOT_VALID 6849 || reason == 19 // PAIRWISE_CIPHER_NOT_VALID 6850 || reason == 23 // IEEE_802_1X_AUTH_FAILED 6851 || reason == 34; // DISASSOC_LOW_ACK 6852 } 6853 6854 /** 6855 * Update WifiMetrics before dumping 6856 */ 6857 public void updateWifiMetrics() { 6858 mWifiMetrics.updateSavedNetworks(mWifiConfigManager.getSavedNetworks()); 6859 } 6860 6861 /** 6862 * Private method to handle calling WifiConfigManager to forget/remove network configs and reply 6863 * to the message from the sender of the outcome. 6864 * 6865 * The current implementation requires that forget and remove be handled in different ways 6866 * (responses are handled differently). In the interests of organization, the handling is all 6867 * now in this helper method. TODO: b/35257965 is filed to track the possibility of merging 6868 * the two call paths. 6869 */ 6870 private boolean deleteNetworkConfigAndSendReply(Message message, boolean calledFromForget) { 6871 boolean success = mWifiConfigManager.removeNetwork(message.arg1, message.sendingUid); 6872 if (!success) { 6873 loge("Failed to remove network"); 6874 } 6875 6876 if (calledFromForget) { 6877 if (success) { 6878 replyToMessage(message, WifiManager.FORGET_NETWORK_SUCCEEDED); 6879 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_FORGOT, 6880 (WifiConfiguration) message.obj); 6881 return true; 6882 } 6883 replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, WifiManager.ERROR); 6884 return false; 6885 } else { 6886 // Remaining calls are from the removeNetwork path 6887 if (success) { 6888 replyToMessage(message, message.what, SUCCESS); 6889 return true; 6890 } 6891 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 6892 replyToMessage(message, message.what, FAILURE); 6893 return false; 6894 } 6895 } 6896 6897 private static String getLinkPropertiesSummary(LinkProperties lp) { 6898 List<String> attributes = new ArrayList<>(6); 6899 if (lp.hasIPv4Address()) { 6900 attributes.add("v4"); 6901 } 6902 if (lp.hasIPv4DefaultRoute()) { 6903 attributes.add("v4r"); 6904 } 6905 if (lp.hasIPv4DnsServer()) { 6906 attributes.add("v4dns"); 6907 } 6908 if (lp.hasGlobalIPv6Address()) { 6909 attributes.add("v6"); 6910 } 6911 if (lp.hasIPv6DefaultRoute()) { 6912 attributes.add("v6r"); 6913 } 6914 if (lp.hasIPv6DnsServer()) { 6915 attributes.add("v6dns"); 6916 } 6917 6918 return TextUtils.join(" ", attributes); 6919 } 6920 6921 /** 6922 * Gets the SSID from the WifiConfiguration pointed at by 'mTargetNetworkId' 6923 * This should match the network config framework is attempting to connect to. 6924 */ 6925 private String getTargetSsid() { 6926 WifiConfiguration currentConfig = mWifiConfigManager.getConfiguredNetwork(mTargetNetworkId); 6927 if (currentConfig != null) { 6928 return currentConfig.SSID; 6929 } 6930 return null; 6931 } 6932 6933 private void p2pSendMessage(int what) { 6934 if (mWifiP2pChannel != null) { 6935 mWifiP2pChannel.sendMessage(what); 6936 } 6937 } 6938 6939 private void p2pSendMessage(int what, int arg1) { 6940 if (mWifiP2pChannel != null) { 6941 mWifiP2pChannel.sendMessage(what, arg1); 6942 } 6943 } 6944 6945 /** 6946 * Check if there is any connection request for WiFi network. 6947 * Note, caller of this helper function must acquire mWifiReqCountLock. 6948 */ 6949 private boolean hasConnectionRequests() { 6950 return mConnectionReqCount > 0 || mUntrustedReqCount > 0; 6951 } 6952 6953 /** 6954 * Returns whether CMD_IP_REACHABILITY_LOST events should trigger disconnects. 6955 */ 6956 public boolean getIpReachabilityDisconnectEnabled() { 6957 return mIpReachabilityDisconnectEnabled; 6958 } 6959 6960 /** 6961 * Sets whether CMD_IP_REACHABILITY_LOST events should trigger disconnects. 6962 */ 6963 public void setIpReachabilityDisconnectEnabled(boolean enabled) { 6964 mIpReachabilityDisconnectEnabled = enabled; 6965 } 6966 6967 /** 6968 * Sends a message to initialize the WifiStateMachine. 6969 * 6970 * @return true if succeeded, false otherwise. 6971 */ 6972 public boolean syncInitialize(AsyncChannel channel) { 6973 Message resultMsg = channel.sendMessageSynchronously(CMD_INITIALIZE); 6974 boolean result = (resultMsg.arg1 != FAILURE); 6975 resultMsg.recycle(); 6976 return result; 6977 } 6978} 6979