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