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