WifiStateMachine.java revision 61e149bc125c753fea54ba59cf70fbaff1772ea5
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 } 4213 4214 @Override 4215 public boolean processMessage(Message message) { 4216 logStateAndMessage(message, this); 4217 4218 switch(message.what) { 4219 case CMD_STOP_SUPPLICANT: /* Supplicant stopped by user */ 4220 if (mP2pSupported) { 4221 transitionTo(mWaitForP2pDisableState); 4222 } else { 4223 transitionTo(mSupplicantStoppingState); 4224 } 4225 break; 4226 case WifiMonitor.SUP_DISCONNECTION_EVENT: /* Supplicant connection lost */ 4227 loge("Connection lost, restart supplicant"); 4228 handleSupplicantConnectionLoss(true); 4229 handleNetworkDisconnect(); 4230 mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE); 4231 if (mP2pSupported) { 4232 transitionTo(mWaitForP2pDisableState); 4233 } else { 4234 transitionTo(mInitialState); 4235 } 4236 sendMessageDelayed(CMD_START_SUPPLICANT, SUPPLICANT_RESTART_INTERVAL_MSECS); 4237 break; 4238 case CMD_START_SCAN: 4239 // TODO: remove scan request path (b/31445200) 4240 handleScanRequest(message); 4241 break; 4242 case WifiMonitor.SCAN_RESULTS_EVENT: 4243 case WifiMonitor.SCAN_FAILED_EVENT: 4244 // TODO: remove handing of SCAN_RESULTS_EVENT and SCAN_FAILED_EVENT when scan 4245 // results are retrieved from WifiScanner (b/31444878) 4246 maybeRegisterNetworkFactory(); // Make sure our NetworkFactory is registered 4247 setScanResults(); 4248 mIsScanOngoing = false; 4249 mIsFullScanOngoing = false; 4250 if (mBufferedScanMsg.size() > 0) 4251 sendMessage(mBufferedScanMsg.remove()); 4252 break; 4253 case CMD_PING_SUPPLICANT: 4254 // TODO (b/35620640): Remove this command since the API is deprecated. 4255 replyToMessage(message, message.what, FAILURE); 4256 break; 4257 case CMD_START_AP: 4258 /* Cannot start soft AP while in client mode */ 4259 loge("Failed to start soft AP with a running supplicant"); 4260 setWifiApState(WIFI_AP_STATE_FAILED, WifiManager.SAP_START_FAILURE_GENERAL); 4261 break; 4262 case CMD_SET_OPERATIONAL_MODE: 4263 mOperationalMode = message.arg1; 4264 if (mOperationalMode == DISABLED_MODE) { 4265 transitionTo(mSupplicantStoppingState); 4266 } 4267 break; 4268 case CMD_TARGET_BSSID: 4269 // Trying to associate to this BSSID 4270 if (message.obj != null) { 4271 mTargetRoamBSSID = (String) message.obj; 4272 } 4273 break; 4274 case CMD_GET_LINK_LAYER_STATS: 4275 WifiLinkLayerStats stats = getWifiLinkLayerStats(); 4276 replyToMessage(message, message.what, stats); 4277 break; 4278 case CMD_RESET_SIM_NETWORKS: 4279 log("resetting EAP-SIM/AKA/AKA' networks since SIM was changed"); 4280 mWifiConfigManager.resetSimNetworks(); 4281 break; 4282 case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE: 4283 mBluetoothConnectionActive = (message.arg1 != 4284 BluetoothAdapter.STATE_DISCONNECTED); 4285 mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive); 4286 break; 4287 case CMD_SET_SUSPEND_OPT_ENABLED: 4288 if (message.arg1 == 1) { 4289 setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, true); 4290 if (message.arg2 == 1) { 4291 mSuspendWakeLock.release(); 4292 } 4293 } else { 4294 setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, false); 4295 } 4296 break; 4297 case CMD_SET_HIGH_PERF_MODE: 4298 if (message.arg1 == 1) { 4299 setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, false); 4300 } else { 4301 setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, true); 4302 } 4303 break; 4304 case CMD_ENABLE_TDLS: 4305 if (message.obj != null) { 4306 String remoteAddress = (String) message.obj; 4307 boolean enable = (message.arg1 == 1); 4308 mWifiNative.startTdls(remoteAddress, enable); 4309 } 4310 break; 4311 case WifiMonitor.ANQP_DONE_EVENT: 4312 // TODO(zqiu): remove this when switch over to wificond for ANQP requests. 4313 mPasspointManager.notifyANQPDone((AnqpEvent) message.obj); 4314 break; 4315 case CMD_STOP_IP_PACKET_OFFLOAD: { 4316 int slot = message.arg1; 4317 int ret = stopWifiIPPacketOffload(slot); 4318 if (mNetworkAgent != null) { 4319 mNetworkAgent.onPacketKeepaliveEvent(slot, ret); 4320 } 4321 break; 4322 } 4323 case WifiMonitor.RX_HS20_ANQP_ICON_EVENT: 4324 // TODO(zqiu): remove this when switch over to wificond for icon requests. 4325 mPasspointManager.notifyIconDone((IconEvent) message.obj); 4326 break; 4327 case WifiMonitor.HS20_REMEDIATION_EVENT: 4328 // TODO(zqiu): remove this when switch over to wificond for WNM frames 4329 // monitoring. 4330 mPasspointManager.receivedWnmFrame((WnmData) message.obj); 4331 break; 4332 case CMD_CONFIG_ND_OFFLOAD: 4333 final boolean enabled = (message.arg1 > 0); 4334 mWifiNative.configureNeighborDiscoveryOffload(enabled); 4335 break; 4336 case CMD_ENABLE_WIFI_CONNECTIVITY_MANAGER: 4337 mWifiConnectivityManager.enable(message.arg1 == 1 ? true : false); 4338 break; 4339 case CMD_ENABLE_AUTOJOIN_WHEN_ASSOCIATED: 4340 final boolean allowed = (message.arg1 > 0); 4341 boolean old_state = mEnableAutoJoinWhenAssociated; 4342 mEnableAutoJoinWhenAssociated = allowed; 4343 if (!old_state && allowed && mScreenOn 4344 && getCurrentState() == mConnectedState) { 4345 mWifiConnectivityManager.forceConnectivityScan(); 4346 } 4347 break; 4348 default: 4349 return NOT_HANDLED; 4350 } 4351 return HANDLED; 4352 } 4353 4354 @Override 4355 public void exit() { 4356 mWifiDiagnostics.stopLogging(); 4357 4358 mIsRunning = false; 4359 updateBatteryWorkSource(null); 4360 mScanResults = new ArrayList<>(); 4361 4362 final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE); 4363 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4364 intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED); 4365 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 4366 mBufferedScanMsg.clear(); 4367 4368 mNetworkInfo.setIsAvailable(false); 4369 if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo); 4370 mCountryCode.setReadyForChange(false); 4371 } 4372 } 4373 4374 class SupplicantStoppingState extends State { 4375 @Override 4376 public void enter() { 4377 /* Send any reset commands to supplicant before shutting it down */ 4378 handleNetworkDisconnect(); 4379 4380 String suppState = System.getProperty("init.svc.wpa_supplicant"); 4381 if (suppState == null) suppState = "unknown"; 4382 4383 setWifiState(WIFI_STATE_DISABLING); 4384 mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE); 4385 logd("SupplicantStoppingState: disableSupplicant " 4386 + " init.svc.wpa_supplicant=" + suppState); 4387 if (mWifiNative.disableSupplicant()) { 4388 mWifiNative.closeSupplicantConnection(); 4389 sendSupplicantConnectionChangedBroadcast(false); 4390 setWifiState(WIFI_STATE_DISABLED); 4391 } else { 4392 // Failed to disable supplicant 4393 handleSupplicantConnectionLoss(true); 4394 } 4395 transitionTo(mInitialState); 4396 } 4397 } 4398 4399 class WaitForP2pDisableState extends State { 4400 private State mTransitionToState; 4401 @Override 4402 public void enter() { 4403 switch (getCurrentMessage().what) { 4404 case WifiMonitor.SUP_DISCONNECTION_EVENT: 4405 mTransitionToState = mInitialState; 4406 break; 4407 case CMD_STOP_SUPPLICANT: 4408 default: 4409 mTransitionToState = mSupplicantStoppingState; 4410 break; 4411 } 4412 p2pSendMessage(WifiStateMachine.CMD_DISABLE_P2P_REQ); 4413 } 4414 @Override 4415 public boolean processMessage(Message message) { 4416 logStateAndMessage(message, this); 4417 4418 switch(message.what) { 4419 case WifiStateMachine.CMD_DISABLE_P2P_RSP: 4420 transitionTo(mTransitionToState); 4421 break; 4422 /* Defer wifi start/shut and driver commands */ 4423 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 4424 case CMD_START_SUPPLICANT: 4425 case CMD_STOP_SUPPLICANT: 4426 case CMD_START_AP: 4427 case CMD_STOP_AP: 4428 case CMD_SET_OPERATIONAL_MODE: 4429 case CMD_START_SCAN: 4430 case CMD_DISCONNECT: 4431 case CMD_REASSOCIATE: 4432 case CMD_RECONNECT: 4433 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 4434 deferMessage(message); 4435 break; 4436 default: 4437 return NOT_HANDLED; 4438 } 4439 return HANDLED; 4440 } 4441 } 4442 4443 class ScanModeState extends State { 4444 private int mLastOperationMode; 4445 @Override 4446 public void enter() { 4447 mLastOperationMode = mOperationalMode; 4448 mWifiStateTracker.updateState(WifiStateTracker.SCAN_MODE); 4449 } 4450 @Override 4451 public boolean processMessage(Message message) { 4452 logStateAndMessage(message, this); 4453 4454 switch(message.what) { 4455 case CMD_SET_OPERATIONAL_MODE: 4456 if (message.arg1 == CONNECT_MODE) { 4457 mOperationalMode = CONNECT_MODE; 4458 transitionTo(mDisconnectedState); 4459 } else if (message.arg1 == DISABLED_MODE) { 4460 transitionTo(mSupplicantStoppingState); 4461 } 4462 // Nothing to do 4463 break; 4464 // Handle scan. All the connection related commands are 4465 // handled only in ConnectModeState 4466 case CMD_START_SCAN: 4467 handleScanRequest(message); 4468 break; 4469 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 4470 SupplicantState state = handleSupplicantStateChange(message); 4471 if (mVerboseLoggingEnabled) log("SupplicantState= " + state); 4472 break; 4473 default: 4474 return NOT_HANDLED; 4475 } 4476 return HANDLED; 4477 } 4478 } 4479 4480 4481 String smToString(Message message) { 4482 return smToString(message.what); 4483 } 4484 4485 String smToString(int what) { 4486 String s = sSmToString.get(what); 4487 if (s != null) { 4488 return s; 4489 } 4490 switch (what) { 4491 case WifiMonitor.DRIVER_HUNG_EVENT: 4492 s = "DRIVER_HUNG_EVENT"; 4493 break; 4494 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: 4495 s = "AsyncChannel.CMD_CHANNEL_HALF_CONNECTED"; 4496 break; 4497 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: 4498 s = "AsyncChannel.CMD_CHANNEL_DISCONNECTED"; 4499 break; 4500 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 4501 s = "WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST"; 4502 break; 4503 case WifiManager.DISABLE_NETWORK: 4504 s = "WifiManager.DISABLE_NETWORK"; 4505 break; 4506 case WifiManager.CONNECT_NETWORK: 4507 s = "CONNECT_NETWORK"; 4508 break; 4509 case WifiManager.SAVE_NETWORK: 4510 s = "SAVE_NETWORK"; 4511 break; 4512 case WifiManager.FORGET_NETWORK: 4513 s = "FORGET_NETWORK"; 4514 break; 4515 case WifiMonitor.SUP_CONNECTION_EVENT: 4516 s = "SUP_CONNECTION_EVENT"; 4517 break; 4518 case WifiMonitor.SUP_DISCONNECTION_EVENT: 4519 s = "SUP_DISCONNECTION_EVENT"; 4520 break; 4521 case WifiMonitor.SCAN_RESULTS_EVENT: 4522 s = "SCAN_RESULTS_EVENT"; 4523 break; 4524 case WifiMonitor.SCAN_FAILED_EVENT: 4525 s = "SCAN_FAILED_EVENT"; 4526 break; 4527 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 4528 s = "SUPPLICANT_STATE_CHANGE_EVENT"; 4529 break; 4530 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 4531 s = "AUTHENTICATION_FAILURE_EVENT"; 4532 break; 4533 case WifiMonitor.SSID_TEMP_DISABLED: 4534 s = "SSID_TEMP_DISABLED"; 4535 break; 4536 case WifiMonitor.SSID_REENABLED: 4537 s = "SSID_REENABLED"; 4538 break; 4539 case WifiMonitor.WPS_SUCCESS_EVENT: 4540 s = "WPS_SUCCESS_EVENT"; 4541 break; 4542 case WifiMonitor.WPS_FAIL_EVENT: 4543 s = "WPS_FAIL_EVENT"; 4544 break; 4545 case WifiMonitor.SUP_REQUEST_IDENTITY: 4546 s = "SUP_REQUEST_IDENTITY"; 4547 break; 4548 case WifiMonitor.NETWORK_CONNECTION_EVENT: 4549 s = "NETWORK_CONNECTION_EVENT"; 4550 break; 4551 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 4552 s = "NETWORK_DISCONNECTION_EVENT"; 4553 break; 4554 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 4555 s = "ASSOCIATION_REJECTION_EVENT"; 4556 break; 4557 case WifiMonitor.ANQP_DONE_EVENT: 4558 s = "WifiMonitor.ANQP_DONE_EVENT"; 4559 break; 4560 case WifiMonitor.RX_HS20_ANQP_ICON_EVENT: 4561 s = "WifiMonitor.RX_HS20_ANQP_ICON_EVENT"; 4562 break; 4563 case WifiMonitor.GAS_QUERY_DONE_EVENT: 4564 s = "WifiMonitor.GAS_QUERY_DONE_EVENT"; 4565 break; 4566 case WifiMonitor.HS20_REMEDIATION_EVENT: 4567 s = "WifiMonitor.HS20_REMEDIATION_EVENT"; 4568 break; 4569 case WifiMonitor.GAS_QUERY_START_EVENT: 4570 s = "WifiMonitor.GAS_QUERY_START_EVENT"; 4571 break; 4572 case WifiP2pServiceImpl.GROUP_CREATING_TIMED_OUT: 4573 s = "GROUP_CREATING_TIMED_OUT"; 4574 break; 4575 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 4576 s = "P2P_CONNECTION_CHANGED"; 4577 break; 4578 case WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE: 4579 s = "P2P.DISCONNECT_WIFI_RESPONSE"; 4580 break; 4581 case WifiP2pServiceImpl.SET_MIRACAST_MODE: 4582 s = "P2P.SET_MIRACAST_MODE"; 4583 break; 4584 case WifiP2pServiceImpl.BLOCK_DISCOVERY: 4585 s = "P2P.BLOCK_DISCOVERY"; 4586 break; 4587 case WifiManager.CANCEL_WPS: 4588 s = "CANCEL_WPS"; 4589 break; 4590 case WifiManager.CANCEL_WPS_FAILED: 4591 s = "CANCEL_WPS_FAILED"; 4592 break; 4593 case WifiManager.CANCEL_WPS_SUCCEDED: 4594 s = "CANCEL_WPS_SUCCEDED"; 4595 break; 4596 case WifiManager.START_WPS: 4597 s = "START_WPS"; 4598 break; 4599 case WifiManager.START_WPS_SUCCEEDED: 4600 s = "START_WPS_SUCCEEDED"; 4601 break; 4602 case WifiManager.WPS_FAILED: 4603 s = "WPS_FAILED"; 4604 break; 4605 case WifiManager.WPS_COMPLETED: 4606 s = "WPS_COMPLETED"; 4607 break; 4608 case WifiManager.RSSI_PKTCNT_FETCH: 4609 s = "RSSI_PKTCNT_FETCH"; 4610 break; 4611 default: 4612 s = "what:" + Integer.toString(what); 4613 break; 4614 } 4615 return s; 4616 } 4617 4618 void registerConnected() { 4619 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 4620 mWifiConfigManager.updateNetworkAfterConnect(mLastNetworkId); 4621 // On connect, reset wifiScoreReport 4622 mWifiScoreReport.reset(); 4623 } 4624 } 4625 4626 void registerDisconnected() { 4627 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 4628 mWifiConfigManager.updateNetworkAfterDisconnect(mLastNetworkId); 4629 // We are switching away from this configuration, 4630 // hence record the time we were connected last 4631 WifiConfiguration config = mWifiConfigManager.getConfiguredNetwork(mLastNetworkId); 4632 if (config != null) { 4633 // Remove WifiConfiguration for ephemeral or Passpoint networks, since they're 4634 // temporary networks. 4635 if (config.ephemeral || config.isPasspoint()) { 4636 mWifiConfigManager.removeNetwork(mLastNetworkId, Process.WIFI_UID); 4637 } 4638 } 4639 } 4640 } 4641 4642 /** 4643 * Returns Wificonfiguration object correponding to the currently connected network, null if 4644 * not connected. 4645 */ 4646 public WifiConfiguration getCurrentWifiConfiguration() { 4647 if (mLastNetworkId == WifiConfiguration.INVALID_NETWORK_ID) { 4648 return null; 4649 } 4650 return mWifiConfigManager.getConfiguredNetwork(mLastNetworkId); 4651 } 4652 4653 ScanResult getCurrentScanResult() { 4654 WifiConfiguration config = getCurrentWifiConfiguration(); 4655 if (config == null) { 4656 return null; 4657 } 4658 String BSSID = mWifiInfo.getBSSID(); 4659 if (BSSID == null) { 4660 BSSID = mTargetRoamBSSID; 4661 } 4662 ScanDetailCache scanDetailCache = 4663 mWifiConfigManager.getScanDetailCacheForNetwork(config.networkId); 4664 4665 if (scanDetailCache == null) { 4666 return null; 4667 } 4668 4669 return scanDetailCache.get(BSSID); 4670 } 4671 4672 String getCurrentBSSID() { 4673 if (isLinkDebouncing()) { 4674 return null; 4675 } 4676 return mLastBssid; 4677 } 4678 4679 class ConnectModeState extends State { 4680 4681 @Override 4682 public void enter() { 4683 // Let the system know that wifi is available in client mode. 4684 setWifiState(WIFI_STATE_ENABLED); 4685 4686 mNetworkInfo.setIsAvailable(true); 4687 if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo); 4688 4689 // initialize network state 4690 setNetworkDetailedState(DetailedState.DISCONNECTED); 4691 4692 4693 // Inform WifiConnectivityManager that Wifi is enabled 4694 mWifiConnectivityManager.setWifiEnabled(true); 4695 // Inform metrics that Wifi is Enabled (but not yet connected) 4696 mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_DISCONNECTED); 4697 // Inform p2p service that wifi is up and ready when applicable 4698 p2pSendMessage(WifiStateMachine.CMD_ENABLE_P2P); 4699 } 4700 4701 @Override 4702 public void exit() { 4703 // Let the system know that wifi is not available since we are exiting client mode. 4704 mNetworkInfo.setIsAvailable(false); 4705 if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo); 4706 // Inform WifiConnectivityManager that Wifi is disabled 4707 mWifiConnectivityManager.setWifiEnabled(false); 4708 // Inform metrics that Wifi is being disabled (Toggled, airplane enabled, etc) 4709 mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_DISABLED); 4710 } 4711 4712 @Override 4713 public boolean processMessage(Message message) { 4714 WifiConfiguration config; 4715 int netId; 4716 boolean ok; 4717 boolean didDisconnect; 4718 String bssid; 4719 String ssid; 4720 NetworkUpdateResult result; 4721 Set<Integer> removedNetworkIds; 4722 int reasonCode; 4723 boolean timedOut; 4724 logStateAndMessage(message, this); 4725 4726 switch (message.what) { 4727 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 4728 mWifiDiagnostics.captureBugReportData( 4729 WifiDiagnostics.REPORT_REASON_ASSOC_FAILURE); 4730 didBlackListBSSID = false; 4731 bssid = (String) message.obj; 4732 timedOut = message.arg1 > 0; 4733 reasonCode = message.arg2; 4734 Log.d(TAG, "Assocation Rejection event: bssid=" + bssid + " reason code=" 4735 + reasonCode + " timedOut=" + Boolean.toString(timedOut)); 4736 if (bssid == null || TextUtils.isEmpty(bssid)) { 4737 // If BSSID is null, use the target roam BSSID 4738 bssid = mTargetRoamBSSID; 4739 } 4740 if (bssid != null) { 4741 // If we have a BSSID, tell configStore to black list it 4742 didBlackListBSSID = mWifiConnectivityManager.trackBssid(bssid, false, 4743 reasonCode); 4744 } 4745 mWifiConfigManager.updateNetworkSelectionStatus(mTargetNetworkId, 4746 WifiConfiguration.NetworkSelectionStatus 4747 .DISABLED_ASSOCIATION_REJECTION); 4748 mSupplicantStateTracker.sendMessage(WifiMonitor.ASSOCIATION_REJECTION_EVENT); 4749 //If rejection occurred while Metrics is tracking a ConnnectionEvent, end it. 4750 reportConnectionAttemptEnd( 4751 WifiMetrics.ConnectionEvent.FAILURE_ASSOCIATION_REJECTION, 4752 WifiMetricsProto.ConnectionEvent.HLF_NONE); 4753 mWifiInjector.getWifiLastResortWatchdog() 4754 .noteConnectionFailureAndTriggerIfNeeded( 4755 getTargetSsid(), bssid, 4756 WifiLastResortWatchdog.FAILURE_CODE_ASSOCIATION); 4757 break; 4758 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 4759 mWifiDiagnostics.captureBugReportData( 4760 WifiDiagnostics.REPORT_REASON_AUTH_FAILURE); 4761 mSupplicantStateTracker.sendMessage(WifiMonitor.AUTHENTICATION_FAILURE_EVENT); 4762 // In case of wrong password, rely on SSID_TEMP_DISABLE event to update 4763 // the WifiConfigManager 4764 if ((message.arg2 != WifiMonitor.AUTHENTICATION_FAILURE_REASON_WRONG_PSWD) 4765 && (mTargetNetworkId != WifiConfiguration.INVALID_NETWORK_ID)) { 4766 mWifiConfigManager.updateNetworkSelectionStatus(mTargetNetworkId, 4767 WifiConfiguration.NetworkSelectionStatus 4768 .DISABLED_AUTHENTICATION_FAILURE); 4769 } 4770 //If failure occurred while Metrics is tracking a ConnnectionEvent, end it. 4771 reportConnectionAttemptEnd( 4772 WifiMetrics.ConnectionEvent.FAILURE_AUTHENTICATION_FAILURE, 4773 WifiMetricsProto.ConnectionEvent.HLF_NONE); 4774 mWifiInjector.getWifiLastResortWatchdog() 4775 .noteConnectionFailureAndTriggerIfNeeded( 4776 getTargetSsid(), mTargetRoamBSSID, 4777 WifiLastResortWatchdog.FAILURE_CODE_AUTHENTICATION); 4778 break; 4779 case WifiMonitor.SSID_TEMP_DISABLED: 4780 netId = lookupFrameworkNetworkId(message.arg1); 4781 Log.e(TAG, "Supplicant SSID temporary disabled:" 4782 + mWifiConfigManager.getConfiguredNetwork(netId)); 4783 mWifiConfigManager.updateNetworkSelectionStatus( 4784 netId, 4785 WifiConfiguration.NetworkSelectionStatus 4786 .DISABLED_AUTHENTICATION_FAILURE); 4787 reportConnectionAttemptEnd( 4788 WifiMetrics.ConnectionEvent.FAILURE_SSID_TEMP_DISABLED, 4789 WifiMetricsProto.ConnectionEvent.HLF_NONE); 4790 mWifiInjector.getWifiLastResortWatchdog() 4791 .noteConnectionFailureAndTriggerIfNeeded( 4792 getTargetSsid(), mTargetRoamBSSID, 4793 WifiLastResortWatchdog.FAILURE_CODE_AUTHENTICATION); 4794 break; 4795 case WifiMonitor.SSID_REENABLED: 4796 netId = lookupFrameworkNetworkId(message.arg1); 4797 Log.d(TAG, "Supplicant SSID reenable:" 4798 + mWifiConfigManager.getConfiguredNetwork(netId)); 4799 // Do not re-enable it in Quality Network Selection since framework has its own 4800 // Algorithm of disable/enable 4801 break; 4802 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 4803 SupplicantState state = handleSupplicantStateChange(message); 4804 // A driver/firmware hang can now put the interface in a down state. 4805 // We detect the interface going down and recover from it 4806 if (!SupplicantState.isDriverActive(state)) { 4807 if (mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) { 4808 handleNetworkDisconnect(); 4809 } 4810 log("Detected an interface down, restart driver"); 4811 // Rely on the fact that this will force us into killing supplicant and then 4812 // restart supplicant from a clean state. 4813 transitionTo(mSupplicantStoppingState); 4814 sendMessage(CMD_START_SUPPLICANT); 4815 break; 4816 } 4817 4818 // Supplicant can fail to report a NETWORK_DISCONNECTION_EVENT 4819 // when authentication times out after a successful connection, 4820 // we can figure this from the supplicant state. If supplicant 4821 // state is DISCONNECTED, but the mNetworkInfo says we are not 4822 // disconnected, we need to handle a disconnection 4823 if (!isLinkDebouncing() && state == SupplicantState.DISCONNECTED && 4824 mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) { 4825 if (mVerboseLoggingEnabled) { 4826 log("Missed CTRL-EVENT-DISCONNECTED, disconnect"); 4827 } 4828 handleNetworkDisconnect(); 4829 transitionTo(mDisconnectedState); 4830 } 4831 4832 // If we have COMPLETED a connection to a BSSID, start doing 4833 // DNAv4/DNAv6 -style probing for on-link neighbors of 4834 // interest (e.g. routers); harmless if none are configured. 4835 if (state == SupplicantState.COMPLETED) { 4836 mIpManager.confirmConfiguration(); 4837 } 4838 break; 4839 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 4840 if (message.arg1 == 1) { 4841 mWifiNative.disconnect(); 4842 mTemporarilyDisconnectWifi = true; 4843 } else { 4844 mWifiNative.reconnect(); 4845 mTemporarilyDisconnectWifi = false; 4846 } 4847 break; 4848 case CMD_ADD_OR_UPDATE_NETWORK: 4849 config = (WifiConfiguration) message.obj; 4850 result = mWifiConfigManager.addOrUpdateNetwork(config, message.sendingUid); 4851 if (!result.isSuccess()) { 4852 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 4853 } 4854 replyToMessage(message, message.what, result.getNetworkId()); 4855 break; 4856 case CMD_REMOVE_NETWORK: 4857 if (!deleteNetworkConfigAndSendReply(message, false)) { 4858 // failed to remove the config and caller was notified 4859 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 4860 break; 4861 } 4862 // we successfully deleted the network config 4863 netId = message.arg1; 4864 if (netId == mTargetNetworkId || netId == mLastNetworkId) { 4865 // Disconnect and let autojoin reselect a new network 4866 sendMessage(CMD_DISCONNECT); 4867 } 4868 break; 4869 case CMD_ENABLE_NETWORK: 4870 boolean disableOthers = message.arg2 == 1; 4871 netId = message.arg1; 4872 if (disableOthers) { 4873 // If the app has all the necessary permissions, this will trigger a connect 4874 // attempt. 4875 ok = connectToUserSelectNetwork(netId, message.sendingUid); 4876 } else { 4877 ok = mWifiConfigManager.enableNetwork(netId, false, message.sendingUid); 4878 } 4879 if (!ok) { 4880 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 4881 } 4882 replyToMessage(message, message.what, ok ? SUCCESS : FAILURE); 4883 break; 4884 case WifiManager.DISABLE_NETWORK: 4885 netId = message.arg1; 4886 if (mWifiConfigManager.disableNetwork(netId, message.sendingUid)) { 4887 replyToMessage(message, WifiManager.DISABLE_NETWORK_SUCCEEDED); 4888 if (netId == mTargetNetworkId || netId == mLastNetworkId) { 4889 // Disconnect and let autojoin reselect a new network 4890 sendMessage(CMD_DISCONNECT); 4891 } 4892 } else { 4893 loge("Failed to remove network"); 4894 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 4895 replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED, 4896 WifiManager.ERROR); 4897 } 4898 break; 4899 case CMD_DISABLE_EPHEMERAL_NETWORK: 4900 config = mWifiConfigManager.disableEphemeralNetwork((String)message.obj); 4901 if (config != null) { 4902 if (config.networkId == mTargetNetworkId 4903 || config.networkId == mLastNetworkId) { 4904 // Disconnect and let autojoin reselect a new network 4905 sendMessage(CMD_DISCONNECT); 4906 } 4907 } 4908 break; 4909 case CMD_SAVE_CONFIG: 4910 ok = mWifiConfigManager.saveToStore(true); 4911 replyToMessage(message, CMD_SAVE_CONFIG, ok ? SUCCESS : FAILURE); 4912 // Inform the backup manager about a data change 4913 mBackupManagerProxy.notifyDataChanged(); 4914 break; 4915 case WifiMonitor.SUP_REQUEST_IDENTITY: 4916 int supplicantNetworkId = message.arg2; 4917 netId = lookupFrameworkNetworkId(supplicantNetworkId); 4918 boolean identitySent = false; 4919 // For SIM & AKA/AKA' EAP method Only, get identity from ICC 4920 if (targetWificonfiguration != null 4921 && targetWificonfiguration.networkId == netId 4922 && TelephonyUtil.isSimConfig(targetWificonfiguration)) { 4923 String identity = 4924 TelephonyUtil.getSimIdentity(getTelephonyManager(), 4925 targetWificonfiguration); 4926 if (identity != null) { 4927 mWifiNative.simIdentityResponse(supplicantNetworkId, identity); 4928 identitySent = true; 4929 } else { 4930 Log.e(TAG, "Unable to retrieve identity from Telephony"); 4931 } 4932 } 4933 if (!identitySent) { 4934 // Supplicant lacks credentials to connect to that network, hence black list 4935 ssid = (String) message.obj; 4936 if (targetWificonfiguration != null && ssid != null 4937 && targetWificonfiguration.SSID != null 4938 && targetWificonfiguration.SSID.equals("\"" + ssid + "\"")) { 4939 mWifiConfigManager.updateNetworkSelectionStatus( 4940 targetWificonfiguration.networkId, 4941 WifiConfiguration.NetworkSelectionStatus 4942 .DISABLED_AUTHENTICATION_NO_CREDENTIALS); 4943 } 4944 mWifiNative.disconnect(); 4945 } 4946 break; 4947 case WifiMonitor.SUP_REQUEST_SIM_AUTH: 4948 logd("Received SUP_REQUEST_SIM_AUTH"); 4949 SimAuthRequestData requestData = (SimAuthRequestData) message.obj; 4950 if (requestData != null) { 4951 if (requestData.protocol == WifiEnterpriseConfig.Eap.SIM) { 4952 handleGsmAuthRequest(requestData); 4953 } else if (requestData.protocol == WifiEnterpriseConfig.Eap.AKA 4954 || requestData.protocol == WifiEnterpriseConfig.Eap.AKA_PRIME) { 4955 handle3GAuthRequest(requestData); 4956 } 4957 } else { 4958 loge("Invalid sim auth request"); 4959 } 4960 break; 4961 case CMD_GET_MATCHING_CONFIG: 4962 replyToMessage(message, message.what, 4963 mPasspointManager.getMatchingWifiConfig((ScanResult) message.obj)); 4964 break; 4965 case CMD_RECONNECT: 4966 mWifiConnectivityManager.forceConnectivityScan(); 4967 break; 4968 case CMD_REASSOCIATE: 4969 lastConnectAttemptTimestamp = mClock.getWallClockMillis(); 4970 mWifiNative.reassociate(); 4971 break; 4972 case CMD_RELOAD_TLS_AND_RECONNECT: 4973 if (mWifiConfigManager.needsUnlockedKeyStore()) { 4974 logd("Reconnecting to give a chance to un-connected TLS networks"); 4975 mWifiNative.disconnect(); 4976 lastConnectAttemptTimestamp = mClock.getWallClockMillis(); 4977 mWifiNative.reconnect(); 4978 } 4979 break; 4980 case CMD_START_ROAM: 4981 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 4982 return HANDLED; 4983 case CMD_START_CONNECT: 4984 /* connect command coming from auto-join */ 4985 netId = message.arg1; 4986 bssid = (String) message.obj; 4987 config = mWifiConfigManager.getConfiguredNetworkWithPassword(netId); 4988 logd("CMD_START_CONNECT sup state " 4989 + mSupplicantStateTracker.getSupplicantStateName() 4990 + " my state " + getCurrentState().getName() 4991 + " nid=" + Integer.toString(netId) 4992 + " roam=" + Boolean.toString(mAutoRoaming)); 4993 if (config == null) { 4994 loge("CMD_START_CONNECT and no config, bail out..."); 4995 break; 4996 } 4997 mTargetNetworkId = netId; 4998 setTargetBssid(config, bssid); 4999 5000 reportConnectionAttemptStart(config, mTargetRoamBSSID, 5001 WifiMetricsProto.ConnectionEvent.ROAM_UNRELATED); 5002 boolean shouldDisconnect = (getCurrentState() != mDisconnectedState); 5003 if (mWifiNative.connectToNetwork(config, shouldDisconnect)) { 5004 lastConnectAttemptTimestamp = mClock.getWallClockMillis(); 5005 targetWificonfiguration = config; 5006 mAutoRoaming = false; 5007 if (isRoaming() || isLinkDebouncing()) { 5008 transitionTo(mRoamingState); 5009 } else if (shouldDisconnect) { 5010 transitionTo(mDisconnectingState); 5011 } else { 5012 transitionTo(mDisconnectedState); 5013 } 5014 } else { 5015 loge("CMD_START_CONNECT Failed to start connection to network " + config); 5016 reportConnectionAttemptEnd( 5017 WifiMetrics.ConnectionEvent.FAILURE_CONNECT_NETWORK_FAILED, 5018 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5019 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 5020 WifiManager.ERROR); 5021 break; 5022 } 5023 break; 5024 case CMD_REMOVE_APP_CONFIGURATIONS: 5025 removedNetworkIds = 5026 mWifiConfigManager.removeNetworksForApp((ApplicationInfo) message.obj); 5027 if (removedNetworkIds.contains(mTargetNetworkId) || 5028 removedNetworkIds.contains(mLastNetworkId)) { 5029 // Disconnect and let autojoin reselect a new network. 5030 sendMessage(CMD_DISCONNECT); 5031 } 5032 break; 5033 case CMD_REMOVE_USER_CONFIGURATIONS: 5034 removedNetworkIds = 5035 mWifiConfigManager.removeNetworksForUser((Integer) message.arg1); 5036 if (removedNetworkIds.contains(mTargetNetworkId) || 5037 removedNetworkIds.contains(mLastNetworkId)) { 5038 // Disconnect and let autojoin reselect a new network. 5039 sendMessage(CMD_DISCONNECT); 5040 } 5041 break; 5042 case WifiManager.CONNECT_NETWORK: 5043 /** 5044 * The connect message can contain a network id passed as arg1 on message or 5045 * or a config passed as obj on message. 5046 * For a new network, a config is passed to create and connect. 5047 * For an existing network, a network id is passed 5048 */ 5049 netId = message.arg1; 5050 config = (WifiConfiguration) message.obj; 5051 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 5052 // New network addition. 5053 if (config != null) { 5054 result = mWifiConfigManager.addOrUpdateNetwork(config, message.sendingUid); 5055 if (!result.isSuccess()) { 5056 loge("CONNECT_NETWORK adding/updating config=" + config + " failed"); 5057 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5058 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 5059 WifiManager.ERROR); 5060 break; 5061 } 5062 netId = result.getNetworkId(); 5063 } 5064 if (!connectToUserSelectNetwork(netId, message.sendingUid)) { 5065 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5066 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 5067 WifiManager.NOT_AUTHORIZED); 5068 break; 5069 } 5070 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_SAVED, config); 5071 replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED); 5072 break; 5073 case WifiManager.SAVE_NETWORK: 5074 config = (WifiConfiguration) message.obj; 5075 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 5076 if (config == null) { 5077 loge("SAVE_NETWORK with null configuration" 5078 + mSupplicantStateTracker.getSupplicantStateName() 5079 + " my state " + getCurrentState().getName()); 5080 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5081 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 5082 WifiManager.ERROR); 5083 break; 5084 } 5085 result = mWifiConfigManager.addOrUpdateNetwork(config, message.sendingUid); 5086 if (!result.isSuccess()) { 5087 loge("SAVE_NETWORK adding/updating config=" + config + " failed"); 5088 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5089 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 5090 WifiManager.ERROR); 5091 break; 5092 } 5093 netId = result.getNetworkId(); 5094 if (mWifiInfo.getNetworkId() == netId) { 5095 if (result.hasIpChanged()) { 5096 // The currently connection configuration was changed 5097 // We switched from DHCP to static or from static to DHCP, or the 5098 // static IP address has changed. 5099 log("Reconfiguring IP on connection"); 5100 // TODO: clear addresses and disable IPv6 5101 // to simplify obtainingIpState. 5102 transitionTo(mObtainingIpState); 5103 } 5104 if (result.hasProxyChanged()) { 5105 log("Reconfiguring proxy on connection"); 5106 mIpManager.setHttpProxy( 5107 getCurrentWifiConfiguration().getHttpProxy()); 5108 } 5109 } else { 5110 if (!connectToUserSelectNetwork(netId, message.sendingUid)) { 5111 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5112 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 5113 WifiManager.NOT_AUTHORIZED); 5114 break; 5115 } 5116 } 5117 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_SAVED, config); 5118 replyToMessage(message, WifiManager.SAVE_NETWORK_SUCCEEDED); 5119 break; 5120 case WifiManager.FORGET_NETWORK: 5121 if (!deleteNetworkConfigAndSendReply(message, true)) { 5122 // Caller was notified of failure, nothing else to do 5123 break; 5124 } 5125 // the network was deleted 5126 netId = message.arg1; 5127 if (netId == mTargetNetworkId || netId == mLastNetworkId) { 5128 // Disconnect and let autojoin reselect a new network 5129 sendMessage(CMD_DISCONNECT); 5130 } 5131 break; 5132 case WifiManager.START_WPS: 5133 WpsInfo wpsInfo = (WpsInfo) message.obj; 5134 WpsResult wpsResult = new WpsResult(); 5135 // TODO(b/32898136): Not needed when we start deleting networks from supplicant 5136 // on disconnect. 5137 if (!mWifiNative.removeAllNetworks()) { 5138 loge("Failed to remove networks before WPS"); 5139 } 5140 switch (wpsInfo.setup) { 5141 case WpsInfo.PBC: 5142 if (mWifiNative.startWpsPbc(wpsInfo.BSSID)) { 5143 wpsResult.status = WpsResult.Status.SUCCESS; 5144 } else { 5145 Log.e(TAG, "Failed to start WPS push button configuration"); 5146 wpsResult.status = WpsResult.Status.FAILURE; 5147 } 5148 break; 5149 case WpsInfo.KEYPAD: 5150 if (mWifiNative.startWpsRegistrar(wpsInfo.BSSID, wpsInfo.pin)) { 5151 wpsResult.status = WpsResult.Status.SUCCESS; 5152 } else { 5153 Log.e(TAG, "Failed to start WPS push button configuration"); 5154 wpsResult.status = WpsResult.Status.FAILURE; 5155 } 5156 break; 5157 case WpsInfo.DISPLAY: 5158 wpsResult.pin = mWifiNative.startWpsPinDisplay(wpsInfo.BSSID); 5159 if (!TextUtils.isEmpty(wpsResult.pin)) { 5160 wpsResult.status = WpsResult.Status.SUCCESS; 5161 } else { 5162 Log.e(TAG, "Failed to start WPS pin method configuration"); 5163 wpsResult.status = WpsResult.Status.FAILURE; 5164 } 5165 break; 5166 default: 5167 wpsResult = new WpsResult(Status.FAILURE); 5168 loge("Invalid setup for WPS"); 5169 break; 5170 } 5171 if (wpsResult.status == Status.SUCCESS) { 5172 replyToMessage(message, WifiManager.START_WPS_SUCCEEDED, wpsResult); 5173 transitionTo(mWpsRunningState); 5174 } else { 5175 loge("Failed to start WPS with config " + wpsInfo.toString()); 5176 replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.ERROR); 5177 } 5178 break; 5179 case CMD_ASSOCIATED_BSSID: 5180 // This is where we can confirm the connection BSSID. Use it to find the 5181 // right ScanDetail to populate metrics. 5182 String someBssid = (String) message.obj; 5183 if (someBssid != null) { 5184 // Get the ScanDetail associated with this BSSID. 5185 ScanDetailCache scanDetailCache = 5186 mWifiConfigManager.getScanDetailCacheForNetwork(mTargetNetworkId); 5187 if (scanDetailCache != null) { 5188 mWifiMetrics.setConnectionScanDetail(scanDetailCache.getScanDetail( 5189 someBssid)); 5190 } 5191 } 5192 return NOT_HANDLED; 5193 case WifiMonitor.NETWORK_CONNECTION_EVENT: 5194 if (mVerboseLoggingEnabled) log("Network connection established"); 5195 mLastNetworkId = lookupFrameworkNetworkId(message.arg1); 5196 mLastBssid = (String) message.obj; 5197 reasonCode = message.arg2; 5198 // TODO: This check should not be needed after WifiStateMachinePrime refactor. 5199 // Currently, the last connected network configuration is left in 5200 // wpa_supplicant, this may result in wpa_supplicant initiating connection 5201 // to it after a config store reload. Hence the old network Id lookups may not 5202 // work, so disconnect the network and let network selector reselect a new 5203 // network. 5204 if (getCurrentWifiConfiguration() != null) { 5205 mWifiInfo.setBSSID(mLastBssid); 5206 mWifiInfo.setNetworkId(mLastNetworkId); 5207 mWifiConnectivityManager.trackBssid(mLastBssid, true, reasonCode); 5208 sendNetworkStateChangeBroadcast(mLastBssid); 5209 transitionTo(mObtainingIpState); 5210 } else { 5211 logw("Connected to unknown networkId " + mLastNetworkId 5212 + ", disconnecting..."); 5213 sendMessage(CMD_DISCONNECT); 5214 } 5215 break; 5216 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 5217 // Calling handleNetworkDisconnect here is redundant because we might already 5218 // have called it when leaving L2ConnectedState to go to disconnecting state 5219 // or thru other path 5220 // We should normally check the mWifiInfo or mLastNetworkId so as to check 5221 // if they are valid, and only in this case call handleNEtworkDisconnect, 5222 // TODO: this should be fixed for a L MR release 5223 // The side effect of calling handleNetworkDisconnect twice is that a bunch of 5224 // idempotent commands are executed twice (stopping Dhcp, enabling the SPS mode 5225 // at the chip etc... 5226 if (mVerboseLoggingEnabled) log("ConnectModeState: Network connection lost "); 5227 handleNetworkDisconnect(); 5228 transitionTo(mDisconnectedState); 5229 break; 5230 case CMD_QUERY_OSU_ICON: 5231 mPasspointManager.queryPasspointIcon( 5232 ((Bundle) message.obj).getLong(EXTRA_OSU_ICON_QUERY_BSSID), 5233 ((Bundle) message.obj).getString(EXTRA_OSU_ICON_QUERY_FILENAME)); 5234 break; 5235 case CMD_MATCH_PROVIDER_NETWORK: 5236 // TODO(b/31065385): Passpoint config management. 5237 replyToMessage(message, message.what, 0); 5238 break; 5239 case CMD_REMOVE_PASSPOINT_CONFIG: 5240 String fqdn = (String) message.obj; 5241 if (mPasspointManager.removeProvider(fqdn)) { 5242 if (isProviderOwnedNetwork(mTargetNetworkId, fqdn) 5243 || isProviderOwnedNetwork(mLastNetworkId, fqdn)) { 5244 logd("Disconnect from current network since its provider is removed"); 5245 sendMessage(CMD_DISCONNECT); 5246 } 5247 replyToMessage(message, message.what, SUCCESS); 5248 } else { 5249 replyToMessage(message, message.what, FAILURE); 5250 } 5251 break; 5252 case CMD_ENABLE_P2P: 5253 p2pSendMessage(WifiStateMachine.CMD_ENABLE_P2P); 5254 break; 5255 default: 5256 return NOT_HANDLED; 5257 } 5258 return HANDLED; 5259 } 5260 } 5261 5262 private void updateCapabilities(WifiConfiguration config) { 5263 NetworkCapabilities networkCapabilities = new NetworkCapabilities(mDfltNetworkCapabilities); 5264 if (config != null) { 5265 if (config.ephemeral) { 5266 networkCapabilities.removeCapability( 5267 NetworkCapabilities.NET_CAPABILITY_TRUSTED); 5268 } else { 5269 networkCapabilities.addCapability( 5270 NetworkCapabilities.NET_CAPABILITY_TRUSTED); 5271 } 5272 5273 networkCapabilities.setSignalStrength( 5274 (mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI) 5275 ? mWifiInfo.getRssi() 5276 : NetworkCapabilities.SIGNAL_STRENGTH_UNSPECIFIED); 5277 } 5278 5279 if (mWifiInfo.getMeteredHint()) { 5280 networkCapabilities.removeCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED); 5281 } 5282 5283 mNetworkAgent.sendNetworkCapabilities(networkCapabilities); 5284 } 5285 5286 /** 5287 * Checks if the given network |networkdId| is provided by the given Passpoint provider with 5288 * |providerFqdn|. 5289 * 5290 * @param networkId The ID of the network to check 5291 * @param providerFqdn The FQDN of the Passpoint provider 5292 * @return true if the given network is provided by the given Passpoint provider 5293 */ 5294 private boolean isProviderOwnedNetwork(int networkId, String providerFqdn) { 5295 if (networkId == WifiConfiguration.INVALID_NETWORK_ID) { 5296 return false; 5297 } 5298 WifiConfiguration config = mWifiConfigManager.getConfiguredNetwork(networkId); 5299 if (config == null) { 5300 return false; 5301 } 5302 return TextUtils.equals(config.FQDN, providerFqdn); 5303 } 5304 5305 private class WifiNetworkAgent extends NetworkAgent { 5306 public WifiNetworkAgent(Looper l, Context c, String TAG, NetworkInfo ni, 5307 NetworkCapabilities nc, LinkProperties lp, int score, NetworkMisc misc) { 5308 super(l, c, TAG, ni, nc, lp, score, misc); 5309 } 5310 5311 @Override 5312 protected void unwanted() { 5313 // Ignore if we're not the current networkAgent. 5314 if (this != mNetworkAgent) return; 5315 if (mVerboseLoggingEnabled) { 5316 log("WifiNetworkAgent -> Wifi unwanted score " + Integer.toString(mWifiInfo.score)); 5317 } 5318 unwantedNetwork(NETWORK_STATUS_UNWANTED_DISCONNECT); 5319 } 5320 5321 @Override 5322 protected void networkStatus(int status, String redirectUrl) { 5323 if (this != mNetworkAgent) return; 5324 if (status == NetworkAgent.INVALID_NETWORK) { 5325 if (mVerboseLoggingEnabled) { 5326 log("WifiNetworkAgent -> Wifi networkStatus invalid, score=" 5327 + Integer.toString(mWifiInfo.score)); 5328 } 5329 unwantedNetwork(NETWORK_STATUS_UNWANTED_VALIDATION_FAILED); 5330 } else if (status == NetworkAgent.VALID_NETWORK) { 5331 if (mVerboseLoggingEnabled) { 5332 log("WifiNetworkAgent -> Wifi networkStatus valid, score= " 5333 + Integer.toString(mWifiInfo.score)); 5334 } 5335 doNetworkStatus(status); 5336 } 5337 } 5338 5339 @Override 5340 protected void saveAcceptUnvalidated(boolean accept) { 5341 if (this != mNetworkAgent) return; 5342 WifiStateMachine.this.sendMessage(CMD_ACCEPT_UNVALIDATED, accept ? 1 : 0); 5343 } 5344 5345 @Override 5346 protected void startPacketKeepalive(Message msg) { 5347 WifiStateMachine.this.sendMessage( 5348 CMD_START_IP_PACKET_OFFLOAD, msg.arg1, msg.arg2, msg.obj); 5349 } 5350 5351 @Override 5352 protected void stopPacketKeepalive(Message msg) { 5353 WifiStateMachine.this.sendMessage( 5354 CMD_STOP_IP_PACKET_OFFLOAD, msg.arg1, msg.arg2, msg.obj); 5355 } 5356 5357 @Override 5358 protected void setSignalStrengthThresholds(int[] thresholds) { 5359 // 0. If there are no thresholds, or if the thresholds are invalid, stop RSSI monitoring. 5360 // 1. Tell the hardware to start RSSI monitoring here, possibly adding MIN_VALUE and 5361 // MAX_VALUE at the start/end of the thresholds array if necessary. 5362 // 2. Ensure that when the hardware event fires, we fetch the RSSI from the hardware 5363 // event, call mWifiInfo.setRssi() with it, and call updateCapabilities(), and then 5364 // re-arm the hardware event. This needs to be done on the state machine thread to 5365 // avoid race conditions. The RSSI used to re-arm the event (and perhaps also the one 5366 // sent in the NetworkCapabilities) must be the one received from the hardware event 5367 // received, or we might skip callbacks. 5368 // 3. Ensure that when we disconnect, RSSI monitoring is stopped. 5369 log("Received signal strength thresholds: " + Arrays.toString(thresholds)); 5370 if (thresholds.length == 0) { 5371 WifiStateMachine.this.sendMessage(CMD_STOP_RSSI_MONITORING_OFFLOAD, 5372 mWifiInfo.getRssi()); 5373 return; 5374 } 5375 int [] rssiVals = Arrays.copyOf(thresholds, thresholds.length + 2); 5376 rssiVals[rssiVals.length - 2] = Byte.MIN_VALUE; 5377 rssiVals[rssiVals.length - 1] = Byte.MAX_VALUE; 5378 Arrays.sort(rssiVals); 5379 byte[] rssiRange = new byte[rssiVals.length]; 5380 for (int i = 0; i < rssiVals.length; i++) { 5381 int val = rssiVals[i]; 5382 if (val <= Byte.MAX_VALUE && val >= Byte.MIN_VALUE) { 5383 rssiRange[i] = (byte) val; 5384 } else { 5385 Log.e(TAG, "Illegal value " + val + " for RSSI thresholds: " 5386 + Arrays.toString(rssiVals)); 5387 WifiStateMachine.this.sendMessage(CMD_STOP_RSSI_MONITORING_OFFLOAD, 5388 mWifiInfo.getRssi()); 5389 return; 5390 } 5391 } 5392 // TODO: Do we quash rssi values in this sorted array which are very close? 5393 mRssiRanges = rssiRange; 5394 WifiStateMachine.this.sendMessage(CMD_START_RSSI_MONITORING_OFFLOAD, 5395 mWifiInfo.getRssi()); 5396 } 5397 5398 @Override 5399 protected void preventAutomaticReconnect() { 5400 if (this != mNetworkAgent) return; 5401 unwantedNetwork(NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN); 5402 } 5403 } 5404 5405 void unwantedNetwork(int reason) { 5406 sendMessage(CMD_UNWANTED_NETWORK, reason); 5407 } 5408 5409 void doNetworkStatus(int status) { 5410 sendMessage(CMD_NETWORK_STATUS, status); 5411 } 5412 5413 // rfc4186 & rfc4187: 5414 // create Permanent Identity base on IMSI, 5415 // identity = usernam@realm 5416 // with username = prefix | IMSI 5417 // and realm is derived MMC/MNC tuple according 3GGP spec(TS23.003) 5418 private String buildIdentity(int eapMethod, String imsi, String mccMnc) { 5419 String mcc; 5420 String mnc; 5421 String prefix; 5422 5423 if (imsi == null || imsi.isEmpty()) 5424 return ""; 5425 5426 if (eapMethod == WifiEnterpriseConfig.Eap.SIM) 5427 prefix = "1"; 5428 else if (eapMethod == WifiEnterpriseConfig.Eap.AKA) 5429 prefix = "0"; 5430 else if (eapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME) 5431 prefix = "6"; 5432 else // not a valide EapMethod 5433 return ""; 5434 5435 /* extract mcc & mnc from mccMnc */ 5436 if (mccMnc != null && !mccMnc.isEmpty()) { 5437 mcc = mccMnc.substring(0, 3); 5438 mnc = mccMnc.substring(3); 5439 if (mnc.length() == 2) 5440 mnc = "0" + mnc; 5441 } else { 5442 // extract mcc & mnc from IMSI, assume mnc size is 3 5443 mcc = imsi.substring(0, 3); 5444 mnc = imsi.substring(3, 6); 5445 } 5446 5447 return prefix + imsi + "@wlan.mnc" + mnc + ".mcc" + mcc + ".3gppnetwork.org"; 5448 } 5449 5450 boolean startScanForConfiguration(WifiConfiguration config) { 5451 if (config == null) 5452 return false; 5453 5454 // We are still seeing a fairly high power consumption triggered by autojoin scans 5455 // Hence do partial scans only for PSK configuration that are roamable since the 5456 // primary purpose of the partial scans is roaming. 5457 // Full badn scans with exponential backoff for the purpose or extended roaming and 5458 // network switching are performed unconditionally. 5459 ScanDetailCache scanDetailCache = 5460 mWifiConfigManager.getScanDetailCacheForNetwork(config.networkId); 5461 if (scanDetailCache == null 5462 || !config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK) 5463 || scanDetailCache.size() > 6) { 5464 //return true but to not trigger the scan 5465 return true; 5466 } 5467 Set<Integer> freqs = 5468 mWifiConfigManager.fetchChannelSetForNetworkForPartialScan( 5469 config.networkId, ONE_HOUR_MILLI, mWifiInfo.getFrequency()); 5470 if (freqs != null && freqs.size() != 0) { 5471 //if (mVerboseLoggingEnabled) { 5472 logd("starting scan for " + config.configKey() + " with " + freqs); 5473 //} 5474 List<WifiScanner.ScanSettings.HiddenNetwork> hiddenNetworks = new ArrayList<>(); 5475 if (config.hiddenSSID) { 5476 hiddenNetworks.add(new WifiScanner.ScanSettings.HiddenNetwork(config.SSID)); 5477 } 5478 // Call wifi native to start the scan 5479 if (startScanNative(freqs, hiddenNetworks, WIFI_WORK_SOURCE)) { 5480 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK; 5481 } else { 5482 // used for debug only, mark scan as failed 5483 messageHandlingStatus = MESSAGE_HANDLING_STATUS_HANDLING_ERROR; 5484 } 5485 return true; 5486 } else { 5487 if (mVerboseLoggingEnabled) logd("no channels for " + config.configKey()); 5488 return false; 5489 } 5490 } 5491 5492 class L2ConnectedState extends State { 5493 @Override 5494 public void enter() { 5495 mRssiPollToken++; 5496 if (mEnableRssiPolling) { 5497 sendMessage(CMD_RSSI_POLL, mRssiPollToken, 0); 5498 } 5499 if (mNetworkAgent != null) { 5500 loge("Have NetworkAgent when entering L2Connected"); 5501 setNetworkDetailedState(DetailedState.DISCONNECTED); 5502 } 5503 setNetworkDetailedState(DetailedState.CONNECTING); 5504 5505 mNetworkAgent = new WifiNetworkAgent(getHandler().getLooper(), mContext, 5506 "WifiNetworkAgent", mNetworkInfo, mNetworkCapabilitiesFilter, 5507 mLinkProperties, 60, mNetworkMisc); 5508 5509 // We must clear the config BSSID, as the wifi chipset may decide to roam 5510 // from this point on and having the BSSID specified in the network block would 5511 // cause the roam to faile and the device to disconnect 5512 clearTargetBssid("L2ConnectedState"); 5513 mCountryCode.setReadyForChange(false); 5514 mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_ASSOCIATED); 5515 } 5516 5517 @Override 5518 public void exit() { 5519 mIpManager.stop(); 5520 5521 // This is handled by receiving a NETWORK_DISCONNECTION_EVENT in ConnectModeState 5522 // Bug: 15347363 5523 // For paranoia's sake, call handleNetworkDisconnect 5524 // only if BSSID is null or last networkId 5525 // is not invalid. 5526 if (mVerboseLoggingEnabled) { 5527 StringBuilder sb = new StringBuilder(); 5528 sb.append("leaving L2ConnectedState state nid=" + Integer.toString(mLastNetworkId)); 5529 if (mLastBssid !=null) { 5530 sb.append(" ").append(mLastBssid); 5531 } 5532 } 5533 if (mLastBssid != null || mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 5534 handleNetworkDisconnect(); 5535 } 5536 mCountryCode.setReadyForChange(true); 5537 mWifiMetrics.setWifiState(WifiMetricsProto.WifiLog.WIFI_DISCONNECTED); 5538 } 5539 5540 @Override 5541 public boolean processMessage(Message message) { 5542 logStateAndMessage(message, this); 5543 5544 switch (message.what) { 5545 case DhcpClient.CMD_PRE_DHCP_ACTION: 5546 handlePreDhcpSetup(); 5547 break; 5548 case DhcpClient.CMD_PRE_DHCP_ACTION_COMPLETE: 5549 mIpManager.completedPreDhcpAction(); 5550 break; 5551 case DhcpClient.CMD_POST_DHCP_ACTION: 5552 handlePostDhcpSetup(); 5553 // We advance to mConnectedState because IpManager will also send a 5554 // CMD_IPV4_PROVISIONING_SUCCESS message, which calls handleIPv4Success(), 5555 // which calls updateLinkProperties, which then sends 5556 // CMD_IP_CONFIGURATION_SUCCESSFUL. 5557 // 5558 // In the event of failure, we transition to mDisconnectingState 5559 // similarly--via messages sent back from IpManager. 5560 break; 5561 case CMD_IPV4_PROVISIONING_SUCCESS: { 5562 handleIPv4Success((DhcpResults) message.obj); 5563 sendNetworkStateChangeBroadcast(mLastBssid); 5564 break; 5565 } 5566 case CMD_IPV4_PROVISIONING_FAILURE: { 5567 handleIPv4Failure(); 5568 break; 5569 } 5570 case CMD_IP_CONFIGURATION_SUCCESSFUL: 5571 handleSuccessfulIpConfiguration(); 5572 reportConnectionAttemptEnd( 5573 WifiMetrics.ConnectionEvent.FAILURE_NONE, 5574 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5575 sendConnectedState(); 5576 transitionTo(mConnectedState); 5577 break; 5578 case CMD_IP_CONFIGURATION_LOST: 5579 // Get Link layer stats so that we get fresh tx packet counters. 5580 getWifiLinkLayerStats(); 5581 handleIpConfigurationLost(); 5582 reportConnectionAttemptEnd( 5583 WifiMetrics.ConnectionEvent.FAILURE_DHCP, 5584 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5585 transitionTo(mDisconnectingState); 5586 break; 5587 case CMD_IP_REACHABILITY_LOST: 5588 if (mVerboseLoggingEnabled && message.obj != null) log((String) message.obj); 5589 if (mIpReachabilityDisconnectEnabled) { 5590 handleIpReachabilityLost(); 5591 transitionTo(mDisconnectingState); 5592 } else { 5593 logd("CMD_IP_REACHABILITY_LOST but disconnect disabled -- ignore"); 5594 } 5595 break; 5596 case CMD_DISCONNECT: 5597 mWifiNative.disconnect(); 5598 transitionTo(mDisconnectingState); 5599 break; 5600 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 5601 if (message.arg1 == 1) { 5602 mWifiNative.disconnect(); 5603 mTemporarilyDisconnectWifi = true; 5604 transitionTo(mDisconnectingState); 5605 } 5606 break; 5607 case CMD_SET_OPERATIONAL_MODE: 5608 if (message.arg1 != CONNECT_MODE) { 5609 sendMessage(CMD_DISCONNECT); 5610 deferMessage(message); 5611 } 5612 break; 5613 /* Ignore connection to same network */ 5614 case WifiManager.CONNECT_NETWORK: 5615 int netId = message.arg1; 5616 if (mWifiInfo.getNetworkId() == netId) { 5617 replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED); 5618 break; 5619 } 5620 return NOT_HANDLED; 5621 case WifiMonitor.NETWORK_CONNECTION_EVENT: 5622 mWifiInfo.setBSSID((String) message.obj); 5623 mLastNetworkId = lookupFrameworkNetworkId(message.arg1); 5624 mWifiInfo.setNetworkId(mLastNetworkId); 5625 if(!mLastBssid.equals(message.obj)) { 5626 mLastBssid = (String) message.obj; 5627 sendNetworkStateChangeBroadcast(mLastBssid); 5628 } 5629 break; 5630 case CMD_RSSI_POLL: 5631 if (message.arg1 == mRssiPollToken) { 5632 if (mEnableChipWakeUpWhenAssociated) { 5633 if (mVerboseLoggingEnabled) { 5634 log(" get link layer stats " + mWifiLinkLayerStatsSupported); 5635 } 5636 WifiLinkLayerStats stats = getWifiLinkLayerStats(); 5637 if (stats != null) { 5638 // Sanity check the results provided by driver 5639 if (mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI 5640 && (stats.rssi_mgmt == 0 5641 || stats.beacon_rx == 0)) { 5642 stats = null; 5643 } 5644 } 5645 // Get Info and continue polling 5646 fetchRssiLinkSpeedAndFrequencyNative(); 5647 // Send the update score to network agent. 5648 mWifiScoreReport.calculateAndReportScore( 5649 mWifiInfo, mNetworkAgent, mAggressiveHandover, 5650 mWifiMetrics); 5651 } 5652 sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, 5653 mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS); 5654 if (mVerboseLoggingEnabled) sendRssiChangeBroadcast(mWifiInfo.getRssi()); 5655 } else { 5656 // Polling has completed 5657 } 5658 break; 5659 case CMD_ENABLE_RSSI_POLL: 5660 cleanWifiScore(); 5661 if (mEnableRssiPollWhenAssociated) { 5662 mEnableRssiPolling = (message.arg1 == 1); 5663 } else { 5664 mEnableRssiPolling = false; 5665 } 5666 mRssiPollToken++; 5667 if (mEnableRssiPolling) { 5668 // First poll 5669 fetchRssiLinkSpeedAndFrequencyNative(); 5670 sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, 5671 mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS); 5672 } 5673 break; 5674 case WifiManager.RSSI_PKTCNT_FETCH: 5675 RssiPacketCountInfo info = new RssiPacketCountInfo(); 5676 fetchRssiLinkSpeedAndFrequencyNative(); 5677 info.rssi = mWifiInfo.getRssi(); 5678 WifiNative.TxPacketCounters counters = mWifiNative.getTxPacketCounters(); 5679 if (counters != null) { 5680 info.txgood = counters.txSucceeded; 5681 info.txbad = counters.txFailed; 5682 replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED, info); 5683 } else { 5684 replyToMessage(message, 5685 WifiManager.RSSI_PKTCNT_FETCH_FAILED, WifiManager.ERROR); 5686 } 5687 break; 5688 case CMD_DELAYED_NETWORK_DISCONNECT: 5689 if (!isLinkDebouncing()) { 5690 5691 // Ignore if we are not debouncing 5692 logd("CMD_DELAYED_NETWORK_DISCONNECT and not debouncing - ignore " 5693 + message.arg1); 5694 return HANDLED; 5695 } else { 5696 logd("CMD_DELAYED_NETWORK_DISCONNECT and debouncing - disconnect " 5697 + message.arg1); 5698 5699 mIsLinkDebouncing = false; 5700 // If we are still debouncing while this message comes, 5701 // it means we were not able to reconnect within the alloted time 5702 // = LINK_FLAPPING_DEBOUNCE_MSEC 5703 // and thus, trigger a real disconnect 5704 handleNetworkDisconnect(); 5705 transitionTo(mDisconnectedState); 5706 } 5707 break; 5708 case CMD_ASSOCIATED_BSSID: 5709 if ((String) message.obj == null) { 5710 logw("Associated command w/o BSSID"); 5711 break; 5712 } 5713 mLastBssid = (String) message.obj; 5714 if (mLastBssid != null && (mWifiInfo.getBSSID() == null 5715 || !mLastBssid.equals(mWifiInfo.getBSSID()))) { 5716 mWifiInfo.setBSSID((String) message.obj); 5717 sendNetworkStateChangeBroadcast(mLastBssid); 5718 } 5719 break; 5720 case CMD_START_RSSI_MONITORING_OFFLOAD: 5721 case CMD_RSSI_THRESHOLD_BREACH: 5722 byte currRssi = (byte) message.arg1; 5723 processRssiThreshold(currRssi, message.what); 5724 break; 5725 case CMD_STOP_RSSI_MONITORING_OFFLOAD: 5726 stopRssiMonitoringOffload(); 5727 break; 5728 case CMD_RESET_SIM_NETWORKS: 5729 if (message.arg1 == 0 // sim was removed 5730 && mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 5731 WifiConfiguration config = 5732 mWifiConfigManager.getConfiguredNetwork(mLastNetworkId); 5733 if (TelephonyUtil.isSimConfig(config)) { 5734 mWifiNative.disconnect(); 5735 transitionTo(mDisconnectingState); 5736 } 5737 } 5738 /* allow parent state to reset data for other networks */ 5739 return NOT_HANDLED; 5740 default: 5741 return NOT_HANDLED; 5742 } 5743 5744 return HANDLED; 5745 } 5746 } 5747 5748 class ObtainingIpState extends State { 5749 @Override 5750 public void enter() { 5751 WifiConfiguration currentConfig = getCurrentWifiConfiguration(); 5752 boolean isUsingStaticIp = 5753 (currentConfig.getIpAssignment() == IpConfiguration.IpAssignment.STATIC); 5754 if (mVerboseLoggingEnabled) { 5755 String key = ""; 5756 if (getCurrentWifiConfiguration() != null) { 5757 key = getCurrentWifiConfiguration().configKey(); 5758 } 5759 log("enter ObtainingIpState netId=" + Integer.toString(mLastNetworkId) 5760 + " " + key + " " 5761 + " roam=" + mAutoRoaming 5762 + " static=" + isUsingStaticIp); 5763 } 5764 5765 // Reset link Debouncing, indicating we have successfully re-connected to the AP 5766 // We might still be roaming 5767 mIsLinkDebouncing = false; 5768 5769 // Send event to CM & network change broadcast 5770 setNetworkDetailedState(DetailedState.OBTAINING_IPADDR); 5771 5772 // We must clear the config BSSID, as the wifi chipset may decide to roam 5773 // from this point on and having the BSSID specified in the network block would 5774 // cause the roam to fail and the device to disconnect. 5775 clearTargetBssid("ObtainingIpAddress"); 5776 5777 // Stop IpManager in case we're switching from DHCP to static 5778 // configuration or vice versa. 5779 // 5780 // TODO: Only ever enter this state the first time we connect to a 5781 // network, never on switching between static configuration and 5782 // DHCP. When we transition from static configuration to DHCP in 5783 // particular, we must tell ConnectivityService that we're 5784 // disconnected, because DHCP might take a long time during which 5785 // connectivity APIs such as getActiveNetworkInfo should not return 5786 // CONNECTED. 5787 stopIpManager(); 5788 5789 mIpManager.setHttpProxy(currentConfig.getHttpProxy()); 5790 if (!TextUtils.isEmpty(mTcpBufferSizes)) { 5791 mIpManager.setTcpBufferSizes(mTcpBufferSizes); 5792 } 5793 5794 if (!isUsingStaticIp) { 5795 final IpManager.ProvisioningConfiguration prov = 5796 IpManager.buildProvisioningConfiguration() 5797 .withPreDhcpAction() 5798 .withApfCapabilities(mWifiNative.getApfCapabilities()) 5799 .build(); 5800 mIpManager.startProvisioning(prov); 5801 // Get Link layer stats so as we get fresh tx packet counters 5802 getWifiLinkLayerStats(); 5803 } else { 5804 StaticIpConfiguration config = currentConfig.getStaticIpConfiguration(); 5805 if (config.ipAddress == null) { 5806 logd("Static IP lacks address"); 5807 sendMessage(CMD_IPV4_PROVISIONING_FAILURE); 5808 } else { 5809 final IpManager.ProvisioningConfiguration prov = 5810 IpManager.buildProvisioningConfiguration() 5811 .withStaticConfiguration(config) 5812 .withApfCapabilities(mWifiNative.getApfCapabilities()) 5813 .build(); 5814 mIpManager.startProvisioning(prov); 5815 } 5816 } 5817 } 5818 5819 @Override 5820 public boolean processMessage(Message message) { 5821 logStateAndMessage(message, this); 5822 5823 switch(message.what) { 5824 case CMD_START_CONNECT: 5825 case CMD_START_ROAM: 5826 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5827 break; 5828 case WifiManager.SAVE_NETWORK: 5829 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 5830 deferMessage(message); 5831 break; 5832 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 5833 reportConnectionAttemptEnd( 5834 WifiMetrics.ConnectionEvent.FAILURE_NETWORK_DISCONNECTION, 5835 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5836 return NOT_HANDLED; 5837 case CMD_SET_HIGH_PERF_MODE: 5838 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 5839 deferMessage(message); 5840 break; 5841 /* Defer scan request since we should not switch to other channels at DHCP */ 5842 case CMD_START_SCAN: 5843 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 5844 deferMessage(message); 5845 break; 5846 default: 5847 return NOT_HANDLED; 5848 } 5849 return HANDLED; 5850 } 5851 } 5852 5853 private void sendConnectedState() { 5854 // If this network was explicitly selected by the user, evaluate whether to call 5855 // explicitlySelected() so the system can treat it appropriately. 5856 WifiConfiguration config = getCurrentWifiConfiguration(); 5857 if (mWifiConfigManager.getLastSelectedNetwork() == config.networkId) { 5858 boolean prompt = 5859 mWifiPermissionsUtil.checkConfigOverridePermission(config.lastConnectUid); 5860 if (mVerboseLoggingEnabled) { 5861 log("Network selected by UID " + config.lastConnectUid + " prompt=" + prompt); 5862 } 5863 if (prompt) { 5864 // Selected by the user via Settings or QuickSettings. If this network has Internet 5865 // access, switch to it. Otherwise, switch to it only if the user confirms that they 5866 // really want to switch, or has already confirmed and selected "Don't ask again". 5867 if (mVerboseLoggingEnabled) { 5868 log("explictlySelected acceptUnvalidated=" + config.noInternetAccessExpected); 5869 } 5870 mNetworkAgent.explicitlySelected(config.noInternetAccessExpected); 5871 } 5872 } 5873 5874 setNetworkDetailedState(DetailedState.CONNECTED); 5875 mWifiConfigManager.updateNetworkAfterConnect(mLastNetworkId); 5876 sendNetworkStateChangeBroadcast(mLastBssid); 5877 } 5878 5879 class RoamingState extends State { 5880 boolean mAssociated; 5881 @Override 5882 public void enter() { 5883 if (mVerboseLoggingEnabled) { 5884 log("RoamingState Enter" 5885 + " mScreenOn=" + mScreenOn ); 5886 } 5887 5888 // Make sure we disconnect if roaming fails 5889 roamWatchdogCount++; 5890 logd("Start Roam Watchdog " + roamWatchdogCount); 5891 sendMessageDelayed(obtainMessage(CMD_ROAM_WATCHDOG_TIMER, 5892 roamWatchdogCount, 0), ROAM_GUARD_TIMER_MSEC); 5893 mAssociated = false; 5894 } 5895 @Override 5896 public boolean processMessage(Message message) { 5897 logStateAndMessage(message, this); 5898 WifiConfiguration config; 5899 switch (message.what) { 5900 case CMD_IP_CONFIGURATION_LOST: 5901 config = getCurrentWifiConfiguration(); 5902 if (config != null) { 5903 mWifiDiagnostics.captureBugReportData( 5904 WifiDiagnostics.REPORT_REASON_AUTOROAM_FAILURE); 5905 } 5906 return NOT_HANDLED; 5907 case CMD_UNWANTED_NETWORK: 5908 if (mVerboseLoggingEnabled) { 5909 log("Roaming and CS doesnt want the network -> ignore"); 5910 } 5911 return HANDLED; 5912 case CMD_SET_OPERATIONAL_MODE: 5913 if (message.arg1 != CONNECT_MODE) { 5914 deferMessage(message); 5915 } 5916 break; 5917 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 5918 /** 5919 * If we get a SUPPLICANT_STATE_CHANGE_EVENT indicating a DISCONNECT 5920 * before NETWORK_DISCONNECTION_EVENT 5921 * And there is an associated BSSID corresponding to our target BSSID, then 5922 * we have missed the network disconnection, transition to mDisconnectedState 5923 * and handle the rest of the events there. 5924 */ 5925 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 5926 if (stateChangeResult.state == SupplicantState.DISCONNECTED 5927 || stateChangeResult.state == SupplicantState.INACTIVE 5928 || stateChangeResult.state == SupplicantState.INTERFACE_DISABLED) { 5929 if (mVerboseLoggingEnabled) { 5930 log("STATE_CHANGE_EVENT in roaming state " 5931 + stateChangeResult.toString() ); 5932 } 5933 if (stateChangeResult.BSSID != null 5934 && stateChangeResult.BSSID.equals(mTargetRoamBSSID)) { 5935 handleNetworkDisconnect(); 5936 transitionTo(mDisconnectedState); 5937 } 5938 } 5939 if (stateChangeResult.state == SupplicantState.ASSOCIATED) { 5940 // We completed the layer2 roaming part 5941 mAssociated = true; 5942 if (stateChangeResult.BSSID != null) { 5943 mTargetRoamBSSID = stateChangeResult.BSSID; 5944 } 5945 } 5946 break; 5947 case CMD_ROAM_WATCHDOG_TIMER: 5948 if (roamWatchdogCount == message.arg1) { 5949 if (mVerboseLoggingEnabled) log("roaming watchdog! -> disconnect"); 5950 mWifiMetrics.endConnectionEvent( 5951 WifiMetrics.ConnectionEvent.FAILURE_ROAM_TIMEOUT, 5952 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5953 mRoamFailCount++; 5954 handleNetworkDisconnect(); 5955 mWifiNative.disconnect(); 5956 transitionTo(mDisconnectedState); 5957 } 5958 break; 5959 case WifiMonitor.NETWORK_CONNECTION_EVENT: 5960 if (mAssociated) { 5961 if (mVerboseLoggingEnabled) { 5962 log("roaming and Network connection established"); 5963 } 5964 mLastNetworkId = lookupFrameworkNetworkId(message.arg1); 5965 mLastBssid = (String) message.obj; 5966 mWifiInfo.setBSSID(mLastBssid); 5967 mWifiInfo.setNetworkId(mLastNetworkId); 5968 int reasonCode = message.arg2; 5969 mWifiConnectivityManager.trackBssid(mLastBssid, true, reasonCode); 5970 sendNetworkStateChangeBroadcast(mLastBssid); 5971 5972 // Successful framework roam! (probably) 5973 reportConnectionAttemptEnd( 5974 WifiMetrics.ConnectionEvent.FAILURE_NONE, 5975 WifiMetricsProto.ConnectionEvent.HLF_NONE); 5976 5977 // We must clear the config BSSID, as the wifi chipset may decide to roam 5978 // from this point on and having the BSSID specified by QNS would cause 5979 // the roam to fail and the device to disconnect. 5980 // When transition from RoamingState to DisconnectingState or 5981 // DisconnectedState, the config BSSID is cleared by 5982 // handleNetworkDisconnect(). 5983 clearTargetBssid("RoamingCompleted"); 5984 5985 // We used to transition to ObtainingIpState in an 5986 // attempt to do DHCPv4 RENEWs on framework roams. 5987 // DHCP can take too long to time out, and we now rely 5988 // upon IpManager's use of IpReachabilityMonitor to 5989 // confirm our current network configuration. 5990 // 5991 // mIpManager.confirmConfiguration() is called within 5992 // the handling of SupplicantState.COMPLETED. 5993 transitionTo(mConnectedState); 5994 } else { 5995 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5996 } 5997 break; 5998 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 5999 // Throw away but only if it corresponds to the network we're roaming to 6000 String bssid = (String) message.obj; 6001 if (true) { 6002 String target = ""; 6003 if (mTargetRoamBSSID != null) target = mTargetRoamBSSID; 6004 log("NETWORK_DISCONNECTION_EVENT in roaming state" 6005 + " BSSID=" + bssid 6006 + " target=" + target); 6007 } 6008 if (bssid != null && bssid.equals(mTargetRoamBSSID)) { 6009 handleNetworkDisconnect(); 6010 transitionTo(mDisconnectedState); 6011 } 6012 break; 6013 case WifiMonitor.SSID_TEMP_DISABLED: 6014 // Auth error while roaming 6015 int netId = lookupFrameworkNetworkId(message.arg1); 6016 logd("SSID_TEMP_DISABLED nid=" + Integer.toString(mLastNetworkId) 6017 + " id=" + netId 6018 + " isRoaming=" + isRoaming() 6019 + " roam=" + mAutoRoaming); 6020 if (netId == mLastNetworkId) { 6021 config = getCurrentWifiConfiguration(); 6022 if (config != null) { 6023 mWifiDiagnostics.captureBugReportData( 6024 WifiDiagnostics.REPORT_REASON_AUTOROAM_FAILURE); 6025 } 6026 handleNetworkDisconnect(); 6027 transitionTo(mDisconnectingState); 6028 } 6029 return NOT_HANDLED; 6030 case CMD_START_SCAN: 6031 deferMessage(message); 6032 break; 6033 default: 6034 return NOT_HANDLED; 6035 } 6036 return HANDLED; 6037 } 6038 6039 @Override 6040 public void exit() { 6041 logd("WifiStateMachine: Leaving Roaming state"); 6042 } 6043 } 6044 6045 class ConnectedState extends State { 6046 @Override 6047 public void enter() { 6048 updateDefaultRouteMacAddress(1000); 6049 if (mVerboseLoggingEnabled) { 6050 log("Enter ConnectedState " 6051 + " mScreenOn=" + mScreenOn); 6052 } 6053 6054 mWifiConnectivityManager.handleConnectionStateChanged( 6055 WifiConnectivityManager.WIFI_STATE_CONNECTED); 6056 registerConnected(); 6057 lastConnectAttemptTimestamp = 0; 6058 targetWificonfiguration = null; 6059 // Paranoia 6060 mIsLinkDebouncing = false; 6061 6062 // Not roaming anymore 6063 mAutoRoaming = false; 6064 6065 if (testNetworkDisconnect) { 6066 testNetworkDisconnectCounter++; 6067 logd("ConnectedState Enter start disconnect test " + 6068 testNetworkDisconnectCounter); 6069 sendMessageDelayed(obtainMessage(CMD_TEST_NETWORK_DISCONNECT, 6070 testNetworkDisconnectCounter, 0), 15000); 6071 } 6072 6073 mLastDriverRoamAttempt = 0; 6074 mTargetNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 6075 mWifiInjector.getWifiLastResortWatchdog().connectedStateTransition(true); 6076 mWifiStateTracker.updateState(WifiStateTracker.CONNECTED); 6077 } 6078 @Override 6079 public boolean processMessage(Message message) { 6080 WifiConfiguration config = null; 6081 logStateAndMessage(message, this); 6082 6083 switch (message.what) { 6084 case CMD_UNWANTED_NETWORK: 6085 if (message.arg1 == NETWORK_STATUS_UNWANTED_DISCONNECT) { 6086 mWifiNative.disconnect(); 6087 transitionTo(mDisconnectingState); 6088 } else if (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN || 6089 message.arg1 == NETWORK_STATUS_UNWANTED_VALIDATION_FAILED) { 6090 Log.d(TAG, (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN 6091 ? "NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN" 6092 : "NETWORK_STATUS_UNWANTED_VALIDATION_FAILED")); 6093 config = getCurrentWifiConfiguration(); 6094 if (config != null) { 6095 // Disable autojoin 6096 if (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN) { 6097 mWifiConfigManager.setNetworkValidatedInternetAccess( 6098 config.networkId, false); 6099 mWifiConfigManager.updateNetworkSelectionStatus(config.networkId, 6100 WifiConfiguration.NetworkSelectionStatus 6101 .DISABLED_NO_INTERNET); 6102 } 6103 mWifiConfigManager.incrementNetworkNoInternetAccessReports( 6104 config.networkId); 6105 } 6106 } 6107 return HANDLED; 6108 case CMD_NETWORK_STATUS: 6109 if (message.arg1 == NetworkAgent.VALID_NETWORK) { 6110 config = getCurrentWifiConfiguration(); 6111 if (config != null) { 6112 // re-enable autojoin 6113 mWifiConfigManager.setNetworkValidatedInternetAccess( 6114 config.networkId, true); 6115 } 6116 } 6117 return HANDLED; 6118 case CMD_ACCEPT_UNVALIDATED: 6119 boolean accept = (message.arg1 != 0); 6120 mWifiConfigManager.setNetworkNoInternetAccessExpected(mLastNetworkId, accept); 6121 return HANDLED; 6122 case CMD_TEST_NETWORK_DISCONNECT: 6123 // Force a disconnect 6124 if (message.arg1 == testNetworkDisconnectCounter) { 6125 mWifiNative.disconnect(); 6126 } 6127 break; 6128 case CMD_ASSOCIATED_BSSID: 6129 // ASSOCIATING to a new BSSID while already connected, indicates 6130 // that driver is roaming 6131 mLastDriverRoamAttempt = mClock.getWallClockMillis(); 6132 return NOT_HANDLED; 6133 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6134 long lastRoam = 0; 6135 reportConnectionAttemptEnd( 6136 WifiMetrics.ConnectionEvent.FAILURE_NETWORK_DISCONNECTION, 6137 WifiMetricsProto.ConnectionEvent.HLF_NONE); 6138 if (mLastDriverRoamAttempt != 0) { 6139 // Calculate time since last driver roam attempt 6140 lastRoam = mClock.getWallClockMillis() - mLastDriverRoamAttempt; 6141 mLastDriverRoamAttempt = 0; 6142 } 6143 if (unexpectedDisconnectedReason(message.arg2)) { 6144 mWifiDiagnostics.captureBugReportData( 6145 WifiDiagnostics.REPORT_REASON_UNEXPECTED_DISCONNECT); 6146 } 6147 config = getCurrentWifiConfiguration(); 6148 if (mEnableLinkDebouncing 6149 && mScreenOn 6150 && !isLinkDebouncing() 6151 && config != null 6152 && config.getNetworkSelectionStatus().isNetworkEnabled() 6153 && config.networkId != mWifiConfigManager.getLastSelectedNetwork() 6154 && (message.arg2 != 3 /* reason cannot be 3, i.e. locally generated */ 6155 || (lastRoam > 0 && lastRoam < 2000) /* unless driver is roaming */) 6156 && ((ScanResult.is24GHz(mWifiInfo.getFrequency()) 6157 && mWifiInfo.getRssi() > 6158 mThresholdQualifiedRssi5) 6159 || (ScanResult.is5GHz(mWifiInfo.getFrequency()) 6160 && mWifiInfo.getRssi() > 6161 mThresholdQualifiedRssi5))) { 6162 // Start de-bouncing the L2 disconnection: 6163 // this L2 disconnection might be spurious. 6164 // Hence we allow 4 seconds for the state machine to try 6165 // to reconnect, go thru the 6166 // roaming cycle and enter Obtaining IP address 6167 // before signalling the disconnect to ConnectivityService and L3 6168 startScanForConfiguration(getCurrentWifiConfiguration()); 6169 mIsLinkDebouncing = true; 6170 6171 sendMessageDelayed(obtainMessage(CMD_DELAYED_NETWORK_DISCONNECT, 6172 0, mLastNetworkId), LINK_FLAPPING_DEBOUNCE_MSEC); 6173 if (mVerboseLoggingEnabled) { 6174 log("NETWORK_DISCONNECTION_EVENT in connected state" 6175 + " BSSID=" + mWifiInfo.getBSSID() 6176 + " RSSI=" + mWifiInfo.getRssi() 6177 + " freq=" + mWifiInfo.getFrequency() 6178 + " reason=" + message.arg2 6179 + " -> debounce"); 6180 } 6181 return HANDLED; 6182 } else { 6183 if (mVerboseLoggingEnabled) { 6184 log("NETWORK_DISCONNECTION_EVENT in connected state" 6185 + " BSSID=" + mWifiInfo.getBSSID() 6186 + " RSSI=" + mWifiInfo.getRssi() 6187 + " freq=" + mWifiInfo.getFrequency() 6188 + " was debouncing=" + isLinkDebouncing() 6189 + " reason=" + message.arg2 6190 + " Network Selection Status=" + (config == null ? "Unavailable" 6191 : config.getNetworkSelectionStatus().getNetworkStatusString())); 6192 } 6193 } 6194 break; 6195 case CMD_START_ROAM: 6196 // Clear the driver roam indication since we are attempting a framework roam 6197 mLastDriverRoamAttempt = 0; 6198 6199 /* Connect command coming from auto-join */ 6200 int netId = message.arg1; 6201 ScanResult candidate = (ScanResult)message.obj; 6202 String bssid = SUPPLICANT_BSSID_ANY; 6203 if (candidate != null) { 6204 bssid = candidate.BSSID; 6205 } 6206 config = mWifiConfigManager.getConfiguredNetworkWithPassword(netId); 6207 if (config == null) { 6208 loge("CMD_START_ROAM and no config, bail out..."); 6209 break; 6210 } 6211 6212 setTargetBssid(config, bssid); 6213 mTargetNetworkId = netId; 6214 6215 logd("CMD_START_ROAM sup state " 6216 + mSupplicantStateTracker.getSupplicantStateName() 6217 + " my state " + getCurrentState().getName() 6218 + " nid=" + Integer.toString(netId) 6219 + " config " + config.configKey() 6220 + " targetRoamBSSID " + mTargetRoamBSSID); 6221 6222 reportConnectionAttemptStart(config, mTargetRoamBSSID, 6223 WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE); 6224 if (mWifiNative.roamToNetwork(config)) { 6225 lastConnectAttemptTimestamp = mClock.getWallClockMillis(); 6226 targetWificonfiguration = config; 6227 mAutoRoaming = true; 6228 transitionTo(mRoamingState); 6229 } else { 6230 loge("CMD_START_ROAM Failed to start roaming to network " + config); 6231 reportConnectionAttemptEnd( 6232 WifiMetrics.ConnectionEvent.FAILURE_CONNECT_NETWORK_FAILED, 6233 WifiMetricsProto.ConnectionEvent.HLF_NONE); 6234 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 6235 WifiManager.ERROR); 6236 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 6237 break; 6238 } 6239 break; 6240 case CMD_START_IP_PACKET_OFFLOAD: { 6241 int slot = message.arg1; 6242 int intervalSeconds = message.arg2; 6243 KeepalivePacketData pkt = (KeepalivePacketData) message.obj; 6244 byte[] dstMac; 6245 try { 6246 InetAddress gateway = RouteInfo.selectBestRoute( 6247 mLinkProperties.getRoutes(), pkt.dstAddress).getGateway(); 6248 String dstMacStr = macAddressFromRoute(gateway.getHostAddress()); 6249 dstMac = NativeUtil.macAddressToByteArray(dstMacStr); 6250 } catch (NullPointerException | IllegalArgumentException e) { 6251 loge("Can't find MAC address for next hop to " + pkt.dstAddress); 6252 mNetworkAgent.onPacketKeepaliveEvent(slot, 6253 ConnectivityManager.PacketKeepalive.ERROR_INVALID_IP_ADDRESS); 6254 break; 6255 } 6256 pkt.dstMac = dstMac; 6257 int result = startWifiIPPacketOffload(slot, pkt, intervalSeconds); 6258 mNetworkAgent.onPacketKeepaliveEvent(slot, result); 6259 break; 6260 } 6261 default: 6262 return NOT_HANDLED; 6263 } 6264 return HANDLED; 6265 } 6266 6267 @Override 6268 public void exit() { 6269 logd("WifiStateMachine: Leaving Connected state"); 6270 mWifiConnectivityManager.handleConnectionStateChanged( 6271 WifiConnectivityManager.WIFI_STATE_TRANSITIONING); 6272 6273 mLastDriverRoamAttempt = 0; 6274 mWifiInjector.getWifiLastResortWatchdog().connectedStateTransition(false); 6275 } 6276 } 6277 6278 class DisconnectingState extends State { 6279 6280 @Override 6281 public void enter() { 6282 6283 if (mVerboseLoggingEnabled) { 6284 logd(" Enter DisconnectingState State screenOn=" + mScreenOn); 6285 } 6286 6287 // Make sure we disconnect: we enter this state prior to connecting to a new 6288 // network, waiting for either a DISCONNECT event or a SUPPLICANT_STATE_CHANGE 6289 // event which in this case will be indicating that supplicant started to associate. 6290 // In some cases supplicant doesn't ignore the connect requests (it might not 6291 // find the target SSID in its cache), 6292 // Therefore we end up stuck that state, hence the need for the watchdog. 6293 disconnectingWatchdogCount++; 6294 logd("Start Disconnecting Watchdog " + disconnectingWatchdogCount); 6295 sendMessageDelayed(obtainMessage(CMD_DISCONNECTING_WATCHDOG_TIMER, 6296 disconnectingWatchdogCount, 0), DISCONNECTING_GUARD_TIMER_MSEC); 6297 } 6298 6299 @Override 6300 public boolean processMessage(Message message) { 6301 logStateAndMessage(message, this); 6302 switch (message.what) { 6303 case CMD_SET_OPERATIONAL_MODE: 6304 if (message.arg1 != CONNECT_MODE) { 6305 deferMessage(message); 6306 } 6307 break; 6308 case CMD_START_SCAN: 6309 deferMessage(message); 6310 return HANDLED; 6311 case CMD_DISCONNECT: 6312 if (mVerboseLoggingEnabled) log("Ignore CMD_DISCONNECT when already disconnecting."); 6313 break; 6314 case CMD_DISCONNECTING_WATCHDOG_TIMER: 6315 if (disconnectingWatchdogCount == message.arg1) { 6316 if (mVerboseLoggingEnabled) log("disconnecting watchdog! -> disconnect"); 6317 handleNetworkDisconnect(); 6318 transitionTo(mDisconnectedState); 6319 } 6320 break; 6321 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6322 /** 6323 * If we get a SUPPLICANT_STATE_CHANGE_EVENT before NETWORK_DISCONNECTION_EVENT 6324 * we have missed the network disconnection, transition to mDisconnectedState 6325 * and handle the rest of the events there 6326 */ 6327 deferMessage(message); 6328 handleNetworkDisconnect(); 6329 transitionTo(mDisconnectedState); 6330 break; 6331 default: 6332 return NOT_HANDLED; 6333 } 6334 return HANDLED; 6335 } 6336 } 6337 6338 class DisconnectedState extends State { 6339 @Override 6340 public void enter() { 6341 // We dont scan frequently if this is a temporary disconnect 6342 // due to p2p 6343 if (mTemporarilyDisconnectWifi) { 6344 p2pSendMessage(WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE); 6345 return; 6346 } 6347 6348 if (mVerboseLoggingEnabled) { 6349 logd(" Enter DisconnectedState screenOn=" + mScreenOn); 6350 } 6351 6352 /** clear the roaming state, if we were roaming, we failed */ 6353 mAutoRoaming = false; 6354 6355 mWifiConnectivityManager.handleConnectionStateChanged( 6356 WifiConnectivityManager.WIFI_STATE_DISCONNECTED); 6357 6358 /** 6359 * If we have no networks saved, the supplicant stops doing the periodic scan. 6360 * The scans are useful to notify the user of the presence of an open network. 6361 * Note that these are not wake up scans. 6362 */ 6363 if (mNoNetworksPeriodicScan != 0 && !mP2pConnected.get() 6364 && mWifiConfigManager.getSavedNetworks().size() == 0) { 6365 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 6366 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 6367 } 6368 6369 mDisconnectedTimeStamp = mClock.getWallClockMillis(); 6370 mWifiStateTracker.updateState(WifiStateTracker.DISCONNECTED); 6371 } 6372 @Override 6373 public boolean processMessage(Message message) { 6374 boolean ret = HANDLED; 6375 6376 logStateAndMessage(message, this); 6377 6378 switch (message.what) { 6379 case CMD_NO_NETWORKS_PERIODIC_SCAN: 6380 if (mP2pConnected.get()) break; 6381 if (mNoNetworksPeriodicScan != 0 && message.arg1 == mPeriodicScanToken && 6382 mWifiConfigManager.getSavedNetworks().size() == 0) { 6383 startScan(UNKNOWN_SCAN_SOURCE, -1, null, WIFI_WORK_SOURCE); 6384 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 6385 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 6386 } 6387 break; 6388 case WifiManager.FORGET_NETWORK: 6389 case CMD_REMOVE_NETWORK: 6390 case CMD_REMOVE_APP_CONFIGURATIONS: 6391 case CMD_REMOVE_USER_CONFIGURATIONS: 6392 // Set up a delayed message here. After the forget/remove is handled 6393 // the handled delayed message will determine if there is a need to 6394 // scan and continue 6395 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 6396 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 6397 ret = NOT_HANDLED; 6398 break; 6399 case CMD_SET_OPERATIONAL_MODE: 6400 if (message.arg1 != CONNECT_MODE) { 6401 mOperationalMode = message.arg1; 6402 if (mOperationalMode == DISABLED_MODE) { 6403 transitionTo(mSupplicantStoppingState); 6404 } else if (mOperationalMode == SCAN_ONLY_MODE 6405 || mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 6406 p2pSendMessage(CMD_DISABLE_P2P_REQ); 6407 setWifiState(WIFI_STATE_DISABLED); 6408 transitionTo(mScanModeState); 6409 } 6410 } 6411 break; 6412 case CMD_DISCONNECT: 6413 mWifiNative.disconnect(); 6414 break; 6415 /* Ignore network disconnect */ 6416 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6417 // Interpret this as an L2 connection failure 6418 break; 6419 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6420 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 6421 if (mVerboseLoggingEnabled) { 6422 logd("SUPPLICANT_STATE_CHANGE_EVENT state=" + stateChangeResult.state + 6423 " -> state= " + WifiInfo.getDetailedStateOf(stateChangeResult.state) 6424 + " debouncing=" + isLinkDebouncing()); 6425 } 6426 setNetworkDetailedState(WifiInfo.getDetailedStateOf(stateChangeResult.state)); 6427 /* ConnectModeState does the rest of the handling */ 6428 ret = NOT_HANDLED; 6429 break; 6430 case CMD_START_SCAN: 6431 if (!checkOrDeferScanAllowed(message)) { 6432 // The scan request was rescheduled 6433 messageHandlingStatus = MESSAGE_HANDLING_STATUS_REFUSED; 6434 return HANDLED; 6435 } 6436 6437 ret = NOT_HANDLED; 6438 break; 6439 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 6440 NetworkInfo info = (NetworkInfo) message.obj; 6441 mP2pConnected.set(info.isConnected()); 6442 if (!mP2pConnected.get() && mWifiConfigManager.getSavedNetworks().size() == 0) { 6443 if (mVerboseLoggingEnabled) log("Turn on scanning after p2p disconnected"); 6444 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 6445 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 6446 } 6447 break; 6448 case CMD_RECONNECT: 6449 case CMD_REASSOCIATE: 6450 if (mTemporarilyDisconnectWifi) { 6451 // Drop a third party reconnect/reassociate if STA is 6452 // temporarily disconnected for p2p 6453 break; 6454 } else { 6455 // ConnectModeState handles it 6456 ret = NOT_HANDLED; 6457 } 6458 break; 6459 case CMD_SCREEN_STATE_CHANGED: 6460 handleScreenStateChanged(message.arg1 != 0); 6461 break; 6462 default: 6463 ret = NOT_HANDLED; 6464 } 6465 return ret; 6466 } 6467 6468 @Override 6469 public void exit() { 6470 mWifiConnectivityManager.handleConnectionStateChanged( 6471 WifiConnectivityManager.WIFI_STATE_TRANSITIONING); 6472 } 6473 } 6474 6475 /** 6476 * WPS connection flow: 6477 * 1. WifiStateMachine receive WPS_START message from WifiManager API. 6478 * 2. WifiStateMachine initiates the appropriate WPS operation using WifiNative methods: 6479 * {@link WifiNative#startWpsPbc(String)}, {@link WifiNative#startWpsPinDisplay(String)}, etc. 6480 * 3. WifiStateMachine then transitions to this WpsRunningState. 6481 * 4a. Once WifiStateMachine receive the connected event: 6482 * {@link WifiMonitor#NETWORK_CONNECTION_EVENT}, 6483 * 4a.1 Load the network params out of wpa_supplicant. 6484 * 4a.2 Add the network with params to WifiConfigManager. 6485 * 4a.3 Enable the network with |disableOthers| set to true. 6486 * 4a.4 Send a response to the original source of WifiManager API using {@link #mSourceMessage}. 6487 * 4b. Any failures are notified to the original source of WifiManager API 6488 * using {@link #mSourceMessage}. 6489 * 5. We then transition to disconnected state and let network selection reconnect to the newly 6490 * added network. 6491 */ 6492 class WpsRunningState extends State { 6493 // Tracks the source to provide a reply 6494 private Message mSourceMessage; 6495 @Override 6496 public void enter() { 6497 mSourceMessage = Message.obtain(getCurrentMessage()); 6498 } 6499 @Override 6500 public boolean processMessage(Message message) { 6501 logStateAndMessage(message, this); 6502 6503 switch (message.what) { 6504 case WifiMonitor.WPS_SUCCESS_EVENT: 6505 // Ignore intermediate success, wait for full connection 6506 break; 6507 case WifiMonitor.NETWORK_CONNECTION_EVENT: 6508 if (loadNetworksFromSupplicantAfterWps()) { 6509 replyToMessage(mSourceMessage, WifiManager.WPS_COMPLETED); 6510 } else { 6511 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 6512 WifiManager.ERROR); 6513 } 6514 mSourceMessage.recycle(); 6515 mSourceMessage = null; 6516 deferMessage(message); 6517 transitionTo(mDisconnectedState); 6518 break; 6519 case WifiMonitor.WPS_OVERLAP_EVENT: 6520 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 6521 WifiManager.WPS_OVERLAP_ERROR); 6522 mSourceMessage.recycle(); 6523 mSourceMessage = null; 6524 transitionTo(mDisconnectedState); 6525 break; 6526 case WifiMonitor.WPS_FAIL_EVENT: 6527 // Arg1 has the reason for the failure 6528 if ((message.arg1 != WifiManager.ERROR) || (message.arg2 != 0)) { 6529 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, message.arg1); 6530 mSourceMessage.recycle(); 6531 mSourceMessage = null; 6532 transitionTo(mDisconnectedState); 6533 } else { 6534 if (mVerboseLoggingEnabled) { 6535 log("Ignore unspecified fail event during WPS connection"); 6536 } 6537 } 6538 break; 6539 case WifiMonitor.WPS_TIMEOUT_EVENT: 6540 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 6541 WifiManager.WPS_TIMED_OUT); 6542 mSourceMessage.recycle(); 6543 mSourceMessage = null; 6544 transitionTo(mDisconnectedState); 6545 break; 6546 case WifiManager.START_WPS: 6547 replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.IN_PROGRESS); 6548 break; 6549 case WifiManager.CANCEL_WPS: 6550 if (mWifiNative.cancelWps()) { 6551 replyToMessage(message, WifiManager.CANCEL_WPS_SUCCEDED); 6552 } else { 6553 replyToMessage(message, WifiManager.CANCEL_WPS_FAILED, WifiManager.ERROR); 6554 } 6555 transitionTo(mDisconnectedState); 6556 break; 6557 /** 6558 * Defer all commands that can cause connections to a different network 6559 * or put the state machine out of connect mode 6560 */ 6561 case CMD_SET_OPERATIONAL_MODE: 6562 case WifiManager.CONNECT_NETWORK: 6563 case CMD_ENABLE_NETWORK: 6564 case CMD_RECONNECT: 6565 case CMD_REASSOCIATE: 6566 deferMessage(message); 6567 break; 6568 case CMD_START_CONNECT: 6569 case CMD_START_ROAM: 6570 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 6571 return HANDLED; 6572 case CMD_START_SCAN: 6573 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 6574 return HANDLED; 6575 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6576 if (mVerboseLoggingEnabled) log("Network connection lost"); 6577 handleNetworkDisconnect(); 6578 break; 6579 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 6580 if (mVerboseLoggingEnabled) { 6581 log("Ignore Assoc reject event during WPS Connection"); 6582 } 6583 break; 6584 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 6585 // Disregard auth failure events during WPS connection. The 6586 // EAP sequence is retried several times, and there might be 6587 // failures (especially for wps pin). We will get a WPS_XXX 6588 // event at the end of the sequence anyway. 6589 if (mVerboseLoggingEnabled) log("Ignore auth failure during WPS connection"); 6590 break; 6591 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6592 // Throw away supplicant state changes when WPS is running. 6593 // We will start getting supplicant state changes once we get 6594 // a WPS success or failure 6595 break; 6596 default: 6597 return NOT_HANDLED; 6598 } 6599 return HANDLED; 6600 } 6601 6602 /** 6603 * Load network config from wpa_supplicant after WPS is complete. 6604 */ 6605 private boolean loadNetworksFromSupplicantAfterWps() { 6606 Map<String, WifiConfiguration> configs = new HashMap<>(); 6607 SparseArray<Map<String, String>> extras = new SparseArray<>(); 6608 if (!mWifiNative.migrateNetworksFromSupplicant(configs, extras)) { 6609 loge("Failed to load networks from wpa_supplicant after Wps"); 6610 return false; 6611 } 6612 for (Map.Entry<String, WifiConfiguration> entry : configs.entrySet()) { 6613 NetworkUpdateResult result = mWifiConfigManager.addOrUpdateNetwork( 6614 entry.getValue(), mSourceMessage.sendingUid); 6615 if (!result.isSuccess()) { 6616 loge("Failed to add network after WPS: " + entry.getValue()); 6617 return false; 6618 } 6619 if (!mWifiConfigManager.enableNetwork( 6620 result.getNetworkId(), true, mSourceMessage.sendingUid)) { 6621 loge("Failed to enable network after WPS: " + entry.getValue()); 6622 return false; 6623 } 6624 } 6625 return true; 6626 } 6627 } 6628 6629 class SoftApState extends State { 6630 private SoftApManager mSoftApManager; 6631 6632 private class SoftApListener implements SoftApManager.Listener { 6633 @Override 6634 public void onStateChanged(int state, int reason) { 6635 if (state == WIFI_AP_STATE_DISABLED) { 6636 sendMessage(CMD_AP_STOPPED); 6637 } else if (state == WIFI_AP_STATE_FAILED) { 6638 sendMessage(CMD_START_AP_FAILURE); 6639 } 6640 6641 setWifiApState(state, reason); 6642 } 6643 } 6644 6645 @Override 6646 public void enter() { 6647 final Message message = getCurrentMessage(); 6648 if (message.what != CMD_START_AP) { 6649 throw new RuntimeException("Illegal transition to SoftApState: " + message); 6650 } 6651 6652 IApInterface apInterface = mWifiNative.setupForSoftApMode(); 6653 if (apInterface == null) { 6654 setWifiApState(WIFI_AP_STATE_FAILED, 6655 WifiManager.SAP_START_FAILURE_GENERAL); 6656 /** 6657 * Transition to InitialState to reset the 6658 * driver/HAL back to the initial state. 6659 */ 6660 transitionTo(mInitialState); 6661 return; 6662 } 6663 6664 WifiConfiguration config = (WifiConfiguration) message.obj; 6665 6666 checkAndSetConnectivityInstance(); 6667 mSoftApManager = mWifiInjector.makeSoftApManager(mNwService, 6668 new SoftApListener(), 6669 apInterface, 6670 config); 6671 mSoftApManager.start(); 6672 mWifiStateTracker.updateState(WifiStateTracker.SOFT_AP); 6673 } 6674 6675 @Override 6676 public void exit() { 6677 mSoftApManager = null; 6678 } 6679 6680 @Override 6681 public boolean processMessage(Message message) { 6682 logStateAndMessage(message, this); 6683 6684 switch(message.what) { 6685 case CMD_START_AP: 6686 /* Ignore start command when it is starting/started. */ 6687 break; 6688 case CMD_STOP_AP: 6689 mSoftApManager.stop(); 6690 break; 6691 case CMD_START_AP_FAILURE: 6692 transitionTo(mInitialState); 6693 break; 6694 case CMD_AP_STOPPED: 6695 transitionTo(mInitialState); 6696 break; 6697 default: 6698 return NOT_HANDLED; 6699 } 6700 return HANDLED; 6701 } 6702 } 6703 6704 /** 6705 * State machine initiated requests can have replyTo set to null indicating 6706 * there are no recepients, we ignore those reply actions. 6707 */ 6708 private void replyToMessage(Message msg, int what) { 6709 if (msg.replyTo == null) return; 6710 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 6711 mReplyChannel.replyToMessage(msg, dstMsg); 6712 } 6713 6714 private void replyToMessage(Message msg, int what, int arg1) { 6715 if (msg.replyTo == null) return; 6716 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 6717 dstMsg.arg1 = arg1; 6718 mReplyChannel.replyToMessage(msg, dstMsg); 6719 } 6720 6721 private void replyToMessage(Message msg, int what, Object obj) { 6722 if (msg.replyTo == null) return; 6723 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 6724 dstMsg.obj = obj; 6725 mReplyChannel.replyToMessage(msg, dstMsg); 6726 } 6727 6728 /** 6729 * arg2 on the source message has a unique id that needs to be retained in replies 6730 * to match the request 6731 * <p>see WifiManager for details 6732 */ 6733 private Message obtainMessageWithWhatAndArg2(Message srcMsg, int what) { 6734 Message msg = Message.obtain(); 6735 msg.what = what; 6736 msg.arg2 = srcMsg.arg2; 6737 return msg; 6738 } 6739 6740 /** 6741 * Notify interested parties if a wifi config has been changed. 6742 * 6743 * @param wifiCredentialEventType WIFI_CREDENTIAL_SAVED or WIFI_CREDENTIAL_FORGOT 6744 * @param config Must have a WifiConfiguration object to succeed 6745 * TODO: b/35258354 investigate if this can be removed. Is the broadcast sent by 6746 * WifiConfigManager sufficient? 6747 */ 6748 private void broadcastWifiCredentialChanged(int wifiCredentialEventType, 6749 WifiConfiguration config) { 6750 if (config != null && config.preSharedKey != null) { 6751 Intent intent = new Intent(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION); 6752 intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID, config.SSID); 6753 intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, 6754 wifiCredentialEventType); 6755 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT, 6756 android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE); 6757 } 6758 } 6759 6760 void handleGsmAuthRequest(SimAuthRequestData requestData) { 6761 if (targetWificonfiguration == null 6762 || targetWificonfiguration.networkId 6763 == lookupFrameworkNetworkId(requestData.networkId)) { 6764 logd("id matches targetWifiConfiguration"); 6765 } else { 6766 logd("id does not match targetWifiConfiguration"); 6767 return; 6768 } 6769 6770 String response = 6771 TelephonyUtil.getGsmSimAuthResponse(requestData.data, getTelephonyManager()); 6772 if (response == null) { 6773 mWifiNative.simAuthFailedResponse(requestData.networkId); 6774 } else { 6775 logv("Supplicant Response -" + response); 6776 mWifiNative.simAuthResponse(requestData.networkId, 6777 WifiNative.SIM_AUTH_RESP_TYPE_GSM_AUTH, response); 6778 } 6779 } 6780 6781 void handle3GAuthRequest(SimAuthRequestData requestData) { 6782 if (targetWificonfiguration == null 6783 || targetWificonfiguration.networkId 6784 == lookupFrameworkNetworkId(requestData.networkId)) { 6785 logd("id matches targetWifiConfiguration"); 6786 } else { 6787 logd("id does not match targetWifiConfiguration"); 6788 return; 6789 } 6790 6791 SimAuthResponseData response = 6792 TelephonyUtil.get3GAuthResponse(requestData, getTelephonyManager()); 6793 if (response != null) { 6794 mWifiNative.simAuthResponse(requestData.networkId, response.type, response.response); 6795 } else { 6796 mWifiNative.umtsAuthFailedResponse(requestData.networkId); 6797 } 6798 } 6799 6800 /** 6801 * Automatically connect to the network specified 6802 * 6803 * @param networkId ID of the network to connect to 6804 * @param bssid BSSID of the network 6805 */ 6806 public void startConnectToNetwork(int networkId, String bssid) { 6807 synchronized (mWifiReqCountLock) { 6808 if (hasConnectionRequests()) { 6809 sendMessage(CMD_START_CONNECT, networkId, 0, bssid); 6810 } 6811 } 6812 } 6813 6814 /** 6815 * Automatically roam to the network specified 6816 * 6817 * @param networkId ID of the network to roam to 6818 * @param scanResult scan result which identifies the network to roam to 6819 */ 6820 public void startRoamToNetwork(int networkId, ScanResult scanResult) { 6821 sendMessage(CMD_START_ROAM, networkId, 0, scanResult); 6822 } 6823 6824 /** 6825 * Dynamically turn on/off WifiConnectivityManager 6826 * 6827 * @param enabled true-enable; false-disable 6828 */ 6829 public void enableWifiConnectivityManager(boolean enabled) { 6830 sendMessage(CMD_ENABLE_WIFI_CONNECTIVITY_MANAGER, enabled ? 1 : 0); 6831 } 6832 6833 /** 6834 * @param reason reason code from supplicant on network disconnected event 6835 * @return true if this is a suspicious disconnect 6836 */ 6837 static boolean unexpectedDisconnectedReason(int reason) { 6838 return reason == 2 // PREV_AUTH_NOT_VALID 6839 || reason == 6 // CLASS2_FRAME_FROM_NONAUTH_STA 6840 || reason == 7 // FRAME_FROM_NONASSOC_STA 6841 || reason == 8 // STA_HAS_LEFT 6842 || reason == 9 // STA_REQ_ASSOC_WITHOUT_AUTH 6843 || reason == 14 // MICHAEL_MIC_FAILURE 6844 || reason == 15 // 4WAY_HANDSHAKE_TIMEOUT 6845 || reason == 16 // GROUP_KEY_UPDATE_TIMEOUT 6846 || reason == 18 // GROUP_CIPHER_NOT_VALID 6847 || reason == 19 // PAIRWISE_CIPHER_NOT_VALID 6848 || reason == 23 // IEEE_802_1X_AUTH_FAILED 6849 || reason == 34; // DISASSOC_LOW_ACK 6850 } 6851 6852 /** 6853 * Update WifiMetrics before dumping 6854 */ 6855 public void updateWifiMetrics() { 6856 mWifiMetrics.updateSavedNetworks(mWifiConfigManager.getSavedNetworks()); 6857 } 6858 6859 /** 6860 * Private method to handle calling WifiConfigManager to forget/remove network configs and reply 6861 * to the message from the sender of the outcome. 6862 * 6863 * The current implementation requires that forget and remove be handled in different ways 6864 * (responses are handled differently). In the interests of organization, the handling is all 6865 * now in this helper method. TODO: b/35257965 is filed to track the possibility of merging 6866 * the two call paths. 6867 */ 6868 private boolean deleteNetworkConfigAndSendReply(Message message, boolean calledFromForget) { 6869 boolean success = mWifiConfigManager.removeNetwork(message.arg1, message.sendingUid); 6870 if (!success) { 6871 loge("Failed to remove network"); 6872 } 6873 6874 if (calledFromForget) { 6875 if (success) { 6876 replyToMessage(message, WifiManager.FORGET_NETWORK_SUCCEEDED); 6877 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_FORGOT, 6878 (WifiConfiguration) message.obj); 6879 return true; 6880 } 6881 replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, WifiManager.ERROR); 6882 return false; 6883 } else { 6884 // Remaining calls are from the removeNetwork path 6885 if (success) { 6886 replyToMessage(message, message.what, SUCCESS); 6887 return true; 6888 } 6889 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 6890 replyToMessage(message, message.what, FAILURE); 6891 return false; 6892 } 6893 } 6894 6895 private static String getLinkPropertiesSummary(LinkProperties lp) { 6896 List<String> attributes = new ArrayList<>(6); 6897 if (lp.hasIPv4Address()) { 6898 attributes.add("v4"); 6899 } 6900 if (lp.hasIPv4DefaultRoute()) { 6901 attributes.add("v4r"); 6902 } 6903 if (lp.hasIPv4DnsServer()) { 6904 attributes.add("v4dns"); 6905 } 6906 if (lp.hasGlobalIPv6Address()) { 6907 attributes.add("v6"); 6908 } 6909 if (lp.hasIPv6DefaultRoute()) { 6910 attributes.add("v6r"); 6911 } 6912 if (lp.hasIPv6DnsServer()) { 6913 attributes.add("v6dns"); 6914 } 6915 6916 return TextUtils.join(" ", attributes); 6917 } 6918 6919 /** 6920 * Gets the SSID from the WifiConfiguration pointed at by 'mTargetNetworkId' 6921 * This should match the network config framework is attempting to connect to. 6922 */ 6923 private String getTargetSsid() { 6924 WifiConfiguration currentConfig = mWifiConfigManager.getConfiguredNetwork(mTargetNetworkId); 6925 if (currentConfig != null) { 6926 return currentConfig.SSID; 6927 } 6928 return null; 6929 } 6930 6931 private void p2pSendMessage(int what) { 6932 if (mWifiP2pChannel != null) { 6933 mWifiP2pChannel.sendMessage(what); 6934 } 6935 } 6936 6937 private void p2pSendMessage(int what, int arg1) { 6938 if (mWifiP2pChannel != null) { 6939 mWifiP2pChannel.sendMessage(what, arg1); 6940 } 6941 } 6942 6943 /** 6944 * Check if there is any connection request for WiFi network. 6945 * Note, caller of this helper function must acquire mWifiReqCountLock. 6946 */ 6947 private boolean hasConnectionRequests() { 6948 return mConnectionReqCount > 0 || mUntrustedReqCount > 0; 6949 } 6950 6951 /** 6952 * Returns whether CMD_IP_REACHABILITY_LOST events should trigger disconnects. 6953 */ 6954 public boolean getIpReachabilityDisconnectEnabled() { 6955 return mIpReachabilityDisconnectEnabled; 6956 } 6957 6958 /** 6959 * Sets whether CMD_IP_REACHABILITY_LOST events should trigger disconnects. 6960 */ 6961 public void setIpReachabilityDisconnectEnabled(boolean enabled) { 6962 mIpReachabilityDisconnectEnabled = enabled; 6963 } 6964 6965 /** 6966 * Sends a message to initialize the WifiStateMachine. 6967 * 6968 * @return true if succeeded, false otherwise. 6969 */ 6970 public boolean syncInitialize(AsyncChannel channel) { 6971 Message resultMsg = channel.sendMessageSynchronously(CMD_INITIALIZE); 6972 boolean result = (resultMsg.arg1 != FAILURE); 6973 resultMsg.recycle(); 6974 return result; 6975 } 6976} 6977