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