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