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