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