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