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