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