WifiStateMachine.java revision bbb3149f3bc301e81c202438b77c45574a90a851
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.AlarmManager; 33import android.app.PendingIntent; 34import android.app.backup.IBackupManager; 35import android.bluetooth.BluetoothAdapter; 36import android.content.BroadcastReceiver; 37import android.content.Context; 38import android.content.Intent; 39import android.content.IntentFilter; 40import android.content.pm.ApplicationInfo; 41import android.content.pm.IPackageManager; 42import android.content.pm.PackageManager; 43import android.content.pm.UserInfo; 44import android.database.ContentObserver; 45import android.net.ConnectivityManager; 46import android.net.DhcpResults; 47import android.net.DhcpStateMachine; 48import android.net.InterfaceConfiguration; 49import android.net.LinkAddress; 50import android.net.LinkProperties; 51import android.net.Network; 52import android.net.NetworkAgent; 53import android.net.NetworkCapabilities; 54import android.net.NetworkFactory; 55import android.net.NetworkInfo; 56import android.net.NetworkInfo.DetailedState; 57import android.net.NetworkRequest; 58import android.net.NetworkUtils; 59import android.net.RouteInfo; 60import android.net.StaticIpConfiguration; 61import android.net.ip.IpManager; 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.p2p.IWifiP2pManager; 80import android.os.BatteryStats; 81import android.os.Binder; 82import android.os.Bundle; 83import android.os.IBinder; 84import android.os.INetworkManagementService; 85import android.os.Looper; 86import android.os.Message; 87import android.os.Messenger; 88import android.os.PowerManager; 89import android.os.Process; 90import android.os.RemoteException; 91import android.os.SystemClock; 92import android.os.SystemProperties; 93import android.os.UserHandle; 94import android.os.UserManager; 95import android.os.WorkSource; 96import android.provider.Settings; 97import android.telephony.TelephonyManager; 98import android.text.TextUtils; 99import android.util.Log; 100import android.util.LruCache; 101 102import com.android.internal.R; 103import com.android.internal.app.IBatteryStats; 104import com.android.internal.util.AsyncChannel; 105import com.android.internal.util.Protocol; 106import com.android.internal.util.State; 107import com.android.internal.util.StateMachine; 108import com.android.server.connectivity.KeepalivePacketData; 109import com.android.server.wifi.hotspot2.IconEvent; 110import com.android.server.wifi.hotspot2.NetworkDetail; 111import com.android.server.wifi.hotspot2.Utils; 112import com.android.server.wifi.p2p.WifiP2pServiceImpl; 113 114import java.io.BufferedReader; 115import java.io.FileDescriptor; 116import java.io.FileNotFoundException; 117import java.io.FileReader; 118import java.io.IOException; 119import java.io.PrintWriter; 120import java.net.Inet4Address; 121import java.net.InetAddress; 122import java.util.ArrayList; 123import java.util.Arrays; 124import java.util.Calendar; 125import java.util.HashSet; 126import java.util.LinkedList; 127import java.util.List; 128import java.util.Locale; 129import java.util.Queue; 130import java.util.Random; 131import java.util.Set; 132import java.util.concurrent.atomic.AtomicBoolean; 133import java.util.concurrent.atomic.AtomicInteger; 134import java.util.regex.Pattern; 135 136/** 137 * TODO: 138 * Deprecate WIFI_STATE_UNKNOWN 139 */ 140 141/** 142 * Track the state of Wifi connectivity. All event handling is done here, 143 * and all changes in connectivity state are initiated here. 144 * 145 * Wi-Fi now supports three modes of operation: Client, SoftAp and p2p 146 * In the current implementation, we support concurrent wifi p2p and wifi operation. 147 * The WifiStateMachine handles SoftAp and Client operations while WifiP2pService 148 * handles p2p operation. 149 * 150 * @hide 151 */ 152public class WifiStateMachine extends StateMachine implements WifiNative.WifiPnoEventHandler, 153 WifiNative.WifiRssiEventHandler { 154 155 private static final String NETWORKTYPE = "WIFI"; 156 private static final String NETWORKTYPE_UNTRUSTED = "WIFI_UT"; 157 private static boolean DBG = false; 158 private static boolean VDBG = false; 159 private static boolean VVDBG = false; 160 private static boolean USE_PAUSE_SCANS = false; 161 private static boolean mLogMessages = false; 162 private static final String TAG = "WifiStateMachine"; 163 164 private static final int ONE_HOUR_MILLI = 1000 * 60 * 60; 165 166 private static final String GOOGLE_OUI = "DA-A1-19"; 167 168 /* temporary debug flag - best network selection development */ 169 private static boolean PDBG = false; 170 171 /* debug flag, indicating if handling of ASSOCIATION_REJECT ended up blacklisting 172 * the corresponding BSSID. 173 */ 174 private boolean didBlackListBSSID = false; 175 176 /** 177 * Log with error attribute 178 * 179 * @param s is string log 180 */ 181 protected void loge(String s) { 182 Log.e(getName(), s); 183 } 184 protected void logd(String s) { 185 Log.d(getName(), s); 186 } 187 protected void log(String s) {; 188 Log.d(getName(), s); 189 } 190 191 private WifiMetrics mWifiMetrics; 192 private WifiMonitor mWifiMonitor; 193 private WifiNative mWifiNative; 194 private WifiConfigStore mWifiConfigStore; 195 private WifiQualifiedNetworkSelector mWifiQualifiedNetworkSelector; 196 private INetworkManagementService mNwService; 197 private ConnectivityManager mCm; 198 private BaseWifiLogger mWifiLogger; 199 private WifiApConfigStore mWifiApConfigStore; 200 private final boolean mP2pSupported; 201 private final AtomicBoolean mP2pConnected = new AtomicBoolean(false); 202 private boolean mTemporarilyDisconnectWifi = false; 203 private final String mPrimaryDeviceType; 204 private final UserManager mUserManager; 205 206 /* Scan results handling */ 207 private List<ScanDetail> mScanResults = new ArrayList<>(); 208 private static final Pattern scanResultPattern = Pattern.compile("\t+"); 209 private static final int SCAN_RESULT_CACHE_SIZE = 160; 210 private final LruCache<NetworkDetail, ScanDetail> mScanResultCache; 211 // For debug, number of known scan results that were found as part of last scan result event, 212 // as well the number of scans results returned by the supplicant with that message 213 private int mNumScanResultsKnown; 214 private int mNumScanResultsReturned; 215 216 private boolean mScreenOn = false; 217 218 /* Chipset supports background scan */ 219 private final boolean mBackgroundScanSupported; 220 221 private final String mInterfaceName; 222 /* Tethering interface could be separate from wlan interface */ 223 private String mTetherInterfaceName; 224 225 private int mLastSignalLevel = -1; 226 private String mLastBssid; 227 private int mLastNetworkId; // The network Id we successfully joined 228 private ScanDetail mActiveScanDetail; // ScanDetail associated with active network 229 private boolean linkDebouncing = false; 230 231 private boolean mHalBasedPnoDriverSupported = false; 232 233 // Below booleans are configurations coming from the Developper Settings 234 private boolean mEnableAssociatedNetworkSwitchingInDevSettings = true; 235 private boolean mHalBasedPnoEnableInDevSettings = false; 236 237 private int mHalFeatureSet = 0; 238 private static int mPnoResultFound = 0; 239 240 private int mCurrentUserId = UserHandle.USER_SYSTEM; 241 242 private boolean mAllowUntrustedConnections = false; 243 244 @Override 245 public void onPnoNetworkFound(ScanResult results[]) { 246 if (DBG) { 247 Log.e(TAG, "onPnoNetworkFound event received num = " + results.length); 248 for (int i = 0; i < results.length; i++) { 249 Log.e(TAG, results[i].toString()); 250 } 251 } 252 sendMessage(CMD_PNO_NETWORK_FOUND, results.length, 0, results); 253 } 254 255 public void processPnoNetworkFound(ScanResult results[]) { 256 ScanSettings settings = new ScanSettings(); 257 settings.channelSet = new ArrayList<WifiChannel>(); 258 StringBuilder sb = new StringBuilder(); 259 sb.append(""); 260 for (int i=0; i<results.length; i++) { 261 WifiChannel channel = new WifiChannel(); 262 channel.freqMHz = results[i].frequency; 263 settings.channelSet.add(channel); 264 sb.append(results[i].SSID).append(" "); 265 } 266 267 stopPnoOffload(); 268 269 Log.e(TAG, "processPnoNetworkFound starting scan cnt=" + mPnoResultFound); 270 startScan(PNO_NETWORK_FOUND_SOURCE, mPnoResultFound, settings, null); 271 mPnoResultFound ++; 272 //sendMessage(CMD_SCAN_RESULTS_AVAILABLE); 273 int delay = 30 * 1000; 274 // reconfigure Pno after 1 minutes if we're still in disconnected state 275 sendMessageDelayed(CMD_RESTART_AUTOJOIN_OFFLOAD, delay, 276 mRestartAutoJoinOffloadCounter, " processPnoNetworkFound " + sb.toString(), 277 (long)delay); 278 mRestartAutoJoinOffloadCounter++; 279 } 280 281 @Override 282 public void onRssiThresholdBreached(byte curRssi) { 283 if (DBG) { 284 Log.e(TAG, "onRssiThresholdBreach event. Cur Rssi = " + curRssi); 285 } 286 sendMessage(CMD_RSSI_THRESHOLD_BREACH, curRssi); 287 } 288 289 public void processRssiThreshold(byte curRssi, int reason) { 290 if (curRssi == Byte.MAX_VALUE || curRssi == Byte.MIN_VALUE) { 291 Log.wtf(TAG, "processRssiThreshold: Invalid rssi " + curRssi); 292 return; 293 } 294 for (int i = 0; i < mRssiRanges.length; i++) { 295 if (curRssi < mRssiRanges[i]) { 296 // Assume sorted values(ascending order) for rssi, 297 // bounded by high(127) and low(-128) at extremeties 298 byte maxRssi = mRssiRanges[i]; 299 byte minRssi = mRssiRanges[i-1]; 300 // This value of hw has to be believed as this value is averaged and has breached 301 // the rssi thresholds and raised event to host. This would be eggregious if this 302 // value is invalid 303 mWifiInfo.setRssi((int) curRssi); 304 updateCapabilities(getCurrentWifiConfiguration()); 305 int ret = startRssiMonitoringOffload(maxRssi, minRssi); 306 Log.d(TAG, "Re-program RSSI thresholds for " + smToString(reason) + 307 ": [" + minRssi + ", " + maxRssi + "], curRssi=" + curRssi + " ret=" + ret); 308 break; 309 } 310 } 311 } 312 public void registerNetworkDisabled(int netId) { 313 // Restart legacy PNO and autojoin offload if needed 314 sendMessage(CMD_RESTART_AUTOJOIN_OFFLOAD, 0, 315 mRestartAutoJoinOffloadCounter, " registerNetworkDisabled " + netId); 316 mRestartAutoJoinOffloadCounter++; 317 } 318 319 // Testing various network disconnect cases by sending lots of spurious 320 // disconnect to supplicant 321 private boolean testNetworkDisconnect = false; 322 323 private boolean mEnableRssiPolling = false; 324 private boolean mLegacyPnoEnabled = false; 325 private int mRssiPollToken = 0; 326 /* 3 operational states for STA operation: CONNECT_MODE, SCAN_ONLY_MODE, SCAN_ONLY_WIFI_OFF_MODE 327 * In CONNECT_MODE, the STA can scan and connect to an access point 328 * In SCAN_ONLY_MODE, the STA can only scan for access points 329 * In SCAN_ONLY_WIFI_OFF_MODE, the STA can only scan for access points with wifi toggle being off 330 */ 331 private int mOperationalMode = CONNECT_MODE; 332 private boolean mIsScanOngoing = false; 333 private boolean mIsFullScanOngoing = false; 334 private boolean mSendScanResultsBroadcast = false; 335 336 private final Queue<Message> mBufferedScanMsg = new LinkedList<Message>(); 337 private WorkSource mScanWorkSource = null; 338 private static final int UNKNOWN_SCAN_SOURCE = -1; 339 private static final int SCAN_ALARM_SOURCE = -2; 340 private static final int ADD_OR_UPDATE_SOURCE = -3; 341 private static final int SET_ALLOW_UNTRUSTED_SOURCE = -4; 342 private static final int ENABLE_WIFI = -5; 343 public static final int DFS_RESTRICTED_SCAN_REQUEST = -6; 344 public static final int PNO_NETWORK_FOUND_SOURCE = -7; 345 346 private static final int SCAN_REQUEST_BUFFER_MAX_SIZE = 10; 347 private static final String CUSTOMIZED_SCAN_SETTING = "customized_scan_settings"; 348 private static final String CUSTOMIZED_SCAN_WORKSOURCE = "customized_scan_worksource"; 349 private static final String SCAN_REQUEST_TIME = "scan_request_time"; 350 351 /* Tracks if state machine has received any screen state change broadcast yet. 352 * We can miss one of these at boot. 353 */ 354 private AtomicBoolean mScreenBroadcastReceived = new AtomicBoolean(false); 355 356 private boolean mBluetoothConnectionActive = false; 357 358 private PowerManager.WakeLock mSuspendWakeLock; 359 360 /** 361 * Interval in milliseconds between polling for RSSI 362 * and linkspeed information 363 */ 364 private static final int POLL_RSSI_INTERVAL_MSECS = 3000; 365 366 /** 367 * Interval in milliseconds between receiving a disconnect event 368 * while connected to a good AP, and handling the disconnect proper 369 */ 370 private static final int LINK_FLAPPING_DEBOUNCE_MSEC = 7000; 371 372 /** 373 * Delay between supplicant restarts upon failure to establish connection 374 */ 375 private static final int SUPPLICANT_RESTART_INTERVAL_MSECS = 5000; 376 377 /** 378 * Number of times we attempt to restart supplicant 379 */ 380 private static final int SUPPLICANT_RESTART_TRIES = 5; 381 382 private int mSupplicantRestartCount = 0; 383 /* Tracks sequence number on stop failure message */ 384 private int mSupplicantStopFailureToken = 0; 385 386 /** 387 * Tether state change notification time out 388 */ 389 private static final int TETHER_NOTIFICATION_TIME_OUT_MSECS = 5000; 390 391 /* Tracks sequence number on a tether notification time out */ 392 private int mTetherToken = 0; 393 394 /** 395 * Driver start time out. 396 */ 397 private static final int DRIVER_START_TIME_OUT_MSECS = 10000; 398 399 /* Tracks sequence number on a driver time out */ 400 private int mDriverStartToken = 0; 401 402 /** 403 * Don't select new network when previous network selection is 404 * pending connection for this much time 405 */ 406 private static final int CONNECT_TIMEOUT_MSEC = 3000; 407 408 /** 409 * The link properties of the wifi interface. 410 * Do not modify this directly; use updateLinkProperties instead. 411 */ 412 private LinkProperties mLinkProperties; 413 414 /* Tracks sequence number on a periodic scan message */ 415 private int mPeriodicScanToken = 0; 416 417 // Wakelock held during wifi start/stop and driver load/unload 418 private PowerManager.WakeLock mWakeLock; 419 420 private Context mContext; 421 422 private final Object mDhcpResultsLock = new Object(); 423 private DhcpResults mDhcpResults; 424 425 // NOTE: Do not return to clients - use #getWiFiInfoForUid(int) 426 private WifiInfo mWifiInfo; 427 private NetworkInfo mNetworkInfo; 428 private final NetworkCapabilities mDfltNetworkCapabilities; 429 private SupplicantStateTracker mSupplicantStateTracker; 430 431 private int mWifiLinkLayerStatsSupported = 4; // Temporary disable 432 433 private final AtomicInteger mCountryCodeSequence = new AtomicInteger(); 434 435 // Whether the state machine goes thru the Disconnecting->Disconnected->ObtainingIpAddress 436 private boolean mAutoRoaming = false; 437 438 // Roaming failure count 439 private int mRoamFailCount = 0; 440 441 // This is the BSSID we are trying to associate to, it can be set to "any" 442 // if we havent selected a BSSID for joining. 443 // if we havent selected a BSSID for joining. 444 // The BSSID we are associated to is found in mWifiInfo 445 private String mTargetRoamBSSID = "any"; 446 //This one is used to track whta is the current target network ID. This is used for error 447 // handling during connection setup since many error message from supplicant does not report 448 // SSID Once connected, it will be set to invalid 449 private int mTargetNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 450 451 private long mLastDriverRoamAttempt = 0; 452 453 private WifiConfiguration targetWificonfiguration = null; 454 455 // Used as debug to indicate which configuration last was saved 456 private WifiConfiguration lastSavedConfigurationAttempt = null; 457 458 // Used as debug to indicate which configuration last was removed 459 private WifiConfiguration lastForgetConfigurationAttempt = null; 460 461 //Random used by softAP channel Selection 462 private static Random mRandom = new Random(Calendar.getInstance().getTimeInMillis()); 463 464 boolean isRoaming() { 465 return mAutoRoaming; 466 } 467 468 public void autoRoamSetBSSID(int netId, String bssid) { 469 autoRoamSetBSSID(mWifiConfigStore.getWifiConfiguration(netId), bssid); 470 } 471 472 public boolean autoRoamSetBSSID(WifiConfiguration config, String bssid) { 473 boolean ret = true; 474 if (mTargetRoamBSSID == null) mTargetRoamBSSID = "any"; 475 if (bssid == null) bssid = "any"; 476 if (config == null) return false; // Nothing to do 477 478 if (mTargetRoamBSSID != null && bssid == mTargetRoamBSSID && bssid == config.BSSID) { 479 return false; // We didnt change anything 480 } 481 if (!mTargetRoamBSSID.equals("any") && bssid.equals("any")) { 482 // Changing to ANY 483 if (!mWifiConfigStore.roamOnAny) { 484 ret = false; // Nothing to do 485 } 486 } 487 if (config.BSSID != null) { 488 bssid = config.BSSID; 489 if (DBG) { 490 Log.d(TAG, "force BSSID to " + bssid + "due to config"); 491 } 492 } 493 494 if (VDBG) { 495 logd("autoRoamSetBSSID " + bssid + " key=" + config.configKey()); 496 } 497 config.getNetworkSelectionStatus().setNetworkSelectionBSSID(bssid); 498 mTargetRoamBSSID = bssid; 499 mWifiConfigStore.saveWifiConfigBSSID(config); 500 return ret; 501 } 502 503 /** 504 * set Config's default BSSID (for association purpose) 505 * @param config config need set BSSID 506 * @param bssid default BSSID to assocaite with when connect to this network 507 * @return false -- does not change the current default BSSID of the configure 508 * true -- change the current default BSSID of the configur 509 */ 510 private boolean setTargetBssid(WifiConfiguration config, String bssid) { 511 if (config == null) { 512 return false; 513 } 514 515 if (config.BSSID != null) { 516 bssid = config.BSSID; 517 if (DBG) { 518 Log.d(TAG, "force BSSID to " + bssid + "due to config"); 519 } 520 } 521 522 if (bssid == null) { 523 bssid = "any"; 524 } 525 526 String networkSelectionBSSID = config.getNetworkSelectionStatus() 527 .getNetworkSelectionBSSID(); 528 if (networkSelectionBSSID != null && networkSelectionBSSID.equals(bssid)) { 529 if (DBG) { 530 Log.d(TAG, "Current prefered BSSID is same as target"); 531 return false; 532 } 533 } 534 535 if (DBG) { 536 Log.d(TAG, "target set to " + config.SSID + ":" + bssid); 537 } 538 539 config.getNetworkSelectionStatus().setNetworkSelectionBSSID(bssid); 540 mTargetRoamBSSID = bssid; 541 mWifiConfigStore.saveWifiConfigBSSID(config); 542 return true; 543 } 544 /** 545 * Save the UID correctly depending on if this is a new or existing network. 546 * @return true if operation is authorized, false otherwise 547 */ 548 boolean recordUidIfAuthorized(WifiConfiguration config, int uid, boolean onlyAnnotate) { 549 if (!mWifiConfigStore.isNetworkConfigured(config)) { 550 config.creatorUid = uid; 551 config.creatorName = mContext.getPackageManager().getNameForUid(uid); 552 } else if (!mWifiConfigStore.canModifyNetwork(uid, config, onlyAnnotate)) { 553 return false; 554 } 555 556 config.lastUpdateUid = uid; 557 config.lastUpdateName = mContext.getPackageManager().getNameForUid(uid); 558 559 return true; 560 561 } 562 563 /** 564 * Checks to see if user has specified if the apps configuration is connectable. 565 * If the user hasn't specified we query the user and return true. 566 * 567 * @param message The message to be deferred 568 * @param netId Network id of the configuration to check against 569 * @param allowOverride If true we won't defer to the user if the uid of the message holds the 570 * CONFIG_OVERRIDE_PERMISSION 571 * @return True if we are waiting for user feedback or netId is invalid. False otherwise. 572 */ 573 boolean deferForUserInput(Message message, int netId, boolean allowOverride){ 574 final WifiConfiguration config = mWifiConfigStore.getWifiConfiguration(netId); 575 576 // We can only evaluate saved configurations. 577 if (config == null) { 578 logd("deferForUserInput: configuration for netId=" + netId + " not stored"); 579 return true; 580 } 581 582 switch (config.userApproved) { 583 case WifiConfiguration.USER_APPROVED: 584 case WifiConfiguration.USER_BANNED: 585 return false; 586 case WifiConfiguration.USER_PENDING: 587 default: // USER_UNSPECIFIED 588 /* the intention was to ask user here; but a dialog box is * 589 * too invasive; so we are going to allow connection for now */ 590 config.userApproved = WifiConfiguration.USER_APPROVED; 591 return false; 592 } 593 } 594 595 private final IpManager mIpManager; 596 597 private AlarmManager mAlarmManager; 598 private PendingIntent mScanIntent; 599 private PendingIntent mDriverStopIntent; 600 private PendingIntent mPnoIntent; 601 602 private int mDisconnectedPnoAlarmCount = 0; 603 /* Tracks current frequency mode */ 604 private AtomicInteger mFrequencyBand = new AtomicInteger(WifiManager.WIFI_FREQUENCY_BAND_AUTO); 605 606 /* Tracks if we are filtering Multicast v4 packets. Default is to filter. */ 607 private AtomicBoolean mFilteringMulticastV4Packets = new AtomicBoolean(true); 608 609 // Channel for sending replies. 610 private AsyncChannel mReplyChannel = new AsyncChannel(); 611 612 private WifiP2pServiceImpl mWifiP2pServiceImpl; 613 614 // Used to initiate a connection with WifiP2pService 615 private AsyncChannel mWifiP2pChannel; 616 617 private WifiScanner mWifiScanner; 618 619 private int mConnectionRequests = 0; 620 private WifiNetworkFactory mNetworkFactory; 621 private UntrustedWifiNetworkFactory mUntrustedNetworkFactory; 622 private WifiNetworkAgent mNetworkAgent; 623 624 private String[] mWhiteListedSsids = null; 625 626 private byte[] mRssiRanges; 627 628 // Keep track of various statistics, for retrieval by System Apps, i.e. under @SystemApi 629 // We should really persist that into the networkHistory.txt file, and read it back when 630 // WifiStateMachine starts up 631 private WifiConnectionStatistics mWifiConnectionStatistics = new WifiConnectionStatistics(); 632 633 // Used to filter out requests we couldn't possibly satisfy. 634 private final NetworkCapabilities mNetworkCapabilitiesFilter = new NetworkCapabilities(); 635 636 /* The base for wifi message types */ 637 static final int BASE = Protocol.BASE_WIFI; 638 /* Start the supplicant */ 639 static final int CMD_START_SUPPLICANT = BASE + 11; 640 /* Stop the supplicant */ 641 static final int CMD_STOP_SUPPLICANT = BASE + 12; 642 /* Start the driver */ 643 static final int CMD_START_DRIVER = BASE + 13; 644 /* Stop the driver */ 645 static final int CMD_STOP_DRIVER = BASE + 14; 646 /* Indicates Static IP succeeded */ 647 static final int CMD_STATIC_IP_SUCCESS = BASE + 15; 648 /* Indicates Static IP failed */ 649 static final int CMD_STATIC_IP_FAILURE = BASE + 16; 650 /* Indicates supplicant stop failed */ 651 static final int CMD_STOP_SUPPLICANT_FAILED = BASE + 17; 652 /* A delayed message sent to start driver when it fail to come up */ 653 static final int CMD_DRIVER_START_TIMED_OUT = BASE + 19; 654 655 /* Start the soft access point */ 656 static final int CMD_START_AP = BASE + 21; 657 /* Indicates soft ap start succeeded */ 658 static final int CMD_START_AP_SUCCESS = BASE + 22; 659 /* Indicates soft ap start failed */ 660 static final int CMD_START_AP_FAILURE = BASE + 23; 661 /* Stop the soft access point */ 662 static final int CMD_STOP_AP = BASE + 24; 663 /* Invoked when getting a tether state change notification */ 664 static final int CMD_TETHER_STATE_CHANGE = BASE + 29; 665 /* A delayed message sent to indicate tether state change failed to arrive */ 666 static final int CMD_TETHER_NOTIFICATION_TIMED_OUT = BASE + 30; 667 668 static final int CMD_BLUETOOTH_ADAPTER_STATE_CHANGE = BASE + 31; 669 670 /* Supplicant commands */ 671 /* Is supplicant alive ? */ 672 static final int CMD_PING_SUPPLICANT = BASE + 51; 673 /* Add/update a network configuration */ 674 static final int CMD_ADD_OR_UPDATE_NETWORK = BASE + 52; 675 /* Delete a network */ 676 static final int CMD_REMOVE_NETWORK = BASE + 53; 677 /* Enable a network. The device will attempt a connection to the given network. */ 678 static final int CMD_ENABLE_NETWORK = BASE + 54; 679 /* Enable all networks */ 680 static final int CMD_ENABLE_ALL_NETWORKS = BASE + 55; 681 /* Blacklist network. De-prioritizes the given BSSID for connection. */ 682 static final int CMD_BLACKLIST_NETWORK = BASE + 56; 683 /* Clear the blacklist network list */ 684 static final int CMD_CLEAR_BLACKLIST = BASE + 57; 685 /* Save configuration */ 686 static final int CMD_SAVE_CONFIG = BASE + 58; 687 /* Get configured networks */ 688 static final int CMD_GET_CONFIGURED_NETWORKS = BASE + 59; 689 /* Get available frequencies */ 690 static final int CMD_GET_CAPABILITY_FREQ = BASE + 60; 691 /* Get adaptors */ 692 static final int CMD_GET_SUPPORTED_FEATURES = BASE + 61; 693 /* Get configured networks with real preSharedKey */ 694 static final int CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS = BASE + 62; 695 /* Get Link Layer Stats thru HAL */ 696 static final int CMD_GET_LINK_LAYER_STATS = BASE + 63; 697 /* Supplicant commands after driver start*/ 698 /* Initiate a scan */ 699 static final int CMD_START_SCAN = BASE + 71; 700 /* Set operational mode. CONNECT, SCAN ONLY, SCAN_ONLY with Wi-Fi off mode */ 701 static final int CMD_SET_OPERATIONAL_MODE = BASE + 72; 702 /* Disconnect from a network */ 703 static final int CMD_DISCONNECT = BASE + 73; 704 /* Reconnect to a network */ 705 static final int CMD_RECONNECT = BASE + 74; 706 /* Reassociate to a network */ 707 static final int CMD_REASSOCIATE = BASE + 75; 708 /* Get Connection Statistis */ 709 static final int CMD_GET_CONNECTION_STATISTICS = BASE + 76; 710 711 /* Controls suspend mode optimizations 712 * 713 * When high perf mode is enabled, suspend mode optimizations are disabled 714 * 715 * When high perf mode is disabled, suspend mode optimizations are enabled 716 * 717 * Suspend mode optimizations include: 718 * - packet filtering 719 * - turn off roaming 720 * - DTIM wake up settings 721 */ 722 static final int CMD_SET_HIGH_PERF_MODE = BASE + 77; 723 /* Set the country code */ 724 static final int CMD_SET_COUNTRY_CODE = BASE + 80; 725 /* Enables RSSI poll */ 726 static final int CMD_ENABLE_RSSI_POLL = BASE + 82; 727 /* RSSI poll */ 728 static final int CMD_RSSI_POLL = BASE + 83; 729 /* Set up packet filtering */ 730 static final int CMD_START_PACKET_FILTERING = BASE + 84; 731 /* Clear packet filter */ 732 static final int CMD_STOP_PACKET_FILTERING = BASE + 85; 733 /* Enable suspend mode optimizations in the driver */ 734 static final int CMD_SET_SUSPEND_OPT_ENABLED = BASE + 86; 735 /* Delayed NETWORK_DISCONNECT */ 736 static final int CMD_DELAYED_NETWORK_DISCONNECT = BASE + 87; 737 /* When there are no saved networks, we do a periodic scan to notify user of 738 * an open network */ 739 static final int CMD_NO_NETWORKS_PERIODIC_SCAN = BASE + 88; 740 /* Test network Disconnection NETWORK_DISCONNECT */ 741 static final int CMD_TEST_NETWORK_DISCONNECT = BASE + 89; 742 743 private int testNetworkDisconnectCounter = 0; 744 745 /* arg1 values to CMD_STOP_PACKET_FILTERING and CMD_START_PACKET_FILTERING */ 746 static final int MULTICAST_V6 = 1; 747 static final int MULTICAST_V4 = 0; 748 749 /* Set the frequency band */ 750 static final int CMD_SET_FREQUENCY_BAND = BASE + 90; 751 /* Enable TDLS on a specific MAC address */ 752 static final int CMD_ENABLE_TDLS = BASE + 92; 753 /* DHCP/IP configuration watchdog */ 754 static final int CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER = BASE + 93; 755 756 /** 757 * Watchdog for protecting against b/16823537 758 * Leave time for 4-way handshake to succeed 759 */ 760 static final int ROAM_GUARD_TIMER_MSEC = 15000; 761 762 int roamWatchdogCount = 0; 763 /* Roam state watchdog */ 764 static final int CMD_ROAM_WATCHDOG_TIMER = BASE + 94; 765 /* Screen change intent handling */ 766 static final int CMD_SCREEN_STATE_CHANGED = BASE + 95; 767 768 /* Disconnecting state watchdog */ 769 static final int CMD_DISCONNECTING_WATCHDOG_TIMER = BASE + 96; 770 771 /* Remove a packages associated configrations */ 772 static final int CMD_REMOVE_APP_CONFIGURATIONS = BASE + 97; 773 774 /* Disable an ephemeral network */ 775 static final int CMD_DISABLE_EPHEMERAL_NETWORK = BASE + 98; 776 777 /* Get matching network */ 778 static final int CMD_GET_MATCHING_CONFIG = BASE + 99; 779 780 /* alert from firmware */ 781 static final int CMD_FIRMWARE_ALERT = BASE + 100; 782 783 /* SIM is removed; reset any cached data for it */ 784 static final int CMD_RESET_SIM_NETWORKS = BASE + 101; 785 786 /* OSU APIs */ 787 static final int CMD_ADD_PASSPOINT_MO = BASE + 102; 788 static final int CMD_MODIFY_PASSPOINT_MO = BASE + 103; 789 static final int CMD_QUERY_OSU_ICON = BASE + 104; 790 791 /* try to match a provider with current network */ 792 static final int CMD_MATCH_PROVIDER_NETWORK = BASE + 105; 793 794 /** 795 * Make this timer 40 seconds, which is about the normal DHCP timeout. 796 * In no valid case, the WiFiStateMachine should remain stuck in ObtainingIpAddress 797 * for more than 30 seconds. 798 */ 799 static final int OBTAINING_IP_ADDRESS_GUARD_TIMER_MSEC = 40000; 800 801 int obtainingIpWatchdogCount = 0; 802 803 /* Commands from/to the SupplicantStateTracker */ 804 /* Reset the supplicant state tracker */ 805 static final int CMD_RESET_SUPPLICANT_STATE = BASE + 111; 806 807 int disconnectingWatchdogCount = 0; 808 static final int DISCONNECTING_GUARD_TIMER_MSEC = 5000; 809 810 /* P2p commands */ 811 /* We are ok with no response here since we wont do much with it anyway */ 812 public static final int CMD_ENABLE_P2P = BASE + 131; 813 /* In order to shut down supplicant cleanly, we wait till p2p has 814 * been disabled */ 815 public static final int CMD_DISABLE_P2P_REQ = BASE + 132; 816 public static final int CMD_DISABLE_P2P_RSP = BASE + 133; 817 818 public static final int CMD_BOOT_COMPLETED = BASE + 134; 819 820 /* We now have a valid IP configuration. */ 821 static final int CMD_IP_CONFIGURATION_SUCCESSFUL = BASE + 138; 822 /* We no longer have a valid IP configuration. */ 823 static final int CMD_IP_CONFIGURATION_LOST = BASE + 139; 824 /* Link configuration (IP address, DNS, ...) changes notified via netlink */ 825 static final int CMD_UPDATE_LINKPROPERTIES = BASE + 140; 826 827 /* Supplicant is trying to associate to a given BSSID */ 828 static final int CMD_TARGET_BSSID = BASE + 141; 829 830 /* Reload all networks and reconnect */ 831 static final int CMD_RELOAD_TLS_AND_RECONNECT = BASE + 142; 832 833 static final int CMD_AUTO_CONNECT = BASE + 143; 834 835 private static final int NETWORK_STATUS_UNWANTED_DISCONNECT = 0; 836 private static final int NETWORK_STATUS_UNWANTED_VALIDATION_FAILED = 1; 837 private static final int NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN = 2; 838 839 static final int CMD_UNWANTED_NETWORK = BASE + 144; 840 841 static final int CMD_AUTO_ROAM = BASE + 145; 842 843 static final int CMD_AUTO_SAVE_NETWORK = BASE + 146; 844 845 static final int CMD_ASSOCIATED_BSSID = BASE + 147; 846 847 static final int CMD_NETWORK_STATUS = BASE + 148; 848 849 /* A layer 3 neighbor on the Wi-Fi link became unreachable. */ 850 static final int CMD_IP_REACHABILITY_LOST = BASE + 149; 851 852 /* Remove a packages associated configrations */ 853 static final int CMD_REMOVE_USER_CONFIGURATIONS = BASE + 152; 854 855 static final int CMD_ACCEPT_UNVALIDATED = BASE + 153; 856 857 /* used to restart PNO when it was stopped due to association attempt */ 858 static final int CMD_RESTART_AUTOJOIN_OFFLOAD = BASE + 154; 859 860 static int mRestartAutoJoinOffloadCounter = 0; 861 862 /* used to log if PNO was started */ 863 static final int CMD_STARTED_PNO_DBG = BASE + 155; 864 865 static final int CMD_PNO_NETWORK_FOUND = BASE + 156; 866 867 /* used to log if PNO was started */ 868 static final int CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION = BASE + 158; 869 870 /* used to log if GSCAN was started */ 871 static final int CMD_STARTED_GSCAN_DBG = BASE + 159; 872 873 /* used to offload sending IP packet */ 874 static final int CMD_START_IP_PACKET_OFFLOAD = BASE + 160; 875 876 /* used to stop offload sending IP packet */ 877 static final int CMD_STOP_IP_PACKET_OFFLOAD = BASE + 161; 878 879 /* used to start rssi monitoring in hw */ 880 static final int CMD_START_RSSI_MONITORING_OFFLOAD = BASE + 162; 881 882 /* used to stop rssi moniroting in hw */ 883 static final int CMD_STOP_RSSI_MONITORING_OFFLOAD = BASE + 163; 884 885 /* used to indicated RSSI threshold breach in hw */ 886 static final int CMD_RSSI_THRESHOLD_BREACH = BASE + 164; 887 888 /* used to indicate that the foreground user was switched */ 889 static final int CMD_USER_SWITCH = BASE + 165; 890 891 /** 892 * Used temporarily to handle messages bounced between WifiStateMachine and IpManager. 893 * 894 * These will be deleted when DHCPv4 and static IP configuration are moved out. 895 */ 896 static final int CMD_IPV4_PROVISIONING_SUCCESS = BASE + 200; 897 static final int CMD_IPV4_PROVISIONING_FAILURE = BASE + 201; 898 899 900 /* Wifi state machine modes of operation */ 901 /* CONNECT_MODE - connect to any 'known' AP when it becomes available */ 902 public static final int CONNECT_MODE = 1; 903 /* SCAN_ONLY_MODE - don't connect to any APs; scan, but only while apps hold lock */ 904 public static final int SCAN_ONLY_MODE = 2; 905 /* SCAN_ONLY_WITH_WIFI_OFF - scan, but don't connect to any APs */ 906 public static final int SCAN_ONLY_WITH_WIFI_OFF_MODE = 3; 907 908 private static final int SUCCESS = 1; 909 private static final int FAILURE = -1; 910 911 /* Tracks if suspend optimizations need to be disabled by DHCP, 912 * screen or due to high perf mode. 913 * When any of them needs to disable it, we keep the suspend optimizations 914 * disabled 915 */ 916 private int mSuspendOptNeedsDisabled = 0; 917 918 private static final int SUSPEND_DUE_TO_DHCP = 1; 919 private static final int SUSPEND_DUE_TO_HIGH_PERF = 1 << 1; 920 private static final int SUSPEND_DUE_TO_SCREEN = 1 << 2; 921 922 /* Tracks if user has enabled suspend optimizations through settings */ 923 private AtomicBoolean mUserWantsSuspendOpt = new AtomicBoolean(true); 924 925 /** 926 * Default framework scan interval in milliseconds. This is used in the scenario in which 927 * wifi chipset does not support background scanning to set up a 928 * periodic wake up scan so that the device can connect to a new access 929 * point on the move. {@link Settings.Global#WIFI_FRAMEWORK_SCAN_INTERVAL_MS} can 930 * override this. 931 */ 932 private final int mDefaultFrameworkScanIntervalMs; 933 934 935 /** 936 * Scan period for the NO_NETWORKS_PERIIDOC_SCAN_FEATURE 937 */ 938 private final int mNoNetworksPeriodicScan; 939 940 /** 941 * Supplicant scan interval in milliseconds. 942 * Comes from {@link Settings.Global#WIFI_SUPPLICANT_SCAN_INTERVAL_MS} or 943 * from the default config if the setting is not set 944 */ 945 private long mSupplicantScanIntervalMs; 946 947 /** 948 * timeStamp of last full band scan we perfoemed for autojoin while connected with screen lit 949 */ 950 private long lastFullBandConnectedTimeMilli; 951 952 /** 953 * time interval to the next full band scan we will perform for 954 * autojoin while connected with screen lit 955 */ 956 private long fullBandConnectedTimeIntervalMilli; 957 958 /** 959 * max time interval to the next full band scan we will perform for 960 * autojoin while connected with screen lit 961 * Max time is 5 minutes 962 */ 963 private static final long maxFullBandConnectedTimeIntervalMilli = 1000 * 60 * 5; 964 965 /** 966 * Minimum time interval between enabling all networks. 967 * A device can end up repeatedly connecting to a bad network on screen on/off toggle 968 * due to enabling every time. We add a threshold to avoid this. 969 */ 970 private static final int MIN_INTERVAL_ENABLE_ALL_NETWORKS_MS = 10 * 60 * 1000; /* 10 minutes */ 971 private long mLastEnableAllNetworksTime; 972 973 int mRunningBeaconCount = 0; 974 975 976 // config option that indicate whether or not to reset country code to default when 977 // cellular radio indicates country code loss 978 private boolean mRevertCountryCodeOnCellularLoss = false; 979 980 private String mDefaultCountryCode; 981 982 private static final String BOOT_DEFAULT_WIFI_COUNTRY_CODE = "ro.boot.wificountrycode"; 983 984 // Supplicant doesn't like setting the same country code multiple times (it may drop 985 // currently connected network), so we save the current device set country code here to avoid 986 // redundency 987 private String mDriverSetCountryCode = null; 988 989 /* Default parent state */ 990 private State mDefaultState = new DefaultState(); 991 /* Temporary initial state */ 992 private State mInitialState = new InitialState(); 993 /* Driver loaded, waiting for supplicant to start */ 994 private State mSupplicantStartingState = new SupplicantStartingState(); 995 /* Driver loaded and supplicant ready */ 996 private State mSupplicantStartedState = new SupplicantStartedState(); 997 /* Waiting for supplicant to stop and monitor to exit */ 998 private State mSupplicantStoppingState = new SupplicantStoppingState(); 999 /* Driver start issued, waiting for completed event */ 1000 private State mDriverStartingState = new DriverStartingState(); 1001 /* Driver started */ 1002 private State mDriverStartedState = new DriverStartedState(); 1003 /* Wait until p2p is disabled 1004 * This is a special state which is entered right after we exit out of DriverStartedState 1005 * before transitioning to another state. 1006 */ 1007 private State mWaitForP2pDisableState = new WaitForP2pDisableState(); 1008 /* Driver stopping */ 1009 private State mDriverStoppingState = new DriverStoppingState(); 1010 /* Driver stopped */ 1011 private State mDriverStoppedState = new DriverStoppedState(); 1012 /* Scan for networks, no connection will be established */ 1013 private State mScanModeState = new ScanModeState(); 1014 /* Connecting to an access point */ 1015 private State mConnectModeState = new ConnectModeState(); 1016 /* Connected at 802.11 (L2) level */ 1017 private State mL2ConnectedState = new L2ConnectedState(); 1018 /* fetching IP after connection to access point (assoc+auth complete) */ 1019 private State mObtainingIpState = new ObtainingIpState(); 1020 /* Connected with IP addr */ 1021 private State mConnectedState = new ConnectedState(); 1022 /* Roaming */ 1023 private State mRoamingState = new RoamingState(); 1024 /* disconnect issued, waiting for network disconnect confirmation */ 1025 private State mDisconnectingState = new DisconnectingState(); 1026 /* Network is not connected, supplicant assoc+auth is not complete */ 1027 private State mDisconnectedState = new DisconnectedState(); 1028 /* Waiting for WPS to be completed*/ 1029 private State mWpsRunningState = new WpsRunningState(); 1030 1031 /* Soft ap is starting up */ 1032 private State mSoftApStartingState = new SoftApStartingState(); 1033 /* Soft ap is running */ 1034 private State mSoftApStartedState = new SoftApStartedState(); 1035 /* Soft ap is running and we are waiting for tether notification */ 1036 private State mTetheringState = new TetheringState(); 1037 /* Soft ap is running and we are tethered through connectivity service */ 1038 private State mTetheredState = new TetheredState(); 1039 /* Waiting for untether confirmation before stopping soft Ap */ 1040 private State mUntetheringState = new UntetheringState(); 1041 1042 1043 1044 private class WifiScanListener implements WifiScanner.ScanListener { 1045 @Override 1046 public void onSuccess() { 1047 Log.e(TAG, "WifiScanListener onSuccess"); 1048 }; 1049 @Override 1050 public void onFailure(int reason, String description) { 1051 Log.e(TAG, "WifiScanListener onFailure"); 1052 }; 1053 @Override 1054 public void onPeriodChanged(int periodInMs) { 1055 Log.e(TAG, "WifiScanListener onPeriodChanged period=" + periodInMs); 1056 } 1057 @Override 1058 public void onResults(WifiScanner.ScanData[] results) { 1059 Log.e(TAG, "WifiScanListener onResults2 " + results.length); 1060 } 1061 @Override 1062 public void onFullResult(ScanResult fullScanResult) { 1063 Log.e(TAG, "WifiScanListener onFullResult " + fullScanResult.toString()); 1064 } 1065 1066 WifiScanListener() {} 1067 } 1068 1069 WifiScanListener mWifiScanListener = new WifiScanListener(); 1070 1071 1072 private class TetherStateChange { 1073 ArrayList<String> available; 1074 ArrayList<String> active; 1075 1076 TetherStateChange(ArrayList<String> av, ArrayList<String> ac) { 1077 available = av; 1078 active = ac; 1079 } 1080 } 1081 1082 public static class SimAuthRequestData { 1083 int networkId; 1084 int protocol; 1085 String ssid; 1086 // EAP-SIM: data[] contains the 3 rand, one for each of the 3 challenges 1087 // EAP-AKA/AKA': data[] contains rand & authn couple for the single challenge 1088 String[] data; 1089 } 1090 1091 /** 1092 * One of {@link WifiManager#WIFI_STATE_DISABLED}, 1093 * {@link WifiManager#WIFI_STATE_DISABLING}, 1094 * {@link WifiManager#WIFI_STATE_ENABLED}, 1095 * {@link WifiManager#WIFI_STATE_ENABLING}, 1096 * {@link WifiManager#WIFI_STATE_UNKNOWN} 1097 */ 1098 private final AtomicInteger mWifiState = new AtomicInteger(WIFI_STATE_DISABLED); 1099 1100 /** 1101 * One of {@link WifiManager#WIFI_AP_STATE_DISABLED}, 1102 * {@link WifiManager#WIFI_AP_STATE_DISABLING}, 1103 * {@link WifiManager#WIFI_AP_STATE_ENABLED}, 1104 * {@link WifiManager#WIFI_AP_STATE_ENABLING}, 1105 * {@link WifiManager#WIFI_AP_STATE_FAILED} 1106 */ 1107 private final AtomicInteger mWifiApState = new AtomicInteger(WIFI_AP_STATE_DISABLED); 1108 1109 private static final int SCAN_REQUEST = 0; 1110 private static final String ACTION_START_SCAN = 1111 "com.android.server.WifiManager.action.START_SCAN"; 1112 1113 private static final int PNO_START_REQUEST = 0; 1114 private static final String ACTION_START_PNO = 1115 "com.android.server.WifiManager.action.START_PNO"; 1116 1117 /** 1118 * Keep track of whether WIFI is running. 1119 */ 1120 private boolean mIsRunning = false; 1121 1122 /** 1123 * Keep track of whether we last told the battery stats we had started. 1124 */ 1125 private boolean mReportedRunning = false; 1126 1127 /** 1128 * Most recently set source of starting WIFI. 1129 */ 1130 private final WorkSource mRunningWifiUids = new WorkSource(); 1131 1132 /** 1133 * The last reported UIDs that were responsible for starting WIFI. 1134 */ 1135 private final WorkSource mLastRunningWifiUids = new WorkSource(); 1136 1137 private final IBatteryStats mBatteryStats; 1138 1139 private String mTcpBufferSizes = null; 1140 1141 // Used for debug and stats gathering 1142 private static int sScanAlarmIntentCount = 0; 1143 1144 private static final int sFrameworkMinScanIntervalSaneValue = 10000; 1145 1146 private boolean mPnoEnabled; 1147 private boolean mLazyRoamEnabled; 1148 private long mGScanStartTimeMilli; 1149 private long mGScanPeriodMilli; 1150 1151 private FrameworkFacade mFacade; 1152 1153 public WifiStateMachine(Context context, WifiTrafficPoller trafficPoller, 1154 FrameworkFacade facade, WifiMetrics wifiMetrics, 1155 UserManager userManager) { 1156 super("WifiStateMachine"); 1157 mWifiMetrics = wifiMetrics; 1158 mContext = context; 1159 mFacade = facade; 1160 mUserManager = userManager; 1161 mWifiNative = WifiNative.getWlanNativeInterface(); 1162 1163 // TODO refactor WifiNative use of context out into it's own class 1164 mWifiNative.initContext(mContext); 1165 mInterfaceName = mWifiNative.getInterfaceName(); 1166 mNetworkInfo = new NetworkInfo(ConnectivityManager.TYPE_WIFI, 0, NETWORKTYPE, ""); 1167 mBatteryStats = IBatteryStats.Stub.asInterface(mFacade.getService( 1168 BatteryStats.SERVICE_NAME)); 1169 1170 IBinder b = mFacade.getService(Context.NETWORKMANAGEMENT_SERVICE); 1171 mNwService = INetworkManagementService.Stub.asInterface(b); 1172 1173 mP2pSupported = mContext.getPackageManager().hasSystemFeature( 1174 PackageManager.FEATURE_WIFI_DIRECT); 1175 1176 mWifiConfigStore = new WifiConfigStore(context, this, mWifiNative, facade); 1177 1178 mWifiMonitor = WifiMonitor.getInstance(); 1179 1180 boolean enableFirmwareLogs = mContext.getResources().getBoolean( 1181 R.bool.config_wifi_enable_wifi_firmware_debugging); 1182 1183 if (enableFirmwareLogs) { 1184 mWifiLogger = facade.makeRealLogger(this, mWifiNative); 1185 } else { 1186 mWifiLogger = facade.makeBaseLogger(); 1187 } 1188 1189 mWifiInfo = new WifiInfo(); 1190 mWifiQualifiedNetworkSelector = new WifiQualifiedNetworkSelector(mWifiConfigStore, mContext, 1191 mWifiInfo); 1192 mSupplicantStateTracker = mFacade.makeSupplicantStateTracker( 1193 context, this, mWifiConfigStore, getHandler()); 1194 1195 mLinkProperties = new LinkProperties(); 1196 1197 IBinder s1 = mFacade.getService(Context.WIFI_P2P_SERVICE); 1198 mWifiP2pServiceImpl = (WifiP2pServiceImpl) IWifiP2pManager.Stub.asInterface(s1); 1199 1200 mNetworkInfo.setIsAvailable(false); 1201 mLastBssid = null; 1202 mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 1203 mLastSignalLevel = -1; 1204 1205 mIpManager = mFacade.makeIpManager(mContext, mInterfaceName, new IpManagerCallback()); 1206 1207 mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE); 1208 mScanIntent = getPrivateBroadcast(ACTION_START_SCAN, SCAN_REQUEST); 1209 mPnoIntent = getPrivateBroadcast(ACTION_START_PNO, PNO_START_REQUEST); 1210 1211 // Make sure the interval is not configured less than 10 seconds 1212 int period = mContext.getResources().getInteger( 1213 R.integer.config_wifi_framework_scan_interval); 1214 if (period < sFrameworkMinScanIntervalSaneValue) { 1215 period = sFrameworkMinScanIntervalSaneValue; 1216 } 1217 mDefaultFrameworkScanIntervalMs = period; 1218 1219 mNoNetworksPeriodicScan = mContext.getResources().getInteger( 1220 R.integer.config_wifi_no_network_periodic_scan_interval); 1221 1222 mBackgroundScanSupported = mContext.getResources().getBoolean( 1223 R.bool.config_wifi_background_scan_support); 1224 1225 mPrimaryDeviceType = mContext.getResources().getString( 1226 R.string.config_wifi_p2p_device_type); 1227 1228 mRevertCountryCodeOnCellularLoss = mContext.getResources().getBoolean( 1229 R.bool.config_wifi_revert_country_code_on_cellular_loss); 1230 1231 mDefaultCountryCode = SystemProperties.get(BOOT_DEFAULT_WIFI_COUNTRY_CODE); 1232 if (TextUtils.isEmpty(mDefaultCountryCode) == false) { 1233 mDefaultCountryCode = mDefaultCountryCode.toUpperCase(Locale.ROOT); 1234 } 1235 1236 if (mRevertCountryCodeOnCellularLoss && TextUtils.isEmpty(mDefaultCountryCode)) { 1237 logw("config_wifi_revert_country_code_on_cellular_loss is set, " + 1238 "but there is no default country code!! Resetting ..."); 1239 mRevertCountryCodeOnCellularLoss = false; 1240 } else if (mRevertCountryCodeOnCellularLoss) { 1241 logd("initializing with and will revert to " + mDefaultCountryCode + " on MCC loss"); 1242 } 1243 1244 if (mRevertCountryCodeOnCellularLoss) { 1245 Settings.Global.putString(mContext.getContentResolver(), 1246 Settings.Global.WIFI_COUNTRY_CODE, mDefaultCountryCode); 1247 } 1248 1249 mUserWantsSuspendOpt.set(mFacade.getIntegerSetting(mContext, 1250 Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED, 1) == 1); 1251 1252 mNetworkCapabilitiesFilter.addTransportType(NetworkCapabilities.TRANSPORT_WIFI); 1253 mNetworkCapabilitiesFilter.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET); 1254 mNetworkCapabilitiesFilter.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED); 1255 mNetworkCapabilitiesFilter.setLinkUpstreamBandwidthKbps(1024 * 1024); 1256 mNetworkCapabilitiesFilter.setLinkDownstreamBandwidthKbps(1024 * 1024); 1257 // TODO - needs to be a bit more dynamic 1258 mDfltNetworkCapabilities = new NetworkCapabilities(mNetworkCapabilitiesFilter); 1259 1260 mContext.registerReceiver( 1261 new BroadcastReceiver() { 1262 @Override 1263 public void onReceive(Context context, Intent intent) { 1264 ArrayList<String> available = intent.getStringArrayListExtra( 1265 ConnectivityManager.EXTRA_AVAILABLE_TETHER); 1266 ArrayList<String> active = intent.getStringArrayListExtra( 1267 ConnectivityManager.EXTRA_ACTIVE_TETHER); 1268 sendMessage(CMD_TETHER_STATE_CHANGE, new TetherStateChange(available, active)); 1269 } 1270 }, new IntentFilter(ConnectivityManager.ACTION_TETHER_STATE_CHANGED)); 1271 1272 mContext.registerReceiver( 1273 new BroadcastReceiver() { 1274 @Override 1275 public void onReceive(Context context, Intent intent) { 1276 sScanAlarmIntentCount++; // Used for debug only 1277 startScan(SCAN_ALARM_SOURCE, mDelayedScanCounter.incrementAndGet(), null, null); 1278 if (VDBG) 1279 logd("SCAN ALARM -> " + mDelayedScanCounter.get()); 1280 } 1281 }, 1282 new IntentFilter(ACTION_START_SCAN)); 1283 1284 mContext.registerReceiver( 1285 new BroadcastReceiver() { 1286 @Override 1287 public void onReceive(Context context, Intent intent) { 1288 sendMessage(CMD_RESTART_AUTOJOIN_OFFLOAD, 0, 1289 mRestartAutoJoinOffloadCounter, "pno alarm"); 1290 if (DBG) 1291 logd("PNO START ALARM sent"); 1292 } 1293 }, 1294 new IntentFilter(ACTION_START_PNO)); 1295 1296 1297 IntentFilter filter = new IntentFilter(); 1298 filter.addAction(Intent.ACTION_SCREEN_ON); 1299 filter.addAction(Intent.ACTION_SCREEN_OFF); 1300 mContext.registerReceiver( 1301 new BroadcastReceiver() { 1302 @Override 1303 public void onReceive(Context context, Intent intent) { 1304 String action = intent.getAction(); 1305 1306 if (action.equals(Intent.ACTION_SCREEN_ON)) { 1307 sendMessage(CMD_SCREEN_STATE_CHANGED, 1); 1308 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { 1309 sendMessage(CMD_SCREEN_STATE_CHANGED, 0); 1310 } 1311 } 1312 }, filter); 1313 1314 mContext.getContentResolver().registerContentObserver(Settings.Global.getUriFor( 1315 Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED), false, 1316 new ContentObserver(getHandler()) { 1317 @Override 1318 public void onChange(boolean selfChange) { 1319 mUserWantsSuspendOpt.set(mFacade.getIntegerSetting(mContext, 1320 Settings.Global.WIFI_SUSPEND_OPTIMIZATIONS_ENABLED, 1) == 1); 1321 } 1322 }); 1323 1324 mContext.registerReceiver( 1325 new BroadcastReceiver() { 1326 @Override 1327 public void onReceive(Context context, Intent intent) { 1328 sendMessage(CMD_BOOT_COMPLETED); 1329 } 1330 }, 1331 new IntentFilter(Intent.ACTION_BOOT_COMPLETED)); 1332 1333 mScanResultCache = new LruCache<>(SCAN_RESULT_CACHE_SIZE); 1334 1335 PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); 1336 mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getName()); 1337 1338 mSuspendWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "WifiSuspend"); 1339 mSuspendWakeLock.setReferenceCounted(false); 1340 1341 mTcpBufferSizes = mContext.getResources().getString( 1342 com.android.internal.R.string.config_wifi_tcp_buffers); 1343 1344 addState(mDefaultState); 1345 addState(mInitialState, mDefaultState); 1346 addState(mSupplicantStartingState, mDefaultState); 1347 addState(mSupplicantStartedState, mDefaultState); 1348 addState(mDriverStartingState, mSupplicantStartedState); 1349 addState(mDriverStartedState, mSupplicantStartedState); 1350 addState(mScanModeState, mDriverStartedState); 1351 addState(mConnectModeState, mDriverStartedState); 1352 addState(mL2ConnectedState, mConnectModeState); 1353 addState(mObtainingIpState, mL2ConnectedState); 1354 addState(mConnectedState, mL2ConnectedState); 1355 addState(mRoamingState, mL2ConnectedState); 1356 addState(mDisconnectingState, mConnectModeState); 1357 addState(mDisconnectedState, mConnectModeState); 1358 addState(mWpsRunningState, mConnectModeState); 1359 addState(mWaitForP2pDisableState, mSupplicantStartedState); 1360 addState(mDriverStoppingState, mSupplicantStartedState); 1361 addState(mDriverStoppedState, mSupplicantStartedState); 1362 addState(mSupplicantStoppingState, mDefaultState); 1363 addState(mSoftApStartingState, mDefaultState); 1364 addState(mSoftApStartedState, mDefaultState); 1365 addState(mTetheringState, mSoftApStartedState); 1366 addState(mTetheredState, mSoftApStartedState); 1367 addState(mUntetheringState, mSoftApStartedState); 1368 1369 setInitialState(mInitialState); 1370 1371 setLogRecSize(ActivityManager.isLowRamDeviceStatic() ? 100 : 3000); 1372 setLogOnlyTransitions(false); 1373 if (VDBG) setDbg(true); 1374 1375 //start the state machine 1376 start(); 1377 1378 mWifiMonitor.registerHandler(mInterfaceName, CMD_TARGET_BSSID, getHandler()); 1379 mWifiMonitor.registerHandler(mInterfaceName, CMD_ASSOCIATED_BSSID, getHandler()); 1380 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.ANQP_DONE_EVENT, getHandler()); 1381 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.ASSOCIATION_REJECTION_EVENT, 1382 getHandler()); 1383 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.AUTHENTICATION_FAILURE_EVENT, 1384 getHandler()); 1385 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.DRIVER_HUNG_EVENT, getHandler()); 1386 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.GAS_QUERY_DONE_EVENT, getHandler()); 1387 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.GAS_QUERY_START_EVENT, 1388 getHandler()); 1389 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.HS20_REMEDIATION_EVENT, 1390 getHandler()); 1391 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.NETWORK_CONNECTION_EVENT, 1392 getHandler()); 1393 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.NETWORK_DISCONNECTION_EVENT, 1394 getHandler()); 1395 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.RX_HS20_ANQP_ICON_EVENT, 1396 getHandler()); 1397 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SCAN_FAILED_EVENT, getHandler()); 1398 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SCAN_RESULTS_EVENT, getHandler()); 1399 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SSID_REENABLED, getHandler()); 1400 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SSID_TEMP_DISABLED, getHandler()); 1401 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_CONNECTION_EVENT, getHandler()); 1402 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_DISCONNECTION_EVENT, 1403 getHandler()); 1404 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 1405 getHandler()); 1406 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_REQUEST_IDENTITY, getHandler()); 1407 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.SUP_REQUEST_SIM_AUTH, getHandler()); 1408 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_FAIL_EVENT, getHandler()); 1409 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_OVERLAP_EVENT, getHandler()); 1410 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_SUCCESS_EVENT, getHandler()); 1411 mWifiMonitor.registerHandler(mInterfaceName, WifiMonitor.WPS_TIMEOUT_EVENT, getHandler()); 1412 1413 final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE); 1414 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1415 intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED); 1416 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 1417 } 1418 1419 class IpManagerCallback extends IpManager.Callback { 1420 @Override 1421 public boolean usingIpReachabilityMonitor() { 1422 return true; 1423 } 1424 1425 @Override 1426 public void onPreDhcpAction() { 1427 sendMessage(DhcpStateMachine.CMD_PRE_DHCP_ACTION); 1428 } 1429 1430 @Override 1431 public void onPostDhcpAction() { 1432 sendMessage(DhcpStateMachine.CMD_POST_DHCP_ACTION); 1433 } 1434 1435 @Override 1436 public void onNewDhcpResults(DhcpResults dhcpResults) { 1437 if (dhcpResults != null) { 1438 sendMessage(CMD_IPV4_PROVISIONING_SUCCESS, dhcpResults); 1439 } else { 1440 sendMessage(CMD_IPV4_PROVISIONING_FAILURE); 1441 } 1442 } 1443 1444 @Override 1445 public void onProvisioningSuccess(LinkProperties newLp) { 1446 sendMessage(CMD_UPDATE_LINKPROPERTIES, newLp); 1447 sendMessage(CMD_IP_CONFIGURATION_SUCCESSFUL); 1448 } 1449 1450 @Override 1451 public void onProvisioningFailure(LinkProperties newLp) { 1452 sendMessage(CMD_IP_CONFIGURATION_LOST); 1453 } 1454 1455 @Override 1456 public void onLinkPropertiesChange(LinkProperties newLp) { 1457 sendMessage(CMD_UPDATE_LINKPROPERTIES, newLp); 1458 } 1459 1460 @Override 1461 public void onReachabilityLost(String logMsg) { 1462 sendMessage(CMD_IP_REACHABILITY_LOST, logMsg); 1463 } 1464 } 1465 1466 private void stopIpManager() { 1467 /* Restore power save and suspend optimizations */ 1468 handlePostDhcpSetup(); 1469 mIpManager.stop(); 1470 } 1471 1472 PendingIntent getPrivateBroadcast(String action, int requestCode) { 1473 Intent intent = new Intent(action, null); 1474 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1475 intent.setPackage("android"); 1476 return mFacade.getBroadcast(mContext, requestCode, intent, 0); 1477 } 1478 1479 private int mVerboseLoggingLevel = 0; 1480 1481 int getVerboseLoggingLevel() { 1482 return mVerboseLoggingLevel; 1483 } 1484 1485 void enableVerboseLogging(int verbose) { 1486 mVerboseLoggingLevel = verbose; 1487 if (verbose > 0) { 1488 DBG = true; 1489 VDBG = true; 1490 PDBG = true; 1491 mLogMessages = true; 1492 mWifiNative.setSupplicantLogLevel("DEBUG"); 1493 } else { 1494 DBG = false; 1495 VDBG = false; 1496 PDBG = false; 1497 mLogMessages = false; 1498 mWifiNative.setSupplicantLogLevel("INFO"); 1499 } 1500 mWifiLogger.startLogging(mVerboseLoggingLevel > 0); 1501 mWifiMonitor.enableVerboseLogging(verbose); 1502 mWifiNative.enableVerboseLogging(verbose); 1503 mWifiConfigStore.enableVerboseLogging(verbose); 1504 mSupplicantStateTracker.enableVerboseLogging(verbose); 1505 mWifiQualifiedNetworkSelector.enableVerboseLogging(verbose); 1506 } 1507 1508 public void setHalBasedAutojoinOffload(int enabled) { 1509 // Shoult be used for debug only, triggered form developper settings 1510 // enabling HAl based PNO dynamically is not safe and not a normal operation 1511 mHalBasedPnoEnableInDevSettings = enabled > 0; 1512 mWifiConfigStore.enableHalBasedPno.set(mHalBasedPnoEnableInDevSettings); 1513 mWifiConfigStore.enableSsidWhitelist.set(mHalBasedPnoEnableInDevSettings); 1514 sendMessage(CMD_DISCONNECT); 1515 } 1516 1517 int getHalBasedAutojoinOffload() { 1518 return mHalBasedPnoEnableInDevSettings ? 1 : 0; 1519 } 1520 1521 boolean useHalBasedAutoJoinOffload() { 1522 // all three settings need to be true: 1523 // - developper settings switch 1524 // - driver support 1525 // - config option 1526 return mHalBasedPnoEnableInDevSettings 1527 && mHalBasedPnoDriverSupported 1528 && mWifiConfigStore.enableHalBasedPno.get(); 1529 } 1530 1531 boolean allowFullBandScanAndAssociated() { 1532 1533 if (!getEnableAutoJoinWhenAssociated()) { 1534 if (DBG) { 1535 Log.e(TAG, "allowFullBandScanAndAssociated: " 1536 + " enableAutoJoinWhenAssociated : disallow"); 1537 } 1538 return false; 1539 } 1540 1541 if (mWifiInfo.txSuccessRate > 1542 mWifiConfigStore.maxTxPacketForFullScans 1543 || mWifiInfo.rxSuccessRate > 1544 mWifiConfigStore.maxRxPacketForFullScans) { 1545 if (DBG) { 1546 Log.e(TAG, "allowFullBandScanAndAssociated: packet rate tx" 1547 + mWifiInfo.txSuccessRate + " rx " 1548 + mWifiInfo.rxSuccessRate 1549 + " allow scan with traffic " + getAllowScansWithTraffic()); 1550 } 1551 // Too much traffic at the interface, hence no full band scan 1552 if (getAllowScansWithTraffic() == 0) { 1553 return false; 1554 } 1555 } 1556 1557 if (getCurrentState() != mConnectedState) { 1558 if (DBG) { 1559 Log.e(TAG, "allowFullBandScanAndAssociated: getCurrentState() : disallow"); 1560 } 1561 return false; 1562 } 1563 1564 return true; 1565 } 1566 1567 long mLastScanPermissionUpdate = 0; 1568 boolean mConnectedModeGScanOffloadStarted = false; 1569 // Don't do a G-scan enable/re-enable cycle more than once within 20seconds 1570 // The function updateAssociatedScanPermission() can be called quite frequently, hence 1571 // we want to throttle the GScan Stop->Start transition 1572 static final long SCAN_PERMISSION_UPDATE_THROTTLE_MILLI = 20000; 1573 void updateAssociatedScanPermission() { 1574 1575 if (useHalBasedAutoJoinOffload()) { 1576 boolean allowed = allowFullBandScanAndAssociated(); 1577 1578 long now = System.currentTimeMillis(); 1579 if (mConnectedModeGScanOffloadStarted && !allowed) { 1580 if (DBG) { 1581 Log.e(TAG, " useHalBasedAutoJoinOffload stop offload"); 1582 } 1583 stopPnoOffload(); 1584 stopGScan(" useHalBasedAutoJoinOffload"); 1585 } 1586 if (!mConnectedModeGScanOffloadStarted && allowed) { 1587 if ((now - mLastScanPermissionUpdate) > SCAN_PERMISSION_UPDATE_THROTTLE_MILLI) { 1588 // Re-enable Gscan offload, this will trigger periodic scans and allow firmware 1589 // to look for 5GHz BSSIDs and better networks 1590 if (DBG) { 1591 Log.e(TAG, " useHalBasedAutoJoinOffload restart offload"); 1592 } 1593 startGScanConnectedModeOffload("updatePermission " 1594 + (now - mLastScanPermissionUpdate) + "ms"); 1595 mLastScanPermissionUpdate = now; 1596 } 1597 } 1598 } 1599 } 1600 1601 private int mAggressiveHandover = 0; 1602 1603 int getAggressiveHandover() { 1604 return mAggressiveHandover; 1605 } 1606 1607 void enableAggressiveHandover(int enabled) { 1608 mAggressiveHandover = enabled; 1609 } 1610 1611 public void clearANQPCache() { 1612 mWifiConfigStore.trimANQPCache(true); 1613 } 1614 1615 public void setAllowScansWithTraffic(int enabled) { 1616 mWifiConfigStore.alwaysEnableScansWhileAssociated.set(enabled); 1617 } 1618 1619 public int getAllowScansWithTraffic() { 1620 return mWifiConfigStore.alwaysEnableScansWhileAssociated.get(); 1621 } 1622 1623 public boolean enableAutoJoinWhenAssociated(boolean enabled) { 1624 boolean old_state = getEnableAutoJoinWhenAssociated(); 1625 mWifiConfigStore.enableAutoJoinWhenAssociated.set(enabled); 1626 if (!old_state && enabled && mScreenOn && getCurrentState() == mConnectedState) { 1627 startDelayedScan(mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(), null, 1628 null); 1629 } 1630 return true; 1631 } 1632 1633 public boolean getEnableAutoJoinWhenAssociated() { 1634 return mWifiConfigStore.enableAutoJoinWhenAssociated.get(); 1635 } 1636 /* 1637 * 1638 * Framework scan control 1639 */ 1640 1641 private boolean mAlarmEnabled = false; 1642 1643 private AtomicInteger mDelayedScanCounter = new AtomicInteger(); 1644 1645 private void setScanAlarm(boolean enabled) { 1646 if (PDBG) { 1647 String state; 1648 if (enabled) state = "enabled"; else state = "disabled"; 1649 logd("setScanAlarm " + state 1650 + " defaultperiod " + mDefaultFrameworkScanIntervalMs 1651 + " mBackgroundScanSupported " + mBackgroundScanSupported); 1652 } 1653 if (mBackgroundScanSupported == false) { 1654 // Scan alarm is only used for background scans if they are not 1655 // offloaded to the wifi chipset, hence enable the scan alarm 1656 // gicing us RTC_WAKEUP of backgroundScan is NOT supported 1657 enabled = true; 1658 } 1659 1660 if (enabled == mAlarmEnabled) return; 1661 if (enabled) { 1662 /* Set RTC_WAKEUP alarms if PNO is not supported - because no one is */ 1663 /* going to wake up the host processor to look for access points */ 1664 mAlarmManager.set(AlarmManager.RTC_WAKEUP, 1665 System.currentTimeMillis() + mDefaultFrameworkScanIntervalMs, 1666 mScanIntent); 1667 mAlarmEnabled = true; 1668 } else { 1669 mAlarmManager.cancel(mScanIntent); 1670 mAlarmEnabled = false; 1671 } 1672 } 1673 1674 private void cancelDelayedScan() { 1675 mDelayedScanCounter.incrementAndGet(); 1676 } 1677 1678 private boolean checkAndRestartDelayedScan(int counter, boolean restart, int milli, 1679 ScanSettings settings, WorkSource workSource) { 1680 1681 if (counter != mDelayedScanCounter.get()) { 1682 return false; 1683 } 1684 if (restart) 1685 startDelayedScan(milli, settings, workSource); 1686 return true; 1687 } 1688 1689 private void startDelayedScan(int milli, ScanSettings settings, WorkSource workSource) { 1690 if (milli <= 0) return; 1691 /** 1692 * The cases where the scan alarm should be run are : 1693 * - DisconnectedState && screenOn => used delayed timer 1694 * - DisconnectedState && !screenOn && mBackgroundScanSupported => PNO 1695 * - DisconnectedState && !screenOn && !mBackgroundScanSupported => used RTC_WAKEUP Alarm 1696 * - ConnectedState && screenOn => used delayed timer 1697 */ 1698 1699 mDelayedScanCounter.incrementAndGet(); 1700 if (mScreenOn && 1701 (getCurrentState() == mDisconnectedState 1702 || getCurrentState() == mConnectedState)) { 1703 Bundle bundle = new Bundle(); 1704 bundle.putParcelable(CUSTOMIZED_SCAN_SETTING, settings); 1705 bundle.putParcelable(CUSTOMIZED_SCAN_WORKSOURCE, workSource); 1706 bundle.putLong(SCAN_REQUEST_TIME, System.currentTimeMillis()); 1707 sendMessageDelayed(CMD_START_SCAN, SCAN_ALARM_SOURCE, 1708 mDelayedScanCounter.get(), bundle, milli); 1709 if (DBG) logd("startDelayedScan send -> " + mDelayedScanCounter + " milli " + milli); 1710 } else if (mBackgroundScanSupported == false 1711 && !mScreenOn && getCurrentState() == mDisconnectedState) { 1712 setScanAlarm(true); 1713 if (DBG) logd("startDelayedScan start scan alarm -> " 1714 + mDelayedScanCounter + " milli " + milli); 1715 } else { 1716 if (DBG) logd("startDelayedScan unhandled -> " 1717 + mDelayedScanCounter + " milli " + milli); 1718 } 1719 } 1720 1721 private boolean setRandomMacOui() { 1722 String oui = mContext.getResources().getString(R.string.config_wifi_random_mac_oui); 1723 if (TextUtils.isEmpty(oui)) { 1724 oui = GOOGLE_OUI; 1725 } 1726 String[] ouiParts = oui.split("-"); 1727 byte[] ouiBytes = new byte[3]; 1728 ouiBytes[0] = (byte) (Integer.parseInt(ouiParts[0], 16) & 0xFF); 1729 ouiBytes[1] = (byte) (Integer.parseInt(ouiParts[1], 16) & 0xFF); 1730 ouiBytes[2] = (byte) (Integer.parseInt(ouiParts[2], 16) & 0xFF); 1731 1732 logd("Setting OUI to " + oui); 1733 return mWifiNative.setScanningMacOui(ouiBytes); 1734 } 1735 1736 /** 1737 * ****************************************************** 1738 * Methods exposed for public use 1739 * ****************************************************** 1740 */ 1741 1742 public Messenger getMessenger() { 1743 return new Messenger(getHandler()); 1744 } 1745 1746 /** 1747 * TODO: doc 1748 */ 1749 public boolean syncPingSupplicant(AsyncChannel channel) { 1750 Message resultMsg = channel.sendMessageSynchronously(CMD_PING_SUPPLICANT); 1751 boolean result = (resultMsg.arg1 != FAILURE); 1752 resultMsg.recycle(); 1753 return result; 1754 } 1755 1756 /** 1757 * When settings allowing making use of untrusted networks change, trigger a scan 1758 * so as to kick of autojoin. 1759 */ 1760 public void startScanForUntrustedSettingChange() { 1761 startScan(SET_ALLOW_UNTRUSTED_SOURCE, 0, null, null); 1762 } 1763 1764 /** 1765 * Initiate a wifi scan. If workSource is not null, blame is given to it, otherwise blame is 1766 * given to callingUid. 1767 * 1768 * @param callingUid The uid initiating the wifi scan. Blame will be given here unless 1769 * workSource is specified. 1770 * @param workSource If not null, blame is given to workSource. 1771 * @param settings Scan settings, see {@link ScanSettings}. 1772 */ 1773 public void startScan(int callingUid, int scanCounter, 1774 ScanSettings settings, WorkSource workSource) { 1775 Bundle bundle = new Bundle(); 1776 bundle.putParcelable(CUSTOMIZED_SCAN_SETTING, settings); 1777 bundle.putParcelable(CUSTOMIZED_SCAN_WORKSOURCE, workSource); 1778 bundle.putLong(SCAN_REQUEST_TIME, System.currentTimeMillis()); 1779 sendMessage(CMD_START_SCAN, callingUid, scanCounter, bundle); 1780 } 1781 1782 // called from BroadcastListener 1783 1784 /** 1785 * Start reading new scan data 1786 * Data comes in as: 1787 * "scancount=5\n" 1788 * "nextcount=5\n" 1789 * "apcount=3\n" 1790 * "trunc\n" (optional) 1791 * "bssid=...\n" 1792 * "ssid=...\n" 1793 * "freq=...\n" (in Mhz) 1794 * "level=...\n" 1795 * "dist=...\n" (in cm) 1796 * "distsd=...\n" (standard deviation, in cm) 1797 * "====" 1798 * "bssid=...\n" 1799 * etc 1800 * "====" 1801 * "bssid=...\n" 1802 * etc 1803 * "%%%%" 1804 * "apcount=2\n" 1805 * "bssid=...\n" 1806 * etc 1807 * "%%%% 1808 * etc 1809 * "----" 1810 */ 1811 private final static boolean DEBUG_PARSE = false; 1812 1813 private long mDisconnectedTimeStamp = 0; 1814 1815 public long getDisconnectedTimeMilli() { 1816 if (getCurrentState() == mDisconnectedState 1817 && mDisconnectedTimeStamp != 0) { 1818 long now_ms = System.currentTimeMillis(); 1819 return now_ms - mDisconnectedTimeStamp; 1820 } 1821 return 0; 1822 } 1823 1824 // Keeping track of scan requests 1825 private long lastStartScanTimeStamp = 0; 1826 private long lastScanDuration = 0; 1827 // Last connect attempt is used to prevent scan requests: 1828 // - for a period of 10 seconds after attempting to connect 1829 private long lastConnectAttemptTimestamp = 0; 1830 private Set<Integer> lastScanFreqs = null; 1831 1832 // For debugging, keep track of last message status handling 1833 // TODO, find an equivalent mechanism as part of parent class 1834 private static int MESSAGE_HANDLING_STATUS_PROCESSED = 2; 1835 private static int MESSAGE_HANDLING_STATUS_OK = 1; 1836 private static int MESSAGE_HANDLING_STATUS_UNKNOWN = 0; 1837 private static int MESSAGE_HANDLING_STATUS_REFUSED = -1; 1838 private static int MESSAGE_HANDLING_STATUS_FAIL = -2; 1839 private static int MESSAGE_HANDLING_STATUS_OBSOLETE = -3; 1840 private static int MESSAGE_HANDLING_STATUS_DEFERRED = -4; 1841 private static int MESSAGE_HANDLING_STATUS_DISCARD = -5; 1842 private static int MESSAGE_HANDLING_STATUS_LOOPED = -6; 1843 private static int MESSAGE_HANDLING_STATUS_HANDLING_ERROR = -7; 1844 1845 private int messageHandlingStatus = 0; 1846 1847 //TODO: this is used only to track connection attempts, however the link state and packet per 1848 //TODO: second logic should be folded into that 1849 private boolean checkOrDeferScanAllowed(Message msg) { 1850 long now = System.currentTimeMillis(); 1851 if (lastConnectAttemptTimestamp != 0 && (now - lastConnectAttemptTimestamp) < 10000) { 1852 Message dmsg = Message.obtain(msg); 1853 sendMessageDelayed(dmsg, 11000 - (now - lastConnectAttemptTimestamp)); 1854 return false; 1855 } 1856 return true; 1857 } 1858 1859 private int mOnTime = 0; 1860 private int mTxTime = 0; 1861 private int mRxTime = 0; 1862 private int mOnTimeStartScan = 0; 1863 private int mTxTimeStartScan = 0; 1864 private int mRxTimeStartScan = 0; 1865 private int mOnTimeScan = 0; 1866 private int mTxTimeScan = 0; 1867 private int mRxTimeScan = 0; 1868 private int mOnTimeThisScan = 0; 1869 private int mTxTimeThisScan = 0; 1870 private int mRxTimeThisScan = 0; 1871 1872 private int mOnTimeScreenStateChange = 0; 1873 private int mOnTimeAtLastReport = 0; 1874 private long lastOntimeReportTimeStamp = 0; 1875 private long lastScreenStateChangeTimeStamp = 0; 1876 private int mOnTimeLastReport = 0; 1877 private int mTxTimeLastReport = 0; 1878 private int mRxTimeLastReport = 0; 1879 1880 private long lastLinkLayerStatsUpdate = 0; 1881 1882 String reportOnTime() { 1883 long now = System.currentTimeMillis(); 1884 StringBuilder sb = new StringBuilder(); 1885 // Report stats since last report 1886 int on = mOnTime - mOnTimeLastReport; 1887 mOnTimeLastReport = mOnTime; 1888 int tx = mTxTime - mTxTimeLastReport; 1889 mTxTimeLastReport = mTxTime; 1890 int rx = mRxTime - mRxTimeLastReport; 1891 mRxTimeLastReport = mRxTime; 1892 int period = (int) (now - lastOntimeReportTimeStamp); 1893 lastOntimeReportTimeStamp = now; 1894 sb.append(String.format("[on:%d tx:%d rx:%d period:%d]", on, tx, rx, period)); 1895 // Report stats since Screen State Changed 1896 on = mOnTime - mOnTimeScreenStateChange; 1897 period = (int) (now - lastScreenStateChangeTimeStamp); 1898 sb.append(String.format(" from screen [on:%d period:%d]", on, period)); 1899 return sb.toString(); 1900 } 1901 1902 WifiLinkLayerStats getWifiLinkLayerStats(boolean dbg) { 1903 WifiLinkLayerStats stats = null; 1904 if (mWifiLinkLayerStatsSupported > 0) { 1905 String name = "wlan0"; 1906 stats = mWifiNative.getWifiLinkLayerStats(name); 1907 if (name != null && stats == null && mWifiLinkLayerStatsSupported > 0) { 1908 mWifiLinkLayerStatsSupported -= 1; 1909 } else if (stats != null) { 1910 lastLinkLayerStatsUpdate = System.currentTimeMillis(); 1911 mOnTime = stats.on_time; 1912 mTxTime = stats.tx_time; 1913 mRxTime = stats.rx_time; 1914 mRunningBeaconCount = stats.beacon_rx; 1915 } 1916 } 1917 if (stats == null || mWifiLinkLayerStatsSupported <= 0) { 1918 long mTxPkts = mFacade.getTxPackets(mInterfaceName); 1919 long mRxPkts = mFacade.getRxPackets(mInterfaceName); 1920 mWifiInfo.updatePacketRates(mTxPkts, mRxPkts); 1921 } else { 1922 mWifiInfo.updatePacketRates(stats); 1923 } 1924 if (useHalBasedAutoJoinOffload()) { 1925 sendMessage(CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION); 1926 } 1927 return stats; 1928 } 1929 1930 void startRadioScanStats() { 1931 WifiLinkLayerStats stats = getWifiLinkLayerStats(false); 1932 if (stats != null) { 1933 mOnTimeStartScan = stats.on_time; 1934 mTxTimeStartScan = stats.tx_time; 1935 mRxTimeStartScan = stats.rx_time; 1936 mOnTime = stats.on_time; 1937 mTxTime = stats.tx_time; 1938 mRxTime = stats.rx_time; 1939 } 1940 } 1941 1942 void closeRadioScanStats() { 1943 WifiLinkLayerStats stats = getWifiLinkLayerStats(false); 1944 if (stats != null) { 1945 mOnTimeThisScan = stats.on_time - mOnTimeStartScan; 1946 mTxTimeThisScan = stats.tx_time - mTxTimeStartScan; 1947 mRxTimeThisScan = stats.rx_time - mRxTimeStartScan; 1948 mOnTimeScan += mOnTimeThisScan; 1949 mTxTimeScan += mTxTimeThisScan; 1950 mRxTimeScan += mRxTimeThisScan; 1951 } 1952 } 1953 1954 int startWifiIPPacketOffload(int slot, KeepalivePacketData packetData, int intervalSeconds) { 1955 int ret = mWifiNative.startSendingOffloadedPacket(slot, packetData, intervalSeconds * 1000); 1956 if (ret != 0) { 1957 loge("startWifiIPPacketOffload(" + slot + ", " + intervalSeconds + 1958 "): hardware error " + ret); 1959 return ConnectivityManager.PacketKeepalive.ERROR_HARDWARE_ERROR; 1960 } else { 1961 return ConnectivityManager.PacketKeepalive.SUCCESS; 1962 } 1963 } 1964 1965 int stopWifiIPPacketOffload(int slot) { 1966 int ret = mWifiNative.stopSendingOffloadedPacket(slot); 1967 if (ret != 0) { 1968 loge("stopWifiIPPacketOffload(" + slot + "): hardware error " + ret); 1969 return ConnectivityManager.PacketKeepalive.ERROR_HARDWARE_ERROR; 1970 } else { 1971 return ConnectivityManager.PacketKeepalive.SUCCESS; 1972 } 1973 } 1974 1975 int startRssiMonitoringOffload(byte maxRssi, byte minRssi) { 1976 return mWifiNative.startRssiMonitoring(maxRssi, minRssi, WifiStateMachine.this); 1977 } 1978 1979 int stopRssiMonitoringOffload() { 1980 return mWifiNative.stopRssiMonitoring(); 1981 } 1982 1983 // If workSource is not null, blame is given to it, otherwise blame is given to callingUid. 1984 private void noteScanStart(int callingUid, WorkSource workSource) { 1985 if (lastStartScanTimeStamp != 0) { 1986 noteScanEnd(); 1987 } 1988 long now = System.currentTimeMillis(); 1989 lastStartScanTimeStamp = now; 1990 lastScanDuration = 0; 1991 if (DBG) { 1992 String ts = String.format("[%,d ms]", now); 1993 if (workSource != null) { 1994 if (DBG) logd(ts + " noteScanStart" + workSource.toString() 1995 + " uid " + Integer.toString(callingUid)); 1996 } else { 1997 if (DBG) logd(ts + " noteScanstart no scan source" 1998 + " uid " + Integer.toString(callingUid)); 1999 } 2000 } 2001 startRadioScanStats(); 2002 if (mScanWorkSource == null && ((callingUid != UNKNOWN_SCAN_SOURCE 2003 && callingUid != SCAN_ALARM_SOURCE) 2004 || workSource != null)) { 2005 mScanWorkSource = workSource != null ? workSource : new WorkSource(callingUid); 2006 2007 if (mScanWorkSource.size() == 1 && mScanWorkSource.get(0) < 0) { 2008 // WiFi uses negative UIDs to mean special things. BatteryStats don't care! 2009 mScanWorkSource = new WorkSource(Process.WIFI_UID); 2010 } 2011 2012 try { 2013 mBatteryStats.noteWifiScanStartedFromSource(mScanWorkSource); 2014 } catch (RemoteException e) { 2015 log(e.toString()); 2016 } 2017 } 2018 } 2019 2020 private void noteScanEnd() { 2021 closeRadioScanStats(); 2022 long now = System.currentTimeMillis(); 2023 if (lastStartScanTimeStamp != 0) { 2024 lastScanDuration = now - lastStartScanTimeStamp; 2025 } 2026 lastStartScanTimeStamp = 0; 2027 if (DBG) { 2028 String ts = String.format("[%,d ms]", now); 2029 if (mScanWorkSource != null) 2030 logd(ts + " noteScanEnd " + mScanWorkSource.toString() 2031 + " onTime=" + mOnTimeThisScan); 2032 else 2033 logd(ts + " noteScanEnd no scan source" 2034 + " onTime=" + mOnTimeThisScan); 2035 } 2036 if (mScanWorkSource != null) { 2037 try { 2038 mBatteryStats.noteWifiScanStoppedFromSource(mScanWorkSource); 2039 } catch (RemoteException e) { 2040 log(e.toString()); 2041 } finally { 2042 mScanWorkSource = null; 2043 } 2044 } 2045 } 2046 2047 private void handleScanRequest(Message message) { 2048 ScanSettings settings = null; 2049 WorkSource workSource = null; 2050 2051 // unbundle parameters 2052 Bundle bundle = (Bundle) message.obj; 2053 2054 if (bundle != null) { 2055 settings = bundle.getParcelable(CUSTOMIZED_SCAN_SETTING); 2056 workSource = bundle.getParcelable(CUSTOMIZED_SCAN_WORKSOURCE); 2057 } 2058 2059 Set<Integer> freqs = null; 2060 if (settings != null && settings.channelSet != null) { 2061 freqs = new HashSet<Integer>(); 2062 for (WifiChannel channel : settings.channelSet) { 2063 freqs.add(channel.freqMHz); 2064 } 2065 } 2066 2067 // call wifi native to start the scan 2068 if (startScanNative(freqs)) { 2069 // only count battery consumption if scan request is accepted 2070 noteScanStart(message.arg1, workSource); 2071 // a full scan covers everything, clearing scan request buffer 2072 if (freqs == null) 2073 mBufferedScanMsg.clear(); 2074 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK; 2075 if (workSource != null) { 2076 // External worksource was passed along the scan request, 2077 // hence always send a broadcast 2078 mSendScanResultsBroadcast = true; 2079 } 2080 return; 2081 } 2082 2083 // if reach here, scan request is rejected 2084 2085 if (!mIsScanOngoing) { 2086 // if rejection is NOT due to ongoing scan (e.g. bad scan parameters), 2087 2088 // discard this request and pop up the next one 2089 if (mBufferedScanMsg.size() > 0) { 2090 sendMessage(mBufferedScanMsg.remove()); 2091 } 2092 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 2093 } else if (!mIsFullScanOngoing) { 2094 // if rejection is due to an ongoing scan, and the ongoing one is NOT a full scan, 2095 // buffer the scan request to make sure specified channels will be scanned eventually 2096 if (freqs == null) 2097 mBufferedScanMsg.clear(); 2098 if (mBufferedScanMsg.size() < SCAN_REQUEST_BUFFER_MAX_SIZE) { 2099 Message msg = obtainMessage(CMD_START_SCAN, 2100 message.arg1, message.arg2, bundle); 2101 mBufferedScanMsg.add(msg); 2102 } else { 2103 // if too many requests in buffer, combine them into a single full scan 2104 bundle = new Bundle(); 2105 bundle.putParcelable(CUSTOMIZED_SCAN_SETTING, null); 2106 bundle.putParcelable(CUSTOMIZED_SCAN_WORKSOURCE, workSource); 2107 Message msg = obtainMessage(CMD_START_SCAN, message.arg1, message.arg2, bundle); 2108 mBufferedScanMsg.clear(); 2109 mBufferedScanMsg.add(msg); 2110 } 2111 messageHandlingStatus = MESSAGE_HANDLING_STATUS_LOOPED; 2112 } else { 2113 // mIsScanOngoing and mIsFullScanOngoing 2114 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 2115 } 2116 } 2117 2118 2119 /** 2120 * return true iff scan request is accepted 2121 */ 2122 private boolean startScanNative(Set<Integer> freqs) { 2123 if (mWifiNative.scan(freqs)) { 2124 mIsScanOngoing = true; 2125 mIsFullScanOngoing = (freqs == null); 2126 lastScanFreqs = freqs; 2127 return true; 2128 } 2129 return false; 2130 } 2131 2132 /** 2133 * TODO: doc 2134 */ 2135 public void setSupplicantRunning(boolean enable) { 2136 if (enable) { 2137 sendMessage(CMD_START_SUPPLICANT); 2138 } else { 2139 sendMessage(CMD_STOP_SUPPLICANT); 2140 } 2141 } 2142 2143 /** 2144 * TODO: doc 2145 */ 2146 public void setHostApRunning(WifiConfiguration wifiConfig, boolean enable) { 2147 if (enable) { 2148 sendMessage(CMD_START_AP, wifiConfig); 2149 } else { 2150 sendMessage(CMD_STOP_AP); 2151 } 2152 } 2153 2154 public void setWifiApConfiguration(WifiConfiguration config) { 2155 mWifiApConfigStore.setApConfiguration(config); 2156 } 2157 2158 public WifiConfiguration syncGetWifiApConfiguration() { 2159 return mWifiApConfigStore.getApConfiguration(); 2160 } 2161 2162 /** 2163 * TODO: doc 2164 */ 2165 public int syncGetWifiState() { 2166 return mWifiState.get(); 2167 } 2168 2169 /** 2170 * TODO: doc 2171 */ 2172 public String syncGetWifiStateByName() { 2173 switch (mWifiState.get()) { 2174 case WIFI_STATE_DISABLING: 2175 return "disabling"; 2176 case WIFI_STATE_DISABLED: 2177 return "disabled"; 2178 case WIFI_STATE_ENABLING: 2179 return "enabling"; 2180 case WIFI_STATE_ENABLED: 2181 return "enabled"; 2182 case WIFI_STATE_UNKNOWN: 2183 return "unknown state"; 2184 default: 2185 return "[invalid state]"; 2186 } 2187 } 2188 2189 /** 2190 * TODO: doc 2191 */ 2192 public int syncGetWifiApState() { 2193 return mWifiApState.get(); 2194 } 2195 2196 /** 2197 * TODO: doc 2198 */ 2199 public String syncGetWifiApStateByName() { 2200 switch (mWifiApState.get()) { 2201 case WIFI_AP_STATE_DISABLING: 2202 return "disabling"; 2203 case WIFI_AP_STATE_DISABLED: 2204 return "disabled"; 2205 case WIFI_AP_STATE_ENABLING: 2206 return "enabling"; 2207 case WIFI_AP_STATE_ENABLED: 2208 return "enabled"; 2209 case WIFI_AP_STATE_FAILED: 2210 return "failed"; 2211 default: 2212 return "[invalid state]"; 2213 } 2214 } 2215 2216 public boolean isConnected() { 2217 return getCurrentState() == mConnectedState; 2218 } 2219 2220 public boolean isDisconnected() { 2221 return getCurrentState() == mDisconnectedState; 2222 } 2223 2224 public boolean isSupplicantTransientState() { 2225 SupplicantState SupplicantState = mWifiInfo.getSupplicantState(); 2226 if (SupplicantState == SupplicantState.ASSOCIATING 2227 || SupplicantState == SupplicantState.AUTHENTICATING 2228 || SupplicantState == SupplicantState.FOUR_WAY_HANDSHAKE 2229 || SupplicantState == SupplicantState.GROUP_HANDSHAKE) { 2230 2231 if (DBG) { 2232 Log.d(TAG, "Supplicant is under transient state: " + SupplicantState); 2233 } 2234 return true; 2235 } else { 2236 if (DBG) { 2237 Log.d(TAG, "Supplicant is under steady state: " + SupplicantState); 2238 } 2239 } 2240 2241 return false; 2242 } 2243 2244 /** 2245 * Get status information for the current connection, if any. 2246 * 2247 * @return a {@link WifiInfo} object containing information about the current connection 2248 */ 2249 public WifiInfo syncRequestConnectionInfo() { 2250 return getWiFiInfoForUid(Binder.getCallingUid()); 2251 } 2252 2253 public WifiInfo getWifiInfo() { 2254 return mWifiInfo; 2255 } 2256 2257 public DhcpResults syncGetDhcpResults() { 2258 synchronized (mDhcpResultsLock) { 2259 return new DhcpResults(mDhcpResults); 2260 } 2261 } 2262 2263 /** 2264 * TODO: doc 2265 */ 2266 public void setDriverStart(boolean enable) { 2267 if (enable) { 2268 sendMessage(CMD_START_DRIVER); 2269 } else { 2270 sendMessage(CMD_STOP_DRIVER); 2271 } 2272 } 2273 2274 /** 2275 * TODO: doc 2276 */ 2277 public void setOperationalMode(int mode) { 2278 if (DBG) log("setting operational mode to " + String.valueOf(mode)); 2279 sendMessage(CMD_SET_OPERATIONAL_MODE, mode, 0); 2280 } 2281 2282 /** 2283 * TODO: doc 2284 */ 2285 public List<ScanResult> syncGetScanResultsList() { 2286 synchronized (mScanResultCache) { 2287 List<ScanResult> scanList = new ArrayList<ScanResult>(); 2288 for (ScanDetail result : mScanResults) { 2289 scanList.add(new ScanResult(result.getScanResult())); 2290 } 2291 return scanList; 2292 } 2293 } 2294 2295 public int syncAddPasspointManagementObject(AsyncChannel channel, String managementObject) { 2296 Message resultMsg = 2297 channel.sendMessageSynchronously(CMD_ADD_PASSPOINT_MO, managementObject); 2298 int result = resultMsg.arg1; 2299 resultMsg.recycle(); 2300 return result; 2301 } 2302 2303 public int syncModifyPasspointManagementObject(AsyncChannel channel, String fqdn, 2304 List<PasspointManagementObjectDefinition> 2305 managementObjectDefinitions) { 2306 Bundle bundle = new Bundle(); 2307 bundle.putString("FQDN", fqdn); 2308 bundle.putParcelableList("MOS", managementObjectDefinitions); 2309 Message resultMsg = channel.sendMessageSynchronously(CMD_MODIFY_PASSPOINT_MO, bundle); 2310 int result = resultMsg.arg1; 2311 resultMsg.recycle(); 2312 return result; 2313 } 2314 2315 public boolean syncQueryPasspointIcon(AsyncChannel channel, long bssid, String fileName) { 2316 Bundle bundle = new Bundle(); 2317 bundle.putLong("BSSID", bssid); 2318 bundle.putString("FILENAME", fileName); 2319 Message resultMsg = channel.sendMessageSynchronously(CMD_QUERY_OSU_ICON, bundle); 2320 int result = resultMsg.arg1; 2321 resultMsg.recycle(); 2322 return result == 1; 2323 } 2324 2325 public int matchProviderWithCurrentNetwork(AsyncChannel channel, String fqdn) { 2326 Message resultMsg = channel.sendMessageSynchronously(CMD_MATCH_PROVIDER_NETWORK, fqdn); 2327 int result = resultMsg.arg1; 2328 resultMsg.recycle(); 2329 return result; 2330 } 2331 2332 /** 2333 * Deauthenticate and set the re-authentication hold off time for the current network 2334 * @param holdoff hold off time in milliseconds 2335 * @param ess set if the hold off pertains to an ESS rather than a BSS 2336 */ 2337 public void deauthenticateNetwork(AsyncChannel channel, long holdoff, boolean ess) { 2338 // TODO: This needs an implementation 2339 } 2340 2341 public void disableEphemeralNetwork(String SSID) { 2342 if (SSID != null) { 2343 sendMessage(CMD_DISABLE_EPHEMERAL_NETWORK, SSID); 2344 } 2345 } 2346 2347 /** 2348 * Get unsynchronized pointer to scan result list 2349 * Can be called only from AutoJoinController which runs in the WifiStateMachine context 2350 */ 2351 public List<ScanDetail> getScanResultsListNoCopyUnsync() { 2352 return mScanResults; 2353 } 2354 2355 /** 2356 * Disconnect from Access Point 2357 */ 2358 public void disconnectCommand() { 2359 sendMessage(CMD_DISCONNECT); 2360 } 2361 2362 public void disconnectCommand(int uid, int reason) { 2363 sendMessage(CMD_DISCONNECT, uid, reason); 2364 } 2365 2366 /** 2367 * Initiate a reconnection to AP 2368 */ 2369 public void reconnectCommand() { 2370 sendMessage(CMD_RECONNECT); 2371 } 2372 2373 /** 2374 * Initiate a re-association to AP 2375 */ 2376 public void reassociateCommand() { 2377 sendMessage(CMD_REASSOCIATE); 2378 } 2379 2380 /** 2381 * Reload networks and then reconnect; helps load correct data for TLS networks 2382 */ 2383 2384 public void reloadTlsNetworksAndReconnect() { 2385 sendMessage(CMD_RELOAD_TLS_AND_RECONNECT); 2386 } 2387 2388 /** 2389 * Add a network synchronously 2390 * 2391 * @return network id of the new network 2392 */ 2393 public int syncAddOrUpdateNetwork(AsyncChannel channel, WifiConfiguration config) { 2394 Message resultMsg = channel.sendMessageSynchronously(CMD_ADD_OR_UPDATE_NETWORK, config); 2395 int result = resultMsg.arg1; 2396 resultMsg.recycle(); 2397 return result; 2398 } 2399 2400 /** 2401 * Get configured networks synchronously 2402 * 2403 * @param channel 2404 * @return 2405 */ 2406 2407 public List<WifiConfiguration> syncGetConfiguredNetworks(int uuid, AsyncChannel channel) { 2408 Message resultMsg = channel.sendMessageSynchronously(CMD_GET_CONFIGURED_NETWORKS, uuid); 2409 List<WifiConfiguration> result = (List<WifiConfiguration>) resultMsg.obj; 2410 resultMsg.recycle(); 2411 return result; 2412 } 2413 2414 public List<WifiConfiguration> syncGetPrivilegedConfiguredNetwork(AsyncChannel channel) { 2415 Message resultMsg = channel.sendMessageSynchronously( 2416 CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS); 2417 List<WifiConfiguration> result = (List<WifiConfiguration>) resultMsg.obj; 2418 resultMsg.recycle(); 2419 return result; 2420 } 2421 2422 public WifiConfiguration syncGetMatchingWifiConfig(ScanResult scanResult, AsyncChannel channel) { 2423 Message resultMsg = channel.sendMessageSynchronously(CMD_GET_MATCHING_CONFIG, scanResult); 2424 return (WifiConfiguration) resultMsg.obj; 2425 } 2426 2427 /** 2428 * Get connection statistics synchronously 2429 * 2430 * @param channel 2431 * @return 2432 */ 2433 2434 public WifiConnectionStatistics syncGetConnectionStatistics(AsyncChannel channel) { 2435 Message resultMsg = channel.sendMessageSynchronously(CMD_GET_CONNECTION_STATISTICS); 2436 WifiConnectionStatistics result = (WifiConnectionStatistics) resultMsg.obj; 2437 resultMsg.recycle(); 2438 return result; 2439 } 2440 2441 /** 2442 * Get adaptors synchronously 2443 */ 2444 2445 public int syncGetSupportedFeatures(AsyncChannel channel) { 2446 Message resultMsg = channel.sendMessageSynchronously(CMD_GET_SUPPORTED_FEATURES); 2447 int supportedFeatureSet = resultMsg.arg1; 2448 resultMsg.recycle(); 2449 return supportedFeatureSet; 2450 } 2451 2452 /** 2453 * Get link layers stats for adapter synchronously 2454 */ 2455 public WifiLinkLayerStats syncGetLinkLayerStats(AsyncChannel channel) { 2456 Message resultMsg = channel.sendMessageSynchronously(CMD_GET_LINK_LAYER_STATS); 2457 WifiLinkLayerStats result = (WifiLinkLayerStats) resultMsg.obj; 2458 resultMsg.recycle(); 2459 return result; 2460 } 2461 2462 /** 2463 * Delete a network 2464 * 2465 * @param networkId id of the network to be removed 2466 */ 2467 public boolean syncRemoveNetwork(AsyncChannel channel, int networkId) { 2468 Message resultMsg = channel.sendMessageSynchronously(CMD_REMOVE_NETWORK, networkId); 2469 boolean result = (resultMsg.arg1 != FAILURE); 2470 resultMsg.recycle(); 2471 return result; 2472 } 2473 2474 /** 2475 * Enable a network 2476 * 2477 * @param netId network id of the network 2478 * @param disableOthers true, if all other networks have to be disabled 2479 * @return {@code true} if the operation succeeds, {@code false} otherwise 2480 */ 2481 public boolean syncEnableNetwork(AsyncChannel channel, int netId, boolean disableOthers) { 2482 Message resultMsg = channel.sendMessageSynchronously(CMD_ENABLE_NETWORK, netId, 2483 disableOthers ? 1 : 0); 2484 boolean result = (resultMsg.arg1 != FAILURE); 2485 resultMsg.recycle(); 2486 return result; 2487 } 2488 2489 /** 2490 * Disable a network 2491 * 2492 * @param netId network id of the network 2493 * @return {@code true} if the operation succeeds, {@code false} otherwise 2494 */ 2495 public boolean syncDisableNetwork(AsyncChannel channel, int netId) { 2496 Message resultMsg = channel.sendMessageSynchronously(WifiManager.DISABLE_NETWORK, netId); 2497 boolean result = (resultMsg.arg1 != WifiManager.DISABLE_NETWORK_FAILED); 2498 resultMsg.recycle(); 2499 return result; 2500 } 2501 2502 /** 2503 * Retrieves a WPS-NFC configuration token for the specified network 2504 * 2505 * @return a hex string representation of the WPS-NFC configuration token 2506 */ 2507 public String syncGetWpsNfcConfigurationToken(int netId) { 2508 return mWifiNative.getNfcWpsConfigurationToken(netId); 2509 } 2510 2511 void enableBackgroundScan(boolean enable) { 2512 if (enable) { 2513 mWifiConfigStore.enableAllNetworks(); 2514 } 2515 List<WifiNative.PnoNetworkPriority> pnoList = 2516 mWifiConfigStore.retrievePnoNetworkPriorityList(enable); 2517 boolean ret = mWifiNative.enableBackgroundScan(enable, pnoList); 2518 if (ret) { 2519 mLegacyPnoEnabled = enable; 2520 } else { 2521 Log.e(TAG, " Fail to set up pno, want " + enable + " now " + mLegacyPnoEnabled); 2522 } 2523 } 2524 2525 /** 2526 * Blacklist a BSSID. This will avoid the AP if there are 2527 * alternate APs to connect 2528 * 2529 * @param bssid BSSID of the network 2530 */ 2531 public void addToBlacklist(String bssid) { 2532 sendMessage(CMD_BLACKLIST_NETWORK, bssid); 2533 } 2534 2535 /** 2536 * Clear the blacklist list 2537 */ 2538 public void clearBlacklist() { 2539 sendMessage(CMD_CLEAR_BLACKLIST); 2540 } 2541 2542 public void enableRssiPolling(boolean enabled) { 2543 sendMessage(CMD_ENABLE_RSSI_POLL, enabled ? 1 : 0, 0); 2544 } 2545 2546 public void enableAllNetworks() { 2547 sendMessage(CMD_ENABLE_ALL_NETWORKS); 2548 } 2549 2550 /** 2551 * Start filtering Multicast v4 packets 2552 */ 2553 public void startFilteringMulticastV4Packets() { 2554 mFilteringMulticastV4Packets.set(true); 2555 sendMessage(CMD_START_PACKET_FILTERING, MULTICAST_V4, 0); 2556 } 2557 2558 /** 2559 * Stop filtering Multicast v4 packets 2560 */ 2561 public void stopFilteringMulticastV4Packets() { 2562 mFilteringMulticastV4Packets.set(false); 2563 sendMessage(CMD_STOP_PACKET_FILTERING, MULTICAST_V4, 0); 2564 } 2565 2566 /** 2567 * Start filtering Multicast v4 packets 2568 */ 2569 public void startFilteringMulticastV6Packets() { 2570 sendMessage(CMD_START_PACKET_FILTERING, MULTICAST_V6, 0); 2571 } 2572 2573 /** 2574 * Stop filtering Multicast v4 packets 2575 */ 2576 public void stopFilteringMulticastV6Packets() { 2577 sendMessage(CMD_STOP_PACKET_FILTERING, MULTICAST_V6, 0); 2578 } 2579 2580 /** 2581 * Set high performance mode of operation. 2582 * Enabling would set active power mode and disable suspend optimizations; 2583 * disabling would set auto power mode and enable suspend optimizations 2584 * 2585 * @param enable true if enable, false otherwise 2586 */ 2587 public void setHighPerfModeEnabled(boolean enable) { 2588 sendMessage(CMD_SET_HIGH_PERF_MODE, enable ? 1 : 0, 0); 2589 } 2590 2591 /** 2592 * Set the country code 2593 * 2594 * @param countryCode following ISO 3166 format 2595 * @param persist {@code true} if the setting should be remembered. 2596 */ 2597 public synchronized void setCountryCode(String countryCode, boolean persist) { 2598 // If it's a good country code, apply after the current 2599 // wifi connection is terminated; ignore resetting of code 2600 // for now (it is unclear what the chipset should do when 2601 // country code is reset) 2602 2603 // if mCountryCodeSequence == 0, it is the first time to set country code, always set 2604 // else only when the new country code is different from the current one to set 2605 2606 if (TextUtils.isEmpty(countryCode)) { 2607 if (DBG) log("Ignoring resetting of country code"); 2608 } else { 2609 int countryCodeSequence = mCountryCodeSequence.get(); 2610 String currentCountryCode = getCurrentCountryCode(); 2611 if (countryCodeSequence == 0 2612 || TextUtils.equals(countryCode, currentCountryCode) == false) { 2613 2614 countryCodeSequence = mCountryCodeSequence.incrementAndGet(); 2615 sendMessage(CMD_SET_COUNTRY_CODE, countryCodeSequence, persist ? 1 : 0, 2616 countryCode); 2617 } 2618 } 2619 } 2620 2621 /** 2622 * reset the country code to default 2623 */ 2624 public synchronized void resetCountryCode() { 2625 if (mRevertCountryCodeOnCellularLoss && TextUtils.isEmpty(mDefaultCountryCode) == false) { 2626 logd("resetting country code to " + mDefaultCountryCode); 2627 setCountryCode(mDefaultCountryCode, /* persist = */ true); 2628 } 2629 } 2630 2631 /** 2632 * reset cached SIM credential data 2633 */ 2634 public synchronized void resetSimAuthNetworks() { 2635 sendMessage(CMD_RESET_SIM_NETWORKS); 2636 } 2637 2638 2639 /** 2640 * Get Network object of current wifi network 2641 * @return Network object of current wifi network 2642 */ 2643 public Network getCurrentNetwork() { 2644 if (mNetworkAgent != null) { 2645 return new Network(mNetworkAgent.netId); 2646 } else { 2647 return null; 2648 } 2649 } 2650 2651 /** 2652 * Get the country code 2653 * 2654 * @return countryCode following ISO 3166 format 2655 */ 2656 public String getCurrentCountryCode() { 2657 return mFacade.getStringSetting(mContext, Settings.Global.WIFI_COUNTRY_CODE); 2658 } 2659 2660 /** 2661 * Set the operational frequency band 2662 * 2663 * @param band 2664 * @param persist {@code true} if the setting should be remembered. 2665 */ 2666 public void setFrequencyBand(int band, boolean persist) { 2667 if (persist) { 2668 Settings.Global.putInt(mContext.getContentResolver(), 2669 Settings.Global.WIFI_FREQUENCY_BAND, 2670 band); 2671 } 2672 sendMessage(CMD_SET_FREQUENCY_BAND, band, 0); 2673 } 2674 2675 /** 2676 * Enable TDLS for a specific MAC address 2677 */ 2678 public void enableTdls(String remoteMacAddress, boolean enable) { 2679 int enabler = enable ? 1 : 0; 2680 sendMessage(CMD_ENABLE_TDLS, enabler, 0, remoteMacAddress); 2681 } 2682 2683 /** 2684 * Returns the operational frequency band 2685 */ 2686 public int getFrequencyBand() { 2687 return mFrequencyBand.get(); 2688 } 2689 2690 /** 2691 * Returns the wifi configuration file 2692 */ 2693 public String getConfigFile() { 2694 return mWifiConfigStore.getConfigFile(); 2695 } 2696 2697 /** 2698 * Send a message indicating bluetooth adapter connection state changed 2699 */ 2700 public void sendBluetoothAdapterStateChange(int state) { 2701 sendMessage(CMD_BLUETOOTH_ADAPTER_STATE_CHANGE, state, 0); 2702 } 2703 2704 /** 2705 * Send a message indicating a package has been uninstalled. 2706 */ 2707 public void removeAppConfigs(String packageName, int uid) { 2708 // Build partial AppInfo manually - package may not exist in database any more 2709 ApplicationInfo ai = new ApplicationInfo(); 2710 ai.packageName = packageName; 2711 ai.uid = uid; 2712 sendMessage(CMD_REMOVE_APP_CONFIGURATIONS, ai); 2713 } 2714 2715 /** 2716 * Send a message indicating a user has been removed. 2717 */ 2718 public void removeUserConfigs(int userId) { 2719 sendMessage(CMD_REMOVE_USER_CONFIGURATIONS, userId); 2720 } 2721 2722 /** 2723 * Save configuration on supplicant 2724 * 2725 * @return {@code true} if the operation succeeds, {@code false} otherwise 2726 * <p/> 2727 * TODO: deprecate this 2728 */ 2729 public boolean syncSaveConfig(AsyncChannel channel) { 2730 Message resultMsg = channel.sendMessageSynchronously(CMD_SAVE_CONFIG); 2731 boolean result = (resultMsg.arg1 != FAILURE); 2732 resultMsg.recycle(); 2733 return result; 2734 } 2735 2736 public void updateBatteryWorkSource(WorkSource newSource) { 2737 synchronized (mRunningWifiUids) { 2738 try { 2739 if (newSource != null) { 2740 mRunningWifiUids.set(newSource); 2741 } 2742 if (mIsRunning) { 2743 if (mReportedRunning) { 2744 // If the work source has changed since last time, need 2745 // to remove old work from battery stats. 2746 if (mLastRunningWifiUids.diff(mRunningWifiUids)) { 2747 mBatteryStats.noteWifiRunningChanged(mLastRunningWifiUids, 2748 mRunningWifiUids); 2749 mLastRunningWifiUids.set(mRunningWifiUids); 2750 } 2751 } else { 2752 // Now being started, report it. 2753 mBatteryStats.noteWifiRunning(mRunningWifiUids); 2754 mLastRunningWifiUids.set(mRunningWifiUids); 2755 mReportedRunning = true; 2756 } 2757 } else { 2758 if (mReportedRunning) { 2759 // Last reported we were running, time to stop. 2760 mBatteryStats.noteWifiStopped(mLastRunningWifiUids); 2761 mLastRunningWifiUids.clear(); 2762 mReportedRunning = false; 2763 } 2764 } 2765 mWakeLock.setWorkSource(newSource); 2766 } catch (RemoteException ignore) { 2767 } 2768 } 2769 } 2770 2771 @Override 2772 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2773 super.dump(fd, pw, args); 2774 mSupplicantStateTracker.dump(fd, pw, args); 2775 pw.println("mLinkProperties " + mLinkProperties); 2776 pw.println("mWifiInfo " + mWifiInfo); 2777 pw.println("mDhcpResults " + mDhcpResults); 2778 pw.println("mNetworkInfo " + mNetworkInfo); 2779 pw.println("mLastSignalLevel " + mLastSignalLevel); 2780 pw.println("mLastBssid " + mLastBssid); 2781 pw.println("mLastNetworkId " + mLastNetworkId); 2782 pw.println("mOperationalMode " + mOperationalMode); 2783 pw.println("mUserWantsSuspendOpt " + mUserWantsSuspendOpt); 2784 pw.println("mSuspendOptNeedsDisabled " + mSuspendOptNeedsDisabled); 2785 pw.println("Supplicant status " + mWifiNative.status(true)); 2786 pw.println("mLegacyPnoEnabled " + mLegacyPnoEnabled); 2787 pw.println("mDriverSetCountryCode " + mDriverSetCountryCode); 2788 pw.println("mConnectedModeGScanOffloadStarted " + mConnectedModeGScanOffloadStarted); 2789 pw.println("mGScanPeriodMilli " + mGScanPeriodMilli); 2790 if (mWhiteListedSsids != null && mWhiteListedSsids.length > 0) { 2791 pw.println("SSID whitelist :" ); 2792 for (int i=0; i < mWhiteListedSsids.length; i++) { 2793 pw.println(" " + mWhiteListedSsids[i]); 2794 } 2795 } 2796 if (mNetworkFactory != null) { 2797 mNetworkFactory.dump(fd, pw, args); 2798 } else { 2799 pw.println("mNetworkFactory is not initialized"); 2800 } 2801 2802 if (mUntrustedNetworkFactory != null) { 2803 mUntrustedNetworkFactory.dump(fd, pw, args); 2804 } else { 2805 pw.println("mUntrustedNetworkFactory is not initialized"); 2806 } 2807 pw.println(); 2808 updateWifiMetrics(); 2809 mWifiMetrics.dump(fd, pw, args); 2810 pw.println(); 2811 mNetworkFactory.dump(fd, pw, args); 2812 mUntrustedNetworkFactory.dump(fd, pw, args); 2813 pw.println(); 2814 2815 mWifiConfigStore.dump(fd, pw, args); 2816 pw.println(); 2817 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_USER_ACTION); 2818 mWifiLogger.dump(fd, pw, args); 2819 mWifiQualifiedNetworkSelector.dump(fd, pw, args); 2820 } 2821 2822 public void handleUserSwitch(int userId) { 2823 sendMessage(CMD_USER_SWITCH, userId); 2824 } 2825 2826 /** 2827 * ****************************************************** 2828 * Internal private functions 2829 * ****************************************************** 2830 */ 2831 2832 private void logStateAndMessage(Message message, State state) { 2833 messageHandlingStatus = 0; 2834 if (mLogMessages) { 2835 logd(" " + state.getClass().getSimpleName() + " " + getLogRecString(message)); 2836 } 2837 } 2838 2839 /** 2840 * helper, prints the milli time since boot wi and w/o suspended time 2841 */ 2842 String printTime() { 2843 StringBuilder sb = new StringBuilder(); 2844 sb.append(" rt=").append(SystemClock.uptimeMillis()); 2845 sb.append("/").append(SystemClock.elapsedRealtime()); 2846 return sb.toString(); 2847 } 2848 2849 /** 2850 * Return the additional string to be logged by LogRec, default 2851 * 2852 * @param msg that was processed 2853 * @return information to be logged as a String 2854 */ 2855 protected String getLogRecString(Message msg) { 2856 WifiConfiguration config; 2857 Long now; 2858 String report; 2859 String key; 2860 StringBuilder sb = new StringBuilder(); 2861 if (mScreenOn) { 2862 sb.append("!"); 2863 } 2864 if (messageHandlingStatus != MESSAGE_HANDLING_STATUS_UNKNOWN) { 2865 sb.append("(").append(messageHandlingStatus).append(")"); 2866 } 2867 sb.append(smToString(msg)); 2868 if (msg.sendingUid > 0 && msg.sendingUid != Process.WIFI_UID) { 2869 sb.append(" uid=" + msg.sendingUid); 2870 } 2871 sb.append(" ").append(printTime()); 2872 switch (msg.what) { 2873 case CMD_STARTED_GSCAN_DBG: 2874 case CMD_STARTED_PNO_DBG: 2875 sb.append(" "); 2876 sb.append(Integer.toString(msg.arg1)); 2877 sb.append(" "); 2878 sb.append(Integer.toString(msg.arg2)); 2879 if (msg.obj != null) { 2880 sb.append(" " + (String)msg.obj); 2881 } 2882 break; 2883 case CMD_RESTART_AUTOJOIN_OFFLOAD: 2884 sb.append(" "); 2885 sb.append(Integer.toString(msg.arg1)); 2886 sb.append(" "); 2887 sb.append(Integer.toString(msg.arg2)); 2888 sb.append("/").append(Integer.toString(mRestartAutoJoinOffloadCounter)); 2889 if (msg.obj != null) { 2890 sb.append(" " + (String)msg.obj); 2891 } 2892 break; 2893 case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION: 2894 sb.append(" "); 2895 sb.append(Integer.toString(msg.arg1)); 2896 sb.append(" "); 2897 sb.append(Integer.toString(msg.arg2)); 2898 sb.append(" halAllowed=").append(useHalBasedAutoJoinOffload()); 2899 sb.append(" scanAllowed=").append(allowFullBandScanAndAssociated()); 2900 sb.append(" autojoinAllowed="); 2901 sb.append(mWifiConfigStore.enableAutoJoinWhenAssociated.get()); 2902 sb.append(" withTraffic=").append(getAllowScansWithTraffic()); 2903 sb.append(" tx=").append(mWifiInfo.txSuccessRate); 2904 sb.append("/").append(mWifiConfigStore.maxTxPacketForFullScans); 2905 sb.append(" rx=").append(mWifiInfo.rxSuccessRate); 2906 sb.append("/").append(mWifiConfigStore.maxRxPacketForFullScans); 2907 sb.append(" -> ").append(mConnectedModeGScanOffloadStarted); 2908 break; 2909 case CMD_PNO_NETWORK_FOUND: 2910 sb.append(" "); 2911 sb.append(Integer.toString(msg.arg1)); 2912 sb.append(" "); 2913 sb.append(Integer.toString(msg.arg2)); 2914 if (msg.obj != null) { 2915 ScanResult[] results = (ScanResult[])msg.obj; 2916 for (int i = 0; i < results.length; i++) { 2917 sb.append(" ").append(results[i].SSID).append(" "); 2918 sb.append(results[i].frequency); 2919 sb.append(" ").append(results[i].level); 2920 } 2921 } 2922 break; 2923 case CMD_START_SCAN: 2924 now = System.currentTimeMillis(); 2925 sb.append(" "); 2926 sb.append(Integer.toString(msg.arg1)); 2927 sb.append(" "); 2928 sb.append(Integer.toString(msg.arg2)); 2929 sb.append(" ic="); 2930 sb.append(Integer.toString(sScanAlarmIntentCount)); 2931 if (msg.obj != null) { 2932 Bundle bundle = (Bundle) msg.obj; 2933 Long request = bundle.getLong(SCAN_REQUEST_TIME, 0); 2934 if (request != 0) { 2935 sb.append(" proc(ms):").append(now - request); 2936 } 2937 } 2938 if (mIsScanOngoing) sb.append(" onGoing"); 2939 if (mIsFullScanOngoing) sb.append(" full"); 2940 if (lastStartScanTimeStamp != 0) { 2941 sb.append(" started:").append(lastStartScanTimeStamp); 2942 sb.append(",").append(now - lastStartScanTimeStamp); 2943 } 2944 if (lastScanDuration != 0) { 2945 sb.append(" dur:").append(lastScanDuration); 2946 } 2947 sb.append(" cnt=").append(mDelayedScanCounter); 2948 sb.append(" rssi=").append(mWifiInfo.getRssi()); 2949 sb.append(" f=").append(mWifiInfo.getFrequency()); 2950 sb.append(" sc=").append(mWifiInfo.score); 2951 sb.append(" link=").append(mWifiInfo.getLinkSpeed()); 2952 sb.append(String.format(" tx=%.1f,", mWifiInfo.txSuccessRate)); 2953 sb.append(String.format(" %.1f,", mWifiInfo.txRetriesRate)); 2954 sb.append(String.format(" %.1f ", mWifiInfo.txBadRate)); 2955 sb.append(String.format(" rx=%.1f", mWifiInfo.rxSuccessRate)); 2956 if (lastScanFreqs != null) { 2957 sb.append(" list="); 2958 for(int freq : lastScanFreqs) { 2959 sb.append(freq).append(","); 2960 } 2961 } else { 2962 sb.append(" fiv=").append(fullBandConnectedTimeIntervalMilli); 2963 } 2964 report = reportOnTime(); 2965 if (report != null) { 2966 sb.append(" ").append(report); 2967 } 2968 break; 2969 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 2970 sb.append(" "); 2971 sb.append(Integer.toString(msg.arg1)); 2972 sb.append(" "); 2973 sb.append(Integer.toString(msg.arg2)); 2974 StateChangeResult stateChangeResult = (StateChangeResult) msg.obj; 2975 if (stateChangeResult != null) { 2976 sb.append(stateChangeResult.toString()); 2977 } 2978 break; 2979 case WifiManager.SAVE_NETWORK: 2980 case WifiStateMachine.CMD_AUTO_SAVE_NETWORK: 2981 sb.append(" "); 2982 sb.append(Integer.toString(msg.arg1)); 2983 sb.append(" "); 2984 sb.append(Integer.toString(msg.arg2)); 2985 if (lastSavedConfigurationAttempt != null) { 2986 sb.append(" ").append(lastSavedConfigurationAttempt.configKey()); 2987 sb.append(" nid=").append(lastSavedConfigurationAttempt.networkId); 2988 if (lastSavedConfigurationAttempt.hiddenSSID) { 2989 sb.append(" hidden"); 2990 } 2991 if (lastSavedConfigurationAttempt.preSharedKey != null 2992 && !lastSavedConfigurationAttempt.preSharedKey.equals("*")) { 2993 sb.append(" hasPSK"); 2994 } 2995 if (lastSavedConfigurationAttempt.ephemeral) { 2996 sb.append(" ephemeral"); 2997 } 2998 if (lastSavedConfigurationAttempt.selfAdded) { 2999 sb.append(" selfAdded"); 3000 } 3001 sb.append(" cuid=").append(lastSavedConfigurationAttempt.creatorUid); 3002 sb.append(" suid=").append(lastSavedConfigurationAttempt.lastUpdateUid); 3003 } 3004 break; 3005 case WifiManager.FORGET_NETWORK: 3006 sb.append(" "); 3007 sb.append(Integer.toString(msg.arg1)); 3008 sb.append(" "); 3009 sb.append(Integer.toString(msg.arg2)); 3010 if (lastForgetConfigurationAttempt != null) { 3011 sb.append(" ").append(lastForgetConfigurationAttempt.configKey()); 3012 sb.append(" nid=").append(lastForgetConfigurationAttempt.networkId); 3013 if (lastForgetConfigurationAttempt.hiddenSSID) { 3014 sb.append(" hidden"); 3015 } 3016 if (lastForgetConfigurationAttempt.preSharedKey != null) { 3017 sb.append(" hasPSK"); 3018 } 3019 if (lastForgetConfigurationAttempt.ephemeral) { 3020 sb.append(" ephemeral"); 3021 } 3022 if (lastForgetConfigurationAttempt.selfAdded) { 3023 sb.append(" selfAdded"); 3024 } 3025 sb.append(" cuid=").append(lastForgetConfigurationAttempt.creatorUid); 3026 sb.append(" suid=").append(lastForgetConfigurationAttempt.lastUpdateUid); 3027 WifiConfiguration.NetworkSelectionStatus netWorkSelectionStatus = 3028 lastForgetConfigurationAttempt.getNetworkSelectionStatus(); 3029 sb.append(" ajst=").append( 3030 netWorkSelectionStatus.getNetworkStatusString()); 3031 } 3032 break; 3033 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 3034 sb.append(" "); 3035 sb.append(Integer.toString(msg.arg1)); 3036 sb.append(" "); 3037 sb.append(Integer.toString(msg.arg2)); 3038 String bssid = (String) msg.obj; 3039 if (bssid != null && bssid.length() > 0) { 3040 sb.append(" "); 3041 sb.append(bssid); 3042 } 3043 sb.append(" blacklist=" + Boolean.toString(didBlackListBSSID)); 3044 break; 3045 case WifiMonitor.SCAN_RESULTS_EVENT: 3046 sb.append(" "); 3047 sb.append(Integer.toString(msg.arg1)); 3048 sb.append(" "); 3049 sb.append(Integer.toString(msg.arg2)); 3050 if (mScanResults != null) { 3051 sb.append(" found="); 3052 sb.append(mScanResults.size()); 3053 } 3054 sb.append(" known=").append(mNumScanResultsKnown); 3055 sb.append(" got=").append(mNumScanResultsReturned); 3056 if (lastScanDuration != 0) { 3057 sb.append(" dur:").append(lastScanDuration); 3058 } 3059 if (mOnTime != 0) { 3060 sb.append(" on:").append(mOnTimeThisScan).append(",").append(mOnTimeScan); 3061 sb.append(",").append(mOnTime); 3062 } 3063 if (mTxTime != 0) { 3064 sb.append(" tx:").append(mTxTimeThisScan).append(",").append(mTxTimeScan); 3065 sb.append(",").append(mTxTime); 3066 } 3067 if (mRxTime != 0) { 3068 sb.append(" rx:").append(mRxTimeThisScan).append(",").append(mRxTimeScan); 3069 sb.append(",").append(mRxTime); 3070 } 3071 sb.append(String.format(" bcn=%d", mRunningBeaconCount)); 3072 sb.append(String.format(" con=%d", mConnectionRequests)); 3073 key = mWifiConfigStore.getLastSelectedConfiguration(); 3074 if (key != null) { 3075 sb.append(" last=").append(key); 3076 } 3077 break; 3078 case WifiMonitor.SCAN_FAILED_EVENT: 3079 break; 3080 case WifiMonitor.NETWORK_CONNECTION_EVENT: 3081 sb.append(" "); 3082 sb.append(Integer.toString(msg.arg1)); 3083 sb.append(" "); 3084 sb.append(Integer.toString(msg.arg2)); 3085 sb.append(" ").append(mLastBssid); 3086 sb.append(" nid=").append(mLastNetworkId); 3087 config = getCurrentWifiConfiguration(); 3088 if (config != null) { 3089 sb.append(" ").append(config.configKey()); 3090 } 3091 key = mWifiConfigStore.getLastSelectedConfiguration(); 3092 if (key != null) { 3093 sb.append(" last=").append(key); 3094 } 3095 break; 3096 case CMD_TARGET_BSSID: 3097 case CMD_ASSOCIATED_BSSID: 3098 sb.append(" "); 3099 sb.append(Integer.toString(msg.arg1)); 3100 sb.append(" "); 3101 sb.append(Integer.toString(msg.arg2)); 3102 if (msg.obj != null) { 3103 sb.append(" BSSID=").append((String) msg.obj); 3104 } 3105 if (mTargetRoamBSSID != null) { 3106 sb.append(" Target=").append(mTargetRoamBSSID); 3107 } 3108 sb.append(" roam=").append(Boolean.toString(mAutoRoaming)); 3109 break; 3110 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 3111 if (msg.obj != null) { 3112 sb.append(" ").append((String) msg.obj); 3113 } 3114 sb.append(" nid=").append(msg.arg1); 3115 sb.append(" reason=").append(msg.arg2); 3116 if (mLastBssid != null) { 3117 sb.append(" lastbssid=").append(mLastBssid); 3118 } 3119 if (mWifiInfo.getFrequency() != -1) { 3120 sb.append(" freq=").append(mWifiInfo.getFrequency()); 3121 sb.append(" rssi=").append(mWifiInfo.getRssi()); 3122 } 3123 if (linkDebouncing) { 3124 sb.append(" debounce"); 3125 } 3126 break; 3127 case WifiMonitor.SSID_TEMP_DISABLED: 3128 case WifiMonitor.SSID_REENABLED: 3129 sb.append(" nid=").append(msg.arg1); 3130 if (msg.obj != null) { 3131 sb.append(" ").append((String) msg.obj); 3132 } 3133 config = getCurrentWifiConfiguration(); 3134 if (config != null) { 3135 WifiConfiguration.NetworkSelectionStatus netWorkSelectionStatus = 3136 config.getNetworkSelectionStatus(); 3137 sb.append(" cur=").append(config.configKey()); 3138 sb.append(" ajst=").append(netWorkSelectionStatus.getNetworkStatusString()); 3139 if (config.selfAdded) { 3140 sb.append(" selfAdded"); 3141 } 3142 if (config.status != 0) { 3143 sb.append(" st=").append(config.status); 3144 sb.append(" rs=").append( 3145 netWorkSelectionStatus.getNetworkDisableReasonString()); 3146 } 3147 if (config.lastConnected != 0) { 3148 now = System.currentTimeMillis(); 3149 sb.append(" lastconn=").append(now - config.lastConnected).append("(ms)"); 3150 } 3151 if (mLastBssid != null) { 3152 sb.append(" lastbssid=").append(mLastBssid); 3153 } 3154 if (mWifiInfo.getFrequency() != -1) { 3155 sb.append(" freq=").append(mWifiInfo.getFrequency()); 3156 sb.append(" rssi=").append(mWifiInfo.getRssi()); 3157 sb.append(" bssid=").append(mWifiInfo.getBSSID()); 3158 } 3159 } 3160 break; 3161 case CMD_RSSI_POLL: 3162 case CMD_UNWANTED_NETWORK: 3163 case WifiManager.RSSI_PKTCNT_FETCH: 3164 sb.append(" "); 3165 sb.append(Integer.toString(msg.arg1)); 3166 sb.append(" "); 3167 sb.append(Integer.toString(msg.arg2)); 3168 if (mWifiInfo.getSSID() != null) 3169 if (mWifiInfo.getSSID() != null) 3170 sb.append(" ").append(mWifiInfo.getSSID()); 3171 if (mWifiInfo.getBSSID() != null) 3172 sb.append(" ").append(mWifiInfo.getBSSID()); 3173 sb.append(" rssi=").append(mWifiInfo.getRssi()); 3174 sb.append(" f=").append(mWifiInfo.getFrequency()); 3175 sb.append(" sc=").append(mWifiInfo.score); 3176 sb.append(" link=").append(mWifiInfo.getLinkSpeed()); 3177 sb.append(String.format(" tx=%.1f,", mWifiInfo.txSuccessRate)); 3178 sb.append(String.format(" %.1f,", mWifiInfo.txRetriesRate)); 3179 sb.append(String.format(" %.1f ", mWifiInfo.txBadRate)); 3180 sb.append(String.format(" rx=%.1f", mWifiInfo.rxSuccessRate)); 3181 sb.append(String.format(" bcn=%d", mRunningBeaconCount)); 3182 report = reportOnTime(); 3183 if (report != null) { 3184 sb.append(" ").append(report); 3185 } 3186 if (wifiScoringReport != null) { 3187 sb.append(wifiScoringReport); 3188 } 3189 if (mConnectedModeGScanOffloadStarted) { 3190 sb.append(" offload-started periodMilli " + mGScanPeriodMilli); 3191 } else { 3192 sb.append(" offload-stopped"); 3193 } 3194 break; 3195 case CMD_AUTO_CONNECT: 3196 case WifiManager.CONNECT_NETWORK: 3197 sb.append(" "); 3198 sb.append(Integer.toString(msg.arg1)); 3199 sb.append(" "); 3200 sb.append(Integer.toString(msg.arg2)); 3201 config = mWifiConfigStore.getWifiConfiguration(msg.arg1); 3202 if (config != null) { 3203 sb.append(" ").append(config.configKey()); 3204 if (config.visibility != null) { 3205 sb.append(" ").append(config.visibility.toString()); 3206 } 3207 } 3208 if (mTargetRoamBSSID != null) { 3209 sb.append(" ").append(mTargetRoamBSSID); 3210 } 3211 sb.append(" roam=").append(Boolean.toString(mAutoRoaming)); 3212 config = getCurrentWifiConfiguration(); 3213 if (config != null) { 3214 sb.append(config.configKey()); 3215 if (config.visibility != null) { 3216 sb.append(" ").append(config.visibility.toString()); 3217 } 3218 } 3219 break; 3220 case CMD_AUTO_ROAM: 3221 sb.append(" "); 3222 sb.append(Integer.toString(msg.arg1)); 3223 sb.append(" "); 3224 sb.append(Integer.toString(msg.arg2)); 3225 ScanResult result = (ScanResult) msg.obj; 3226 if (result != null) { 3227 now = System.currentTimeMillis(); 3228 sb.append(" bssid=").append(result.BSSID); 3229 sb.append(" rssi=").append(result.level); 3230 sb.append(" freq=").append(result.frequency); 3231 if (result.seen > 0 && result.seen < now) { 3232 sb.append(" seen=").append(now - result.seen); 3233 } else { 3234 // Somehow the timestamp for this scan result is inconsistent 3235 sb.append(" !seen=").append(result.seen); 3236 } 3237 } 3238 if (mTargetRoamBSSID != null) { 3239 sb.append(" ").append(mTargetRoamBSSID); 3240 } 3241 sb.append(" roam=").append(Boolean.toString(mAutoRoaming)); 3242 sb.append(" fail count=").append(Integer.toString(mRoamFailCount)); 3243 break; 3244 case CMD_ADD_OR_UPDATE_NETWORK: 3245 sb.append(" "); 3246 sb.append(Integer.toString(msg.arg1)); 3247 sb.append(" "); 3248 sb.append(Integer.toString(msg.arg2)); 3249 if (msg.obj != null) { 3250 config = (WifiConfiguration) msg.obj; 3251 sb.append(" ").append(config.configKey()); 3252 sb.append(" prio=").append(config.priority); 3253 sb.append(" status=").append(config.status); 3254 if (config.BSSID != null) { 3255 sb.append(" ").append(config.BSSID); 3256 } 3257 WifiConfiguration curConfig = getCurrentWifiConfiguration(); 3258 if (curConfig != null) { 3259 if (curConfig.configKey().equals(config.configKey())) { 3260 sb.append(" is current"); 3261 } else { 3262 sb.append(" current=").append(curConfig.configKey()); 3263 sb.append(" prio=").append(curConfig.priority); 3264 sb.append(" status=").append(curConfig.status); 3265 } 3266 } 3267 } 3268 break; 3269 case WifiManager.DISABLE_NETWORK: 3270 case CMD_ENABLE_NETWORK: 3271 sb.append(" "); 3272 sb.append(Integer.toString(msg.arg1)); 3273 sb.append(" "); 3274 sb.append(Integer.toString(msg.arg2)); 3275 key = mWifiConfigStore.getLastSelectedConfiguration(); 3276 if (key != null) { 3277 sb.append(" last=").append(key); 3278 } 3279 config = mWifiConfigStore.getWifiConfiguration(msg.arg1); 3280 if (config != null && (key == null || !config.configKey().equals(key))) { 3281 sb.append(" target=").append(key); 3282 } 3283 break; 3284 case CMD_GET_CONFIGURED_NETWORKS: 3285 sb.append(" "); 3286 sb.append(Integer.toString(msg.arg1)); 3287 sb.append(" "); 3288 sb.append(Integer.toString(msg.arg2)); 3289 sb.append(" num=").append(mWifiConfigStore.getConfiguredNetworksSize()); 3290 break; 3291 case DhcpStateMachine.CMD_PRE_DHCP_ACTION: 3292 sb.append(" "); 3293 sb.append(Integer.toString(msg.arg1)); 3294 sb.append(" "); 3295 sb.append(Integer.toString(msg.arg2)); 3296 sb.append(" txpkts=").append(mWifiInfo.txSuccess); 3297 sb.append(",").append(mWifiInfo.txBad); 3298 sb.append(",").append(mWifiInfo.txRetries); 3299 break; 3300 case DhcpStateMachine.CMD_POST_DHCP_ACTION: 3301 sb.append(" "); 3302 sb.append(Integer.toString(msg.arg1)); 3303 sb.append(" "); 3304 sb.append(Integer.toString(msg.arg2)); 3305 if (msg.arg1 == DhcpStateMachine.DHCP_SUCCESS) { 3306 sb.append(" OK "); 3307 } else if (msg.arg1 == DhcpStateMachine.DHCP_FAILURE) { 3308 sb.append(" FAIL "); 3309 } 3310 if (mLinkProperties != null) { 3311 sb.append(" "); 3312 sb.append(getLinkPropertiesSummary(mLinkProperties)); 3313 } 3314 break; 3315 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 3316 sb.append(" "); 3317 sb.append(Integer.toString(msg.arg1)); 3318 sb.append(" "); 3319 sb.append(Integer.toString(msg.arg2)); 3320 if (msg.obj != null) { 3321 NetworkInfo info = (NetworkInfo) msg.obj; 3322 NetworkInfo.State state = info.getState(); 3323 NetworkInfo.DetailedState detailedState = info.getDetailedState(); 3324 if (state != null) { 3325 sb.append(" st=").append(state); 3326 } 3327 if (detailedState != null) { 3328 sb.append("/").append(detailedState); 3329 } 3330 } 3331 break; 3332 case CMD_IP_CONFIGURATION_LOST: 3333 int count = -1; 3334 WifiConfiguration c = getCurrentWifiConfiguration(); 3335 if (c != null) { 3336 count = c.getNetworkSelectionStatus().getDisableReasonCounter( 3337 WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE); 3338 } 3339 sb.append(" "); 3340 sb.append(Integer.toString(msg.arg1)); 3341 sb.append(" "); 3342 sb.append(Integer.toString(msg.arg2)); 3343 sb.append(" failures: "); 3344 sb.append(Integer.toString(count)); 3345 sb.append("/"); 3346 sb.append(Integer.toString(mWifiConfigStore.getMaxDhcpRetries())); 3347 if (mWifiInfo.getBSSID() != null) { 3348 sb.append(" ").append(mWifiInfo.getBSSID()); 3349 } 3350 sb.append(String.format(" bcn=%d", mRunningBeaconCount)); 3351 break; 3352 case CMD_UPDATE_LINKPROPERTIES: 3353 sb.append(" "); 3354 sb.append(Integer.toString(msg.arg1)); 3355 sb.append(" "); 3356 sb.append(Integer.toString(msg.arg2)); 3357 if (mLinkProperties != null) { 3358 sb.append(" "); 3359 sb.append(getLinkPropertiesSummary(mLinkProperties)); 3360 } 3361 break; 3362 case CMD_IP_REACHABILITY_LOST: 3363 if (msg.obj != null) { 3364 sb.append(" ").append((String) msg.obj); 3365 } 3366 break; 3367 case CMD_SET_COUNTRY_CODE: 3368 sb.append(" "); 3369 sb.append(Integer.toString(msg.arg1)); 3370 sb.append(" "); 3371 sb.append(Integer.toString(msg.arg2)); 3372 if (msg.obj != null) { 3373 sb.append(" ").append((String) msg.obj); 3374 } 3375 break; 3376 case CMD_ROAM_WATCHDOG_TIMER: 3377 sb.append(" "); 3378 sb.append(Integer.toString(msg.arg1)); 3379 sb.append(" "); 3380 sb.append(Integer.toString(msg.arg2)); 3381 sb.append(" cur=").append(roamWatchdogCount); 3382 break; 3383 case CMD_DISCONNECTING_WATCHDOG_TIMER: 3384 sb.append(" "); 3385 sb.append(Integer.toString(msg.arg1)); 3386 sb.append(" "); 3387 sb.append(Integer.toString(msg.arg2)); 3388 sb.append(" cur=").append(disconnectingWatchdogCount); 3389 break; 3390 case CMD_START_RSSI_MONITORING_OFFLOAD: 3391 case CMD_STOP_RSSI_MONITORING_OFFLOAD: 3392 case CMD_RSSI_THRESHOLD_BREACH: 3393 sb.append(" rssi="); 3394 sb.append(Integer.toString(msg.arg1)); 3395 sb.append(" thresholds="); 3396 sb.append(Arrays.toString(mRssiRanges)); 3397 break; 3398 case CMD_USER_SWITCH: 3399 sb.append(" userId="); 3400 sb.append(Integer.toString(msg.arg1)); 3401 break; 3402 case CMD_IPV4_PROVISIONING_SUCCESS: 3403 sb.append(" "); 3404 if (msg.arg1 == DhcpStateMachine.DHCP_SUCCESS) { 3405 sb.append("DHCP_OK"); 3406 } else if (msg.arg1 == CMD_STATIC_IP_SUCCESS) { 3407 sb.append("STATIC_OK"); 3408 } else { 3409 sb.append(Integer.toString(msg.arg1)); 3410 } 3411 break; 3412 case CMD_IPV4_PROVISIONING_FAILURE: 3413 sb.append(" "); 3414 if (msg.arg1 == DhcpStateMachine.DHCP_FAILURE) { 3415 sb.append("DHCP_FAIL"); 3416 } else if (msg.arg1 == CMD_STATIC_IP_FAILURE) { 3417 sb.append("STATIC_FAIL"); 3418 } else { 3419 sb.append(Integer.toString(msg.arg1)); 3420 } 3421 break; 3422 default: 3423 sb.append(" "); 3424 sb.append(Integer.toString(msg.arg1)); 3425 sb.append(" "); 3426 sb.append(Integer.toString(msg.arg2)); 3427 break; 3428 } 3429 3430 return sb.toString(); 3431 } 3432 3433 private void stopPnoOffload() { 3434 3435 // clear the PNO list 3436 if (!mWifiNative.setPnoList(null, WifiStateMachine.this)) { 3437 Log.e(TAG, "Failed to stop pno"); 3438 } 3439 3440 } 3441 3442 3443 private boolean configureSsidWhiteList() { 3444 3445 mWhiteListedSsids = mWifiConfigStore.getWhiteListedSsids(getCurrentWifiConfiguration()); 3446 if (mWhiteListedSsids == null || mWhiteListedSsids.length == 0) { 3447 return true; 3448 } 3449 3450 if (!mWifiNative.setSsidWhitelist(mWhiteListedSsids)) { 3451 loge("configureSsidWhiteList couldnt program SSID list, size " 3452 + mWhiteListedSsids.length); 3453 return false; 3454 } 3455 3456 logd("configureSsidWhiteList success"); 3457 return true; 3458 } 3459 3460 // In associated more, lazy roam will be looking for 5GHz roam candidate 3461 //Fixme: This is for network selection offload , whole function need to be re-written according 3462 // to the new design 3463 private boolean configureLazyRoam() { 3464 /*boolean status; 3465 if (!useHalBasedAutoJoinOffload()) return false; 3466 3467 WifiNative.WifiLazyRoamParams params = new WifiNative.WifiLazyRoamParams(); 3468 //params.A_band_boost_threshold = mWifiConfigStore.bandPreferenceBoostThreshold5.get(); 3469 //params.A_band_penalty_threshold = mWifiConfigStore.bandPreferencePenaltyThreshold5.get(); 3470 params.A_band_boost_factor = mWifiConfigStore.bandPreferenceBoostFactor5; 3471 params.A_band_penalty_factor = mWifiConfigStore.bandPreferencePenaltyFactor5; 3472 params.A_band_max_boost = 65; 3473 params.lazy_roam_hysteresis = 25; 3474 params.alert_roam_rssi_trigger = -75; 3475 3476 if (DBG) { 3477 Log.e(TAG, "configureLazyRoam " + params.toString()); 3478 } 3479 3480 if (!mWifiNative.setLazyRoam(true, params)) { 3481 3482 Log.e(TAG, "configureLazyRoam couldnt program params"); 3483 3484 return false; 3485 } 3486 if (DBG) { 3487 Log.e(TAG, "configureLazyRoam success"); 3488 }*/ 3489 return true; 3490 } 3491 3492 // In associated more, lazy roam will be looking for 5GHz roam candidate 3493 private boolean stopLazyRoam() { 3494 boolean status; 3495 if (!useHalBasedAutoJoinOffload()) return false; 3496 if (DBG) { 3497 Log.e(TAG, "stopLazyRoam"); 3498 } 3499 return mWifiNative.setLazyRoam(false, null); 3500 } 3501 3502 private boolean startGScanConnectedModeOffload(String reason) { 3503 if (DBG) { 3504 if (reason == null) { 3505 reason = ""; 3506 } 3507 logd("startGScanConnectedModeOffload " + reason); 3508 } 3509 stopGScan("startGScanConnectedModeOffload " + reason); 3510 if (!mScreenOn) return false; 3511 3512 if (USE_PAUSE_SCANS) { 3513 mWifiNative.pauseScan(); 3514 } 3515 mPnoEnabled = configurePno(); 3516 if (mPnoEnabled == false) { 3517 if (USE_PAUSE_SCANS) { 3518 mWifiNative.restartScan(); 3519 } 3520 return false; 3521 } 3522 mLazyRoamEnabled = configureLazyRoam(); 3523 if (mLazyRoamEnabled == false) { 3524 if (USE_PAUSE_SCANS) { 3525 mWifiNative.restartScan(); 3526 } 3527 return false; 3528 } 3529 if (mWifiConfigStore.getLastSelectedConfiguration() == null) { 3530 configureSsidWhiteList(); 3531 } 3532 if (!startConnectedGScan(reason)) { 3533 if (USE_PAUSE_SCANS) { 3534 mWifiNative.restartScan(); 3535 } 3536 return false; 3537 } 3538 if (USE_PAUSE_SCANS) { 3539 mWifiNative.restartScan(); 3540 } 3541 mConnectedModeGScanOffloadStarted = true; 3542 if (DBG) { 3543 logd("startGScanConnectedModeOffload success"); 3544 } 3545 return true; 3546 } 3547 3548 private boolean startGScanDisconnectedModeOffload(String reason) { 3549 if (DBG) { 3550 logd("startGScanDisconnectedModeOffload " + reason); 3551 } 3552 stopGScan("startGScanDisconnectedModeOffload " + reason); 3553 if (USE_PAUSE_SCANS) { 3554 mWifiNative.pauseScan(); 3555 } 3556 mPnoEnabled = configurePno(); 3557 if (mPnoEnabled == false) { 3558 if (USE_PAUSE_SCANS) { 3559 mWifiNative.restartScan(); 3560 } 3561 return false; 3562 } 3563 if (!startDisconnectedGScan(reason)) { 3564 if (USE_PAUSE_SCANS) { 3565 mWifiNative.restartScan(); 3566 } 3567 return false; 3568 } 3569 if (USE_PAUSE_SCANS) { 3570 mWifiNative.restartScan(); 3571 } 3572 return true; 3573 } 3574 3575 private boolean configurePno() { 3576 if (!useHalBasedAutoJoinOffload()) return false; 3577 3578 if (mWifiScanner == null) { 3579 log("configurePno: mWifiScanner is null "); 3580 return true; 3581 } 3582 3583 List<WifiNative.WifiPnoNetwork> llist = null; 3584 //TODO: add getPnoList in WifiQualifiedNetworkSelector 3585 //mWifiAutoJoinController.getPnoList(getCurrentWifiConfiguration()); 3586 if (llist == null || llist.size() == 0) { 3587 stopPnoOffload(); 3588 log("configurePno: empty PNO list "); 3589 return true; 3590 } 3591 if (DBG) { 3592 log("configurePno: got llist size " + llist.size()); 3593 } 3594 3595 // first program the network we want to look for thru the pno API 3596 WifiNative.WifiPnoNetwork list[] 3597 = (WifiNative.WifiPnoNetwork[]) llist.toArray(new WifiNative.WifiPnoNetwork[0]); 3598 3599 if (!mWifiNative.setPnoList(list, WifiStateMachine.this)) { 3600 Log.e(TAG, "Failed to set pno, length = " + list.length); 3601 return false; 3602 } 3603 3604 if (true) { 3605 StringBuilder sb = new StringBuilder(); 3606 for (WifiNative.WifiPnoNetwork network : list) { 3607 sb.append("[").append(network.SSID).append(" auth=").append(network.auth); 3608 sb.append(" flags="); 3609 sb.append(network.flags).append(" rssi").append(network.rssi_threshold); 3610 sb.append("] "); 3611 3612 } 3613 sendMessage(CMD_STARTED_PNO_DBG, 1, (int)mGScanPeriodMilli, sb.toString()); 3614 } 3615 return true; 3616 } 3617 3618 final static int DISCONNECTED_SHORT_SCANS_DURATION_MILLI = 2 * 60 * 1000; 3619 final static int CONNECTED_SHORT_SCANS_DURATION_MILLI = 2 * 60 * 1000; 3620 3621 private boolean startConnectedGScan(String reason) { 3622 // send a scan background request so as to kick firmware 3623 // 5GHz roaming and autojoin 3624 // We do this only if screen is on 3625 WifiScanner.ScanSettings settings; 3626 3627 if (mPnoEnabled || mLazyRoamEnabled) { 3628 settings = new WifiScanner.ScanSettings(); 3629 settings.band = WifiScanner.WIFI_BAND_BOTH; 3630 long now = System.currentTimeMillis(); 3631 3632 if (!mScreenOn || (mGScanStartTimeMilli!= 0 && now > mGScanStartTimeMilli 3633 && ((now - mGScanStartTimeMilli) > CONNECTED_SHORT_SCANS_DURATION_MILLI))) { 3634 settings.periodInMs = mWifiConfigStore.wifiAssociatedLongScanIntervalMilli.get(); 3635 } else { 3636 mGScanStartTimeMilli = now; 3637 settings.periodInMs = mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(); 3638 // if we start offload with short interval, then reconfigure it after a given 3639 // duration of time so as to reduce the scan frequency 3640 int delay = 30 * 1000 + CONNECTED_SHORT_SCANS_DURATION_MILLI; 3641 sendMessageDelayed(CMD_RESTART_AUTOJOIN_OFFLOAD, delay, 3642 mRestartAutoJoinOffloadCounter, " startConnectedGScan " + reason, 3643 (long)delay); 3644 mRestartAutoJoinOffloadCounter++; 3645 } 3646 mGScanPeriodMilli = settings.periodInMs; 3647 settings.reportEvents = WifiScanner.REPORT_EVENT_AFTER_BUFFER_FULL; 3648 if (DBG) { 3649 log("startConnectedScan: settings band="+ settings.band 3650 + " period=" + settings.periodInMs); 3651 } 3652 3653 mWifiScanner.startBackgroundScan(settings, mWifiScanListener); 3654 if (true) { 3655 sendMessage(CMD_STARTED_GSCAN_DBG, 1, (int)mGScanPeriodMilli, reason); 3656 } 3657 } 3658 return true; 3659 } 3660 3661 private boolean startDisconnectedGScan(String reason) { 3662 // send a scan background request so as to kick firmware 3663 // PNO 3664 // This is done in both screen On and screen Off modes 3665 WifiScanner.ScanSettings settings; 3666 3667 if (mWifiScanner == null) { 3668 log("startDisconnectedGScan: no wifi scanner"); 3669 return false; 3670 } 3671 3672 if (mPnoEnabled || mLazyRoamEnabled) { 3673 settings = new WifiScanner.ScanSettings(); 3674 settings.band = WifiScanner.WIFI_BAND_BOTH; 3675 long now = System.currentTimeMillis(); 3676 3677 3678 if (!mScreenOn || (mGScanStartTimeMilli != 0 && now > mGScanStartTimeMilli 3679 && ((now - mGScanStartTimeMilli) > DISCONNECTED_SHORT_SCANS_DURATION_MILLI))) { 3680 settings.periodInMs = mWifiConfigStore.wifiDisconnectedLongScanIntervalMilli.get(); 3681 } else { 3682 settings.periodInMs = mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get(); 3683 mGScanStartTimeMilli = now; 3684 // if we start offload with short interval, then reconfigure it after a given 3685 // duration of time so as to reduce the scan frequency 3686 int delay = 30 * 1000 + DISCONNECTED_SHORT_SCANS_DURATION_MILLI; 3687 sendMessageDelayed(CMD_RESTART_AUTOJOIN_OFFLOAD, delay, 3688 mRestartAutoJoinOffloadCounter, " startDisconnectedGScan " + reason, 3689 (long)delay); 3690 mRestartAutoJoinOffloadCounter++; 3691 } 3692 mGScanPeriodMilli = settings.periodInMs; 3693 settings.reportEvents = WifiScanner.REPORT_EVENT_AFTER_BUFFER_FULL; 3694 if (DBG) { 3695 log("startDisconnectedScan: settings band="+ settings.band 3696 + " period=" + settings.periodInMs); 3697 } 3698 mWifiScanner.startBackgroundScan(settings, mWifiScanListener); 3699 if (true) { 3700 sendMessage(CMD_STARTED_GSCAN_DBG, 1, (int)mGScanPeriodMilli, reason); 3701 } 3702 } 3703 return true; 3704 } 3705 3706 private boolean stopGScan(String reason) { 3707 mGScanStartTimeMilli = 0; 3708 mGScanPeriodMilli = 0; 3709 if (mWifiScanner != null) { 3710 mWifiScanner.stopBackgroundScan(mWifiScanListener); 3711 } 3712 mConnectedModeGScanOffloadStarted = false; 3713 if (true) { 3714 sendMessage(CMD_STARTED_GSCAN_DBG, 0, 0, reason); 3715 } 3716 return true; 3717 } 3718 3719 private void handleScreenStateChanged(boolean screenOn) { 3720 mScreenOn = screenOn; 3721 if (PDBG) { 3722 logd(" handleScreenStateChanged Enter: screenOn=" + screenOn 3723 + " mUserWantsSuspendOpt=" + mUserWantsSuspendOpt 3724 + " state " + getCurrentState().getName() 3725 + " suppState:" + mSupplicantStateTracker.getSupplicantStateName()); 3726 } 3727 enableRssiPolling(screenOn); 3728 if (mUserWantsSuspendOpt.get()) { 3729 if (screenOn) { 3730 sendMessage(CMD_SET_SUSPEND_OPT_ENABLED, 0, 0); 3731 } else { 3732 // Allow 2s for suspend optimizations to be set 3733 mSuspendWakeLock.acquire(2000); 3734 sendMessage(CMD_SET_SUSPEND_OPT_ENABLED, 1, 0); 3735 } 3736 } 3737 mScreenBroadcastReceived.set(true); 3738 3739 getWifiLinkLayerStats(false); 3740 mOnTimeScreenStateChange = mOnTime; 3741 lastScreenStateChangeTimeStamp = lastLinkLayerStatsUpdate; 3742 3743 cancelDelayedScan(); 3744 3745 if (screenOn) { 3746 enableBackgroundScan(false); 3747 setScanAlarm(false); 3748 clearBlacklist(); 3749 3750 fullBandConnectedTimeIntervalMilli 3751 = mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(); 3752 // In either Disconnectedstate or ConnectedState, 3753 // start the scan alarm so as to enable autojoin 3754 if (getCurrentState() == mConnectedState 3755 && allowFullBandScanAndAssociated()) { 3756 if (useHalBasedAutoJoinOffload()) { 3757 startGScanConnectedModeOffload("screenOnConnected"); 3758 } else { 3759 // Scan after 500ms 3760 startDelayedScan(500, null, null); 3761 } 3762 } else if (getCurrentState() == mDisconnectedState) { 3763 if (useHalBasedAutoJoinOffload()) { 3764 startGScanDisconnectedModeOffload("screenOnDisconnected"); 3765 } else { 3766 // Scan after 500ms 3767 startDelayedScan(500, null, null); 3768 } 3769 } 3770 } else { 3771 if (getCurrentState() == mDisconnectedState) { 3772 // Screen Off and Disconnected and chipset doesn't support scan offload 3773 // => start scan alarm 3774 // Screen Off and Disconnected and chipset does support scan offload 3775 // => will use scan offload (i.e. background scan) 3776 if (useHalBasedAutoJoinOffload()) { 3777 startGScanDisconnectedModeOffload("screenOffDisconnected"); 3778 } else { 3779 if (!mBackgroundScanSupported) { 3780 setScanAlarm(true); 3781 } else { 3782 if (!mIsScanOngoing) { 3783 enableBackgroundScan(true); 3784 } 3785 } 3786 } 3787 } else { 3788 enableBackgroundScan(false); 3789 if (useHalBasedAutoJoinOffload()) { 3790 // don't try stop Gscan if it is not enabled 3791 stopGScan("ScreenOffStop(enableBackground=" + mLegacyPnoEnabled + ") "); 3792 } 3793 } 3794 } 3795 if (DBG) logd("backgroundScan enabled=" + mLegacyPnoEnabled); 3796 3797 if (DBG) log("handleScreenStateChanged Exit: " + screenOn); 3798 } 3799 3800 private void checkAndSetConnectivityInstance() { 3801 if (mCm == null) { 3802 mCm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); 3803 } 3804 } 3805 3806 private boolean startTethering(ArrayList<String> available) { 3807 3808 boolean wifiAvailable = false; 3809 3810 checkAndSetConnectivityInstance(); 3811 3812 String[] wifiRegexs = mCm.getTetherableWifiRegexs(); 3813 3814 for (String intf : available) { 3815 for (String regex : wifiRegexs) { 3816 if (intf.matches(regex)) { 3817 3818 InterfaceConfiguration ifcg = null; 3819 try { 3820 ifcg = mNwService.getInterfaceConfig(intf); 3821 if (ifcg != null) { 3822 /* IP/netmask: 192.168.43.1/255.255.255.0 */ 3823 ifcg.setLinkAddress(new LinkAddress( 3824 NetworkUtils.numericToInetAddress("192.168.43.1"), 24)); 3825 ifcg.setInterfaceUp(); 3826 3827 mNwService.setInterfaceConfig(intf, ifcg); 3828 } 3829 } catch (Exception e) { 3830 loge("Error configuring interface " + intf + ", :" + e); 3831 return false; 3832 } 3833 3834 if (mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) { 3835 loge("Error tethering on " + intf); 3836 return false; 3837 } 3838 mTetherInterfaceName = intf; 3839 return true; 3840 } 3841 } 3842 } 3843 // We found no interfaces to tether 3844 return false; 3845 } 3846 3847 private void stopTethering() { 3848 3849 checkAndSetConnectivityInstance(); 3850 3851 /* Clear the interface config to allow dhcp correctly configure new 3852 ip settings */ 3853 InterfaceConfiguration ifcg = null; 3854 try { 3855 ifcg = mNwService.getInterfaceConfig(mTetherInterfaceName); 3856 if (ifcg != null) { 3857 ifcg.setLinkAddress( 3858 new LinkAddress(NetworkUtils.numericToInetAddress("0.0.0.0"), 0)); 3859 mNwService.setInterfaceConfig(mTetherInterfaceName, ifcg); 3860 } 3861 } catch (Exception e) { 3862 loge("Error resetting interface " + mTetherInterfaceName + ", :" + e); 3863 } 3864 3865 if (mCm.untether(mTetherInterfaceName) != ConnectivityManager.TETHER_ERROR_NO_ERROR) { 3866 loge("Untether initiate failed!"); 3867 } 3868 } 3869 3870 private boolean isWifiTethered(ArrayList<String> active) { 3871 3872 checkAndSetConnectivityInstance(); 3873 3874 String[] wifiRegexs = mCm.getTetherableWifiRegexs(); 3875 for (String intf : active) { 3876 for (String regex : wifiRegexs) { 3877 if (intf.matches(regex)) { 3878 return true; 3879 } 3880 } 3881 } 3882 // We found no interfaces that are tethered 3883 return false; 3884 } 3885 3886 /** 3887 * Set the country code from the system setting value, if any. 3888 */ 3889 private void initializeCountryCode() { 3890 String countryCode = getCurrentCountryCode(); 3891 if (countryCode != null && !countryCode.isEmpty()) { 3892 setCountryCode(countryCode, false); 3893 } else { 3894 //use driver default 3895 } 3896 } 3897 3898 /** 3899 * Set the frequency band from the system setting value, if any. 3900 */ 3901 private void setFrequencyBand() { 3902 int band = mFacade.getIntegerSetting(mContext, 3903 Settings.Global.WIFI_FREQUENCY_BAND, WifiManager.WIFI_FREQUENCY_BAND_AUTO); 3904 3905 if (mWifiNative.setBand(band)) { 3906 mFrequencyBand.set(band); 3907 if (PDBG) { 3908 logd("done set frequency band " + band); 3909 mWifiQualifiedNetworkSelector.setUserPreferredBand(band); 3910 } 3911 } else { 3912 loge("Failed to set frequency band " + band); 3913 } 3914 } 3915 3916 private void setSuspendOptimizationsNative(int reason, boolean enabled) { 3917 if (DBG) { 3918 log("setSuspendOptimizationsNative: " + reason + " " + enabled 3919 + " -want " + mUserWantsSuspendOpt.get() 3920 + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName() 3921 + " - " + Thread.currentThread().getStackTrace()[3].getMethodName() 3922 + " - " + Thread.currentThread().getStackTrace()[4].getMethodName() 3923 + " - " + Thread.currentThread().getStackTrace()[5].getMethodName()); 3924 } 3925 //mWifiNative.setSuspendOptimizations(enabled); 3926 3927 if (enabled) { 3928 mSuspendOptNeedsDisabled &= ~reason; 3929 /* None of dhcp, screen or highperf need it disabled and user wants it enabled */ 3930 if (mSuspendOptNeedsDisabled == 0 && mUserWantsSuspendOpt.get()) { 3931 if (DBG) { 3932 log("setSuspendOptimizationsNative do it " + reason + " " + enabled 3933 + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName() 3934 + " - " + Thread.currentThread().getStackTrace()[3].getMethodName() 3935 + " - " + Thread.currentThread().getStackTrace()[4].getMethodName() 3936 + " - " + Thread.currentThread().getStackTrace()[5].getMethodName()); 3937 } 3938 mWifiNative.setSuspendOptimizations(true); 3939 } 3940 } else { 3941 mSuspendOptNeedsDisabled |= reason; 3942 mWifiNative.setSuspendOptimizations(false); 3943 } 3944 } 3945 3946 private void setSuspendOptimizations(int reason, boolean enabled) { 3947 if (DBG) log("setSuspendOptimizations: " + reason + " " + enabled); 3948 if (enabled) { 3949 mSuspendOptNeedsDisabled &= ~reason; 3950 } else { 3951 mSuspendOptNeedsDisabled |= reason; 3952 } 3953 if (DBG) log("mSuspendOptNeedsDisabled " + mSuspendOptNeedsDisabled); 3954 } 3955 3956 private void setWifiState(int wifiState) { 3957 final int previousWifiState = mWifiState.get(); 3958 3959 try { 3960 if (wifiState == WIFI_STATE_ENABLED) { 3961 mBatteryStats.noteWifiOn(); 3962 } else if (wifiState == WIFI_STATE_DISABLED) { 3963 mBatteryStats.noteWifiOff(); 3964 } 3965 } catch (RemoteException e) { 3966 loge("Failed to note battery stats in wifi"); 3967 } 3968 3969 mWifiState.set(wifiState); 3970 3971 if (DBG) log("setWifiState: " + syncGetWifiStateByName()); 3972 3973 final Intent intent = new Intent(WifiManager.WIFI_STATE_CHANGED_ACTION); 3974 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 3975 intent.putExtra(WifiManager.EXTRA_WIFI_STATE, wifiState); 3976 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_STATE, previousWifiState); 3977 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 3978 } 3979 3980 private void setWifiApState(int wifiApState, int reason) { 3981 final int previousWifiApState = mWifiApState.get(); 3982 3983 try { 3984 if (wifiApState == WIFI_AP_STATE_ENABLED) { 3985 mBatteryStats.noteWifiOn(); 3986 } else if (wifiApState == WIFI_AP_STATE_DISABLED) { 3987 mBatteryStats.noteWifiOff(); 3988 } 3989 } catch (RemoteException e) { 3990 loge("Failed to note battery stats in wifi"); 3991 } 3992 3993 // Update state 3994 mWifiApState.set(wifiApState); 3995 3996 if (DBG) log("setWifiApState: " + syncGetWifiApStateByName()); 3997 3998 final Intent intent = new Intent(WifiManager.WIFI_AP_STATE_CHANGED_ACTION); 3999 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4000 intent.putExtra(WifiManager.EXTRA_WIFI_AP_STATE, wifiApState); 4001 intent.putExtra(WifiManager.EXTRA_PREVIOUS_WIFI_AP_STATE, previousWifiApState); 4002 if (wifiApState == WifiManager.WIFI_AP_STATE_FAILED) { 4003 //only set reason number when softAP start failed 4004 intent.putExtra(WifiManager.EXTRA_WIFI_AP_FAILURE_REASON, reason); 4005 } 4006 4007 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 4008 } 4009 4010 private void setScanResults() { 4011 mNumScanResultsKnown = 0; 4012 mNumScanResultsReturned = 0; 4013 4014 ArrayList<ScanDetail> scanResults = mWifiNative.getScanResults(); 4015 4016 if (scanResults.isEmpty()) { 4017 mScanResults = new ArrayList<>(); 4018 return; 4019 } 4020 4021 mWifiConfigStore.trimANQPCache(false); 4022 4023 boolean connected = mLastBssid != null; 4024 long activeBssid = 0L; 4025 if (connected) { 4026 try { 4027 activeBssid = Utils.parseMac(mLastBssid); 4028 } catch (IllegalArgumentException iae) { 4029 connected = false; 4030 } 4031 } 4032 4033 synchronized (mScanResultCache) { 4034 ScanDetail activeScanDetail = null; 4035 mScanResults = scanResults; 4036 mNumScanResultsReturned = mScanResults.size(); 4037 for (ScanDetail resultDetail : mScanResults) { 4038 mScanResultCache.put(resultDetail.getNetworkDetail(), resultDetail); 4039 if (connected && resultDetail.getNetworkDetail().getBSSID() == activeBssid) { 4040 if (activeScanDetail == null 4041 || activeScanDetail.getNetworkDetail().getBSSID() != activeBssid 4042 || activeScanDetail.getNetworkDetail().getANQPElements() == null) { 4043 activeScanDetail = resultDetail; 4044 } 4045 } 4046 } 4047 mActiveScanDetail = activeScanDetail; 4048 } 4049 if (mNumScanResultsReturned > 0) { 4050 mWifiMetrics.incrementNonEmptyScanResultCount(); 4051 } else { 4052 mWifiMetrics.incrementEmptyScanResultCount(); 4053 } 4054 4055 if (linkDebouncing) { 4056 // If debouncing, we dont re-select a SSID or BSSID hence 4057 // there is no need to call the network selection code 4058 // in WifiAutoJoinController, instead, 4059 // just try to reconnect to the same SSID by triggering a roam 4060 // The third parameter 1 means roam not from network selection but debouncing 4061 sendMessage(CMD_AUTO_ROAM, mLastNetworkId, 1, null); 4062 } else { 4063 WifiConfiguration candidate = 4064 mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, 4065 mAllowUntrustedConnections, mScanResults, linkDebouncing, isConnected(), 4066 isDisconnected(), isSupplicantTransientState()); 4067 tryToConnectToNetwork(candidate); 4068 } 4069 } 4070 4071 /** 4072 * Set whether connections to untrusted connections are allowed. 4073 */ 4074 void setAllowUntrustedConnections(boolean allow) { 4075 boolean changed = (mAllowUntrustedConnections != allow); 4076 mAllowUntrustedConnections = allow; 4077 if (changed) { 4078 // Trigger a scan so as to reattempt autojoin 4079 startScanForUntrustedSettingChange(); 4080 } 4081 } 4082 4083 public ScanDetail getActiveScanDetail() { 4084 synchronized (mScanResultCache) { 4085 return mActiveScanDetail; 4086 } 4087 } 4088 4089 /* 4090 * Fetch RSSI, linkspeed, and frequency on current connection 4091 */ 4092 private void fetchRssiLinkSpeedAndFrequencyNative() { 4093 Integer newRssi = null; 4094 Integer newLinkSpeed = null; 4095 Integer newFrequency = null; 4096 4097 String signalPoll = mWifiNative.signalPoll(); 4098 4099 if (signalPoll != null) { 4100 String[] lines = signalPoll.split("\n"); 4101 for (String line : lines) { 4102 String[] prop = line.split("="); 4103 if (prop.length < 2) continue; 4104 try { 4105 if (prop[0].equals("RSSI")) { 4106 newRssi = Integer.parseInt(prop[1]); 4107 } else if (prop[0].equals("LINKSPEED")) { 4108 newLinkSpeed = Integer.parseInt(prop[1]); 4109 } else if (prop[0].equals("FREQUENCY")) { 4110 newFrequency = Integer.parseInt(prop[1]); 4111 } 4112 } catch (NumberFormatException e) { 4113 //Ignore, defaults on rssi and linkspeed are assigned 4114 } 4115 } 4116 } 4117 4118 if (PDBG) { 4119 logd("fetchRssiLinkSpeedAndFrequencyNative rssi=" + newRssi + 4120 " linkspeed=" + newLinkSpeed + " freq=" + newFrequency); 4121 } 4122 4123 if (newRssi != null && newRssi > WifiInfo.INVALID_RSSI && newRssi < WifiInfo.MAX_RSSI) { 4124 // screen out invalid values 4125 /* some implementations avoid negative values by adding 256 4126 * so we need to adjust for that here. 4127 */ 4128 if (newRssi > 0) newRssi -= 256; 4129 mWifiInfo.setRssi(newRssi); 4130 /* 4131 * Rather then sending the raw RSSI out every time it 4132 * changes, we precalculate the signal level that would 4133 * be displayed in the status bar, and only send the 4134 * broadcast if that much more coarse-grained number 4135 * changes. This cuts down greatly on the number of 4136 * broadcasts, at the cost of not informing others 4137 * interested in RSSI of all the changes in signal 4138 * level. 4139 */ 4140 int newSignalLevel = WifiManager.calculateSignalLevel(newRssi, WifiManager.RSSI_LEVELS); 4141 if (newSignalLevel != mLastSignalLevel) { 4142 updateCapabilities(getCurrentWifiConfiguration()); 4143 sendRssiChangeBroadcast(newRssi); 4144 } 4145 mLastSignalLevel = newSignalLevel; 4146 } else { 4147 mWifiInfo.setRssi(WifiInfo.INVALID_RSSI); 4148 updateCapabilities(getCurrentWifiConfiguration()); 4149 } 4150 4151 if (newLinkSpeed != null) { 4152 mWifiInfo.setLinkSpeed(newLinkSpeed); 4153 } 4154 if (newFrequency != null && newFrequency > 0) { 4155 if (ScanResult.is5GHz(newFrequency)) { 4156 mWifiConnectionStatistics.num5GhzConnected++; 4157 } 4158 if (ScanResult.is24GHz(newFrequency)) { 4159 mWifiConnectionStatistics.num24GhzConnected++; 4160 } 4161 mWifiInfo.setFrequency(newFrequency); 4162 } 4163 mWifiConfigStore.updateConfiguration(mWifiInfo); 4164 } 4165 4166 /** 4167 * Determine if we need to switch network: 4168 * - the delta determine the urgency to switch and/or or the expected evilness of the disruption 4169 * - match the uregncy of the switch versus the packet usage at the interface 4170 */ 4171 boolean shouldSwitchNetwork(int networkDelta) { 4172 int delta; 4173 if (networkDelta <= 0) { 4174 return false; 4175 } 4176 delta = networkDelta; 4177 if (mWifiInfo != null) { 4178 if (!getEnableAutoJoinWhenAssociated() 4179 && mWifiInfo.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID) { 4180 // If AutoJoin while associated is not enabled, 4181 // we should never switch network when already associated 4182 delta = -1000; 4183 } else { 4184 // TODO: Look at per AC packet count, do not switch if VO/VI traffic is present 4185 // TODO: at the interface. We should also discriminate between ucast and mcast, 4186 // TODO: since the rxSuccessRate include all the bonjour and Ipv6 4187 // TODO: broadcasts 4188 if ((mWifiInfo.txSuccessRate > 20) || (mWifiInfo.rxSuccessRate > 80)) { 4189 delta -= 999; 4190 } else if ((mWifiInfo.txSuccessRate > 5) || (mWifiInfo.rxSuccessRate > 30)) { 4191 delta -= 6; 4192 } 4193 logd("shouldSwitchNetwork " 4194 + " txSuccessRate=" + String.format("%.2f", mWifiInfo.txSuccessRate) 4195 + " rxSuccessRate=" + String.format("%.2f", mWifiInfo.rxSuccessRate) 4196 + " delta " + networkDelta + " -> " + delta); 4197 } 4198 } else { 4199 logd("shouldSwitchNetwork " 4200 + " delta " + networkDelta + " -> " + delta); 4201 } 4202 if (delta > 0) { 4203 return true; 4204 } 4205 return false; 4206 } 4207 4208 // Polling has completed, hence we wont have a score anymore 4209 private void cleanWifiScore() { 4210 mWifiInfo.txBadRate = 0; 4211 mWifiInfo.txSuccessRate = 0; 4212 mWifiInfo.txRetriesRate = 0; 4213 mWifiInfo.rxSuccessRate = 0; 4214 } 4215 4216 int mBadLinkspeedcount = 0; 4217 4218 // For debug, provide information about the last scoring operation 4219 String wifiScoringReport = null; 4220 4221 private void calculateWifiScore(WifiLinkLayerStats stats) { 4222 StringBuilder sb = new StringBuilder(); 4223 4224 int score = 56; // Starting score, temporarily hardcoded in between 50 and 60 4225 boolean isBadLinkspeed = (mWifiInfo.is24GHz() 4226 && mWifiInfo.getLinkSpeed() < mWifiConfigStore.badLinkSpeed24) 4227 || (mWifiInfo.is5GHz() && mWifiInfo.getLinkSpeed() 4228 < mWifiConfigStore.badLinkSpeed5); 4229 boolean isGoodLinkspeed = (mWifiInfo.is24GHz() 4230 && mWifiInfo.getLinkSpeed() >= mWifiConfigStore.goodLinkSpeed24) 4231 || (mWifiInfo.is5GHz() && mWifiInfo.getLinkSpeed() 4232 >= mWifiConfigStore.goodLinkSpeed5); 4233 4234 if (isBadLinkspeed) { 4235 if (mBadLinkspeedcount < 6) 4236 mBadLinkspeedcount++; 4237 } else { 4238 if (mBadLinkspeedcount > 0) 4239 mBadLinkspeedcount--; 4240 } 4241 4242 if (isBadLinkspeed) sb.append(" bl(").append(mBadLinkspeedcount).append(")"); 4243 if (isGoodLinkspeed) sb.append(" gl"); 4244 4245 /** 4246 * We want to make sure that we use the 24GHz RSSI thresholds if 4247 * there are 2.4GHz scan results 4248 * otherwise we end up lowering the score based on 5GHz values 4249 * which may cause a switch to LTE before roaming has a chance to try 2.4GHz 4250 * We also might unblacklist the configuation based on 2.4GHz 4251 * thresholds but joining 5GHz anyhow, and failing over to 2.4GHz because 5GHz is not good 4252 */ 4253 boolean use24Thresholds = false; 4254 boolean homeNetworkBoost = false; 4255 WifiConfiguration currentConfiguration = getCurrentWifiConfiguration(); 4256 ScanDetailCache scanDetailCache = 4257 mWifiConfigStore.getScanDetailCache(currentConfiguration); 4258 if (currentConfiguration != null && scanDetailCache != null) { 4259 currentConfiguration.setVisibility(scanDetailCache.getVisibility(12000)); 4260 if (currentConfiguration.visibility != null) { 4261 if (currentConfiguration.visibility.rssi24 != WifiConfiguration.INVALID_RSSI 4262 && currentConfiguration.visibility.rssi24 4263 >= (currentConfiguration.visibility.rssi5 - 2)) { 4264 use24Thresholds = true; 4265 } 4266 } 4267 if (scanDetailCache.size() <= 6 4268 && currentConfiguration.allowedKeyManagement.cardinality() == 1 4269 && currentConfiguration.allowedKeyManagement. 4270 get(WifiConfiguration.KeyMgmt.WPA_PSK) == true) { 4271 // A PSK network with less than 6 known BSSIDs 4272 // This is most likely a home network and thus we want to stick to wifi more 4273 homeNetworkBoost = true; 4274 } 4275 } 4276 if (homeNetworkBoost) sb.append(" hn"); 4277 if (use24Thresholds) sb.append(" u24"); 4278 4279 int rssi = mWifiInfo.getRssi() - 6 * mAggressiveHandover 4280 + (homeNetworkBoost ? WifiConfiguration.HOME_NETWORK_RSSI_BOOST : 0); 4281 sb.append(String.format(" rssi=%d ag=%d", rssi, mAggressiveHandover)); 4282 4283 boolean is24GHz = use24Thresholds || mWifiInfo.is24GHz(); 4284 4285 boolean isBadRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdMinimumRssi24.get()) 4286 || (!is24GHz && rssi < mWifiConfigStore.thresholdMinimumRssi5.get()); 4287 boolean isLowRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdQualifiedRssi24.get()) 4288 || (!is24GHz && mWifiInfo.getRssi() < mWifiConfigStore.thresholdMinimumRssi5.get()); 4289 boolean isHighRSSI = (is24GHz && rssi >= mWifiConfigStore.thresholdSaturatedRssi24.get()) 4290 || (!is24GHz && mWifiInfo.getRssi() 4291 >= mWifiConfigStore.thresholdSaturatedRssi5.get()); 4292 4293 if (isBadRSSI) sb.append(" br"); 4294 if (isLowRSSI) sb.append(" lr"); 4295 if (isHighRSSI) sb.append(" hr"); 4296 4297 int penalizedDueToUserTriggeredDisconnect = 0; // For debug information 4298 if (currentConfiguration != null && 4299 (mWifiInfo.txSuccessRate > 5 || mWifiInfo.rxSuccessRate > 5)) { 4300 if (isBadRSSI) { 4301 currentConfiguration.numTicksAtBadRSSI++; 4302 if (currentConfiguration.numTicksAtBadRSSI > 1000) { 4303 // We remained associated for a compound amount of time while passing 4304 // traffic, hence loose the corresponding user triggered disabled stats 4305 if (currentConfiguration.numUserTriggeredWifiDisableBadRSSI > 0) { 4306 currentConfiguration.numUserTriggeredWifiDisableBadRSSI--; 4307 } 4308 if (currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0) { 4309 currentConfiguration.numUserTriggeredWifiDisableLowRSSI--; 4310 } 4311 if (currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) { 4312 currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI--; 4313 } 4314 currentConfiguration.numTicksAtBadRSSI = 0; 4315 } 4316 if (mWifiConfigStore.enableWifiCellularHandoverUserTriggeredAdjustment && 4317 (currentConfiguration.numUserTriggeredWifiDisableBadRSSI > 0 4318 || currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0 4319 || currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0)) { 4320 score = score - 5; 4321 penalizedDueToUserTriggeredDisconnect = 1; 4322 sb.append(" p1"); 4323 } 4324 } else if (isLowRSSI) { 4325 currentConfiguration.numTicksAtLowRSSI++; 4326 if (currentConfiguration.numTicksAtLowRSSI > 1000) { 4327 // We remained associated for a compound amount of time while passing 4328 // traffic, hence loose the corresponding user triggered disabled stats 4329 if (currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0) { 4330 currentConfiguration.numUserTriggeredWifiDisableLowRSSI--; 4331 } 4332 if (currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) { 4333 currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI--; 4334 } 4335 currentConfiguration.numTicksAtLowRSSI = 0; 4336 } 4337 if (mWifiConfigStore.enableWifiCellularHandoverUserTriggeredAdjustment && 4338 (currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0 4339 || currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0)) { 4340 score = score - 5; 4341 penalizedDueToUserTriggeredDisconnect = 2; 4342 sb.append(" p2"); 4343 } 4344 } else if (!isHighRSSI) { 4345 currentConfiguration.numTicksAtNotHighRSSI++; 4346 if (currentConfiguration.numTicksAtNotHighRSSI > 1000) { 4347 // We remained associated for a compound amount of time while passing 4348 // traffic, hence loose the corresponding user triggered disabled stats 4349 if (currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) { 4350 currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI--; 4351 } 4352 currentConfiguration.numTicksAtNotHighRSSI = 0; 4353 } 4354 if (mWifiConfigStore.enableWifiCellularHandoverUserTriggeredAdjustment && 4355 currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) { 4356 score = score - 5; 4357 penalizedDueToUserTriggeredDisconnect = 3; 4358 sb.append(" p3"); 4359 } 4360 } 4361 sb.append(String.format(" ticks %d,%d,%d", currentConfiguration.numTicksAtBadRSSI, 4362 currentConfiguration.numTicksAtLowRSSI, 4363 currentConfiguration.numTicksAtNotHighRSSI)); 4364 } 4365 4366 if (PDBG) { 4367 String rssiStatus = ""; 4368 if (isBadRSSI) rssiStatus += " badRSSI "; 4369 else if (isHighRSSI) rssiStatus += " highRSSI "; 4370 else if (isLowRSSI) rssiStatus += " lowRSSI "; 4371 if (isBadLinkspeed) rssiStatus += " lowSpeed "; 4372 logd("calculateWifiScore freq=" + Integer.toString(mWifiInfo.getFrequency()) 4373 + " speed=" + Integer.toString(mWifiInfo.getLinkSpeed()) 4374 + " score=" + Integer.toString(mWifiInfo.score) 4375 + rssiStatus 4376 + " -> txbadrate=" + String.format("%.2f", mWifiInfo.txBadRate) 4377 + " txgoodrate=" + String.format("%.2f", mWifiInfo.txSuccessRate) 4378 + " txretriesrate=" + String.format("%.2f", mWifiInfo.txRetriesRate) 4379 + " rxrate=" + String.format("%.2f", mWifiInfo.rxSuccessRate) 4380 + " userTriggerdPenalty" + penalizedDueToUserTriggeredDisconnect); 4381 } 4382 4383 if ((mWifiInfo.txBadRate >= 1) && (mWifiInfo.txSuccessRate < 3) 4384 && (isBadRSSI || isLowRSSI)) { 4385 // Link is stuck 4386 if (mWifiInfo.linkStuckCount < 5) 4387 mWifiInfo.linkStuckCount += 1; 4388 sb.append(String.format(" ls+=%d", mWifiInfo.linkStuckCount)); 4389 if (PDBG) logd(" bad link -> stuck count =" 4390 + Integer.toString(mWifiInfo.linkStuckCount)); 4391 } else if (mWifiInfo.txBadRate < 0.3) { 4392 if (mWifiInfo.linkStuckCount > 0) 4393 mWifiInfo.linkStuckCount -= 1; 4394 sb.append(String.format(" ls-=%d", mWifiInfo.linkStuckCount)); 4395 if (PDBG) logd(" good link -> stuck count =" 4396 + Integer.toString(mWifiInfo.linkStuckCount)); 4397 } 4398 4399 sb.append(String.format(" [%d", score)); 4400 4401 if (mWifiInfo.linkStuckCount > 1) { 4402 // Once link gets stuck for more than 3 seconds, start reducing the score 4403 score = score - 2 * (mWifiInfo.linkStuckCount - 1); 4404 } 4405 sb.append(String.format(",%d", score)); 4406 4407 if (isBadLinkspeed) { 4408 score -= 4; 4409 if (PDBG) { 4410 logd(" isBadLinkspeed ---> count=" + mBadLinkspeedcount 4411 + " score=" + Integer.toString(score)); 4412 } 4413 } else if ((isGoodLinkspeed) && (mWifiInfo.txSuccessRate > 5)) { 4414 score += 4; // So as bad rssi alone dont kill us 4415 } 4416 sb.append(String.format(",%d", score)); 4417 4418 if (isBadRSSI) { 4419 if (mWifiInfo.badRssiCount < 7) 4420 mWifiInfo.badRssiCount += 1; 4421 } else if (isLowRSSI) { 4422 mWifiInfo.lowRssiCount = 1; // Dont increment the lowRssi count above 1 4423 if (mWifiInfo.badRssiCount > 0) { 4424 // Decrement bad Rssi count 4425 mWifiInfo.badRssiCount -= 1; 4426 } 4427 } else { 4428 mWifiInfo.badRssiCount = 0; 4429 mWifiInfo.lowRssiCount = 0; 4430 } 4431 4432 score -= mWifiInfo.badRssiCount * 2 + mWifiInfo.lowRssiCount; 4433 sb.append(String.format(",%d", score)); 4434 4435 if (PDBG) logd(" badRSSI count" + Integer.toString(mWifiInfo.badRssiCount) 4436 + " lowRSSI count" + Integer.toString(mWifiInfo.lowRssiCount) 4437 + " --> score " + Integer.toString(score)); 4438 4439 4440 if (isHighRSSI) { 4441 score += 5; 4442 if (PDBG) logd(" isHighRSSI ---> score=" + Integer.toString(score)); 4443 } 4444 sb.append(String.format(",%d]", score)); 4445 4446 sb.append(String.format(" brc=%d lrc=%d", mWifiInfo.badRssiCount, mWifiInfo.lowRssiCount)); 4447 4448 //sanitize boundaries 4449 if (score > NetworkAgent.WIFI_BASE_SCORE) 4450 score = NetworkAgent.WIFI_BASE_SCORE; 4451 if (score < 0) 4452 score = 0; 4453 4454 //report score 4455 if (score != mWifiInfo.score) { 4456 if (DBG) { 4457 logd("calculateWifiScore() report new score " + Integer.toString(score)); 4458 } 4459 mWifiInfo.score = score; 4460 if (mNetworkAgent != null) { 4461 mNetworkAgent.sendNetworkScore(score); 4462 } 4463 } 4464 wifiScoringReport = sb.toString(); 4465 } 4466 4467 public double getTxPacketRate() { 4468 if (mWifiInfo != null) { 4469 return mWifiInfo.txSuccessRate; 4470 } 4471 return -1; 4472 } 4473 4474 public double getRxPacketRate() { 4475 if (mWifiInfo != null) { 4476 return mWifiInfo.rxSuccessRate; 4477 } 4478 return -1; 4479 } 4480 4481 /** 4482 * Fetch TX packet counters on current connection 4483 */ 4484 private void fetchPktcntNative(RssiPacketCountInfo info) { 4485 String pktcntPoll = mWifiNative.pktcntPoll(); 4486 4487 if (pktcntPoll != null) { 4488 String[] lines = pktcntPoll.split("\n"); 4489 for (String line : lines) { 4490 String[] prop = line.split("="); 4491 if (prop.length < 2) continue; 4492 try { 4493 if (prop[0].equals("TXGOOD")) { 4494 info.txgood = Integer.parseInt(prop[1]); 4495 } else if (prop[0].equals("TXBAD")) { 4496 info.txbad = Integer.parseInt(prop[1]); 4497 } 4498 } catch (NumberFormatException e) { 4499 // Ignore 4500 } 4501 } 4502 } 4503 } 4504 4505 private void notifyLinkProperties() { 4506 // TODO: Add setters for TCP buffer sizes and HTTP proxy to IpManager. 4507 // Once that is done delete this. 4508 updateLinkProperties(new LinkProperties(mLinkProperties)); 4509 } 4510 4511 private void updateLinkProperties(LinkProperties newLp) { 4512 // HTTP proxy and TCP buffer sizes are locally configured. 4513 newLp.setHttpProxy(mWifiConfigStore.getProxyProperties(mLastNetworkId)); 4514 if (!TextUtils.isEmpty(mTcpBufferSizes)) { 4515 newLp.setTcpBufferSizes(mTcpBufferSizes); 4516 } 4517 4518 if (!newLp.equals(mLinkProperties)) { 4519 if (DBG) { 4520 log("Link configuration changed for netId: " + mLastNetworkId 4521 + " old: " + mLinkProperties + " new: " + newLp); 4522 } 4523 // We own this instance of LinkProperties because IpManager passes us a copy. 4524 mLinkProperties = newLp; 4525 if (mNetworkAgent != null) { 4526 mNetworkAgent.sendLinkProperties(mLinkProperties); 4527 } 4528 4529 if (getNetworkDetailedState() == DetailedState.CONNECTED) { 4530 // If anything has changed and we're already connected, send out a notification. 4531 // TODO: Update all callers to use NetworkCallbacks and delete this. 4532 sendLinkConfigurationChangedBroadcast(); 4533 } 4534 } 4535 4536 if (DBG) { 4537 StringBuilder sb = new StringBuilder(); 4538 sb.append("updateLinkProperties nid: " + mLastNetworkId); 4539 sb.append(" state: " + getNetworkDetailedState()); 4540 4541 if (mLinkProperties != null) { 4542 sb.append(" "); 4543 sb.append(getLinkPropertiesSummary(mLinkProperties)); 4544 } 4545 logd(sb.toString()); 4546 } 4547 } 4548 4549 /** 4550 * Clears all our link properties. 4551 */ 4552 private void clearLinkProperties() { 4553 // Clear the link properties obtained from DHCP. The only caller of this 4554 // function has already called IpManager#stop(), which clears its state. 4555 synchronized (mDhcpResultsLock) { 4556 if (mDhcpResults != null) { 4557 mDhcpResults.clear(); 4558 } 4559 } 4560 4561 // Now clear the merged link properties. 4562 mLinkProperties.clear(); 4563 if (mNetworkAgent != null) mNetworkAgent.sendLinkProperties(mLinkProperties); 4564 } 4565 4566 /** 4567 * try to update default route MAC address. 4568 */ 4569 private String updateDefaultRouteMacAddress(int timeout) { 4570 String address = null; 4571 for (RouteInfo route : mLinkProperties.getRoutes()) { 4572 if (route.isDefaultRoute() && route.hasGateway()) { 4573 InetAddress gateway = route.getGateway(); 4574 if (gateway instanceof Inet4Address) { 4575 if (PDBG) { 4576 logd("updateDefaultRouteMacAddress found Ipv4 default :" 4577 + gateway.getHostAddress()); 4578 } 4579 address = macAddressFromRoute(gateway.getHostAddress()); 4580 /* The gateway's MAC address is known */ 4581 if ((address == null) && (timeout > 0)) { 4582 boolean reachable = false; 4583 try { 4584 reachable = gateway.isReachable(timeout); 4585 } catch (Exception e) { 4586 loge("updateDefaultRouteMacAddress exception reaching :" 4587 + gateway.getHostAddress()); 4588 4589 } finally { 4590 if (reachable == true) { 4591 4592 address = macAddressFromRoute(gateway.getHostAddress()); 4593 if (PDBG) { 4594 logd("updateDefaultRouteMacAddress reachable (tried again) :" 4595 + gateway.getHostAddress() + " found " + address); 4596 } 4597 } 4598 } 4599 } 4600 if (address != null) { 4601 mWifiConfigStore.setDefaultGwMacAddress(mLastNetworkId, address); 4602 } 4603 } 4604 } 4605 } 4606 return address; 4607 } 4608 4609 void sendScanResultsAvailableBroadcast(boolean scanSucceeded) { 4610 Intent intent = new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 4611 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4612 intent.putExtra(WifiManager.EXTRA_RESULTS_UPDATED, scanSucceeded); 4613 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 4614 } 4615 4616 private void sendRssiChangeBroadcast(final int newRssi) { 4617 try { 4618 mBatteryStats.noteWifiRssiChanged(newRssi); 4619 } catch (RemoteException e) { 4620 // Won't happen. 4621 } 4622 Intent intent = new Intent(WifiManager.RSSI_CHANGED_ACTION); 4623 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4624 intent.putExtra(WifiManager.EXTRA_NEW_RSSI, newRssi); 4625 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 4626 } 4627 4628 private void sendNetworkStateChangeBroadcast(String bssid) { 4629 Intent intent = new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION); 4630 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4631 intent.putExtra(WifiManager.EXTRA_NETWORK_INFO, new NetworkInfo(mNetworkInfo)); 4632 intent.putExtra(WifiManager.EXTRA_LINK_PROPERTIES, new LinkProperties(mLinkProperties)); 4633 if (bssid != null) 4634 intent.putExtra(WifiManager.EXTRA_BSSID, bssid); 4635 if (mNetworkInfo.getDetailedState() == DetailedState.VERIFYING_POOR_LINK || 4636 mNetworkInfo.getDetailedState() == DetailedState.CONNECTED) { 4637 // We no longer report MAC address to third-parties and our code does 4638 // not rely on this broadcast, so just send the default MAC address. 4639 WifiInfo sentWifiInfo = new WifiInfo(mWifiInfo); 4640 sentWifiInfo.setMacAddress(WifiInfo.DEFAULT_MAC_ADDRESS); 4641 intent.putExtra(WifiManager.EXTRA_WIFI_INFO, sentWifiInfo); 4642 } 4643 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 4644 } 4645 4646 private WifiInfo getWiFiInfoForUid(int uid) { 4647 if (Binder.getCallingUid() == Process.myUid()) { 4648 return mWifiInfo; 4649 } 4650 4651 WifiInfo result = new WifiInfo(mWifiInfo); 4652 result.setMacAddress(WifiInfo.DEFAULT_MAC_ADDRESS); 4653 4654 IBinder binder = mFacade.getService("package"); 4655 IPackageManager packageManager = IPackageManager.Stub.asInterface(binder); 4656 4657 try { 4658 if (packageManager.checkUidPermission(Manifest.permission.LOCAL_MAC_ADDRESS, 4659 uid) == PackageManager.PERMISSION_GRANTED) { 4660 result.setMacAddress(mWifiInfo.getMacAddress()); 4661 } 4662 } catch (RemoteException e) { 4663 Log.e(TAG, "Error checking receiver permission", e); 4664 } 4665 4666 return result; 4667 } 4668 4669 private void sendLinkConfigurationChangedBroadcast() { 4670 Intent intent = new Intent(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION); 4671 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4672 intent.putExtra(WifiManager.EXTRA_LINK_PROPERTIES, new LinkProperties(mLinkProperties)); 4673 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 4674 } 4675 4676 private void sendSupplicantConnectionChangedBroadcast(boolean connected) { 4677 Intent intent = new Intent(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION); 4678 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4679 intent.putExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, connected); 4680 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 4681 } 4682 4683 /** 4684 * Record the detailed state of a network. 4685 * 4686 * @param state the new {@code DetailedState} 4687 */ 4688 private boolean setNetworkDetailedState(NetworkInfo.DetailedState state) { 4689 boolean hidden = false; 4690 4691 if (linkDebouncing || isRoaming()) { 4692 // There is generally a confusion in the system about colluding 4693 // WiFi Layer 2 state (as reported by supplicant) and the Network state 4694 // which leads to multiple confusion. 4695 // 4696 // If link is de-bouncing or roaming, we already have an IP address 4697 // as well we were connected and are doing L2 cycles of 4698 // reconnecting or renewing IP address to check that we still have it 4699 // This L2 link flapping should ne be reflected into the Network state 4700 // which is the state of the WiFi Network visible to Layer 3 and applications 4701 // Note that once debouncing and roaming are completed, we will 4702 // set the Network state to where it should be, or leave it as unchanged 4703 // 4704 hidden = true; 4705 } 4706 if (DBG) { 4707 log("setDetailed state, old =" 4708 + mNetworkInfo.getDetailedState() + " and new state=" + state 4709 + " hidden=" + hidden); 4710 } 4711 if (mNetworkInfo.getExtraInfo() != null && mWifiInfo.getSSID() != null 4712 && !mWifiInfo.getSSID().equals(WifiSsid.NONE)) { 4713 // Always indicate that SSID has changed 4714 if (!mNetworkInfo.getExtraInfo().equals(mWifiInfo.getSSID())) { 4715 if (DBG) { 4716 log("setDetailed state send new extra info" + mWifiInfo.getSSID()); 4717 } 4718 mNetworkInfo.setExtraInfo(mWifiInfo.getSSID()); 4719 sendNetworkStateChangeBroadcast(null); 4720 } 4721 } 4722 if (hidden == true) { 4723 return false; 4724 } 4725 4726 if (state != mNetworkInfo.getDetailedState()) { 4727 mNetworkInfo.setDetailedState(state, null, mWifiInfo.getSSID()); 4728 if (mNetworkAgent != null) { 4729 mNetworkAgent.sendNetworkInfo(mNetworkInfo); 4730 } 4731 sendNetworkStateChangeBroadcast(null); 4732 return true; 4733 } 4734 return false; 4735 } 4736 4737 private DetailedState getNetworkDetailedState() { 4738 return mNetworkInfo.getDetailedState(); 4739 } 4740 4741 private SupplicantState handleSupplicantStateChange(Message message) { 4742 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 4743 SupplicantState state = stateChangeResult.state; 4744 // Supplicant state change 4745 // [31-13] Reserved for future use 4746 // [8 - 0] Supplicant state (as defined in SupplicantState.java) 4747 // 50023 supplicant_state_changed (custom|1|5) 4748 mWifiInfo.setSupplicantState(state); 4749 // Network id is only valid when we start connecting 4750 if (SupplicantState.isConnecting(state)) { 4751 mWifiInfo.setNetworkId(stateChangeResult.networkId); 4752 } else { 4753 mWifiInfo.setNetworkId(WifiConfiguration.INVALID_NETWORK_ID); 4754 } 4755 4756 mWifiInfo.setBSSID(stateChangeResult.BSSID); 4757 4758 if (mWhiteListedSsids != null 4759 && mWhiteListedSsids.length > 0 4760 && stateChangeResult.wifiSsid != null) { 4761 String SSID = stateChangeResult.wifiSsid.toString(); 4762 String currentSSID = mWifiInfo.getSSID(); 4763 if (SSID != null && currentSSID != null && !SSID.equals(WifiSsid.NONE)) { 4764 // Remove quote before comparing 4765 if (SSID.length() >= 2 && SSID.charAt(0) == '"' 4766 && SSID.charAt(SSID.length() - 1) == '"') { 4767 SSID = SSID.substring(1, SSID.length() - 1); 4768 } 4769 if (currentSSID.length() >= 2 && currentSSID.charAt(0) == '"' 4770 && currentSSID.charAt(currentSSID.length() - 1) == '"') { 4771 currentSSID = currentSSID.substring(1, currentSSID.length() - 1); 4772 } 4773 if ((!SSID.equals(currentSSID)) && (getCurrentState() == mConnectedState)) { 4774 lastConnectAttemptTimestamp = System.currentTimeMillis(); 4775 //Create new connection event for connection attempt. 4776 mWifiMetrics.startConnectionEvent(mWifiInfo, 4777 WifiMetricsProto.ConnectionEvent.ROAM_ENTERPRISE); 4778 targetWificonfiguration = 4779 mWifiConfigStore.getWifiConfiguration(mWifiInfo.getNetworkId()); 4780 transitionTo(mRoamingState); 4781 } 4782 } 4783 } 4784 4785 mWifiInfo.setSSID(stateChangeResult.wifiSsid); 4786 mWifiInfo.setEphemeral(mWifiConfigStore.isEphemeral(mWifiInfo.getNetworkId())); 4787 4788 mSupplicantStateTracker.sendMessage(Message.obtain(message)); 4789 4790 return state; 4791 } 4792 4793 /** 4794 * Resets the Wi-Fi Connections by clearing any state, resetting any sockets 4795 * using the interface, stopping DHCP & disabling interface 4796 */ 4797 private void handleNetworkDisconnect() { 4798 if (DBG) log("handleNetworkDisconnect: Stopping DHCP and clearing IP" 4799 + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName() 4800 + " - " + Thread.currentThread().getStackTrace()[3].getMethodName() 4801 + " - " + Thread.currentThread().getStackTrace()[4].getMethodName() 4802 + " - " + Thread.currentThread().getStackTrace()[5].getMethodName()); 4803 4804 stopRssiMonitoringOffload(); 4805 4806 clearCurrentConfigBSSID("handleNetworkDisconnect"); 4807 4808 stopIpManager(); 4809 4810 /* Reset data structures */ 4811 mBadLinkspeedcount = 0; 4812 mWifiInfo.reset(); 4813 linkDebouncing = false; 4814 /* Reset roaming parameters */ 4815 mAutoRoaming = false; 4816 4817 /** 4818 * fullBandConnectedTimeIntervalMilli: 4819 * - start scans at mWifiConfigStore.wifiAssociatedShortScanIntervalMilli seconds interval 4820 * - exponentially increase to mWifiConfigStore.associatedFullScanMaxIntervalMilli 4821 * Initialize to sane value = 20 seconds 4822 */ 4823 fullBandConnectedTimeIntervalMilli = 20 * 1000; 4824 4825 setNetworkDetailedState(DetailedState.DISCONNECTED); 4826 if (mNetworkAgent != null) { 4827 mNetworkAgent.sendNetworkInfo(mNetworkInfo); 4828 mNetworkAgent = null; 4829 } 4830 mWifiConfigStore.updateStatus(mLastNetworkId, DetailedState.DISCONNECTED); 4831 4832 /* Clear network properties */ 4833 clearLinkProperties(); 4834 4835 /* Cend event to CM & network change broadcast */ 4836 sendNetworkStateChangeBroadcast(mLastBssid); 4837 4838 /* Cancel auto roam requests */ 4839 autoRoamSetBSSID(mLastNetworkId, "any"); 4840 mTargetNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 4841 mLastBssid = null; 4842 registerDisconnected(); 4843 mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 4844 } 4845 4846 private void handleSupplicantConnectionLoss(boolean killSupplicant) { 4847 /* Socket connection can be lost when we do a graceful shutdown 4848 * or when the driver is hung. Ensure supplicant is stopped here. 4849 */ 4850 if (killSupplicant) { 4851 mWifiMonitor.killSupplicant(mP2pSupported); 4852 } 4853 mWifiNative.closeSupplicantConnection(); 4854 sendSupplicantConnectionChangedBroadcast(false); 4855 setWifiState(WIFI_STATE_DISABLED); 4856 } 4857 4858 void handlePreDhcpSetup() { 4859 if (!mBluetoothConnectionActive) { 4860 /* 4861 * There are problems setting the Wi-Fi driver's power 4862 * mode to active when bluetooth coexistence mode is 4863 * enabled or sense. 4864 * <p> 4865 * We set Wi-Fi to active mode when 4866 * obtaining an IP address because we've found 4867 * compatibility issues with some routers with low power 4868 * mode. 4869 * <p> 4870 * In order for this active power mode to properly be set, 4871 * we disable coexistence mode until we're done with 4872 * obtaining an IP address. One exception is if we 4873 * are currently connected to a headset, since disabling 4874 * coexistence would interrupt that connection. 4875 */ 4876 // Disable the coexistence mode 4877 mWifiNative.setBluetoothCoexistenceMode( 4878 mWifiNative.BLUETOOTH_COEXISTENCE_MODE_DISABLED); 4879 } 4880 4881 // Disable power save and suspend optimizations during DHCP 4882 // Note: The order here is important for now. Brcm driver changes 4883 // power settings when we control suspend mode optimizations. 4884 // TODO: Remove this comment when the driver is fixed. 4885 setSuspendOptimizationsNative(SUSPEND_DUE_TO_DHCP, false); 4886 mWifiNative.setPowerSave(false); 4887 4888 // Update link layer stats 4889 getWifiLinkLayerStats(false); 4890 4891 /* P2p discovery breaks dhcp, shut it down in order to get through this */ 4892 Message msg = new Message(); 4893 msg.what = WifiP2pServiceImpl.BLOCK_DISCOVERY; 4894 msg.arg1 = WifiP2pServiceImpl.ENABLED; 4895 msg.arg2 = DhcpStateMachine.CMD_PRE_DHCP_ACTION_COMPLETE; 4896 msg.obj = WifiStateMachine.this; 4897 mWifiP2pChannel.sendMessage(msg); 4898 } 4899 4900 void handlePostDhcpSetup() { 4901 /* Restore power save and suspend optimizations */ 4902 setSuspendOptimizationsNative(SUSPEND_DUE_TO_DHCP, true); 4903 mWifiNative.setPowerSave(true); 4904 4905 mWifiP2pChannel.sendMessage(WifiP2pServiceImpl.BLOCK_DISCOVERY, 4906 WifiP2pServiceImpl.DISABLED); 4907 4908 // Set the coexistence mode back to its default value 4909 mWifiNative.setBluetoothCoexistenceMode( 4910 mWifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE); 4911 } 4912 4913 void connectScanningService() { 4914 if (mWifiScanner == null) { 4915 mWifiScanner = (WifiScanner) mContext.getSystemService(Context.WIFI_SCANNING_SERVICE); 4916 } 4917 } 4918 4919 private void handleIPv4Success(DhcpResults dhcpResults) { 4920 if (PDBG) { 4921 logd("handleIPv4Success <" + dhcpResults.toString() + ">"); 4922 logd("link address " + dhcpResults.ipAddress); 4923 } 4924 4925 Inet4Address addr; 4926 synchronized (mDhcpResultsLock) { 4927 mDhcpResults = dhcpResults; 4928 addr = (Inet4Address) dhcpResults.ipAddress.getAddress(); 4929 } 4930 4931 if (isRoaming()) { 4932 int previousAddress = mWifiInfo.getIpAddress(); 4933 int newAddress = NetworkUtils.inetAddressToInt(addr); 4934 if (previousAddress != newAddress) { 4935 logd("handleIPv4Success, roaming and address changed" + 4936 mWifiInfo + " got: " + addr); 4937 } 4938 } 4939 mWifiInfo.setInetAddress(addr); 4940 mWifiInfo.setMeteredHint(dhcpResults.hasMeteredHint()); 4941 } 4942 4943 private void handleSuccessfulIpConfiguration() { 4944 mLastSignalLevel = -1; // Force update of signal strength 4945 WifiConfiguration c = getCurrentWifiConfiguration(); 4946 if (c != null) { 4947 // Reset IP failure tracking 4948 c.getNetworkSelectionStatus().clearDisableReasonCounter( 4949 WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE); 4950 4951 // Tell the framework whether the newly connected network is trusted or untrusted. 4952 updateCapabilities(c); 4953 } 4954 if (c != null) { 4955 ScanResult result = getCurrentScanResult(); 4956 if (result == null) { 4957 logd("WifiStateMachine: handleSuccessfulIpConfiguration and no scan results" + 4958 c.configKey()); 4959 } else { 4960 // Clear the per BSSID failure count 4961 result.numIpConfigFailures = 0; 4962 // Clear the WHOLE BSSID blacklist, which means supplicant is free to retry 4963 // any BSSID, even though it may already have a non zero ip failure count, 4964 // this will typically happen if the user walks away and come back to his arrea 4965 // TODO: implement blacklisting based on a timer, i.e. keep BSSID blacklisted 4966 // in supplicant for a couple of hours or a day 4967 mWifiConfigStore.clearBssidBlacklist(); 4968 } 4969 } 4970 } 4971 4972 private void handleIPv4Failure() { 4973 // TODO: Move this to provisioning failure, not DHCP failure. 4974 // DHCPv4 failure is expected on an IPv6-only network. 4975 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_DHCP_FAILURE); 4976 if (DBG) { 4977 int count = -1; 4978 WifiConfiguration config = getCurrentWifiConfiguration(); 4979 if (config != null) { 4980 count = config.getNetworkSelectionStatus().getDisableReasonCounter( 4981 WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE); 4982 } 4983 log("DHCP failure count=" + count); 4984 } 4985 mWifiMetrics.endConnectionEvent(0, WifiMetricsProto.ConnectionEvent.HLF_DHCP); 4986 4987 synchronized(mDhcpResultsLock) { 4988 if (mDhcpResults != null) { 4989 mDhcpResults.clear(); 4990 } 4991 } 4992 if (PDBG) { 4993 logd("handleIPv4Failure"); 4994 } 4995 } 4996 4997 private void handleIpConfigurationLost() { 4998 mWifiInfo.setInetAddress(null); 4999 mWifiInfo.setMeteredHint(false); 5000 5001 mWifiConfigStore.updateNetworkSelectionStatus(mLastNetworkId, 5002 WifiConfiguration.NetworkSelectionStatus.DISABLED_DHCP_FAILURE); 5003 5004 /* DHCP times out after about 30 seconds, we do a 5005 * disconnect thru supplicant, we will let autojoin retry connecting to the network 5006 */ 5007 mWifiNative.disconnect(); 5008 } 5009 5010 // TODO: De-duplicated this and handleIpConfigurationLost(). 5011 private void handleIpReachabilityLost() { 5012 mWifiInfo.setInetAddress(null); 5013 mWifiInfo.setMeteredHint(false); 5014 5015 // TODO: Determine whether to call some form of mWifiConfigStore.handleSSIDStateChange(). 5016 5017 // Disconnect via supplicant, and let autojoin retry connecting to the network. 5018 mWifiNative.disconnect(); 5019 } 5020 5021 private int convertFrequencyToChannelNumber(int frequency) { 5022 if (frequency >= 2412 && frequency <= 2484) { 5023 return (frequency -2412) / 5 + 1; 5024 } else if (frequency >= 5170 && frequency <=5825) { 5025 //DFS is included 5026 return (frequency -5170) / 5 + 34; 5027 } else { 5028 return 0; 5029 } 5030 } 5031 5032 private int chooseApChannel(int apBand) { 5033 int apChannel; 5034 int[] channel; 5035 5036 if (apBand == 0) { 5037 ArrayList<Integer> allowed2GChannel = 5038 mWifiApConfigStore.getAllowed2GChannel(); 5039 if (allowed2GChannel == null || allowed2GChannel.size() == 0) { 5040 //most safe channel to use 5041 if(DBG) { 5042 Log.d(TAG, "No specified 2G allowed channel list"); 5043 } 5044 apChannel = 6; 5045 } else { 5046 int index = mRandom.nextInt(allowed2GChannel.size()); 5047 apChannel = allowed2GChannel.get(index).intValue(); 5048 } 5049 } else { 5050 //5G without DFS 5051 channel = mWifiNative.getChannelsForBand(2); 5052 if (channel != null && channel.length > 0) { 5053 apChannel = channel[mRandom.nextInt(channel.length)]; 5054 apChannel = convertFrequencyToChannelNumber(apChannel); 5055 } else { 5056 Log.e(TAG, "SoftAp do not get available channel list"); 5057 apChannel = 0; 5058 } 5059 } 5060 5061 if(DBG) { 5062 Log.d(TAG, "SoftAp set on channel " + apChannel); 5063 } 5064 5065 return apChannel; 5066 } 5067 5068 /* SoftAP configuration */ 5069 private boolean enableSoftAp() { 5070 if (mWifiNative.getInterfaces() != 0) { 5071 if (!mWifiNative.toggleInterface(0)) { 5072 if (DBG) Log.e(TAG, "toggleInterface failed"); 5073 return false; 5074 } 5075 } else { 5076 if (DBG) Log.d(TAG, "No interfaces to toggle"); 5077 } 5078 5079 try { 5080 mNwService.wifiFirmwareReload(mInterfaceName, "AP"); 5081 if (DBG) Log.d(TAG, "Firmware reloaded in AP mode"); 5082 } catch (Exception e) { 5083 Log.e(TAG, "Failed to reload AP firmware " + e); 5084 } 5085 5086 if (mWifiNative.startHal() == false) { 5087 /* starting HAL is optional */ 5088 Log.e(TAG, "Failed to start HAL"); 5089 } 5090 return true; 5091 } 5092 5093 /* Current design is to not set the config on a running hostapd but instead 5094 * stop and start tethering when user changes config on a running access point 5095 * 5096 * TODO: Add control channel setup through hostapd that allows changing config 5097 * on a running daemon 5098 */ 5099 private void startSoftApWithConfig(final WifiConfiguration configuration) { 5100 // set channel 5101 final WifiConfiguration config = new WifiConfiguration(configuration); 5102 5103 if (DBG) { 5104 Log.d(TAG, "SoftAp config channel is: " + config.apChannel); 5105 } 5106 5107 //We need HAL support to set country code and get available channel list, if HAL is 5108 //not available, like razor, we regress to original implementaion (2GHz, channel 6) 5109 if (mWifiNative.isHalStarted()) { 5110 //set country code through HAL Here 5111 String countryCode = getCurrentCountryCode(); 5112 5113 if (countryCode != null) { 5114 if (!mWifiNative.setCountryCodeHal(countryCode.toUpperCase(Locale.ROOT))) { 5115 if (config.apBand != 0) { 5116 Log.e(TAG, "Fail to set country code. Can not setup Softap on 5GHz"); 5117 //countrycode is mandatory for 5GHz 5118 sendMessage(CMD_START_AP_FAILURE, WifiManager.SAP_START_FAILURE_GENERAL); 5119 return; 5120 } 5121 } 5122 } else { 5123 if (config.apBand != 0) { 5124 //countrycode is mandatory for 5GHz 5125 Log.e(TAG, "Can not setup softAp on 5GHz without country code!"); 5126 sendMessage(CMD_START_AP_FAILURE, WifiManager.SAP_START_FAILURE_GENERAL); 5127 return; 5128 } 5129 } 5130 5131 if (config.apChannel == 0) { 5132 config.apChannel = chooseApChannel(config.apBand); 5133 if (config.apChannel == 0) { 5134 if(mWifiNative.isGetChannelsForBandSupported()) { 5135 //fail to get available channel 5136 sendMessage(CMD_START_AP_FAILURE, WifiManager.SAP_START_FAILURE_NO_CHANNEL); 5137 return; 5138 } else { 5139 //for some old device, wifiHal may not be supportedget valid channels are not 5140 //supported 5141 config.apBand = 0; 5142 config.apChannel = 6; 5143 } 5144 } 5145 } 5146 } else { 5147 //for some old device, wifiHal may not be supported 5148 config.apBand = 0; 5149 config.apChannel = 6; 5150 } 5151 // Start hostapd on a separate thread 5152 new Thread(new Runnable() { 5153 public void run() { 5154 try { 5155 mNwService.startAccessPoint(config, mInterfaceName); 5156 } catch (Exception e) { 5157 loge("Exception in softap start " + e); 5158 try { 5159 mNwService.stopAccessPoint(mInterfaceName); 5160 mNwService.startAccessPoint(config, mInterfaceName); 5161 } catch (Exception e1) { 5162 loge("Exception in softap re-start " + e1); 5163 sendMessage(CMD_START_AP_FAILURE, WifiManager.SAP_START_FAILURE_GENERAL); 5164 return; 5165 } 5166 } 5167 if (DBG) log("Soft AP start successful"); 5168 sendMessage(CMD_START_AP_SUCCESS); 5169 } 5170 }).start(); 5171 } 5172 5173 private byte[] macAddressFromString(String macString) { 5174 String[] macBytes = macString.split(":"); 5175 if (macBytes.length != 6) { 5176 throw new IllegalArgumentException("MAC address should be 6 bytes long!"); 5177 } 5178 byte[] mac = new byte[6]; 5179 for (int i = 0; i < macBytes.length; i++) { 5180 Integer hexVal = Integer.parseInt(macBytes[i], 16); 5181 mac[i] = hexVal.byteValue(); 5182 } 5183 return mac; 5184 } 5185 5186 /* 5187 * Read a MAC address in /proc/arp/table, used by WifistateMachine 5188 * so as to record MAC address of default gateway. 5189 **/ 5190 private String macAddressFromRoute(String ipAddress) { 5191 String macAddress = null; 5192 BufferedReader reader = null; 5193 try { 5194 reader = new BufferedReader(new FileReader("/proc/net/arp")); 5195 5196 // Skip over the line bearing colum titles 5197 String line = reader.readLine(); 5198 5199 while ((line = reader.readLine()) != null) { 5200 String[] tokens = line.split("[ ]+"); 5201 if (tokens.length < 6) { 5202 continue; 5203 } 5204 5205 // ARP column format is 5206 // Address HWType HWAddress Flags Mask IFace 5207 String ip = tokens[0]; 5208 String mac = tokens[3]; 5209 5210 if (ipAddress.equals(ip)) { 5211 macAddress = mac; 5212 break; 5213 } 5214 } 5215 5216 if (macAddress == null) { 5217 loge("Did not find remoteAddress {" + ipAddress + "} in " + 5218 "/proc/net/arp"); 5219 } 5220 5221 } catch (FileNotFoundException e) { 5222 loge("Could not open /proc/net/arp to lookup mac address"); 5223 } catch (IOException e) { 5224 loge("Could not read /proc/net/arp to lookup mac address"); 5225 } finally { 5226 try { 5227 if (reader != null) { 5228 reader.close(); 5229 } 5230 } catch (IOException e) { 5231 // Do nothing 5232 } 5233 } 5234 return macAddress; 5235 5236 } 5237 5238 private class WifiNetworkFactory extends NetworkFactory { 5239 public WifiNetworkFactory(Looper l, Context c, String TAG, NetworkCapabilities f) { 5240 super(l, c, TAG, f); 5241 } 5242 5243 @Override 5244 protected void needNetworkFor(NetworkRequest networkRequest, int score) { 5245 ++mConnectionRequests; 5246 } 5247 5248 @Override 5249 protected void releaseNetworkFor(NetworkRequest networkRequest) { 5250 --mConnectionRequests; 5251 } 5252 5253 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 5254 pw.println("mConnectionRequests " + mConnectionRequests); 5255 } 5256 5257 } 5258 5259 private class UntrustedWifiNetworkFactory extends NetworkFactory { 5260 private int mUntrustedReqCount; 5261 5262 public UntrustedWifiNetworkFactory(Looper l, Context c, String tag, NetworkCapabilities f) { 5263 super(l, c, tag, f); 5264 } 5265 5266 @Override 5267 protected void needNetworkFor(NetworkRequest networkRequest, int score) { 5268 if (!networkRequest.networkCapabilities.hasCapability( 5269 NetworkCapabilities.NET_CAPABILITY_TRUSTED)) { 5270 if (++mUntrustedReqCount == 1) { 5271 setAllowUntrustedConnections(true); 5272 } 5273 } 5274 } 5275 5276 @Override 5277 protected void releaseNetworkFor(NetworkRequest networkRequest) { 5278 if (!networkRequest.networkCapabilities.hasCapability( 5279 NetworkCapabilities.NET_CAPABILITY_TRUSTED)) { 5280 if (--mUntrustedReqCount == 0) { 5281 setAllowUntrustedConnections(false); 5282 } 5283 } 5284 } 5285 5286 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 5287 pw.println("mUntrustedReqCount " + mUntrustedReqCount); 5288 } 5289 } 5290 5291 void maybeRegisterNetworkFactory() { 5292 if (mNetworkFactory == null) { 5293 checkAndSetConnectivityInstance(); 5294 if (mCm != null) { 5295 mNetworkFactory = new WifiNetworkFactory(getHandler().getLooper(), mContext, 5296 NETWORKTYPE, mNetworkCapabilitiesFilter); 5297 mNetworkFactory.setScoreFilter(60); 5298 mNetworkFactory.register(); 5299 5300 // We can't filter untrusted network in the capabilities filter because a trusted 5301 // network would still satisfy a request that accepts untrusted ones. 5302 mUntrustedNetworkFactory = new UntrustedWifiNetworkFactory(getHandler().getLooper(), 5303 mContext, NETWORKTYPE_UNTRUSTED, mNetworkCapabilitiesFilter); 5304 mUntrustedNetworkFactory.setScoreFilter(Integer.MAX_VALUE); 5305 mUntrustedNetworkFactory.register(); 5306 } 5307 } 5308 } 5309 5310 /******************************************************** 5311 * HSM states 5312 *******************************************************/ 5313 5314 class DefaultState extends State { 5315 @Override 5316 public boolean processMessage(Message message) { 5317 logStateAndMessage(message, this); 5318 5319 switch (message.what) { 5320 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: { 5321 AsyncChannel ac = (AsyncChannel) message.obj; 5322 if (ac == mWifiP2pChannel) { 5323 if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 5324 mWifiP2pChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION); 5325 } else { 5326 loge("WifiP2pService connection failure, error=" + message.arg1); 5327 } 5328 } else { 5329 loge("got HALF_CONNECTED for unknown channel"); 5330 } 5331 break; 5332 } 5333 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: { 5334 AsyncChannel ac = (AsyncChannel) message.obj; 5335 if (ac == mWifiP2pChannel) { 5336 loge("WifiP2pService channel lost, message.arg1 =" + message.arg1); 5337 //TODO: Re-establish connection to state machine after a delay 5338 // mWifiP2pChannel.connect(mContext, getHandler(), 5339 // mWifiP2pManager.getMessenger()); 5340 } 5341 break; 5342 } 5343 case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE: 5344 mBluetoothConnectionActive = (message.arg1 != 5345 BluetoothAdapter.STATE_DISCONNECTED); 5346 break; 5347 /* Synchronous call returns */ 5348 case CMD_PING_SUPPLICANT: 5349 case CMD_ENABLE_NETWORK: 5350 case CMD_ADD_OR_UPDATE_NETWORK: 5351 case CMD_REMOVE_NETWORK: 5352 case CMD_SAVE_CONFIG: 5353 replyToMessage(message, message.what, FAILURE); 5354 break; 5355 case CMD_GET_CAPABILITY_FREQ: 5356 replyToMessage(message, message.what, null); 5357 break; 5358 case CMD_GET_CONFIGURED_NETWORKS: 5359 replyToMessage(message, message.what, (List<WifiConfiguration>) null); 5360 break; 5361 case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS: 5362 replyToMessage(message, message.what, (List<WifiConfiguration>) null); 5363 break; 5364 case CMD_ENABLE_RSSI_POLL: 5365 mEnableRssiPolling = (message.arg1 == 1); 5366 break; 5367 case CMD_SET_HIGH_PERF_MODE: 5368 if (message.arg1 == 1) { 5369 setSuspendOptimizations(SUSPEND_DUE_TO_HIGH_PERF, false); 5370 } else { 5371 setSuspendOptimizations(SUSPEND_DUE_TO_HIGH_PERF, true); 5372 } 5373 break; 5374 case CMD_BOOT_COMPLETED: 5375 maybeRegisterNetworkFactory(); 5376 break; 5377 case CMD_SCREEN_STATE_CHANGED: 5378 handleScreenStateChanged(message.arg1 != 0); 5379 break; 5380 /* Discard */ 5381 case CMD_START_SCAN: 5382 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5383 break; 5384 case CMD_START_SUPPLICANT: 5385 case CMD_STOP_SUPPLICANT: 5386 case CMD_STOP_SUPPLICANT_FAILED: 5387 case CMD_START_DRIVER: 5388 case CMD_STOP_DRIVER: 5389 case CMD_DRIVER_START_TIMED_OUT: 5390 case CMD_START_AP: 5391 case CMD_START_AP_SUCCESS: 5392 case CMD_START_AP_FAILURE: 5393 case CMD_STOP_AP: 5394 case CMD_TETHER_STATE_CHANGE: 5395 case CMD_TETHER_NOTIFICATION_TIMED_OUT: 5396 case CMD_DISCONNECT: 5397 case CMD_RECONNECT: 5398 case CMD_REASSOCIATE: 5399 case CMD_RELOAD_TLS_AND_RECONNECT: 5400 case WifiMonitor.SUP_CONNECTION_EVENT: 5401 case WifiMonitor.SUP_DISCONNECTION_EVENT: 5402 case WifiMonitor.NETWORK_CONNECTION_EVENT: 5403 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 5404 case WifiMonitor.SCAN_RESULTS_EVENT: 5405 case WifiMonitor.SCAN_FAILED_EVENT: 5406 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 5407 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 5408 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 5409 case WifiMonitor.WPS_OVERLAP_EVENT: 5410 case CMD_BLACKLIST_NETWORK: 5411 case CMD_CLEAR_BLACKLIST: 5412 case CMD_SET_OPERATIONAL_MODE: 5413 case CMD_SET_FREQUENCY_BAND: 5414 case CMD_RSSI_POLL: 5415 case CMD_ENABLE_ALL_NETWORKS: 5416 case DhcpStateMachine.CMD_PRE_DHCP_ACTION: 5417 case DhcpStateMachine.CMD_PRE_DHCP_ACTION_COMPLETE: 5418 case DhcpStateMachine.CMD_POST_DHCP_ACTION: 5419 case CMD_NO_NETWORKS_PERIODIC_SCAN: 5420 case CMD_DISABLE_P2P_RSP: 5421 case WifiMonitor.SUP_REQUEST_IDENTITY: 5422 case CMD_TEST_NETWORK_DISCONNECT: 5423 case CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER: 5424 case WifiMonitor.SUP_REQUEST_SIM_AUTH: 5425 case CMD_TARGET_BSSID: 5426 case CMD_AUTO_CONNECT: 5427 case CMD_AUTO_ROAM: 5428 case CMD_AUTO_SAVE_NETWORK: 5429 case CMD_ASSOCIATED_BSSID: 5430 case CMD_UNWANTED_NETWORK: 5431 case CMD_DISCONNECTING_WATCHDOG_TIMER: 5432 case CMD_ROAM_WATCHDOG_TIMER: 5433 case CMD_DISABLE_EPHEMERAL_NETWORK: 5434 case CMD_RESTART_AUTOJOIN_OFFLOAD: 5435 case CMD_STARTED_PNO_DBG: 5436 case CMD_STARTED_GSCAN_DBG: 5437 case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION: 5438 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5439 break; 5440 case CMD_SET_COUNTRY_CODE: 5441 String country = (String) message.obj; 5442 final boolean persist = (message.arg2 == 1); 5443 final int sequence = message.arg1; 5444 if (sequence != mCountryCodeSequence.get()) { 5445 if (DBG) log("set country code ignored due to sequnce num"); 5446 break; 5447 } 5448 5449 if (persist) { 5450 country = country.toUpperCase(Locale.ROOT); 5451 if (DBG) log("set country code " + (country == null ? "(null)" : country)); 5452 Settings.Global.putString(mContext.getContentResolver(), 5453 Settings.Global.WIFI_COUNTRY_CODE, 5454 country == null ? "" : country); 5455 } 5456 5457 break; 5458 case CMD_SET_SUSPEND_OPT_ENABLED: 5459 if (message.arg1 == 1) { 5460 mSuspendWakeLock.release(); 5461 setSuspendOptimizations(SUSPEND_DUE_TO_SCREEN, true); 5462 } else { 5463 setSuspendOptimizations(SUSPEND_DUE_TO_SCREEN, false); 5464 } 5465 break; 5466 case WifiMonitor.DRIVER_HUNG_EVENT: 5467 setSupplicantRunning(false); 5468 setSupplicantRunning(true); 5469 break; 5470 case WifiManager.CONNECT_NETWORK: 5471 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 5472 WifiManager.BUSY); 5473 break; 5474 case WifiManager.FORGET_NETWORK: 5475 replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, 5476 WifiManager.BUSY); 5477 break; 5478 case WifiManager.SAVE_NETWORK: 5479 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5480 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 5481 WifiManager.BUSY); 5482 break; 5483 case WifiManager.START_WPS: 5484 replyToMessage(message, WifiManager.WPS_FAILED, 5485 WifiManager.BUSY); 5486 break; 5487 case WifiManager.CANCEL_WPS: 5488 replyToMessage(message, WifiManager.CANCEL_WPS_FAILED, 5489 WifiManager.BUSY); 5490 break; 5491 case WifiManager.DISABLE_NETWORK: 5492 replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED, 5493 WifiManager.BUSY); 5494 break; 5495 case WifiManager.RSSI_PKTCNT_FETCH: 5496 replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_FAILED, 5497 WifiManager.BUSY); 5498 break; 5499 case CMD_GET_SUPPORTED_FEATURES: 5500 int featureSet = mWifiNative.getSupportedFeatureSet(); 5501 replyToMessage(message, message.what, featureSet); 5502 break; 5503 case CMD_FIRMWARE_ALERT: 5504 if (mWifiLogger != null) { 5505 byte[] buffer = (byte[])message.obj; 5506 mWifiLogger.captureAlertData(message.arg1, buffer); 5507 } 5508 break; 5509 case CMD_GET_LINK_LAYER_STATS: 5510 // Not supported hence reply with error message 5511 replyToMessage(message, message.what, null); 5512 break; 5513 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 5514 NetworkInfo info = (NetworkInfo) message.obj; 5515 mP2pConnected.set(info.isConnected()); 5516 break; 5517 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 5518 mTemporarilyDisconnectWifi = (message.arg1 == 1); 5519 replyToMessage(message, WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE); 5520 break; 5521 /* Link configuration (IP address, DNS, ...) changes notified via netlink */ 5522 case CMD_UPDATE_LINKPROPERTIES: 5523 updateLinkProperties((LinkProperties) message.obj); 5524 break; 5525 case CMD_GET_MATCHING_CONFIG: 5526 replyToMessage(message, message.what); 5527 break; 5528 case CMD_IP_CONFIGURATION_SUCCESSFUL: 5529 case CMD_IP_CONFIGURATION_LOST: 5530 case CMD_IP_REACHABILITY_LOST: 5531 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5532 break; 5533 case CMD_GET_CONNECTION_STATISTICS: 5534 replyToMessage(message, message.what, mWifiConnectionStatistics); 5535 break; 5536 case CMD_REMOVE_APP_CONFIGURATIONS: 5537 deferMessage(message); 5538 break; 5539 case CMD_REMOVE_USER_CONFIGURATIONS: 5540 deferMessage(message); 5541 break; 5542 case CMD_START_IP_PACKET_OFFLOAD: 5543 if (mNetworkAgent != null) mNetworkAgent.onPacketKeepaliveEvent( 5544 message.arg1, 5545 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK); 5546 break; 5547 case CMD_STOP_IP_PACKET_OFFLOAD: 5548 if (mNetworkAgent != null) mNetworkAgent.onPacketKeepaliveEvent( 5549 message.arg1, 5550 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK); 5551 break; 5552 case CMD_START_RSSI_MONITORING_OFFLOAD: 5553 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5554 break; 5555 case CMD_STOP_RSSI_MONITORING_OFFLOAD: 5556 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5557 break; 5558 case CMD_USER_SWITCH: 5559 mCurrentUserId = message.arg1; 5560 mWifiConfigStore.handleUserSwitch(); 5561 break; 5562 case CMD_ADD_PASSPOINT_MO: 5563 case CMD_MODIFY_PASSPOINT_MO: 5564 case CMD_QUERY_OSU_ICON: 5565 case CMD_MATCH_PROVIDER_NETWORK: 5566 /* reply with arg1 = 0 - it returns API failure to the calling app 5567 * (message.what is not looked at) 5568 */ 5569 replyToMessage(message, message.what); 5570 break; 5571 default: 5572 loge("Error! unhandled message" + message); 5573 break; 5574 } 5575 return HANDLED; 5576 } 5577 } 5578 5579 class InitialState extends State { 5580 @Override 5581 public void enter() { 5582 mWifiNative.stopHal(); 5583 mWifiNative.unloadDriver(); 5584 if (mWifiP2pChannel == null) { 5585 mWifiP2pChannel = new AsyncChannel(); 5586 mWifiP2pChannel.connect(mContext, getHandler(), 5587 mWifiP2pServiceImpl.getP2pStateMachineMessenger()); 5588 } 5589 5590 if (mWifiApConfigStore == null) { 5591 mWifiApConfigStore = mFacade.makeApConfigStore(mContext); 5592 } 5593 5594 if (mWifiConfigStore.enableHalBasedPno.get()) { 5595 // make sure developer Settings are in sync with the config option 5596 mHalBasedPnoEnableInDevSettings = true; 5597 } 5598 } 5599 @Override 5600 public boolean processMessage(Message message) { 5601 logStateAndMessage(message, this); 5602 switch (message.what) { 5603 case CMD_START_SUPPLICANT: 5604 if (mWifiNative.loadDriver()) { 5605 try { 5606 mNwService.wifiFirmwareReload(mInterfaceName, "STA"); 5607 } catch (Exception e) { 5608 loge("Failed to reload STA firmware " + e); 5609 // Continue 5610 } 5611 5612 try { 5613 // A runtime crash can leave the interface up and 5614 // IP addresses configured, and this affects 5615 // connectivity when supplicant starts up. 5616 // Ensure interface is down and we have no IP 5617 // addresses before a supplicant start. 5618 mNwService.setInterfaceDown(mInterfaceName); 5619 mNwService.clearInterfaceAddresses(mInterfaceName); 5620 5621 // Set privacy extensions 5622 mNwService.setInterfaceIpv6PrivacyExtensions(mInterfaceName, true); 5623 5624 // IPv6 is enabled only as long as access point is connected since: 5625 // - IPv6 addresses and routes stick around after disconnection 5626 // - kernel is unaware when connected and fails to start IPv6 negotiation 5627 // - kernel can start autoconfiguration when 802.1x is not complete 5628 mNwService.disableIpv6(mInterfaceName); 5629 } catch (RemoteException re) { 5630 loge("Unable to change interface settings: " + re); 5631 } catch (IllegalStateException ie) { 5632 loge("Unable to change interface settings: " + ie); 5633 } 5634 5635 /* Stop a running supplicant after a runtime restart 5636 * Avoids issues with drivers that do not handle interface down 5637 * on a running supplicant properly. 5638 */ 5639 mWifiMonitor.killSupplicant(mP2pSupported); 5640 5641 if (mWifiNative.startHal() == false) { 5642 /* starting HAL is optional */ 5643 loge("Failed to start HAL"); 5644 } 5645 5646 if (mWifiNative.startSupplicant(mP2pSupported)) { 5647 setWifiState(WIFI_STATE_ENABLING); 5648 if (DBG) log("Supplicant start successful"); 5649 mWifiMonitor.startMonitoring(mInterfaceName); 5650 transitionTo(mSupplicantStartingState); 5651 } else { 5652 loge("Failed to start supplicant!"); 5653 } 5654 } else { 5655 loge("Failed to load driver"); 5656 } 5657 break; 5658 case CMD_START_AP: 5659 if (mWifiNative.loadDriver() == false) { 5660 loge("Failed to load driver for softap"); 5661 } else { 5662 if (enableSoftAp() == true) { 5663 setWifiApState(WIFI_AP_STATE_ENABLING, 0); 5664 transitionTo(mSoftApStartingState); 5665 } else { 5666 setWifiApState(WIFI_AP_STATE_FAILED, 5667 WifiManager.SAP_START_FAILURE_GENERAL); 5668 transitionTo(mInitialState); 5669 } 5670 } 5671 break; 5672 default: 5673 return NOT_HANDLED; 5674 } 5675 return HANDLED; 5676 } 5677 } 5678 5679 class SupplicantStartingState extends State { 5680 private void initializeWpsDetails() { 5681 String detail; 5682 detail = SystemProperties.get("ro.product.name", ""); 5683 if (!mWifiNative.setDeviceName(detail)) { 5684 loge("Failed to set device name " + detail); 5685 } 5686 detail = SystemProperties.get("ro.product.manufacturer", ""); 5687 if (!mWifiNative.setManufacturer(detail)) { 5688 loge("Failed to set manufacturer " + detail); 5689 } 5690 detail = SystemProperties.get("ro.product.model", ""); 5691 if (!mWifiNative.setModelName(detail)) { 5692 loge("Failed to set model name " + detail); 5693 } 5694 detail = SystemProperties.get("ro.product.model", ""); 5695 if (!mWifiNative.setModelNumber(detail)) { 5696 loge("Failed to set model number " + detail); 5697 } 5698 detail = SystemProperties.get("ro.serialno", ""); 5699 if (!mWifiNative.setSerialNumber(detail)) { 5700 loge("Failed to set serial number " + detail); 5701 } 5702 if (!mWifiNative.setConfigMethods("physical_display virtual_push_button")) { 5703 loge("Failed to set WPS config methods"); 5704 } 5705 if (!mWifiNative.setDeviceType(mPrimaryDeviceType)) { 5706 loge("Failed to set primary device type " + mPrimaryDeviceType); 5707 } 5708 } 5709 5710 @Override 5711 public boolean processMessage(Message message) { 5712 logStateAndMessage(message, this); 5713 5714 switch(message.what) { 5715 case WifiMonitor.SUP_CONNECTION_EVENT: 5716 if (DBG) log("Supplicant connection established"); 5717 setWifiState(WIFI_STATE_ENABLED); 5718 mSupplicantRestartCount = 0; 5719 /* Reset the supplicant state to indicate the supplicant 5720 * state is not known at this time */ 5721 mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE); 5722 /* Initialize data structures */ 5723 mLastBssid = null; 5724 mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 5725 mLastSignalLevel = -1; 5726 5727 mWifiInfo.setMacAddress(mWifiNative.getMacAddress()); 5728 /* set frequency band of operation */ 5729 setFrequencyBand(); 5730 mWifiNative.enableSaveConfig(); 5731 mWifiConfigStore.loadAndEnableAllNetworks(); 5732 if (mWifiConfigStore.enableVerboseLogging.get() > 0) { 5733 enableVerboseLogging(mWifiConfigStore.enableVerboseLogging.get()); 5734 } 5735 initializeWpsDetails(); 5736 5737 sendSupplicantConnectionChangedBroadcast(true); 5738 transitionTo(mDriverStartedState); 5739 break; 5740 case WifiMonitor.SUP_DISCONNECTION_EVENT: 5741 if (++mSupplicantRestartCount <= SUPPLICANT_RESTART_TRIES) { 5742 loge("Failed to setup control channel, restart supplicant"); 5743 mWifiMonitor.killSupplicant(mP2pSupported); 5744 transitionTo(mInitialState); 5745 sendMessageDelayed(CMD_START_SUPPLICANT, SUPPLICANT_RESTART_INTERVAL_MSECS); 5746 } else { 5747 loge("Failed " + mSupplicantRestartCount + 5748 " times to start supplicant, unload driver"); 5749 mSupplicantRestartCount = 0; 5750 setWifiState(WIFI_STATE_UNKNOWN); 5751 transitionTo(mInitialState); 5752 } 5753 break; 5754 case CMD_START_SUPPLICANT: 5755 case CMD_STOP_SUPPLICANT: 5756 case CMD_START_AP: 5757 case CMD_STOP_AP: 5758 case CMD_START_DRIVER: 5759 case CMD_STOP_DRIVER: 5760 case CMD_SET_OPERATIONAL_MODE: 5761 case CMD_SET_COUNTRY_CODE: 5762 case CMD_SET_FREQUENCY_BAND: 5763 case CMD_START_PACKET_FILTERING: 5764 case CMD_STOP_PACKET_FILTERING: 5765 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 5766 deferMessage(message); 5767 break; 5768 default: 5769 return NOT_HANDLED; 5770 } 5771 return HANDLED; 5772 } 5773 } 5774 5775 class SupplicantStartedState extends State { 5776 @Override 5777 public void enter() { 5778 /* Wifi is available as long as we have a connection to supplicant */ 5779 mNetworkInfo.setIsAvailable(true); 5780 if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo); 5781 5782 int defaultInterval = mContext.getResources().getInteger( 5783 R.integer.config_wifi_supplicant_scan_interval); 5784 5785 mSupplicantScanIntervalMs = mFacade.getLongSetting(mContext, 5786 Settings.Global.WIFI_SUPPLICANT_SCAN_INTERVAL_MS, 5787 defaultInterval); 5788 5789 mWifiNative.setScanInterval((int)mSupplicantScanIntervalMs / 1000); 5790 mWifiNative.setExternalSim(true); 5791 5792 /* turn on use of DFS channels */ 5793 mWifiNative.setDfsFlag(true); 5794 5795 /* set country code */ 5796 initializeCountryCode(); 5797 5798 setRandomMacOui(); 5799 mWifiNative.enableAutoConnect(false); 5800 } 5801 5802 @Override 5803 public boolean processMessage(Message message) { 5804 logStateAndMessage(message, this); 5805 5806 switch(message.what) { 5807 case CMD_STOP_SUPPLICANT: /* Supplicant stopped by user */ 5808 if (mP2pSupported) { 5809 transitionTo(mWaitForP2pDisableState); 5810 } else { 5811 transitionTo(mSupplicantStoppingState); 5812 } 5813 break; 5814 case WifiMonitor.SUP_DISCONNECTION_EVENT: /* Supplicant connection lost */ 5815 loge("Connection lost, restart supplicant"); 5816 handleSupplicantConnectionLoss(true); 5817 handleNetworkDisconnect(); 5818 mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE); 5819 if (mP2pSupported) { 5820 transitionTo(mWaitForP2pDisableState); 5821 } else { 5822 transitionTo(mInitialState); 5823 } 5824 sendMessageDelayed(CMD_START_SUPPLICANT, SUPPLICANT_RESTART_INTERVAL_MSECS); 5825 break; 5826 case WifiMonitor.SCAN_RESULTS_EVENT: 5827 case WifiMonitor.SCAN_FAILED_EVENT: 5828 maybeRegisterNetworkFactory(); // Make sure our NetworkFactory is registered 5829 noteScanEnd(); 5830 setScanResults(); 5831 if (mIsFullScanOngoing || mSendScanResultsBroadcast) { 5832 /* Just updated results from full scan, let apps know about this */ 5833 boolean scanSucceeded = message.what == WifiMonitor.SCAN_RESULTS_EVENT; 5834 sendScanResultsAvailableBroadcast(scanSucceeded); 5835 } 5836 mSendScanResultsBroadcast = false; 5837 mIsScanOngoing = false; 5838 mIsFullScanOngoing = false; 5839 if (mBufferedScanMsg.size() > 0) 5840 sendMessage(mBufferedScanMsg.remove()); 5841 break; 5842 case CMD_PING_SUPPLICANT: 5843 boolean ok = mWifiNative.ping(); 5844 replyToMessage(message, message.what, ok ? SUCCESS : FAILURE); 5845 break; 5846 case CMD_GET_CAPABILITY_FREQ: 5847 String freqs = mWifiNative.getFreqCapability(); 5848 replyToMessage(message, message.what, freqs); 5849 break; 5850 case CMD_START_AP: 5851 /* Cannot start soft AP while in client mode */ 5852 loge("Failed to start soft AP with a running supplicant"); 5853 setWifiApState(WIFI_AP_STATE_FAILED, WifiManager.SAP_START_FAILURE_GENERAL); 5854 break; 5855 case CMD_SET_OPERATIONAL_MODE: 5856 mOperationalMode = message.arg1; 5857 mWifiConfigStore. 5858 setAndEnableLastSelectedConfiguration( 5859 WifiConfiguration.INVALID_NETWORK_ID); 5860 break; 5861 case CMD_TARGET_BSSID: 5862 // Trying to associate to this BSSID 5863 if (message.obj != null) { 5864 mTargetRoamBSSID = (String) message.obj; 5865 } 5866 break; 5867 case CMD_GET_LINK_LAYER_STATS: 5868 WifiLinkLayerStats stats = getWifiLinkLayerStats(DBG); 5869 if (stats == null) { 5870 // When firmware doesnt support link layer stats, return an empty object 5871 stats = new WifiLinkLayerStats(); 5872 } 5873 replyToMessage(message, message.what, stats); 5874 break; 5875 case CMD_SET_COUNTRY_CODE: 5876 String country = (String) message.obj; 5877 final boolean persist = (message.arg2 == 1); 5878 final int sequence = message.arg1; 5879 if (sequence != mCountryCodeSequence.get()) { 5880 if (DBG) log("set country code ignored due to sequnce num"); 5881 break; 5882 } 5883 5884 country = country.toUpperCase(Locale.ROOT); 5885 5886 if (DBG) log("set country code " + (country == null ? "(null)" : country)); 5887 5888 if (!TextUtils.equals(mDriverSetCountryCode, country)) { 5889 if (mWifiNative.setCountryCode(country)) { 5890 mDriverSetCountryCode = country; 5891 } else { 5892 loge("Failed to set country code " + country); 5893 } 5894 } 5895 5896 if (persist) { 5897 Settings.Global.putString(mContext.getContentResolver(), 5898 Settings.Global.WIFI_COUNTRY_CODE, 5899 country == null ? "" : country); 5900 } 5901 5902 mWifiP2pChannel.sendMessage(WifiP2pServiceImpl.SET_COUNTRY_CODE, country); 5903 break; 5904 case CMD_RESET_SIM_NETWORKS: 5905 log("resetting EAP-SIM/AKA/AKA' networks since SIM was removed"); 5906 mWifiConfigStore.resetSimNetworks(); 5907 break; 5908 default: 5909 return NOT_HANDLED; 5910 } 5911 return HANDLED; 5912 } 5913 5914 @Override 5915 public void exit() { 5916 mNetworkInfo.setIsAvailable(false); 5917 if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo); 5918 } 5919 } 5920 5921 class SupplicantStoppingState extends State { 5922 @Override 5923 public void enter() { 5924 /* Send any reset commands to supplicant before shutting it down */ 5925 handleNetworkDisconnect(); 5926 5927 String suppState = System.getProperty("init.svc.wpa_supplicant"); 5928 if (suppState == null) suppState = "unknown"; 5929 String p2pSuppState = System.getProperty("init.svc.p2p_supplicant"); 5930 if (p2pSuppState == null) p2pSuppState = "unknown"; 5931 5932 logd("SupplicantStoppingState: stopSupplicant " 5933 + " init.svc.wpa_supplicant=" + suppState 5934 + " init.svc.p2p_supplicant=" + p2pSuppState); 5935 mWifiMonitor.stopSupplicant(); 5936 5937 /* Send ourselves a delayed message to indicate failure after a wait time */ 5938 sendMessageDelayed(obtainMessage(CMD_STOP_SUPPLICANT_FAILED, 5939 ++mSupplicantStopFailureToken, 0), SUPPLICANT_RESTART_INTERVAL_MSECS); 5940 setWifiState(WIFI_STATE_DISABLING); 5941 mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE); 5942 } 5943 @Override 5944 public boolean processMessage(Message message) { 5945 logStateAndMessage(message, this); 5946 5947 switch(message.what) { 5948 case WifiMonitor.SUP_CONNECTION_EVENT: 5949 loge("Supplicant connection received while stopping"); 5950 break; 5951 case WifiMonitor.SUP_DISCONNECTION_EVENT: 5952 if (DBG) log("Supplicant connection lost"); 5953 handleSupplicantConnectionLoss(false); 5954 transitionTo(mInitialState); 5955 break; 5956 case CMD_STOP_SUPPLICANT_FAILED: 5957 if (message.arg1 == mSupplicantStopFailureToken) { 5958 loge("Timed out on a supplicant stop, kill and proceed"); 5959 handleSupplicantConnectionLoss(true); 5960 transitionTo(mInitialState); 5961 } 5962 break; 5963 case CMD_START_SUPPLICANT: 5964 case CMD_STOP_SUPPLICANT: 5965 case CMD_START_AP: 5966 case CMD_STOP_AP: 5967 case CMD_START_DRIVER: 5968 case CMD_STOP_DRIVER: 5969 case CMD_SET_OPERATIONAL_MODE: 5970 case CMD_SET_COUNTRY_CODE: 5971 case CMD_SET_FREQUENCY_BAND: 5972 case CMD_START_PACKET_FILTERING: 5973 case CMD_STOP_PACKET_FILTERING: 5974 deferMessage(message); 5975 break; 5976 default: 5977 return NOT_HANDLED; 5978 } 5979 return HANDLED; 5980 } 5981 } 5982 5983 class DriverStartingState extends State { 5984 private int mTries; 5985 @Override 5986 public void enter() { 5987 mTries = 1; 5988 /* Send ourselves a delayed message to start driver a second time */ 5989 sendMessageDelayed(obtainMessage(CMD_DRIVER_START_TIMED_OUT, 5990 ++mDriverStartToken, 0), DRIVER_START_TIME_OUT_MSECS); 5991 } 5992 @Override 5993 public boolean processMessage(Message message) { 5994 logStateAndMessage(message, this); 5995 5996 switch(message.what) { 5997 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 5998 SupplicantState state = handleSupplicantStateChange(message); 5999 /* If suplicant is exiting out of INTERFACE_DISABLED state into 6000 * a state that indicates driver has started, it is ready to 6001 * receive driver commands 6002 */ 6003 if (SupplicantState.isDriverActive(state)) { 6004 transitionTo(mDriverStartedState); 6005 } 6006 break; 6007 case CMD_DRIVER_START_TIMED_OUT: 6008 if (message.arg1 == mDriverStartToken) { 6009 if (mTries >= 2) { 6010 loge("Failed to start driver after " + mTries); 6011 transitionTo(mDriverStoppedState); 6012 } else { 6013 loge("Driver start failed, retrying"); 6014 mWakeLock.acquire(); 6015 mWifiNative.startDriver(); 6016 mWakeLock.release(); 6017 6018 ++mTries; 6019 /* Send ourselves a delayed message to start driver again */ 6020 sendMessageDelayed(obtainMessage(CMD_DRIVER_START_TIMED_OUT, 6021 ++mDriverStartToken, 0), DRIVER_START_TIME_OUT_MSECS); 6022 } 6023 } 6024 break; 6025 /* Queue driver commands & connection events */ 6026 case CMD_START_DRIVER: 6027 case CMD_STOP_DRIVER: 6028 case WifiMonitor.NETWORK_CONNECTION_EVENT: 6029 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6030 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 6031 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 6032 case WifiMonitor.WPS_OVERLAP_EVENT: 6033 case CMD_SET_COUNTRY_CODE: 6034 case CMD_SET_FREQUENCY_BAND: 6035 case CMD_START_PACKET_FILTERING: 6036 case CMD_STOP_PACKET_FILTERING: 6037 case CMD_START_SCAN: 6038 case CMD_DISCONNECT: 6039 case CMD_REASSOCIATE: 6040 case CMD_RECONNECT: 6041 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 6042 deferMessage(message); 6043 break; 6044 case WifiMonitor.SCAN_RESULTS_EVENT: 6045 case WifiMonitor.SCAN_FAILED_EVENT: 6046 // Loose scan results obtained in Driver Starting state, they can only confuse 6047 // the state machine 6048 break; 6049 default: 6050 return NOT_HANDLED; 6051 } 6052 return HANDLED; 6053 } 6054 } 6055 6056 class DriverStartedState extends State { 6057 @Override 6058 public void enter() { 6059 6060 if (PDBG) { 6061 logd("DriverStartedState enter"); 6062 } 6063 6064 mWifiLogger.startLogging(mVerboseLoggingLevel > 0); 6065 mIsRunning = true; 6066 updateBatteryWorkSource(null); 6067 /** 6068 * Enable bluetooth coexistence scan mode when bluetooth connection is active. 6069 * When this mode is on, some of the low-level scan parameters used by the 6070 * driver are changed to reduce interference with bluetooth 6071 */ 6072 mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive); 6073 /* initialize network state */ 6074 setNetworkDetailedState(DetailedState.DISCONNECTED); 6075 6076 /* Remove any filtering on Multicast v6 at start */ 6077 mWifiNative.stopFilteringMulticastV6Packets(); 6078 6079 /* Reset Multicast v4 filtering state */ 6080 if (mFilteringMulticastV4Packets.get()) { 6081 mWifiNative.startFilteringMulticastV4Packets(); 6082 } else { 6083 mWifiNative.stopFilteringMulticastV4Packets(); 6084 } 6085 6086 if (mOperationalMode != CONNECT_MODE) { 6087 mWifiNative.disconnect(); 6088 mWifiConfigStore.disableAllNetworks(); 6089 if (mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 6090 setWifiState(WIFI_STATE_DISABLED); 6091 } 6092 transitionTo(mScanModeState); 6093 } else { 6094 6095 // Status pulls in the current supplicant state and network connection state 6096 // events over the monitor connection. This helps framework sync up with 6097 // current supplicant state 6098 // TODO: actually check th supplicant status string and make sure the supplicant 6099 // is in disconnecte4d state. 6100 mWifiNative.status(); 6101 // Transitioning to Disconnected state will trigger a scan and subsequently AutoJoin 6102 transitionTo(mDisconnectedState); 6103 transitionTo(mDisconnectedState); 6104 } 6105 6106 // We may have missed screen update at boot 6107 if (mScreenBroadcastReceived.get() == false) { 6108 PowerManager powerManager = (PowerManager)mContext.getSystemService( 6109 Context.POWER_SERVICE); 6110 handleScreenStateChanged(powerManager.isScreenOn()); 6111 } else { 6112 // Set the right suspend mode settings 6113 mWifiNative.setSuspendOptimizations(mSuspendOptNeedsDisabled == 0 6114 && mUserWantsSuspendOpt.get()); 6115 } 6116 mWifiNative.setPowerSave(true); 6117 6118 if (mP2pSupported) { 6119 if (mOperationalMode == CONNECT_MODE) { 6120 mWifiP2pChannel.sendMessage(WifiStateMachine.CMD_ENABLE_P2P); 6121 } else { 6122 // P2P statemachine starts in disabled state, and is not enabled until 6123 // CMD_ENABLE_P2P is sent from here; so, nothing needs to be done to 6124 // keep it disabled. 6125 } 6126 } 6127 6128 final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE); 6129 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 6130 intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_ENABLED); 6131 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 6132 6133 mHalFeatureSet = mWifiNative.getSupportedFeatureSet(); 6134 if ((mHalFeatureSet & WifiManager.WIFI_FEATURE_HAL_EPNO) 6135 == WifiManager.WIFI_FEATURE_HAL_EPNO) { 6136 mHalBasedPnoDriverSupported = true; 6137 } 6138 6139 // Enable link layer stats gathering 6140 mWifiNative.setWifiLinkLayerStats("wlan0", 1); 6141 6142 if (PDBG) { 6143 logd("Driverstarted State enter done, epno=" + mHalBasedPnoDriverSupported 6144 + " feature=" + mHalFeatureSet); 6145 } 6146 } 6147 6148 @Override 6149 public boolean processMessage(Message message) { 6150 logStateAndMessage(message, this); 6151 6152 switch(message.what) { 6153 case CMD_START_SCAN: 6154 handleScanRequest(message); 6155 break; 6156 case CMD_SET_FREQUENCY_BAND: 6157 int band = message.arg1; 6158 if (DBG) log("set frequency band " + band); 6159 if (mWifiNative.setBand(band)) { 6160 6161 if (PDBG) logd("did set frequency band " + band); 6162 6163 mFrequencyBand.set(band); 6164 // Flush old data - like scan results 6165 mWifiNative.bssFlush(); 6166 6167 if (PDBG) logd("done set frequency band " + band); 6168 6169 } else { 6170 loge("Failed to set frequency band " + band); 6171 } 6172 break; 6173 case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE: 6174 mBluetoothConnectionActive = (message.arg1 != 6175 BluetoothAdapter.STATE_DISCONNECTED); 6176 mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive); 6177 break; 6178 case CMD_STOP_DRIVER: 6179 int mode = message.arg1; 6180 6181 log("stop driver"); 6182 mWifiConfigStore.disableAllNetworks(); 6183 6184 if (getCurrentState() != mDisconnectedState) { 6185 mWifiNative.disconnect(); 6186 handleNetworkDisconnect(); 6187 } 6188 mWakeLock.acquire(); 6189 mWifiNative.stopDriver(); 6190 mWakeLock.release(); 6191 if (mP2pSupported) { 6192 transitionTo(mWaitForP2pDisableState); 6193 } else { 6194 transitionTo(mDriverStoppingState); 6195 } 6196 break; 6197 case CMD_START_DRIVER: 6198 if (mOperationalMode == CONNECT_MODE) { 6199 mWifiConfigStore.enableAllNetworks(); 6200 } 6201 break; 6202 case CMD_START_PACKET_FILTERING: 6203 if (message.arg1 == MULTICAST_V6) { 6204 mWifiNative.startFilteringMulticastV6Packets(); 6205 } else if (message.arg1 == MULTICAST_V4) { 6206 mWifiNative.startFilteringMulticastV4Packets(); 6207 } else { 6208 loge("Illegal arugments to CMD_START_PACKET_FILTERING"); 6209 } 6210 break; 6211 case CMD_STOP_PACKET_FILTERING: 6212 if (message.arg1 == MULTICAST_V6) { 6213 mWifiNative.stopFilteringMulticastV6Packets(); 6214 } else if (message.arg1 == MULTICAST_V4) { 6215 mWifiNative.stopFilteringMulticastV4Packets(); 6216 } else { 6217 loge("Illegal arugments to CMD_STOP_PACKET_FILTERING"); 6218 } 6219 break; 6220 case CMD_SET_SUSPEND_OPT_ENABLED: 6221 if (message.arg1 == 1) { 6222 setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, true); 6223 mSuspendWakeLock.release(); 6224 } else { 6225 setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, false); 6226 } 6227 break; 6228 case CMD_SET_HIGH_PERF_MODE: 6229 if (message.arg1 == 1) { 6230 setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, false); 6231 } else { 6232 setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, true); 6233 } 6234 break; 6235 case CMD_ENABLE_TDLS: 6236 if (message.obj != null) { 6237 String remoteAddress = (String) message.obj; 6238 boolean enable = (message.arg1 == 1); 6239 mWifiNative.startTdls(remoteAddress, enable); 6240 } 6241 break; 6242 case WifiMonitor.ANQP_DONE_EVENT: 6243 mWifiConfigStore.notifyANQPDone((Long) message.obj, message.arg1 != 0); 6244 break; 6245 case CMD_STOP_IP_PACKET_OFFLOAD: { 6246 int slot = message.arg1; 6247 int ret = stopWifiIPPacketOffload(slot); 6248 if (mNetworkAgent != null) { 6249 mNetworkAgent.onPacketKeepaliveEvent(slot, ret); 6250 } 6251 break; 6252 } 6253 case WifiMonitor.RX_HS20_ANQP_ICON_EVENT: 6254 mWifiConfigStore.notifyIconReceived((IconEvent) message.obj); 6255 break; 6256 case WifiMonitor.HS20_REMEDIATION_EVENT: 6257 mWifiConfigStore.wnmFrameReceived((WnmData) message.obj); 6258 break; 6259 default: 6260 return NOT_HANDLED; 6261 } 6262 return HANDLED; 6263 } 6264 @Override 6265 public void exit() { 6266 6267 mWifiLogger.stopLogging(); 6268 6269 mIsRunning = false; 6270 updateBatteryWorkSource(null); 6271 mScanResults = new ArrayList<>(); 6272 6273 final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE); 6274 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 6275 intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED); 6276 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 6277 noteScanEnd(); // wrap up any pending request. 6278 mBufferedScanMsg.clear(); 6279 } 6280 } 6281 6282 class WaitForP2pDisableState extends State { 6283 private State mTransitionToState; 6284 @Override 6285 public void enter() { 6286 switch (getCurrentMessage().what) { 6287 case WifiMonitor.SUP_DISCONNECTION_EVENT: 6288 mTransitionToState = mInitialState; 6289 break; 6290 case CMD_STOP_DRIVER: 6291 mTransitionToState = mDriverStoppingState; 6292 break; 6293 case CMD_STOP_SUPPLICANT: 6294 mTransitionToState = mSupplicantStoppingState; 6295 break; 6296 default: 6297 mTransitionToState = mDriverStoppingState; 6298 break; 6299 } 6300 mWifiP2pChannel.sendMessage(WifiStateMachine.CMD_DISABLE_P2P_REQ); 6301 } 6302 @Override 6303 public boolean processMessage(Message message) { 6304 logStateAndMessage(message, this); 6305 6306 switch(message.what) { 6307 case WifiStateMachine.CMD_DISABLE_P2P_RSP: 6308 transitionTo(mTransitionToState); 6309 break; 6310 /* Defer wifi start/shut and driver commands */ 6311 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6312 case CMD_START_SUPPLICANT: 6313 case CMD_STOP_SUPPLICANT: 6314 case CMD_START_AP: 6315 case CMD_STOP_AP: 6316 case CMD_START_DRIVER: 6317 case CMD_STOP_DRIVER: 6318 case CMD_SET_OPERATIONAL_MODE: 6319 case CMD_SET_COUNTRY_CODE: 6320 case CMD_SET_FREQUENCY_BAND: 6321 case CMD_START_PACKET_FILTERING: 6322 case CMD_STOP_PACKET_FILTERING: 6323 case CMD_START_SCAN: 6324 case CMD_DISCONNECT: 6325 case CMD_REASSOCIATE: 6326 case CMD_RECONNECT: 6327 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 6328 deferMessage(message); 6329 break; 6330 default: 6331 return NOT_HANDLED; 6332 } 6333 return HANDLED; 6334 } 6335 } 6336 6337 class DriverStoppingState extends State { 6338 @Override 6339 public boolean processMessage(Message message) { 6340 logStateAndMessage(message, this); 6341 6342 switch(message.what) { 6343 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6344 SupplicantState state = handleSupplicantStateChange(message); 6345 if (state == SupplicantState.INTERFACE_DISABLED) { 6346 transitionTo(mDriverStoppedState); 6347 } 6348 break; 6349 /* Queue driver commands */ 6350 case CMD_START_DRIVER: 6351 case CMD_STOP_DRIVER: 6352 case CMD_SET_COUNTRY_CODE: 6353 case CMD_SET_FREQUENCY_BAND: 6354 case CMD_START_PACKET_FILTERING: 6355 case CMD_STOP_PACKET_FILTERING: 6356 case CMD_START_SCAN: 6357 case CMD_DISCONNECT: 6358 case CMD_REASSOCIATE: 6359 case CMD_RECONNECT: 6360 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 6361 deferMessage(message); 6362 break; 6363 default: 6364 return NOT_HANDLED; 6365 } 6366 return HANDLED; 6367 } 6368 } 6369 6370 class DriverStoppedState extends State { 6371 @Override 6372 public boolean processMessage(Message message) { 6373 logStateAndMessage(message, this); 6374 switch (message.what) { 6375 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6376 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 6377 SupplicantState state = stateChangeResult.state; 6378 // A WEXT bug means that we can be back to driver started state 6379 // unexpectedly 6380 if (SupplicantState.isDriverActive(state)) { 6381 transitionTo(mDriverStartedState); 6382 } 6383 break; 6384 case CMD_START_DRIVER: 6385 mWakeLock.acquire(); 6386 mWifiNative.startDriver(); 6387 mWakeLock.release(); 6388 transitionTo(mDriverStartingState); 6389 break; 6390 default: 6391 return NOT_HANDLED; 6392 } 6393 return HANDLED; 6394 } 6395 } 6396 6397 class ScanModeState extends State { 6398 private int mLastOperationMode; 6399 @Override 6400 public void enter() { 6401 mLastOperationMode = mOperationalMode; 6402 } 6403 @Override 6404 public boolean processMessage(Message message) { 6405 logStateAndMessage(message, this); 6406 6407 switch(message.what) { 6408 case CMD_SET_OPERATIONAL_MODE: 6409 if (message.arg1 == CONNECT_MODE) { 6410 6411 if (mLastOperationMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 6412 setWifiState(WIFI_STATE_ENABLED); 6413 // Load and re-enable networks when going back to enabled state 6414 // This is essential for networks to show up after restore 6415 mWifiConfigStore.loadAndEnableAllNetworks(); 6416 mWifiP2pChannel.sendMessage(CMD_ENABLE_P2P); 6417 } else { 6418 mWifiConfigStore.enableAllNetworks(); 6419 } 6420 // start a scan to trigger Quality network selection 6421 startScan(ENABLE_WIFI, 0, null, null); 6422 6423 // Loose last selection choice since user toggled WiFi 6424 mWifiConfigStore. 6425 setAndEnableLastSelectedConfiguration( 6426 WifiConfiguration.INVALID_NETWORK_ID); 6427 6428 mOperationalMode = CONNECT_MODE; 6429 transitionTo(mDisconnectedState); 6430 } else { 6431 // Nothing to do 6432 return HANDLED; 6433 } 6434 break; 6435 // Handle scan. All the connection related commands are 6436 // handled only in ConnectModeState 6437 case CMD_START_SCAN: 6438 handleScanRequest(message); 6439 break; 6440 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6441 SupplicantState state = handleSupplicantStateChange(message); 6442 if(DBG) log("SupplicantState= " + state); 6443 break; 6444 default: 6445 return NOT_HANDLED; 6446 } 6447 return HANDLED; 6448 } 6449 } 6450 6451 6452 String smToString(Message message) { 6453 return smToString(message.what); 6454 } 6455 6456 String smToString(int what) { 6457 String s = "unknown"; 6458 switch (what) { 6459 case WifiMonitor.DRIVER_HUNG_EVENT: 6460 s = "DRIVER_HUNG_EVENT"; 6461 break; 6462 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: 6463 s = "AsyncChannel.CMD_CHANNEL_HALF_CONNECTED"; 6464 break; 6465 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: 6466 s = "AsyncChannel.CMD_CHANNEL_DISCONNECTED"; 6467 break; 6468 case CMD_SET_FREQUENCY_BAND: 6469 s = "CMD_SET_FREQUENCY_BAND"; 6470 break; 6471 case CMD_DELAYED_NETWORK_DISCONNECT: 6472 s = "CMD_DELAYED_NETWORK_DISCONNECT"; 6473 break; 6474 case CMD_TEST_NETWORK_DISCONNECT: 6475 s = "CMD_TEST_NETWORK_DISCONNECT"; 6476 break; 6477 case CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER: 6478 s = "CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER"; 6479 break; 6480 case CMD_DISABLE_EPHEMERAL_NETWORK: 6481 s = "CMD_DISABLE_EPHEMERAL_NETWORK"; 6482 break; 6483 case CMD_START_DRIVER: 6484 s = "CMD_START_DRIVER"; 6485 break; 6486 case CMD_STOP_DRIVER: 6487 s = "CMD_STOP_DRIVER"; 6488 break; 6489 case CMD_STOP_SUPPLICANT: 6490 s = "CMD_STOP_SUPPLICANT"; 6491 break; 6492 case CMD_STOP_SUPPLICANT_FAILED: 6493 s = "CMD_STOP_SUPPLICANT_FAILED"; 6494 break; 6495 case CMD_START_SUPPLICANT: 6496 s = "CMD_START_SUPPLICANT"; 6497 break; 6498 case CMD_TETHER_STATE_CHANGE: 6499 s = "CMD_TETHER_STATE_CHANGE"; 6500 break; 6501 case CMD_TETHER_NOTIFICATION_TIMED_OUT: 6502 s = "CMD_TETHER_NOTIFICATION_TIMED_OUT"; 6503 break; 6504 case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE: 6505 s = "CMD_BLUETOOTH_ADAPTER_STATE_CHANGE"; 6506 break; 6507 case CMD_ADD_OR_UPDATE_NETWORK: 6508 s = "CMD_ADD_OR_UPDATE_NETWORK"; 6509 break; 6510 case CMD_REMOVE_NETWORK: 6511 s = "CMD_REMOVE_NETWORK"; 6512 break; 6513 case CMD_ENABLE_NETWORK: 6514 s = "CMD_ENABLE_NETWORK"; 6515 break; 6516 case CMD_ENABLE_ALL_NETWORKS: 6517 s = "CMD_ENABLE_ALL_NETWORKS"; 6518 break; 6519 case CMD_AUTO_CONNECT: 6520 s = "CMD_AUTO_CONNECT"; 6521 break; 6522 case CMD_AUTO_ROAM: 6523 s = "CMD_AUTO_ROAM"; 6524 break; 6525 case CMD_AUTO_SAVE_NETWORK: 6526 s = "CMD_AUTO_SAVE_NETWORK"; 6527 break; 6528 case CMD_BOOT_COMPLETED: 6529 s = "CMD_BOOT_COMPLETED"; 6530 break; 6531 case DhcpStateMachine.CMD_START_DHCP: 6532 s = "CMD_START_DHCP"; 6533 break; 6534 case DhcpStateMachine.CMD_STOP_DHCP: 6535 s = "CMD_STOP_DHCP"; 6536 break; 6537 case DhcpStateMachine.CMD_RENEW_DHCP: 6538 s = "CMD_RENEW_DHCP"; 6539 break; 6540 case DhcpStateMachine.CMD_PRE_DHCP_ACTION: 6541 s = "CMD_PRE_DHCP_ACTION"; 6542 break; 6543 case DhcpStateMachine.CMD_POST_DHCP_ACTION: 6544 s = "CMD_POST_DHCP_ACTION"; 6545 break; 6546 case DhcpStateMachine.CMD_PRE_DHCP_ACTION_COMPLETE: 6547 s = "CMD_PRE_DHCP_ACTION_COMPLETE"; 6548 break; 6549 case DhcpStateMachine.CMD_ON_QUIT: 6550 s = "CMD_ON_QUIT"; 6551 break; 6552 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 6553 s = "WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST"; 6554 break; 6555 case WifiManager.DISABLE_NETWORK: 6556 s = "WifiManager.DISABLE_NETWORK"; 6557 break; 6558 case CMD_BLACKLIST_NETWORK: 6559 s = "CMD_BLACKLIST_NETWORK"; 6560 break; 6561 case CMD_CLEAR_BLACKLIST: 6562 s = "CMD_CLEAR_BLACKLIST"; 6563 break; 6564 case CMD_SAVE_CONFIG: 6565 s = "CMD_SAVE_CONFIG"; 6566 break; 6567 case CMD_GET_CONFIGURED_NETWORKS: 6568 s = "CMD_GET_CONFIGURED_NETWORKS"; 6569 break; 6570 case CMD_GET_SUPPORTED_FEATURES: 6571 s = "CMD_GET_SUPPORTED_FEATURES"; 6572 break; 6573 case CMD_UNWANTED_NETWORK: 6574 s = "CMD_UNWANTED_NETWORK"; 6575 break; 6576 case CMD_NETWORK_STATUS: 6577 s = "CMD_NETWORK_STATUS"; 6578 break; 6579 case CMD_GET_LINK_LAYER_STATS: 6580 s = "CMD_GET_LINK_LAYER_STATS"; 6581 break; 6582 case CMD_GET_MATCHING_CONFIG: 6583 s = "CMD_GET_MATCHING_CONFIG"; 6584 break; 6585 case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS: 6586 s = "CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS"; 6587 break; 6588 case CMD_DISCONNECT: 6589 s = "CMD_DISCONNECT"; 6590 break; 6591 case CMD_RECONNECT: 6592 s = "CMD_RECONNECT"; 6593 break; 6594 case CMD_REASSOCIATE: 6595 s = "CMD_REASSOCIATE"; 6596 break; 6597 case CMD_GET_CONNECTION_STATISTICS: 6598 s = "CMD_GET_CONNECTION_STATISTICS"; 6599 break; 6600 case CMD_SET_HIGH_PERF_MODE: 6601 s = "CMD_SET_HIGH_PERF_MODE"; 6602 break; 6603 case CMD_SET_COUNTRY_CODE: 6604 s = "CMD_SET_COUNTRY_CODE"; 6605 break; 6606 case CMD_ENABLE_RSSI_POLL: 6607 s = "CMD_ENABLE_RSSI_POLL"; 6608 break; 6609 case CMD_RSSI_POLL: 6610 s = "CMD_RSSI_POLL"; 6611 break; 6612 case CMD_START_PACKET_FILTERING: 6613 s = "CMD_START_PACKET_FILTERING"; 6614 break; 6615 case CMD_STOP_PACKET_FILTERING: 6616 s = "CMD_STOP_PACKET_FILTERING"; 6617 break; 6618 case CMD_SET_SUSPEND_OPT_ENABLED: 6619 s = "CMD_SET_SUSPEND_OPT_ENABLED"; 6620 break; 6621 case CMD_NO_NETWORKS_PERIODIC_SCAN: 6622 s = "CMD_NO_NETWORKS_PERIODIC_SCAN"; 6623 break; 6624 case CMD_UPDATE_LINKPROPERTIES: 6625 s = "CMD_UPDATE_LINKPROPERTIES"; 6626 break; 6627 case CMD_RELOAD_TLS_AND_RECONNECT: 6628 s = "CMD_RELOAD_TLS_AND_RECONNECT"; 6629 break; 6630 case WifiManager.CONNECT_NETWORK: 6631 s = "CONNECT_NETWORK"; 6632 break; 6633 case WifiManager.SAVE_NETWORK: 6634 s = "SAVE_NETWORK"; 6635 break; 6636 case WifiManager.FORGET_NETWORK: 6637 s = "FORGET_NETWORK"; 6638 break; 6639 case WifiMonitor.SUP_CONNECTION_EVENT: 6640 s = "SUP_CONNECTION_EVENT"; 6641 break; 6642 case WifiMonitor.SUP_DISCONNECTION_EVENT: 6643 s = "SUP_DISCONNECTION_EVENT"; 6644 break; 6645 case WifiMonitor.SCAN_RESULTS_EVENT: 6646 s = "SCAN_RESULTS_EVENT"; 6647 break; 6648 case WifiMonitor.SCAN_FAILED_EVENT: 6649 s = "SCAN_FAILED_EVENT"; 6650 break; 6651 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6652 s = "SUPPLICANT_STATE_CHANGE_EVENT"; 6653 break; 6654 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 6655 s = "AUTHENTICATION_FAILURE_EVENT"; 6656 break; 6657 case WifiMonitor.SSID_TEMP_DISABLED: 6658 s = "SSID_TEMP_DISABLED"; 6659 break; 6660 case WifiMonitor.SSID_REENABLED: 6661 s = "SSID_REENABLED"; 6662 break; 6663 case WifiMonitor.WPS_SUCCESS_EVENT: 6664 s = "WPS_SUCCESS_EVENT"; 6665 break; 6666 case WifiMonitor.WPS_FAIL_EVENT: 6667 s = "WPS_FAIL_EVENT"; 6668 break; 6669 case WifiMonitor.SUP_REQUEST_IDENTITY: 6670 s = "SUP_REQUEST_IDENTITY"; 6671 break; 6672 case WifiMonitor.NETWORK_CONNECTION_EVENT: 6673 s = "NETWORK_CONNECTION_EVENT"; 6674 break; 6675 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6676 s = "NETWORK_DISCONNECTION_EVENT"; 6677 break; 6678 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 6679 s = "ASSOCIATION_REJECTION_EVENT"; 6680 break; 6681 case WifiMonitor.ANQP_DONE_EVENT: 6682 s = "WifiMonitor.ANQP_DONE_EVENT"; 6683 break; 6684 case WifiMonitor.RX_HS20_ANQP_ICON_EVENT: 6685 s = "WifiMonitor.RX_HS20_ANQP_ICON_EVENT"; 6686 break; 6687 case WifiMonitor.GAS_QUERY_DONE_EVENT: 6688 s = "WifiMonitor.GAS_QUERY_DONE_EVENT"; 6689 break; 6690 case WifiMonitor.HS20_REMEDIATION_EVENT: 6691 s = "WifiMonitor.HS20_REMEDIATION_EVENT"; 6692 break; 6693 case WifiMonitor.GAS_QUERY_START_EVENT: 6694 s = "WifiMonitor.GAS_QUERY_START_EVENT"; 6695 break; 6696 case CMD_SET_OPERATIONAL_MODE: 6697 s = "CMD_SET_OPERATIONAL_MODE"; 6698 break; 6699 case CMD_START_SCAN: 6700 s = "CMD_START_SCAN"; 6701 break; 6702 case CMD_DISABLE_P2P_RSP: 6703 s = "CMD_DISABLE_P2P_RSP"; 6704 break; 6705 case CMD_DISABLE_P2P_REQ: 6706 s = "CMD_DISABLE_P2P_REQ"; 6707 break; 6708 case WifiP2pServiceImpl.GROUP_CREATING_TIMED_OUT: 6709 s = "GROUP_CREATING_TIMED_OUT"; 6710 break; 6711 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 6712 s = "P2P_CONNECTION_CHANGED"; 6713 break; 6714 case WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE: 6715 s = "P2P.DISCONNECT_WIFI_RESPONSE"; 6716 break; 6717 case WifiP2pServiceImpl.SET_MIRACAST_MODE: 6718 s = "P2P.SET_MIRACAST_MODE"; 6719 break; 6720 case WifiP2pServiceImpl.BLOCK_DISCOVERY: 6721 s = "P2P.BLOCK_DISCOVERY"; 6722 break; 6723 case WifiP2pServiceImpl.SET_COUNTRY_CODE: 6724 s = "P2P.SET_COUNTRY_CODE"; 6725 break; 6726 case WifiManager.CANCEL_WPS: 6727 s = "CANCEL_WPS"; 6728 break; 6729 case WifiManager.CANCEL_WPS_FAILED: 6730 s = "CANCEL_WPS_FAILED"; 6731 break; 6732 case WifiManager.CANCEL_WPS_SUCCEDED: 6733 s = "CANCEL_WPS_SUCCEDED"; 6734 break; 6735 case WifiManager.START_WPS: 6736 s = "START_WPS"; 6737 break; 6738 case WifiManager.START_WPS_SUCCEEDED: 6739 s = "START_WPS_SUCCEEDED"; 6740 break; 6741 case WifiManager.WPS_FAILED: 6742 s = "WPS_FAILED"; 6743 break; 6744 case WifiManager.WPS_COMPLETED: 6745 s = "WPS_COMPLETED"; 6746 break; 6747 case WifiManager.RSSI_PKTCNT_FETCH: 6748 s = "RSSI_PKTCNT_FETCH"; 6749 break; 6750 case CMD_IP_CONFIGURATION_LOST: 6751 s = "CMD_IP_CONFIGURATION_LOST"; 6752 break; 6753 case CMD_IP_CONFIGURATION_SUCCESSFUL: 6754 s = "CMD_IP_CONFIGURATION_SUCCESSFUL"; 6755 break; 6756 case CMD_IP_REACHABILITY_LOST: 6757 s = "CMD_IP_REACHABILITY_LOST"; 6758 break; 6759 case CMD_STATIC_IP_SUCCESS: 6760 s = "CMD_STATIC_IP_SUCCESS"; 6761 break; 6762 case CMD_STATIC_IP_FAILURE: 6763 s = "CMD_STATIC_IP_FAILURE"; 6764 break; 6765 case DhcpStateMachine.DHCP_SUCCESS: 6766 s = "DHCP_SUCCESS"; 6767 break; 6768 case DhcpStateMachine.DHCP_FAILURE: 6769 s = "DHCP_FAILURE"; 6770 break; 6771 case CMD_TARGET_BSSID: 6772 s = "CMD_TARGET_BSSID"; 6773 break; 6774 case CMD_ASSOCIATED_BSSID: 6775 s = "CMD_ASSOCIATED_BSSID"; 6776 break; 6777 case CMD_REMOVE_APP_CONFIGURATIONS: 6778 s = "CMD_REMOVE_APP_CONFIGURATIONS"; 6779 break; 6780 case CMD_REMOVE_USER_CONFIGURATIONS: 6781 s = "CMD_REMOVE_USER_CONFIGURATIONS"; 6782 break; 6783 case CMD_ROAM_WATCHDOG_TIMER: 6784 s = "CMD_ROAM_WATCHDOG_TIMER"; 6785 break; 6786 case CMD_SCREEN_STATE_CHANGED: 6787 s = "CMD_SCREEN_STATE_CHANGED"; 6788 break; 6789 case CMD_DISCONNECTING_WATCHDOG_TIMER: 6790 s = "CMD_DISCONNECTING_WATCHDOG_TIMER"; 6791 break; 6792 case CMD_RESTART_AUTOJOIN_OFFLOAD: 6793 s = "CMD_RESTART_AUTOJOIN_OFFLOAD"; 6794 break; 6795 case CMD_STARTED_PNO_DBG: 6796 s = "CMD_STARTED_PNO_DBG"; 6797 break; 6798 case CMD_STARTED_GSCAN_DBG: 6799 s = "CMD_STARTED_GSCAN_DBG"; 6800 break; 6801 case CMD_PNO_NETWORK_FOUND: 6802 s = "CMD_PNO_NETWORK_FOUND"; 6803 break; 6804 case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION: 6805 s = "CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION"; 6806 break; 6807 case CMD_START_IP_PACKET_OFFLOAD: 6808 s = "CMD_START_IP_PACKET_OFFLOAD"; 6809 break; 6810 case CMD_STOP_IP_PACKET_OFFLOAD: 6811 s = "CMD_STOP_IP_PACKET_OFFLOAD"; 6812 break; 6813 case CMD_START_RSSI_MONITORING_OFFLOAD: 6814 s = "CMD_START_RSSI_MONITORING_OFFLOAD"; 6815 break; 6816 case CMD_STOP_RSSI_MONITORING_OFFLOAD: 6817 s = "CMD_STOP_RSSI_MONITORING_OFFLOAD"; 6818 break; 6819 case CMD_RSSI_THRESHOLD_BREACH: 6820 s = "CMD_RSSI_THRESHOLD_BREACH"; 6821 break; 6822 case CMD_USER_SWITCH: 6823 s = "CMD_USER_SWITCH"; 6824 break; 6825 case CMD_IPV4_PROVISIONING_SUCCESS: 6826 s = "CMD_IPV4_PROVISIONING_SUCCESS"; 6827 break; 6828 case CMD_IPV4_PROVISIONING_FAILURE: 6829 s = "CMD_IPV4_PROVISIONING_FAILURE"; 6830 break; 6831 default: 6832 s = "what:" + Integer.toString(what); 6833 break; 6834 } 6835 return s; 6836 } 6837 6838 void registerConnected() { 6839 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 6840 WifiConfiguration config = mWifiConfigStore.getWifiConfiguration(mLastNetworkId); 6841 if (config != null) { 6842 //Here we will clear all disable counters once a network is connected 6843 //records how long this network is connected in future 6844 config.lastConnected = System.currentTimeMillis(); 6845 config.getNetworkSelectionStatus().clearDisableReasonCounter(); 6846 } 6847 mBadLinkspeedcount = 0; 6848 } 6849 } 6850 6851 void registerDisconnected() { 6852 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 6853 long now_ms = System.currentTimeMillis(); 6854 // We are switching away from this configuration, 6855 // hence record the time we were connected last 6856 WifiConfiguration config = mWifiConfigStore.getWifiConfiguration(mLastNetworkId); 6857 if (config != null) { 6858 config.lastDisconnected = System.currentTimeMillis(); 6859 if (config.ephemeral) { 6860 // Remove ephemeral WifiConfigurations from file 6861 mWifiConfigStore.forgetNetwork(mLastNetworkId); 6862 } 6863 } 6864 } 6865 } 6866 6867 void noteWifiDisabledWhileAssociated() { 6868 // We got disabled by user while we were associated, make note of it 6869 int rssi = mWifiInfo.getRssi(); 6870 WifiConfiguration config = getCurrentWifiConfiguration(); 6871 if (getCurrentState() == mConnectedState 6872 && rssi != WifiInfo.INVALID_RSSI 6873 && config != null) { 6874 boolean is24GHz = mWifiInfo.is24GHz(); 6875 boolean isBadRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdMinimumRssi24.get()) 6876 || (!is24GHz && rssi < mWifiConfigStore.thresholdMinimumRssi5.get()); 6877 boolean isLowRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdQualifiedRssi24.get()) 6878 || (!is24GHz && mWifiInfo.getRssi() 6879 < mWifiConfigStore.thresholdQualifiedRssi5.get()); 6880 boolean isHighRSSI = (is24GHz && rssi 6881 >= mWifiConfigStore.thresholdSaturatedRssi24.get()) 6882 || (!is24GHz && mWifiInfo.getRssi() 6883 >= mWifiConfigStore.thresholdSaturatedRssi5.get()); 6884 if (isBadRSSI) { 6885 // Take note that we got disabled while RSSI was Bad 6886 config.numUserTriggeredWifiDisableLowRSSI++; 6887 } else if (isLowRSSI) { 6888 // Take note that we got disabled while RSSI was Low 6889 config.numUserTriggeredWifiDisableBadRSSI++; 6890 } else if (!isHighRSSI) { 6891 // Take note that we got disabled while RSSI was Not high 6892 config.numUserTriggeredWifiDisableNotHighRSSI++; 6893 } 6894 } 6895 } 6896 6897 WifiConfiguration getCurrentWifiConfiguration() { 6898 if (mLastNetworkId == WifiConfiguration.INVALID_NETWORK_ID) { 6899 return null; 6900 } 6901 return mWifiConfigStore.getWifiConfiguration(mLastNetworkId); 6902 } 6903 6904 ScanResult getCurrentScanResult() { 6905 WifiConfiguration config = getCurrentWifiConfiguration(); 6906 if (config == null) { 6907 return null; 6908 } 6909 String BSSID = mWifiInfo.getBSSID(); 6910 if (BSSID == null) { 6911 BSSID = mTargetRoamBSSID; 6912 } 6913 ScanDetailCache scanDetailCache = 6914 mWifiConfigStore.getScanDetailCache(config); 6915 6916 if (scanDetailCache == null) { 6917 return null; 6918 } 6919 6920 return scanDetailCache.get(BSSID); 6921 } 6922 6923 String getCurrentBSSID() { 6924 if (linkDebouncing) { 6925 return null; 6926 } 6927 return mLastBssid; 6928 } 6929 6930 class ConnectModeState extends State { 6931 6932 @Override 6933 public void enter() { 6934 connectScanningService(); 6935 } 6936 6937 @Override 6938 public boolean processMessage(Message message) { 6939 WifiConfiguration config; 6940 int netId; 6941 boolean ok; 6942 boolean didDisconnect; 6943 String bssid; 6944 String ssid; 6945 NetworkUpdateResult result; 6946 logStateAndMessage(message, this); 6947 6948 switch (message.what) { 6949 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 6950 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_ASSOC_FAILURE); 6951 didBlackListBSSID = false; 6952 bssid = (String) message.obj; 6953 if (bssid == null || TextUtils.isEmpty(bssid)) { 6954 // If BSSID is null, use the target roam BSSID 6955 bssid = mTargetRoamBSSID; 6956 } 6957 if (bssid != null) { 6958 // If we have a BSSID, tell configStore to black list it 6959 synchronized(mScanResultCache) { 6960 didBlackListBSSID = mWifiQualifiedNetworkSelector 6961 .enableBssidForQualitynetworkSelection(bssid, false); 6962 } 6963 } 6964 6965 mWifiConfigStore.updateNetworkSelectionStatus(mTargetNetworkId, 6966 WifiConfiguration.NetworkSelectionStatus 6967 .DISABLED_ASSOCIATION_REJECTION); 6968 6969 mSupplicantStateTracker.sendMessage(WifiMonitor.ASSOCIATION_REJECTION_EVENT); 6970 break; 6971 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 6972 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_AUTH_FAILURE); 6973 mSupplicantStateTracker.sendMessage(WifiMonitor.AUTHENTICATION_FAILURE_EVENT); 6974 if (mTargetNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 6975 mWifiConfigStore.updateNetworkSelectionStatus(mTargetNetworkId, 6976 WifiConfiguration.NetworkSelectionStatus 6977 .DISABLED_AUTHENTICATION_FAILURE); 6978 } 6979 break; 6980 case WifiMonitor.SSID_TEMP_DISABLED: 6981 Log.e(TAG, "Supplicant SSID temporary disabled:" 6982 + mWifiConfigStore.getWifiConfiguration(message.arg1)); 6983 mWifiConfigStore.updateNetworkSelectionStatus( 6984 message.arg1, 6985 WifiConfiguration.NetworkSelectionStatus 6986 .DISABLED_AUTHENTICATION_FAILURE); 6987 break; 6988 case WifiMonitor.SSID_REENABLED: 6989 Log.d(TAG, "Supplicant SSID reenable:" 6990 + mWifiConfigStore.getWifiConfiguration(message.arg1)); 6991 // Do not re-enable it in Quality Network Selection since framework has its own 6992 // Algorithm of disable/enable 6993 break; 6994 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6995 SupplicantState state = handleSupplicantStateChange(message); 6996 // A driver/firmware hang can now put the interface in a down state. 6997 // We detect the interface going down and recover from it 6998 if (!SupplicantState.isDriverActive(state)) { 6999 if (mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) { 7000 handleNetworkDisconnect(); 7001 } 7002 log("Detected an interface down, restart driver"); 7003 transitionTo(mDriverStoppedState); 7004 sendMessage(CMD_START_DRIVER); 7005 break; 7006 } 7007 7008 // Supplicant can fail to report a NETWORK_DISCONNECTION_EVENT 7009 // when authentication times out after a successful connection, 7010 // we can figure this from the supplicant state. If supplicant 7011 // state is DISCONNECTED, but the mNetworkInfo says we are not 7012 // disconnected, we need to handle a disconnection 7013 if (!linkDebouncing && state == SupplicantState.DISCONNECTED && 7014 mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) { 7015 if (DBG) log("Missed CTRL-EVENT-DISCONNECTED, disconnect"); 7016 handleNetworkDisconnect(); 7017 transitionTo(mDisconnectedState); 7018 } 7019 7020 // If we have COMPLETED a connection to a BSSID, start doing 7021 // DNAv4/DNAv6 -style probing for on-link neighbors of 7022 // interest (e.g. routers); harmless if none are configured. 7023 if (state == SupplicantState.COMPLETED) { 7024 mIpManager.confirmConfiguration(); 7025 } 7026 break; 7027 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 7028 if (message.arg1 == 1) { 7029 mWifiNative.disconnect(); 7030 mTemporarilyDisconnectWifi = true; 7031 } else { 7032 mWifiNative.reconnect(); 7033 mTemporarilyDisconnectWifi = false; 7034 } 7035 break; 7036 case CMD_ADD_OR_UPDATE_NETWORK: 7037 // Only the current foreground user can modify networks. 7038 if (!isCurrentUserProfile(UserHandle.getUserId(message.sendingUid))) { 7039 loge("Only the current foreground user can modify networks " 7040 + " currentUserId=" + mCurrentUserId 7041 + " sendingUserId=" + UserHandle.getUserId(message.sendingUid)); 7042 replyToMessage(message, message.what, FAILURE); 7043 break; 7044 } 7045 7046 config = (WifiConfiguration) message.obj; 7047 7048 if (!recordUidIfAuthorized(config, message.sendingUid, 7049 /* onlyAnnotate */ false)) { 7050 logw("Not authorized to update network " 7051 + " config=" + config.SSID 7052 + " cnid=" + config.networkId 7053 + " uid=" + message.sendingUid); 7054 replyToMessage(message, message.what, FAILURE); 7055 break; 7056 } 7057 7058 int res = mWifiConfigStore.addOrUpdateNetwork(config, message.sendingUid); 7059 if (res < 0) { 7060 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7061 } else { 7062 WifiConfiguration curConfig = getCurrentWifiConfiguration(); 7063 if (curConfig != null && config != null) { 7064 if (curConfig.priority < config.priority 7065 && config.status == WifiConfiguration.Status.ENABLED) { 7066 // Interpret this as a connect attempt 7067 // Set the last selected configuration so as to allow the system to 7068 // stick the last user choice without persisting the choice 7069 mWifiConfigStore.setAndEnableLastSelectedConfiguration(res); 7070 mWifiConfigStore.updateLastConnectUid(config, message.sendingUid); 7071 boolean persist = mWifiConfigStore 7072 .checkConfigOverridePermission(message.sendingUid); 7073 mWifiQualifiedNetworkSelector 7074 .userSelectNetwork(res, persist); 7075 7076 // Remember time of last connection attempt 7077 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7078 //Create clearcut connection event of type USER_SELECTED 7079 mWifiMetrics.startConnectionEvent(mWifiInfo, 7080 WifiMetricsProto.ConnectionEvent.ROAM_USER_SELECTED); 7081 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 7082 7083 // As a courtesy to the caller, trigger a scan now 7084 startScan(ADD_OR_UPDATE_SOURCE, 0, null, null); 7085 } 7086 } 7087 } 7088 replyToMessage(message, CMD_ADD_OR_UPDATE_NETWORK, res); 7089 break; 7090 case CMD_REMOVE_NETWORK: 7091 // Only the current foreground user can modify networks. 7092 if (!isCurrentUserProfile(UserHandle.getUserId(message.sendingUid))) { 7093 loge("Only the current foreground user can modify networks " 7094 + " currentUserId=" + mCurrentUserId 7095 + " sendingUserId=" + UserHandle.getUserId(message.sendingUid)); 7096 replyToMessage(message, message.what, FAILURE); 7097 break; 7098 } 7099 netId = message.arg1; 7100 7101 if (!mWifiConfigStore.canModifyNetwork(message.sendingUid, netId, 7102 /* onlyAnnotate */ false)) { 7103 logw("Not authorized to remove network " 7104 + " cnid=" + netId 7105 + " uid=" + message.sendingUid); 7106 replyToMessage(message, message.what, FAILURE); 7107 break; 7108 } 7109 7110 ok = mWifiConfigStore.removeNetwork(message.arg1); 7111 if (!ok) { 7112 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7113 } 7114 replyToMessage(message, message.what, ok ? SUCCESS : FAILURE); 7115 break; 7116 case CMD_ENABLE_NETWORK: 7117 // Only the current foreground user can modify networks. 7118 if (!isCurrentUserProfile(UserHandle.getUserId(message.sendingUid))) { 7119 loge("Only the current foreground user can modify networks " 7120 + " currentUserId=" + mCurrentUserId 7121 + " sendingUserId=" + UserHandle.getUserId(message.sendingUid)); 7122 replyToMessage(message, message.what, FAILURE); 7123 break; 7124 } 7125 7126 boolean disableOthers = message.arg2 == 1; 7127 netId = message.arg1; 7128 config = mWifiConfigStore.getWifiConfiguration(netId); 7129 if (config == null) { 7130 loge("No network with id = " + netId); 7131 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7132 replyToMessage(message, message.what, FAILURE); 7133 break; 7134 } 7135 7136 // disable other only means select this network, does not mean all other 7137 // networks need to be disabled 7138 if (disableOthers) { 7139 mWifiQualifiedNetworkSelector.enableNetworkByUser(config); 7140 // Remember time of last connection attempt 7141 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7142 mWifiMetrics.startConnectionEvent(mWifiInfo, 7143 WifiMetricsProto.ConnectionEvent.ROAM_USER_SELECTED); 7144 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 7145 } 7146 // Cancel auto roam requests 7147 autoRoamSetBSSID(netId, "any"); 7148 7149 int uid = message.sendingUid; 7150 mWifiQualifiedNetworkSelector.enableNetworkByUser(config); 7151 ok = mWifiConfigStore.enableNetwork(netId, disableOthers, uid); 7152 if (!ok) { 7153 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7154 } else if (disableOthers) { 7155 mTargetNetworkId = netId; 7156 } 7157 7158 replyToMessage(message, message.what, ok ? SUCCESS : FAILURE); 7159 break; 7160 case CMD_ENABLE_ALL_NETWORKS: 7161 long time = android.os.SystemClock.elapsedRealtime(); 7162 if (time - mLastEnableAllNetworksTime > MIN_INTERVAL_ENABLE_ALL_NETWORKS_MS) { 7163 mWifiConfigStore.enableAllNetworks(); 7164 mLastEnableAllNetworksTime = time; 7165 } 7166 break; 7167 case WifiManager.DISABLE_NETWORK: 7168 if (mWifiConfigStore.updateNetworkSelectionStatus(message.arg1, 7169 WifiConfiguration.NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER)) { 7170 replyToMessage(message, WifiManager.DISABLE_NETWORK_SUCCEEDED); 7171 } else { 7172 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7173 replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED, 7174 WifiManager.ERROR); 7175 } 7176 break; 7177 case CMD_DISABLE_EPHEMERAL_NETWORK: 7178 config = mWifiConfigStore.disableEphemeralNetwork((String)message.obj); 7179 if (config != null) { 7180 if (config.networkId == mLastNetworkId) { 7181 // Disconnect and let autojoin reselect a new network 7182 sendMessage(CMD_DISCONNECT); 7183 } 7184 } 7185 break; 7186 case CMD_BLACKLIST_NETWORK: 7187 mWifiConfigStore.blackListBssid((String) message.obj); 7188 break; 7189 case CMD_CLEAR_BLACKLIST: 7190 mWifiConfigStore.clearBssidBlacklist(); 7191 break; 7192 case CMD_SAVE_CONFIG: 7193 ok = mWifiConfigStore.saveConfig(); 7194 7195 if (DBG) logd("did save config " + ok); 7196 replyToMessage(message, CMD_SAVE_CONFIG, ok ? SUCCESS : FAILURE); 7197 7198 // Inform the backup manager about a data change 7199 IBackupManager ibm = IBackupManager.Stub.asInterface( 7200 mFacade.getService(Context.BACKUP_SERVICE)); 7201 if (ibm != null) { 7202 try { 7203 ibm.dataChanged("com.android.providers.settings"); 7204 } catch (Exception e) { 7205 // Try again later 7206 } 7207 } 7208 break; 7209 case CMD_GET_CONFIGURED_NETWORKS: 7210 replyToMessage(message, message.what, 7211 mWifiConfigStore.getConfiguredNetworks()); 7212 break; 7213 case WifiMonitor.SUP_REQUEST_IDENTITY: 7214 int networkId = message.arg2; 7215 boolean identitySent = false; 7216 int eapMethod = WifiEnterpriseConfig.Eap.NONE; 7217 7218 if (targetWificonfiguration != null 7219 && targetWificonfiguration.enterpriseConfig != null) { 7220 eapMethod = targetWificonfiguration.enterpriseConfig.getEapMethod(); 7221 } 7222 7223 // For SIM & AKA/AKA' EAP method Only, get identity from ICC 7224 if (targetWificonfiguration != null 7225 && targetWificonfiguration.networkId == networkId 7226 && targetWificonfiguration.allowedKeyManagement 7227 .get(WifiConfiguration.KeyMgmt.IEEE8021X) 7228 && (eapMethod == WifiEnterpriseConfig.Eap.SIM 7229 || eapMethod == WifiEnterpriseConfig.Eap.AKA 7230 || eapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME)) { 7231 TelephonyManager tm = (TelephonyManager) 7232 mContext.getSystemService(Context.TELEPHONY_SERVICE); 7233 if (tm != null) { 7234 String imsi = tm.getSubscriberId(); 7235 String mccMnc = ""; 7236 7237 if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) 7238 mccMnc = tm.getSimOperator(); 7239 7240 String identity = buildIdentity(eapMethod, imsi, mccMnc); 7241 7242 if (!identity.isEmpty()) { 7243 mWifiNative.simIdentityResponse(networkId, identity); 7244 identitySent = true; 7245 } 7246 } 7247 } 7248 if (!identitySent) { 7249 // Supplicant lacks credentials to connect to that network, hence black list 7250 ssid = (String) message.obj; 7251 if (targetWificonfiguration != null && ssid != null 7252 && targetWificonfiguration.SSID != null 7253 && targetWificonfiguration.SSID.equals("\"" + ssid + "\"")) { 7254 mWifiConfigStore.updateNetworkSelectionStatus(targetWificonfiguration, 7255 WifiConfiguration.NetworkSelectionStatus 7256 .DISABLED_AUTHENTICATION_NO_CREDENTIALS); 7257 } 7258 // Disconnect now, as we don't have any way to fullfill 7259 // the supplicant request. 7260 mWifiConfigStore.setAndEnableLastSelectedConfiguration( 7261 WifiConfiguration.INVALID_NETWORK_ID); 7262 mWifiNative.disconnect(); 7263 } 7264 break; 7265 case WifiMonitor.SUP_REQUEST_SIM_AUTH: 7266 logd("Received SUP_REQUEST_SIM_AUTH"); 7267 SimAuthRequestData requestData = (SimAuthRequestData) message.obj; 7268 if (requestData != null) { 7269 if (requestData.protocol == WifiEnterpriseConfig.Eap.SIM) { 7270 handleGsmAuthRequest(requestData); 7271 } else if (requestData.protocol == WifiEnterpriseConfig.Eap.AKA 7272 || requestData.protocol == WifiEnterpriseConfig.Eap.AKA_PRIME) { 7273 handle3GAuthRequest(requestData); 7274 } 7275 } else { 7276 loge("Invalid sim auth request"); 7277 } 7278 break; 7279 case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS: 7280 replyToMessage(message, message.what, 7281 mWifiConfigStore.getPrivilegedConfiguredNetworks()); 7282 break; 7283 case CMD_GET_MATCHING_CONFIG: 7284 replyToMessage(message, message.what, 7285 mWifiConfigStore.getMatchingConfig((ScanResult)message.obj)); 7286 break; 7287 /* Do a redundant disconnect without transition */ 7288 case CMD_DISCONNECT: 7289 mWifiConfigStore.setAndEnableLastSelectedConfiguration 7290 (WifiConfiguration.INVALID_NETWORK_ID); 7291 mWifiNative.disconnect(); 7292 break; 7293 case CMD_RECONNECT: 7294 WifiConfiguration candidate = 7295 mWifiQualifiedNetworkSelector.selectQualifiedNetwork(true, 7296 mAllowUntrustedConnections, mScanResults, linkDebouncing, 7297 isConnected(), isDisconnected(), isSupplicantTransientState()); 7298 tryToConnectToNetwork(candidate); 7299 break; 7300 case CMD_REASSOCIATE: 7301 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7302 mWifiMetrics.startConnectionEvent(mWifiInfo); 7303 mWifiNative.reassociate(); 7304 break; 7305 case CMD_RELOAD_TLS_AND_RECONNECT: 7306 if (mWifiConfigStore.needsUnlockedKeyStore()) { 7307 logd("Reconnecting to give a chance to un-connected TLS networks"); 7308 mWifiNative.disconnect(); 7309 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7310 mWifiMetrics.startConnectionEvent(mWifiInfo); 7311 mWifiNative.reconnect(); 7312 } 7313 break; 7314 case CMD_AUTO_ROAM: 7315 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 7316 return HANDLED; 7317 case CMD_AUTO_CONNECT: 7318 /* Work Around: wpa_supplicant can get in a bad state where it returns a non 7319 * associated status to the STATUS command but somehow-someplace still thinks 7320 * it is associated and thus will ignore select/reconnect command with 7321 * following message: 7322 * "Already associated with the selected network - do nothing" 7323 * 7324 * Hence, sends a disconnect to supplicant first. 7325 */ 7326 didDisconnect = false; 7327 if (getCurrentState() != mDisconnectedState) { 7328 /** Supplicant will ignore the reconnect if we are currently associated, 7329 * hence trigger a disconnect 7330 */ 7331 didDisconnect = true; 7332 mWifiNative.disconnect(); 7333 } 7334 7335 /* connect command coming from auto-join */ 7336 netId = message.arg1; 7337 mTargetNetworkId = netId; 7338 mTargetRoamBSSID = (String) message.obj; 7339 config = mWifiConfigStore.getWifiConfiguration(netId); 7340 logd("CMD_AUTO_CONNECT sup state " 7341 + mSupplicantStateTracker.getSupplicantStateName() 7342 + " my state " + getCurrentState().getName() 7343 + " nid=" + Integer.toString(netId) 7344 + " roam=" + Boolean.toString(mAutoRoaming)); 7345 if (config == null) { 7346 loge("AUTO_CONNECT and no config, bail out..."); 7347 break; 7348 } 7349 7350 /* Make sure we cancel any previous roam request */ 7351 setTargetBssid(config, mTargetRoamBSSID); 7352 7353 /* Save the network config */ 7354 logd("CMD_AUTO_CONNECT will save config -> " + config.SSID 7355 + " nid=" + Integer.toString(netId)); 7356 result = mWifiConfigStore.saveNetwork(config, WifiConfiguration.UNKNOWN_UID); 7357 netId = result.getNetworkId(); 7358 logd("CMD_AUTO_CONNECT did save config -> " 7359 + " nid=" + Integer.toString(netId)); 7360 7361 // Since we updated the config,read it back from config store: 7362 config = mWifiConfigStore.getWifiConfiguration(netId); 7363 if (config == null) { 7364 loge("CMD_AUTO_CONNECT couldn't update the config, got null config"); 7365 break; 7366 } 7367 if (netId != config.networkId) { 7368 loge("CMD_AUTO_CONNECT couldn't update the config, want" 7369 + " nid=" + Integer.toString(netId) + " but got" + config.networkId); 7370 break; 7371 } 7372 7373 if (deferForUserInput(message, netId, false)) { 7374 break; 7375 } else if (mWifiConfigStore.getWifiConfiguration(netId).userApproved == 7376 WifiConfiguration.USER_BANNED) { 7377 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7378 WifiManager.NOT_AUTHORIZED); 7379 break; 7380 } 7381 7382 // Make sure the network is enabled, since supplicant will not reenable it 7383 mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false); 7384 7385 // If we're autojoining a network that the user or an app explicitly selected, 7386 // keep track of the UID that selected it. 7387 // TODO(b/26786318): Keep track of the lastSelectedConfiguration and the 7388 // lastConnectUid on a per-user basis. 7389 int lastConnectUid = WifiConfiguration.UNKNOWN_UID; 7390 if (mWifiConfigStore.isLastSelectedConfiguration(config) 7391 && isCurrentUserProfile(UserHandle.getUserId(config.lastConnectUid))) { 7392 lastConnectUid = config.lastConnectUid; 7393 } 7394 7395 if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ false, 7396 lastConnectUid) && mWifiNative.reconnect()) { 7397 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7398 mWifiMetrics.startConnectionEvent(mWifiInfo, 7399 WifiMetricsProto.ConnectionEvent.ROAM_UNRELATED); 7400 targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId); 7401 config = mWifiConfigStore.getWifiConfiguration(netId); 7402 if (config != null 7403 && !mWifiConfigStore.isLastSelectedConfiguration(config)) { 7404 // If we autojoined a different config than the user selected one, 7405 // it means we could not see the last user selection, 7406 // or that the last user selection was faulty and ended up blacklisted 7407 // for some reason (in which case the user is notified with an error 7408 // message in the Wifi picker), and thus we managed to auto-join away 7409 // from the selected config. -> in that case we need to forget 7410 // the selection because we don't want to abruptly switch back to it. 7411 // 7412 // Note that the user selection is also forgotten after a period of time 7413 // during which the device has been disconnected. 7414 // The default value is 30 minutes : see the code path at bottom of 7415 // setScanResults() function. 7416 mWifiConfigStore. 7417 setAndEnableLastSelectedConfiguration( 7418 WifiConfiguration.INVALID_NETWORK_ID); 7419 } 7420 mAutoRoaming = false; 7421 if (isRoaming() || linkDebouncing) { 7422 transitionTo(mRoamingState); 7423 } else if (didDisconnect) { 7424 transitionTo(mDisconnectingState); 7425 } else { 7426 /* Already in disconnected state, nothing to change */ 7427 if (!mScreenOn && mLegacyPnoEnabled && mBackgroundScanSupported) { 7428 int delay = 60 * 1000; 7429 if (VDBG) { 7430 logd("Starting PNO alarm: " + delay); 7431 } 7432 mAlarmManager.set(AlarmManager.RTC_WAKEUP, 7433 System.currentTimeMillis() + delay, 7434 mPnoIntent); 7435 } 7436 mRestartAutoJoinOffloadCounter++; 7437 } 7438 } else { 7439 loge("Failed to connect config: " + config + " netId: " + netId); 7440 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7441 WifiManager.ERROR); 7442 break; 7443 } 7444 break; 7445 case CMD_REMOVE_APP_CONFIGURATIONS: 7446 mWifiConfigStore.removeNetworksForApp((ApplicationInfo) message.obj); 7447 break; 7448 case CMD_REMOVE_USER_CONFIGURATIONS: 7449 mWifiConfigStore.removeNetworksForUser(message.arg1); 7450 break; 7451 case WifiManager.CONNECT_NETWORK: 7452 // Only the current foreground user can modify networks. 7453 if (!isCurrentUserProfile(UserHandle.getUserId(message.sendingUid))) { 7454 loge("Only the current foreground user can modify networks " 7455 + " currentUserId=" + mCurrentUserId 7456 + " sendingUserId=" + UserHandle.getUserId(message.sendingUid)); 7457 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7458 WifiManager.NOT_AUTHORIZED); 7459 break; 7460 } 7461 7462 /** 7463 * The connect message can contain a network id passed as arg1 on message or 7464 * or a config passed as obj on message. 7465 * For a new network, a config is passed to create and connect. 7466 * For an existing network, a network id is passed 7467 */ 7468 netId = message.arg1; 7469 config = (WifiConfiguration) message.obj; 7470 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 7471 boolean updatedExisting = false; 7472 7473 /* Save the network config */ 7474 if (config != null) { 7475 // When connecting to an access point, WifiStateMachine wants to update the 7476 // relevant config with administrative data. This update should not be 7477 // considered a 'real' update, therefore lockdown by Device Owner must be 7478 // disregarded. 7479 if (!recordUidIfAuthorized(config, message.sendingUid, 7480 /* onlyAnnotate */ true)) { 7481 logw("Not authorized to update network " 7482 + " config=" + config.SSID 7483 + " cnid=" + config.networkId 7484 + " uid=" + message.sendingUid); 7485 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7486 WifiManager.NOT_AUTHORIZED); 7487 break; 7488 } 7489 7490 String configKey = config.configKey(true /* allowCached */); 7491 WifiConfiguration savedConfig = 7492 mWifiConfigStore.getWifiConfiguration(configKey); 7493 if (savedConfig != null) { 7494 // There is an existing config with this netId, but it wasn't exposed 7495 // (either AUTO_JOIN_DELETED or ephemeral; see WifiConfigStore# 7496 // getConfiguredNetworks). Remove those bits and update the config. 7497 config = savedConfig; 7498 logd("CONNECT_NETWORK updating existing config with id=" + 7499 config.networkId + " configKey=" + configKey); 7500 config.ephemeral = false; 7501 mWifiConfigStore.updateNetworkSelectionStatus(config, 7502 WifiConfiguration.NetworkSelectionStatus 7503 .NETWORK_SELECTION_ENABLE); 7504 updatedExisting = true; 7505 } 7506 7507 result = mWifiConfigStore.saveNetwork(config, message.sendingUid); 7508 netId = result.getNetworkId(); 7509 } 7510 config = mWifiConfigStore.getWifiConfiguration(netId); 7511 7512 if (config == null) { 7513 logd("CONNECT_NETWORK no config for id=" + Integer.toString(netId) + " " 7514 + mSupplicantStateTracker.getSupplicantStateName() + " my state " 7515 + getCurrentState().getName()); 7516 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7517 WifiManager.ERROR); 7518 break; 7519 } 7520 mTargetNetworkId = netId; 7521 autoRoamSetBSSID(netId, "any"); 7522 7523 if (message.sendingUid == Process.WIFI_UID 7524 || message.sendingUid == Process.SYSTEM_UID) { 7525 // As a sanity measure, clear the BSSID in the supplicant network block. 7526 // If system or Wifi Settings want to connect, they will not 7527 // specify the BSSID. 7528 // If an app however had added a BSSID to this configuration, and the BSSID 7529 // was wrong, Then we would forever fail to connect until that BSSID 7530 // is cleaned up. 7531 clearConfigBSSID(config, "CONNECT_NETWORK"); 7532 } 7533 7534 if (deferForUserInput(message, netId, true)) { 7535 break; 7536 } else if (mWifiConfigStore.getWifiConfiguration(netId).userApproved == 7537 WifiConfiguration.USER_BANNED) { 7538 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7539 WifiManager.NOT_AUTHORIZED); 7540 break; 7541 } 7542 7543 mAutoRoaming = false; 7544 7545 /* Tell network selection the user did try to connect to that network if from 7546 settings */ 7547 boolean persist = 7548 mWifiConfigStore.checkConfigOverridePermission(message.sendingUid); 7549 7550 7551 mWifiConfigStore.setAndEnableLastSelectedConfiguration(netId); 7552 mWifiQualifiedNetworkSelector.userSelectNetwork(netId, persist); 7553 didDisconnect = false; 7554 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID 7555 && mLastNetworkId != netId) { 7556 /** Supplicant will ignore the reconnect if we are currently associated, 7557 * hence trigger a disconnect 7558 */ 7559 didDisconnect = true; 7560 mWifiNative.disconnect(); 7561 } 7562 7563 // Make sure the network is enabled, since supplicant will not reenable it 7564 mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false); 7565 7566 if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ true, 7567 message.sendingUid) && mWifiNative.reconnect()) { 7568 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7569 mWifiMetrics.startConnectionEvent(mWifiInfo, 7570 WifiMetricsProto.ConnectionEvent.ROAM_USER_SELECTED); 7571 targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId); 7572 7573 /* The state tracker handles enabling networks upon completion/failure */ 7574 mSupplicantStateTracker.sendMessage(WifiManager.CONNECT_NETWORK); 7575 replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED); 7576 if (didDisconnect) { 7577 /* Expect a disconnection from the old connection */ 7578 transitionTo(mDisconnectingState); 7579 } else if (updatedExisting && getCurrentState() == mConnectedState && 7580 getCurrentWifiConfiguration().networkId == netId) { 7581 // Update the current set of network capabilities, but stay in the 7582 // current state. 7583 updateCapabilities(config); 7584 } else { 7585 /** 7586 * Directly go to disconnected state where we 7587 * process the connection events from supplicant 7588 */ 7589 transitionTo(mDisconnectedState); 7590 } 7591 } else { 7592 loge("Failed to connect config: " + config + " netId: " + netId); 7593 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7594 WifiManager.ERROR); 7595 break; 7596 } 7597 break; 7598 case WifiManager.SAVE_NETWORK: 7599 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 7600 // Fall thru 7601 case WifiStateMachine.CMD_AUTO_SAVE_NETWORK: 7602 // Only the current foreground user can modify networks. 7603 if (!isCurrentUserProfile(UserHandle.getUserId(message.sendingUid))) { 7604 loge("Only the current foreground user can modify networks " 7605 + " currentUserId=" + mCurrentUserId 7606 + " sendingUserId=" + UserHandle.getUserId(message.sendingUid)); 7607 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 7608 WifiManager.NOT_AUTHORIZED); 7609 break; 7610 } 7611 7612 lastSavedConfigurationAttempt = null; // Used for debug 7613 config = (WifiConfiguration) message.obj; 7614 if (config == null) { 7615 loge("ERROR: SAVE_NETWORK with null configuration" 7616 + mSupplicantStateTracker.getSupplicantStateName() 7617 + " my state " + getCurrentState().getName()); 7618 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7619 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 7620 WifiManager.ERROR); 7621 break; 7622 } 7623 lastSavedConfigurationAttempt = new WifiConfiguration(config); 7624 int nid = config.networkId; 7625 logd("SAVE_NETWORK id=" + Integer.toString(nid) 7626 + " config=" + config.SSID 7627 + " nid=" + config.networkId 7628 + " supstate=" + mSupplicantStateTracker.getSupplicantStateName() 7629 + " my state " + getCurrentState().getName()); 7630 7631 // Only record the uid if this is user initiated 7632 boolean checkUid = (message.what == WifiManager.SAVE_NETWORK); 7633 if (checkUid && !recordUidIfAuthorized(config, message.sendingUid, 7634 /* onlyAnnotate */ false)) { 7635 logw("Not authorized to update network " 7636 + " config=" + config.SSID 7637 + " cnid=" + config.networkId 7638 + " uid=" + message.sendingUid); 7639 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 7640 WifiManager.NOT_AUTHORIZED); 7641 break; 7642 } 7643 7644 result = mWifiConfigStore.saveNetwork(config, WifiConfiguration.UNKNOWN_UID); 7645 if (result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID) { 7646 if (mWifiInfo.getNetworkId() == result.getNetworkId()) { 7647 if (result.hasIpChanged()) { 7648 // The currently connection configuration was changed 7649 // We switched from DHCP to static or from static to DHCP, or the 7650 // static IP address has changed. 7651 log("Reconfiguring IP on connection"); 7652 // TODO: clear addresses and disable IPv6 7653 // to simplify obtainingIpState. 7654 transitionTo(mObtainingIpState); 7655 } 7656 if (result.hasProxyChanged()) { 7657 log("Reconfiguring proxy on connection"); 7658 notifyLinkProperties(); 7659 } 7660 } 7661 replyToMessage(message, WifiManager.SAVE_NETWORK_SUCCEEDED); 7662 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_SAVED, config); 7663 7664 if (VDBG) { 7665 logd("Success save network nid=" 7666 + Integer.toString(result.getNetworkId())); 7667 } 7668 7669 synchronized(mScanResultCache) { 7670 /** 7671 * If the command comes from WifiManager, then 7672 * tell autojoin the user did try to modify and save that network, 7673 * and interpret the SAVE_NETWORK as a request to connect 7674 */ 7675 boolean user = message.what == WifiManager.SAVE_NETWORK; 7676 7677 // Did this connect come from settings 7678 boolean persistConnect = 7679 mWifiConfigStore.checkConfigOverridePermission(message.sendingUid); 7680 7681 if (user) { 7682 mWifiConfigStore.updateLastConnectUid(config, message.sendingUid); 7683 mWifiConfigStore.writeKnownNetworkHistory(); 7684 } 7685 //Fixme, CMD_AUTO_SAVE_NETWORK can be cleaned 7686 mWifiQualifiedNetworkSelector.userSelectNetwork( 7687 result.getNetworkId(), persistConnect); 7688 candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(true, 7689 mAllowUntrustedConnections, mScanResults, linkDebouncing, 7690 isConnected(), isDisconnected(), isSupplicantTransientState()); 7691 tryToConnectToNetwork(candidate); 7692 } 7693 } else { 7694 loge("Failed to save network"); 7695 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7696 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 7697 WifiManager.ERROR); 7698 } 7699 break; 7700 case WifiManager.FORGET_NETWORK: 7701 // Only the current foreground user can modify networks. 7702 if (!isCurrentUserProfile(UserHandle.getUserId(message.sendingUid))) { 7703 loge("Only the current foreground user can modify networks " 7704 + " currentUserId=" + mCurrentUserId 7705 + " sendingUserId=" + UserHandle.getUserId(message.sendingUid)); 7706 replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, 7707 WifiManager.NOT_AUTHORIZED); 7708 break; 7709 } 7710 7711 // Debug only, remember last configuration that was forgotten 7712 WifiConfiguration toRemove 7713 = mWifiConfigStore.getWifiConfiguration(message.arg1); 7714 if (toRemove == null) { 7715 lastForgetConfigurationAttempt = null; 7716 } else { 7717 lastForgetConfigurationAttempt = new WifiConfiguration(toRemove); 7718 } 7719 // check that the caller owns this network 7720 netId = message.arg1; 7721 7722 if (!mWifiConfigStore.canModifyNetwork(message.sendingUid, netId, 7723 /* onlyAnnotate */ false)) { 7724 logw("Not authorized to forget network " 7725 + " cnid=" + netId 7726 + " uid=" + message.sendingUid); 7727 replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, 7728 WifiManager.NOT_AUTHORIZED); 7729 break; 7730 } 7731 7732 if (mWifiConfigStore.forgetNetwork(message.arg1)) { 7733 replyToMessage(message, WifiManager.FORGET_NETWORK_SUCCEEDED); 7734 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_FORGOT, 7735 (WifiConfiguration) message.obj); 7736 } else { 7737 loge("Failed to forget network"); 7738 replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, 7739 WifiManager.ERROR); 7740 } 7741 break; 7742 case WifiManager.START_WPS: 7743 WpsInfo wpsInfo = (WpsInfo) message.obj; 7744 WpsResult wpsResult; 7745 switch (wpsInfo.setup) { 7746 case WpsInfo.PBC: 7747 wpsResult = mWifiConfigStore.startWpsPbc(wpsInfo); 7748 break; 7749 case WpsInfo.KEYPAD: 7750 wpsResult = mWifiConfigStore.startWpsWithPinFromAccessPoint(wpsInfo); 7751 break; 7752 case WpsInfo.DISPLAY: 7753 wpsResult = mWifiConfigStore.startWpsWithPinFromDevice(wpsInfo); 7754 break; 7755 default: 7756 wpsResult = new WpsResult(Status.FAILURE); 7757 loge("Invalid setup for WPS"); 7758 break; 7759 } 7760 mWifiConfigStore.setAndEnableLastSelectedConfiguration 7761 (WifiConfiguration.INVALID_NETWORK_ID); 7762 if (wpsResult.status == Status.SUCCESS) { 7763 replyToMessage(message, WifiManager.START_WPS_SUCCEEDED, wpsResult); 7764 transitionTo(mWpsRunningState); 7765 } else { 7766 loge("Failed to start WPS with config " + wpsInfo.toString()); 7767 replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.ERROR); 7768 } 7769 break; 7770 case WifiMonitor.NETWORK_CONNECTION_EVENT: 7771 if (DBG) log("Network connection established"); 7772 mLastNetworkId = message.arg1; 7773 mLastBssid = (String) message.obj; 7774 7775 mWifiInfo.setBSSID(mLastBssid); 7776 mWifiInfo.setNetworkId(mLastNetworkId); 7777 7778 sendNetworkStateChangeBroadcast(mLastBssid); 7779 transitionTo(mObtainingIpState); 7780 break; 7781 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 7782 // Calling handleNetworkDisconnect here is redundant because we might already 7783 // have called it when leaving L2ConnectedState to go to disconnecting state 7784 // or thru other path 7785 // We should normally check the mWifiInfo or mLastNetworkId so as to check 7786 // if they are valid, and only in this case call handleNEtworkDisconnect, 7787 // TODO: this should be fixed for a L MR release 7788 // The side effect of calling handleNetworkDisconnect twice is that a bunch of 7789 // idempotent commands are executed twice (stopping Dhcp, enabling the SPS mode 7790 // at the chip etc... 7791 if (DBG) log("ConnectModeState: Network connection lost "); 7792 handleNetworkDisconnect(); 7793 transitionTo(mDisconnectedState); 7794 break; 7795 case CMD_PNO_NETWORK_FOUND: 7796 processPnoNetworkFound((ScanResult[]) message.obj); 7797 break; 7798 case CMD_ADD_PASSPOINT_MO: 7799 res = mWifiConfigStore.addPasspointManagementObject((String) message.obj); 7800 replyToMessage(message, message.what, res); 7801 break; 7802 case CMD_MODIFY_PASSPOINT_MO: 7803 if (message.obj != null) { 7804 Bundle bundle = (Bundle) message.obj; 7805 ArrayList<PasspointManagementObjectDefinition> mos = 7806 bundle.getParcelableArrayList("MOS"); 7807 res = mWifiConfigStore.modifyPasspointMo(bundle.getString("FQDN"), mos); 7808 } else { 7809 res = 0; 7810 } 7811 replyToMessage(message, message.what, res); 7812 7813 break; 7814 case CMD_QUERY_OSU_ICON: 7815 if (mWifiConfigStore.queryPasspointIcon( 7816 ((Bundle) message.obj).getLong("BSSID"), 7817 ((Bundle) message.obj).getString("FILENAME"))) { 7818 res = 1; 7819 } else { 7820 res = 0; 7821 } 7822 replyToMessage(message, message.what, res); 7823 break; 7824 case CMD_MATCH_PROVIDER_NETWORK: 7825 res = mWifiConfigStore.matchProviderWithCurrentNetwork((String) message.obj); 7826 replyToMessage(message, message.what, res); 7827 break; 7828 default: 7829 return NOT_HANDLED; 7830 } 7831 return HANDLED; 7832 } 7833 } 7834 7835 private void updateCapabilities(WifiConfiguration config) { 7836 NetworkCapabilities networkCapabilities = new NetworkCapabilities(mDfltNetworkCapabilities); 7837 if (config != null) { 7838 if (config.ephemeral) { 7839 networkCapabilities.removeCapability( 7840 NetworkCapabilities.NET_CAPABILITY_TRUSTED); 7841 } else { 7842 networkCapabilities.addCapability( 7843 NetworkCapabilities.NET_CAPABILITY_TRUSTED); 7844 } 7845 networkCapabilities.setSignalStrength(mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI ? 7846 mWifiInfo.getRssi() : NetworkCapabilities.SIGNAL_STRENGTH_UNSPECIFIED); 7847 } 7848 mNetworkAgent.sendNetworkCapabilities(networkCapabilities); 7849 } 7850 7851 private class WifiNetworkAgent extends NetworkAgent { 7852 public WifiNetworkAgent(Looper l, Context c, String TAG, NetworkInfo ni, 7853 NetworkCapabilities nc, LinkProperties lp, int score) { 7854 super(l, c, TAG, ni, nc, lp, score); 7855 } 7856 protected void unwanted() { 7857 // Ignore if we're not the current networkAgent. 7858 if (this != mNetworkAgent) return; 7859 if (DBG) log("WifiNetworkAgent -> Wifi unwanted score " 7860 + Integer.toString(mWifiInfo.score)); 7861 unwantedNetwork(NETWORK_STATUS_UNWANTED_DISCONNECT); 7862 } 7863 7864 @Override 7865 protected void networkStatus(int status) { 7866 if (this != mNetworkAgent) return; 7867 if (status == NetworkAgent.INVALID_NETWORK) { 7868 if (DBG) log("WifiNetworkAgent -> Wifi networkStatus invalid, score=" 7869 + Integer.toString(mWifiInfo.score)); 7870 unwantedNetwork(NETWORK_STATUS_UNWANTED_VALIDATION_FAILED); 7871 } else if (status == NetworkAgent.VALID_NETWORK) { 7872 if (DBG && mWifiInfo != null) log("WifiNetworkAgent -> Wifi networkStatus valid, score= " 7873 + Integer.toString(mWifiInfo.score)); 7874 doNetworkStatus(status); 7875 } 7876 } 7877 7878 @Override 7879 protected void saveAcceptUnvalidated(boolean accept) { 7880 if (this != mNetworkAgent) return; 7881 WifiStateMachine.this.sendMessage(CMD_ACCEPT_UNVALIDATED, accept ? 1 : 0); 7882 } 7883 7884 @Override 7885 protected void startPacketKeepalive(Message msg) { 7886 WifiStateMachine.this.sendMessage( 7887 CMD_START_IP_PACKET_OFFLOAD, msg.arg1, msg.arg2, msg.obj); 7888 } 7889 7890 @Override 7891 protected void stopPacketKeepalive(Message msg) { 7892 WifiStateMachine.this.sendMessage( 7893 CMD_STOP_IP_PACKET_OFFLOAD, msg.arg1, msg.arg2, msg.obj); 7894 } 7895 7896 @Override 7897 protected void setSignalStrengthThresholds(int[] thresholds) { 7898 // 0. If there are no thresholds, or if the thresholds are invalid, stop RSSI monitoring. 7899 // 1. Tell the hardware to start RSSI monitoring here, possibly adding MIN_VALUE and 7900 // MAX_VALUE at the start/end of the thresholds array if necessary. 7901 // 2. Ensure that when the hardware event fires, we fetch the RSSI from the hardware 7902 // event, call mWifiInfo.setRssi() with it, and call updateCapabilities(), and then 7903 // re-arm the hardware event. This needs to be done on the state machine thread to 7904 // avoid race conditions. The RSSI used to re-arm the event (and perhaps also the one 7905 // sent in the NetworkCapabilities) must be the one received from the hardware event 7906 // received, or we might skip callbacks. 7907 // 3. Ensure that when we disconnect, RSSI monitoring is stopped. 7908 log("Received signal strength thresholds: " + Arrays.toString(thresholds)); 7909 if (thresholds.length == 0) { 7910 WifiStateMachine.this.sendMessage(CMD_STOP_RSSI_MONITORING_OFFLOAD, 7911 mWifiInfo.getRssi()); 7912 return; 7913 } 7914 int [] rssiVals = Arrays.copyOf(thresholds, thresholds.length + 2); 7915 rssiVals[rssiVals.length - 2] = Byte.MIN_VALUE; 7916 rssiVals[rssiVals.length - 1] = Byte.MAX_VALUE; 7917 Arrays.sort(rssiVals); 7918 byte[] rssiRange = new byte[rssiVals.length]; 7919 for (int i = 0; i < rssiVals.length; i++) { 7920 int val = rssiVals[i]; 7921 if (val <= Byte.MAX_VALUE && val >= Byte.MIN_VALUE) { 7922 rssiRange[i] = (byte) val; 7923 } else { 7924 Log.e(TAG, "Illegal value " + val + " for RSSI thresholds: " 7925 + Arrays.toString(rssiVals)); 7926 WifiStateMachine.this.sendMessage(CMD_STOP_RSSI_MONITORING_OFFLOAD, 7927 mWifiInfo.getRssi()); 7928 return; 7929 } 7930 } 7931 // TODO: Do we quash rssi values in this sorted array which are very close? 7932 mRssiRanges = rssiRange; 7933 WifiStateMachine.this.sendMessage(CMD_START_RSSI_MONITORING_OFFLOAD, 7934 mWifiInfo.getRssi()); 7935 } 7936 7937 @Override 7938 protected void preventAutomaticReconnect() { 7939 if (this != mNetworkAgent) return; 7940 unwantedNetwork(NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN); 7941 } 7942 } 7943 7944 void unwantedNetwork(int reason) { 7945 sendMessage(CMD_UNWANTED_NETWORK, reason); 7946 } 7947 7948 void doNetworkStatus(int status) { 7949 sendMessage(CMD_NETWORK_STATUS, status); 7950 } 7951 7952 // rfc4186 & rfc4187: 7953 // create Permanent Identity base on IMSI, 7954 // identity = usernam@realm 7955 // with username = prefix | IMSI 7956 // and realm is derived MMC/MNC tuple according 3GGP spec(TS23.003) 7957 private String buildIdentity(int eapMethod, String imsi, String mccMnc) { 7958 String mcc; 7959 String mnc; 7960 String prefix; 7961 7962 if (imsi == null || imsi.isEmpty()) 7963 return ""; 7964 7965 if (eapMethod == WifiEnterpriseConfig.Eap.SIM) 7966 prefix = "1"; 7967 else if (eapMethod == WifiEnterpriseConfig.Eap.AKA) 7968 prefix = "0"; 7969 else if (eapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME) 7970 prefix = "6"; 7971 else // not a valide EapMethod 7972 return ""; 7973 7974 /* extract mcc & mnc from mccMnc */ 7975 if (mccMnc != null && !mccMnc.isEmpty()) { 7976 mcc = mccMnc.substring(0, 3); 7977 mnc = mccMnc.substring(3); 7978 if (mnc.length() == 2) 7979 mnc = "0" + mnc; 7980 } else { 7981 // extract mcc & mnc from IMSI, assume mnc size is 3 7982 mcc = imsi.substring(0, 3); 7983 mnc = imsi.substring(3, 6); 7984 } 7985 7986 return prefix + imsi + "@wlan.mnc" + mnc + ".mcc" + mcc + ".3gppnetwork.org"; 7987 } 7988 7989 boolean startScanForConfiguration(WifiConfiguration config, boolean restrictChannelList) { 7990 if (config == null) 7991 return false; 7992 7993 // We are still seeing a fairly high power consumption triggered by autojoin scans 7994 // Hence do partial scans only for PSK configuration that are roamable since the 7995 // primary purpose of the partial scans is roaming. 7996 // Full badn scans with exponential backoff for the purpose or extended roaming and 7997 // network switching are performed unconditionally. 7998 ScanDetailCache scanDetailCache = 7999 mWifiConfigStore.getScanDetailCache(config); 8000 if (scanDetailCache == null 8001 || !config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK) 8002 || scanDetailCache.size() > 6) { 8003 //return true but to not trigger the scan 8004 return true; 8005 } 8006 HashSet<Integer> freqs = mWifiConfigStore.makeChannelList(config, 8007 ONE_HOUR_MILLI, restrictChannelList); 8008 if (freqs != null && freqs.size() != 0) { 8009 //if (DBG) { 8010 logd("starting scan for " + config.configKey() + " with " + freqs); 8011 //} 8012 // Call wifi native to start the scan 8013 if (startScanNative(freqs)) { 8014 // Only count battery consumption if scan request is accepted 8015 noteScanStart(SCAN_ALARM_SOURCE, null); 8016 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK; 8017 } else { 8018 // used for debug only, mark scan as failed 8019 messageHandlingStatus = MESSAGE_HANDLING_STATUS_HANDLING_ERROR; 8020 } 8021 return true; 8022 } else { 8023 if (DBG) logd("no channels for " + config.configKey()); 8024 return false; 8025 } 8026 } 8027 8028 void clearCurrentConfigBSSID(String dbg) { 8029 // Clear the bssid in the current config's network block 8030 WifiConfiguration config = getCurrentWifiConfiguration(); 8031 if (config == null) 8032 return; 8033 clearConfigBSSID(config, dbg); 8034 } 8035 void clearConfigBSSID(WifiConfiguration config, String dbg) { 8036 if (config == null) 8037 return; 8038 if (DBG) { 8039 logd(dbg + " " + mTargetRoamBSSID + " config " + config.configKey() 8040 + " config.NetworkSelectionStatus.mNetworkSelectionBSSID " 8041 + config.getNetworkSelectionStatus().getNetworkSelectionBSSID()); 8042 } 8043 config.getNetworkSelectionStatus().setNetworkSelectionBSSID("any"); 8044 if (DBG) { 8045 logd(dbg + " " + config.SSID 8046 + " nid=" + Integer.toString(config.networkId)); 8047 } 8048 mWifiConfigStore.saveWifiConfigBSSID(config); 8049 } 8050 8051 class L2ConnectedState extends State { 8052 @Override 8053 public void enter() { 8054 mRssiPollToken++; 8055 if (mEnableRssiPolling) { 8056 sendMessage(CMD_RSSI_POLL, mRssiPollToken, 0); 8057 } 8058 if (mNetworkAgent != null) { 8059 loge("Have NetworkAgent when entering L2Connected"); 8060 setNetworkDetailedState(DetailedState.DISCONNECTED); 8061 } 8062 setNetworkDetailedState(DetailedState.CONNECTING); 8063 8064 if (!TextUtils.isEmpty(mTcpBufferSizes)) { 8065 mLinkProperties.setTcpBufferSizes(mTcpBufferSizes); 8066 } 8067 mNetworkAgent = new WifiNetworkAgent(getHandler().getLooper(), mContext, 8068 "WifiNetworkAgent", mNetworkInfo, mNetworkCapabilitiesFilter, 8069 mLinkProperties, 60); 8070 8071 // We must clear the config BSSID, as the wifi chipset may decide to roam 8072 // from this point on and having the BSSID specified in the network block would 8073 // cause the roam to faile and the device to disconnect 8074 clearCurrentConfigBSSID("L2ConnectedState"); 8075 } 8076 8077 @Override 8078 public void exit() { 8079 mIpManager.stop(); 8080 8081 // This is handled by receiving a NETWORK_DISCONNECTION_EVENT in ConnectModeState 8082 // Bug: 15347363 8083 // For paranoia's sake, call handleNetworkDisconnect 8084 // only if BSSID is null or last networkId 8085 // is not invalid. 8086 if (DBG) { 8087 StringBuilder sb = new StringBuilder(); 8088 sb.append("leaving L2ConnectedState state nid=" + Integer.toString(mLastNetworkId)); 8089 if (mLastBssid !=null) { 8090 sb.append(" ").append(mLastBssid); 8091 } 8092 } 8093 if (mLastBssid != null || mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 8094 handleNetworkDisconnect(); 8095 } 8096 } 8097 8098 @Override 8099 public boolean processMessage(Message message) { 8100 logStateAndMessage(message, this); 8101 8102 switch (message.what) { 8103 case DhcpStateMachine.CMD_PRE_DHCP_ACTION: 8104 handlePreDhcpSetup(); 8105 break; 8106 case DhcpStateMachine.CMD_PRE_DHCP_ACTION_COMPLETE: 8107 mIpManager.completedPreDhcpAction(); 8108 break; 8109 case DhcpStateMachine.CMD_POST_DHCP_ACTION: 8110 handlePostDhcpSetup(); 8111 // We advance to mConnectedState because IpManager will also send a 8112 // CMD_IPV4_PROVISIONING_SUCCESS message, which calls handleIPv4Success(), 8113 // which calls updateLinkProperties, which then sends 8114 // CMD_IP_CONFIGURATION_SUCCESSFUL. 8115 // 8116 // In the event of failure, we transition to mDisconnectingState 8117 // similarly--via messages sent back from IpManager. 8118 break; 8119 case CMD_IPV4_PROVISIONING_SUCCESS: { 8120 handleIPv4Success((DhcpResults) message.obj); 8121 break; 8122 } 8123 case CMD_IPV4_PROVISIONING_FAILURE: { 8124 handleIPv4Failure(); 8125 break; 8126 } 8127 case CMD_IP_CONFIGURATION_SUCCESSFUL: 8128 handleSuccessfulIpConfiguration(); 8129 mWifiMetrics.endConnectionEvent(0, WifiMetricsProto.ConnectionEvent.HLF_NONE); 8130 sendConnectedState(); 8131 transitionTo(mConnectedState); 8132 break; 8133 case CMD_IP_CONFIGURATION_LOST: 8134 // Get Link layer stats so that we get fresh tx packet counters. 8135 getWifiLinkLayerStats(true); 8136 handleIpConfigurationLost(); 8137 transitionTo(mDisconnectingState); 8138 break; 8139 case CMD_IP_REACHABILITY_LOST: 8140 if (DBG && message.obj != null) log((String) message.obj); 8141 handleIpReachabilityLost(); 8142 transitionTo(mDisconnectingState); 8143 break; 8144 case CMD_DISCONNECT: 8145 mWifiNative.disconnect(); 8146 transitionTo(mDisconnectingState); 8147 break; 8148 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 8149 if (message.arg1 == 1) { 8150 mWifiNative.disconnect(); 8151 mTemporarilyDisconnectWifi = true; 8152 transitionTo(mDisconnectingState); 8153 } 8154 break; 8155 case CMD_SET_OPERATIONAL_MODE: 8156 if (message.arg1 != CONNECT_MODE) { 8157 sendMessage(CMD_DISCONNECT); 8158 deferMessage(message); 8159 if (message.arg1 == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 8160 noteWifiDisabledWhileAssociated(); 8161 } 8162 } 8163 mWifiConfigStore. 8164 setAndEnableLastSelectedConfiguration( 8165 WifiConfiguration.INVALID_NETWORK_ID); 8166 break; 8167 case CMD_SET_COUNTRY_CODE: 8168 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 8169 deferMessage(message); 8170 break; 8171 case CMD_START_SCAN: 8172 if (DBG) { 8173 logd("CMD_START_SCAN source " + message.arg1 8174 + " txSuccessRate="+String.format( "%.2f", mWifiInfo.txSuccessRate) 8175 + " rxSuccessRate="+String.format( "%.2f", mWifiInfo.rxSuccessRate) 8176 + " targetRoamBSSID=" + mTargetRoamBSSID 8177 + " RSSI=" + mWifiInfo.getRssi()); 8178 } 8179 if (message.arg1 == SCAN_ALARM_SOURCE) { 8180 // Check if the CMD_START_SCAN message is obsolete (and thus if it should 8181 // not be processed) and restart the scan if neede 8182 if (!getEnableAutoJoinWhenAssociated()) { 8183 return HANDLED; 8184 } 8185 boolean shouldScan = mScreenOn; 8186 8187 if (!checkAndRestartDelayedScan(message.arg2, 8188 shouldScan, 8189 mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(), 8190 null, null)) { 8191 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 8192 logd("L2Connected CMD_START_SCAN source " 8193 + message.arg1 8194 + " " + message.arg2 + ", " + mDelayedScanCounter 8195 + " -> obsolete"); 8196 return HANDLED; 8197 } 8198 if (mP2pConnected.get()) { 8199 logd("L2Connected CMD_START_SCAN source " 8200 + message.arg1 8201 + " " + message.arg2 + ", " + mDelayedScanCounter 8202 + " ignore because P2P is connected"); 8203 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8204 return HANDLED; 8205 } 8206 boolean tryFullBandScan = false; 8207 boolean restrictChannelList = false; 8208 long now_ms = System.currentTimeMillis(); 8209 if (DBG) { 8210 logd("CMD_START_SCAN with age=" 8211 + Long.toString(now_ms - lastFullBandConnectedTimeMilli) 8212 + " interval=" + fullBandConnectedTimeIntervalMilli 8213 + " maxinterval=" + maxFullBandConnectedTimeIntervalMilli); 8214 } 8215 if (mWifiInfo != null) { 8216 if (mWifiConfigStore.enableFullBandScanWhenAssociated.get() && 8217 (now_ms - lastFullBandConnectedTimeMilli) 8218 > fullBandConnectedTimeIntervalMilli) { 8219 if (DBG) { 8220 logd("CMD_START_SCAN try full band scan age=" 8221 + Long.toString(now_ms - lastFullBandConnectedTimeMilli) 8222 + " interval=" + fullBandConnectedTimeIntervalMilli 8223 + " maxinterval=" + maxFullBandConnectedTimeIntervalMilli); 8224 } 8225 tryFullBandScan = true; 8226 } 8227 8228 if (mWifiInfo.txSuccessRate > 8229 mWifiConfigStore.maxTxPacketForFullScans 8230 || mWifiInfo.rxSuccessRate > 8231 mWifiConfigStore.maxRxPacketForFullScans) { 8232 // Too much traffic at the interface, hence no full band scan 8233 if (DBG) { 8234 logd("CMD_START_SCAN " + 8235 "prevent full band scan due to pkt rate"); 8236 } 8237 tryFullBandScan = false; 8238 } 8239 8240 if (mWifiInfo.txSuccessRate > 8241 mWifiConfigStore.maxTxPacketForPartialScans 8242 || mWifiInfo.rxSuccessRate > 8243 mWifiConfigStore.maxRxPacketForPartialScans) { 8244 // Don't scan if lots of packets are being sent 8245 restrictChannelList = true; 8246 if (mWifiConfigStore.alwaysEnableScansWhileAssociated.get() == 0) { 8247 if (DBG) { 8248 logd("CMD_START_SCAN source " + message.arg1 8249 + " ...and ignore scans" 8250 + " tx=" + String.format("%.2f", mWifiInfo.txSuccessRate) 8251 + " rx=" + String.format("%.2f", mWifiInfo.rxSuccessRate)); 8252 } 8253 messageHandlingStatus = MESSAGE_HANDLING_STATUS_REFUSED; 8254 return HANDLED; 8255 } 8256 } 8257 } 8258 8259 WifiConfiguration currentConfiguration = getCurrentWifiConfiguration(); 8260 if (DBG) { 8261 logd("CMD_START_SCAN full=" + 8262 tryFullBandScan); 8263 } 8264 if (currentConfiguration != null) { 8265 if (fullBandConnectedTimeIntervalMilli 8266 < mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get()) { 8267 // Sanity 8268 fullBandConnectedTimeIntervalMilli 8269 = mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(); 8270 } 8271 if (tryFullBandScan) { 8272 lastFullBandConnectedTimeMilli = now_ms; 8273 if (fullBandConnectedTimeIntervalMilli 8274 < mWifiConfigStore.associatedFullScanMaxIntervalMilli) { 8275 // Increase the interval 8276 fullBandConnectedTimeIntervalMilli 8277 = fullBandConnectedTimeIntervalMilli 8278 * mWifiConfigStore.associatedFullScanBackoff.get() / 8; 8279 8280 if (DBG) { 8281 logd("CMD_START_SCAN bump interval =" 8282 + fullBandConnectedTimeIntervalMilli); 8283 } 8284 } 8285 handleScanRequest(message); 8286 } else { 8287 if (!startScanForConfiguration( 8288 currentConfiguration, restrictChannelList)) { 8289 if (DBG) { 8290 logd("starting scan, " + 8291 " did not find channels -> full"); 8292 } 8293 lastFullBandConnectedTimeMilli = now_ms; 8294 if (fullBandConnectedTimeIntervalMilli 8295 < mWifiConfigStore.associatedFullScanMaxIntervalMilli) { 8296 // Increase the interval 8297 fullBandConnectedTimeIntervalMilli 8298 = fullBandConnectedTimeIntervalMilli 8299 * mWifiConfigStore.associatedFullScanBackoff.get() / 8; 8300 8301 if (DBG) { 8302 logd("CMD_START_SCAN bump interval =" 8303 + fullBandConnectedTimeIntervalMilli); 8304 } 8305 } 8306 handleScanRequest(message); 8307 } 8308 } 8309 8310 } else { 8311 logd("CMD_START_SCAN : connected mode and no configuration"); 8312 messageHandlingStatus = MESSAGE_HANDLING_STATUS_HANDLING_ERROR; 8313 } 8314 } else { 8315 // Not scan alarm source 8316 return NOT_HANDLED; 8317 } 8318 break; 8319 /* Ignore connection to same network */ 8320 case WifiManager.CONNECT_NETWORK: 8321 int netId = message.arg1; 8322 if (mWifiInfo.getNetworkId() == netId) { 8323 break; 8324 } 8325 return NOT_HANDLED; 8326 case WifiMonitor.NETWORK_CONNECTION_EVENT: 8327 mWifiInfo.setBSSID((String) message.obj); 8328 mLastNetworkId = message.arg1; 8329 mWifiInfo.setNetworkId(mLastNetworkId); 8330 if(!mLastBssid.equals((String) message.obj)) { 8331 mLastBssid = (String) message.obj; 8332 sendNetworkStateChangeBroadcast(mLastBssid); 8333 } 8334 break; 8335 case CMD_RSSI_POLL: 8336 if (message.arg1 == mRssiPollToken) { 8337 if (mWifiConfigStore.enableChipWakeUpWhenAssociated.get()) { 8338 if (VVDBG) log(" get link layer stats " + mWifiLinkLayerStatsSupported); 8339 WifiLinkLayerStats stats = getWifiLinkLayerStats(VDBG); 8340 if (stats != null) { 8341 // Sanity check the results provided by driver 8342 if (mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI 8343 && (stats.rssi_mgmt == 0 8344 || stats.beacon_rx == 0)) { 8345 stats = null; 8346 } 8347 } 8348 // Get Info and continue polling 8349 fetchRssiLinkSpeedAndFrequencyNative(); 8350 calculateWifiScore(stats); 8351 } 8352 sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, 8353 mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS); 8354 if (DBG) sendRssiChangeBroadcast(mWifiInfo.getRssi()); 8355 } else { 8356 // Polling has completed 8357 } 8358 break; 8359 case CMD_ENABLE_RSSI_POLL: 8360 cleanWifiScore(); 8361 if (mWifiConfigStore.enableRssiPollWhenAssociated.get()) { 8362 mEnableRssiPolling = (message.arg1 == 1); 8363 } else { 8364 mEnableRssiPolling = false; 8365 } 8366 mRssiPollToken++; 8367 if (mEnableRssiPolling) { 8368 // First poll 8369 fetchRssiLinkSpeedAndFrequencyNative(); 8370 sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, 8371 mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS); 8372 } 8373 break; 8374 case WifiManager.RSSI_PKTCNT_FETCH: 8375 RssiPacketCountInfo info = new RssiPacketCountInfo(); 8376 fetchRssiLinkSpeedAndFrequencyNative(); 8377 info.rssi = mWifiInfo.getRssi(); 8378 fetchPktcntNative(info); 8379 replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED, info); 8380 break; 8381 case CMD_DELAYED_NETWORK_DISCONNECT: 8382 if (!linkDebouncing && mWifiConfigStore.enableLinkDebouncing) { 8383 8384 // Ignore if we are not debouncing 8385 logd("CMD_DELAYED_NETWORK_DISCONNECT and not debouncing - ignore " 8386 + message.arg1); 8387 return HANDLED; 8388 } else { 8389 logd("CMD_DELAYED_NETWORK_DISCONNECT and debouncing - disconnect " 8390 + message.arg1); 8391 8392 linkDebouncing = false; 8393 // If we are still debouncing while this message comes, 8394 // it means we were not able to reconnect within the alloted time 8395 // = LINK_FLAPPING_DEBOUNCE_MSEC 8396 // and thus, trigger a real disconnect 8397 handleNetworkDisconnect(); 8398 transitionTo(mDisconnectedState); 8399 } 8400 break; 8401 case CMD_ASSOCIATED_BSSID: 8402 if ((String) message.obj == null) { 8403 logw("Associated command w/o BSSID"); 8404 break; 8405 } 8406 mLastBssid = (String) message.obj; 8407 if (mLastBssid != null 8408 && (mWifiInfo.getBSSID() == null 8409 || !mLastBssid.equals(mWifiInfo.getBSSID()))) { 8410 mWifiInfo.setBSSID((String) message.obj); 8411 sendNetworkStateChangeBroadcast(mLastBssid); 8412 } 8413 break; 8414 case CMD_START_RSSI_MONITORING_OFFLOAD: 8415 case CMD_RSSI_THRESHOLD_BREACH: 8416 byte currRssi = (byte) message.arg1; 8417 processRssiThreshold(currRssi, message.what); 8418 break; 8419 case CMD_STOP_RSSI_MONITORING_OFFLOAD: 8420 stopRssiMonitoringOffload(); 8421 break; 8422 case CMD_RESET_SIM_NETWORKS: 8423 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 8424 WifiConfiguration config = 8425 mWifiConfigStore.getWifiConfiguration(mLastNetworkId); 8426 if (mWifiConfigStore.isSimConfig(config)) { 8427 mWifiNative.disconnect(); 8428 transitionTo(mDisconnectingState); 8429 } 8430 } 8431 /* allow parent state to reset data for other networks */ 8432 return NOT_HANDLED; 8433 default: 8434 return NOT_HANDLED; 8435 } 8436 8437 return HANDLED; 8438 } 8439 } 8440 8441 class ObtainingIpState extends State { 8442 @Override 8443 public void enter() { 8444 if (DBG) { 8445 String key = ""; 8446 if (getCurrentWifiConfiguration() != null) { 8447 key = getCurrentWifiConfiguration().configKey(); 8448 } 8449 log("enter ObtainingIpState netId=" + Integer.toString(mLastNetworkId) 8450 + " " + key + " " 8451 + " roam=" + mAutoRoaming 8452 + " static=" + mWifiConfigStore.isUsingStaticIp(mLastNetworkId) 8453 + " watchdog= " + obtainingIpWatchdogCount); 8454 } 8455 8456 // Reset link Debouncing, indicating we have successfully re-connected to the AP 8457 // We might still be roaming 8458 linkDebouncing = false; 8459 8460 // Send event to CM & network change broadcast 8461 setNetworkDetailedState(DetailedState.OBTAINING_IPADDR); 8462 8463 // We must clear the config BSSID, as the wifi chipset may decide to roam 8464 // from this point on and having the BSSID specified in the network block would 8465 // cause the roam to fail and the device to disconnect. 8466 clearCurrentConfigBSSID("ObtainingIpAddress"); 8467 8468 if (!mWifiConfigStore.isUsingStaticIp(mLastNetworkId)) { 8469 // We used to do DHCPv4 RENEWs on framework roams. 8470 // TODO: Investigate whether we should reinstitute this. 8471 // 8472 // When we get here after a roam, we will already have called 8473 // mIpManager.confirmConfiguration() to ensure we're on the 8474 // same network (in handling of SupplicantState.COMPLETED). 8475 if (!isRoaming()) { 8476 mIpManager.stop(); 8477 mIpManager.startProvisioning(); 8478 } 8479 obtainingIpWatchdogCount++; 8480 logd("Start Dhcp Watchdog " + obtainingIpWatchdogCount); 8481 // Get Link layer stats so as we get fresh tx packet counters 8482 getWifiLinkLayerStats(true); 8483 sendMessageDelayed(obtainMessage(CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER, 8484 obtainingIpWatchdogCount, 0), OBTAINING_IP_ADDRESS_GUARD_TIMER_MSEC); 8485 } else { 8486 // Stop IpManager in case we're switching from static 8487 // configuration to DHCP. 8488 // 8489 // TODO: Only ever enter this state the first time we 8490 // connect to a network, never on changing from static 8491 // configuration to DHCP. When we transition from static 8492 // configuration to DHCP, we must tell ConnectivityService 8493 // that we're disconnected, because DHCP might take a long 8494 // time, during which connectivity APIs such as 8495 // getActiveNetworkInfo should not return CONNECTED. 8496 stopIpManager(); 8497 StaticIpConfiguration config = mWifiConfigStore.getStaticIpConfiguration( 8498 mLastNetworkId); 8499 if (config.ipAddress == null) { 8500 logd("Static IP lacks address"); 8501 sendMessage(CMD_IPV4_PROVISIONING_FAILURE); 8502 } else { 8503 mIpManager.startProvisioning(config); 8504 } 8505 } 8506 } 8507 8508 @Override 8509 public boolean processMessage(Message message) { 8510 logStateAndMessage(message, this); 8511 8512 switch(message.what) { 8513 case CMD_AUTO_CONNECT: 8514 case CMD_AUTO_ROAM: 8515 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8516 break; 8517 case WifiManager.SAVE_NETWORK: 8518 case WifiStateMachine.CMD_AUTO_SAVE_NETWORK: 8519 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 8520 deferMessage(message); 8521 break; 8522 /* Defer any power mode changes since we must keep active power mode at DHCP */ 8523 case CMD_SET_HIGH_PERF_MODE: 8524 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 8525 deferMessage(message); 8526 break; 8527 /* Defer scan request since we should not switch to other channels at DHCP */ 8528 case CMD_START_SCAN: 8529 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 8530 deferMessage(message); 8531 break; 8532 case CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER: 8533 if (message.arg1 == obtainingIpWatchdogCount) { 8534 logd("ObtainingIpAddress: Watchdog Triggered, count=" 8535 + obtainingIpWatchdogCount); 8536 handleIpConfigurationLost(); 8537 transitionTo(mDisconnectingState); 8538 break; 8539 } 8540 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8541 break; 8542 default: 8543 return NOT_HANDLED; 8544 } 8545 return HANDLED; 8546 } 8547 } 8548 8549 private void sendConnectedState() { 8550 // If this network was explicitly selected by the user, evaluate whether to call 8551 // explicitlySelected() so the system can treat it appropriately. 8552 WifiConfiguration config = getCurrentWifiConfiguration(); 8553 if (mWifiConfigStore.isLastSelectedConfiguration(config)) { 8554 boolean prompt = mWifiConfigStore.checkConfigOverridePermission(config.lastConnectUid); 8555 if (DBG) { 8556 log("Network selected by UID " + config.lastConnectUid + " prompt=" + prompt); 8557 } 8558 if (prompt) { 8559 // Selected by the user via Settings or QuickSettings. If this network has Internet 8560 // access, switch to it. Otherwise, switch to it only if the user confirms that they 8561 // really want to switch, or has already confirmed and selected "Don't ask again". 8562 if (DBG) { 8563 log("explictlySelected acceptUnvalidated=" + config.noInternetAccessExpected); 8564 } 8565 mNetworkAgent.explicitlySelected(config.noInternetAccessExpected); 8566 } 8567 } 8568 8569 setNetworkDetailedState(DetailedState.CONNECTED); 8570 mWifiConfigStore.updateStatus(mLastNetworkId, DetailedState.CONNECTED); 8571 sendNetworkStateChangeBroadcast(mLastBssid); 8572 } 8573 8574 class RoamingState extends State { 8575 boolean mAssociated; 8576 @Override 8577 public void enter() { 8578 if (DBG) { 8579 log("RoamingState Enter" 8580 + " mScreenOn=" + mScreenOn ); 8581 } 8582 setScanAlarm(false); 8583 8584 // Make sure we disconnect if roaming fails 8585 roamWatchdogCount++; 8586 logd("Start Roam Watchdog " + roamWatchdogCount); 8587 sendMessageDelayed(obtainMessage(CMD_ROAM_WATCHDOG_TIMER, 8588 roamWatchdogCount, 0), ROAM_GUARD_TIMER_MSEC); 8589 mAssociated = false; 8590 } 8591 @Override 8592 public boolean processMessage(Message message) { 8593 logStateAndMessage(message, this); 8594 WifiConfiguration config; 8595 switch (message.what) { 8596 case CMD_IP_CONFIGURATION_LOST: 8597 config = getCurrentWifiConfiguration(); 8598 if (config != null) { 8599 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_AUTOROAM_FAILURE); 8600 mWifiConfigStore.noteRoamingFailure(config, 8601 WifiConfiguration.ROAMING_FAILURE_IP_CONFIG); 8602 } 8603 return NOT_HANDLED; 8604 case CMD_UNWANTED_NETWORK: 8605 if (DBG) log("Roaming and CS doesnt want the network -> ignore"); 8606 return HANDLED; 8607 case CMD_SET_OPERATIONAL_MODE: 8608 if (message.arg1 != CONNECT_MODE) { 8609 deferMessage(message); 8610 } 8611 break; 8612 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 8613 /** 8614 * If we get a SUPPLICANT_STATE_CHANGE_EVENT indicating a DISCONNECT 8615 * before NETWORK_DISCONNECTION_EVENT 8616 * And there is an associated BSSID corresponding to our target BSSID, then 8617 * we have missed the network disconnection, transition to mDisconnectedState 8618 * and handle the rest of the events there. 8619 */ 8620 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 8621 if (stateChangeResult.state == SupplicantState.DISCONNECTED 8622 || stateChangeResult.state == SupplicantState.INACTIVE 8623 || stateChangeResult.state == SupplicantState.INTERFACE_DISABLED) { 8624 if (DBG) { 8625 log("STATE_CHANGE_EVENT in roaming state " 8626 + stateChangeResult.toString() ); 8627 } 8628 if (stateChangeResult.BSSID != null 8629 && stateChangeResult.BSSID.equals(mTargetRoamBSSID)) { 8630 handleNetworkDisconnect(); 8631 transitionTo(mDisconnectedState); 8632 } 8633 } 8634 if (stateChangeResult.state == SupplicantState.ASSOCIATED) { 8635 // We completed the layer2 roaming part 8636 mAssociated = true; 8637 if (stateChangeResult.BSSID != null) { 8638 mTargetRoamBSSID = (String) stateChangeResult.BSSID; 8639 } 8640 } 8641 break; 8642 case CMD_ROAM_WATCHDOG_TIMER: 8643 if (roamWatchdogCount == message.arg1) { 8644 if (DBG) log("roaming watchdog! -> disconnect"); 8645 mRoamFailCount++; 8646 handleNetworkDisconnect(); 8647 mWifiNative.disconnect(); 8648 transitionTo(mDisconnectedState); 8649 } 8650 break; 8651 case WifiMonitor.NETWORK_CONNECTION_EVENT: 8652 if (mAssociated) { 8653 if (DBG) log("roaming and Network connection established"); 8654 mLastNetworkId = message.arg1; 8655 mLastBssid = (String) message.obj; 8656 mWifiInfo.setBSSID(mLastBssid); 8657 mWifiInfo.setNetworkId(mLastNetworkId); 8658 mWifiQualifiedNetworkSelector.enableBssidForQualitynetworkSelection( 8659 mLastBssid, true); 8660 sendNetworkStateChangeBroadcast(mLastBssid); 8661 transitionTo(mObtainingIpState); 8662 } else { 8663 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8664 } 8665 break; 8666 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 8667 // Throw away but only if it corresponds to the network we're roaming to 8668 String bssid = (String) message.obj; 8669 if (true) { 8670 String target = ""; 8671 if (mTargetRoamBSSID != null) target = mTargetRoamBSSID; 8672 log("NETWORK_DISCONNECTION_EVENT in roaming state" 8673 + " BSSID=" + bssid 8674 + " target=" + target); 8675 } 8676 if (bssid != null && bssid.equals(mTargetRoamBSSID)) { 8677 handleNetworkDisconnect(); 8678 transitionTo(mDisconnectedState); 8679 } 8680 break; 8681 case WifiMonitor.SSID_TEMP_DISABLED: 8682 // Auth error while roaming 8683 logd("SSID_TEMP_DISABLED nid=" + Integer.toString(mLastNetworkId) 8684 + " id=" + Integer.toString(message.arg1) 8685 + " isRoaming=" + isRoaming() 8686 + " roam=" + mAutoRoaming); 8687 if (message.arg1 == mLastNetworkId) { 8688 config = getCurrentWifiConfiguration(); 8689 if (config != null) { 8690 mWifiLogger.captureBugReportData( 8691 WifiLogger.REPORT_REASON_AUTOROAM_FAILURE); 8692 mWifiConfigStore.noteRoamingFailure(config, 8693 WifiConfiguration.ROAMING_FAILURE_AUTH_FAILURE); 8694 } 8695 handleNetworkDisconnect(); 8696 transitionTo(mDisconnectingState); 8697 } 8698 return NOT_HANDLED; 8699 case CMD_START_SCAN: 8700 deferMessage(message); 8701 break; 8702 default: 8703 return NOT_HANDLED; 8704 } 8705 return HANDLED; 8706 } 8707 8708 @Override 8709 public void exit() { 8710 logd("WifiStateMachine: Leaving Roaming state"); 8711 } 8712 } 8713 8714 class ConnectedState extends State { 8715 @Override 8716 public void enter() { 8717 String address; 8718 updateDefaultRouteMacAddress(1000); 8719 if (DBG) { 8720 log("Enter ConnectedState " 8721 + " mScreenOn=" + mScreenOn 8722 + " scanperiod=" 8723 + Integer.toString(mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get()) 8724 + " useGscan=" + mHalBasedPnoDriverSupported + "/" 8725 + mWifiConfigStore.enableHalBasedPno.get() 8726 + " mHalBasedPnoEnableInDevSettings " + mHalBasedPnoEnableInDevSettings); 8727 } 8728 if (mScreenOn 8729 && getEnableAutoJoinWhenAssociated()) { 8730 if (useHalBasedAutoJoinOffload()) { 8731 startGScanConnectedModeOffload("connectedEnter"); 8732 } else { 8733 // restart scan alarm 8734 startDelayedScan(mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(), 8735 null, null); 8736 } 8737 } 8738 registerConnected(); 8739 lastConnectAttemptTimestamp = 0; 8740 targetWificonfiguration = null; 8741 // Paranoia 8742 linkDebouncing = false; 8743 8744 // Not roaming anymore 8745 mAutoRoaming = false; 8746 8747 if (testNetworkDisconnect) { 8748 testNetworkDisconnectCounter++; 8749 logd("ConnectedState Enter start disconnect test " + 8750 testNetworkDisconnectCounter); 8751 sendMessageDelayed(obtainMessage(CMD_TEST_NETWORK_DISCONNECT, 8752 testNetworkDisconnectCounter, 0), 15000); 8753 } 8754 8755 // Reenable all networks, allow for hidden networks to be scanned 8756 mWifiConfigStore.enableAllNetworks(); 8757 8758 mLastDriverRoamAttempt = 0; 8759 mTargetNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 8760 //startLazyRoam(); 8761 } 8762 @Override 8763 public boolean processMessage(Message message) { 8764 WifiConfiguration config = null; 8765 logStateAndMessage(message, this); 8766 8767 switch (message.what) { 8768 case CMD_RESTART_AUTOJOIN_OFFLOAD: 8769 if ( (int)message.arg2 < mRestartAutoJoinOffloadCounter ) { 8770 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 8771 return HANDLED; 8772 } 8773 /* If we are still in Disconnected state after having discovered a valid 8774 * network this means autojoin didnt managed to associate to the network, 8775 * then restart PNO so as we will try associating to it again. 8776 */ 8777 if (useHalBasedAutoJoinOffload()) { 8778 if (mGScanStartTimeMilli == 0) { 8779 // If offload is not started, then start it... 8780 startGScanConnectedModeOffload("connectedRestart"); 8781 } else { 8782 // If offload is already started, then check if we need to increase 8783 // the scan period and restart the Gscan 8784 long now = System.currentTimeMillis(); 8785 if (mGScanStartTimeMilli != 0 && now > mGScanStartTimeMilli 8786 && ((now - mGScanStartTimeMilli) 8787 > DISCONNECTED_SHORT_SCANS_DURATION_MILLI) 8788 && (mGScanPeriodMilli 8789 < mWifiConfigStore.wifiDisconnectedLongScanIntervalMilli.get())) 8790 { 8791 startConnectedGScan("Connected restart gscan"); 8792 } 8793 } 8794 } 8795 break; 8796 case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION: 8797 updateAssociatedScanPermission(); 8798 break; 8799 case CMD_UNWANTED_NETWORK: 8800 if (message.arg1 == NETWORK_STATUS_UNWANTED_DISCONNECT) { 8801 mWifiConfigStore.handleBadNetworkDisconnectReport(mLastNetworkId, mWifiInfo); 8802 mWifiNative.disconnect(); 8803 transitionTo(mDisconnectingState); 8804 } else if (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN || 8805 message.arg1 == NETWORK_STATUS_UNWANTED_VALIDATION_FAILED) { 8806 Log.d(TAG, (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN 8807 ? "NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN" 8808 : "NETWORK_STATUS_UNWANTED_VALIDATION_FAILED")); 8809 config = getCurrentWifiConfiguration(); 8810 if (config != null) { 8811 // Disable autojoin 8812 if (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN) { 8813 config.validatedInternetAccess = false; 8814 // Clear last-selected status, as being last-selected also avoids 8815 // disabling auto-join. 8816 if (mWifiConfigStore.isLastSelectedConfiguration(config)) { 8817 mWifiConfigStore.setAndEnableLastSelectedConfiguration( 8818 WifiConfiguration.INVALID_NETWORK_ID); 8819 } 8820 mWifiConfigStore.updateNetworkSelectionStatus(config, 8821 WifiConfiguration.NetworkSelectionStatus 8822 .DISABLED_NO_INTERNET); 8823 } 8824 config.numNoInternetAccessReports += 1; 8825 mWifiConfigStore.writeKnownNetworkHistory(); 8826 } 8827 } 8828 return HANDLED; 8829 case CMD_NETWORK_STATUS: 8830 if (message.arg1 == NetworkAgent.VALID_NETWORK) { 8831 config = getCurrentWifiConfiguration(); 8832 if (config != null) { 8833 // re-enable autojoin 8834 config.numNoInternetAccessReports = 0; 8835 config.validatedInternetAccess = true; 8836 mWifiConfigStore.writeKnownNetworkHistory(); 8837 } 8838 } 8839 return HANDLED; 8840 case CMD_ACCEPT_UNVALIDATED: 8841 boolean accept = (message.arg1 != 0); 8842 config = getCurrentWifiConfiguration(); 8843 if (config != null) { 8844 config.noInternetAccessExpected = accept; 8845 } 8846 return HANDLED; 8847 case CMD_TEST_NETWORK_DISCONNECT: 8848 // Force a disconnect 8849 if (message.arg1 == testNetworkDisconnectCounter) { 8850 mWifiNative.disconnect(); 8851 } 8852 break; 8853 case CMD_ASSOCIATED_BSSID: 8854 // ASSOCIATING to a new BSSID while already connected, indicates 8855 // that driver is roaming 8856 mLastDriverRoamAttempt = System.currentTimeMillis(); 8857 String toBSSID = (String)message.obj; 8858 if (toBSSID != null && !toBSSID.equals(mWifiInfo.getBSSID())) { 8859 mWifiConfigStore.driverRoamedFrom(mWifiInfo); 8860 } 8861 return NOT_HANDLED; 8862 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 8863 long lastRoam = 0; 8864 if (mLastDriverRoamAttempt != 0) { 8865 // Calculate time since last driver roam attempt 8866 lastRoam = System.currentTimeMillis() - mLastDriverRoamAttempt; 8867 mLastDriverRoamAttempt = 0; 8868 } 8869 if (unexpectedDisconnectedReason(message.arg2)) { 8870 mWifiLogger.captureBugReportData( 8871 WifiLogger.REPORT_REASON_UNEXPECTED_DISCONNECT); 8872 } 8873 config = getCurrentWifiConfiguration(); 8874 if (mScreenOn 8875 && !linkDebouncing 8876 && config != null 8877 && config.getNetworkSelectionStatus().isNetworkEnabled() 8878 && !mWifiConfigStore.isLastSelectedConfiguration(config) 8879 && (message.arg2 != 3 /* reason cannot be 3, i.e. locally generated */ 8880 || (lastRoam > 0 && lastRoam < 2000) /* unless driver is roaming */) 8881 && ((ScanResult.is24GHz(mWifiInfo.getFrequency()) 8882 && mWifiInfo.getRssi() > 8883 WifiQualifiedNetworkSelector.QUALIFIED_RSSI_24G_BAND) 8884 || (ScanResult.is5GHz(mWifiInfo.getFrequency()) 8885 && mWifiInfo.getRssi() > 8886 mWifiConfigStore.thresholdQualifiedRssi5.get()))) { 8887 // Start de-bouncing the L2 disconnection: 8888 // this L2 disconnection might be spurious. 8889 // Hence we allow 7 seconds for the state machine to try 8890 // to reconnect, go thru the 8891 // roaming cycle and enter Obtaining IP address 8892 // before signalling the disconnect to ConnectivityService and L3 8893 startScanForConfiguration(getCurrentWifiConfiguration(), false); 8894 linkDebouncing = true; 8895 8896 sendMessageDelayed(obtainMessage(CMD_DELAYED_NETWORK_DISCONNECT, 8897 0, mLastNetworkId), LINK_FLAPPING_DEBOUNCE_MSEC); 8898 if (DBG) { 8899 log("NETWORK_DISCONNECTION_EVENT in connected state" 8900 + " BSSID=" + mWifiInfo.getBSSID() 8901 + " RSSI=" + mWifiInfo.getRssi() 8902 + " freq=" + mWifiInfo.getFrequency() 8903 + " reason=" + message.arg2 8904 + " -> debounce"); 8905 } 8906 return HANDLED; 8907 } else { 8908 if (DBG) { 8909 log("NETWORK_DISCONNECTION_EVENT in connected state" 8910 + " BSSID=" + mWifiInfo.getBSSID() 8911 + " RSSI=" + mWifiInfo.getRssi() 8912 + " freq=" + mWifiInfo.getFrequency() 8913 + " was debouncing=" + linkDebouncing 8914 + " reason=" + message.arg2 8915 + " Network Selection Status=" + (config == null ? "Unavailable" 8916 : config.getNetworkSelectionStatus().getNetworkStatusString())); 8917 } 8918 } 8919 break; 8920 case CMD_AUTO_ROAM: 8921 // Clear the driver roam indication since we are attempting a framework roam 8922 mLastDriverRoamAttempt = 0; 8923 8924 /* Connect command coming from auto-join */ 8925 ScanResult candidate = (ScanResult)message.obj; 8926 String bssid = "any"; 8927 if (candidate != null) { 8928 bssid = candidate.BSSID; 8929 } 8930 int netId = mLastNetworkId; 8931 config = getCurrentWifiConfiguration(); 8932 8933 8934 if (config == null) { 8935 loge("AUTO_ROAM and no config, bail out..."); 8936 break; 8937 } 8938 8939 logd("CMD_AUTO_ROAM sup state " 8940 + mSupplicantStateTracker.getSupplicantStateName() 8941 + " my state " + getCurrentState().getName() 8942 + " nid=" + Integer.toString(netId) 8943 + " config " + config.configKey() 8944 + " roam=" + Integer.toString(message.arg2) 8945 + " to " + bssid 8946 + " targetRoamBSSID " + mTargetRoamBSSID); 8947 8948 setTargetBssid(config, bssid); 8949 mTargetNetworkId = netId; 8950 // Make sure the network is enabled, since supplicant will not re-enable it 8951 mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false); 8952 8953 if (deferForUserInput(message, netId, false)) { 8954 break; 8955 } else if (mWifiConfigStore.getWifiConfiguration(netId).userApproved == 8956 WifiConfiguration.USER_BANNED) { 8957 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 8958 WifiManager.NOT_AUTHORIZED); 8959 break; 8960 } 8961 8962 boolean ret = false; 8963 if (mLastNetworkId != netId) { 8964 if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ false, 8965 WifiConfiguration.UNKNOWN_UID) && mWifiNative.reconnect()) { 8966 ret = true; 8967 } 8968 } else { 8969 ret = mWifiNative.reassociate(); 8970 } 8971 if (ret) { 8972 lastConnectAttemptTimestamp = System.currentTimeMillis(); 8973 mWifiMetrics.startConnectionEvent(mWifiInfo); 8974 targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId); 8975 8976 // replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED); 8977 mAutoRoaming = true; 8978 transitionTo(mRoamingState); 8979 8980 } else { 8981 loge("Failed to connect config: " + config + " netId: " + netId); 8982 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 8983 WifiManager.ERROR); 8984 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 8985 break; 8986 } 8987 break; 8988 case CMD_START_IP_PACKET_OFFLOAD: { 8989 int slot = message.arg1; 8990 int intervalSeconds = message.arg2; 8991 KeepalivePacketData pkt = (KeepalivePacketData) message.obj; 8992 byte[] dstMac; 8993 try { 8994 InetAddress gateway = RouteInfo.selectBestRoute( 8995 mLinkProperties.getRoutes(), pkt.dstAddress).getGateway(); 8996 String dstMacStr = macAddressFromRoute(gateway.getHostAddress()); 8997 dstMac = macAddressFromString(dstMacStr); 8998 } catch (NullPointerException|IllegalArgumentException e) { 8999 loge("Can't find MAC address for next hop to " + pkt.dstAddress); 9000 mNetworkAgent.onPacketKeepaliveEvent(slot, 9001 ConnectivityManager.PacketKeepalive.ERROR_INVALID_IP_ADDRESS); 9002 break; 9003 } 9004 pkt.dstMac = dstMac; 9005 int result = startWifiIPPacketOffload(slot, pkt, intervalSeconds); 9006 mNetworkAgent.onPacketKeepaliveEvent(slot, result); 9007 break; 9008 } 9009 default: 9010 return NOT_HANDLED; 9011 } 9012 return HANDLED; 9013 } 9014 9015 @Override 9016 public void exit() { 9017 logd("WifiStateMachine: Leaving Connected state"); 9018 setScanAlarm(false); 9019 mLastDriverRoamAttempt = 0; 9020 9021 stopLazyRoam(); 9022 9023 mWhiteListedSsids = null; 9024 } 9025 } 9026 9027 class DisconnectingState extends State { 9028 9029 @Override 9030 public void enter() { 9031 9032 if (PDBG) { 9033 logd(" Enter DisconnectingState State scan interval " 9034 + mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get() 9035 + " mLegacyPnoEnabled= " + mLegacyPnoEnabled 9036 + " screenOn=" + mScreenOn); 9037 } 9038 9039 // Make sure we disconnect: we enter this state prior to connecting to a new 9040 // network, waiting for either a DISCONNECT event or a SUPPLICANT_STATE_CHANGE 9041 // event which in this case will be indicating that supplicant started to associate. 9042 // In some cases supplicant doesn't ignore the connect requests (it might not 9043 // find the target SSID in its cache), 9044 // Therefore we end up stuck that state, hence the need for the watchdog. 9045 disconnectingWatchdogCount++; 9046 logd("Start Disconnecting Watchdog " + disconnectingWatchdogCount); 9047 sendMessageDelayed(obtainMessage(CMD_DISCONNECTING_WATCHDOG_TIMER, 9048 disconnectingWatchdogCount, 0), DISCONNECTING_GUARD_TIMER_MSEC); 9049 } 9050 9051 @Override 9052 public boolean processMessage(Message message) { 9053 logStateAndMessage(message, this); 9054 switch (message.what) { 9055 case CMD_SET_OPERATIONAL_MODE: 9056 if (message.arg1 != CONNECT_MODE) { 9057 deferMessage(message); 9058 } 9059 break; 9060 case CMD_START_SCAN: 9061 deferMessage(message); 9062 return HANDLED; 9063 case CMD_DISCONNECTING_WATCHDOG_TIMER: 9064 if (disconnectingWatchdogCount == message.arg1) { 9065 if (DBG) log("disconnecting watchdog! -> disconnect"); 9066 handleNetworkDisconnect(); 9067 transitionTo(mDisconnectedState); 9068 } 9069 break; 9070 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 9071 /** 9072 * If we get a SUPPLICANT_STATE_CHANGE_EVENT before NETWORK_DISCONNECTION_EVENT 9073 * we have missed the network disconnection, transition to mDisconnectedState 9074 * and handle the rest of the events there 9075 */ 9076 deferMessage(message); 9077 handleNetworkDisconnect(); 9078 transitionTo(mDisconnectedState); 9079 break; 9080 default: 9081 return NOT_HANDLED; 9082 } 9083 return HANDLED; 9084 } 9085 } 9086 9087 class DisconnectedState extends State { 9088 @Override 9089 public void enter() { 9090 // We dont scan frequently if this is a temporary disconnect 9091 // due to p2p 9092 if (mTemporarilyDisconnectWifi) { 9093 mWifiP2pChannel.sendMessage(WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE); 9094 return; 9095 } 9096 9097 if (PDBG) { 9098 logd(" Enter DisconnectedState scan interval " 9099 + mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get() 9100 + " mLegacyPnoEnabled= " + mLegacyPnoEnabled 9101 + " screenOn=" + mScreenOn 9102 + " useGscan=" + mHalBasedPnoDriverSupported + "/" 9103 + mWifiConfigStore.enableHalBasedPno.get()); 9104 } 9105 9106 /** clear the roaming state, if we were roaming, we failed */ 9107 mAutoRoaming = false; 9108 9109 if (useHalBasedAutoJoinOffload()) { 9110 startGScanDisconnectedModeOffload("disconnectedEnter"); 9111 } else { 9112 if (mScreenOn) { 9113 /** 9114 * screen lit and => start scan immediately 9115 */ 9116 startScan(UNKNOWN_SCAN_SOURCE, 0, null, null); 9117 } else { 9118 /** 9119 * screen dark and PNO supported => scan alarm disabled 9120 */ 9121 if (mBackgroundScanSupported) { 9122 /* If a regular scan result is pending, do not initiate background 9123 * scan until the scan results are returned. This is needed because 9124 * initiating a background scan will cancel the regular scan and 9125 * scan results will not be returned until background scanning is 9126 * cleared 9127 */ 9128 if (!mIsScanOngoing) { 9129 enableBackgroundScan(true); 9130 } 9131 } else { 9132 setScanAlarm(true); 9133 } 9134 } 9135 } 9136 9137 /** 9138 * If we have no networks saved, the supplicant stops doing the periodic scan. 9139 * The scans are useful to notify the user of the presence of an open network. 9140 * Note that these are not wake up scans. 9141 */ 9142 if (mNoNetworksPeriodicScan != 0 && !mP2pConnected.get() 9143 && mWifiConfigStore.getConfiguredNetworks().size() == 0) { 9144 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 9145 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 9146 } 9147 9148 mDisconnectedTimeStamp = System.currentTimeMillis(); 9149 mDisconnectedPnoAlarmCount = 0; 9150 } 9151 @Override 9152 public boolean processMessage(Message message) { 9153 boolean ret = HANDLED; 9154 9155 logStateAndMessage(message, this); 9156 9157 switch (message.what) { 9158 case CMD_NO_NETWORKS_PERIODIC_SCAN: 9159 if (mP2pConnected.get()) break; 9160 if (mNoNetworksPeriodicScan != 0 && message.arg1 == mPeriodicScanToken && 9161 mWifiConfigStore.getConfiguredNetworks().size() == 0) { 9162 startScan(UNKNOWN_SCAN_SOURCE, -1, null, null); 9163 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 9164 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 9165 } 9166 break; 9167 case WifiManager.FORGET_NETWORK: 9168 case CMD_REMOVE_NETWORK: 9169 case CMD_REMOVE_APP_CONFIGURATIONS: 9170 case CMD_REMOVE_USER_CONFIGURATIONS: 9171 // Set up a delayed message here. After the forget/remove is handled 9172 // the handled delayed message will determine if there is a need to 9173 // scan and continue 9174 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 9175 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 9176 ret = NOT_HANDLED; 9177 break; 9178 case CMD_SET_OPERATIONAL_MODE: 9179 if (message.arg1 != CONNECT_MODE) { 9180 mOperationalMode = message.arg1; 9181 9182 mWifiConfigStore.disableAllNetworks(); 9183 if (mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 9184 mWifiP2pChannel.sendMessage(CMD_DISABLE_P2P_REQ); 9185 setWifiState(WIFI_STATE_DISABLED); 9186 } 9187 transitionTo(mScanModeState); 9188 } 9189 mWifiConfigStore. 9190 setAndEnableLastSelectedConfiguration( 9191 WifiConfiguration.INVALID_NETWORK_ID); 9192 break; 9193 /* Ignore network disconnect */ 9194 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 9195 // Interpret this as an L2 connection failure 9196 // End current connection event and log L2 reason code. 9197 mWifiMetrics.endConnectionEvent(message.arg2, 9198 WifiMetricsProto.ConnectionEvent.HLF_UNKNOWN); 9199 break; 9200 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 9201 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 9202 if (DBG) { 9203 logd("SUPPLICANT_STATE_CHANGE_EVENT state=" + stateChangeResult.state + 9204 " -> state= " + WifiInfo.getDetailedStateOf(stateChangeResult.state) 9205 + " debouncing=" + linkDebouncing); 9206 } 9207 setNetworkDetailedState(WifiInfo.getDetailedStateOf(stateChangeResult.state)); 9208 /* ConnectModeState does the rest of the handling */ 9209 ret = NOT_HANDLED; 9210 break; 9211 case CMD_START_SCAN: 9212 if (!checkOrDeferScanAllowed(message)) { 9213 // The scan request was rescheduled 9214 messageHandlingStatus = MESSAGE_HANDLING_STATUS_REFUSED; 9215 return HANDLED; 9216 } 9217 if (message.arg1 == SCAN_ALARM_SOURCE) { 9218 // Check if the CMD_START_SCAN message is obsolete (and thus if it should 9219 // not be processed) and restart the scan 9220 int period = mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get(); 9221 if (mP2pConnected.get()) { 9222 period = (int) mFacade.getLongSetting(mContext, 9223 Settings.Global.WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS, 9224 period); 9225 } 9226 if (!checkAndRestartDelayedScan(message.arg2, 9227 true, period, null, null)) { 9228 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 9229 logd("Disconnected CMD_START_SCAN source " 9230 + message.arg1 9231 + " " + message.arg2 + ", " + mDelayedScanCounter 9232 + " -> obsolete"); 9233 return HANDLED; 9234 } 9235 /* Disable background scan temporarily during a regular scan */ 9236 enableBackgroundScan(false); 9237 handleScanRequest(message); 9238 ret = HANDLED; 9239 } else { 9240 9241 /* 9242 * The SCAN request is not handled in this state and 9243 * would eventually might/will get handled in the 9244 * parent's state. The PNO, if already enabled had to 9245 * get disabled before the SCAN trigger. Hence, stop 9246 * the PNO if already enabled in this state, though the 9247 * SCAN request is not handled(PNO disable before the 9248 * SCAN trigger in any other state is not the right 9249 * place to issue). 9250 */ 9251 9252 enableBackgroundScan(false); 9253 ret = NOT_HANDLED; 9254 } 9255 break; 9256 case CMD_RESTART_AUTOJOIN_OFFLOAD: 9257 if ( (int)message.arg2 < mRestartAutoJoinOffloadCounter ) { 9258 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 9259 return HANDLED; 9260 } 9261 /* If we are still in Disconnected state after having discovered a valid 9262 * network this means autojoin didnt managed to associate to the network, 9263 * then restart PNO so as we will try associating to it again. 9264 */ 9265 if (useHalBasedAutoJoinOffload()) { 9266 if (mGScanStartTimeMilli == 0) { 9267 // If offload is not started, then start it... 9268 startGScanDisconnectedModeOffload("disconnectedRestart"); 9269 } else { 9270 // If offload is already started, then check if we need to increase 9271 // the scan period and restart the Gscan 9272 long now = System.currentTimeMillis(); 9273 if (mGScanStartTimeMilli != 0 && now > mGScanStartTimeMilli 9274 && ((now - mGScanStartTimeMilli) 9275 > DISCONNECTED_SHORT_SCANS_DURATION_MILLI) 9276 && (mGScanPeriodMilli 9277 < mWifiConfigStore.wifiDisconnectedLongScanIntervalMilli.get())) 9278 { 9279 startDisconnectedGScan("disconnected restart gscan"); 9280 } 9281 } 9282 } else { 9283 // If we are still disconnected for a short while after having found a 9284 // network thru PNO, then something went wrong, and for some reason we 9285 // couldn't join this network. 9286 // It might be due to a SW bug in supplicant or the wifi stack, or an 9287 // interoperability issue, or we try to join a bad bss and failed 9288 // In that case we want to restart pno so as to make sure that we will 9289 // attempt again to join that network. 9290 if (!mScreenOn && !mIsScanOngoing && mBackgroundScanSupported) { 9291 enableBackgroundScan(false); 9292 enableBackgroundScan(true); 9293 } 9294 return HANDLED; 9295 } 9296 break; 9297 case WifiMonitor.SCAN_RESULTS_EVENT: 9298 case WifiMonitor.SCAN_FAILED_EVENT: 9299 /* Re-enable background scan when a pending scan result is received */ 9300 if (!mScreenOn && mIsScanOngoing 9301 && mBackgroundScanSupported 9302 && !useHalBasedAutoJoinOffload()) { 9303 enableBackgroundScan(true); 9304 } else if (!mScreenOn 9305 && !mIsScanOngoing 9306 && mBackgroundScanSupported 9307 && !useHalBasedAutoJoinOffload()) { 9308 // We receive scan results from legacy PNO, hence restart the PNO alarm 9309 int delay; 9310 if (mDisconnectedPnoAlarmCount < 1) { 9311 delay = 30 * 1000; 9312 } else if (mDisconnectedPnoAlarmCount < 3) { 9313 delay = 60 * 1000; 9314 } else { 9315 delay = 360 * 1000; 9316 } 9317 mDisconnectedPnoAlarmCount++; 9318 if (VDBG) { 9319 logd("Starting PNO alarm " + delay); 9320 } 9321 mAlarmManager.set(AlarmManager.RTC_WAKEUP, 9322 System.currentTimeMillis() + delay, 9323 mPnoIntent); 9324 } 9325 /* Handled in parent state */ 9326 ret = NOT_HANDLED; 9327 break; 9328 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 9329 NetworkInfo info = (NetworkInfo) message.obj; 9330 mP2pConnected.set(info.isConnected()); 9331 if (mP2pConnected.get()) { 9332 int defaultInterval = mContext.getResources().getInteger( 9333 R.integer.config_wifi_scan_interval_p2p_connected); 9334 long scanIntervalMs = mFacade.getLongSetting(mContext, 9335 Settings.Global.WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS, 9336 defaultInterval); 9337 mWifiNative.setScanInterval((int) scanIntervalMs/1000); 9338 } else if (mWifiConfigStore.getConfiguredNetworks().size() == 0) { 9339 if (DBG) log("Turn on scanning after p2p disconnected"); 9340 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 9341 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 9342 } else { 9343 // If P2P is not connected and there are saved networks, then restart 9344 // scanning at the normal period. This is necessary because scanning might 9345 // have been disabled altogether if WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS 9346 // was set to zero. 9347 if (useHalBasedAutoJoinOffload()) { 9348 startGScanDisconnectedModeOffload("p2pRestart"); 9349 } else { 9350 startDelayedScan( 9351 mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get(), 9352 null, null); 9353 } 9354 } 9355 break; 9356 case CMD_RECONNECT: 9357 case CMD_REASSOCIATE: 9358 if (mTemporarilyDisconnectWifi) { 9359 // Drop a third party reconnect/reassociate if STA is 9360 // temporarily disconnected for p2p 9361 break; 9362 } else { 9363 // ConnectModeState handles it 9364 ret = NOT_HANDLED; 9365 } 9366 break; 9367 case CMD_SCREEN_STATE_CHANGED: 9368 handleScreenStateChanged(message.arg1 != 0); 9369 break; 9370 default: 9371 ret = NOT_HANDLED; 9372 } 9373 return ret; 9374 } 9375 9376 @Override 9377 public void exit() { 9378 mDisconnectedPnoAlarmCount = 0; 9379 /* No need for a background scan upon exit from a disconnected state */ 9380 enableBackgroundScan(false); 9381 setScanAlarm(false); 9382 mAlarmManager.cancel(mPnoIntent); 9383 } 9384 } 9385 9386 class WpsRunningState extends State { 9387 // Tracks the source to provide a reply 9388 private Message mSourceMessage; 9389 @Override 9390 public void enter() { 9391 mSourceMessage = Message.obtain(getCurrentMessage()); 9392 } 9393 @Override 9394 public boolean processMessage(Message message) { 9395 logStateAndMessage(message, this); 9396 9397 switch (message.what) { 9398 case WifiMonitor.WPS_SUCCESS_EVENT: 9399 // Ignore intermediate success, wait for full connection 9400 break; 9401 case WifiMonitor.NETWORK_CONNECTION_EVENT: 9402 replyToMessage(mSourceMessage, WifiManager.WPS_COMPLETED); 9403 mSourceMessage.recycle(); 9404 mSourceMessage = null; 9405 deferMessage(message); 9406 transitionTo(mDisconnectedState); 9407 break; 9408 case WifiMonitor.WPS_OVERLAP_EVENT: 9409 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 9410 WifiManager.WPS_OVERLAP_ERROR); 9411 mSourceMessage.recycle(); 9412 mSourceMessage = null; 9413 transitionTo(mDisconnectedState); 9414 break; 9415 case WifiMonitor.WPS_FAIL_EVENT: 9416 // Arg1 has the reason for the failure 9417 if ((message.arg1 != WifiManager.ERROR) || (message.arg2 != 0)) { 9418 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, message.arg1); 9419 mSourceMessage.recycle(); 9420 mSourceMessage = null; 9421 transitionTo(mDisconnectedState); 9422 mWifiMetrics.endConnectionEvent( 9423 message.arg1, WifiMetricsProto.ConnectionEvent.HLF_UNKNOWN); 9424 } else { 9425 if (DBG) log("Ignore unspecified fail event during WPS connection"); 9426 } 9427 break; 9428 case WifiMonitor.WPS_TIMEOUT_EVENT: 9429 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 9430 WifiManager.WPS_TIMED_OUT); 9431 mSourceMessage.recycle(); 9432 mSourceMessage = null; 9433 transitionTo(mDisconnectedState); 9434 break; 9435 case WifiManager.START_WPS: 9436 replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.IN_PROGRESS); 9437 break; 9438 case WifiManager.CANCEL_WPS: 9439 if (mWifiNative.cancelWps()) { 9440 replyToMessage(message, WifiManager.CANCEL_WPS_SUCCEDED); 9441 } else { 9442 replyToMessage(message, WifiManager.CANCEL_WPS_FAILED, WifiManager.ERROR); 9443 } 9444 transitionTo(mDisconnectedState); 9445 break; 9446 /** 9447 * Defer all commands that can cause connections to a different network 9448 * or put the state machine out of connect mode 9449 */ 9450 case CMD_STOP_DRIVER: 9451 case CMD_SET_OPERATIONAL_MODE: 9452 case WifiManager.CONNECT_NETWORK: 9453 case CMD_ENABLE_NETWORK: 9454 case CMD_RECONNECT: 9455 case CMD_REASSOCIATE: 9456 case CMD_ENABLE_ALL_NETWORKS: 9457 deferMessage(message); 9458 break; 9459 case CMD_AUTO_CONNECT: 9460 case CMD_AUTO_ROAM: 9461 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 9462 return HANDLED; 9463 case CMD_START_SCAN: 9464 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 9465 return HANDLED; 9466 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 9467 if (DBG) log("Network connection lost"); 9468 handleNetworkDisconnect(); 9469 break; 9470 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 9471 if (DBG) log("Ignore Assoc reject event during WPS Connection"); 9472 break; 9473 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 9474 // Disregard auth failure events during WPS connection. The 9475 // EAP sequence is retried several times, and there might be 9476 // failures (especially for wps pin). We will get a WPS_XXX 9477 // event at the end of the sequence anyway. 9478 if (DBG) log("Ignore auth failure during WPS connection"); 9479 break; 9480 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 9481 // Throw away supplicant state changes when WPS is running. 9482 // We will start getting supplicant state changes once we get 9483 // a WPS success or failure 9484 break; 9485 default: 9486 return NOT_HANDLED; 9487 } 9488 return HANDLED; 9489 } 9490 9491 @Override 9492 public void exit() { 9493 mWifiConfigStore.enableAllNetworks(); 9494 mWifiConfigStore.loadConfiguredNetworks(); 9495 } 9496 } 9497 9498 class SoftApStartingState extends State { 9499 @Override 9500 public void enter() { 9501 final Message message = getCurrentMessage(); 9502 if (message.what == CMD_START_AP) { 9503 WifiConfiguration config = (WifiConfiguration) message.obj; 9504 9505 if (config == null) { 9506 /** 9507 * Configuration not provided in the command, fallback to use the current 9508 * configuration. 9509 */ 9510 config = mWifiApConfigStore.getApConfiguration(); 9511 } else { 9512 /* Update AP configuration. */ 9513 mWifiApConfigStore.setApConfiguration(config); 9514 } 9515 startSoftApWithConfig(config); 9516 } else { 9517 throw new RuntimeException("Illegal transition to SoftApStartingState: " + message); 9518 } 9519 } 9520 @Override 9521 public boolean processMessage(Message message) { 9522 logStateAndMessage(message, this); 9523 9524 switch(message.what) { 9525 case CMD_START_SUPPLICANT: 9526 case CMD_STOP_SUPPLICANT: 9527 case CMD_START_AP: 9528 case CMD_STOP_AP: 9529 case CMD_START_DRIVER: 9530 case CMD_STOP_DRIVER: 9531 case CMD_SET_OPERATIONAL_MODE: 9532 case CMD_SET_COUNTRY_CODE: 9533 case CMD_SET_FREQUENCY_BAND: 9534 case CMD_START_PACKET_FILTERING: 9535 case CMD_STOP_PACKET_FILTERING: 9536 case CMD_TETHER_STATE_CHANGE: 9537 deferMessage(message); 9538 break; 9539 case CMD_START_AP_SUCCESS: 9540 setWifiApState(WIFI_AP_STATE_ENABLED, 0); 9541 transitionTo(mSoftApStartedState); 9542 break; 9543 case CMD_START_AP_FAILURE: 9544 setWifiApState(WIFI_AP_STATE_FAILED, message.arg1); 9545 transitionTo(mInitialState); 9546 break; 9547 default: 9548 return NOT_HANDLED; 9549 } 9550 return HANDLED; 9551 } 9552 } 9553 9554 class SoftApStartedState extends State { 9555 @Override 9556 public boolean processMessage(Message message) { 9557 logStateAndMessage(message, this); 9558 9559 switch(message.what) { 9560 case CMD_STOP_AP: 9561 if (DBG) log("Stopping Soft AP"); 9562 /* We have not tethered at this point, so we just shutdown soft Ap */ 9563 try { 9564 mNwService.stopAccessPoint(mInterfaceName); 9565 } catch(Exception e) { 9566 loge("Exception in stopAccessPoint()"); 9567 } 9568 setWifiApState(WIFI_AP_STATE_DISABLED, 0); 9569 transitionTo(mInitialState); 9570 break; 9571 case CMD_START_AP: 9572 // Ignore a start on a running access point 9573 break; 9574 // Fail client mode operation when soft AP is enabled 9575 case CMD_START_SUPPLICANT: 9576 loge("Cannot start supplicant with a running soft AP"); 9577 setWifiState(WIFI_STATE_UNKNOWN); 9578 break; 9579 case CMD_TETHER_STATE_CHANGE: 9580 TetherStateChange stateChange = (TetherStateChange) message.obj; 9581 if (startTethering(stateChange.available)) { 9582 transitionTo(mTetheringState); 9583 } 9584 break; 9585 default: 9586 return NOT_HANDLED; 9587 } 9588 return HANDLED; 9589 } 9590 } 9591 9592 class TetheringState extends State { 9593 @Override 9594 public void enter() { 9595 /* Send ourselves a delayed message to shut down if tethering fails to notify */ 9596 sendMessageDelayed(obtainMessage(CMD_TETHER_NOTIFICATION_TIMED_OUT, 9597 ++mTetherToken, 0), TETHER_NOTIFICATION_TIME_OUT_MSECS); 9598 } 9599 @Override 9600 public boolean processMessage(Message message) { 9601 logStateAndMessage(message, this); 9602 9603 switch(message.what) { 9604 case CMD_TETHER_STATE_CHANGE: 9605 TetherStateChange stateChange = (TetherStateChange) message.obj; 9606 if (isWifiTethered(stateChange.active)) { 9607 transitionTo(mTetheredState); 9608 } 9609 return HANDLED; 9610 case CMD_TETHER_NOTIFICATION_TIMED_OUT: 9611 if (message.arg1 == mTetherToken) { 9612 loge("Failed to get tether update, shutdown soft access point"); 9613 transitionTo(mSoftApStartedState); 9614 // Needs to be first thing handled 9615 sendMessageAtFrontOfQueue(CMD_STOP_AP); 9616 } 9617 break; 9618 case CMD_START_SUPPLICANT: 9619 case CMD_STOP_SUPPLICANT: 9620 case CMD_START_AP: 9621 case CMD_STOP_AP: 9622 case CMD_START_DRIVER: 9623 case CMD_STOP_DRIVER: 9624 case CMD_SET_OPERATIONAL_MODE: 9625 case CMD_SET_COUNTRY_CODE: 9626 case CMD_SET_FREQUENCY_BAND: 9627 case CMD_START_PACKET_FILTERING: 9628 case CMD_STOP_PACKET_FILTERING: 9629 deferMessage(message); 9630 break; 9631 default: 9632 return NOT_HANDLED; 9633 } 9634 return HANDLED; 9635 } 9636 } 9637 9638 class TetheredState extends State { 9639 @Override 9640 public boolean processMessage(Message message) { 9641 logStateAndMessage(message, this); 9642 9643 switch(message.what) { 9644 case CMD_TETHER_STATE_CHANGE: 9645 TetherStateChange stateChange = (TetherStateChange) message.obj; 9646 if (!isWifiTethered(stateChange.active)) { 9647 loge("Tethering reports wifi as untethered!, shut down soft Ap"); 9648 setHostApRunning(null, false); 9649 setHostApRunning(null, true); 9650 } 9651 return HANDLED; 9652 case CMD_STOP_AP: 9653 if (DBG) log("Untethering before stopping AP"); 9654 setWifiApState(WIFI_AP_STATE_DISABLING, 0); 9655 stopTethering(); 9656 transitionTo(mUntetheringState); 9657 // More work to do after untethering 9658 deferMessage(message); 9659 break; 9660 default: 9661 return NOT_HANDLED; 9662 } 9663 return HANDLED; 9664 } 9665 } 9666 9667 class UntetheringState extends State { 9668 @Override 9669 public void enter() { 9670 /* Send ourselves a delayed message to shut down if tethering fails to notify */ 9671 sendMessageDelayed(obtainMessage(CMD_TETHER_NOTIFICATION_TIMED_OUT, 9672 ++mTetherToken, 0), TETHER_NOTIFICATION_TIME_OUT_MSECS); 9673 9674 } 9675 @Override 9676 public boolean processMessage(Message message) { 9677 logStateAndMessage(message, this); 9678 9679 switch(message.what) { 9680 case CMD_TETHER_STATE_CHANGE: 9681 TetherStateChange stateChange = (TetherStateChange) message.obj; 9682 9683 /* Wait till wifi is untethered */ 9684 if (isWifiTethered(stateChange.active)) break; 9685 9686 transitionTo(mSoftApStartedState); 9687 break; 9688 case CMD_TETHER_NOTIFICATION_TIMED_OUT: 9689 if (message.arg1 == mTetherToken) { 9690 loge("Failed to get tether update, force stop access point"); 9691 transitionTo(mSoftApStartedState); 9692 } 9693 break; 9694 case CMD_START_SUPPLICANT: 9695 case CMD_STOP_SUPPLICANT: 9696 case CMD_START_AP: 9697 case CMD_STOP_AP: 9698 case CMD_START_DRIVER: 9699 case CMD_STOP_DRIVER: 9700 case CMD_SET_OPERATIONAL_MODE: 9701 case CMD_SET_COUNTRY_CODE: 9702 case CMD_SET_FREQUENCY_BAND: 9703 case CMD_START_PACKET_FILTERING: 9704 case CMD_STOP_PACKET_FILTERING: 9705 deferMessage(message); 9706 break; 9707 default: 9708 return NOT_HANDLED; 9709 } 9710 return HANDLED; 9711 } 9712 } 9713 9714 /** 9715 * State machine initiated requests can have replyTo set to null indicating 9716 * there are no recepients, we ignore those reply actions. 9717 */ 9718 private void replyToMessage(Message msg, int what) { 9719 if (msg.replyTo == null) return; 9720 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 9721 mReplyChannel.replyToMessage(msg, dstMsg); 9722 } 9723 9724 private void replyToMessage(Message msg, int what, int arg1) { 9725 if (msg.replyTo == null) return; 9726 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 9727 dstMsg.arg1 = arg1; 9728 mReplyChannel.replyToMessage(msg, dstMsg); 9729 } 9730 9731 private void replyToMessage(Message msg, int what, Object obj) { 9732 if (msg.replyTo == null) return; 9733 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 9734 dstMsg.obj = obj; 9735 mReplyChannel.replyToMessage(msg, dstMsg); 9736 } 9737 9738 /** 9739 * arg2 on the source message has a unique id that needs to be retained in replies 9740 * to match the request 9741 * <p>see WifiManager for details 9742 */ 9743 private Message obtainMessageWithWhatAndArg2(Message srcMsg, int what) { 9744 Message msg = Message.obtain(); 9745 msg.what = what; 9746 msg.arg2 = srcMsg.arg2; 9747 return msg; 9748 } 9749 9750 /** 9751 * @param wifiCredentialEventType WIFI_CREDENTIAL_SAVED or WIFI_CREDENTIAL_FORGOT 9752 * @param msg Must have a WifiConfiguration obj to succeed 9753 */ 9754 private void broadcastWifiCredentialChanged(int wifiCredentialEventType, 9755 WifiConfiguration config) { 9756 if (config != null && config.preSharedKey != null) { 9757 Intent intent = new Intent(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION); 9758 intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID, config.SSID); 9759 intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, 9760 wifiCredentialEventType); 9761 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT, 9762 android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE); 9763 } 9764 } 9765 9766 private static int parseHex(char ch) { 9767 if ('0' <= ch && ch <= '9') { 9768 return ch - '0'; 9769 } else if ('a' <= ch && ch <= 'f') { 9770 return ch - 'a' + 10; 9771 } else if ('A' <= ch && ch <= 'F') { 9772 return ch - 'A' + 10; 9773 } else { 9774 throw new NumberFormatException("" + ch + " is not a valid hex digit"); 9775 } 9776 } 9777 9778 private byte[] parseHex(String hex) { 9779 /* This only works for good input; don't throw bad data at it */ 9780 if (hex == null) { 9781 return new byte[0]; 9782 } 9783 9784 if (hex.length() % 2 != 0) { 9785 throw new NumberFormatException(hex + " is not a valid hex string"); 9786 } 9787 9788 byte[] result = new byte[(hex.length())/2 + 1]; 9789 result[0] = (byte) ((hex.length())/2); 9790 for (int i = 0, j = 1; i < hex.length(); i += 2, j++) { 9791 int val = parseHex(hex.charAt(i)) * 16 + parseHex(hex.charAt(i+1)); 9792 byte b = (byte) (val & 0xFF); 9793 result[j] = b; 9794 } 9795 9796 return result; 9797 } 9798 9799 private static String makeHex(byte[] bytes) { 9800 StringBuilder sb = new StringBuilder(); 9801 for (byte b : bytes) { 9802 sb.append(String.format("%02x", b)); 9803 } 9804 return sb.toString(); 9805 } 9806 9807 private static String makeHex(byte[] bytes, int from, int len) { 9808 StringBuilder sb = new StringBuilder(); 9809 for (int i = 0; i < len; i++) { 9810 sb.append(String.format("%02x", bytes[from+i])); 9811 } 9812 return sb.toString(); 9813 } 9814 9815 private static byte[] concat(byte[] array1, byte[] array2, byte[] array3) { 9816 9817 int len = array1.length + array2.length + array3.length; 9818 9819 if (array1.length != 0) { 9820 len++; /* add another byte for size */ 9821 } 9822 9823 if (array2.length != 0) { 9824 len++; /* add another byte for size */ 9825 } 9826 9827 if (array3.length != 0) { 9828 len++; /* add another byte for size */ 9829 } 9830 9831 byte[] result = new byte[len]; 9832 9833 int index = 0; 9834 if (array1.length != 0) { 9835 result[index] = (byte) (array1.length & 0xFF); 9836 index++; 9837 for (byte b : array1) { 9838 result[index] = b; 9839 index++; 9840 } 9841 } 9842 9843 if (array2.length != 0) { 9844 result[index] = (byte) (array2.length & 0xFF); 9845 index++; 9846 for (byte b : array2) { 9847 result[index] = b; 9848 index++; 9849 } 9850 } 9851 9852 if (array3.length != 0) { 9853 result[index] = (byte) (array3.length & 0xFF); 9854 index++; 9855 for (byte b : array3) { 9856 result[index] = b; 9857 index++; 9858 } 9859 } 9860 return result; 9861 } 9862 9863 private static byte[] concatHex(byte[] array1, byte[] array2) { 9864 9865 int len = array1.length + array2.length; 9866 9867 byte[] result = new byte[len]; 9868 9869 int index = 0; 9870 if (array1.length != 0) { 9871 for (byte b : array1) { 9872 result[index] = b; 9873 index++; 9874 } 9875 } 9876 9877 if (array2.length != 0) { 9878 for (byte b : array2) { 9879 result[index] = b; 9880 index++; 9881 } 9882 } 9883 9884 return result; 9885 } 9886 9887 void handleGsmAuthRequest(SimAuthRequestData requestData) { 9888 if (targetWificonfiguration == null 9889 || targetWificonfiguration.networkId == requestData.networkId) { 9890 logd("id matches targetWifiConfiguration"); 9891 } else { 9892 logd("id does not match targetWifiConfiguration"); 9893 return; 9894 } 9895 9896 TelephonyManager tm = (TelephonyManager) 9897 mContext.getSystemService(Context.TELEPHONY_SERVICE); 9898 9899 if (tm != null) { 9900 StringBuilder sb = new StringBuilder(); 9901 for (String challenge : requestData.data) { 9902 9903 if (challenge == null || challenge.isEmpty()) 9904 continue; 9905 logd("RAND = " + challenge); 9906 9907 byte[] rand = null; 9908 try { 9909 rand = parseHex(challenge); 9910 } catch (NumberFormatException e) { 9911 loge("malformed challenge"); 9912 continue; 9913 } 9914 9915 String base64Challenge = android.util.Base64.encodeToString( 9916 rand, android.util.Base64.NO_WRAP); 9917 /* 9918 * First, try with appType = 2 => USIM according to 9919 * com.android.internal.telephony.PhoneConstants#APPTYPE_xxx 9920 */ 9921 int appType = 2; 9922 String tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge); 9923 if (tmResponse == null) { 9924 /* Then, in case of failure, issue may be due to sim type, retry as a simple sim 9925 * appType = 1 => SIM 9926 */ 9927 appType = 1; 9928 tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge); 9929 } 9930 logv("Raw Response - " + tmResponse); 9931 9932 if (tmResponse != null && tmResponse.length() > 4) { 9933 byte[] result = android.util.Base64.decode(tmResponse, 9934 android.util.Base64.DEFAULT); 9935 logv("Hex Response -" + makeHex(result)); 9936 int sres_len = result[0]; 9937 String sres = makeHex(result, 1, sres_len); 9938 int kc_offset = 1+sres_len; 9939 int kc_len = result[kc_offset]; 9940 String kc = makeHex(result, 1 + kc_offset, kc_len); 9941 sb.append(":" + kc + ":" + sres); 9942 logv("kc:" + kc + " sres:" + sres); 9943 9944 String response = sb.toString(); 9945 logv("Supplicant Response -" + response); 9946 mWifiNative.simAuthResponse(requestData.networkId, "GSM-AUTH", response); 9947 } else { 9948 loge("bad response - " + tmResponse); 9949 mWifiNative.simAuthFailedResponse(requestData.networkId); 9950 } 9951 } 9952 9953 } else { 9954 loge("could not get telephony manager"); 9955 mWifiNative.simAuthFailedResponse(requestData.networkId); 9956 } 9957 } 9958 9959 void handle3GAuthRequest(SimAuthRequestData requestData) { 9960 StringBuilder sb = new StringBuilder(); 9961 byte[] rand = null; 9962 byte[] authn = null; 9963 String res_type = "UMTS-AUTH"; 9964 9965 if (targetWificonfiguration == null 9966 || targetWificonfiguration.networkId == requestData.networkId) { 9967 logd("id matches targetWifiConfiguration"); 9968 } else { 9969 logd("id does not match targetWifiConfiguration"); 9970 return; 9971 } 9972 if (requestData.data.length == 2) { 9973 try { 9974 rand = parseHex(requestData.data[0]); 9975 authn = parseHex(requestData.data[1]); 9976 } catch (NumberFormatException e) { 9977 loge("malformed challenge"); 9978 } 9979 } else { 9980 loge("malformed challenge"); 9981 } 9982 9983 String tmResponse = ""; 9984 if (rand != null && authn != null) { 9985 String base64Challenge = android.util.Base64.encodeToString( 9986 concatHex(rand,authn), android.util.Base64.NO_WRAP); 9987 9988 TelephonyManager tm = (TelephonyManager) 9989 mContext.getSystemService(Context.TELEPHONY_SERVICE); 9990 if (tm != null) { 9991 int appType = 2; // 2 => USIM 9992 tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge); 9993 logv("Raw Response - " + tmResponse); 9994 } else { 9995 loge("could not get telephony manager"); 9996 } 9997 } 9998 9999 boolean good_response = false; 10000 if (tmResponse != null && tmResponse.length() > 4) { 10001 byte[] result = android.util.Base64.decode(tmResponse, 10002 android.util.Base64.DEFAULT); 10003 loge("Hex Response - " + makeHex(result)); 10004 byte tag = result[0]; 10005 if (tag == (byte) 0xdb) { 10006 logv("successful 3G authentication "); 10007 int res_len = result[1]; 10008 String res = makeHex(result, 2, res_len); 10009 int ck_len = result[res_len + 2]; 10010 String ck = makeHex(result, res_len + 3, ck_len); 10011 int ik_len = result[res_len + ck_len + 3]; 10012 String ik = makeHex(result, res_len + ck_len + 4, ik_len); 10013 sb.append(":" + ik + ":" + ck + ":" + res); 10014 logv("ik:" + ik + "ck:" + ck + " res:" + res); 10015 good_response = true; 10016 } else if (tag == (byte) 0xdc) { 10017 loge("synchronisation failure"); 10018 int auts_len = result[1]; 10019 String auts = makeHex(result, 2, auts_len); 10020 res_type = "UMTS-AUTS"; 10021 sb.append(":" + auts); 10022 logv("auts:" + auts); 10023 good_response = true; 10024 } else { 10025 loge("bad response - unknown tag = " + tag); 10026 } 10027 } else { 10028 loge("bad response - " + tmResponse); 10029 } 10030 10031 if (good_response) { 10032 String response = sb.toString(); 10033 logv("Supplicant Response -" + response); 10034 mWifiNative.simAuthResponse(requestData.networkId, res_type, response); 10035 } else { 10036 mWifiNative.umtsAuthFailedResponse(requestData.networkId); 10037 } 10038 } 10039 10040 public int getCurrentUserId() { 10041 return mCurrentUserId; 10042 } 10043 10044 private boolean isCurrentUserProfile(int userId) { 10045 if (userId == mCurrentUserId) { 10046 return true; 10047 } 10048 final UserInfo parent = mUserManager.getProfileParent(userId); 10049 return parent != null && parent.id == mCurrentUserId; 10050 } 10051 10052 public List<UserInfo> getCurrentUserProfiles() { 10053 return mUserManager.getProfiles(mCurrentUserId); 10054 } 10055 10056 /** 10057 * @param reason reason code from supplicant on network disconnected event 10058 * @return true if this is a suspicious disconnect 10059 */ 10060 static boolean unexpectedDisconnectedReason(int reason) { 10061 return reason == 2 // PREV_AUTH_NOT_VALID 10062 || reason == 6 // CLASS2_FRAME_FROM_NONAUTH_STA 10063 || reason == 7 // FRAME_FROM_NONASSOC_STA 10064 || reason == 8 // STA_HAS_LEFT 10065 || reason == 9 // STA_REQ_ASSOC_WITHOUT_AUTH 10066 || reason == 14 // MICHAEL_MIC_FAILURE 10067 || reason == 15 // 4WAY_HANDSHAKE_TIMEOUT 10068 || reason == 16 // GROUP_KEY_UPDATE_TIMEOUT 10069 || reason == 18 // GROUP_CIPHER_NOT_VALID 10070 || reason == 19 // PAIRWISE_CIPHER_NOT_VALID 10071 || reason == 23 // IEEE_802_1X_AUTH_FAILED 10072 || reason == 34; // DISASSOC_LOW_ACK 10073 } 10074 10075 /** 10076 * Update WifiMetrics before dumping 10077 */ 10078 void updateWifiMetrics() { 10079 int numSavedNetworks = mWifiConfigStore.getConfiguredNetworksSize(); 10080 int numOpenNetworks = 0; 10081 int numPersonalNetworks = 0; 10082 int numEnterpriseNetworks = 0; 10083 int numNetworksAddedByUser = 0; 10084 int numNetworksAddedByApps = 0; 10085 for (WifiConfiguration config : mWifiConfigStore.getConfiguredNetworks()) { 10086 if (config.allowedAuthAlgorithms.get(WifiConfiguration.AuthAlgorithm.OPEN)) { 10087 numOpenNetworks++; 10088 } else if (config.isEnterprise()) { 10089 numEnterpriseNetworks++; 10090 } else { 10091 numPersonalNetworks++; 10092 } 10093 if (config.selfAdded) { 10094 numNetworksAddedByUser++; 10095 } else { 10096 numNetworksAddedByApps++; 10097 } 10098 } 10099 mWifiMetrics.setNumSavedNetworks(numSavedNetworks); 10100 mWifiMetrics.setNumOpenNetworks(numOpenNetworks); 10101 mWifiMetrics.setNumPersonalNetworks(numPersonalNetworks); 10102 mWifiMetrics.setNumEnterpriseNetworks(numEnterpriseNetworks); 10103 mWifiMetrics.setNumNetworksAddedByUser(numNetworksAddedByUser); 10104 mWifiMetrics.setNumNetworksAddedByApps(numNetworksAddedByApps); 10105 10106 /* <TODO> decide how to access WifiServiecImpl.isLocationEnabled() or if to do it manually 10107 mWifiMetrics.setIsLocationEnabled(Settings.Secure.getInt( 10108 mContext.getContentResolver(), 10109 Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF) 10110 != Settings.Secure.LOCATION_MODE_OFF); 10111 */ 10112 10113 /* <TODO> decide how statemachine will access WifiSettingsStore 10114 mWifiMetrics.setIsScanningAlwaysEnabled(mSettingsStore.isScanningAlwaysAvailable()); 10115 */ 10116 } 10117 10118 private static String getLinkPropertiesSummary(LinkProperties lp) { 10119 List<String> attributes = new ArrayList(6); 10120 if (lp.hasIPv4Address()) { 10121 attributes.add("v4"); 10122 } 10123 if (lp.hasIPv4DefaultRoute()) { 10124 attributes.add("v4r"); 10125 } 10126 if (lp.hasIPv4DnsServer()) { 10127 attributes.add("v4dns"); 10128 } 10129 if (lp.hasGlobalIPv6Address()) { 10130 attributes.add("v6"); 10131 } 10132 if (lp.hasIPv6DefaultRoute()) { 10133 attributes.add("v6r"); 10134 } 10135 if (lp.hasIPv6DnsServer()) { 10136 attributes.add("v6dns"); 10137 } 10138 10139 // TODO: Replace with String.join(" ", attributes) once we're fully on JDK 8. 10140 StringBuilder sb = new StringBuilder(); 10141 boolean first = true; 10142 for (String attr : attributes) { 10143 if (!first) { 10144 sb.append(" "); 10145 } else { 10146 first = false; 10147 } 10148 sb.append(attr); 10149 } 10150 return sb.toString(); 10151 } 10152 10153 /** 10154 * Try to connect to the network of candidate. According to the current connected network, this 10155 * API determines whether no action, disconnect and connect, or roaming. 10156 * 10157 * @param candidate the candidate network to connect to 10158 */ 10159 private void tryToConnectToNetwork(WifiConfiguration candidate) { 10160 if (candidate == null) { 10161 if (DBG) { 10162 Log.d(TAG, "Try to connect to null, give up"); 10163 } 10164 return; 10165 } 10166 10167 ScanResult scanResultCandidate = candidate.getNetworkSelectionStatus().getCandidate(); 10168 if (scanResultCandidate == null) { 10169 Log.e(TAG, "tryToConnectToNetwork: bad candidate. Network:" + candidate 10170 + " scanresult: " + scanResultCandidate); 10171 return; 10172 } 10173 10174 String targetBssid = scanResultCandidate.BSSID; 10175 String targetAssociationId = candidate.SSID + " : " + targetBssid; 10176 if (targetBssid != null && targetBssid.equals(mWifiInfo.getBSSID())) { 10177 if (DBG) { 10178 Log.d(TAG, "tryToConnectToNetwork: Already connect to" + targetAssociationId); 10179 } 10180 return; 10181 } 10182 10183 WifiConfiguration currentConnectedNetwork = mWifiConfigStore 10184 .getWifiConfiguration(mWifiInfo.getNetworkId()); 10185 String currentAssociationId = (currentConnectedNetwork == null) ? "Disconnected" : 10186 (mWifiInfo.getSSID() + " : " + mWifiInfo.getBSSID()); 10187 10188 if (currentConnectedNetwork != null 10189 && (currentConnectedNetwork.networkId == candidate.networkId 10190 || currentConnectedNetwork.isLinked(candidate))) { 10191 if (DBG) { 10192 Log.d(TAG, "tryToConnectToNetwork: Roaming from " + currentAssociationId + " to " 10193 + targetAssociationId); 10194 } 10195 sendMessage(CMD_AUTO_ROAM, candidate.networkId, 0, scanResultCandidate); 10196 } else { 10197 if (DBG) { 10198 Log.d(TAG, "tryToConnectToNetwork: Reconnect from " + currentAssociationId + " to " 10199 + targetAssociationId); 10200 } 10201 10202 sendMessage(CMD_AUTO_CONNECT, candidate.networkId, 0, scanResultCandidate.BSSID); 10203 } 10204 } 10205} 10206