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