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