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