WifiStateMachine.java revision d3ae426c1b298f038b34171d13d710524779074e
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 private static final String IE_STR = "ie="; 3836 private static final String ID_STR = "id="; 3837 private static final String BSSID_STR = "bssid="; 3838 private static final String FREQ_STR = "freq="; 3839 private static final String LEVEL_STR = "level="; 3840 private static final String TSF_STR = "tsf="; 3841 private static final String FLAGS_STR = "flags="; 3842 private static final String SSID_STR = "ssid="; 3843 private static final String DELIMITER_STR = "===="; 3844 private static final String END_STR = "####"; 3845 3846 // Used for matching BSSID strings, at least one characteer must be a non-zero number 3847 private static Pattern mNotZero = Pattern.compile("[1-9a-fA-F]"); 3848 3849 /** 3850 * Format: 3851 * <p/> 3852 * id=1 3853 * bssid=68:7f:76:d7:1a:6e 3854 * freq=2412 3855 * level=-44 3856 * tsf=1344626243700342 3857 * flags=[WPA2-PSK-CCMP][WPS][ESS] 3858 * ssid=zfdy 3859 * ==== 3860 * id=2 3861 * bssid=68:5f:74:d7:1a:6f 3862 * freq=5180 3863 * level=-73 3864 * tsf=1344626243700373 3865 * flags=[WPA2-PSK-CCMP][WPS][ESS] 3866 * ssid=zuby 3867 * ==== 3868 */ 3869 private void setScanResults() { 3870 mNumScanResultsKnown = 0; 3871 mNumScanResultsReturned = 0; 3872 String bssid = ""; 3873 int level = 0; 3874 int freq = 0; 3875 long tsf = 0; 3876 String flags = ""; 3877 WifiSsid wifiSsid = null; 3878 String scanResults; 3879 String tmpResults; 3880 StringBuffer scanResultsBuf = new StringBuffer(); 3881 int sid = 0; 3882 3883 while (true) { 3884 tmpResults = mWifiNative.scanResults(sid); 3885 if (TextUtils.isEmpty(tmpResults)) break; 3886 scanResultsBuf.append(tmpResults); 3887 scanResultsBuf.append("\n"); 3888 String[] lines = tmpResults.split("\n"); 3889 sid = -1; 3890 for (int i = lines.length - 1; i >= 0; i--) { 3891 if (lines[i].startsWith(END_STR)) { 3892 break; 3893 } else if (lines[i].startsWith(ID_STR)) { 3894 try { 3895 sid = Integer.parseInt(lines[i].substring(ID_STR.length())) + 1; 3896 } catch (NumberFormatException e) { 3897 // Nothing to do 3898 } 3899 break; 3900 } 3901 } 3902 if (sid == -1) break; 3903 } 3904 3905 scanResults = scanResultsBuf.toString(); 3906 3907 if (TextUtils.isEmpty(scanResults)) { 3908 mScanResults = new ArrayList<>(); 3909 return; 3910 } 3911 3912 mWifiConfigStore.trimANQPCache(false); 3913 3914 // note that all these splits and substrings keep references to the original 3915 // huge string buffer while the amount we really want is generally pretty small 3916 // so make copies instead (one example b/11087956 wasted 400k of heap here). 3917 synchronized (mScanResultCache) { 3918 mScanResults = new ArrayList<>(); 3919 String[] lines = scanResults.split("\n"); 3920 final int bssidStrLen = BSSID_STR.length(); 3921 final int flagLen = FLAGS_STR.length(); 3922 String infoElements = null; 3923 List<String> anqpLines = null; 3924 3925 for (String line : lines) { 3926 if (line.startsWith(BSSID_STR)) { 3927 bssid = new String(line.getBytes(), bssidStrLen, line.length() - bssidStrLen); 3928 } else if (line.startsWith(FREQ_STR)) { 3929 try { 3930 freq = Integer.parseInt(line.substring(FREQ_STR.length())); 3931 } catch (NumberFormatException e) { 3932 freq = 0; 3933 } 3934 } else if (line.startsWith(LEVEL_STR)) { 3935 try { 3936 level = Integer.parseInt(line.substring(LEVEL_STR.length())); 3937 /* some implementations avoid negative values by adding 256 3938 * so we need to adjust for that here. 3939 */ 3940 if (level > 0) level -= 256; 3941 } catch (NumberFormatException e) { 3942 level = 0; 3943 } 3944 } else if (line.startsWith(TSF_STR)) { 3945 try { 3946 tsf = Long.parseLong(line.substring(TSF_STR.length())); 3947 } catch (NumberFormatException e) { 3948 tsf = 0; 3949 } 3950 } else if (line.startsWith(FLAGS_STR)) { 3951 flags = new String(line.getBytes(), flagLen, line.length() - flagLen); 3952 } else if (line.startsWith(SSID_STR)) { 3953 wifiSsid = WifiSsid.createFromAsciiEncoded( 3954 line.substring(SSID_STR.length())); 3955 } else if (line.startsWith(IE_STR)) { 3956 infoElements = line; 3957 } else if (SupplicantBridge.isAnqpAttribute(line)) { 3958 if (anqpLines == null) { 3959 anqpLines = new ArrayList<>(); 3960 } 3961 anqpLines.add(line); 3962 } else if (line.startsWith(DELIMITER_STR) || line.startsWith(END_STR)) { 3963 if (bssid != null) { 3964 try { 3965 NetworkDetail networkDetail = 3966 new NetworkDetail(bssid, infoElements, anqpLines, freq); 3967 3968 String xssid = (wifiSsid != null) ? wifiSsid.toString() : WifiSsid.NONE; 3969 if (!xssid.equals(networkDetail.getTrimmedSSID())) { 3970 logd(String.format( 3971 "Inconsistent SSID on BSSID '%s': '%s' vs '%s': %s", 3972 bssid, xssid, networkDetail.getSSID(), infoElements)); 3973 } 3974 3975 if (networkDetail.hasInterworking()) { 3976 Log.d(Utils.hs2LogTag(getClass()), "HSNwk: '" + networkDetail); 3977 } 3978 3979 ScanDetail scanDetail = mScanResultCache.get(networkDetail); 3980 if (scanDetail != null) { 3981 scanDetail.updateResults(networkDetail, level, wifiSsid, xssid, 3982 flags, freq, tsf); 3983 } else { 3984 scanDetail = new ScanDetail(networkDetail, wifiSsid, bssid, 3985 flags, level, freq, tsf); 3986 mScanResultCache.put(networkDetail, scanDetail); 3987 } 3988 3989 mNumScanResultsReturned++; // Keep track of how many scan results we got 3990 // as part of this scan's processing 3991 mScanResults.add(scanDetail); 3992 } catch (IllegalArgumentException iae) { 3993 Log.d(TAG, "Failed to parse information elements: " + iae); 3994 } 3995 } 3996 bssid = null; 3997 level = 0; 3998 freq = 0; 3999 tsf = 0; 4000 flags = ""; 4001 wifiSsid = null; 4002 infoElements = null; 4003 anqpLines = null; 4004 } 4005 } 4006 } 4007 4008 /* don't attempt autojoin if last connect attempt was just scheduled */ 4009 boolean attemptAutoJoin = 4010 (System.currentTimeMillis() - lastConnectAttemptTimestamp) > CONNECT_TIMEOUT_MSEC; 4011 SupplicantState state = mWifiInfo.getSupplicantState(); 4012 String selection = mWifiConfigStore.getLastSelectedConfiguration(); 4013 if (getCurrentState() == mRoamingState 4014 || getCurrentState() == mObtainingIpState 4015 || getCurrentState() == mScanModeState 4016 || getCurrentState() == mDisconnectingState 4017 || (getCurrentState() == mConnectedState 4018 && !getEnableAutoJoinWhenAssociated()) 4019 || linkDebouncing 4020 || state == SupplicantState.ASSOCIATING 4021 || state == SupplicantState.AUTHENTICATING 4022 || state == SupplicantState.FOUR_WAY_HANDSHAKE 4023 || state == SupplicantState.GROUP_HANDSHAKE 4024 || (/* keep autojoin enabled if user has manually selected a wifi network, 4025 so as to make sure we reliably remain connected to this network */ 4026 mConnectionRequests == 0 && selection == null)) { 4027 // Dont attempt auto-joining again while we are already attempting to join 4028 // and/or obtaining Ip address 4029 attemptAutoJoin = false; 4030 } 4031 if (DBG) { 4032 if (selection == null) { 4033 selection = "<none>"; 4034 } 4035 logd("wifi setScanResults state" + getCurrentState() 4036 + " sup_state=" + state 4037 + " debouncing=" + linkDebouncing 4038 + " mConnectionRequests=" + mConnectionRequests 4039 + " selection=" + selection 4040 + " mNumScanResultsReturned " + mNumScanResultsReturned 4041 + " mScanResults " + mScanResults.size()); 4042 } 4043 if (attemptAutoJoin) { 4044 messageHandlingStatus = MESSAGE_HANDLING_STATUS_PROCESSED; 4045 } 4046 // Loose last selected configuration if we have been disconnected for 5 minutes 4047 if (getDisconnectedTimeMilli() > mWifiConfigStore.wifiConfigLastSelectionHysteresis) { 4048 mWifiConfigStore.setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID); 4049 } 4050 4051 if (attemptAutoJoin) { 4052 synchronized (mScanResultCache) { 4053 // AutoJoincontroller will directly acces the scan result list and update it with 4054 // ScanResult status 4055 mNumScanResultsKnown = mWifiAutoJoinController.newSupplicantResults(attemptAutoJoin); 4056 } 4057 } 4058 if (linkDebouncing) { 4059 // If debouncing, we dont re-select a SSID or BSSID hence 4060 // there is no need to call the network selection code 4061 // in WifiAutoJoinController, instead, 4062 // just try to reconnect to the same SSID by triggering a roam 4063 sendMessage(CMD_AUTO_ROAM, mLastNetworkId, 1, null); 4064 } 4065 } 4066 4067 /* 4068 * Fetch RSSI, linkspeed, and frequency on current connection 4069 */ 4070 private void fetchRssiLinkSpeedAndFrequencyNative() { 4071 int newRssi = -1; 4072 int newLinkSpeed = -1; 4073 int newFrequency = -1; 4074 4075 String signalPoll = mWifiNative.signalPoll(); 4076 4077 if (signalPoll != null) { 4078 String[] lines = signalPoll.split("\n"); 4079 for (String line : lines) { 4080 String[] prop = line.split("="); 4081 if (prop.length < 2) continue; 4082 try { 4083 if (prop[0].equals("RSSI")) { 4084 newRssi = Integer.parseInt(prop[1]); 4085 } else if (prop[0].equals("LINKSPEED")) { 4086 newLinkSpeed = Integer.parseInt(prop[1]); 4087 } else if (prop[0].equals("FREQUENCY")) { 4088 newFrequency = Integer.parseInt(prop[1]); 4089 } 4090 } catch (NumberFormatException e) { 4091 //Ignore, defaults on rssi and linkspeed are assigned 4092 } 4093 } 4094 } 4095 4096 if (PDBG) { 4097 logd("fetchRssiLinkSpeedAndFrequencyNative rssi=" 4098 + Integer.toString(newRssi) + " linkspeed=" 4099 + Integer.toString(newLinkSpeed)); 4100 } 4101 4102 if (newRssi > WifiInfo.INVALID_RSSI && newRssi < WifiInfo.MAX_RSSI) { 4103 // screen out invalid values 4104 /* some implementations avoid negative values by adding 256 4105 * so we need to adjust for that here. 4106 */ 4107 if (newRssi > 0) newRssi -= 256; 4108 mWifiInfo.setRssi(newRssi); 4109 /* 4110 * Rather then sending the raw RSSI out every time it 4111 * changes, we precalculate the signal level that would 4112 * be displayed in the status bar, and only send the 4113 * broadcast if that much more coarse-grained number 4114 * changes. This cuts down greatly on the number of 4115 * broadcasts, at the cost of not informing others 4116 * interested in RSSI of all the changes in signal 4117 * level. 4118 */ 4119 int newSignalLevel = WifiManager.calculateSignalLevel(newRssi, WifiManager.RSSI_LEVELS); 4120 if (newSignalLevel != mLastSignalLevel) { 4121 updateCapabilities(getCurrentWifiConfiguration()); 4122 sendRssiChangeBroadcast(newRssi); 4123 } 4124 mLastSignalLevel = newSignalLevel; 4125 } else { 4126 mWifiInfo.setRssi(WifiInfo.INVALID_RSSI); 4127 updateCapabilities(getCurrentWifiConfiguration()); 4128 } 4129 4130 if (newLinkSpeed != -1) { 4131 mWifiInfo.setLinkSpeed(newLinkSpeed); 4132 } 4133 if (newFrequency > 0) { 4134 if (ScanResult.is5GHz(newFrequency)) { 4135 mWifiConnectionStatistics.num5GhzConnected++; 4136 } 4137 if (ScanResult.is24GHz(newFrequency)) { 4138 mWifiConnectionStatistics.num24GhzConnected++; 4139 } 4140 mWifiInfo.setFrequency(newFrequency); 4141 } 4142 mWifiConfigStore.updateConfiguration(mWifiInfo); 4143 } 4144 4145 /** 4146 * Determine if we need to switch network: 4147 * - the delta determine the urgency to switch and/or or the expected evilness of the disruption 4148 * - match the uregncy of the switch versus the packet usage at the interface 4149 */ 4150 boolean shouldSwitchNetwork(int networkDelta) { 4151 int delta; 4152 if (networkDelta <= 0) { 4153 return false; 4154 } 4155 delta = networkDelta; 4156 if (mWifiInfo != null) { 4157 if (!getEnableAutoJoinWhenAssociated() 4158 && mWifiInfo.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID) { 4159 // If AutoJoin while associated is not enabled, 4160 // we should never switch network when already associated 4161 delta = -1000; 4162 } else { 4163 // TODO: Look at per AC packet count, do not switch if VO/VI traffic is present 4164 // TODO: at the interface. We should also discriminate between ucast and mcast, 4165 // TODO: since the rxSuccessRate include all the bonjour and Ipv6 4166 // TODO: broadcasts 4167 if ((mWifiInfo.txSuccessRate > 20) || (mWifiInfo.rxSuccessRate > 80)) { 4168 delta -= 999; 4169 } else if ((mWifiInfo.txSuccessRate > 5) || (mWifiInfo.rxSuccessRate > 30)) { 4170 delta -= 6; 4171 } 4172 logd("shouldSwitchNetwork " 4173 + " txSuccessRate=" + String.format("%.2f", mWifiInfo.txSuccessRate) 4174 + " rxSuccessRate=" + String.format("%.2f", mWifiInfo.rxSuccessRate) 4175 + " delta " + networkDelta + " -> " + delta); 4176 } 4177 } else { 4178 logd("shouldSwitchNetwork " 4179 + " delta " + networkDelta + " -> " + delta); 4180 } 4181 if (delta > 0) { 4182 return true; 4183 } 4184 return false; 4185 } 4186 4187 // Polling has completed, hence we wont have a score anymore 4188 private void cleanWifiScore() { 4189 mWifiInfo.txBadRate = 0; 4190 mWifiInfo.txSuccessRate = 0; 4191 mWifiInfo.txRetriesRate = 0; 4192 mWifiInfo.rxSuccessRate = 0; 4193 } 4194 4195 int mBadLinkspeedcount = 0; 4196 4197 // For debug, provide information about the last scoring operation 4198 String wifiScoringReport = null; 4199 4200 private void calculateWifiScore(WifiLinkLayerStats stats) { 4201 StringBuilder sb = new StringBuilder(); 4202 4203 int score = 56; // Starting score, temporarily hardcoded in between 50 and 60 4204 boolean isBadLinkspeed = (mWifiInfo.is24GHz() 4205 && mWifiInfo.getLinkSpeed() < mWifiConfigStore.badLinkSpeed24) 4206 || (mWifiInfo.is5GHz() && mWifiInfo.getLinkSpeed() 4207 < mWifiConfigStore.badLinkSpeed5); 4208 boolean isGoodLinkspeed = (mWifiInfo.is24GHz() 4209 && mWifiInfo.getLinkSpeed() >= mWifiConfigStore.goodLinkSpeed24) 4210 || (mWifiInfo.is5GHz() && mWifiInfo.getLinkSpeed() 4211 >= mWifiConfigStore.goodLinkSpeed5); 4212 4213 if (isBadLinkspeed) { 4214 if (mBadLinkspeedcount < 6) 4215 mBadLinkspeedcount++; 4216 } else { 4217 if (mBadLinkspeedcount > 0) 4218 mBadLinkspeedcount--; 4219 } 4220 4221 if (isBadLinkspeed) sb.append(" bl(").append(mBadLinkspeedcount).append(")"); 4222 if (isGoodLinkspeed) sb.append(" gl"); 4223 4224 /** 4225 * We want to make sure that we use the 24GHz RSSI thresholds if 4226 * there are 2.4GHz scan results 4227 * otherwise we end up lowering the score based on 5GHz values 4228 * which may cause a switch to LTE before roaming has a chance to try 2.4GHz 4229 * We also might unblacklist the configuation based on 2.4GHz 4230 * thresholds but joining 5GHz anyhow, and failing over to 2.4GHz because 5GHz is not good 4231 */ 4232 boolean use24Thresholds = false; 4233 boolean homeNetworkBoost = false; 4234 WifiConfiguration currentConfiguration = getCurrentWifiConfiguration(); 4235 ScanDetailCache scanDetailCache = 4236 mWifiConfigStore.getScanDetailCache(currentConfiguration); 4237 if (currentConfiguration != null && scanDetailCache != null) { 4238 currentConfiguration.setVisibility(scanDetailCache.getVisibility(12000)); 4239 if (currentConfiguration.visibility != null) { 4240 if (currentConfiguration.visibility.rssi24 != WifiConfiguration.INVALID_RSSI 4241 && currentConfiguration.visibility.rssi24 4242 >= (currentConfiguration.visibility.rssi5 - 2)) { 4243 use24Thresholds = true; 4244 } 4245 } 4246 if (scanDetailCache.size() <= 6 4247 && currentConfiguration.allowedKeyManagement.cardinality() == 1 4248 && currentConfiguration.allowedKeyManagement. 4249 get(WifiConfiguration.KeyMgmt.WPA_PSK) == true) { 4250 // A PSK network with less than 6 known BSSIDs 4251 // This is most likely a home network and thus we want to stick to wifi more 4252 homeNetworkBoost = true; 4253 } 4254 } 4255 if (homeNetworkBoost) sb.append(" hn"); 4256 if (use24Thresholds) sb.append(" u24"); 4257 4258 int rssi = mWifiInfo.getRssi() - 6 * mAggressiveHandover 4259 + (homeNetworkBoost ? WifiConfiguration.HOME_NETWORK_RSSI_BOOST : 0); 4260 sb.append(String.format(" rssi=%d ag=%d", rssi, mAggressiveHandover)); 4261 4262 boolean is24GHz = use24Thresholds || mWifiInfo.is24GHz(); 4263 4264 boolean isBadRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdBadRssi24.get()) 4265 || (!is24GHz && rssi < mWifiConfigStore.thresholdBadRssi5.get()); 4266 boolean isLowRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdLowRssi24.get()) 4267 || (!is24GHz && mWifiInfo.getRssi() < mWifiConfigStore.thresholdLowRssi5.get()); 4268 boolean isHighRSSI = (is24GHz && rssi >= mWifiConfigStore.thresholdGoodRssi24.get()) 4269 || (!is24GHz && mWifiInfo.getRssi() >= mWifiConfigStore.thresholdGoodRssi5.get()); 4270 4271 if (isBadRSSI) sb.append(" br"); 4272 if (isLowRSSI) sb.append(" lr"); 4273 if (isHighRSSI) sb.append(" hr"); 4274 4275 int penalizedDueToUserTriggeredDisconnect = 0; // For debug information 4276 if (currentConfiguration != null && 4277 (mWifiInfo.txSuccessRate > 5 || mWifiInfo.rxSuccessRate > 5)) { 4278 if (isBadRSSI) { 4279 currentConfiguration.numTicksAtBadRSSI++; 4280 if (currentConfiguration.numTicksAtBadRSSI > 1000) { 4281 // We remained associated for a compound amount of time while passing 4282 // traffic, hence loose the corresponding user triggered disabled stats 4283 if (currentConfiguration.numUserTriggeredWifiDisableBadRSSI > 0) { 4284 currentConfiguration.numUserTriggeredWifiDisableBadRSSI--; 4285 } 4286 if (currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0) { 4287 currentConfiguration.numUserTriggeredWifiDisableLowRSSI--; 4288 } 4289 if (currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) { 4290 currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI--; 4291 } 4292 currentConfiguration.numTicksAtBadRSSI = 0; 4293 } 4294 if (mWifiConfigStore.enableWifiCellularHandoverUserTriggeredAdjustment && 4295 (currentConfiguration.numUserTriggeredWifiDisableBadRSSI > 0 4296 || currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0 4297 || currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0)) { 4298 score = score - 5; 4299 penalizedDueToUserTriggeredDisconnect = 1; 4300 sb.append(" p1"); 4301 } 4302 } else if (isLowRSSI) { 4303 currentConfiguration.numTicksAtLowRSSI++; 4304 if (currentConfiguration.numTicksAtLowRSSI > 1000) { 4305 // We remained associated for a compound amount of time while passing 4306 // traffic, hence loose the corresponding user triggered disabled stats 4307 if (currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0) { 4308 currentConfiguration.numUserTriggeredWifiDisableLowRSSI--; 4309 } 4310 if (currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) { 4311 currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI--; 4312 } 4313 currentConfiguration.numTicksAtLowRSSI = 0; 4314 } 4315 if (mWifiConfigStore.enableWifiCellularHandoverUserTriggeredAdjustment && 4316 (currentConfiguration.numUserTriggeredWifiDisableLowRSSI > 0 4317 || currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0)) { 4318 score = score - 5; 4319 penalizedDueToUserTriggeredDisconnect = 2; 4320 sb.append(" p2"); 4321 } 4322 } else if (!isHighRSSI) { 4323 currentConfiguration.numTicksAtNotHighRSSI++; 4324 if (currentConfiguration.numTicksAtNotHighRSSI > 1000) { 4325 // We remained associated for a compound amount of time while passing 4326 // traffic, hence loose the corresponding user triggered disabled stats 4327 if (currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) { 4328 currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI--; 4329 } 4330 currentConfiguration.numTicksAtNotHighRSSI = 0; 4331 } 4332 if (mWifiConfigStore.enableWifiCellularHandoverUserTriggeredAdjustment && 4333 currentConfiguration.numUserTriggeredWifiDisableNotHighRSSI > 0) { 4334 score = score - 5; 4335 penalizedDueToUserTriggeredDisconnect = 3; 4336 sb.append(" p3"); 4337 } 4338 } 4339 sb.append(String.format(" ticks %d,%d,%d", currentConfiguration.numTicksAtBadRSSI, 4340 currentConfiguration.numTicksAtLowRSSI, 4341 currentConfiguration.numTicksAtNotHighRSSI)); 4342 } 4343 4344 if (PDBG) { 4345 String rssiStatus = ""; 4346 if (isBadRSSI) rssiStatus += " badRSSI "; 4347 else if (isHighRSSI) rssiStatus += " highRSSI "; 4348 else if (isLowRSSI) rssiStatus += " lowRSSI "; 4349 if (isBadLinkspeed) rssiStatus += " lowSpeed "; 4350 logd("calculateWifiScore freq=" + Integer.toString(mWifiInfo.getFrequency()) 4351 + " speed=" + Integer.toString(mWifiInfo.getLinkSpeed()) 4352 + " score=" + Integer.toString(mWifiInfo.score) 4353 + rssiStatus 4354 + " -> txbadrate=" + String.format("%.2f", mWifiInfo.txBadRate) 4355 + " txgoodrate=" + String.format("%.2f", mWifiInfo.txSuccessRate) 4356 + " txretriesrate=" + String.format("%.2f", mWifiInfo.txRetriesRate) 4357 + " rxrate=" + String.format("%.2f", mWifiInfo.rxSuccessRate) 4358 + " userTriggerdPenalty" + penalizedDueToUserTriggeredDisconnect); 4359 } 4360 4361 if ((mWifiInfo.txBadRate >= 1) && (mWifiInfo.txSuccessRate < 3) 4362 && (isBadRSSI || isLowRSSI)) { 4363 // Link is stuck 4364 if (mWifiInfo.linkStuckCount < 5) 4365 mWifiInfo.linkStuckCount += 1; 4366 sb.append(String.format(" ls+=%d", mWifiInfo.linkStuckCount)); 4367 if (PDBG) logd(" bad link -> stuck count =" 4368 + Integer.toString(mWifiInfo.linkStuckCount)); 4369 } else if (mWifiInfo.txBadRate < 0.3) { 4370 if (mWifiInfo.linkStuckCount > 0) 4371 mWifiInfo.linkStuckCount -= 1; 4372 sb.append(String.format(" ls-=%d", mWifiInfo.linkStuckCount)); 4373 if (PDBG) logd(" good link -> stuck count =" 4374 + Integer.toString(mWifiInfo.linkStuckCount)); 4375 } 4376 4377 sb.append(String.format(" [%d", score)); 4378 4379 if (mWifiInfo.linkStuckCount > 1) { 4380 // Once link gets stuck for more than 3 seconds, start reducing the score 4381 score = score - 2 * (mWifiInfo.linkStuckCount - 1); 4382 } 4383 sb.append(String.format(",%d", score)); 4384 4385 if (isBadLinkspeed) { 4386 score -= 4; 4387 if (PDBG) { 4388 logd(" isBadLinkspeed ---> count=" + mBadLinkspeedcount 4389 + " score=" + Integer.toString(score)); 4390 } 4391 } else if ((isGoodLinkspeed) && (mWifiInfo.txSuccessRate > 5)) { 4392 score += 4; // So as bad rssi alone dont kill us 4393 } 4394 sb.append(String.format(",%d", score)); 4395 4396 if (isBadRSSI) { 4397 if (mWifiInfo.badRssiCount < 7) 4398 mWifiInfo.badRssiCount += 1; 4399 } else if (isLowRSSI) { 4400 mWifiInfo.lowRssiCount = 1; // Dont increment the lowRssi count above 1 4401 if (mWifiInfo.badRssiCount > 0) { 4402 // Decrement bad Rssi count 4403 mWifiInfo.badRssiCount -= 1; 4404 } 4405 } else { 4406 mWifiInfo.badRssiCount = 0; 4407 mWifiInfo.lowRssiCount = 0; 4408 } 4409 4410 score -= mWifiInfo.badRssiCount * 2 + mWifiInfo.lowRssiCount; 4411 sb.append(String.format(",%d", score)); 4412 4413 if (PDBG) logd(" badRSSI count" + Integer.toString(mWifiInfo.badRssiCount) 4414 + " lowRSSI count" + Integer.toString(mWifiInfo.lowRssiCount) 4415 + " --> score " + Integer.toString(score)); 4416 4417 4418 if (isHighRSSI) { 4419 score += 5; 4420 if (PDBG) logd(" isHighRSSI ---> score=" + Integer.toString(score)); 4421 } 4422 sb.append(String.format(",%d]", score)); 4423 4424 sb.append(String.format(" brc=%d lrc=%d", mWifiInfo.badRssiCount, mWifiInfo.lowRssiCount)); 4425 4426 //sanitize boundaries 4427 if (score > NetworkAgent.WIFI_BASE_SCORE) 4428 score = NetworkAgent.WIFI_BASE_SCORE; 4429 if (score < 0) 4430 score = 0; 4431 4432 //report score 4433 if (score != mWifiInfo.score) { 4434 if (DBG) { 4435 logd("calculateWifiScore() report new score " + Integer.toString(score)); 4436 } 4437 mWifiInfo.score = score; 4438 if (mNetworkAgent != null) { 4439 mNetworkAgent.sendNetworkScore(score); 4440 } 4441 } 4442 wifiScoringReport = sb.toString(); 4443 } 4444 4445 public double getTxPacketRate() { 4446 if (mWifiInfo != null) { 4447 return mWifiInfo.txSuccessRate; 4448 } 4449 return -1; 4450 } 4451 4452 public double getRxPacketRate() { 4453 if (mWifiInfo != null) { 4454 return mWifiInfo.rxSuccessRate; 4455 } 4456 return -1; 4457 } 4458 4459 /** 4460 * Fetch TX packet counters on current connection 4461 */ 4462 private void fetchPktcntNative(RssiPacketCountInfo info) { 4463 String pktcntPoll = mWifiNative.pktcntPoll(); 4464 4465 if (pktcntPoll != null) { 4466 String[] lines = pktcntPoll.split("\n"); 4467 for (String line : lines) { 4468 String[] prop = line.split("="); 4469 if (prop.length < 2) continue; 4470 try { 4471 if (prop[0].equals("TXGOOD")) { 4472 info.txgood = Integer.parseInt(prop[1]); 4473 } else if (prop[0].equals("TXBAD")) { 4474 info.txbad = Integer.parseInt(prop[1]); 4475 } 4476 } catch (NumberFormatException e) { 4477 // Ignore 4478 } 4479 } 4480 } 4481 } 4482 4483 private boolean clearIPv4Address(String iface) { 4484 try { 4485 InterfaceConfiguration ifcg = new InterfaceConfiguration(); 4486 ifcg.setLinkAddress(new LinkAddress("0.0.0.0/0")); 4487 mNwService.setInterfaceConfig(iface, ifcg); 4488 return true; 4489 } catch (RemoteException e) { 4490 return false; 4491 } 4492 } 4493 4494 private boolean isProvisioned(LinkProperties lp) { 4495 return lp.isProvisioned() || 4496 (mWifiConfigStore.isUsingStaticIp(mLastNetworkId) && lp.hasIPv4Address()); 4497 } 4498 4499 /** 4500 * Creates a new LinkProperties object by merging information from various sources. 4501 * <p/> 4502 * This is needed because the information in mLinkProperties comes from multiple sources (DHCP, 4503 * netlink, static configuration, ...). When one of these sources of information has updated 4504 * link properties, we can't just assign them to mLinkProperties or we'd lose track of the 4505 * information that came from other sources. Instead, when one of those sources has new 4506 * information, we update the object that tracks the information from that source and then 4507 * call this method to integrate the change into a new LinkProperties object for subsequent 4508 * comparison with mLinkProperties. 4509 * <p/> 4510 * The information used to build LinkProperties is currently obtained as follows: 4511 * - Interface name: set in the constructor. 4512 * - IPv4 and IPv6 addresses: netlink, passed in by mNetlinkTracker. 4513 * - IPv4 routes, DNS servers, and domains: DHCP. 4514 * - IPv6 routes and DNS servers: netlink, passed in by mNetlinkTracker. 4515 * - HTTP proxy: the wifi config store. 4516 */ 4517 private LinkProperties makeLinkProperties() { 4518 LinkProperties newLp = new LinkProperties(); 4519 4520 // Interface name, proxy, and TCP buffer sizes are locally configured. 4521 newLp.setInterfaceName(mInterfaceName); 4522 newLp.setHttpProxy(mWifiConfigStore.getProxyProperties(mLastNetworkId)); 4523 if (!TextUtils.isEmpty(mTcpBufferSizes)) { 4524 newLp.setTcpBufferSizes(mTcpBufferSizes); 4525 } 4526 4527 // IPv4/v6 addresses, IPv6 routes and IPv6 DNS servers come from netlink. 4528 LinkProperties netlinkLinkProperties = mNetlinkTracker.getLinkProperties(); 4529 newLp.setLinkAddresses(netlinkLinkProperties.getLinkAddresses()); 4530 for (RouteInfo route : netlinkLinkProperties.getRoutes()) { 4531 newLp.addRoute(route); 4532 } 4533 for (InetAddress dns : netlinkLinkProperties.getDnsServers()) { 4534 // Only add likely reachable DNS servers. 4535 // TODO: investigate deleting this. 4536 if (newLp.isReachable(dns)) { 4537 newLp.addDnsServer(dns); 4538 } 4539 } 4540 4541 // IPv4 routes, DNS servers and domains come from mDhcpResults. 4542 synchronized (mDhcpResultsLock) { 4543 // Even when we're using static configuration, we don't need to look at the config 4544 // store, because static IP configuration also populates mDhcpResults. 4545 if ((mDhcpResults != null)) { 4546 for (RouteInfo route : mDhcpResults.getRoutes(mInterfaceName)) { 4547 newLp.addRoute(route); 4548 } 4549 for (InetAddress dns : mDhcpResults.dnsServers) { 4550 // Only add likely reachable DNS servers. 4551 // TODO: investigate deleting this. 4552 if (newLp.isReachable(dns)) { 4553 newLp.addDnsServer(dns); 4554 } 4555 } 4556 newLp.setDomains(mDhcpResults.domains); 4557 } 4558 } 4559 4560 return newLp; 4561 } 4562 4563 private void updateLinkProperties(int reason) { 4564 LinkProperties newLp = makeLinkProperties(); 4565 4566 final boolean linkChanged = !newLp.equals(mLinkProperties); 4567 final boolean wasProvisioned = isProvisioned(mLinkProperties); 4568 final boolean isProvisioned = isProvisioned(newLp); 4569 // TODO: Teach LinkProperties how to understand static assignment 4570 // and simplify all this provisioning change detection logic by 4571 // unifying it under LinkProperties.compareProvisioning(). 4572 final boolean lostProvisioning = 4573 (wasProvisioned && !isProvisioned) || 4574 (mLinkProperties.hasIPv4Address() && !newLp.hasIPv4Address()) || 4575 (mLinkProperties.isIPv6Provisioned() && !newLp.isIPv6Provisioned()); 4576 final DetailedState detailedState = getNetworkDetailedState(); 4577 4578 if (linkChanged) { 4579 if (DBG) { 4580 log("Link configuration changed for netId: " + mLastNetworkId 4581 + " old: " + mLinkProperties + " new: " + newLp); 4582 } 4583 mLinkProperties = newLp; 4584 if (mIpReachabilityMonitor != null) { 4585 mIpReachabilityMonitor.updateLinkProperties(mLinkProperties); 4586 } 4587 if (mNetworkAgent != null) mNetworkAgent.sendLinkProperties(mLinkProperties); 4588 } 4589 4590 if (lostProvisioning) { 4591 log("Lost IP layer provisioning!" + 4592 " was: " + mLinkProperties + 4593 " now: " + newLp); 4594 } 4595 4596 if (DBG) { 4597 StringBuilder sb = new StringBuilder(); 4598 sb.append("updateLinkProperties nid: " + mLastNetworkId); 4599 sb.append(" state: " + detailedState); 4600 sb.append(" reason: " + smToString(reason)); 4601 4602 if (mLinkProperties != null) { 4603 if (mLinkProperties.hasIPv4Address()) { 4604 sb.append(" v4"); 4605 } 4606 if (mLinkProperties.hasGlobalIPv6Address()) { 4607 sb.append(" v6"); 4608 } 4609 if (mLinkProperties.hasIPv4DefaultRoute()) { 4610 sb.append(" v4r"); 4611 } 4612 if (mLinkProperties.hasIPv6DefaultRoute()) { 4613 sb.append(" v6r"); 4614 } 4615 if (mLinkProperties.hasIPv4DnsServer()) { 4616 sb.append(" v4dns"); 4617 } 4618 if (mLinkProperties.hasIPv6DnsServer()) { 4619 sb.append(" v6dns"); 4620 } 4621 if (isProvisioned) { 4622 sb.append(" isprov"); 4623 } 4624 } 4625 logd(sb.toString()); 4626 } 4627 4628 // If we just configured or lost IP configuration, do the needful. 4629 // We don't just call handleSuccessfulIpConfiguration() or handleIpConfigurationLost() 4630 // here because those should only be called if we're attempting to connect or already 4631 // connected, whereas updateLinkProperties can be called at any time. 4632 switch (reason) { 4633 case DhcpStateMachine.DHCP_SUCCESS: 4634 case CMD_STATIC_IP_SUCCESS: 4635 // IPv4 provisioning succeded. Advance to connected state. 4636 sendMessage(CMD_IP_CONFIGURATION_SUCCESSFUL); 4637 if (!isProvisioned) { 4638 // Can never happen unless DHCP reports success but isProvisioned thinks the 4639 // resulting configuration is invalid (e.g., no IPv4 address, or the state in 4640 // mLinkProperties is out of sync with reality, or there's a bug in this code). 4641 // TODO: disconnect here instead. If our configuration is not usable, there's no 4642 // point in staying connected, and if mLinkProperties is out of sync with 4643 // reality, that will cause problems in the future. 4644 logd("IPv4 config succeeded, but not provisioned"); 4645 } 4646 break; 4647 4648 case DhcpStateMachine.DHCP_FAILURE: 4649 // DHCP failed. If we're not already provisioned, or we had IPv4 and now lost it, 4650 // give up and disconnect. 4651 // If we're already provisioned (e.g., IPv6-only network), stay connected. 4652 if (!isProvisioned || lostProvisioning) { 4653 sendMessage(CMD_IP_CONFIGURATION_LOST); 4654 } else { 4655 // DHCP failed, but we're provisioned (e.g., if we're on an IPv6-only network). 4656 sendMessage(CMD_IP_CONFIGURATION_SUCCESSFUL); 4657 4658 // To be sure we don't get stuck with a non-working network if all we had is 4659 // IPv4, remove the IPv4 address from the interface (since we're using DHCP, 4660 // and DHCP failed). If we had an IPv4 address before, the deletion of the 4661 // address will cause a CMD_UPDATE_LINKPROPERTIES. If the IPv4 address was 4662 // necessary for provisioning, its deletion will cause us to disconnect. 4663 // 4664 // This shouldn't be needed, because on an IPv4-only network a DHCP failure will 4665 // have empty DhcpResults and thus empty LinkProperties, and isProvisioned will 4666 // not return true if we're using DHCP and don't have an IPv4 default route. So 4667 // for now it's only here for extra redundancy. However, it will increase 4668 // robustness if we move to getting IPv4 routes from netlink as well. 4669 loge("DHCP failure: provisioned, clearing IPv4 address."); 4670 if (!clearIPv4Address(mInterfaceName)) { 4671 sendMessage(CMD_IP_CONFIGURATION_LOST); 4672 } 4673 } 4674 break; 4675 4676 case CMD_STATIC_IP_FAILURE: 4677 // Static configuration was invalid, or an error occurred in applying it. Give up. 4678 sendMessage(CMD_IP_CONFIGURATION_LOST); 4679 break; 4680 4681 case CMD_UPDATE_LINKPROPERTIES: 4682 // IP addresses, DNS servers, etc. changed. Act accordingly. 4683 if (lostProvisioning) { 4684 // We no longer have a usable network configuration. Disconnect. 4685 sendMessage(CMD_IP_CONFIGURATION_LOST); 4686 } else if (!wasProvisioned && isProvisioned) { 4687 // We have a usable IPv6-only config. Advance to connected state. 4688 sendMessage(CMD_IP_CONFIGURATION_SUCCESSFUL); 4689 } 4690 if (linkChanged && getNetworkDetailedState() == DetailedState.CONNECTED) { 4691 // If anything has changed and we're already connected, send out a notification. 4692 sendLinkConfigurationChangedBroadcast(); 4693 } 4694 break; 4695 } 4696 } 4697 4698 /** 4699 * Clears all our link properties. 4700 */ 4701 private void clearLinkProperties() { 4702 // Clear the link properties obtained from DHCP and netlink. 4703 synchronized (mDhcpResultsLock) { 4704 if (mDhcpResults != null) { 4705 mDhcpResults.clear(); 4706 } 4707 } 4708 mNetlinkTracker.clearLinkProperties(); 4709 if (mIpReachabilityMonitor != null) { 4710 mIpReachabilityMonitor.clearLinkProperties(); 4711 } 4712 4713 // Now clear the merged link properties. 4714 mLinkProperties.clear(); 4715 if (mNetworkAgent != null) mNetworkAgent.sendLinkProperties(mLinkProperties); 4716 } 4717 4718 /** 4719 * try to update default route MAC address. 4720 */ 4721 private String updateDefaultRouteMacAddress(int timeout) { 4722 String address = null; 4723 for (RouteInfo route : mLinkProperties.getRoutes()) { 4724 if (route.isDefaultRoute() && route.hasGateway()) { 4725 InetAddress gateway = route.getGateway(); 4726 if (gateway instanceof Inet4Address) { 4727 if (PDBG) { 4728 logd("updateDefaultRouteMacAddress found Ipv4 default :" 4729 + gateway.getHostAddress()); 4730 } 4731 address = macAddressFromRoute(gateway.getHostAddress()); 4732 /* The gateway's MAC address is known */ 4733 if ((address == null) && (timeout > 0)) { 4734 boolean reachable = false; 4735 try { 4736 reachable = gateway.isReachable(timeout); 4737 } catch (Exception e) { 4738 loge("updateDefaultRouteMacAddress exception reaching :" 4739 + gateway.getHostAddress()); 4740 4741 } finally { 4742 if (reachable == true) { 4743 4744 address = macAddressFromRoute(gateway.getHostAddress()); 4745 if (PDBG) { 4746 logd("updateDefaultRouteMacAddress reachable (tried again) :" 4747 + gateway.getHostAddress() + " found " + address); 4748 } 4749 } 4750 } 4751 } 4752 if (address != null) { 4753 mWifiConfigStore.setDefaultGwMacAddress(mLastNetworkId, address); 4754 } 4755 } 4756 } 4757 } 4758 return address; 4759 } 4760 4761 void sendScanResultsAvailableBroadcast(boolean scanSucceeded) { 4762 Intent intent = new Intent(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); 4763 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4764 intent.putExtra(WifiManager.EXTRA_RESULTS_UPDATED, scanSucceeded); 4765 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 4766 } 4767 4768 private void sendRssiChangeBroadcast(final int newRssi) { 4769 try { 4770 mBatteryStats.noteWifiRssiChanged(newRssi); 4771 } catch (RemoteException e) { 4772 // Won't happen. 4773 } 4774 Intent intent = new Intent(WifiManager.RSSI_CHANGED_ACTION); 4775 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4776 intent.putExtra(WifiManager.EXTRA_NEW_RSSI, newRssi); 4777 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 4778 } 4779 4780 private void sendNetworkStateChangeBroadcast(String bssid) { 4781 Intent intent = new Intent(WifiManager.NETWORK_STATE_CHANGED_ACTION); 4782 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4783 intent.putExtra(WifiManager.EXTRA_NETWORK_INFO, new NetworkInfo(mNetworkInfo)); 4784 intent.putExtra(WifiManager.EXTRA_LINK_PROPERTIES, new LinkProperties(mLinkProperties)); 4785 if (bssid != null) 4786 intent.putExtra(WifiManager.EXTRA_BSSID, bssid); 4787 if (mNetworkInfo.getDetailedState() == DetailedState.VERIFYING_POOR_LINK || 4788 mNetworkInfo.getDetailedState() == DetailedState.CONNECTED) { 4789 // We no longer report MAC address to third-parties and our code does 4790 // not rely on this broadcast, so just send the default MAC address. 4791 WifiInfo sentWifiInfo = new WifiInfo(mWifiInfo); 4792 sentWifiInfo.setMacAddress(WifiInfo.DEFAULT_MAC_ADDRESS); 4793 intent.putExtra(WifiManager.EXTRA_WIFI_INFO, sentWifiInfo); 4794 } 4795 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 4796 } 4797 4798 private WifiInfo getWiFiInfoForUid(int uid) { 4799 if (Binder.getCallingUid() == Process.myUid()) { 4800 return mWifiInfo; 4801 } 4802 4803 WifiInfo result = new WifiInfo(mWifiInfo); 4804 result.setMacAddress(WifiInfo.DEFAULT_MAC_ADDRESS); 4805 4806 IBinder binder = ServiceManager.getService("package"); 4807 IPackageManager packageManager = IPackageManager.Stub.asInterface(binder); 4808 4809 try { 4810 if (packageManager.checkUidPermission(Manifest.permission.LOCAL_MAC_ADDRESS, 4811 uid) == PackageManager.PERMISSION_GRANTED) { 4812 result.setMacAddress(mWifiInfo.getMacAddress()); 4813 } 4814 } catch (RemoteException e) { 4815 Log.e(TAG, "Error checking receiver permission", e); 4816 } 4817 4818 return result; 4819 } 4820 4821 private void sendLinkConfigurationChangedBroadcast() { 4822 Intent intent = new Intent(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION); 4823 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4824 intent.putExtra(WifiManager.EXTRA_LINK_PROPERTIES, new LinkProperties(mLinkProperties)); 4825 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 4826 } 4827 4828 private void sendSupplicantConnectionChangedBroadcast(boolean connected) { 4829 Intent intent = new Intent(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION); 4830 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 4831 intent.putExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, connected); 4832 mContext.sendBroadcastAsUser(intent, UserHandle.ALL); 4833 } 4834 4835 /** 4836 * Record the detailed state of a network. 4837 * 4838 * @param state the new {@code DetailedState} 4839 */ 4840 private boolean setNetworkDetailedState(NetworkInfo.DetailedState state) { 4841 boolean hidden = false; 4842 4843 if (linkDebouncing || isRoaming()) { 4844 // There is generally a confusion in the system about colluding 4845 // WiFi Layer 2 state (as reported by supplicant) and the Network state 4846 // which leads to multiple confusion. 4847 // 4848 // If link is de-bouncing or roaming, we already have an IP address 4849 // as well we were connected and are doing L2 cycles of 4850 // reconnecting or renewing IP address to check that we still have it 4851 // This L2 link flapping should ne be reflected into the Network state 4852 // which is the state of the WiFi Network visible to Layer 3 and applications 4853 // Note that once debouncing and roaming are completed, we will 4854 // set the Network state to where it should be, or leave it as unchanged 4855 // 4856 hidden = true; 4857 } 4858 if (DBG) { 4859 log("setDetailed state, old =" 4860 + mNetworkInfo.getDetailedState() + " and new state=" + state 4861 + " hidden=" + hidden); 4862 } 4863 if (mNetworkInfo.getExtraInfo() != null && mWifiInfo.getSSID() != null) { 4864 // Always indicate that SSID has changed 4865 if (!mNetworkInfo.getExtraInfo().equals(mWifiInfo.getSSID())) { 4866 if (DBG) { 4867 log("setDetailed state send new extra info" + mWifiInfo.getSSID()); 4868 } 4869 mNetworkInfo.setExtraInfo(mWifiInfo.getSSID()); 4870 sendNetworkStateChangeBroadcast(null); 4871 } 4872 } 4873 if (hidden == true) { 4874 return false; 4875 } 4876 4877 if (state != mNetworkInfo.getDetailedState()) { 4878 mNetworkInfo.setDetailedState(state, null, mWifiInfo.getSSID()); 4879 if (mNetworkAgent != null) { 4880 mNetworkAgent.sendNetworkInfo(mNetworkInfo); 4881 } 4882 sendNetworkStateChangeBroadcast(null); 4883 return true; 4884 } 4885 return false; 4886 } 4887 4888 private DetailedState getNetworkDetailedState() { 4889 return mNetworkInfo.getDetailedState(); 4890 } 4891 4892 private SupplicantState handleSupplicantStateChange(Message message) { 4893 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 4894 SupplicantState state = stateChangeResult.state; 4895 // Supplicant state change 4896 // [31-13] Reserved for future use 4897 // [8 - 0] Supplicant state (as defined in SupplicantState.java) 4898 // 50023 supplicant_state_changed (custom|1|5) 4899 mWifiInfo.setSupplicantState(state); 4900 // Network id is only valid when we start connecting 4901 if (SupplicantState.isConnecting(state)) { 4902 mWifiInfo.setNetworkId(stateChangeResult.networkId); 4903 } else { 4904 mWifiInfo.setNetworkId(WifiConfiguration.INVALID_NETWORK_ID); 4905 } 4906 4907 mWifiInfo.setBSSID(stateChangeResult.BSSID); 4908 4909 if (mWhiteListedSsids != null 4910 && mWhiteListedSsids.length > 0 4911 && stateChangeResult.wifiSsid != null) { 4912 String SSID = stateChangeResult.wifiSsid.toString(); 4913 String currentSSID = mWifiInfo.getSSID(); 4914 if (SSID != null 4915 && currentSSID != null 4916 && !SSID.equals(WifiSsid.NONE)) { 4917 // Remove quote before comparing 4918 if (SSID.length() >= 2 && SSID.charAt(0) == '"' 4919 && SSID.charAt(SSID.length() - 1) == '"') 4920 { 4921 SSID = SSID.substring(1, SSID.length() - 1); 4922 } 4923 if (currentSSID.length() >= 2 && currentSSID.charAt(0) == '"' 4924 && currentSSID.charAt(currentSSID.length() - 1) == '"') { 4925 currentSSID = currentSSID.substring(1, currentSSID.length() - 1); 4926 } 4927 if ((!SSID.equals(currentSSID)) && (getCurrentState() == mConnectedState)) { 4928 lastConnectAttemptTimestamp = System.currentTimeMillis(); 4929 targetWificonfiguration 4930 = mWifiConfigStore.getWifiConfiguration(mWifiInfo.getNetworkId()); 4931 transitionTo(mRoamingState); 4932 } 4933 } 4934 } 4935 4936 mWifiInfo.setSSID(stateChangeResult.wifiSsid); 4937 mWifiInfo.setEphemeral(mWifiConfigStore.isEphemeral(mWifiInfo.getNetworkId())); 4938 4939 mSupplicantStateTracker.sendMessage(Message.obtain(message)); 4940 4941 return state; 4942 } 4943 4944 /** 4945 * Resets the Wi-Fi Connections by clearing any state, resetting any sockets 4946 * using the interface, stopping DHCP & disabling interface 4947 */ 4948 private void handleNetworkDisconnect() { 4949 if (DBG) log("handleNetworkDisconnect: Stopping DHCP and clearing IP" 4950 + " stack:" + Thread.currentThread().getStackTrace()[2].getMethodName() 4951 + " - " + Thread.currentThread().getStackTrace()[3].getMethodName() 4952 + " - " + Thread.currentThread().getStackTrace()[4].getMethodName() 4953 + " - " + Thread.currentThread().getStackTrace()[5].getMethodName()); 4954 4955 stopRssiMonitoringOffload(); 4956 4957 clearCurrentConfigBSSID("handleNetworkDisconnect"); 4958 4959 stopDhcp(); 4960 4961 try { 4962 mNwService.clearInterfaceAddresses(mInterfaceName); 4963 mNwService.disableIpv6(mInterfaceName); 4964 } catch (Exception e) { 4965 loge("Failed to clear addresses or disable ipv6" + e); 4966 } 4967 4968 /* Reset data structures */ 4969 mBadLinkspeedcount = 0; 4970 mWifiInfo.reset(); 4971 linkDebouncing = false; 4972 /* Reset roaming parameters */ 4973 mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE; 4974 4975 /** 4976 * fullBandConnectedTimeIntervalMilli: 4977 * - start scans at mWifiConfigStore.wifiAssociatedShortScanIntervalMilli seconds interval 4978 * - exponentially increase to mWifiConfigStore.associatedFullScanMaxIntervalMilli 4979 * Initialize to sane value = 20 seconds 4980 */ 4981 fullBandConnectedTimeIntervalMilli = 20 * 1000; 4982 4983 setNetworkDetailedState(DetailedState.DISCONNECTED); 4984 if (mNetworkAgent != null) { 4985 mNetworkAgent.sendNetworkInfo(mNetworkInfo); 4986 mNetworkAgent = null; 4987 } 4988 mWifiConfigStore.updateStatus(mLastNetworkId, DetailedState.DISCONNECTED); 4989 4990 /* Clear network properties */ 4991 clearLinkProperties(); 4992 4993 /* Cend event to CM & network change broadcast */ 4994 sendNetworkStateChangeBroadcast(mLastBssid); 4995 4996 /* Cancel auto roam requests */ 4997 autoRoamSetBSSID(mLastNetworkId, "any"); 4998 4999 mLastBssid = null; 5000 registerDisconnected(); 5001 mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 5002 } 5003 5004 private void handleSupplicantConnectionLoss(boolean killSupplicant) { 5005 /* Socket connection can be lost when we do a graceful shutdown 5006 * or when the driver is hung. Ensure supplicant is stopped here. 5007 */ 5008 if (killSupplicant) { 5009 mWifiMonitor.killSupplicant(mP2pSupported); 5010 } 5011 mWifiNative.closeSupplicantConnection(); 5012 sendSupplicantConnectionChangedBroadcast(false); 5013 setWifiState(WIFI_STATE_DISABLED); 5014 } 5015 5016 void handlePreDhcpSetup() { 5017 mDhcpActive = true; 5018 if (!mBluetoothConnectionActive) { 5019 /* 5020 * There are problems setting the Wi-Fi driver's power 5021 * mode to active when bluetooth coexistence mode is 5022 * enabled or sense. 5023 * <p> 5024 * We set Wi-Fi to active mode when 5025 * obtaining an IP address because we've found 5026 * compatibility issues with some routers with low power 5027 * mode. 5028 * <p> 5029 * In order for this active power mode to properly be set, 5030 * we disable coexistence mode until we're done with 5031 * obtaining an IP address. One exception is if we 5032 * are currently connected to a headset, since disabling 5033 * coexistence would interrupt that connection. 5034 */ 5035 // Disable the coexistence mode 5036 mWifiNative.setBluetoothCoexistenceMode( 5037 mWifiNative.BLUETOOTH_COEXISTENCE_MODE_DISABLED); 5038 } 5039 5040 // Disable power save and suspend optimizations during DHCP 5041 // Note: The order here is important for now. Brcm driver changes 5042 // power settings when we control suspend mode optimizations. 5043 // TODO: Remove this comment when the driver is fixed. 5044 setSuspendOptimizationsNative(SUSPEND_DUE_TO_DHCP, false); 5045 mWifiNative.setPowerSave(false); 5046 5047 // Update link layer stats 5048 getWifiLinkLayerStats(false); 5049 5050 /* P2p discovery breaks dhcp, shut it down in order to get through this */ 5051 Message msg = new Message(); 5052 msg.what = WifiP2pServiceImpl.BLOCK_DISCOVERY; 5053 msg.arg1 = WifiP2pServiceImpl.ENABLED; 5054 msg.arg2 = DhcpStateMachine.CMD_PRE_DHCP_ACTION_COMPLETE; 5055 msg.obj = mDhcpStateMachine; 5056 mWifiP2pChannel.sendMessage(msg); 5057 } 5058 5059 5060 private boolean useLegacyDhcpClient() { 5061 return Settings.Global.getInt( 5062 mContext.getContentResolver(), 5063 Settings.Global.LEGACY_DHCP_CLIENT, 0) == 1; 5064 } 5065 5066 private void maybeInitDhcpStateMachine() { 5067 if (mDhcpStateMachine == null) { 5068 if (useLegacyDhcpClient()) { 5069 mDhcpStateMachine = DhcpStateMachine.makeDhcpStateMachine( 5070 mContext, WifiStateMachine.this, mInterfaceName); 5071 } else { 5072 mDhcpStateMachine = DhcpClient.makeDhcpStateMachine( 5073 mContext, WifiStateMachine.this, mInterfaceName); 5074 } 5075 } 5076 } 5077 5078 void startDhcp() { 5079 maybeInitDhcpStateMachine(); 5080 mDhcpStateMachine.registerForPreDhcpNotification(); 5081 mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_START_DHCP); 5082 } 5083 5084 void renewDhcp() { 5085 maybeInitDhcpStateMachine(); 5086 mDhcpStateMachine.registerForPreDhcpNotification(); 5087 mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_RENEW_DHCP); 5088 } 5089 5090 void stopDhcp() { 5091 if (mDhcpStateMachine != null) { 5092 /* In case we were in middle of DHCP operation restore back powermode */ 5093 handlePostDhcpSetup(); 5094 mDhcpStateMachine.sendMessage(DhcpStateMachine.CMD_STOP_DHCP); 5095 } 5096 } 5097 5098 void handlePostDhcpSetup() { 5099 /* Restore power save and suspend optimizations */ 5100 setSuspendOptimizationsNative(SUSPEND_DUE_TO_DHCP, true); 5101 mWifiNative.setPowerSave(true); 5102 5103 mWifiP2pChannel.sendMessage(WifiP2pServiceImpl.BLOCK_DISCOVERY, WifiP2pServiceImpl.DISABLED); 5104 5105 // Set the coexistence mode back to its default value 5106 mWifiNative.setBluetoothCoexistenceMode( 5107 mWifiNative.BLUETOOTH_COEXISTENCE_MODE_SENSE); 5108 5109 mDhcpActive = false; 5110 } 5111 5112 void connectScanningService() { 5113 5114 if (mWifiScanner == null) { 5115 mWifiScanner = (WifiScanner) mContext.getSystemService(Context.WIFI_SCANNING_SERVICE); 5116 } 5117 } 5118 5119 private void handleIPv4Success(DhcpResults dhcpResults, int reason) { 5120 5121 if (PDBG) { 5122 logd("handleIPv4Success <" + dhcpResults.toString() + ">"); 5123 logd("link address " + dhcpResults.ipAddress); 5124 } 5125 5126 Inet4Address addr; 5127 synchronized (mDhcpResultsLock) { 5128 mDhcpResults = dhcpResults; 5129 addr = (Inet4Address) dhcpResults.ipAddress.getAddress(); 5130 } 5131 5132 if (isRoaming()) { 5133 int previousAddress = mWifiInfo.getIpAddress(); 5134 int newAddress = NetworkUtils.inetAddressToInt(addr); 5135 if (previousAddress != newAddress) { 5136 logd("handleIPv4Success, roaming and address changed" + 5137 mWifiInfo + " got: " + addr); 5138 } 5139 } 5140 mWifiInfo.setInetAddress(addr); 5141 mWifiInfo.setMeteredHint(dhcpResults.hasMeteredHint()); 5142 updateLinkProperties(reason); 5143 } 5144 5145 private void handleSuccessfulIpConfiguration() { 5146 mLastSignalLevel = -1; // Force update of signal strength 5147 WifiConfiguration c = getCurrentWifiConfiguration(); 5148 if (c != null) { 5149 // Reset IP failure tracking 5150 c.numConnectionFailures = 0; 5151 5152 // Tell the framework whether the newly connected network is trusted or untrusted. 5153 updateCapabilities(c); 5154 } 5155 if (c != null) { 5156 ScanResult result = getCurrentScanResult(); 5157 if (result == null) { 5158 logd("WifiStateMachine: handleSuccessfulIpConfiguration and no scan results" + 5159 c.configKey()); 5160 } else { 5161 // Clear the per BSSID failure count 5162 result.numIpConfigFailures = 0; 5163 // Clear the WHOLE BSSID blacklist, which means supplicant is free to retry 5164 // any BSSID, even though it may already have a non zero ip failure count, 5165 // this will typically happen if the user walks away and come back to his arrea 5166 // TODO: implement blacklisting based on a timer, i.e. keep BSSID blacklisted 5167 // in supplicant for a couple of hours or a day 5168 mWifiConfigStore.clearBssidBlacklist(); 5169 } 5170 } 5171 } 5172 5173 private void handleIPv4Failure(int reason) { 5174 synchronized(mDhcpResultsLock) { 5175 if (mDhcpResults != null) { 5176 mDhcpResults.clear(); 5177 } 5178 } 5179 if (PDBG) { 5180 logd("handleIPv4Failure"); 5181 } 5182 updateLinkProperties(reason); 5183 } 5184 5185 private void handleIpConfigurationLost() { 5186 mWifiInfo.setInetAddress(null); 5187 mWifiInfo.setMeteredHint(false); 5188 5189 mWifiConfigStore.handleSSIDStateChange(mLastNetworkId, false, 5190 "DHCP FAILURE", mWifiInfo.getBSSID()); 5191 5192 /* DHCP times out after about 30 seconds, we do a 5193 * disconnect thru supplicant, we will let autojoin retry connecting to the network 5194 */ 5195 mWifiNative.disconnect(); 5196 } 5197 5198 // TODO: De-duplicated this and handleIpConfigurationLost(). 5199 private void handleIpReachabilityLost() { 5200 // No need to be told about any additional neighbors that might also 5201 // become unreachable--quiet them now while we start disconnecting. 5202 if (mIpReachabilityMonitor != null) { 5203 mIpReachabilityMonitor.clearLinkProperties(); 5204 } 5205 5206 mWifiInfo.setInetAddress(null); 5207 mWifiInfo.setMeteredHint(false); 5208 5209 // TODO: Determine whether to call some form of mWifiConfigStore.handleSSIDStateChange(). 5210 5211 // Disconnect via supplicant, and let autojoin retry connecting to the network. 5212 mWifiNative.disconnect(); 5213 } 5214 5215 private int convertFrequencyToChannelNumber(int frequency) { 5216 if (frequency >= 2412 && frequency <= 2484) { 5217 return (frequency -2412) / 5 + 1; 5218 } else if (frequency >= 5170 && frequency <=5825) { 5219 //DFS is included 5220 return (frequency -5170) / 5 + 34; 5221 } else { 5222 return 0; 5223 } 5224 } 5225 5226 private int chooseApChannel(int apBand) { 5227 int apChannel; 5228 int[] channel; 5229 5230 if (apBand == 0) { 5231 if (mWifiApConfigStore.allowed2GChannel == null || 5232 mWifiApConfigStore.allowed2GChannel.size() == 0) { 5233 //most safe channel to use 5234 if(DBG) { 5235 Log.d(TAG, "No specified 2G allowed channel list"); 5236 } 5237 apChannel = 6; 5238 } else { 5239 int index = mRandom.nextInt(mWifiApConfigStore.allowed2GChannel.size()); 5240 apChannel = mWifiApConfigStore.allowed2GChannel.get(index).intValue(); 5241 } 5242 } else { 5243 //5G without DFS 5244 channel = mWifiNative.getChannelsForBand(2); 5245 if (channel != null && channel.length > 0) { 5246 apChannel = channel[mRandom.nextInt(channel.length)]; 5247 apChannel = convertFrequencyToChannelNumber(apChannel); 5248 } else { 5249 Log.e(TAG, "SoftAp do not get available channel list"); 5250 apChannel = 0; 5251 } 5252 } 5253 5254 if(DBG) { 5255 Log.d(TAG, "SoftAp set on channel " + apChannel); 5256 } 5257 5258 return apChannel; 5259 } 5260 5261 /* SoftAP configuration */ 5262 private boolean enableSoftAp() { 5263 if (WifiNative.getInterfaces() != 0) { 5264 if (!mWifiNative.toggleInterface(0)) { 5265 if (DBG) Log.e(TAG, "toggleInterface failed"); 5266 return false; 5267 } 5268 } else { 5269 if (DBG) Log.d(TAG, "No interfaces to toggle"); 5270 } 5271 5272 try { 5273 mNwService.wifiFirmwareReload(mInterfaceName, "AP"); 5274 if (DBG) Log.d(TAG, "Firmware reloaded in AP mode"); 5275 } catch (Exception e) { 5276 Log.e(TAG, "Failed to reload AP firmware " + e); 5277 } 5278 5279 if (WifiNative.startHal() == false) { 5280 /* starting HAL is optional */ 5281 Log.e(TAG, "Failed to start HAL"); 5282 } 5283 return true; 5284 } 5285 5286 /* Current design is to not set the config on a running hostapd but instead 5287 * stop and start tethering when user changes config on a running access point 5288 * 5289 * TODO: Add control channel setup through hostapd that allows changing config 5290 * on a running daemon 5291 */ 5292 private void startSoftApWithConfig(final WifiConfiguration configuration) { 5293 // set channel 5294 final WifiConfiguration config = new WifiConfiguration(configuration); 5295 5296 if (DBG) { 5297 Log.d(TAG, "SoftAp config channel is: " + config.apChannel); 5298 } 5299 5300 //We need HAL support to set country code and get available channel list, if HAL is 5301 //not available, like razor, we regress to original implementaion (2GHz, channel 6) 5302 if (mWifiNative.isHalStarted()) { 5303 //set country code through HAL Here 5304 String countryCode = getCurrentCountryCode(); 5305 5306 if (countryCode != null) { 5307 if (!mWifiNative.setCountryCodeHal(countryCode.toUpperCase(Locale.ROOT))) { 5308 if (config.apBand != 0) { 5309 Log.e(TAG, "Fail to set country code. Can not setup Softap on 5GHz"); 5310 //countrycode is mandatory for 5GHz 5311 sendMessage(CMD_START_AP_FAILURE, WifiManager.SAP_START_FAILURE_GENERAL); 5312 return; 5313 } 5314 } 5315 } else { 5316 if (config.apBand != 0) { 5317 //countrycode is mandatory for 5GHz 5318 Log.e(TAG, "Can not setup softAp on 5GHz without country code!"); 5319 sendMessage(CMD_START_AP_FAILURE, WifiManager.SAP_START_FAILURE_GENERAL); 5320 return; 5321 } 5322 } 5323 5324 if (config.apChannel == 0) { 5325 config.apChannel = chooseApChannel(config.apBand); 5326 if (config.apChannel == 0) { 5327 if(mWifiNative.isGetChannelsForBandSupported()) { 5328 //fail to get available channel 5329 sendMessage(CMD_START_AP_FAILURE, WifiManager.SAP_START_FAILURE_NO_CHANNEL); 5330 return; 5331 } else { 5332 //for some old device, wifiHal may not be supportedget valid channels are not 5333 //supported 5334 config.apBand = 0; 5335 config.apChannel = 6; 5336 } 5337 } 5338 } 5339 } else { 5340 //for some old device, wifiHal may not be supported 5341 config.apBand = 0; 5342 config.apChannel = 6; 5343 } 5344 // Start hostapd on a separate thread 5345 new Thread(new Runnable() { 5346 public void run() { 5347 try { 5348 mNwService.startAccessPoint(config, mInterfaceName); 5349 } catch (Exception e) { 5350 loge("Exception in softap start " + e); 5351 try { 5352 mNwService.stopAccessPoint(mInterfaceName); 5353 mNwService.startAccessPoint(config, mInterfaceName); 5354 } catch (Exception e1) { 5355 loge("Exception in softap re-start " + e1); 5356 sendMessage(CMD_START_AP_FAILURE, WifiManager.SAP_START_FAILURE_GENERAL); 5357 return; 5358 } 5359 } 5360 if (DBG) log("Soft AP start successful"); 5361 sendMessage(CMD_START_AP_SUCCESS); 5362 } 5363 }).start(); 5364 } 5365 5366 private byte[] macAddressFromString(String macString) { 5367 String[] macBytes = macString.split(":"); 5368 if (macBytes.length != 6) { 5369 throw new IllegalArgumentException("MAC address should be 6 bytes long!"); 5370 } 5371 byte[] mac = new byte[6]; 5372 for (int i = 0; i < macBytes.length; i++) { 5373 Integer hexVal = Integer.parseInt(macBytes[i], 16); 5374 mac[i] = hexVal.byteValue(); 5375 } 5376 return mac; 5377 } 5378 5379 /* 5380 * Read a MAC address in /proc/arp/table, used by WifistateMachine 5381 * so as to record MAC address of default gateway. 5382 **/ 5383 private String macAddressFromRoute(String ipAddress) { 5384 String macAddress = null; 5385 BufferedReader reader = null; 5386 try { 5387 reader = new BufferedReader(new FileReader("/proc/net/arp")); 5388 5389 // Skip over the line bearing colum titles 5390 String line = reader.readLine(); 5391 5392 while ((line = reader.readLine()) != null) { 5393 String[] tokens = line.split("[ ]+"); 5394 if (tokens.length < 6) { 5395 continue; 5396 } 5397 5398 // ARP column format is 5399 // Address HWType HWAddress Flags Mask IFace 5400 String ip = tokens[0]; 5401 String mac = tokens[3]; 5402 5403 if (ipAddress.equals(ip)) { 5404 macAddress = mac; 5405 break; 5406 } 5407 } 5408 5409 if (macAddress == null) { 5410 loge("Did not find remoteAddress {" + ipAddress + "} in " + 5411 "/proc/net/arp"); 5412 } 5413 5414 } catch (FileNotFoundException e) { 5415 loge("Could not open /proc/net/arp to lookup mac address"); 5416 } catch (IOException e) { 5417 loge("Could not read /proc/net/arp to lookup mac address"); 5418 } finally { 5419 try { 5420 if (reader != null) { 5421 reader.close(); 5422 } 5423 } catch (IOException e) { 5424 // Do nothing 5425 } 5426 } 5427 return macAddress; 5428 5429 } 5430 5431 private class WifiNetworkFactory extends NetworkFactory { 5432 public WifiNetworkFactory(Looper l, Context c, String TAG, NetworkCapabilities f) { 5433 super(l, c, TAG, f); 5434 } 5435 5436 @Override 5437 protected void needNetworkFor(NetworkRequest networkRequest, int score) { 5438 ++mConnectionRequests; 5439 } 5440 5441 @Override 5442 protected void releaseNetworkFor(NetworkRequest networkRequest) { 5443 --mConnectionRequests; 5444 } 5445 5446 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 5447 pw.println("mConnectionRequests " + mConnectionRequests); 5448 } 5449 5450 } 5451 5452 private class UntrustedWifiNetworkFactory extends NetworkFactory { 5453 private int mUntrustedReqCount; 5454 5455 public UntrustedWifiNetworkFactory(Looper l, Context c, String tag, NetworkCapabilities f) { 5456 super(l, c, tag, f); 5457 } 5458 5459 @Override 5460 protected void needNetworkFor(NetworkRequest networkRequest, int score) { 5461 if (!networkRequest.networkCapabilities.hasCapability( 5462 NetworkCapabilities.NET_CAPABILITY_TRUSTED)) { 5463 if (++mUntrustedReqCount == 1) { 5464 mWifiAutoJoinController.setAllowUntrustedConnections(true); 5465 } 5466 } 5467 } 5468 5469 @Override 5470 protected void releaseNetworkFor(NetworkRequest networkRequest) { 5471 if (!networkRequest.networkCapabilities.hasCapability( 5472 NetworkCapabilities.NET_CAPABILITY_TRUSTED)) { 5473 if (--mUntrustedReqCount == 0) { 5474 mWifiAutoJoinController.setAllowUntrustedConnections(false); 5475 } 5476 } 5477 } 5478 5479 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 5480 pw.println("mUntrustedReqCount " + mUntrustedReqCount); 5481 } 5482 } 5483 5484 void maybeRegisterNetworkFactory() { 5485 if (mNetworkFactory == null) { 5486 checkAndSetConnectivityInstance(); 5487 if (mCm != null) { 5488 mNetworkFactory = new WifiNetworkFactory(getHandler().getLooper(), mContext, 5489 NETWORKTYPE, mNetworkCapabilitiesFilter); 5490 mNetworkFactory.setScoreFilter(60); 5491 mNetworkFactory.register(); 5492 5493 // We can't filter untrusted network in the capabilities filter because a trusted 5494 // network would still satisfy a request that accepts untrusted ones. 5495 mUntrustedNetworkFactory = new UntrustedWifiNetworkFactory(getHandler().getLooper(), 5496 mContext, NETWORKTYPE_UNTRUSTED, mNetworkCapabilitiesFilter); 5497 mUntrustedNetworkFactory.setScoreFilter(Integer.MAX_VALUE); 5498 mUntrustedNetworkFactory.register(); 5499 } 5500 } 5501 } 5502 5503 /******************************************************** 5504 * HSM states 5505 *******************************************************/ 5506 5507 class DefaultState extends State { 5508 @Override 5509 public boolean processMessage(Message message) { 5510 logStateAndMessage(message, getClass().getSimpleName()); 5511 5512 switch (message.what) { 5513 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: { 5514 AsyncChannel ac = (AsyncChannel) message.obj; 5515 if (ac == mWifiP2pChannel) { 5516 if (message.arg1 == AsyncChannel.STATUS_SUCCESSFUL) { 5517 mWifiP2pChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION); 5518 } else { 5519 loge("WifiP2pService connection failure, error=" + message.arg1); 5520 } 5521 } else { 5522 loge("got HALF_CONNECTED for unknown channel"); 5523 } 5524 break; 5525 } 5526 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: { 5527 AsyncChannel ac = (AsyncChannel) message.obj; 5528 if (ac == mWifiP2pChannel) { 5529 loge("WifiP2pService channel lost, message.arg1 =" + message.arg1); 5530 //TODO: Re-establish connection to state machine after a delay 5531 // mWifiP2pChannel.connect(mContext, getHandler(), 5532 // mWifiP2pManager.getMessenger()); 5533 } 5534 break; 5535 } 5536 case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE: 5537 mBluetoothConnectionActive = (message.arg1 != 5538 BluetoothAdapter.STATE_DISCONNECTED); 5539 break; 5540 /* Synchronous call returns */ 5541 case CMD_PING_SUPPLICANT: 5542 case CMD_ENABLE_NETWORK: 5543 case CMD_ADD_OR_UPDATE_NETWORK: 5544 case CMD_REMOVE_NETWORK: 5545 case CMD_SAVE_CONFIG: 5546 replyToMessage(message, message.what, FAILURE); 5547 break; 5548 case CMD_GET_CAPABILITY_FREQ: 5549 replyToMessage(message, message.what, null); 5550 break; 5551 case CMD_GET_CONFIGURED_NETWORKS: 5552 replyToMessage(message, message.what, (List<WifiConfiguration>) null); 5553 break; 5554 case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS: 5555 replyToMessage(message, message.what, (List<WifiConfiguration>) null); 5556 break; 5557 case CMD_ENABLE_RSSI_POLL: 5558 mEnableRssiPolling = (message.arg1 == 1); 5559 break; 5560 case CMD_SET_HIGH_PERF_MODE: 5561 if (message.arg1 == 1) { 5562 setSuspendOptimizations(SUSPEND_DUE_TO_HIGH_PERF, false); 5563 } else { 5564 setSuspendOptimizations(SUSPEND_DUE_TO_HIGH_PERF, true); 5565 } 5566 break; 5567 case CMD_BOOT_COMPLETED: 5568 maybeRegisterNetworkFactory(); 5569 break; 5570 case CMD_SCREEN_STATE_CHANGED: 5571 handleScreenStateChanged(message.arg1 != 0); 5572 break; 5573 /* Discard */ 5574 case CMD_START_SCAN: 5575 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5576 break; 5577 case CMD_START_SUPPLICANT: 5578 case CMD_STOP_SUPPLICANT: 5579 case CMD_STOP_SUPPLICANT_FAILED: 5580 case CMD_START_DRIVER: 5581 case CMD_STOP_DRIVER: 5582 case CMD_DELAYED_STOP_DRIVER: 5583 case CMD_DRIVER_START_TIMED_OUT: 5584 case CMD_START_AP: 5585 case CMD_START_AP_SUCCESS: 5586 case CMD_START_AP_FAILURE: 5587 case CMD_STOP_AP: 5588 case CMD_TETHER_STATE_CHANGE: 5589 case CMD_TETHER_NOTIFICATION_TIMED_OUT: 5590 case CMD_DISCONNECT: 5591 case CMD_RECONNECT: 5592 case CMD_REASSOCIATE: 5593 case CMD_RELOAD_TLS_AND_RECONNECT: 5594 case WifiMonitor.SUP_CONNECTION_EVENT: 5595 case WifiMonitor.SUP_DISCONNECTION_EVENT: 5596 case WifiMonitor.NETWORK_CONNECTION_EVENT: 5597 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 5598 case WifiMonitor.SCAN_RESULTS_EVENT: 5599 case WifiMonitor.SCAN_FAILED_EVENT: 5600 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 5601 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 5602 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 5603 case WifiMonitor.WPS_OVERLAP_EVENT: 5604 case CMD_BLACKLIST_NETWORK: 5605 case CMD_CLEAR_BLACKLIST: 5606 case CMD_SET_OPERATIONAL_MODE: 5607 case CMD_SET_FREQUENCY_BAND: 5608 case CMD_RSSI_POLL: 5609 case CMD_ENABLE_ALL_NETWORKS: 5610 case DhcpStateMachine.CMD_PRE_DHCP_ACTION: 5611 case DhcpStateMachine.CMD_POST_DHCP_ACTION: 5612 /* Handled by WifiApConfigStore */ 5613 case CMD_SET_AP_CONFIG: 5614 case CMD_SET_AP_CONFIG_COMPLETED: 5615 case CMD_REQUEST_AP_CONFIG: 5616 case CMD_RESPONSE_AP_CONFIG: 5617 case WifiWatchdogStateMachine.POOR_LINK_DETECTED: 5618 case WifiWatchdogStateMachine.GOOD_LINK_DETECTED: 5619 case CMD_NO_NETWORKS_PERIODIC_SCAN: 5620 case CMD_DISABLE_P2P_RSP: 5621 case WifiMonitor.SUP_REQUEST_IDENTITY: 5622 case CMD_TEST_NETWORK_DISCONNECT: 5623 case CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER: 5624 case WifiMonitor.SUP_REQUEST_SIM_AUTH: 5625 case CMD_TARGET_BSSID: 5626 case CMD_AUTO_CONNECT: 5627 case CMD_AUTO_ROAM: 5628 case CMD_AUTO_SAVE_NETWORK: 5629 case CMD_ASSOCIATED_BSSID: 5630 case CMD_UNWANTED_NETWORK: 5631 case CMD_DISCONNECTING_WATCHDOG_TIMER: 5632 case CMD_ROAM_WATCHDOG_TIMER: 5633 case CMD_DISABLE_EPHEMERAL_NETWORK: 5634 case CMD_RESTART_AUTOJOIN_OFFLOAD: 5635 case CMD_STARTED_PNO_DBG: 5636 case CMD_STARTED_GSCAN_DBG: 5637 case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION: 5638 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5639 break; 5640 case CMD_SET_COUNTRY_CODE: 5641 String country = (String) message.obj; 5642 final boolean persist = (message.arg2 == 1); 5643 final int sequence = message.arg1; 5644 if (sequence != mCountryCodeSequence.get()) { 5645 if (DBG) log("set country code ignored due to sequnce num"); 5646 break; 5647 } 5648 5649 if (persist) { 5650 country = country.toUpperCase(Locale.ROOT); 5651 if (DBG) log("set country code " + (country == null ? "(null)" : country)); 5652 Settings.Global.putString(mContext.getContentResolver(), 5653 Settings.Global.WIFI_COUNTRY_CODE, 5654 country == null ? "" : country); 5655 } 5656 5657 break; 5658 case DhcpStateMachine.CMD_ON_QUIT: 5659 mDhcpStateMachine = null; 5660 break; 5661 case CMD_SET_SUSPEND_OPT_ENABLED: 5662 if (message.arg1 == 1) { 5663 mSuspendWakeLock.release(); 5664 setSuspendOptimizations(SUSPEND_DUE_TO_SCREEN, true); 5665 } else { 5666 setSuspendOptimizations(SUSPEND_DUE_TO_SCREEN, false); 5667 } 5668 break; 5669 case WifiMonitor.DRIVER_HUNG_EVENT: 5670 setSupplicantRunning(false); 5671 setSupplicantRunning(true); 5672 break; 5673 case WifiManager.CONNECT_NETWORK: 5674 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 5675 WifiManager.BUSY); 5676 break; 5677 case WifiManager.FORGET_NETWORK: 5678 replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, 5679 WifiManager.BUSY); 5680 break; 5681 case WifiManager.SAVE_NETWORK: 5682 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 5683 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 5684 WifiManager.BUSY); 5685 break; 5686 case WifiManager.START_WPS: 5687 replyToMessage(message, WifiManager.WPS_FAILED, 5688 WifiManager.BUSY); 5689 break; 5690 case WifiManager.CANCEL_WPS: 5691 replyToMessage(message, WifiManager.CANCEL_WPS_FAILED, 5692 WifiManager.BUSY); 5693 break; 5694 case WifiManager.DISABLE_NETWORK: 5695 replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED, 5696 WifiManager.BUSY); 5697 break; 5698 case WifiManager.RSSI_PKTCNT_FETCH: 5699 replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_FAILED, 5700 WifiManager.BUSY); 5701 break; 5702 case CMD_GET_SUPPORTED_FEATURES: 5703 int featureSet = WifiNative.getSupportedFeatureSet(); 5704 replyToMessage(message, message.what, featureSet); 5705 break; 5706 case CMD_FIRMWARE_ALERT: 5707 if (mWifiLogger != null) { 5708 byte[] buffer = (byte[])message.obj; 5709 mWifiLogger.captureAlertData(message.arg1, buffer); 5710 } 5711 break; 5712 case CMD_GET_LINK_LAYER_STATS: 5713 // Not supported hence reply with error message 5714 replyToMessage(message, message.what, null); 5715 break; 5716 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 5717 NetworkInfo info = (NetworkInfo) message.obj; 5718 mP2pConnected.set(info.isConnected()); 5719 break; 5720 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 5721 mTemporarilyDisconnectWifi = (message.arg1 == 1); 5722 replyToMessage(message, WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE); 5723 break; 5724 /* Link configuration (IP address, DNS, ...) changes notified via netlink */ 5725 case CMD_UPDATE_LINKPROPERTIES: 5726 updateLinkProperties(CMD_UPDATE_LINKPROPERTIES); 5727 break; 5728 case CMD_GET_MATCHING_CONFIG: 5729 replyToMessage(message, message.what); 5730 break; 5731 case CMD_IP_CONFIGURATION_SUCCESSFUL: 5732 case CMD_IP_CONFIGURATION_LOST: 5733 case CMD_IP_REACHABILITY_LOST: 5734 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5735 break; 5736 case CMD_GET_CONNECTION_STATISTICS: 5737 replyToMessage(message, message.what, mWifiConnectionStatistics); 5738 break; 5739 case CMD_REMOVE_APP_CONFIGURATIONS: 5740 deferMessage(message); 5741 break; 5742 case CMD_REMOVE_USER_CONFIGURATIONS: 5743 deferMessage(message); 5744 break; 5745 case CMD_START_IP_PACKET_OFFLOAD: 5746 if (mNetworkAgent != null) mNetworkAgent.onPacketKeepaliveEvent( 5747 message.arg1, 5748 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK); 5749 break; 5750 case CMD_STOP_IP_PACKET_OFFLOAD: 5751 if (mNetworkAgent != null) mNetworkAgent.onPacketKeepaliveEvent( 5752 message.arg1, 5753 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK); 5754 break; 5755 case CMD_START_RSSI_MONITORING_OFFLOAD: 5756 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5757 break; 5758 case CMD_STOP_RSSI_MONITORING_OFFLOAD: 5759 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 5760 break; 5761 default: 5762 loge("Error! unhandled message" + message); 5763 break; 5764 } 5765 return HANDLED; 5766 } 5767 } 5768 5769 class InitialState extends State { 5770 @Override 5771 public void enter() { 5772 WifiNative.stopHal(); 5773 mWifiNative.unloadDriver(); 5774 if (mWifiP2pChannel == null) { 5775 mWifiP2pChannel = new AsyncChannel(); 5776 mWifiP2pChannel.connect(mContext, getHandler(), 5777 mWifiP2pServiceImpl.getP2pStateMachineMessenger()); 5778 } 5779 5780 if (mWifiApConfigChannel == null) { 5781 mWifiApConfigChannel = new AsyncChannel(); 5782 mWifiApConfigStore = WifiApConfigStore.makeWifiApConfigStore( 5783 mContext, getHandler()); 5784 mWifiApConfigStore.loadApConfiguration(); 5785 mWifiApConfigChannel.connectSync(mContext, getHandler(), 5786 mWifiApConfigStore.getMessenger()); 5787 } 5788 5789 if (mWifiConfigStore.enableHalBasedPno.get()) { 5790 // make sure developer Settings are in sync with the config option 5791 mHalBasedPnoEnableInDevSettings = true; 5792 } 5793 } 5794 @Override 5795 public boolean processMessage(Message message) { 5796 logStateAndMessage(message, getClass().getSimpleName()); 5797 switch (message.what) { 5798 case CMD_START_SUPPLICANT: 5799 if (mWifiNative.loadDriver()) { 5800 try { 5801 mNwService.wifiFirmwareReload(mInterfaceName, "STA"); 5802 } catch (Exception e) { 5803 loge("Failed to reload STA firmware " + e); 5804 // Continue 5805 } 5806 5807 try { 5808 // A runtime crash can leave the interface up and 5809 // IP addresses configured, and this affects 5810 // connectivity when supplicant starts up. 5811 // Ensure interface is down and we have no IP 5812 // addresses before a supplicant start. 5813 mNwService.setInterfaceDown(mInterfaceName); 5814 mNwService.clearInterfaceAddresses(mInterfaceName); 5815 5816 // Set privacy extensions 5817 mNwService.setInterfaceIpv6PrivacyExtensions(mInterfaceName, true); 5818 5819 // IPv6 is enabled only as long as access point is connected since: 5820 // - IPv6 addresses and routes stick around after disconnection 5821 // - kernel is unaware when connected and fails to start IPv6 negotiation 5822 // - kernel can start autoconfiguration when 802.1x is not complete 5823 mNwService.disableIpv6(mInterfaceName); 5824 } catch (RemoteException re) { 5825 loge("Unable to change interface settings: " + re); 5826 } catch (IllegalStateException ie) { 5827 loge("Unable to change interface settings: " + ie); 5828 } 5829 5830 /* Stop a running supplicant after a runtime restart 5831 * Avoids issues with drivers that do not handle interface down 5832 * on a running supplicant properly. 5833 */ 5834 mWifiMonitor.killSupplicant(mP2pSupported); 5835 5836 if (WifiNative.startHal() == false) { 5837 /* starting HAL is optional */ 5838 loge("Failed to start HAL"); 5839 } 5840 5841 if (mWifiNative.startSupplicant(mP2pSupported)) { 5842 setWifiState(WIFI_STATE_ENABLING); 5843 if (DBG) log("Supplicant start successful"); 5844 mWifiMonitor.startMonitoring(); 5845 transitionTo(mSupplicantStartingState); 5846 } else { 5847 loge("Failed to start supplicant!"); 5848 } 5849 } else { 5850 loge("Failed to load driver"); 5851 } 5852 break; 5853 case CMD_START_AP: 5854 if (mWifiNative.loadDriver() == false) { 5855 loge("Failed to load driver for softap"); 5856 } else { 5857 if (enableSoftAp() == true) { 5858 setWifiApState(WIFI_AP_STATE_ENABLING, 0); 5859 transitionTo(mSoftApStartingState); 5860 } else { 5861 setWifiApState(WIFI_AP_STATE_FAILED, 5862 WifiManager.SAP_START_FAILURE_GENERAL); 5863 transitionTo(mInitialState); 5864 } 5865 } 5866 break; 5867 default: 5868 return NOT_HANDLED; 5869 } 5870 return HANDLED; 5871 } 5872 } 5873 5874 class SupplicantStartingState extends State { 5875 private void initializeWpsDetails() { 5876 String detail; 5877 detail = SystemProperties.get("ro.product.name", ""); 5878 if (!mWifiNative.setDeviceName(detail)) { 5879 loge("Failed to set device name " + detail); 5880 } 5881 detail = SystemProperties.get("ro.product.manufacturer", ""); 5882 if (!mWifiNative.setManufacturer(detail)) { 5883 loge("Failed to set manufacturer " + detail); 5884 } 5885 detail = SystemProperties.get("ro.product.model", ""); 5886 if (!mWifiNative.setModelName(detail)) { 5887 loge("Failed to set model name " + detail); 5888 } 5889 detail = SystemProperties.get("ro.product.model", ""); 5890 if (!mWifiNative.setModelNumber(detail)) { 5891 loge("Failed to set model number " + detail); 5892 } 5893 detail = SystemProperties.get("ro.serialno", ""); 5894 if (!mWifiNative.setSerialNumber(detail)) { 5895 loge("Failed to set serial number " + detail); 5896 } 5897 if (!mWifiNative.setConfigMethods("physical_display virtual_push_button")) { 5898 loge("Failed to set WPS config methods"); 5899 } 5900 if (!mWifiNative.setDeviceType(mPrimaryDeviceType)) { 5901 loge("Failed to set primary device type " + mPrimaryDeviceType); 5902 } 5903 } 5904 5905 @Override 5906 public boolean processMessage(Message message) { 5907 logStateAndMessage(message, getClass().getSimpleName()); 5908 5909 switch(message.what) { 5910 case WifiMonitor.SUP_CONNECTION_EVENT: 5911 if (DBG) log("Supplicant connection established"); 5912 setWifiState(WIFI_STATE_ENABLED); 5913 mSupplicantRestartCount = 0; 5914 /* Reset the supplicant state to indicate the supplicant 5915 * state is not known at this time */ 5916 mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE); 5917 /* Initialize data structures */ 5918 mLastBssid = null; 5919 mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID; 5920 mLastSignalLevel = -1; 5921 5922 mWifiInfo.setMacAddress(mWifiNative.getMacAddress()); 5923 /* set frequency band of operation */ 5924 setFrequencyBand(); 5925 mWifiNative.enableSaveConfig(); 5926 mWifiConfigStore.loadAndEnableAllNetworks(); 5927 if (mWifiConfigStore.enableVerboseLogging.get() > 0) { 5928 enableVerboseLogging(mWifiConfigStore.enableVerboseLogging.get()); 5929 } 5930 initializeWpsDetails(); 5931 5932 sendSupplicantConnectionChangedBroadcast(true); 5933 transitionTo(mDriverStartedState); 5934 break; 5935 case WifiMonitor.SUP_DISCONNECTION_EVENT: 5936 if (++mSupplicantRestartCount <= SUPPLICANT_RESTART_TRIES) { 5937 loge("Failed to setup control channel, restart supplicant"); 5938 mWifiMonitor.killSupplicant(mP2pSupported); 5939 transitionTo(mInitialState); 5940 sendMessageDelayed(CMD_START_SUPPLICANT, SUPPLICANT_RESTART_INTERVAL_MSECS); 5941 } else { 5942 loge("Failed " + mSupplicantRestartCount + 5943 " times to start supplicant, unload driver"); 5944 mSupplicantRestartCount = 0; 5945 setWifiState(WIFI_STATE_UNKNOWN); 5946 transitionTo(mInitialState); 5947 } 5948 break; 5949 case CMD_START_SUPPLICANT: 5950 case CMD_STOP_SUPPLICANT: 5951 case CMD_START_AP: 5952 case CMD_STOP_AP: 5953 case CMD_START_DRIVER: 5954 case CMD_STOP_DRIVER: 5955 case CMD_SET_OPERATIONAL_MODE: 5956 case CMD_SET_COUNTRY_CODE: 5957 case CMD_SET_FREQUENCY_BAND: 5958 case CMD_START_PACKET_FILTERING: 5959 case CMD_STOP_PACKET_FILTERING: 5960 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 5961 deferMessage(message); 5962 break; 5963 default: 5964 return NOT_HANDLED; 5965 } 5966 return HANDLED; 5967 } 5968 } 5969 5970 class SupplicantStartedState extends State { 5971 @Override 5972 public void enter() { 5973 /* Wifi is available as long as we have a connection to supplicant */ 5974 mNetworkInfo.setIsAvailable(true); 5975 if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo); 5976 5977 int defaultInterval = mContext.getResources().getInteger( 5978 R.integer.config_wifi_supplicant_scan_interval); 5979 5980 mSupplicantScanIntervalMs = Settings.Global.getLong(mContext.getContentResolver(), 5981 Settings.Global.WIFI_SUPPLICANT_SCAN_INTERVAL_MS, 5982 defaultInterval); 5983 5984 mWifiNative.setScanInterval((int)mSupplicantScanIntervalMs / 1000); 5985 mWifiNative.setExternalSim(true); 5986 5987 /* turn on use of DFS channels */ 5988 WifiNative.setDfsFlag(true); 5989 5990 /* set country code */ 5991 initializeCountryCode(); 5992 5993 setRandomMacOui(); 5994 mWifiNative.enableAutoConnect(false); 5995 } 5996 5997 @Override 5998 public boolean processMessage(Message message) { 5999 logStateAndMessage(message, getClass().getSimpleName()); 6000 6001 switch(message.what) { 6002 case CMD_STOP_SUPPLICANT: /* Supplicant stopped by user */ 6003 if (mP2pSupported) { 6004 transitionTo(mWaitForP2pDisableState); 6005 } else { 6006 transitionTo(mSupplicantStoppingState); 6007 } 6008 break; 6009 case WifiMonitor.SUP_DISCONNECTION_EVENT: /* Supplicant connection lost */ 6010 loge("Connection lost, restart supplicant"); 6011 handleSupplicantConnectionLoss(true); 6012 handleNetworkDisconnect(); 6013 mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE); 6014 if (mP2pSupported) { 6015 transitionTo(mWaitForP2pDisableState); 6016 } else { 6017 transitionTo(mInitialState); 6018 } 6019 sendMessageDelayed(CMD_START_SUPPLICANT, SUPPLICANT_RESTART_INTERVAL_MSECS); 6020 break; 6021 case WifiMonitor.SCAN_RESULTS_EVENT: 6022 case WifiMonitor.SCAN_FAILED_EVENT: 6023 maybeRegisterNetworkFactory(); // Make sure our NetworkFactory is registered 6024 closeRadioScanStats(); 6025 noteScanEnd(); 6026 setScanResults(); 6027 if (mIsFullScanOngoing || mSendScanResultsBroadcast) { 6028 /* Just updated results from full scan, let apps know about this */ 6029 boolean scanSucceeded = message.what == WifiMonitor.SCAN_RESULTS_EVENT; 6030 sendScanResultsAvailableBroadcast(scanSucceeded); 6031 } 6032 mSendScanResultsBroadcast = false; 6033 mIsScanOngoing = false; 6034 mIsFullScanOngoing = false; 6035 if (mBufferedScanMsg.size() > 0) 6036 sendMessage(mBufferedScanMsg.remove()); 6037 break; 6038 case CMD_PING_SUPPLICANT: 6039 boolean ok = mWifiNative.ping(); 6040 replyToMessage(message, message.what, ok ? SUCCESS : FAILURE); 6041 break; 6042 case CMD_GET_CAPABILITY_FREQ: 6043 String freqs = mWifiNative.getFreqCapability(); 6044 replyToMessage(message, message.what, freqs); 6045 break; 6046 case CMD_START_AP: 6047 /* Cannot start soft AP while in client mode */ 6048 loge("Failed to start soft AP with a running supplicant"); 6049 setWifiApState(WIFI_AP_STATE_FAILED, WifiManager.SAP_START_FAILURE_GENERAL); 6050 break; 6051 case CMD_SET_OPERATIONAL_MODE: 6052 mOperationalMode = message.arg1; 6053 mWifiConfigStore. 6054 setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID); 6055 break; 6056 case CMD_TARGET_BSSID: 6057 // Trying to associate to this BSSID 6058 if (message.obj != null) { 6059 mTargetRoamBSSID = (String) message.obj; 6060 } 6061 break; 6062 case CMD_GET_LINK_LAYER_STATS: 6063 WifiLinkLayerStats stats = getWifiLinkLayerStats(DBG); 6064 if (stats == null) { 6065 // When firmware doesnt support link layer stats, return an empty object 6066 stats = new WifiLinkLayerStats(); 6067 } 6068 replyToMessage(message, message.what, stats); 6069 break; 6070 case CMD_SET_COUNTRY_CODE: 6071 String country = (String) message.obj; 6072 final boolean persist = (message.arg2 == 1); 6073 final int sequence = message.arg1; 6074 if (sequence != mCountryCodeSequence.get()) { 6075 if (DBG) log("set country code ignored due to sequnce num"); 6076 break; 6077 } 6078 6079 country = country.toUpperCase(Locale.ROOT); 6080 6081 if (DBG) log("set country code " + (country == null ? "(null)" : country)); 6082 6083 if (!TextUtils.equals(mDriverSetCountryCode, country)) { 6084 if (mWifiNative.setCountryCode(country)) { 6085 mDriverSetCountryCode = country; 6086 } else { 6087 loge("Failed to set country code " + country); 6088 } 6089 } 6090 6091 if (persist) { 6092 Settings.Global.putString(mContext.getContentResolver(), 6093 Settings.Global.WIFI_COUNTRY_CODE, 6094 country == null ? "" : country); 6095 } 6096 6097 mWifiP2pChannel.sendMessage(WifiP2pServiceImpl.SET_COUNTRY_CODE, country); 6098 break; 6099 default: 6100 return NOT_HANDLED; 6101 } 6102 return HANDLED; 6103 } 6104 6105 @Override 6106 public void exit() { 6107 mNetworkInfo.setIsAvailable(false); 6108 if (mNetworkAgent != null) mNetworkAgent.sendNetworkInfo(mNetworkInfo); 6109 } 6110 } 6111 6112 class SupplicantStoppingState extends State { 6113 @Override 6114 public void enter() { 6115 /* Send any reset commands to supplicant before shutting it down */ 6116 handleNetworkDisconnect(); 6117 if (mDhcpStateMachine != null) { 6118 mDhcpStateMachine.doQuit(); 6119 } 6120 6121 String suppState = System.getProperty("init.svc.wpa_supplicant"); 6122 if (suppState == null) suppState = "unknown"; 6123 String p2pSuppState = System.getProperty("init.svc.p2p_supplicant"); 6124 if (p2pSuppState == null) p2pSuppState = "unknown"; 6125 6126 logd("SupplicantStoppingState: stopSupplicant " 6127 + " init.svc.wpa_supplicant=" + suppState 6128 + " init.svc.p2p_supplicant=" + p2pSuppState); 6129 mWifiMonitor.stopSupplicant(); 6130 6131 /* Send ourselves a delayed message to indicate failure after a wait time */ 6132 sendMessageDelayed(obtainMessage(CMD_STOP_SUPPLICANT_FAILED, 6133 ++mSupplicantStopFailureToken, 0), SUPPLICANT_RESTART_INTERVAL_MSECS); 6134 setWifiState(WIFI_STATE_DISABLING); 6135 mSupplicantStateTracker.sendMessage(CMD_RESET_SUPPLICANT_STATE); 6136 } 6137 @Override 6138 public boolean processMessage(Message message) { 6139 logStateAndMessage(message, getClass().getSimpleName()); 6140 6141 switch(message.what) { 6142 case WifiMonitor.SUP_CONNECTION_EVENT: 6143 loge("Supplicant connection received while stopping"); 6144 break; 6145 case WifiMonitor.SUP_DISCONNECTION_EVENT: 6146 if (DBG) log("Supplicant connection lost"); 6147 handleSupplicantConnectionLoss(false); 6148 transitionTo(mInitialState); 6149 break; 6150 case CMD_STOP_SUPPLICANT_FAILED: 6151 if (message.arg1 == mSupplicantStopFailureToken) { 6152 loge("Timed out on a supplicant stop, kill and proceed"); 6153 handleSupplicantConnectionLoss(true); 6154 transitionTo(mInitialState); 6155 } 6156 break; 6157 case CMD_START_SUPPLICANT: 6158 case CMD_STOP_SUPPLICANT: 6159 case CMD_START_AP: 6160 case CMD_STOP_AP: 6161 case CMD_START_DRIVER: 6162 case CMD_STOP_DRIVER: 6163 case CMD_SET_OPERATIONAL_MODE: 6164 case CMD_SET_COUNTRY_CODE: 6165 case CMD_SET_FREQUENCY_BAND: 6166 case CMD_START_PACKET_FILTERING: 6167 case CMD_STOP_PACKET_FILTERING: 6168 deferMessage(message); 6169 break; 6170 default: 6171 return NOT_HANDLED; 6172 } 6173 return HANDLED; 6174 } 6175 } 6176 6177 class DriverStartingState extends State { 6178 private int mTries; 6179 @Override 6180 public void enter() { 6181 mTries = 1; 6182 /* Send ourselves a delayed message to start driver a second time */ 6183 sendMessageDelayed(obtainMessage(CMD_DRIVER_START_TIMED_OUT, 6184 ++mDriverStartToken, 0), DRIVER_START_TIME_OUT_MSECS); 6185 } 6186 @Override 6187 public boolean processMessage(Message message) { 6188 logStateAndMessage(message, getClass().getSimpleName()); 6189 6190 switch(message.what) { 6191 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6192 SupplicantState state = handleSupplicantStateChange(message); 6193 /* If suplicant is exiting out of INTERFACE_DISABLED state into 6194 * a state that indicates driver has started, it is ready to 6195 * receive driver commands 6196 */ 6197 if (SupplicantState.isDriverActive(state)) { 6198 transitionTo(mDriverStartedState); 6199 } 6200 break; 6201 case CMD_DRIVER_START_TIMED_OUT: 6202 if (message.arg1 == mDriverStartToken) { 6203 if (mTries >= 2) { 6204 loge("Failed to start driver after " + mTries); 6205 transitionTo(mDriverStoppedState); 6206 } else { 6207 loge("Driver start failed, retrying"); 6208 mWakeLock.acquire(); 6209 mWifiNative.startDriver(); 6210 mWakeLock.release(); 6211 6212 ++mTries; 6213 /* Send ourselves a delayed message to start driver again */ 6214 sendMessageDelayed(obtainMessage(CMD_DRIVER_START_TIMED_OUT, 6215 ++mDriverStartToken, 0), DRIVER_START_TIME_OUT_MSECS); 6216 } 6217 } 6218 break; 6219 /* Queue driver commands & connection events */ 6220 case CMD_START_DRIVER: 6221 case CMD_STOP_DRIVER: 6222 case WifiMonitor.NETWORK_CONNECTION_EVENT: 6223 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6224 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 6225 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 6226 case WifiMonitor.WPS_OVERLAP_EVENT: 6227 case CMD_SET_COUNTRY_CODE: 6228 case CMD_SET_FREQUENCY_BAND: 6229 case CMD_START_PACKET_FILTERING: 6230 case CMD_STOP_PACKET_FILTERING: 6231 case CMD_START_SCAN: 6232 case CMD_DISCONNECT: 6233 case CMD_REASSOCIATE: 6234 case CMD_RECONNECT: 6235 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 6236 deferMessage(message); 6237 break; 6238 case WifiMonitor.SCAN_RESULTS_EVENT: 6239 case WifiMonitor.SCAN_FAILED_EVENT: 6240 // Loose scan results obtained in Driver Starting state, they can only confuse 6241 // the state machine 6242 break; 6243 default: 6244 return NOT_HANDLED; 6245 } 6246 return HANDLED; 6247 } 6248 } 6249 6250 class DriverStartedState extends State { 6251 @Override 6252 public void enter() { 6253 6254 if (PDBG) { 6255 logd("DriverStartedState enter"); 6256 } 6257 6258 mWifiLogger.startLogging(mVerboseLoggingLevel > 0); 6259 mIsRunning = true; 6260 mInDelayedStop = false; 6261 mDelayedStopCounter++; 6262 updateBatteryWorkSource(null); 6263 /** 6264 * Enable bluetooth coexistence scan mode when bluetooth connection is active. 6265 * When this mode is on, some of the low-level scan parameters used by the 6266 * driver are changed to reduce interference with bluetooth 6267 */ 6268 mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive); 6269 /* initialize network state */ 6270 setNetworkDetailedState(DetailedState.DISCONNECTED); 6271 6272 /* Remove any filtering on Multicast v6 at start */ 6273 mWifiNative.stopFilteringMulticastV6Packets(); 6274 6275 /* Reset Multicast v4 filtering state */ 6276 if (mFilteringMulticastV4Packets.get()) { 6277 mWifiNative.startFilteringMulticastV4Packets(); 6278 } else { 6279 mWifiNative.stopFilteringMulticastV4Packets(); 6280 } 6281 6282 mDhcpActive = false; 6283 6284 if (mOperationalMode != CONNECT_MODE) { 6285 mWifiNative.disconnect(); 6286 mWifiConfigStore.disableAllNetworks(); 6287 if (mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 6288 setWifiState(WIFI_STATE_DISABLED); 6289 } 6290 transitionTo(mScanModeState); 6291 } else { 6292 6293 // Status pulls in the current supplicant state and network connection state 6294 // events over the monitor connection. This helps framework sync up with 6295 // current supplicant state 6296 // TODO: actually check th supplicant status string and make sure the supplicant 6297 // is in disconnecte4d state. 6298 mWifiNative.status(); 6299 // Transitioning to Disconnected state will trigger a scan and subsequently AutoJoin 6300 transitionTo(mDisconnectedState); 6301 transitionTo(mDisconnectedState); 6302 } 6303 6304 // We may have missed screen update at boot 6305 if (mScreenBroadcastReceived.get() == false) { 6306 PowerManager powerManager = (PowerManager)mContext.getSystemService( 6307 Context.POWER_SERVICE); 6308 handleScreenStateChanged(powerManager.isScreenOn()); 6309 } else { 6310 // Set the right suspend mode settings 6311 mWifiNative.setSuspendOptimizations(mSuspendOptNeedsDisabled == 0 6312 && mUserWantsSuspendOpt.get()); 6313 } 6314 mWifiNative.setPowerSave(true); 6315 6316 if (mP2pSupported) { 6317 if (mOperationalMode == CONNECT_MODE) { 6318 mWifiP2pChannel.sendMessage(WifiStateMachine.CMD_ENABLE_P2P); 6319 } else { 6320 // P2P statemachine starts in disabled state, and is not enabled until 6321 // CMD_ENABLE_P2P is sent from here; so, nothing needs to be done to 6322 // keep it disabled. 6323 } 6324 } 6325 6326 final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE); 6327 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 6328 intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_ENABLED); 6329 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 6330 6331 mHalFeatureSet = WifiNative.getSupportedFeatureSet(); 6332 if ((mHalFeatureSet & WifiManager.WIFI_FEATURE_HAL_EPNO) 6333 == WifiManager.WIFI_FEATURE_HAL_EPNO) { 6334 mHalBasedPnoDriverSupported = true; 6335 } 6336 6337 // Enable link layer stats gathering 6338 mWifiNative.setWifiLinkLayerStats("wlan0", 1); 6339 6340 if (PDBG) { 6341 logd("Driverstarted State enter done, epno=" + mHalBasedPnoDriverSupported 6342 + " feature=" + mHalFeatureSet); 6343 } 6344 } 6345 6346 @Override 6347 public boolean processMessage(Message message) { 6348 logStateAndMessage(message, getClass().getSimpleName()); 6349 6350 switch(message.what) { 6351 case CMD_START_SCAN: 6352 handleScanRequest(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message); 6353 break; 6354 case CMD_SET_FREQUENCY_BAND: 6355 int band = message.arg1; 6356 if (DBG) log("set frequency band " + band); 6357 if (mWifiNative.setBand(band)) { 6358 6359 if (PDBG) logd("did set frequency band " + band); 6360 6361 mFrequencyBand.set(band); 6362 // Flush old data - like scan results 6363 mWifiNative.bssFlush(); 6364 // Fetch the latest scan results when frequency band is set 6365// startScanNative(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, null); 6366 6367 if (PDBG) logd("done set frequency band " + band); 6368 6369 } else { 6370 loge("Failed to set frequency band " + band); 6371 } 6372 break; 6373 case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE: 6374 mBluetoothConnectionActive = (message.arg1 != 6375 BluetoothAdapter.STATE_DISCONNECTED); 6376 mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive); 6377 break; 6378 case CMD_STOP_DRIVER: 6379 int mode = message.arg1; 6380 6381 /* Already doing a delayed stop */ 6382 if (mInDelayedStop) { 6383 if (DBG) log("Already in delayed stop"); 6384 break; 6385 } 6386 /* disconnect right now, but leave the driver running for a bit */ 6387 mWifiConfigStore.disableAllNetworks(); 6388 6389 mInDelayedStop = true; 6390 mDelayedStopCounter++; 6391 if (DBG) log("Delayed stop message " + mDelayedStopCounter); 6392 6393 /* send regular delayed shut down */ 6394 Intent driverStopIntent = new Intent(ACTION_DELAYED_DRIVER_STOP, null); 6395 driverStopIntent.setPackage(this.getClass().getPackage().getName()); 6396 driverStopIntent.putExtra(DELAYED_STOP_COUNTER, mDelayedStopCounter); 6397 mDriverStopIntent = PendingIntent.getBroadcast(mContext, 6398 DRIVER_STOP_REQUEST, driverStopIntent, 6399 PendingIntent.FLAG_UPDATE_CURRENT); 6400 6401 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() 6402 + mDriverStopDelayMs, mDriverStopIntent); 6403 break; 6404 case CMD_START_DRIVER: 6405 if (mInDelayedStop) { 6406 mInDelayedStop = false; 6407 mDelayedStopCounter++; 6408 mAlarmManager.cancel(mDriverStopIntent); 6409 if (DBG) log("Delayed stop ignored due to start"); 6410 if (mOperationalMode == CONNECT_MODE) { 6411 mWifiConfigStore.enableAllNetworks(); 6412 } 6413 } 6414 break; 6415 case CMD_DELAYED_STOP_DRIVER: 6416 if (DBG) log("delayed stop " + message.arg1 + " " + mDelayedStopCounter); 6417 if (message.arg1 != mDelayedStopCounter) break; 6418 if (getCurrentState() != mDisconnectedState) { 6419 mWifiNative.disconnect(); 6420 handleNetworkDisconnect(); 6421 } 6422 mWakeLock.acquire(); 6423 mWifiNative.stopDriver(); 6424 mWakeLock.release(); 6425 if (mP2pSupported) { 6426 transitionTo(mWaitForP2pDisableState); 6427 } else { 6428 transitionTo(mDriverStoppingState); 6429 } 6430 break; 6431 case CMD_START_PACKET_FILTERING: 6432 if (message.arg1 == MULTICAST_V6) { 6433 mWifiNative.startFilteringMulticastV6Packets(); 6434 } else if (message.arg1 == MULTICAST_V4) { 6435 mWifiNative.startFilteringMulticastV4Packets(); 6436 } else { 6437 loge("Illegal arugments to CMD_START_PACKET_FILTERING"); 6438 } 6439 break; 6440 case CMD_STOP_PACKET_FILTERING: 6441 if (message.arg1 == MULTICAST_V6) { 6442 mWifiNative.stopFilteringMulticastV6Packets(); 6443 } else if (message.arg1 == MULTICAST_V4) { 6444 mWifiNative.stopFilteringMulticastV4Packets(); 6445 } else { 6446 loge("Illegal arugments to CMD_STOP_PACKET_FILTERING"); 6447 } 6448 break; 6449 case CMD_SET_SUSPEND_OPT_ENABLED: 6450 if (message.arg1 == 1) { 6451 setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, true); 6452 mSuspendWakeLock.release(); 6453 } else { 6454 setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, false); 6455 } 6456 break; 6457 case CMD_SET_HIGH_PERF_MODE: 6458 if (message.arg1 == 1) { 6459 setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, false); 6460 } else { 6461 setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, true); 6462 } 6463 break; 6464 case CMD_ENABLE_TDLS: 6465 if (message.obj != null) { 6466 String remoteAddress = (String) message.obj; 6467 boolean enable = (message.arg1 == 1); 6468 mWifiNative.startTdls(remoteAddress, enable); 6469 } 6470 break; 6471 case WifiMonitor.ANQP_DONE_EVENT: 6472 mWifiConfigStore.notifyANQPDone((Long) message.obj, message.arg1 != 0); 6473 break; 6474 case CMD_STOP_IP_PACKET_OFFLOAD: { 6475 int slot = message.arg1; 6476 int ret = stopWifiIPPacketOffload(slot); 6477 if (mNetworkAgent != null) { 6478 mNetworkAgent.onPacketKeepaliveEvent(slot, ret); 6479 } 6480 break; 6481 } 6482 default: 6483 return NOT_HANDLED; 6484 } 6485 return HANDLED; 6486 } 6487 @Override 6488 public void exit() { 6489 6490 mWifiLogger.stopLogging(); 6491 6492 mIsRunning = false; 6493 updateBatteryWorkSource(null); 6494 mScanResults = new ArrayList<>(); 6495 6496 final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE); 6497 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 6498 intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED); 6499 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 6500 noteScanEnd(); // wrap up any pending request. 6501 mBufferedScanMsg.clear(); 6502 } 6503 } 6504 6505 class WaitForP2pDisableState extends State { 6506 private State mTransitionToState; 6507 @Override 6508 public void enter() { 6509 switch (getCurrentMessage().what) { 6510 case WifiMonitor.SUP_DISCONNECTION_EVENT: 6511 mTransitionToState = mInitialState; 6512 break; 6513 case CMD_DELAYED_STOP_DRIVER: 6514 mTransitionToState = mDriverStoppingState; 6515 break; 6516 case CMD_STOP_SUPPLICANT: 6517 mTransitionToState = mSupplicantStoppingState; 6518 break; 6519 default: 6520 mTransitionToState = mDriverStoppingState; 6521 break; 6522 } 6523 mWifiP2pChannel.sendMessage(WifiStateMachine.CMD_DISABLE_P2P_REQ); 6524 } 6525 @Override 6526 public boolean processMessage(Message message) { 6527 logStateAndMessage(message, getClass().getSimpleName()); 6528 6529 switch(message.what) { 6530 case WifiStateMachine.CMD_DISABLE_P2P_RSP: 6531 transitionTo(mTransitionToState); 6532 break; 6533 /* Defer wifi start/shut and driver commands */ 6534 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6535 case CMD_START_SUPPLICANT: 6536 case CMD_STOP_SUPPLICANT: 6537 case CMD_START_AP: 6538 case CMD_STOP_AP: 6539 case CMD_START_DRIVER: 6540 case CMD_STOP_DRIVER: 6541 case CMD_SET_OPERATIONAL_MODE: 6542 case CMD_SET_COUNTRY_CODE: 6543 case CMD_SET_FREQUENCY_BAND: 6544 case CMD_START_PACKET_FILTERING: 6545 case CMD_STOP_PACKET_FILTERING: 6546 case CMD_START_SCAN: 6547 case CMD_DISCONNECT: 6548 case CMD_REASSOCIATE: 6549 case CMD_RECONNECT: 6550 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 6551 deferMessage(message); 6552 break; 6553 default: 6554 return NOT_HANDLED; 6555 } 6556 return HANDLED; 6557 } 6558 } 6559 6560 class DriverStoppingState extends State { 6561 @Override 6562 public boolean processMessage(Message message) { 6563 logStateAndMessage(message, getClass().getSimpleName()); 6564 6565 switch(message.what) { 6566 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6567 SupplicantState state = handleSupplicantStateChange(message); 6568 if (state == SupplicantState.INTERFACE_DISABLED) { 6569 transitionTo(mDriverStoppedState); 6570 } 6571 break; 6572 /* Queue driver commands */ 6573 case CMD_START_DRIVER: 6574 case CMD_STOP_DRIVER: 6575 case CMD_SET_COUNTRY_CODE: 6576 case CMD_SET_FREQUENCY_BAND: 6577 case CMD_START_PACKET_FILTERING: 6578 case CMD_STOP_PACKET_FILTERING: 6579 case CMD_START_SCAN: 6580 case CMD_DISCONNECT: 6581 case CMD_REASSOCIATE: 6582 case CMD_RECONNECT: 6583 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 6584 deferMessage(message); 6585 break; 6586 default: 6587 return NOT_HANDLED; 6588 } 6589 return HANDLED; 6590 } 6591 } 6592 6593 class DriverStoppedState extends State { 6594 @Override 6595 public boolean processMessage(Message message) { 6596 logStateAndMessage(message, getClass().getSimpleName()); 6597 switch (message.what) { 6598 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6599 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 6600 SupplicantState state = stateChangeResult.state; 6601 // A WEXT bug means that we can be back to driver started state 6602 // unexpectedly 6603 if (SupplicantState.isDriverActive(state)) { 6604 transitionTo(mDriverStartedState); 6605 } 6606 break; 6607 case CMD_START_DRIVER: 6608 mWakeLock.acquire(); 6609 mWifiNative.startDriver(); 6610 mWakeLock.release(); 6611 transitionTo(mDriverStartingState); 6612 break; 6613 default: 6614 return NOT_HANDLED; 6615 } 6616 return HANDLED; 6617 } 6618 } 6619 6620 class ScanModeState extends State { 6621 private int mLastOperationMode; 6622 @Override 6623 public void enter() { 6624 mLastOperationMode = mOperationalMode; 6625 } 6626 @Override 6627 public boolean processMessage(Message message) { 6628 logStateAndMessage(message, getClass().getSimpleName()); 6629 6630 switch(message.what) { 6631 case CMD_SET_OPERATIONAL_MODE: 6632 if (message.arg1 == CONNECT_MODE) { 6633 6634 if (mLastOperationMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 6635 setWifiState(WIFI_STATE_ENABLED); 6636 // Load and re-enable networks when going back to enabled state 6637 // This is essential for networks to show up after restore 6638 mWifiConfigStore.loadAndEnableAllNetworks(); 6639 mWifiP2pChannel.sendMessage(CMD_ENABLE_P2P); 6640 } else { 6641 mWifiConfigStore.enableAllNetworks(); 6642 } 6643 6644 // Try autojoining with recent network already present in the cache 6645 // If none are found then trigger a scan which will trigger autojoin 6646 // upon reception of scan results event 6647 if (!mWifiAutoJoinController.attemptAutoJoin()) { 6648 startScan(ENABLE_WIFI, 0, null, null); 6649 } 6650 6651 // Loose last selection choice since user toggled WiFi 6652 mWifiConfigStore. 6653 setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID); 6654 6655 mOperationalMode = CONNECT_MODE; 6656 transitionTo(mDisconnectedState); 6657 } else { 6658 // Nothing to do 6659 return HANDLED; 6660 } 6661 break; 6662 // Handle scan. All the connection related commands are 6663 // handled only in ConnectModeState 6664 case CMD_START_SCAN: 6665 handleScanRequest(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message); 6666 break; 6667 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6668 SupplicantState state = handleSupplicantStateChange(message); 6669 if(DBG) log("SupplicantState= " + state); 6670 break; 6671 default: 6672 return NOT_HANDLED; 6673 } 6674 return HANDLED; 6675 } 6676 } 6677 6678 6679 String smToString(Message message) { 6680 return smToString(message.what); 6681 } 6682 6683 String smToString(int what) { 6684 String s = "unknown"; 6685 switch (what) { 6686 case WifiMonitor.DRIVER_HUNG_EVENT: 6687 s = "DRIVER_HUNG_EVENT"; 6688 break; 6689 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: 6690 s = "AsyncChannel.CMD_CHANNEL_HALF_CONNECTED"; 6691 break; 6692 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: 6693 s = "AsyncChannel.CMD_CHANNEL_DISCONNECTED"; 6694 break; 6695 case CMD_SET_FREQUENCY_BAND: 6696 s = "CMD_SET_FREQUENCY_BAND"; 6697 break; 6698 case CMD_DELAYED_NETWORK_DISCONNECT: 6699 s = "CMD_DELAYED_NETWORK_DISCONNECT"; 6700 break; 6701 case CMD_TEST_NETWORK_DISCONNECT: 6702 s = "CMD_TEST_NETWORK_DISCONNECT"; 6703 break; 6704 case CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER: 6705 s = "CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER"; 6706 break; 6707 case CMD_DISABLE_EPHEMERAL_NETWORK: 6708 s = "CMD_DISABLE_EPHEMERAL_NETWORK"; 6709 break; 6710 case CMD_START_DRIVER: 6711 s = "CMD_START_DRIVER"; 6712 break; 6713 case CMD_STOP_DRIVER: 6714 s = "CMD_STOP_DRIVER"; 6715 break; 6716 case CMD_STOP_SUPPLICANT: 6717 s = "CMD_STOP_SUPPLICANT"; 6718 break; 6719 case CMD_STOP_SUPPLICANT_FAILED: 6720 s = "CMD_STOP_SUPPLICANT_FAILED"; 6721 break; 6722 case CMD_START_SUPPLICANT: 6723 s = "CMD_START_SUPPLICANT"; 6724 break; 6725 case CMD_REQUEST_AP_CONFIG: 6726 s = "CMD_REQUEST_AP_CONFIG"; 6727 break; 6728 case CMD_RESPONSE_AP_CONFIG: 6729 s = "CMD_RESPONSE_AP_CONFIG"; 6730 break; 6731 case CMD_TETHER_STATE_CHANGE: 6732 s = "CMD_TETHER_STATE_CHANGE"; 6733 break; 6734 case CMD_TETHER_NOTIFICATION_TIMED_OUT: 6735 s = "CMD_TETHER_NOTIFICATION_TIMED_OUT"; 6736 break; 6737 case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE: 6738 s = "CMD_BLUETOOTH_ADAPTER_STATE_CHANGE"; 6739 break; 6740 case CMD_ADD_OR_UPDATE_NETWORK: 6741 s = "CMD_ADD_OR_UPDATE_NETWORK"; 6742 break; 6743 case CMD_REMOVE_NETWORK: 6744 s = "CMD_REMOVE_NETWORK"; 6745 break; 6746 case CMD_ENABLE_NETWORK: 6747 s = "CMD_ENABLE_NETWORK"; 6748 break; 6749 case CMD_ENABLE_ALL_NETWORKS: 6750 s = "CMD_ENABLE_ALL_NETWORKS"; 6751 break; 6752 case CMD_AUTO_CONNECT: 6753 s = "CMD_AUTO_CONNECT"; 6754 break; 6755 case CMD_AUTO_ROAM: 6756 s = "CMD_AUTO_ROAM"; 6757 break; 6758 case CMD_AUTO_SAVE_NETWORK: 6759 s = "CMD_AUTO_SAVE_NETWORK"; 6760 break; 6761 case CMD_BOOT_COMPLETED: 6762 s = "CMD_BOOT_COMPLETED"; 6763 break; 6764 case DhcpStateMachine.CMD_START_DHCP: 6765 s = "CMD_START_DHCP"; 6766 break; 6767 case DhcpStateMachine.CMD_STOP_DHCP: 6768 s = "CMD_STOP_DHCP"; 6769 break; 6770 case DhcpStateMachine.CMD_RENEW_DHCP: 6771 s = "CMD_RENEW_DHCP"; 6772 break; 6773 case DhcpStateMachine.CMD_PRE_DHCP_ACTION: 6774 s = "CMD_PRE_DHCP_ACTION"; 6775 break; 6776 case DhcpStateMachine.CMD_POST_DHCP_ACTION: 6777 s = "CMD_POST_DHCP_ACTION"; 6778 break; 6779 case DhcpStateMachine.CMD_PRE_DHCP_ACTION_COMPLETE: 6780 s = "CMD_PRE_DHCP_ACTION_COMPLETE"; 6781 break; 6782 case DhcpStateMachine.CMD_ON_QUIT: 6783 s = "CMD_ON_QUIT"; 6784 break; 6785 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 6786 s = "WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST"; 6787 break; 6788 case WifiManager.DISABLE_NETWORK: 6789 s = "WifiManager.DISABLE_NETWORK"; 6790 break; 6791 case CMD_BLACKLIST_NETWORK: 6792 s = "CMD_BLACKLIST_NETWORK"; 6793 break; 6794 case CMD_CLEAR_BLACKLIST: 6795 s = "CMD_CLEAR_BLACKLIST"; 6796 break; 6797 case CMD_SAVE_CONFIG: 6798 s = "CMD_SAVE_CONFIG"; 6799 break; 6800 case CMD_GET_CONFIGURED_NETWORKS: 6801 s = "CMD_GET_CONFIGURED_NETWORKS"; 6802 break; 6803 case CMD_GET_SUPPORTED_FEATURES: 6804 s = "CMD_GET_SUPPORTED_FEATURES"; 6805 break; 6806 case CMD_UNWANTED_NETWORK: 6807 s = "CMD_UNWANTED_NETWORK"; 6808 break; 6809 case CMD_NETWORK_STATUS: 6810 s = "CMD_NETWORK_STATUS"; 6811 break; 6812 case CMD_GET_LINK_LAYER_STATS: 6813 s = "CMD_GET_LINK_LAYER_STATS"; 6814 break; 6815 case CMD_GET_MATCHING_CONFIG: 6816 s = "CMD_GET_MATCHING_CONFIG"; 6817 break; 6818 case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS: 6819 s = "CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS"; 6820 break; 6821 case CMD_DISCONNECT: 6822 s = "CMD_DISCONNECT"; 6823 break; 6824 case CMD_RECONNECT: 6825 s = "CMD_RECONNECT"; 6826 break; 6827 case CMD_REASSOCIATE: 6828 s = "CMD_REASSOCIATE"; 6829 break; 6830 case CMD_GET_CONNECTION_STATISTICS: 6831 s = "CMD_GET_CONNECTION_STATISTICS"; 6832 break; 6833 case CMD_SET_HIGH_PERF_MODE: 6834 s = "CMD_SET_HIGH_PERF_MODE"; 6835 break; 6836 case CMD_SET_COUNTRY_CODE: 6837 s = "CMD_SET_COUNTRY_CODE"; 6838 break; 6839 case CMD_ENABLE_RSSI_POLL: 6840 s = "CMD_ENABLE_RSSI_POLL"; 6841 break; 6842 case CMD_RSSI_POLL: 6843 s = "CMD_RSSI_POLL"; 6844 break; 6845 case CMD_START_PACKET_FILTERING: 6846 s = "CMD_START_PACKET_FILTERING"; 6847 break; 6848 case CMD_STOP_PACKET_FILTERING: 6849 s = "CMD_STOP_PACKET_FILTERING"; 6850 break; 6851 case CMD_SET_SUSPEND_OPT_ENABLED: 6852 s = "CMD_SET_SUSPEND_OPT_ENABLED"; 6853 break; 6854 case CMD_NO_NETWORKS_PERIODIC_SCAN: 6855 s = "CMD_NO_NETWORKS_PERIODIC_SCAN"; 6856 break; 6857 case CMD_UPDATE_LINKPROPERTIES: 6858 s = "CMD_UPDATE_LINKPROPERTIES"; 6859 break; 6860 case CMD_RELOAD_TLS_AND_RECONNECT: 6861 s = "CMD_RELOAD_TLS_AND_RECONNECT"; 6862 break; 6863 case WifiManager.CONNECT_NETWORK: 6864 s = "CONNECT_NETWORK"; 6865 break; 6866 case WifiManager.SAVE_NETWORK: 6867 s = "SAVE_NETWORK"; 6868 break; 6869 case WifiManager.FORGET_NETWORK: 6870 s = "FORGET_NETWORK"; 6871 break; 6872 case WifiMonitor.SUP_CONNECTION_EVENT: 6873 s = "SUP_CONNECTION_EVENT"; 6874 break; 6875 case WifiMonitor.SUP_DISCONNECTION_EVENT: 6876 s = "SUP_DISCONNECTION_EVENT"; 6877 break; 6878 case WifiMonitor.SCAN_RESULTS_EVENT: 6879 s = "SCAN_RESULTS_EVENT"; 6880 break; 6881 case WifiMonitor.SCAN_FAILED_EVENT: 6882 s = "SCAN_FAILED_EVENT"; 6883 break; 6884 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6885 s = "SUPPLICANT_STATE_CHANGE_EVENT"; 6886 break; 6887 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 6888 s = "AUTHENTICATION_FAILURE_EVENT"; 6889 break; 6890 case WifiMonitor.SSID_TEMP_DISABLED: 6891 s = "SSID_TEMP_DISABLED"; 6892 break; 6893 case WifiMonitor.SSID_REENABLED: 6894 s = "SSID_REENABLED"; 6895 break; 6896 case WifiMonitor.WPS_SUCCESS_EVENT: 6897 s = "WPS_SUCCESS_EVENT"; 6898 break; 6899 case WifiMonitor.WPS_FAIL_EVENT: 6900 s = "WPS_FAIL_EVENT"; 6901 break; 6902 case WifiMonitor.SUP_REQUEST_IDENTITY: 6903 s = "SUP_REQUEST_IDENTITY"; 6904 break; 6905 case WifiMonitor.NETWORK_CONNECTION_EVENT: 6906 s = "NETWORK_CONNECTION_EVENT"; 6907 break; 6908 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6909 s = "NETWORK_DISCONNECTION_EVENT"; 6910 break; 6911 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 6912 s = "ASSOCIATION_REJECTION_EVENT"; 6913 break; 6914 case WifiMonitor.ANQP_DONE_EVENT: 6915 s = "WifiMonitor.ANQP_DONE_EVENT"; 6916 break; 6917 case WifiMonitor.GAS_QUERY_DONE_EVENT: 6918 s = "WifiMonitor.GAS_QUERY_DONE_EVENT"; 6919 break; 6920 case WifiMonitor.HS20_DEAUTH_EVENT: 6921 s = "WifiMonitor.HS20_DEAUTH_EVENT"; 6922 break; 6923 case WifiMonitor.GAS_QUERY_START_EVENT: 6924 s = "WifiMonitor.GAS_QUERY_START_EVENT"; 6925 break; 6926 case CMD_SET_OPERATIONAL_MODE: 6927 s = "CMD_SET_OPERATIONAL_MODE"; 6928 break; 6929 case CMD_START_SCAN: 6930 s = "CMD_START_SCAN"; 6931 break; 6932 case CMD_DISABLE_P2P_RSP: 6933 s = "CMD_DISABLE_P2P_RSP"; 6934 break; 6935 case CMD_DISABLE_P2P_REQ: 6936 s = "CMD_DISABLE_P2P_REQ"; 6937 break; 6938 case WifiWatchdogStateMachine.GOOD_LINK_DETECTED: 6939 s = "GOOD_LINK_DETECTED"; 6940 break; 6941 case WifiWatchdogStateMachine.POOR_LINK_DETECTED: 6942 s = "POOR_LINK_DETECTED"; 6943 break; 6944 case WifiP2pServiceImpl.GROUP_CREATING_TIMED_OUT: 6945 s = "GROUP_CREATING_TIMED_OUT"; 6946 break; 6947 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 6948 s = "P2P_CONNECTION_CHANGED"; 6949 break; 6950 case WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE: 6951 s = "P2P.DISCONNECT_WIFI_RESPONSE"; 6952 break; 6953 case WifiP2pServiceImpl.SET_MIRACAST_MODE: 6954 s = "P2P.SET_MIRACAST_MODE"; 6955 break; 6956 case WifiP2pServiceImpl.BLOCK_DISCOVERY: 6957 s = "P2P.BLOCK_DISCOVERY"; 6958 break; 6959 case WifiP2pServiceImpl.SET_COUNTRY_CODE: 6960 s = "P2P.SET_COUNTRY_CODE"; 6961 break; 6962 case WifiManager.CANCEL_WPS: 6963 s = "CANCEL_WPS"; 6964 break; 6965 case WifiManager.CANCEL_WPS_FAILED: 6966 s = "CANCEL_WPS_FAILED"; 6967 break; 6968 case WifiManager.CANCEL_WPS_SUCCEDED: 6969 s = "CANCEL_WPS_SUCCEDED"; 6970 break; 6971 case WifiManager.START_WPS: 6972 s = "START_WPS"; 6973 break; 6974 case WifiManager.START_WPS_SUCCEEDED: 6975 s = "START_WPS_SUCCEEDED"; 6976 break; 6977 case WifiManager.WPS_FAILED: 6978 s = "WPS_FAILED"; 6979 break; 6980 case WifiManager.WPS_COMPLETED: 6981 s = "WPS_COMPLETED"; 6982 break; 6983 case WifiManager.RSSI_PKTCNT_FETCH: 6984 s = "RSSI_PKTCNT_FETCH"; 6985 break; 6986 case CMD_IP_CONFIGURATION_LOST: 6987 s = "CMD_IP_CONFIGURATION_LOST"; 6988 break; 6989 case CMD_IP_CONFIGURATION_SUCCESSFUL: 6990 s = "CMD_IP_CONFIGURATION_SUCCESSFUL"; 6991 break; 6992 case CMD_IP_REACHABILITY_LOST: 6993 s = "CMD_IP_REACHABILITY_LOST"; 6994 break; 6995 case CMD_STATIC_IP_SUCCESS: 6996 s = "CMD_STATIC_IP_SUCCESSFUL"; 6997 break; 6998 case CMD_STATIC_IP_FAILURE: 6999 s = "CMD_STATIC_IP_FAILURE"; 7000 break; 7001 case DhcpStateMachine.DHCP_SUCCESS: 7002 s = "DHCP_SUCCESS"; 7003 break; 7004 case DhcpStateMachine.DHCP_FAILURE: 7005 s = "DHCP_FAILURE"; 7006 break; 7007 case CMD_TARGET_BSSID: 7008 s = "CMD_TARGET_BSSID"; 7009 break; 7010 case CMD_ASSOCIATED_BSSID: 7011 s = "CMD_ASSOCIATED_BSSID"; 7012 break; 7013 case CMD_REMOVE_APP_CONFIGURATIONS: 7014 s = "CMD_REMOVE_APP_CONFIGURATIONS"; 7015 break; 7016 case CMD_REMOVE_USER_CONFIGURATIONS: 7017 s = "CMD_REMOVE_USER_CONFIGURATIONS"; 7018 break; 7019 case CMD_ROAM_WATCHDOG_TIMER: 7020 s = "CMD_ROAM_WATCHDOG_TIMER"; 7021 break; 7022 case CMD_SCREEN_STATE_CHANGED: 7023 s = "CMD_SCREEN_STATE_CHANGED"; 7024 break; 7025 case CMD_DISCONNECTING_WATCHDOG_TIMER: 7026 s = "CMD_DISCONNECTING_WATCHDOG_TIMER"; 7027 break; 7028 case CMD_RESTART_AUTOJOIN_OFFLOAD: 7029 s = "CMD_RESTART_AUTOJOIN_OFFLOAD"; 7030 break; 7031 case CMD_STARTED_PNO_DBG: 7032 s = "CMD_STARTED_PNO_DBG"; 7033 break; 7034 case CMD_STARTED_GSCAN_DBG: 7035 s = "CMD_STARTED_GSCAN_DBG"; 7036 break; 7037 case CMD_PNO_NETWORK_FOUND: 7038 s = "CMD_PNO_NETWORK_FOUND"; 7039 break; 7040 case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION: 7041 s = "CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION"; 7042 break; 7043 case CMD_START_IP_PACKET_OFFLOAD: 7044 s = "CMD_START_IP_PACKET_OFFLOAD"; 7045 break; 7046 case CMD_STOP_IP_PACKET_OFFLOAD: 7047 s = "CMD_STOP_IP_PACKET_OFFLOAD"; 7048 break; 7049 case CMD_START_RSSI_MONITORING_OFFLOAD: 7050 s = "CMD_START_RSSI_MONITORING_OFFLOAD"; 7051 break; 7052 case CMD_STOP_RSSI_MONITORING_OFFLOAD: 7053 s = "CMD_STOP_RSSI_MONITORING_OFFLOAD"; 7054 break; 7055 case CMD_RSSI_THRESHOLD_BREACH: 7056 s = "CMD_RSSI_THRESHOLD_BREACH"; 7057 break; 7058 default: 7059 s = "what:" + Integer.toString(what); 7060 break; 7061 } 7062 return s; 7063 } 7064 7065 void registerConnected() { 7066 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 7067 long now_ms = System.currentTimeMillis(); 7068 // We are switching away from this configuration, 7069 // hence record the time we were connected last 7070 WifiConfiguration config = mWifiConfigStore.getWifiConfiguration(mLastNetworkId); 7071 if (config != null) { 7072 config.lastConnected = System.currentTimeMillis(); 7073 config.autoJoinBailedDueToLowRssi = false; 7074 config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED); 7075 config.numConnectionFailures = 0; 7076 config.numIpConfigFailures = 0; 7077 config.numAuthFailures = 0; 7078 config.numAssociation++; 7079 } 7080 mBadLinkspeedcount = 0; 7081 } 7082 } 7083 7084 void registerDisconnected() { 7085 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 7086 long now_ms = System.currentTimeMillis(); 7087 // We are switching away from this configuration, 7088 // hence record the time we were connected last 7089 WifiConfiguration config = mWifiConfigStore.getWifiConfiguration(mLastNetworkId); 7090 if (config != null) { 7091 config.lastDisconnected = System.currentTimeMillis(); 7092 if (config.ephemeral) { 7093 // Remove ephemeral WifiConfigurations from file 7094 mWifiConfigStore.forgetNetwork(mLastNetworkId); 7095 } 7096 } 7097 } 7098 } 7099 7100 void noteWifiDisabledWhileAssociated() { 7101 // We got disabled by user while we were associated, make note of it 7102 int rssi = mWifiInfo.getRssi(); 7103 WifiConfiguration config = getCurrentWifiConfiguration(); 7104 if (getCurrentState() == mConnectedState 7105 && rssi != WifiInfo.INVALID_RSSI 7106 && config != null) { 7107 boolean is24GHz = mWifiInfo.is24GHz(); 7108 boolean isBadRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdBadRssi24.get()) 7109 || (!is24GHz && rssi < mWifiConfigStore.thresholdBadRssi5.get()); 7110 boolean isLowRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdLowRssi24.get()) 7111 || (!is24GHz && mWifiInfo.getRssi() < mWifiConfigStore.thresholdLowRssi5.get()); 7112 boolean isHighRSSI = (is24GHz && rssi >= mWifiConfigStore.thresholdGoodRssi24.get()) 7113 || (!is24GHz && mWifiInfo.getRssi() >= mWifiConfigStore.thresholdGoodRssi5.get()); 7114 if (isBadRSSI) { 7115 // Take note that we got disabled while RSSI was Bad 7116 config.numUserTriggeredWifiDisableLowRSSI++; 7117 } else if (isLowRSSI) { 7118 // Take note that we got disabled while RSSI was Low 7119 config.numUserTriggeredWifiDisableBadRSSI++; 7120 } else if (!isHighRSSI) { 7121 // Take note that we got disabled while RSSI was Not high 7122 config.numUserTriggeredWifiDisableNotHighRSSI++; 7123 } 7124 } 7125 } 7126 7127 WifiConfiguration getCurrentWifiConfiguration() { 7128 if (mLastNetworkId == WifiConfiguration.INVALID_NETWORK_ID) { 7129 return null; 7130 } 7131 return mWifiConfigStore.getWifiConfiguration(mLastNetworkId); 7132 } 7133 7134 ScanResult getCurrentScanResult() { 7135 WifiConfiguration config = getCurrentWifiConfiguration(); 7136 if (config == null) { 7137 return null; 7138 } 7139 String BSSID = mWifiInfo.getBSSID(); 7140 if (BSSID == null) { 7141 BSSID = mTargetRoamBSSID; 7142 } 7143 ScanDetailCache scanDetailCache = 7144 mWifiConfigStore.getScanDetailCache(config); 7145 7146 if (scanDetailCache == null) { 7147 return null; 7148 } 7149 7150 return scanDetailCache.get(BSSID); 7151 } 7152 7153 String getCurrentBSSID() { 7154 if (linkDebouncing) { 7155 return null; 7156 } 7157 return mLastBssid; 7158 } 7159 7160 class ConnectModeState extends State { 7161 7162 @Override 7163 public void enter() { 7164 connectScanningService(); 7165 } 7166 7167 @Override 7168 public boolean processMessage(Message message) { 7169 WifiConfiguration config; 7170 int netId; 7171 boolean ok; 7172 boolean didDisconnect; 7173 String bssid; 7174 String ssid; 7175 NetworkUpdateResult result; 7176 logStateAndMessage(message, getClass().getSimpleName()); 7177 7178 switch (message.what) { 7179 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 7180 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_ASSOC_FAILURE); 7181 didBlackListBSSID = false; 7182 bssid = (String) message.obj; 7183 if (bssid == null || TextUtils.isEmpty(bssid)) { 7184 // If BSSID is null, use the target roam BSSID 7185 bssid = mTargetRoamBSSID; 7186 } 7187 if (bssid != null) { 7188 // If we have a BSSID, tell configStore to black list it 7189 synchronized(mScanResultCache) { 7190 didBlackListBSSID = mWifiConfigStore.handleBSSIDBlackList 7191 (mLastNetworkId, bssid, false); 7192 } 7193 } 7194 mSupplicantStateTracker.sendMessage(WifiMonitor.ASSOCIATION_REJECTION_EVENT); 7195 break; 7196 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 7197 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_AUTH_FAILURE); 7198 mSupplicantStateTracker.sendMessage(WifiMonitor.AUTHENTICATION_FAILURE_EVENT); 7199 break; 7200 case WifiMonitor.SSID_TEMP_DISABLED: 7201 case WifiMonitor.SSID_REENABLED: 7202 String substr = (String) message.obj; 7203 String en = message.what == WifiMonitor.SSID_TEMP_DISABLED ? 7204 "temp-disabled" : "re-enabled"; 7205 logd("ConnectModeState SSID state=" + en + " nid=" 7206 + Integer.toString(message.arg1) + " [" + substr + "]"); 7207 synchronized(mScanResultCache) { 7208 mWifiConfigStore.handleSSIDStateChange(message.arg1, message.what == 7209 WifiMonitor.SSID_REENABLED, substr, mWifiInfo.getBSSID()); 7210 } 7211 break; 7212 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 7213 SupplicantState state = handleSupplicantStateChange(message); 7214 // A driver/firmware hang can now put the interface in a down state. 7215 // We detect the interface going down and recover from it 7216 if (!SupplicantState.isDriverActive(state)) { 7217 if (mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) { 7218 handleNetworkDisconnect(); 7219 } 7220 log("Detected an interface down, restart driver"); 7221 transitionTo(mDriverStoppedState); 7222 sendMessage(CMD_START_DRIVER); 7223 break; 7224 } 7225 7226 // Supplicant can fail to report a NETWORK_DISCONNECTION_EVENT 7227 // when authentication times out after a successful connection, 7228 // we can figure this from the supplicant state. If supplicant 7229 // state is DISCONNECTED, but the mNetworkInfo says we are not 7230 // disconnected, we need to handle a disconnection 7231 if (!linkDebouncing && state == SupplicantState.DISCONNECTED && 7232 mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) { 7233 if (DBG) log("Missed CTRL-EVENT-DISCONNECTED, disconnect"); 7234 handleNetworkDisconnect(); 7235 transitionTo(mDisconnectedState); 7236 } 7237 7238 // If we have COMPLETED a connection to a BSSID, start doing 7239 // DNAv4/DNAv6 -style probing for on-link neighbors of 7240 // interest (e.g. routers); harmless if none are configured. 7241 if (state == SupplicantState.COMPLETED) { 7242 if (mIpReachabilityMonitor != null) { 7243 mIpReachabilityMonitor.probeAll(); 7244 } 7245 } 7246 break; 7247 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 7248 if (message.arg1 == 1) { 7249 mWifiNative.disconnect(); 7250 mTemporarilyDisconnectWifi = true; 7251 } else { 7252 mWifiNative.reconnect(); 7253 mTemporarilyDisconnectWifi = false; 7254 } 7255 break; 7256 case CMD_ADD_OR_UPDATE_NETWORK: 7257 config = (WifiConfiguration) message.obj; 7258 7259 if (!recordUidIfAuthorized(config, message.sendingUid, 7260 /* onlyAnnotate */ false)) { 7261 logw("Not authorized to update network " 7262 + " config=" + config.SSID 7263 + " cnid=" + config.networkId 7264 + " uid=" + message.sendingUid); 7265 replyToMessage(message, message.what, FAILURE); 7266 break; 7267 } 7268 7269 int res = mWifiConfigStore.addOrUpdateNetwork(config, message.sendingUid); 7270 if (res < 0) { 7271 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7272 } else { 7273 WifiConfiguration curConfig = getCurrentWifiConfiguration(); 7274 if (curConfig != null && config != null) { 7275 if (curConfig.priority < config.priority 7276 && config.status == WifiConfiguration.Status.ENABLED) { 7277 // Interpret this as a connect attempt 7278 // Set the last selected configuration so as to allow the system to 7279 // stick the last user choice without persisting the choice 7280 mWifiConfigStore.setLastSelectedConfiguration(res); 7281 mWifiConfigStore.updateLastConnectUid(config, message.sendingUid); 7282 mWifiConfigStore.writeKnownNetworkHistory(false); 7283 7284 // Remember time of last connection attempt 7285 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7286 7287 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 7288 7289 // As a courtesy to the caller, trigger a scan now 7290 startScan(ADD_OR_UPDATE_SOURCE, 0, null, null); 7291 } 7292 } 7293 } 7294 replyToMessage(message, CMD_ADD_OR_UPDATE_NETWORK, res); 7295 break; 7296 case CMD_REMOVE_NETWORK: 7297 netId = message.arg1; 7298 if (!mWifiConfigStore.canModifyNetwork(message.sendingUid, netId, 7299 /* onlyAnnotate */ false)) { 7300 logw("Not authorized to remove network " 7301 + " cnid=" + netId 7302 + " uid=" + message.sendingUid); 7303 replyToMessage(message, message.what, FAILURE); 7304 break; 7305 } 7306 7307 ok = mWifiConfigStore.removeNetwork(message.arg1); 7308 if (!ok) { 7309 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7310 } 7311 replyToMessage(message, message.what, ok ? SUCCESS : FAILURE); 7312 break; 7313 case CMD_ENABLE_NETWORK: 7314 boolean disableOthers = message.arg2 == 1; 7315 netId = message.arg1; 7316 config = mWifiConfigStore.getWifiConfiguration(netId); 7317 if (config == null) { 7318 loge("No network with id = " + netId); 7319 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7320 break; 7321 } 7322 7323 // Tell autojoin the user did try to select to that network 7324 // However, do NOT persist the choice by bumping the priority of the network 7325 if (disableOthers) { 7326 mWifiAutoJoinController. 7327 updateConfigurationHistory(netId, true, false); 7328 // Set the last selected configuration so as to allow the system to 7329 // stick the last user choice without persisting the choice 7330 mWifiConfigStore.setLastSelectedConfiguration(netId); 7331 7332 // Remember time of last connection attempt 7333 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7334 7335 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 7336 } 7337 // Cancel auto roam requests 7338 autoRoamSetBSSID(netId, "any"); 7339 7340 int uid = message.sendingUid; 7341 ok = mWifiConfigStore.enableNetwork(netId, disableOthers, uid); 7342 if (!ok) { 7343 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7344 } 7345 7346 replyToMessage(message, message.what, ok ? SUCCESS : FAILURE); 7347 break; 7348 case CMD_ENABLE_ALL_NETWORKS: 7349 long time = android.os.SystemClock.elapsedRealtime(); 7350 if (time - mLastEnableAllNetworksTime > MIN_INTERVAL_ENABLE_ALL_NETWORKS_MS) { 7351 mWifiConfigStore.enableAllNetworks(); 7352 mLastEnableAllNetworksTime = time; 7353 } 7354 break; 7355 case WifiManager.DISABLE_NETWORK: 7356 if (mWifiConfigStore.disableNetwork(message.arg1, 7357 WifiConfiguration.DISABLED_BY_WIFI_MANAGER) == true) { 7358 replyToMessage(message, WifiManager.DISABLE_NETWORK_SUCCEEDED); 7359 } else { 7360 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7361 replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED, 7362 WifiManager.ERROR); 7363 } 7364 break; 7365 case CMD_DISABLE_EPHEMERAL_NETWORK: 7366 config = mWifiConfigStore.disableEphemeralNetwork((String)message.obj); 7367 if (config != null) { 7368 if (config.networkId == mLastNetworkId) { 7369 // Disconnect and let autojoin reselect a new network 7370 sendMessage(CMD_DISCONNECT); 7371 } 7372 } 7373 break; 7374 case CMD_BLACKLIST_NETWORK: 7375 mWifiConfigStore.blackListBssid((String) message.obj); 7376 break; 7377 case CMD_CLEAR_BLACKLIST: 7378 mWifiConfigStore.clearBssidBlacklist(); 7379 break; 7380 case CMD_SAVE_CONFIG: 7381 ok = mWifiConfigStore.saveConfig(); 7382 7383 if (DBG) logd("did save config " + ok); 7384 replyToMessage(message, CMD_SAVE_CONFIG, ok ? SUCCESS : FAILURE); 7385 7386 // Inform the backup manager about a data change 7387 IBackupManager ibm = IBackupManager.Stub.asInterface( 7388 ServiceManager.getService(Context.BACKUP_SERVICE)); 7389 if (ibm != null) { 7390 try { 7391 ibm.dataChanged("com.android.providers.settings"); 7392 } catch (Exception e) { 7393 // Try again later 7394 } 7395 } 7396 break; 7397 case CMD_GET_CONFIGURED_NETWORKS: 7398 replyToMessage(message, message.what, 7399 mWifiConfigStore.getConfiguredNetworks()); 7400 break; 7401 case WifiMonitor.SUP_REQUEST_IDENTITY: 7402 int networkId = message.arg2; 7403 boolean identitySent = false; 7404 int eapMethod = WifiEnterpriseConfig.Eap.NONE; 7405 7406 if (targetWificonfiguration != null 7407 && targetWificonfiguration.enterpriseConfig != null) { 7408 eapMethod = targetWificonfiguration.enterpriseConfig.getEapMethod(); 7409 } 7410 7411 // For SIM & AKA/AKA' EAP method Only, get identity from ICC 7412 if (targetWificonfiguration != null 7413 && targetWificonfiguration.networkId == networkId 7414 && targetWificonfiguration.allowedKeyManagement 7415 .get(WifiConfiguration.KeyMgmt.IEEE8021X) 7416 && (eapMethod == WifiEnterpriseConfig.Eap.SIM 7417 || eapMethod == WifiEnterpriseConfig.Eap.AKA 7418 || eapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME)) { 7419 TelephonyManager tm = (TelephonyManager) 7420 mContext.getSystemService(Context.TELEPHONY_SERVICE); 7421 if (tm != null) { 7422 String imsi = tm.getSubscriberId(); 7423 String mccMnc = ""; 7424 7425 if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) 7426 mccMnc = tm.getSimOperator(); 7427 7428 String identity = buildIdentity(eapMethod, imsi, mccMnc); 7429 7430 if (!identity.isEmpty()) { 7431 mWifiNative.simIdentityResponse(networkId, identity); 7432 identitySent = true; 7433 } 7434 } 7435 } 7436 if (!identitySent) { 7437 // Supplicant lacks credentials to connect to that network, hence black list 7438 ssid = (String) message.obj; 7439 if (targetWificonfiguration != null && ssid != null 7440 && targetWificonfiguration.SSID != null 7441 && targetWificonfiguration.SSID.equals("\"" + ssid + "\"")) { 7442 mWifiConfigStore.handleSSIDStateChange( 7443 targetWificonfiguration.networkId, false, 7444 "AUTH_FAILED no identity", null); 7445 } 7446 // Disconnect now, as we don't have any way to fullfill 7447 // the supplicant request. 7448 mWifiConfigStore.setLastSelectedConfiguration( 7449 WifiConfiguration.INVALID_NETWORK_ID); 7450 mWifiNative.disconnect(); 7451 } 7452 break; 7453 case WifiMonitor.SUP_REQUEST_SIM_AUTH: 7454 logd("Received SUP_REQUEST_SIM_AUTH"); 7455 SimAuthRequestData requestData = (SimAuthRequestData) message.obj; 7456 if (requestData != null) { 7457 if (requestData.protocol == WifiEnterpriseConfig.Eap.SIM) { 7458 handleGsmAuthRequest(requestData); 7459 } else if (requestData.protocol == WifiEnterpriseConfig.Eap.AKA 7460 || requestData.protocol == WifiEnterpriseConfig.Eap.AKA_PRIME) { 7461 handle3GAuthRequest(requestData); 7462 } 7463 } else { 7464 loge("Invalid sim auth request"); 7465 } 7466 break; 7467 case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS: 7468 replyToMessage(message, message.what, 7469 mWifiConfigStore.getPrivilegedConfiguredNetworks()); 7470 break; 7471 case CMD_GET_MATCHING_CONFIG: 7472 replyToMessage(message, message.what, 7473 mWifiConfigStore.getMatchingConfig((ScanResult)message.obj)); 7474 break; 7475 /* Do a redundant disconnect without transition */ 7476 case CMD_DISCONNECT: 7477 mWifiConfigStore.setLastSelectedConfiguration 7478 (WifiConfiguration.INVALID_NETWORK_ID); 7479 mWifiNative.disconnect(); 7480 break; 7481 case CMD_RECONNECT: 7482 mWifiAutoJoinController.attemptAutoJoin(); 7483 break; 7484 case CMD_REASSOCIATE: 7485 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7486 mWifiNative.reassociate(); 7487 break; 7488 case CMD_RELOAD_TLS_AND_RECONNECT: 7489 if (mWifiConfigStore.needsUnlockedKeyStore()) { 7490 logd("Reconnecting to give a chance to un-connected TLS networks"); 7491 mWifiNative.disconnect(); 7492 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7493 mWifiNative.reconnect(); 7494 } 7495 break; 7496 case CMD_AUTO_ROAM: 7497 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 7498 return HANDLED; 7499 case CMD_AUTO_CONNECT: 7500 /* Work Around: wpa_supplicant can get in a bad state where it returns a non 7501 * associated status to the STATUS command but somehow-someplace still thinks 7502 * it is associated and thus will ignore select/reconnect command with 7503 * following message: 7504 * "Already associated with the selected network - do nothing" 7505 * 7506 * Hence, sends a disconnect to supplicant first. 7507 */ 7508 didDisconnect = false; 7509 if (getCurrentState() != mDisconnectedState) { 7510 /** Supplicant will ignore the reconnect if we are currently associated, 7511 * hence trigger a disconnect 7512 */ 7513 didDisconnect = true; 7514 mWifiNative.disconnect(); 7515 } 7516 7517 /* connect command coming from auto-join */ 7518 config = (WifiConfiguration) message.obj; 7519 netId = message.arg1; 7520 int roam = message.arg2; 7521 logd("CMD_AUTO_CONNECT sup state " 7522 + mSupplicantStateTracker.getSupplicantStateName() 7523 + " my state " + getCurrentState().getName() 7524 + " nid=" + Integer.toString(netId) 7525 + " roam=" + Integer.toString(roam)); 7526 if (config == null) { 7527 loge("AUTO_CONNECT and no config, bail out..."); 7528 break; 7529 } 7530 7531 /* Make sure we cancel any previous roam request */ 7532 autoRoamSetBSSID(netId, config.BSSID); 7533 7534 /* Save the network config */ 7535 logd("CMD_AUTO_CONNECT will save config -> " + config.SSID 7536 + " nid=" + Integer.toString(netId)); 7537 result = mWifiConfigStore.saveNetwork(config, WifiConfiguration.UNKNOWN_UID); 7538 netId = result.getNetworkId(); 7539 logd("CMD_AUTO_CONNECT did save config -> " 7540 + " nid=" + Integer.toString(netId)); 7541 7542 // Since we updated the config,read it back from config store: 7543 config = mWifiConfigStore.getWifiConfiguration(netId); 7544 if (config == null) { 7545 loge("CMD_AUTO_CONNECT couldn't update the config, got null config"); 7546 break; 7547 } 7548 if (netId != config.networkId) { 7549 loge("CMD_AUTO_CONNECT couldn't update the config, want" 7550 + " nid=" + Integer.toString(netId) + " but got" + config.networkId); 7551 break; 7552 } 7553 7554 if (deferForUserInput(message, netId, false)) { 7555 break; 7556 } else if (mWifiConfigStore.getWifiConfiguration(netId).userApproved == 7557 WifiConfiguration.USER_BANNED) { 7558 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7559 WifiManager.NOT_AUTHORIZED); 7560 break; 7561 } 7562 7563 // Make sure the network is enabled, since supplicant will not reenable it 7564 mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false); 7565 7566 // If we're autojoining a network that the user or an app explicitly selected, 7567 // keep track of the UID that selected it. 7568 int lastConnectUid = mWifiConfigStore.isLastSelectedConfiguration(config) ? 7569 config.lastConnectUid : WifiConfiguration.UNKNOWN_UID; 7570 7571 if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ false, 7572 lastConnectUid) && mWifiNative.reconnect()) { 7573 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7574 targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId); 7575 config = mWifiConfigStore.getWifiConfiguration(netId); 7576 if (config != null 7577 && !mWifiConfigStore.isLastSelectedConfiguration(config)) { 7578 // If we autojoined a different config than the user selected one, 7579 // it means we could not see the last user selection, 7580 // or that the last user selection was faulty and ended up blacklisted 7581 // for some reason (in which case the user is notified with an error 7582 // message in the Wifi picker), and thus we managed to auto-join away 7583 // from the selected config. -> in that case we need to forget 7584 // the selection because we don't want to abruptly switch back to it. 7585 // 7586 // Note that the user selection is also forgotten after a period of time 7587 // during which the device has been disconnected. 7588 // The default value is 30 minutes : see the code path at bottom of 7589 // setScanResults() function. 7590 mWifiConfigStore. 7591 setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID); 7592 } 7593 mAutoRoaming = roam; 7594 if (isRoaming() || linkDebouncing) { 7595 transitionTo(mRoamingState); 7596 } else if (didDisconnect) { 7597 transitionTo(mDisconnectingState); 7598 } else { 7599 /* Already in disconnected state, nothing to change */ 7600 if (!mScreenOn && mLegacyPnoEnabled && mBackgroundScanSupported) { 7601 int delay = 60 * 1000; 7602 if (VDBG) { 7603 logd("Starting PNO alarm: " + delay); 7604 } 7605 mAlarmManager.set(AlarmManager.RTC_WAKEUP, 7606 System.currentTimeMillis() + delay, 7607 mPnoIntent); 7608 } 7609 mRestartAutoJoinOffloadCounter++; 7610 } 7611 } else { 7612 loge("Failed to connect config: " + config + " netId: " + netId); 7613 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7614 WifiManager.ERROR); 7615 break; 7616 } 7617 break; 7618 case CMD_REMOVE_APP_CONFIGURATIONS: 7619 mWifiConfigStore.removeNetworksForApp((ApplicationInfo) message.obj); 7620 break; 7621 case CMD_REMOVE_USER_CONFIGURATIONS: 7622 mWifiConfigStore.removeNetworksForUser(message.arg1); 7623 break; 7624 case WifiManager.CONNECT_NETWORK: 7625 /** 7626 * The connect message can contain a network id passed as arg1 on message or 7627 * or a config passed as obj on message. 7628 * For a new network, a config is passed to create and connect. 7629 * For an existing network, a network id is passed 7630 */ 7631 netId = message.arg1; 7632 config = (WifiConfiguration) message.obj; 7633 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 7634 boolean updatedExisting = false; 7635 7636 /* Save the network config */ 7637 if (config != null) { 7638 // When connecting to an access point, WifiStateMachine wants to update the 7639 // relevant config with administrative data. This update should not be 7640 // considered a 'real' update, therefore lockdown by Device Owner must be 7641 // disregarded. 7642 if (!recordUidIfAuthorized(config, message.sendingUid, 7643 /* onlyAnnotate */ true)) { 7644 logw("Not authorized to update network " 7645 + " config=" + config.SSID 7646 + " cnid=" + config.networkId 7647 + " uid=" + message.sendingUid); 7648 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7649 WifiManager.NOT_AUTHORIZED); 7650 break; 7651 } 7652 7653 String configKey = config.configKey(true /* allowCached */); 7654 WifiConfiguration savedConfig = 7655 mWifiConfigStore.getWifiConfiguration(configKey); 7656 if (savedConfig != null) { 7657 // There is an existing config with this netId, but it wasn't exposed 7658 // (either AUTO_JOIN_DELETED or ephemeral; see WifiConfigStore# 7659 // getConfiguredNetworks). Remove those bits and update the config. 7660 config = savedConfig; 7661 logd("CONNECT_NETWORK updating existing config with id=" + 7662 config.networkId + " configKey=" + configKey); 7663 config.ephemeral = false; 7664 config.autoJoinStatus = WifiConfiguration.AUTO_JOIN_ENABLED; 7665 updatedExisting = true; 7666 } 7667 7668 result = mWifiConfigStore.saveNetwork(config, message.sendingUid); 7669 netId = result.getNetworkId(); 7670 } 7671 config = mWifiConfigStore.getWifiConfiguration(netId); 7672 7673 if (config == null) { 7674 logd("CONNECT_NETWORK no config for id=" + Integer.toString(netId) + " " 7675 + mSupplicantStateTracker.getSupplicantStateName() + " my state " 7676 + getCurrentState().getName()); 7677 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7678 WifiManager.ERROR); 7679 break; 7680 } else { 7681 String wasSkipped = config.autoJoinBailedDueToLowRssi ? " skipped" : ""; 7682 logd("CONNECT_NETWORK id=" + Integer.toString(netId) 7683 + " config=" + config.SSID 7684 + " cnid=" + config.networkId 7685 + " supstate=" + mSupplicantStateTracker.getSupplicantStateName() 7686 + " my state " + getCurrentState().getName() 7687 + " uid = " + message.sendingUid 7688 + wasSkipped); 7689 } 7690 7691 autoRoamSetBSSID(netId, "any"); 7692 7693 if (message.sendingUid == Process.WIFI_UID 7694 || message.sendingUid == Process.SYSTEM_UID) { 7695 // As a sanity measure, clear the BSSID in the supplicant network block. 7696 // If system or Wifi Settings want to connect, they will not 7697 // specify the BSSID. 7698 // If an app however had added a BSSID to this configuration, and the BSSID 7699 // was wrong, Then we would forever fail to connect until that BSSID 7700 // is cleaned up. 7701 clearConfigBSSID(config, "CONNECT_NETWORK"); 7702 } 7703 7704 if (deferForUserInput(message, netId, true)) { 7705 break; 7706 } else if (mWifiConfigStore.getWifiConfiguration(netId).userApproved == 7707 WifiConfiguration.USER_BANNED) { 7708 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7709 WifiManager.NOT_AUTHORIZED); 7710 break; 7711 } 7712 7713 mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE; 7714 7715 /* Tell autojoin the user did try to connect to that network if from settings */ 7716 boolean persist = 7717 mWifiConfigStore.checkConfigOverridePermission(message.sendingUid); 7718 mWifiAutoJoinController.updateConfigurationHistory(netId, true, persist); 7719 7720 mWifiConfigStore.setLastSelectedConfiguration(netId); 7721 7722 didDisconnect = false; 7723 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID 7724 && mLastNetworkId != netId) { 7725 /** Supplicant will ignore the reconnect if we are currently associated, 7726 * hence trigger a disconnect 7727 */ 7728 didDisconnect = true; 7729 mWifiNative.disconnect(); 7730 } 7731 7732 // Make sure the network is enabled, since supplicant will not reenable it 7733 mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false); 7734 7735 if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ true, 7736 message.sendingUid) && mWifiNative.reconnect()) { 7737 lastConnectAttemptTimestamp = System.currentTimeMillis(); 7738 targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId); 7739 7740 /* The state tracker handles enabling networks upon completion/failure */ 7741 mSupplicantStateTracker.sendMessage(WifiManager.CONNECT_NETWORK); 7742 replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED); 7743 if (didDisconnect) { 7744 /* Expect a disconnection from the old connection */ 7745 transitionTo(mDisconnectingState); 7746 } else if (updatedExisting && getCurrentState() == mConnectedState && 7747 getCurrentWifiConfiguration().networkId == netId) { 7748 // Update the current set of network capabilities, but stay in the 7749 // current state. 7750 updateCapabilities(config); 7751 } else { 7752 /** 7753 * Directly go to disconnected state where we 7754 * process the connection events from supplicant 7755 **/ 7756 transitionTo(mDisconnectedState); 7757 } 7758 } else { 7759 loge("Failed to connect config: " + config + " netId: " + netId); 7760 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7761 WifiManager.ERROR); 7762 break; 7763 } 7764 break; 7765 case WifiManager.SAVE_NETWORK: 7766 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 7767 // Fall thru 7768 case WifiStateMachine.CMD_AUTO_SAVE_NETWORK: 7769 lastSavedConfigurationAttempt = null; // Used for debug 7770 config = (WifiConfiguration) message.obj; 7771 if (config == null) { 7772 loge("ERROR: SAVE_NETWORK with null configuration" 7773 + mSupplicantStateTracker.getSupplicantStateName() 7774 + " my state " + getCurrentState().getName()); 7775 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7776 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 7777 WifiManager.ERROR); 7778 break; 7779 } 7780 lastSavedConfigurationAttempt = new WifiConfiguration(config); 7781 int nid = config.networkId; 7782 logd("SAVE_NETWORK id=" + Integer.toString(nid) 7783 + " config=" + config.SSID 7784 + " nid=" + config.networkId 7785 + " supstate=" + mSupplicantStateTracker.getSupplicantStateName() 7786 + " my state " + getCurrentState().getName()); 7787 7788 // Only record the uid if this is user initiated 7789 boolean checkUid = (message.what == WifiManager.SAVE_NETWORK); 7790 if (checkUid && !recordUidIfAuthorized(config, message.sendingUid, 7791 /* onlyAnnotate */ false)) { 7792 logw("Not authorized to update network " 7793 + " config=" + config.SSID 7794 + " cnid=" + config.networkId 7795 + " uid=" + message.sendingUid); 7796 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 7797 WifiManager.NOT_AUTHORIZED); 7798 break; 7799 } 7800 7801 result = mWifiConfigStore.saveNetwork(config, WifiConfiguration.UNKNOWN_UID); 7802 if (result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID) { 7803 if (mWifiInfo.getNetworkId() == result.getNetworkId()) { 7804 if (result.hasIpChanged()) { 7805 // The currently connection configuration was changed 7806 // We switched from DHCP to static or from static to DHCP, or the 7807 // static IP address has changed. 7808 log("Reconfiguring IP on connection"); 7809 // TODO: clear addresses and disable IPv6 7810 // to simplify obtainingIpState. 7811 transitionTo(mObtainingIpState); 7812 } 7813 if (result.hasProxyChanged()) { 7814 log("Reconfiguring proxy on connection"); 7815 updateLinkProperties(CMD_UPDATE_LINKPROPERTIES); 7816 } 7817 } 7818 replyToMessage(message, WifiManager.SAVE_NETWORK_SUCCEEDED); 7819 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_SAVED, config); 7820 7821 if (VDBG) { 7822 logd("Success save network nid=" 7823 + Integer.toString(result.getNetworkId())); 7824 } 7825 7826 synchronized(mScanResultCache) { 7827 /** 7828 * If the command comes from WifiManager, then 7829 * tell autojoin the user did try to modify and save that network, 7830 * and interpret the SAVE_NETWORK as a request to connect 7831 */ 7832 boolean user = message.what == WifiManager.SAVE_NETWORK; 7833 7834 // Did this connect come from settings 7835 boolean persistConnect = 7836 mWifiConfigStore.checkConfigOverridePermission(message.sendingUid); 7837 7838 if (user) { 7839 mWifiConfigStore.updateLastConnectUid(config, message.sendingUid); 7840 mWifiConfigStore.writeKnownNetworkHistory(false); 7841 } 7842 7843 mWifiAutoJoinController.updateConfigurationHistory(result.getNetworkId() 7844 , user, persistConnect); 7845 mWifiAutoJoinController.attemptAutoJoin(); 7846 } 7847 } else { 7848 loge("Failed to save network"); 7849 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7850 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 7851 WifiManager.ERROR); 7852 } 7853 break; 7854 case WifiManager.FORGET_NETWORK: 7855 // Debug only, remember last configuration that was forgotten 7856 WifiConfiguration toRemove 7857 = mWifiConfigStore.getWifiConfiguration(message.arg1); 7858 if (toRemove == null) { 7859 lastForgetConfigurationAttempt = null; 7860 } else { 7861 lastForgetConfigurationAttempt = new WifiConfiguration(toRemove); 7862 } 7863 // check that the caller owns this network 7864 netId = message.arg1; 7865 7866 if (!mWifiConfigStore.canModifyNetwork(message.sendingUid, netId, 7867 /* onlyAnnotate */ false)) { 7868 logw("Not authorized to forget network " 7869 + " cnid=" + netId 7870 + " uid=" + message.sendingUid); 7871 replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, 7872 WifiManager.NOT_AUTHORIZED); 7873 break; 7874 } 7875 7876 if (mWifiConfigStore.forgetNetwork(message.arg1)) { 7877 replyToMessage(message, WifiManager.FORGET_NETWORK_SUCCEEDED); 7878 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_FORGOT, 7879 (WifiConfiguration) message.obj); 7880 } else { 7881 loge("Failed to forget network"); 7882 replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, 7883 WifiManager.ERROR); 7884 } 7885 break; 7886 case WifiManager.START_WPS: 7887 WpsInfo wpsInfo = (WpsInfo) message.obj; 7888 WpsResult wpsResult; 7889 switch (wpsInfo.setup) { 7890 case WpsInfo.PBC: 7891 wpsResult = mWifiConfigStore.startWpsPbc(wpsInfo); 7892 break; 7893 case WpsInfo.KEYPAD: 7894 wpsResult = mWifiConfigStore.startWpsWithPinFromAccessPoint(wpsInfo); 7895 break; 7896 case WpsInfo.DISPLAY: 7897 wpsResult = mWifiConfigStore.startWpsWithPinFromDevice(wpsInfo); 7898 break; 7899 default: 7900 wpsResult = new WpsResult(Status.FAILURE); 7901 loge("Invalid setup for WPS"); 7902 break; 7903 } 7904 mWifiConfigStore.setLastSelectedConfiguration 7905 (WifiConfiguration.INVALID_NETWORK_ID); 7906 if (wpsResult.status == Status.SUCCESS) { 7907 replyToMessage(message, WifiManager.START_WPS_SUCCEEDED, wpsResult); 7908 transitionTo(mWpsRunningState); 7909 } else { 7910 loge("Failed to start WPS with config " + wpsInfo.toString()); 7911 replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.ERROR); 7912 } 7913 break; 7914 case WifiMonitor.NETWORK_CONNECTION_EVENT: 7915 if (DBG) log("Network connection established"); 7916 mLastNetworkId = message.arg1; 7917 mLastBssid = (String) message.obj; 7918 7919 mWifiInfo.setBSSID(mLastBssid); 7920 mWifiInfo.setNetworkId(mLastNetworkId); 7921 7922 sendNetworkStateChangeBroadcast(mLastBssid); 7923 transitionTo(mObtainingIpState); 7924 break; 7925 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 7926 // Calling handleNetworkDisconnect here is redundant because we might already 7927 // have called it when leaving L2ConnectedState to go to disconnecting state 7928 // or thru other path 7929 // We should normally check the mWifiInfo or mLastNetworkId so as to check 7930 // if they are valid, and only in this case call handleNEtworkDisconnect, 7931 // TODO: this should be fixed for a L MR release 7932 // The side effect of calling handleNetworkDisconnect twice is that a bunch of 7933 // idempotent commands are executed twice (stopping Dhcp, enabling the SPS mode 7934 // at the chip etc... 7935 if (DBG) log("ConnectModeState: Network connection lost "); 7936 handleNetworkDisconnect(); 7937 transitionTo(mDisconnectedState); 7938 break; 7939 case CMD_PNO_NETWORK_FOUND: 7940 processPnoNetworkFound((ScanResult[])message.obj); 7941 break; 7942 default: 7943 return NOT_HANDLED; 7944 } 7945 return HANDLED; 7946 } 7947 } 7948 7949 private void updateCapabilities(WifiConfiguration config) { 7950 if (config != null) { 7951 if (config.ephemeral) { 7952 mNetworkCapabilities.removeCapability( 7953 NetworkCapabilities.NET_CAPABILITY_TRUSTED); 7954 } else { 7955 mNetworkCapabilities.addCapability( 7956 NetworkCapabilities.NET_CAPABILITY_TRUSTED); 7957 } 7958 } 7959 mNetworkCapabilities.setSignalStrength(mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI ? 7960 mWifiInfo.getRssi() : NetworkCapabilities.SIGNAL_STRENGTH_UNSPECIFIED); 7961 mNetworkAgent.sendNetworkCapabilities(mNetworkCapabilities); 7962 } 7963 7964 private class WifiNetworkAgent extends NetworkAgent { 7965 public WifiNetworkAgent(Looper l, Context c, String TAG, NetworkInfo ni, 7966 NetworkCapabilities nc, LinkProperties lp, int score) { 7967 super(l, c, TAG, ni, nc, lp, score); 7968 } 7969 protected void unwanted() { 7970 // Ignore if we're not the current networkAgent. 7971 if (this != mNetworkAgent) return; 7972 if (DBG) log("WifiNetworkAgent -> Wifi unwanted score " 7973 + Integer.toString(mWifiInfo.score)); 7974 unwantedNetwork(NETWORK_STATUS_UNWANTED_DISCONNECT); 7975 } 7976 7977 @Override 7978 protected void networkStatus(int status) { 7979 if (this != mNetworkAgent) return; 7980 if (status == NetworkAgent.INVALID_NETWORK) { 7981 if (DBG) log("WifiNetworkAgent -> Wifi networkStatus invalid, score=" 7982 + Integer.toString(mWifiInfo.score)); 7983 unwantedNetwork(NETWORK_STATUS_UNWANTED_VALIDATION_FAILED); 7984 } else if (status == NetworkAgent.VALID_NETWORK) { 7985 if (DBG && mWifiInfo != null) log("WifiNetworkAgent -> Wifi networkStatus valid, score= " 7986 + Integer.toString(mWifiInfo.score)); 7987 doNetworkStatus(status); 7988 } 7989 } 7990 7991 @Override 7992 protected void saveAcceptUnvalidated(boolean accept) { 7993 if (this != mNetworkAgent) return; 7994 WifiStateMachine.this.sendMessage(CMD_ACCEPT_UNVALIDATED, accept ? 1 : 0); 7995 } 7996 7997 @Override 7998 protected void startPacketKeepalive(Message msg) { 7999 WifiStateMachine.this.sendMessage( 8000 CMD_START_IP_PACKET_OFFLOAD, msg.arg1, msg.arg2, msg.obj); 8001 } 8002 8003 @Override 8004 protected void stopPacketKeepalive(Message msg) { 8005 WifiStateMachine.this.sendMessage( 8006 CMD_STOP_IP_PACKET_OFFLOAD, msg.arg1, msg.arg2, msg.obj); 8007 } 8008 8009 @Override 8010 protected void setSignalStrengthThresholds(int[] thresholds) { 8011 // 0. If there are no thresholds, or if the thresholds are invalid, stop RSSI monitoring. 8012 // 1. Tell the hardware to start RSSI monitoring here, possibly adding MIN_VALUE and 8013 // MAX_VALUE at the start/end of the thresholds array if necessary. 8014 // 2. Ensure that when the hardware event fires, we fetch the RSSI from the hardware 8015 // event, call mWifiInfo.setRssi() with it, and call updateCapabilities(), and then 8016 // re-arm the hardware event. This needs to be done on the state machine thread to 8017 // avoid race conditions. The RSSI used to re-arm the event (and perhaps also the one 8018 // sent in the NetworkCapabilities) must be the one received from the hardware event 8019 // received, or we might skip callbacks. 8020 // 3. Ensure that when we disconnect, RSSI monitoring is stopped. 8021 log("Received signal strength thresholds: " + Arrays.toString(thresholds)); 8022 if (thresholds.length == 0) { 8023 WifiStateMachine.this.sendMessage(CMD_STOP_RSSI_MONITORING_OFFLOAD, 8024 mWifiInfo.getRssi()); 8025 return; 8026 } 8027 int [] rssiVals = Arrays.copyOf(thresholds, thresholds.length + 2); 8028 rssiVals[rssiVals.length - 2] = Byte.MIN_VALUE; 8029 rssiVals[rssiVals.length - 1] = Byte.MAX_VALUE; 8030 Arrays.sort(rssiVals); 8031 byte[] rssiRange = new byte[rssiVals.length]; 8032 for (int i = 0; i < rssiVals.length; i++) { 8033 int val = rssiVals[i]; 8034 if (val <= Byte.MAX_VALUE && val >= Byte.MIN_VALUE) { 8035 rssiRange[i] = (byte) val; 8036 } else { 8037 Log.e(TAG, "Illegal value " + val + " for RSSI thresholds: " 8038 + Arrays.toString(rssiVals)); 8039 WifiStateMachine.this.sendMessage(CMD_STOP_RSSI_MONITORING_OFFLOAD, 8040 mWifiInfo.getRssi()); 8041 return; 8042 } 8043 } 8044 // TODO: Do we quash rssi values in this sorted array which are very close? 8045 mRssiRanges = rssiRange; 8046 WifiStateMachine.this.sendMessage(CMD_START_RSSI_MONITORING_OFFLOAD, 8047 mWifiInfo.getRssi()); 8048 } 8049 8050 @Override 8051 protected void preventAutomaticReconnect() { 8052 if (this != mNetworkAgent) return; 8053 unwantedNetwork(NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN); 8054 } 8055 } 8056 8057 void unwantedNetwork(int reason) { 8058 sendMessage(CMD_UNWANTED_NETWORK, reason); 8059 } 8060 8061 void doNetworkStatus(int status) { 8062 sendMessage(CMD_NETWORK_STATUS, status); 8063 } 8064 8065 // rfc4186 & rfc4187: 8066 // create Permanent Identity base on IMSI, 8067 // identity = usernam@realm 8068 // with username = prefix | IMSI 8069 // and realm is derived MMC/MNC tuple according 3GGP spec(TS23.003) 8070 private String buildIdentity(int eapMethod, String imsi, String mccMnc) { 8071 String mcc; 8072 String mnc; 8073 String prefix; 8074 8075 if (imsi == null || imsi.isEmpty()) 8076 return ""; 8077 8078 if (eapMethod == WifiEnterpriseConfig.Eap.SIM) 8079 prefix = "1"; 8080 else if (eapMethod == WifiEnterpriseConfig.Eap.AKA) 8081 prefix = "0"; 8082 else if (eapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME) 8083 prefix = "6"; 8084 else // not a valide EapMethod 8085 return ""; 8086 8087 /* extract mcc & mnc from mccMnc */ 8088 if (mccMnc != null && !mccMnc.isEmpty()) { 8089 mcc = mccMnc.substring(0, 3); 8090 mnc = mccMnc.substring(3); 8091 if (mnc.length() == 2) 8092 mnc = "0" + mnc; 8093 } else { 8094 // extract mcc & mnc from IMSI, assume mnc size is 3 8095 mcc = imsi.substring(0, 3); 8096 mnc = imsi.substring(3, 6); 8097 } 8098 8099 return prefix + imsi + "@wlan.mnc" + mnc + ".mcc" + mcc + ".3gppnetwork.org"; 8100 } 8101 8102 boolean startScanForConfiguration(WifiConfiguration config, boolean restrictChannelList) { 8103 if (config == null) 8104 return false; 8105 8106 // We are still seeing a fairly high power consumption triggered by autojoin scans 8107 // Hence do partial scans only for PSK configuration that are roamable since the 8108 // primary purpose of the partial scans is roaming. 8109 // Full badn scans with exponential backoff for the purpose or extended roaming and 8110 // network switching are performed unconditionally. 8111 ScanDetailCache scanDetailCache = 8112 mWifiConfigStore.getScanDetailCache(config); 8113 if (scanDetailCache == null 8114 || !config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK) 8115 || scanDetailCache.size() > 6) { 8116 //return true but to not trigger the scan 8117 return true; 8118 } 8119 HashSet<Integer> channels = mWifiConfigStore.makeChannelList(config, 8120 ONE_HOUR_MILLI, restrictChannelList); 8121 if (channels != null && channels.size() != 0) { 8122 StringBuilder freqs = new StringBuilder(); 8123 boolean first = true; 8124 for (Integer channel : channels) { 8125 if (!first) 8126 freqs.append(","); 8127 freqs.append(channel.toString()); 8128 first = false; 8129 } 8130 //if (DBG) { 8131 logd("starting scan for " + config.configKey() + " with " + freqs); 8132 //} 8133 // Call wifi native to start the scan 8134 if (startScanNative( 8135 WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, 8136 freqs.toString())) { 8137 // Only count battery consumption if scan request is accepted 8138 noteScanStart(SCAN_ALARM_SOURCE, null); 8139 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK; 8140 } else { 8141 // used for debug only, mark scan as failed 8142 messageHandlingStatus = MESSAGE_HANDLING_STATUS_HANDLING_ERROR; 8143 } 8144 return true; 8145 } else { 8146 if (DBG) logd("no channels for " + config.configKey()); 8147 return false; 8148 } 8149 } 8150 8151 void clearCurrentConfigBSSID(String dbg) { 8152 // Clear the bssid in the current config's network block 8153 WifiConfiguration config = getCurrentWifiConfiguration(); 8154 if (config == null) 8155 return; 8156 clearConfigBSSID(config, dbg); 8157 } 8158 void clearConfigBSSID(WifiConfiguration config, String dbg) { 8159 if (config == null) 8160 return; 8161 if (DBG) { 8162 logd(dbg + " " + mTargetRoamBSSID + " config " + config.configKey() 8163 + " config.bssid " + config.BSSID); 8164 } 8165 config.autoJoinBSSID = "any"; 8166 config.BSSID = "any"; 8167 if (DBG) { 8168 logd(dbg + " " + config.SSID 8169 + " nid=" + Integer.toString(config.networkId)); 8170 } 8171 mWifiConfigStore.saveWifiConfigBSSID(config); 8172 } 8173 8174 class L2ConnectedState extends State { 8175 @Override 8176 public void enter() { 8177 mRssiPollToken++; 8178 if (mEnableRssiPolling) { 8179 sendMessage(CMD_RSSI_POLL, mRssiPollToken, 0); 8180 } 8181 if (mNetworkAgent != null) { 8182 loge("Have NetworkAgent when entering L2Connected"); 8183 setNetworkDetailedState(DetailedState.DISCONNECTED); 8184 } 8185 setNetworkDetailedState(DetailedState.CONNECTING); 8186 8187 if (!TextUtils.isEmpty(mTcpBufferSizes)) { 8188 mLinkProperties.setTcpBufferSizes(mTcpBufferSizes); 8189 } 8190 mNetworkAgent = new WifiNetworkAgent(getHandler().getLooper(), mContext, 8191 "WifiNetworkAgent", mNetworkInfo, mNetworkCapabilitiesFilter, 8192 mLinkProperties, 60); 8193 8194 // We must clear the config BSSID, as the wifi chipset may decide to roam 8195 // from this point on and having the BSSID specified in the network block would 8196 // cause the roam to faile and the device to disconnect 8197 clearCurrentConfigBSSID("L2ConnectedState"); 8198 8199 try { 8200 mIpReachabilityMonitor = new IpReachabilityMonitor( 8201 mContext, 8202 mInterfaceName, 8203 new IpReachabilityMonitor.Callback() { 8204 @Override 8205 public void notifyLost(InetAddress ip, String logMsg) { 8206 sendMessage(CMD_IP_REACHABILITY_LOST, logMsg); 8207 } 8208 }); 8209 } catch (IllegalArgumentException e) { 8210 Log.wtf("Failed to create IpReachabilityMonitor", e); 8211 } 8212 } 8213 8214 @Override 8215 public void exit() { 8216 if (mIpReachabilityMonitor != null) { 8217 mIpReachabilityMonitor.stop(); 8218 mIpReachabilityMonitor = null; 8219 } 8220 8221 // This is handled by receiving a NETWORK_DISCONNECTION_EVENT in ConnectModeState 8222 // Bug: 15347363 8223 // For paranoia's sake, call handleNetworkDisconnect 8224 // only if BSSID is null or last networkId 8225 // is not invalid. 8226 if (DBG) { 8227 StringBuilder sb = new StringBuilder(); 8228 sb.append("leaving L2ConnectedState state nid=" + Integer.toString(mLastNetworkId)); 8229 if (mLastBssid !=null) { 8230 sb.append(" ").append(mLastBssid); 8231 } 8232 } 8233 if (mLastBssid != null || mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 8234 handleNetworkDisconnect(); 8235 } 8236 } 8237 8238 @Override 8239 public boolean processMessage(Message message) { 8240 logStateAndMessage(message, getClass().getSimpleName()); 8241 8242 switch (message.what) { 8243 case DhcpStateMachine.CMD_PRE_DHCP_ACTION: 8244 handlePreDhcpSetup(); 8245 break; 8246 case DhcpStateMachine.CMD_POST_DHCP_ACTION: 8247 handlePostDhcpSetup(); 8248 if (message.arg1 == DhcpStateMachine.DHCP_SUCCESS) { 8249 if (DBG) log("DHCP successful"); 8250 handleIPv4Success((DhcpResults) message.obj, DhcpStateMachine.DHCP_SUCCESS); 8251 // We advance to mConnectedState because handleIPv4Success will call 8252 // updateLinkProperties, which then sends CMD_IP_CONFIGURATION_SUCCESSFUL. 8253 } else if (message.arg1 == DhcpStateMachine.DHCP_FAILURE) { 8254 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_DHCP_FAILURE); 8255 if (DBG) { 8256 int count = -1; 8257 WifiConfiguration config = getCurrentWifiConfiguration(); 8258 if (config != null) { 8259 count = config.numConnectionFailures; 8260 } 8261 log("DHCP failure count=" + count); 8262 } 8263 handleIPv4Failure(DhcpStateMachine.DHCP_FAILURE); 8264 // As above, we transition to mDisconnectingState via updateLinkProperties. 8265 } 8266 break; 8267 case CMD_IP_CONFIGURATION_SUCCESSFUL: 8268 handleSuccessfulIpConfiguration(); 8269 sendConnectedState(); 8270 transitionTo(mConnectedState); 8271 break; 8272 case CMD_IP_CONFIGURATION_LOST: 8273 // Get Link layer stats so that we get fresh tx packet counters. 8274 getWifiLinkLayerStats(true); 8275 handleIpConfigurationLost(); 8276 transitionTo(mDisconnectingState); 8277 break; 8278 case CMD_IP_REACHABILITY_LOST: 8279 if (DBG && message.obj != null) log((String) message.obj); 8280 handleIpReachabilityLost(); 8281 transitionTo(mDisconnectingState); 8282 break; 8283 case CMD_DISCONNECT: 8284 mWifiNative.disconnect(); 8285 transitionTo(mDisconnectingState); 8286 break; 8287 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 8288 if (message.arg1 == 1) { 8289 mWifiNative.disconnect(); 8290 mTemporarilyDisconnectWifi = true; 8291 transitionTo(mDisconnectingState); 8292 } 8293 break; 8294 case CMD_SET_OPERATIONAL_MODE: 8295 if (message.arg1 != CONNECT_MODE) { 8296 sendMessage(CMD_DISCONNECT); 8297 deferMessage(message); 8298 if (message.arg1 == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 8299 noteWifiDisabledWhileAssociated(); 8300 } 8301 } 8302 mWifiConfigStore. 8303 setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID); 8304 break; 8305 case CMD_SET_COUNTRY_CODE: 8306 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 8307 deferMessage(message); 8308 break; 8309 case CMD_START_SCAN: 8310 if (DBG) { 8311 logd("CMD_START_SCAN source " + message.arg1 8312 + " txSuccessRate="+String.format( "%.2f", mWifiInfo.txSuccessRate) 8313 + " rxSuccessRate="+String.format( "%.2f", mWifiInfo.rxSuccessRate) 8314 + " targetRoamBSSID=" + mTargetRoamBSSID 8315 + " RSSI=" + mWifiInfo.getRssi()); 8316 } 8317 if (message.arg1 == SCAN_ALARM_SOURCE) { 8318 // Check if the CMD_START_SCAN message is obsolete (and thus if it should 8319 // not be processed) and restart the scan if neede 8320 if (!getEnableAutoJoinWhenAssociated()) { 8321 return HANDLED; 8322 } 8323 boolean shouldScan = mScreenOn; 8324 8325 if (!checkAndRestartDelayedScan(message.arg2, 8326 shouldScan, 8327 mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(), 8328 null, null)) { 8329 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 8330 logd("L2Connected CMD_START_SCAN source " 8331 + message.arg1 8332 + " " + message.arg2 + ", " + mDelayedScanCounter 8333 + " -> obsolete"); 8334 return HANDLED; 8335 } 8336 if (mP2pConnected.get()) { 8337 logd("L2Connected CMD_START_SCAN source " 8338 + message.arg1 8339 + " " + message.arg2 + ", " + mDelayedScanCounter 8340 + " ignore because P2P is connected"); 8341 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8342 return HANDLED; 8343 } 8344 boolean tryFullBandScan = false; 8345 boolean restrictChannelList = false; 8346 long now_ms = System.currentTimeMillis(); 8347 if (DBG) { 8348 logd("CMD_START_SCAN with age=" 8349 + Long.toString(now_ms - lastFullBandConnectedTimeMilli) 8350 + " interval=" + fullBandConnectedTimeIntervalMilli 8351 + " maxinterval=" + maxFullBandConnectedTimeIntervalMilli); 8352 } 8353 if (mWifiInfo != null) { 8354 if (mWifiConfigStore.enableFullBandScanWhenAssociated.get() && 8355 (now_ms - lastFullBandConnectedTimeMilli) 8356 > fullBandConnectedTimeIntervalMilli) { 8357 if (DBG) { 8358 logd("CMD_START_SCAN try full band scan age=" 8359 + Long.toString(now_ms - lastFullBandConnectedTimeMilli) 8360 + " interval=" + fullBandConnectedTimeIntervalMilli 8361 + " maxinterval=" + maxFullBandConnectedTimeIntervalMilli); 8362 } 8363 tryFullBandScan = true; 8364 } 8365 8366 if (mWifiInfo.txSuccessRate > 8367 mWifiConfigStore.maxTxPacketForFullScans 8368 || mWifiInfo.rxSuccessRate > 8369 mWifiConfigStore.maxRxPacketForFullScans) { 8370 // Too much traffic at the interface, hence no full band scan 8371 if (DBG) { 8372 logd("CMD_START_SCAN " + 8373 "prevent full band scan due to pkt rate"); 8374 } 8375 tryFullBandScan = false; 8376 } 8377 8378 if (mWifiInfo.txSuccessRate > 8379 mWifiConfigStore.maxTxPacketForPartialScans 8380 || mWifiInfo.rxSuccessRate > 8381 mWifiConfigStore.maxRxPacketForPartialScans) { 8382 // Don't scan if lots of packets are being sent 8383 restrictChannelList = true; 8384 if (mWifiConfigStore.alwaysEnableScansWhileAssociated.get() == 0) { 8385 if (DBG) { 8386 logd("CMD_START_SCAN source " + message.arg1 8387 + " ...and ignore scans" 8388 + " tx=" + String.format("%.2f", mWifiInfo.txSuccessRate) 8389 + " rx=" + String.format("%.2f", mWifiInfo.rxSuccessRate)); 8390 } 8391 messageHandlingStatus = MESSAGE_HANDLING_STATUS_REFUSED; 8392 return HANDLED; 8393 } 8394 } 8395 } 8396 8397 WifiConfiguration currentConfiguration = getCurrentWifiConfiguration(); 8398 if (DBG) { 8399 logd("CMD_START_SCAN full=" + 8400 tryFullBandScan); 8401 } 8402 if (currentConfiguration != null) { 8403 if (fullBandConnectedTimeIntervalMilli 8404 < mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get()) { 8405 // Sanity 8406 fullBandConnectedTimeIntervalMilli 8407 = mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(); 8408 } 8409 if (tryFullBandScan) { 8410 lastFullBandConnectedTimeMilli = now_ms; 8411 if (fullBandConnectedTimeIntervalMilli 8412 < mWifiConfigStore.associatedFullScanMaxIntervalMilli) { 8413 // Increase the interval 8414 fullBandConnectedTimeIntervalMilli 8415 = fullBandConnectedTimeIntervalMilli 8416 * mWifiConfigStore.associatedFullScanBackoff.get() / 8; 8417 8418 if (DBG) { 8419 logd("CMD_START_SCAN bump interval =" 8420 + fullBandConnectedTimeIntervalMilli); 8421 } 8422 } 8423 handleScanRequest( 8424 WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message); 8425 } else { 8426 if (!startScanForConfiguration( 8427 currentConfiguration, restrictChannelList)) { 8428 if (DBG) { 8429 logd("starting scan, " + 8430 " did not find channels -> full"); 8431 } 8432 lastFullBandConnectedTimeMilli = now_ms; 8433 if (fullBandConnectedTimeIntervalMilli 8434 < mWifiConfigStore.associatedFullScanMaxIntervalMilli) { 8435 // Increase the interval 8436 fullBandConnectedTimeIntervalMilli 8437 = fullBandConnectedTimeIntervalMilli 8438 * mWifiConfigStore.associatedFullScanBackoff.get() / 8; 8439 8440 if (DBG) { 8441 logd("CMD_START_SCAN bump interval =" 8442 + fullBandConnectedTimeIntervalMilli); 8443 } 8444 } 8445 handleScanRequest( 8446 WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message); 8447 } 8448 } 8449 8450 } else { 8451 logd("CMD_START_SCAN : connected mode and no configuration"); 8452 messageHandlingStatus = MESSAGE_HANDLING_STATUS_HANDLING_ERROR; 8453 } 8454 } else { 8455 // Not scan alarm source 8456 return NOT_HANDLED; 8457 } 8458 break; 8459 /* Ignore connection to same network */ 8460 case WifiManager.CONNECT_NETWORK: 8461 int netId = message.arg1; 8462 if (mWifiInfo.getNetworkId() == netId) { 8463 break; 8464 } 8465 return NOT_HANDLED; 8466 case WifiMonitor.NETWORK_CONNECTION_EVENT: 8467 mWifiInfo.setBSSID((String) message.obj); 8468 mLastNetworkId = message.arg1; 8469 mWifiInfo.setNetworkId(mLastNetworkId); 8470 if(!mLastBssid.equals((String) message.obj)) { 8471 mLastBssid = (String) message.obj; 8472 sendNetworkStateChangeBroadcast(mLastBssid); 8473 } 8474 break; 8475 case CMD_RSSI_POLL: 8476 if (message.arg1 == mRssiPollToken) { 8477 if (mWifiConfigStore.enableChipWakeUpWhenAssociated.get()) { 8478 if (VVDBG) log(" get link layer stats " + mWifiLinkLayerStatsSupported); 8479 WifiLinkLayerStats stats = getWifiLinkLayerStats(VDBG); 8480 if (stats != null) { 8481 // Sanity check the results provided by driver 8482 if (mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI 8483 && (stats.rssi_mgmt == 0 8484 || stats.beacon_rx == 0)) { 8485 stats = null; 8486 } 8487 } 8488 // Get Info and continue polling 8489 fetchRssiLinkSpeedAndFrequencyNative(); 8490 calculateWifiScore(stats); 8491 } 8492 sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, 8493 mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS); 8494 8495 if (DBG) sendRssiChangeBroadcast(mWifiInfo.getRssi()); 8496 } else { 8497 // Polling has completed 8498 } 8499 break; 8500 case CMD_ENABLE_RSSI_POLL: 8501 cleanWifiScore(); 8502 if (mWifiConfigStore.enableRssiPollWhenAssociated.get()) { 8503 mEnableRssiPolling = (message.arg1 == 1); 8504 } else { 8505 mEnableRssiPolling = false; 8506 } 8507 mRssiPollToken++; 8508 if (mEnableRssiPolling) { 8509 // First poll 8510 fetchRssiLinkSpeedAndFrequencyNative(); 8511 sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, 8512 mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS); 8513 } 8514 break; 8515 case WifiManager.RSSI_PKTCNT_FETCH: 8516 RssiPacketCountInfo info = new RssiPacketCountInfo(); 8517 fetchRssiLinkSpeedAndFrequencyNative(); 8518 info.rssi = mWifiInfo.getRssi(); 8519 fetchPktcntNative(info); 8520 replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED, info); 8521 break; 8522 case CMD_DELAYED_NETWORK_DISCONNECT: 8523 if (!linkDebouncing && mWifiConfigStore.enableLinkDebouncing) { 8524 8525 // Ignore if we are not debouncing 8526 logd("CMD_DELAYED_NETWORK_DISCONNECT and not debouncing - ignore " 8527 + message.arg1); 8528 return HANDLED; 8529 } else { 8530 logd("CMD_DELAYED_NETWORK_DISCONNECT and debouncing - disconnect " 8531 + message.arg1); 8532 8533 linkDebouncing = false; 8534 // If we are still debouncing while this message comes, 8535 // it means we were not able to reconnect within the alloted time 8536 // = LINK_FLAPPING_DEBOUNCE_MSEC 8537 // and thus, trigger a real disconnect 8538 handleNetworkDisconnect(); 8539 transitionTo(mDisconnectedState); 8540 } 8541 break; 8542 case CMD_ASSOCIATED_BSSID: 8543 if ((String) message.obj == null) { 8544 logw("Associated command w/o BSSID"); 8545 break; 8546 } 8547 mLastBssid = (String) message.obj; 8548 if (mLastBssid != null 8549 && (mWifiInfo.getBSSID() == null 8550 || !mLastBssid.equals(mWifiInfo.getBSSID()))) { 8551 mWifiInfo.setBSSID((String) message.obj); 8552 sendNetworkStateChangeBroadcast(mLastBssid); 8553 } 8554 break; 8555 case CMD_START_RSSI_MONITORING_OFFLOAD: 8556 case CMD_RSSI_THRESHOLD_BREACH: 8557 byte currRssi = (byte) message.arg1; 8558 processRssiThreshold(currRssi, message.what); 8559 break; 8560 case CMD_STOP_RSSI_MONITORING_OFFLOAD: 8561 stopRssiMonitoringOffload(); 8562 break; 8563 default: 8564 return NOT_HANDLED; 8565 } 8566 8567 return HANDLED; 8568 } 8569 } 8570 8571 class ObtainingIpState extends State { 8572 @Override 8573 public void enter() { 8574 if (DBG) { 8575 String key = ""; 8576 if (getCurrentWifiConfiguration() != null) { 8577 key = getCurrentWifiConfiguration().configKey(); 8578 } 8579 log("enter ObtainingIpState netId=" + Integer.toString(mLastNetworkId) 8580 + " " + key + " " 8581 + " roam=" + mAutoRoaming 8582 + " static=" + mWifiConfigStore.isUsingStaticIp(mLastNetworkId) 8583 + " watchdog= " + obtainingIpWatchdogCount); 8584 } 8585 8586 // Reset link Debouncing, indicating we have successfully re-connected to the AP 8587 // We might still be roaming 8588 linkDebouncing = false; 8589 8590 // Send event to CM & network change broadcast 8591 setNetworkDetailedState(DetailedState.OBTAINING_IPADDR); 8592 8593 // We must clear the config BSSID, as the wifi chipset may decide to roam 8594 // from this point on and having the BSSID specified in the network block would 8595 // cause the roam to faile and the device to disconnect 8596 clearCurrentConfigBSSID("ObtainingIpAddress"); 8597 8598 try { 8599 mNwService.enableIpv6(mInterfaceName); 8600 } catch (RemoteException re) { 8601 loge("Failed to enable IPv6: " + re); 8602 } catch (IllegalStateException e) { 8603 loge("Failed to enable IPv6: " + e); 8604 } 8605 8606 if (!mWifiConfigStore.isUsingStaticIp(mLastNetworkId)) { 8607 if (isRoaming()) { 8608 renewDhcp(); 8609 } else { 8610 // Remove any IP address on the interface in case we're switching from static 8611 // IP configuration to DHCP. This is safe because if we get here when not 8612 // roaming, we don't have a usable address. 8613 clearIPv4Address(mInterfaceName); 8614 startDhcp(); 8615 } 8616 obtainingIpWatchdogCount++; 8617 logd("Start Dhcp Watchdog " + obtainingIpWatchdogCount); 8618 // Get Link layer stats so as we get fresh tx packet counters 8619 getWifiLinkLayerStats(true); 8620 sendMessageDelayed(obtainMessage(CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER, 8621 obtainingIpWatchdogCount, 0), OBTAINING_IP_ADDRESS_GUARD_TIMER_MSEC); 8622 } else { 8623 // stop any running dhcp before assigning static IP 8624 stopDhcp(); 8625 StaticIpConfiguration config = mWifiConfigStore.getStaticIpConfiguration( 8626 mLastNetworkId); 8627 if (config.ipAddress == null) { 8628 logd("Static IP lacks address"); 8629 sendMessage(CMD_STATIC_IP_FAILURE); 8630 } else { 8631 InterfaceConfiguration ifcg = new InterfaceConfiguration(); 8632 ifcg.setLinkAddress(config.ipAddress); 8633 ifcg.setInterfaceUp(); 8634 try { 8635 mNwService.setInterfaceConfig(mInterfaceName, ifcg); 8636 if (DBG) log("Static IP configuration succeeded"); 8637 DhcpResults dhcpResults = new DhcpResults(config); 8638 sendMessage(CMD_STATIC_IP_SUCCESS, dhcpResults); 8639 } catch (RemoteException re) { 8640 loge("Static IP configuration failed: " + re); 8641 sendMessage(CMD_STATIC_IP_FAILURE); 8642 } catch (IllegalStateException e) { 8643 loge("Static IP configuration failed: " + e); 8644 sendMessage(CMD_STATIC_IP_FAILURE); 8645 } 8646 } 8647 } 8648 } 8649 @Override 8650 public boolean processMessage(Message message) { 8651 logStateAndMessage(message, getClass().getSimpleName()); 8652 8653 switch(message.what) { 8654 case CMD_STATIC_IP_SUCCESS: 8655 handleIPv4Success((DhcpResults) message.obj, CMD_STATIC_IP_SUCCESS); 8656 break; 8657 case CMD_STATIC_IP_FAILURE: 8658 handleIPv4Failure(CMD_STATIC_IP_FAILURE); 8659 break; 8660 case CMD_AUTO_CONNECT: 8661 case CMD_AUTO_ROAM: 8662 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8663 break; 8664 case WifiManager.SAVE_NETWORK: 8665 case WifiStateMachine.CMD_AUTO_SAVE_NETWORK: 8666 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 8667 deferMessage(message); 8668 break; 8669 /* Defer any power mode changes since we must keep active power mode at DHCP */ 8670 case CMD_SET_HIGH_PERF_MODE: 8671 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 8672 deferMessage(message); 8673 break; 8674 /* Defer scan request since we should not switch to other channels at DHCP */ 8675 case CMD_START_SCAN: 8676 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 8677 deferMessage(message); 8678 break; 8679 case CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER: 8680 if (message.arg1 == obtainingIpWatchdogCount) { 8681 logd("ObtainingIpAddress: Watchdog Triggered, count=" 8682 + obtainingIpWatchdogCount); 8683 handleIpConfigurationLost(); 8684 transitionTo(mDisconnectingState); 8685 break; 8686 } 8687 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8688 break; 8689 default: 8690 return NOT_HANDLED; 8691 } 8692 return HANDLED; 8693 } 8694 } 8695 8696 // Note: currently, this state is never used, because WifiWatchdogStateMachine unconditionally 8697 // sets mPoorNetworkDetectionEnabled to false. 8698 class VerifyingLinkState extends State { 8699 @Override 8700 public void enter() { 8701 log(getName() + " enter"); 8702 setNetworkDetailedState(DetailedState.VERIFYING_POOR_LINK); 8703 mWifiConfigStore.updateStatus(mLastNetworkId, DetailedState.VERIFYING_POOR_LINK); 8704 sendNetworkStateChangeBroadcast(mLastBssid); 8705 // End roaming 8706 mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE; 8707 } 8708 @Override 8709 public boolean processMessage(Message message) { 8710 logStateAndMessage(message, getClass().getSimpleName()); 8711 8712 switch (message.what) { 8713 case WifiWatchdogStateMachine.POOR_LINK_DETECTED: 8714 // Stay here 8715 log(getName() + " POOR_LINK_DETECTED: no transition"); 8716 break; 8717 case WifiWatchdogStateMachine.GOOD_LINK_DETECTED: 8718 log(getName() + " GOOD_LINK_DETECTED: transition to CONNECTED"); 8719 sendConnectedState(); 8720 transitionTo(mConnectedState); 8721 break; 8722 default: 8723 if (DBG) log(getName() + " what=" + message.what + " NOT_HANDLED"); 8724 return NOT_HANDLED; 8725 } 8726 return HANDLED; 8727 } 8728 } 8729 8730 private void sendConnectedState() { 8731 // If this network was explicitly selected by the user, evaluate whether to call 8732 // explicitlySelected() so the system can treat it appropriately. 8733 WifiConfiguration config = getCurrentWifiConfiguration(); 8734 if (mWifiConfigStore.isLastSelectedConfiguration(config)) { 8735 boolean prompt = mWifiConfigStore.checkConfigOverridePermission(config.lastConnectUid); 8736 if (DBG) { 8737 log("Network selected by UID " + config.lastConnectUid + " prompt=" + prompt); 8738 } 8739 if (prompt) { 8740 // Selected by the user via Settings or QuickSettings. If this network has Internet 8741 // access, switch to it. Otherwise, switch to it only if the user confirms that they 8742 // really want to switch, or has already confirmed and selected "Don't ask again". 8743 if (DBG) { 8744 log("explictlySelected acceptUnvalidated=" + config.noInternetAccessExpected); 8745 } 8746 mNetworkAgent.explicitlySelected(config.noInternetAccessExpected); 8747 } 8748 } 8749 8750 setNetworkDetailedState(DetailedState.CONNECTED); 8751 mWifiConfigStore.updateStatus(mLastNetworkId, DetailedState.CONNECTED); 8752 sendNetworkStateChangeBroadcast(mLastBssid); 8753 } 8754 8755 class RoamingState extends State { 8756 boolean mAssociated; 8757 @Override 8758 public void enter() { 8759 if (DBG) { 8760 log("RoamingState Enter" 8761 + " mScreenOn=" + mScreenOn ); 8762 } 8763 setScanAlarm(false); 8764 8765 // Make sure we disconnect if roaming fails 8766 roamWatchdogCount++; 8767 logd("Start Roam Watchdog " + roamWatchdogCount); 8768 sendMessageDelayed(obtainMessage(CMD_ROAM_WATCHDOG_TIMER, 8769 roamWatchdogCount, 0), ROAM_GUARD_TIMER_MSEC); 8770 mAssociated = false; 8771 } 8772 @Override 8773 public boolean processMessage(Message message) { 8774 logStateAndMessage(message, getClass().getSimpleName()); 8775 WifiConfiguration config; 8776 switch (message.what) { 8777 case CMD_IP_CONFIGURATION_LOST: 8778 config = getCurrentWifiConfiguration(); 8779 if (config != null) { 8780 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_AUTOROAM_FAILURE); 8781 mWifiConfigStore.noteRoamingFailure(config, 8782 WifiConfiguration.ROAMING_FAILURE_IP_CONFIG); 8783 } 8784 return NOT_HANDLED; 8785 case WifiWatchdogStateMachine.POOR_LINK_DETECTED: 8786 if (DBG) log("Roaming and Watchdog reports poor link -> ignore"); 8787 return HANDLED; 8788 case CMD_UNWANTED_NETWORK: 8789 if (DBG) log("Roaming and CS doesnt want the network -> ignore"); 8790 return HANDLED; 8791 case CMD_SET_OPERATIONAL_MODE: 8792 if (message.arg1 != CONNECT_MODE) { 8793 deferMessage(message); 8794 } 8795 break; 8796 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 8797 /** 8798 * If we get a SUPPLICANT_STATE_CHANGE_EVENT indicating a DISCONNECT 8799 * before NETWORK_DISCONNECTION_EVENT 8800 * And there is an associated BSSID corresponding to our target BSSID, then 8801 * we have missed the network disconnection, transition to mDisconnectedState 8802 * and handle the rest of the events there. 8803 */ 8804 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 8805 if (stateChangeResult.state == SupplicantState.DISCONNECTED 8806 || stateChangeResult.state == SupplicantState.INACTIVE 8807 || stateChangeResult.state == SupplicantState.INTERFACE_DISABLED) { 8808 if (DBG) { 8809 log("STATE_CHANGE_EVENT in roaming state " 8810 + stateChangeResult.toString() ); 8811 } 8812 if (stateChangeResult.BSSID != null 8813 && stateChangeResult.BSSID.equals(mTargetRoamBSSID)) { 8814 handleNetworkDisconnect(); 8815 transitionTo(mDisconnectedState); 8816 } 8817 } 8818 if (stateChangeResult.state == SupplicantState.ASSOCIATED) { 8819 // We completed the layer2 roaming part 8820 mAssociated = true; 8821 if (stateChangeResult.BSSID != null) { 8822 mTargetRoamBSSID = (String) stateChangeResult.BSSID; 8823 } 8824 } 8825 break; 8826 case CMD_ROAM_WATCHDOG_TIMER: 8827 if (roamWatchdogCount == message.arg1) { 8828 if (DBG) log("roaming watchdog! -> disconnect"); 8829 mRoamFailCount++; 8830 handleNetworkDisconnect(); 8831 mWifiNative.disconnect(); 8832 transitionTo(mDisconnectedState); 8833 } 8834 break; 8835 case WifiMonitor.NETWORK_CONNECTION_EVENT: 8836 if (mAssociated) { 8837 if (DBG) log("roaming and Network connection established"); 8838 mLastNetworkId = message.arg1; 8839 mLastBssid = (String) message.obj; 8840 mWifiInfo.setBSSID(mLastBssid); 8841 mWifiInfo.setNetworkId(mLastNetworkId); 8842 mWifiConfigStore.handleBSSIDBlackList(mLastNetworkId, mLastBssid, true); 8843 sendNetworkStateChangeBroadcast(mLastBssid); 8844 transitionTo(mObtainingIpState); 8845 } else { 8846 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8847 } 8848 break; 8849 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 8850 // Throw away but only if it corresponds to the network we're roaming to 8851 String bssid = (String)message.obj; 8852 if (true) { 8853 String target = ""; 8854 if (mTargetRoamBSSID != null) target = mTargetRoamBSSID; 8855 log("NETWORK_DISCONNECTION_EVENT in roaming state" 8856 + " BSSID=" + bssid 8857 + " target=" + target); 8858 } 8859 if (bssid != null && bssid.equals(mTargetRoamBSSID)) { 8860 handleNetworkDisconnect(); 8861 transitionTo(mDisconnectedState); 8862 } 8863 break; 8864 case WifiMonitor.SSID_TEMP_DISABLED: 8865 // Auth error while roaming 8866 logd("SSID_TEMP_DISABLED nid=" + Integer.toString(mLastNetworkId) 8867 + " id=" + Integer.toString(message.arg1) 8868 + " isRoaming=" + isRoaming() 8869 + " roam=" + Integer.toString(mAutoRoaming)); 8870 if (message.arg1 == mLastNetworkId) { 8871 config = getCurrentWifiConfiguration(); 8872 if (config != null) { 8873 mWifiLogger.captureBugReportData( 8874 WifiLogger.REPORT_REASON_AUTOROAM_FAILURE); 8875 mWifiConfigStore.noteRoamingFailure(config, 8876 WifiConfiguration.ROAMING_FAILURE_AUTH_FAILURE); 8877 } 8878 handleNetworkDisconnect(); 8879 transitionTo(mDisconnectingState); 8880 } 8881 return NOT_HANDLED; 8882 case CMD_START_SCAN: 8883 deferMessage(message); 8884 break; 8885 default: 8886 return NOT_HANDLED; 8887 } 8888 return HANDLED; 8889 } 8890 8891 @Override 8892 public void exit() { 8893 logd("WifiStateMachine: Leaving Roaming state"); 8894 } 8895 } 8896 8897 class ConnectedState extends State { 8898 @Override 8899 public void enter() { 8900 String address; 8901 updateDefaultRouteMacAddress(1000); 8902 if (DBG) { 8903 log("Enter ConnectedState " 8904 + " mScreenOn=" + mScreenOn 8905 + " scanperiod=" 8906 + Integer.toString(mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get()) 8907 + " useGscan=" + mHalBasedPnoDriverSupported + "/" 8908 + mWifiConfigStore.enableHalBasedPno.get() 8909 + " mHalBasedPnoEnableInDevSettings " + mHalBasedPnoEnableInDevSettings); 8910 } 8911 if (mScreenOn 8912 && getEnableAutoJoinWhenAssociated()) { 8913 if (useHalBasedAutoJoinOffload()) { 8914 startGScanConnectedModeOffload("connectedEnter"); 8915 } else { 8916 // restart scan alarm 8917 startDelayedScan(mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(), 8918 null, null); 8919 } 8920 } 8921 registerConnected(); 8922 lastConnectAttemptTimestamp = 0; 8923 targetWificonfiguration = null; 8924 // Paranoia 8925 linkDebouncing = false; 8926 8927 // Not roaming anymore 8928 mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE; 8929 8930 if (testNetworkDisconnect) { 8931 testNetworkDisconnectCounter++; 8932 logd("ConnectedState Enter start disconnect test " + 8933 testNetworkDisconnectCounter); 8934 sendMessageDelayed(obtainMessage(CMD_TEST_NETWORK_DISCONNECT, 8935 testNetworkDisconnectCounter, 0), 15000); 8936 } 8937 8938 // Reenable all networks, allow for hidden networks to be scanned 8939 mWifiConfigStore.enableAllNetworks(); 8940 8941 mLastDriverRoamAttempt = 0; 8942 8943 //startLazyRoam(); 8944 } 8945 @Override 8946 public boolean processMessage(Message message) { 8947 WifiConfiguration config = null; 8948 logStateAndMessage(message, getClass().getSimpleName()); 8949 8950 switch (message.what) { 8951 case CMD_RESTART_AUTOJOIN_OFFLOAD: 8952 if ( (int)message.arg2 < mRestartAutoJoinOffloadCounter ) { 8953 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 8954 return HANDLED; 8955 } 8956 /* If we are still in Disconnected state after having discovered a valid 8957 * network this means autojoin didnt managed to associate to the network, 8958 * then restart PNO so as we will try associating to it again. 8959 */ 8960 if (useHalBasedAutoJoinOffload()) { 8961 if (mGScanStartTimeMilli == 0) { 8962 // If offload is not started, then start it... 8963 startGScanConnectedModeOffload("connectedRestart"); 8964 } else { 8965 // If offload is already started, then check if we need to increase 8966 // the scan period and restart the Gscan 8967 long now = System.currentTimeMillis(); 8968 if (mGScanStartTimeMilli != 0 && now > mGScanStartTimeMilli 8969 && ((now - mGScanStartTimeMilli) 8970 > DISCONNECTED_SHORT_SCANS_DURATION_MILLI) 8971 && (mGScanPeriodMilli 8972 < mWifiConfigStore.wifiDisconnectedLongScanIntervalMilli.get())) 8973 { 8974 startConnectedGScan("Connected restart gscan"); 8975 } 8976 } 8977 } 8978 break; 8979 case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION: 8980 updateAssociatedScanPermission(); 8981 break; 8982 case WifiWatchdogStateMachine.POOR_LINK_DETECTED: 8983 if (DBG) log("Watchdog reports poor link"); 8984 transitionTo(mVerifyingLinkState); 8985 break; 8986 case CMD_UNWANTED_NETWORK: 8987 if (message.arg1 == NETWORK_STATUS_UNWANTED_DISCONNECT) { 8988 mWifiConfigStore.handleBadNetworkDisconnectReport(mLastNetworkId, mWifiInfo); 8989 mWifiNative.disconnect(); 8990 transitionTo(mDisconnectingState); 8991 } else if (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN || 8992 message.arg1 == NETWORK_STATUS_UNWANTED_VALIDATION_FAILED) { 8993 config = getCurrentWifiConfiguration(); 8994 if (config != null) { 8995 // Disable autojoin 8996 if (message.arg1 == NETWORK_STATUS_UNWANTED_DISABLE_AUTOJOIN) { 8997 config.validatedInternetAccess = false; 8998 // Clear last-selected status, as being last-selected also avoids 8999 // disabling auto-join. 9000 if (mWifiConfigStore.isLastSelectedConfiguration(config)) { 9001 mWifiConfigStore.setLastSelectedConfiguration( 9002 WifiConfiguration.INVALID_NETWORK_ID); 9003 } 9004 } 9005 config.numNoInternetAccessReports += 1; 9006 config.dirty = true; 9007 mWifiConfigStore.writeKnownNetworkHistory(false); 9008 } 9009 } 9010 return HANDLED; 9011 case CMD_NETWORK_STATUS: 9012 if (message.arg1 == NetworkAgent.VALID_NETWORK) { 9013 config = getCurrentWifiConfiguration(); 9014 if (config != null) { 9015 if (!config.validatedInternetAccess 9016 || config.numNoInternetAccessReports != 0) { 9017 config.dirty = true; 9018 } 9019 // re-enable autojoin 9020 config.numNoInternetAccessReports = 0; 9021 config.validatedInternetAccess = true; 9022 mWifiConfigStore.writeKnownNetworkHistory(false); 9023 } 9024 } 9025 return HANDLED; 9026 case CMD_ACCEPT_UNVALIDATED: 9027 boolean accept = (message.arg1 != 0); 9028 config = getCurrentWifiConfiguration(); 9029 if (config != null) { 9030 config.noInternetAccessExpected = accept; 9031 } 9032 return HANDLED; 9033 case CMD_TEST_NETWORK_DISCONNECT: 9034 // Force a disconnect 9035 if (message.arg1 == testNetworkDisconnectCounter) { 9036 mWifiNative.disconnect(); 9037 } 9038 break; 9039 case CMD_ASSOCIATED_BSSID: 9040 // ASSOCIATING to a new BSSID while already connected, indicates 9041 // that driver is roaming 9042 mLastDriverRoamAttempt = System.currentTimeMillis(); 9043 String toBSSID = (String)message.obj; 9044 if (toBSSID != null && !toBSSID.equals(mWifiInfo.getBSSID())) { 9045 mWifiConfigStore.driverRoamedFrom(mWifiInfo); 9046 } 9047 return NOT_HANDLED; 9048 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 9049 long lastRoam = 0; 9050 if (mLastDriverRoamAttempt != 0) { 9051 // Calculate time since last driver roam attempt 9052 lastRoam = System.currentTimeMillis() - mLastDriverRoamAttempt; 9053 mLastDriverRoamAttempt = 0; 9054 } 9055 if (unexpectedDisconnectedReason(message.arg2)) { 9056 mWifiLogger.captureBugReportData( 9057 WifiLogger.REPORT_REASON_UNEXPECTED_DISCONNECT); 9058 } 9059 config = getCurrentWifiConfiguration(); 9060 if (mScreenOn 9061 && !linkDebouncing 9062 && config != null 9063 && config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_ENABLED 9064 && !mWifiConfigStore.isLastSelectedConfiguration(config) 9065 && (message.arg2 != 3 /* reason cannot be 3, i.e. locally generated */ 9066 || (lastRoam > 0 && lastRoam < 2000) /* unless driver is roaming */) 9067 && ((ScanResult.is24GHz(mWifiInfo.getFrequency()) 9068 && mWifiInfo.getRssi() > 9069 WifiConfiguration.BAD_RSSI_24) 9070 || (ScanResult.is5GHz(mWifiInfo.getFrequency()) 9071 && mWifiInfo.getRssi() > 9072 WifiConfiguration.BAD_RSSI_5))) { 9073 // Start de-bouncing the L2 disconnection: 9074 // this L2 disconnection might be spurious. 9075 // Hence we allow 7 seconds for the state machine to try 9076 // to reconnect, go thru the 9077 // roaming cycle and enter Obtaining IP address 9078 // before signalling the disconnect to ConnectivityService and L3 9079 startScanForConfiguration(getCurrentWifiConfiguration(), false); 9080 linkDebouncing = true; 9081 9082 sendMessageDelayed(obtainMessage(CMD_DELAYED_NETWORK_DISCONNECT, 9083 0, mLastNetworkId), LINK_FLAPPING_DEBOUNCE_MSEC); 9084 if (DBG) { 9085 log("NETWORK_DISCONNECTION_EVENT in connected state" 9086 + " BSSID=" + mWifiInfo.getBSSID() 9087 + " RSSI=" + mWifiInfo.getRssi() 9088 + " freq=" + mWifiInfo.getFrequency() 9089 + " reason=" + message.arg2 9090 + " -> debounce"); 9091 } 9092 return HANDLED; 9093 } else { 9094 if (DBG) { 9095 int ajst = -1; 9096 if (config != null) ajst = config.autoJoinStatus; 9097 log("NETWORK_DISCONNECTION_EVENT in connected state" 9098 + " BSSID=" + mWifiInfo.getBSSID() 9099 + " RSSI=" + mWifiInfo.getRssi() 9100 + " freq=" + mWifiInfo.getFrequency() 9101 + " was debouncing=" + linkDebouncing 9102 + " reason=" + message.arg2 9103 + " ajst=" + ajst); 9104 } 9105 } 9106 break; 9107 case CMD_AUTO_ROAM: 9108 // Clear the driver roam indication since we are attempting a framework roam 9109 mLastDriverRoamAttempt = 0; 9110 9111 /* Connect command coming from auto-join */ 9112 ScanResult candidate = (ScanResult)message.obj; 9113 String bssid = "any"; 9114 if (candidate != null && candidate.is5GHz()) { 9115 // Only lock BSSID for 5GHz networks 9116 bssid = candidate.BSSID; 9117 } 9118 int netId = mLastNetworkId; 9119 config = getCurrentWifiConfiguration(); 9120 9121 9122 if (config == null) { 9123 loge("AUTO_ROAM and no config, bail out..."); 9124 break; 9125 } 9126 9127 logd("CMD_AUTO_ROAM sup state " 9128 + mSupplicantStateTracker.getSupplicantStateName() 9129 + " my state " + getCurrentState().getName() 9130 + " nid=" + Integer.toString(netId) 9131 + " config " + config.configKey() 9132 + " roam=" + Integer.toString(message.arg2) 9133 + " to " + bssid 9134 + " targetRoamBSSID " + mTargetRoamBSSID); 9135 9136 /* Save the BSSID so as to lock it @ firmware */ 9137 if (!autoRoamSetBSSID(config, bssid) && !linkDebouncing) { 9138 logd("AUTO_ROAM nothing to do"); 9139 // Same BSSID, nothing to do 9140 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 9141 break; 9142 }; 9143 9144 // Make sure the network is enabled, since supplicant will not re-enable it 9145 mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false); 9146 9147 if (deferForUserInput(message, netId, false)) { 9148 break; 9149 } else if (mWifiConfigStore.getWifiConfiguration(netId).userApproved == 9150 WifiConfiguration.USER_BANNED) { 9151 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 9152 WifiManager.NOT_AUTHORIZED); 9153 break; 9154 } 9155 9156 boolean ret = false; 9157 if (mLastNetworkId != netId) { 9158 if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ false, 9159 WifiConfiguration.UNKNOWN_UID) && mWifiNative.reconnect()) { 9160 ret = true; 9161 } 9162 } else { 9163 ret = mWifiNative.reassociate(); 9164 } 9165 if (ret) { 9166 lastConnectAttemptTimestamp = System.currentTimeMillis(); 9167 targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId); 9168 9169 // replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED); 9170 mAutoRoaming = message.arg2; 9171 transitionTo(mRoamingState); 9172 9173 } else { 9174 loge("Failed to connect config: " + config + " netId: " + netId); 9175 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 9176 WifiManager.ERROR); 9177 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 9178 break; 9179 } 9180 break; 9181 case CMD_START_IP_PACKET_OFFLOAD: { 9182 int slot = message.arg1; 9183 int intervalSeconds = message.arg2; 9184 KeepalivePacketData pkt = (KeepalivePacketData) message.obj; 9185 byte[] dstMac; 9186 try { 9187 InetAddress gateway = RouteInfo.selectBestRoute( 9188 mLinkProperties.getRoutes(), pkt.dstAddress).getGateway(); 9189 String dstMacStr = macAddressFromRoute(gateway.getHostAddress()); 9190 dstMac = macAddressFromString(dstMacStr); 9191 } catch (NullPointerException|IllegalArgumentException e) { 9192 loge("Can't find MAC address for next hop to " + pkt.dstAddress); 9193 mNetworkAgent.onPacketKeepaliveEvent(slot, 9194 ConnectivityManager.PacketKeepalive.ERROR_INVALID_IP_ADDRESS); 9195 break; 9196 } 9197 pkt.dstMac = dstMac; 9198 int result = startWifiIPPacketOffload(slot, pkt, intervalSeconds); 9199 mNetworkAgent.onPacketKeepaliveEvent(slot, result); 9200 break; 9201 } 9202 default: 9203 return NOT_HANDLED; 9204 } 9205 return HANDLED; 9206 } 9207 9208 @Override 9209 public void exit() { 9210 logd("WifiStateMachine: Leaving Connected state"); 9211 setScanAlarm(false); 9212 mLastDriverRoamAttempt = 0; 9213 9214 stopLazyRoam(); 9215 9216 mWhiteListedSsids = null; 9217 } 9218 } 9219 9220 class DisconnectingState extends State { 9221 9222 @Override 9223 public void enter() { 9224 9225 if (PDBG) { 9226 logd(" Enter DisconnectingState State scan interval " 9227 + mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get() 9228 + " mLegacyPnoEnabled= " + mLegacyPnoEnabled 9229 + " screenOn=" + mScreenOn); 9230 } 9231 9232 // Make sure we disconnect: we enter this state prior to connecting to a new 9233 // network, waiting for either a DISCONNECT event or a SUPPLICANT_STATE_CHANGE 9234 // event which in this case will be indicating that supplicant started to associate. 9235 // In some cases supplicant doesn't ignore the connect requests (it might not 9236 // find the target SSID in its cache), 9237 // Therefore we end up stuck that state, hence the need for the watchdog. 9238 disconnectingWatchdogCount++; 9239 logd("Start Disconnecting Watchdog " + disconnectingWatchdogCount); 9240 sendMessageDelayed(obtainMessage(CMD_DISCONNECTING_WATCHDOG_TIMER, 9241 disconnectingWatchdogCount, 0), DISCONNECTING_GUARD_TIMER_MSEC); 9242 } 9243 9244 @Override 9245 public boolean processMessage(Message message) { 9246 logStateAndMessage(message, getClass().getSimpleName()); 9247 switch (message.what) { 9248 case CMD_SET_OPERATIONAL_MODE: 9249 if (message.arg1 != CONNECT_MODE) { 9250 deferMessage(message); 9251 } 9252 break; 9253 case CMD_START_SCAN: 9254 deferMessage(message); 9255 return HANDLED; 9256 case CMD_DISCONNECTING_WATCHDOG_TIMER: 9257 if (disconnectingWatchdogCount == message.arg1) { 9258 if (DBG) log("disconnecting watchdog! -> disconnect"); 9259 handleNetworkDisconnect(); 9260 transitionTo(mDisconnectedState); 9261 } 9262 break; 9263 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 9264 /** 9265 * If we get a SUPPLICANT_STATE_CHANGE_EVENT before NETWORK_DISCONNECTION_EVENT 9266 * we have missed the network disconnection, transition to mDisconnectedState 9267 * and handle the rest of the events there 9268 */ 9269 deferMessage(message); 9270 handleNetworkDisconnect(); 9271 transitionTo(mDisconnectedState); 9272 break; 9273 default: 9274 return NOT_HANDLED; 9275 } 9276 return HANDLED; 9277 } 9278 } 9279 9280 class DisconnectedState extends State { 9281 @Override 9282 public void enter() { 9283 // We dont scan frequently if this is a temporary disconnect 9284 // due to p2p 9285 if (mTemporarilyDisconnectWifi) { 9286 mWifiP2pChannel.sendMessage(WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE); 9287 return; 9288 } 9289 9290 if (PDBG) { 9291 logd(" Enter DisconnectedState scan interval " 9292 + mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get() 9293 + " mLegacyPnoEnabled= " + mLegacyPnoEnabled 9294 + " screenOn=" + mScreenOn 9295 + " useGscan=" + mHalBasedPnoDriverSupported + "/" 9296 + mWifiConfigStore.enableHalBasedPno.get()); 9297 } 9298 9299 /** clear the roaming state, if we were roaming, we failed */ 9300 mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE; 9301 9302 if (useHalBasedAutoJoinOffload()) { 9303 startGScanDisconnectedModeOffload("disconnectedEnter"); 9304 } else { 9305 if (mScreenOn) { 9306 /** 9307 * screen lit and => start scan immediately 9308 */ 9309 startScan(UNKNOWN_SCAN_SOURCE, 0, null, null); 9310 } else { 9311 /** 9312 * screen dark and PNO supported => scan alarm disabled 9313 */ 9314 if (mBackgroundScanSupported) { 9315 /* If a regular scan result is pending, do not initiate background 9316 * scan until the scan results are returned. This is needed because 9317 * initiating a background scan will cancel the regular scan and 9318 * scan results will not be returned until background scanning is 9319 * cleared 9320 */ 9321 if (!mIsScanOngoing) { 9322 enableBackgroundScan(true); 9323 } 9324 } else { 9325 setScanAlarm(true); 9326 } 9327 } 9328 } 9329 9330 /** 9331 * If we have no networks saved, the supplicant stops doing the periodic scan. 9332 * The scans are useful to notify the user of the presence of an open network. 9333 * Note that these are not wake up scans. 9334 */ 9335 if (mNoNetworksPeriodicScan != 0 && !mP2pConnected.get() 9336 && mWifiConfigStore.getConfiguredNetworks().size() == 0) { 9337 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 9338 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 9339 } 9340 9341 mDisconnectedTimeStamp = System.currentTimeMillis(); 9342 mDisconnectedPnoAlarmCount = 0; 9343 } 9344 @Override 9345 public boolean processMessage(Message message) { 9346 boolean ret = HANDLED; 9347 9348 logStateAndMessage(message, getClass().getSimpleName()); 9349 9350 switch (message.what) { 9351 case CMD_NO_NETWORKS_PERIODIC_SCAN: 9352 if (mP2pConnected.get()) break; 9353 if (mNoNetworksPeriodicScan != 0 && message.arg1 == mPeriodicScanToken && 9354 mWifiConfigStore.getConfiguredNetworks().size() == 0) { 9355 startScan(UNKNOWN_SCAN_SOURCE, -1, null, null); 9356 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 9357 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 9358 } 9359 break; 9360 case WifiManager.FORGET_NETWORK: 9361 case CMD_REMOVE_NETWORK: 9362 case CMD_REMOVE_APP_CONFIGURATIONS: 9363 case CMD_REMOVE_USER_CONFIGURATIONS: 9364 // Set up a delayed message here. After the forget/remove is handled 9365 // the handled delayed message will determine if there is a need to 9366 // scan and continue 9367 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 9368 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 9369 ret = NOT_HANDLED; 9370 break; 9371 case CMD_SET_OPERATIONAL_MODE: 9372 if (message.arg1 != CONNECT_MODE) { 9373 mOperationalMode = message.arg1; 9374 9375 mWifiConfigStore.disableAllNetworks(); 9376 if (mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 9377 mWifiP2pChannel.sendMessage(CMD_DISABLE_P2P_REQ); 9378 setWifiState(WIFI_STATE_DISABLED); 9379 } 9380 transitionTo(mScanModeState); 9381 } 9382 mWifiConfigStore. 9383 setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID); 9384 break; 9385 /* Ignore network disconnect */ 9386 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 9387 break; 9388 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 9389 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 9390 if (DBG) { 9391 logd("SUPPLICANT_STATE_CHANGE_EVENT state=" + stateChangeResult.state + 9392 " -> state= " + WifiInfo.getDetailedStateOf(stateChangeResult.state) 9393 + " debouncing=" + linkDebouncing); 9394 } 9395 setNetworkDetailedState(WifiInfo.getDetailedStateOf(stateChangeResult.state)); 9396 /* ConnectModeState does the rest of the handling */ 9397 ret = NOT_HANDLED; 9398 break; 9399 case CMD_START_SCAN: 9400 if (!checkOrDeferScanAllowed(message)) { 9401 // The scan request was rescheduled 9402 messageHandlingStatus = MESSAGE_HANDLING_STATUS_REFUSED; 9403 return HANDLED; 9404 } 9405 if (message.arg1 == SCAN_ALARM_SOURCE) { 9406 // Check if the CMD_START_SCAN message is obsolete (and thus if it should 9407 // not be processed) and restart the scan 9408 int period = mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get(); 9409 if (mP2pConnected.get()) { 9410 period = (int)Settings.Global.getLong(mContext.getContentResolver(), 9411 Settings.Global.WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS, 9412 period); 9413 } 9414 if (!checkAndRestartDelayedScan(message.arg2, 9415 true, period, null, null)) { 9416 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 9417 logd("Disconnected CMD_START_SCAN source " 9418 + message.arg1 9419 + " " + message.arg2 + ", " + mDelayedScanCounter 9420 + " -> obsolete"); 9421 return HANDLED; 9422 } 9423 /* Disable background scan temporarily during a regular scan */ 9424 enableBackgroundScan(false); 9425 handleScanRequest(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message); 9426 ret = HANDLED; 9427 } else { 9428 9429 /* 9430 * The SCAN request is not handled in this state and 9431 * would eventually might/will get handled in the 9432 * parent's state. The PNO, if already enabled had to 9433 * get disabled before the SCAN trigger. Hence, stop 9434 * the PNO if already enabled in this state, though the 9435 * SCAN request is not handled(PNO disable before the 9436 * SCAN trigger in any other state is not the right 9437 * place to issue). 9438 */ 9439 9440 enableBackgroundScan(false); 9441 ret = NOT_HANDLED; 9442 } 9443 break; 9444 case CMD_RESTART_AUTOJOIN_OFFLOAD: 9445 if ( (int)message.arg2 < mRestartAutoJoinOffloadCounter ) { 9446 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 9447 return HANDLED; 9448 } 9449 /* If we are still in Disconnected state after having discovered a valid 9450 * network this means autojoin didnt managed to associate to the network, 9451 * then restart PNO so as we will try associating to it again. 9452 */ 9453 if (useHalBasedAutoJoinOffload()) { 9454 if (mGScanStartTimeMilli == 0) { 9455 // If offload is not started, then start it... 9456 startGScanDisconnectedModeOffload("disconnectedRestart"); 9457 } else { 9458 // If offload is already started, then check if we need to increase 9459 // the scan period and restart the Gscan 9460 long now = System.currentTimeMillis(); 9461 if (mGScanStartTimeMilli != 0 && now > mGScanStartTimeMilli 9462 && ((now - mGScanStartTimeMilli) 9463 > DISCONNECTED_SHORT_SCANS_DURATION_MILLI) 9464 && (mGScanPeriodMilli 9465 < mWifiConfigStore.wifiDisconnectedLongScanIntervalMilli.get())) 9466 { 9467 startDisconnectedGScan("disconnected restart gscan"); 9468 } 9469 } 9470 } else { 9471 // If we are still disconnected for a short while after having found a 9472 // network thru PNO, then something went wrong, and for some reason we 9473 // couldn't join this network. 9474 // It might be due to a SW bug in supplicant or the wifi stack, or an 9475 // interoperability issue, or we try to join a bad bss and failed 9476 // In that case we want to restart pno so as to make sure that we will 9477 // attempt again to join that network. 9478 if (!mScreenOn && !mIsScanOngoing && mBackgroundScanSupported) { 9479 enableBackgroundScan(false); 9480 enableBackgroundScan(true); 9481 } 9482 return HANDLED; 9483 } 9484 break; 9485 case WifiMonitor.SCAN_RESULTS_EVENT: 9486 case WifiMonitor.SCAN_FAILED_EVENT: 9487 /* Re-enable background scan when a pending scan result is received */ 9488 if (!mScreenOn && mIsScanOngoing 9489 && mBackgroundScanSupported 9490 && !useHalBasedAutoJoinOffload()) { 9491 enableBackgroundScan(true); 9492 } else if (!mScreenOn 9493 && !mIsScanOngoing 9494 && mBackgroundScanSupported 9495 && !useHalBasedAutoJoinOffload()) { 9496 // We receive scan results from legacy PNO, hence restart the PNO alarm 9497 int delay; 9498 if (mDisconnectedPnoAlarmCount < 1) { 9499 delay = 30 * 1000; 9500 } else if (mDisconnectedPnoAlarmCount < 3) { 9501 delay = 60 * 1000; 9502 } else { 9503 delay = 360 * 1000; 9504 } 9505 mDisconnectedPnoAlarmCount++; 9506 if (VDBG) { 9507 logd("Starting PNO alarm " + delay); 9508 } 9509 mAlarmManager.set(AlarmManager.RTC_WAKEUP, 9510 System.currentTimeMillis() + delay, 9511 mPnoIntent); 9512 } 9513 /* Handled in parent state */ 9514 ret = NOT_HANDLED; 9515 break; 9516 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 9517 NetworkInfo info = (NetworkInfo) message.obj; 9518 mP2pConnected.set(info.isConnected()); 9519 if (mP2pConnected.get()) { 9520 int defaultInterval = mContext.getResources().getInteger( 9521 R.integer.config_wifi_scan_interval_p2p_connected); 9522 long scanIntervalMs = Settings.Global.getLong(mContext.getContentResolver(), 9523 Settings.Global.WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS, 9524 defaultInterval); 9525 mWifiNative.setScanInterval((int) scanIntervalMs/1000); 9526 } else if (mWifiConfigStore.getConfiguredNetworks().size() == 0) { 9527 if (DBG) log("Turn on scanning after p2p disconnected"); 9528 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 9529 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 9530 } else { 9531 // If P2P is not connected and there are saved networks, then restart 9532 // scanning at the normal period. This is necessary because scanning might 9533 // have been disabled altogether if WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS 9534 // was set to zero. 9535 if (useHalBasedAutoJoinOffload()) { 9536 startGScanDisconnectedModeOffload("p2pRestart"); 9537 } else { 9538 startDelayedScan( 9539 mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get(), 9540 null, null); 9541 } 9542 } 9543 break; 9544 case CMD_RECONNECT: 9545 case CMD_REASSOCIATE: 9546 if (mTemporarilyDisconnectWifi) { 9547 // Drop a third party reconnect/reassociate if STA is 9548 // temporarily disconnected for p2p 9549 break; 9550 } else { 9551 // ConnectModeState handles it 9552 ret = NOT_HANDLED; 9553 } 9554 break; 9555 case CMD_SCREEN_STATE_CHANGED: 9556 handleScreenStateChanged(message.arg1 != 0); 9557 break; 9558 default: 9559 ret = NOT_HANDLED; 9560 } 9561 return ret; 9562 } 9563 9564 @Override 9565 public void exit() { 9566 mDisconnectedPnoAlarmCount = 0; 9567 /* No need for a background scan upon exit from a disconnected state */ 9568 enableBackgroundScan(false); 9569 setScanAlarm(false); 9570 mAlarmManager.cancel(mPnoIntent); 9571 } 9572 } 9573 9574 class WpsRunningState extends State { 9575 // Tracks the source to provide a reply 9576 private Message mSourceMessage; 9577 @Override 9578 public void enter() { 9579 mSourceMessage = Message.obtain(getCurrentMessage()); 9580 } 9581 @Override 9582 public boolean processMessage(Message message) { 9583 logStateAndMessage(message, getClass().getSimpleName()); 9584 9585 switch (message.what) { 9586 case WifiMonitor.WPS_SUCCESS_EVENT: 9587 // Ignore intermediate success, wait for full connection 9588 break; 9589 case WifiMonitor.NETWORK_CONNECTION_EVENT: 9590 replyToMessage(mSourceMessage, WifiManager.WPS_COMPLETED); 9591 mSourceMessage.recycle(); 9592 mSourceMessage = null; 9593 deferMessage(message); 9594 transitionTo(mDisconnectedState); 9595 break; 9596 case WifiMonitor.WPS_OVERLAP_EVENT: 9597 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 9598 WifiManager.WPS_OVERLAP_ERROR); 9599 mSourceMessage.recycle(); 9600 mSourceMessage = null; 9601 transitionTo(mDisconnectedState); 9602 break; 9603 case WifiMonitor.WPS_FAIL_EVENT: 9604 // Arg1 has the reason for the failure 9605 if ((message.arg1 != WifiManager.ERROR) || (message.arg2 != 0)) { 9606 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, message.arg1); 9607 mSourceMessage.recycle(); 9608 mSourceMessage = null; 9609 transitionTo(mDisconnectedState); 9610 } else { 9611 if (DBG) log("Ignore unspecified fail event during WPS connection"); 9612 } 9613 break; 9614 case WifiMonitor.WPS_TIMEOUT_EVENT: 9615 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 9616 WifiManager.WPS_TIMED_OUT); 9617 mSourceMessage.recycle(); 9618 mSourceMessage = null; 9619 transitionTo(mDisconnectedState); 9620 break; 9621 case WifiManager.START_WPS: 9622 replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.IN_PROGRESS); 9623 break; 9624 case WifiManager.CANCEL_WPS: 9625 if (mWifiNative.cancelWps()) { 9626 replyToMessage(message, WifiManager.CANCEL_WPS_SUCCEDED); 9627 } else { 9628 replyToMessage(message, WifiManager.CANCEL_WPS_FAILED, WifiManager.ERROR); 9629 } 9630 transitionTo(mDisconnectedState); 9631 break; 9632 /** 9633 * Defer all commands that can cause connections to a different network 9634 * or put the state machine out of connect mode 9635 */ 9636 case CMD_STOP_DRIVER: 9637 case CMD_SET_OPERATIONAL_MODE: 9638 case WifiManager.CONNECT_NETWORK: 9639 case CMD_ENABLE_NETWORK: 9640 case CMD_RECONNECT: 9641 case CMD_REASSOCIATE: 9642 case CMD_ENABLE_ALL_NETWORKS: 9643 deferMessage(message); 9644 break; 9645 case CMD_AUTO_CONNECT: 9646 case CMD_AUTO_ROAM: 9647 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 9648 return HANDLED; 9649 case CMD_START_SCAN: 9650 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 9651 return HANDLED; 9652 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 9653 if (DBG) log("Network connection lost"); 9654 handleNetworkDisconnect(); 9655 break; 9656 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 9657 if (DBG) log("Ignore Assoc reject event during WPS Connection"); 9658 break; 9659 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 9660 // Disregard auth failure events during WPS connection. The 9661 // EAP sequence is retried several times, and there might be 9662 // failures (especially for wps pin). We will get a WPS_XXX 9663 // event at the end of the sequence anyway. 9664 if (DBG) log("Ignore auth failure during WPS connection"); 9665 break; 9666 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 9667 // Throw away supplicant state changes when WPS is running. 9668 // We will start getting supplicant state changes once we get 9669 // a WPS success or failure 9670 break; 9671 default: 9672 return NOT_HANDLED; 9673 } 9674 return HANDLED; 9675 } 9676 9677 @Override 9678 public void exit() { 9679 mWifiConfigStore.enableAllNetworks(); 9680 mWifiConfigStore.loadConfiguredNetworks(); 9681 } 9682 } 9683 9684 class SoftApStartingState extends State { 9685 @Override 9686 public void enter() { 9687 final Message message = getCurrentMessage(); 9688 if (message.what == CMD_START_AP) { 9689 final WifiConfiguration config = (WifiConfiguration) message.obj; 9690 9691 if (config == null) { 9692 mWifiApConfigChannel.sendMessage(CMD_REQUEST_AP_CONFIG); 9693 } else { 9694 mWifiApConfigChannel.sendMessage(CMD_SET_AP_CONFIG, config); 9695 startSoftApWithConfig(config); 9696 } 9697 } else { 9698 throw new RuntimeException("Illegal transition to SoftApStartingState: " + message); 9699 } 9700 } 9701 @Override 9702 public boolean processMessage(Message message) { 9703 logStateAndMessage(message, getClass().getSimpleName()); 9704 9705 switch(message.what) { 9706 case CMD_START_SUPPLICANT: 9707 case CMD_STOP_SUPPLICANT: 9708 case CMD_START_AP: 9709 case CMD_STOP_AP: 9710 case CMD_START_DRIVER: 9711 case CMD_STOP_DRIVER: 9712 case CMD_SET_OPERATIONAL_MODE: 9713 case CMD_SET_COUNTRY_CODE: 9714 case CMD_SET_FREQUENCY_BAND: 9715 case CMD_START_PACKET_FILTERING: 9716 case CMD_STOP_PACKET_FILTERING: 9717 case CMD_TETHER_STATE_CHANGE: 9718 deferMessage(message); 9719 break; 9720 case WifiStateMachine.CMD_RESPONSE_AP_CONFIG: 9721 WifiConfiguration config = (WifiConfiguration) message.obj; 9722 if (config != null) { 9723 startSoftApWithConfig(config); 9724 } else { 9725 loge("Softap config is null!"); 9726 sendMessage(CMD_START_AP_FAILURE, WifiManager.SAP_START_FAILURE_GENERAL); 9727 } 9728 break; 9729 case CMD_START_AP_SUCCESS: 9730 setWifiApState(WIFI_AP_STATE_ENABLED, 0); 9731 transitionTo(mSoftApStartedState); 9732 break; 9733 case CMD_START_AP_FAILURE: 9734 setWifiApState(WIFI_AP_STATE_FAILED, message.arg1); 9735 transitionTo(mInitialState); 9736 break; 9737 default: 9738 return NOT_HANDLED; 9739 } 9740 return HANDLED; 9741 } 9742 } 9743 9744 class SoftApStartedState extends State { 9745 @Override 9746 public boolean processMessage(Message message) { 9747 logStateAndMessage(message, getClass().getSimpleName()); 9748 9749 switch(message.what) { 9750 case CMD_STOP_AP: 9751 if (DBG) log("Stopping Soft AP"); 9752 /* We have not tethered at this point, so we just shutdown soft Ap */ 9753 try { 9754 mNwService.stopAccessPoint(mInterfaceName); 9755 } catch(Exception e) { 9756 loge("Exception in stopAccessPoint()"); 9757 } 9758 setWifiApState(WIFI_AP_STATE_DISABLED, 0); 9759 transitionTo(mInitialState); 9760 break; 9761 case CMD_START_AP: 9762 // Ignore a start on a running access point 9763 break; 9764 // Fail client mode operation when soft AP is enabled 9765 case CMD_START_SUPPLICANT: 9766 loge("Cannot start supplicant with a running soft AP"); 9767 setWifiState(WIFI_STATE_UNKNOWN); 9768 break; 9769 case CMD_TETHER_STATE_CHANGE: 9770 TetherStateChange stateChange = (TetherStateChange) message.obj; 9771 if (startTethering(stateChange.available)) { 9772 transitionTo(mTetheringState); 9773 } 9774 break; 9775 default: 9776 return NOT_HANDLED; 9777 } 9778 return HANDLED; 9779 } 9780 } 9781 9782 class TetheringState extends State { 9783 @Override 9784 public void enter() { 9785 /* Send ourselves a delayed message to shut down if tethering fails to notify */ 9786 sendMessageDelayed(obtainMessage(CMD_TETHER_NOTIFICATION_TIMED_OUT, 9787 ++mTetherToken, 0), TETHER_NOTIFICATION_TIME_OUT_MSECS); 9788 } 9789 @Override 9790 public boolean processMessage(Message message) { 9791 logStateAndMessage(message, getClass().getSimpleName()); 9792 9793 switch(message.what) { 9794 case CMD_TETHER_STATE_CHANGE: 9795 TetherStateChange stateChange = (TetherStateChange) message.obj; 9796 if (isWifiTethered(stateChange.active)) { 9797 transitionTo(mTetheredState); 9798 } 9799 return HANDLED; 9800 case CMD_TETHER_NOTIFICATION_TIMED_OUT: 9801 if (message.arg1 == mTetherToken) { 9802 loge("Failed to get tether update, shutdown soft access point"); 9803 transitionTo(mSoftApStartedState); 9804 // Needs to be first thing handled 9805 sendMessageAtFrontOfQueue(CMD_STOP_AP); 9806 } 9807 break; 9808 case CMD_START_SUPPLICANT: 9809 case CMD_STOP_SUPPLICANT: 9810 case CMD_START_AP: 9811 case CMD_STOP_AP: 9812 case CMD_START_DRIVER: 9813 case CMD_STOP_DRIVER: 9814 case CMD_SET_OPERATIONAL_MODE: 9815 case CMD_SET_COUNTRY_CODE: 9816 case CMD_SET_FREQUENCY_BAND: 9817 case CMD_START_PACKET_FILTERING: 9818 case CMD_STOP_PACKET_FILTERING: 9819 deferMessage(message); 9820 break; 9821 default: 9822 return NOT_HANDLED; 9823 } 9824 return HANDLED; 9825 } 9826 } 9827 9828 class TetheredState extends State { 9829 @Override 9830 public boolean processMessage(Message message) { 9831 logStateAndMessage(message, getClass().getSimpleName()); 9832 9833 switch(message.what) { 9834 case CMD_TETHER_STATE_CHANGE: 9835 TetherStateChange stateChange = (TetherStateChange) message.obj; 9836 if (!isWifiTethered(stateChange.active)) { 9837 loge("Tethering reports wifi as untethered!, shut down soft Ap"); 9838 setHostApRunning(null, false); 9839 setHostApRunning(null, true); 9840 } 9841 return HANDLED; 9842 case CMD_STOP_AP: 9843 if (DBG) log("Untethering before stopping AP"); 9844 setWifiApState(WIFI_AP_STATE_DISABLING, 0); 9845 stopTethering(); 9846 transitionTo(mUntetheringState); 9847 // More work to do after untethering 9848 deferMessage(message); 9849 break; 9850 default: 9851 return NOT_HANDLED; 9852 } 9853 return HANDLED; 9854 } 9855 } 9856 9857 class UntetheringState extends State { 9858 @Override 9859 public void enter() { 9860 /* Send ourselves a delayed message to shut down if tethering fails to notify */ 9861 sendMessageDelayed(obtainMessage(CMD_TETHER_NOTIFICATION_TIMED_OUT, 9862 ++mTetherToken, 0), TETHER_NOTIFICATION_TIME_OUT_MSECS); 9863 9864 } 9865 @Override 9866 public boolean processMessage(Message message) { 9867 logStateAndMessage(message, getClass().getSimpleName()); 9868 9869 switch(message.what) { 9870 case CMD_TETHER_STATE_CHANGE: 9871 TetherStateChange stateChange = (TetherStateChange) message.obj; 9872 9873 /* Wait till wifi is untethered */ 9874 if (isWifiTethered(stateChange.active)) break; 9875 9876 transitionTo(mSoftApStartedState); 9877 break; 9878 case CMD_TETHER_NOTIFICATION_TIMED_OUT: 9879 if (message.arg1 == mTetherToken) { 9880 loge("Failed to get tether update, force stop access point"); 9881 transitionTo(mSoftApStartedState); 9882 } 9883 break; 9884 case CMD_START_SUPPLICANT: 9885 case CMD_STOP_SUPPLICANT: 9886 case CMD_START_AP: 9887 case CMD_STOP_AP: 9888 case CMD_START_DRIVER: 9889 case CMD_STOP_DRIVER: 9890 case CMD_SET_OPERATIONAL_MODE: 9891 case CMD_SET_COUNTRY_CODE: 9892 case CMD_SET_FREQUENCY_BAND: 9893 case CMD_START_PACKET_FILTERING: 9894 case CMD_STOP_PACKET_FILTERING: 9895 deferMessage(message); 9896 break; 9897 default: 9898 return NOT_HANDLED; 9899 } 9900 return HANDLED; 9901 } 9902 } 9903 9904 /** 9905 * State machine initiated requests can have replyTo set to null indicating 9906 * there are no recepients, we ignore those reply actions. 9907 */ 9908 private void replyToMessage(Message msg, int what) { 9909 if (msg.replyTo == null) return; 9910 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 9911 mReplyChannel.replyToMessage(msg, dstMsg); 9912 } 9913 9914 private void replyToMessage(Message msg, int what, int arg1) { 9915 if (msg.replyTo == null) return; 9916 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 9917 dstMsg.arg1 = arg1; 9918 mReplyChannel.replyToMessage(msg, dstMsg); 9919 } 9920 9921 private void replyToMessage(Message msg, int what, Object obj) { 9922 if (msg.replyTo == null) return; 9923 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 9924 dstMsg.obj = obj; 9925 mReplyChannel.replyToMessage(msg, dstMsg); 9926 } 9927 9928 /** 9929 * arg2 on the source message has a unique id that needs to be retained in replies 9930 * to match the request 9931 * <p>see WifiManager for details 9932 */ 9933 private Message obtainMessageWithWhatAndArg2(Message srcMsg, int what) { 9934 Message msg = Message.obtain(); 9935 msg.what = what; 9936 msg.arg2 = srcMsg.arg2; 9937 return msg; 9938 } 9939 9940 /** 9941 * @param wifiCredentialEventType WIFI_CREDENTIAL_SAVED or WIFI_CREDENTIAL_FORGOT 9942 * @param msg Must have a WifiConfiguration obj to succeed 9943 */ 9944 private void broadcastWifiCredentialChanged(int wifiCredentialEventType, 9945 WifiConfiguration config) { 9946 if (config != null && config.preSharedKey != null) { 9947 Intent intent = new Intent(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION); 9948 intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID, config.SSID); 9949 intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, 9950 wifiCredentialEventType); 9951 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT, 9952 android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE); 9953 } 9954 } 9955 9956 private static int parseHex(char ch) { 9957 if ('0' <= ch && ch <= '9') { 9958 return ch - '0'; 9959 } else if ('a' <= ch && ch <= 'f') { 9960 return ch - 'a' + 10; 9961 } else if ('A' <= ch && ch <= 'F') { 9962 return ch - 'A' + 10; 9963 } else { 9964 throw new NumberFormatException("" + ch + " is not a valid hex digit"); 9965 } 9966 } 9967 9968 private byte[] parseHex(String hex) { 9969 /* This only works for good input; don't throw bad data at it */ 9970 if (hex == null) { 9971 return new byte[0]; 9972 } 9973 9974 if (hex.length() % 2 != 0) { 9975 throw new NumberFormatException(hex + " is not a valid hex string"); 9976 } 9977 9978 byte[] result = new byte[(hex.length())/2 + 1]; 9979 result[0] = (byte) ((hex.length())/2); 9980 for (int i = 0, j = 1; i < hex.length(); i += 2, j++) { 9981 int val = parseHex(hex.charAt(i)) * 16 + parseHex(hex.charAt(i+1)); 9982 byte b = (byte) (val & 0xFF); 9983 result[j] = b; 9984 } 9985 9986 return result; 9987 } 9988 9989 private static String makeHex(byte[] bytes) { 9990 StringBuilder sb = new StringBuilder(); 9991 for (byte b : bytes) { 9992 sb.append(String.format("%02x", b)); 9993 } 9994 return sb.toString(); 9995 } 9996 9997 private static String makeHex(byte[] bytes, int from, int len) { 9998 StringBuilder sb = new StringBuilder(); 9999 for (int i = 0; i < len; i++) { 10000 sb.append(String.format("%02x", bytes[from+i])); 10001 } 10002 return sb.toString(); 10003 } 10004 10005 private static byte[] concat(byte[] array1, byte[] array2, byte[] array3) { 10006 10007 int len = array1.length + array2.length + array3.length; 10008 10009 if (array1.length != 0) { 10010 len++; /* add another byte for size */ 10011 } 10012 10013 if (array2.length != 0) { 10014 len++; /* add another byte for size */ 10015 } 10016 10017 if (array3.length != 0) { 10018 len++; /* add another byte for size */ 10019 } 10020 10021 byte[] result = new byte[len]; 10022 10023 int index = 0; 10024 if (array1.length != 0) { 10025 result[index] = (byte) (array1.length & 0xFF); 10026 index++; 10027 for (byte b : array1) { 10028 result[index] = b; 10029 index++; 10030 } 10031 } 10032 10033 if (array2.length != 0) { 10034 result[index] = (byte) (array2.length & 0xFF); 10035 index++; 10036 for (byte b : array2) { 10037 result[index] = b; 10038 index++; 10039 } 10040 } 10041 10042 if (array3.length != 0) { 10043 result[index] = (byte) (array3.length & 0xFF); 10044 index++; 10045 for (byte b : array3) { 10046 result[index] = b; 10047 index++; 10048 } 10049 } 10050 return result; 10051 } 10052 10053 private static byte[] concatHex(byte[] array1, byte[] array2) { 10054 10055 int len = array1.length + array2.length; 10056 10057 byte[] result = new byte[len]; 10058 10059 int index = 0; 10060 if (array1.length != 0) { 10061 for (byte b : array1) { 10062 result[index] = b; 10063 index++; 10064 } 10065 } 10066 10067 if (array2.length != 0) { 10068 for (byte b : array2) { 10069 result[index] = b; 10070 index++; 10071 } 10072 } 10073 10074 return result; 10075 } 10076 10077 void handleGsmAuthRequest(SimAuthRequestData requestData) { 10078 if (targetWificonfiguration == null 10079 || targetWificonfiguration.networkId == requestData.networkId) { 10080 logd("id matches targetWifiConfiguration"); 10081 } else { 10082 logd("id does not match targetWifiConfiguration"); 10083 return; 10084 } 10085 10086 TelephonyManager tm = (TelephonyManager) 10087 mContext.getSystemService(Context.TELEPHONY_SERVICE); 10088 10089 if (tm != null) { 10090 StringBuilder sb = new StringBuilder(); 10091 for (String challenge : requestData.data) { 10092 10093 if (challenge == null || challenge.isEmpty()) 10094 continue; 10095 logd("RAND = " + challenge); 10096 10097 byte[] rand = null; 10098 try { 10099 rand = parseHex(challenge); 10100 } catch (NumberFormatException e) { 10101 loge("malformed challenge"); 10102 continue; 10103 } 10104 10105 String base64Challenge = android.util.Base64.encodeToString( 10106 rand, android.util.Base64.NO_WRAP); 10107 /* 10108 * First, try with appType = 2 => USIM according to 10109 * com.android.internal.telephony.PhoneConstants#APPTYPE_xxx 10110 */ 10111 int appType = 2; 10112 String tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge); 10113 if (tmResponse == null) { 10114 /* Then, in case of failure, issue may be due to sim type, retry as a simple sim 10115 * appType = 1 => SIM 10116 */ 10117 appType = 1; 10118 tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge); 10119 } 10120 logv("Raw Response - " + tmResponse); 10121 10122 if (tmResponse != null && tmResponse.length() > 4) { 10123 byte[] result = android.util.Base64.decode(tmResponse, 10124 android.util.Base64.DEFAULT); 10125 logv("Hex Response -" + makeHex(result)); 10126 int sres_len = result[0]; 10127 String sres = makeHex(result, 1, sres_len); 10128 int kc_offset = 1+sres_len; 10129 int kc_len = result[kc_offset]; 10130 String kc = makeHex(result, 1+kc_offset, kc_len); 10131 sb.append(":" + kc + ":" + sres); 10132 logv("kc:" + kc + " sres:" + sres); 10133 } else { 10134 loge("bad response - " + tmResponse); 10135 } 10136 } 10137 10138 String response = sb.toString(); 10139 logv("Supplicant Response -" + response); 10140 mWifiNative.simAuthResponse(requestData.networkId, "GSM-AUTH", response); 10141 } else { 10142 loge("could not get telephony manager"); 10143 } 10144 } 10145 10146 void handle3GAuthRequest(SimAuthRequestData requestData) { 10147 StringBuilder sb = new StringBuilder(); 10148 byte[] rand = null; 10149 byte[] authn = null; 10150 String res_type = "UMTS-AUTH"; 10151 10152 if (targetWificonfiguration == null 10153 || targetWificonfiguration.networkId == requestData.networkId) { 10154 logd("id matches targetWifiConfiguration"); 10155 } else { 10156 logd("id does not match targetWifiConfiguration"); 10157 return; 10158 } 10159 if (requestData.data.length == 2) { 10160 try { 10161 rand = parseHex(requestData.data[0]); 10162 authn = parseHex(requestData.data[1]); 10163 } catch (NumberFormatException e) { 10164 loge("malformed challenge"); 10165 } 10166 } else { 10167 loge("malformed challenge"); 10168 } 10169 10170 String tmResponse = ""; 10171 if (rand != null && authn != null) { 10172 String base64Challenge = android.util.Base64.encodeToString( 10173 concatHex(rand,authn), android.util.Base64.NO_WRAP); 10174 10175 TelephonyManager tm = (TelephonyManager) 10176 mContext.getSystemService(Context.TELEPHONY_SERVICE); 10177 if (tm != null) { 10178 int appType = 2; // 2 => USIM 10179 tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge); 10180 logv("Raw Response - " + tmResponse); 10181 } else { 10182 loge("could not get telephony manager"); 10183 } 10184 } 10185 10186 if (tmResponse != null && tmResponse.length() > 4) { 10187 byte[] result = android.util.Base64.decode(tmResponse, 10188 android.util.Base64.DEFAULT); 10189 loge("Hex Response - " + makeHex(result)); 10190 byte tag = result[0]; 10191 if (tag == (byte) 0xdb) { 10192 logv("successful 3G authentication "); 10193 int res_len = result[1]; 10194 String res = makeHex(result, 2, res_len); 10195 int ck_len = result[res_len + 2]; 10196 String ck = makeHex(result, res_len + 3, ck_len); 10197 int ik_len = result[res_len + ck_len + 3]; 10198 String ik = makeHex(result, res_len + ck_len + 4, ik_len); 10199 sb.append(":" + ik + ":" + ck + ":" + res); 10200 logv("ik:" + ik + "ck:" + ck + " res:" + res); 10201 } else if (tag == (byte) 0xdc) { 10202 loge("synchronisation failure"); 10203 int auts_len = result[1]; 10204 String auts = makeHex(result, 2, auts_len); 10205 res_type = "UMTS-AUTS"; 10206 sb.append(":" + auts); 10207 logv("auts:" + auts); 10208 } else { 10209 loge("bad response - unknown tag = " + tag); 10210 return; 10211 } 10212 } else { 10213 loge("bad response - " + tmResponse); 10214 return; 10215 } 10216 10217 String response = sb.toString(); 10218 logv("Supplicant Response -" + response); 10219 mWifiNative.simAuthResponse(requestData.networkId, res_type, response); 10220 } 10221 10222 /** 10223 * @param reason reason code from supplicant on network disconnected event 10224 * @return true if this is a suspicious disconnect 10225 */ 10226 static boolean unexpectedDisconnectedReason(int reason) { 10227 return reason == 2 // PREV_AUTH_NOT_VALID 10228 || reason == 6 // CLASS2_FRAME_FROM_NONAUTH_STA 10229 || reason == 7 // FRAME_FROM_NONASSOC_STA 10230 || reason == 8 // STA_HAS_LEFT 10231 || reason == 9 // STA_REQ_ASSOC_WITHOUT_AUTH 10232 || reason == 14 // MICHAEL_MIC_FAILURE 10233 || reason == 15 // 4WAY_HANDSHAKE_TIMEOUT 10234 || reason == 16 // GROUP_KEY_UPDATE_TIMEOUT 10235 || reason == 18 // GROUP_CIPHER_NOT_VALID 10236 || reason == 19 // PAIRWISE_CIPHER_NOT_VALID 10237 || reason == 23 // IEEE_802_1X_AUTH_FAILED 10238 || reason == 34; // DISASSOC_LOW_ACK 10239 } 10240} 10241