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