WifiStateMachine.java revision c97b98d6877f6603a6a0eee820576f59e7da5e52
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 boolean ret = mWifiNative.enableBackgroundScan(enable); 2210 if (ret) { 2211 mLegacyPnoEnabled = enable; 2212 } else { 2213 Log.e(TAG, " Fail to set up pno, want " + enable + " now " + mLegacyPnoEnabled); 2214 } 2215 } 2216 2217 /** 2218 * Blacklist a BSSID. This will avoid the AP if there are 2219 * alternate APs to connect 2220 * 2221 * @param bssid BSSID of the network 2222 */ 2223 public void addToBlacklist(String bssid) { 2224 sendMessage(CMD_BLACKLIST_NETWORK, bssid); 2225 } 2226 2227 /** 2228 * Clear the blacklist list 2229 */ 2230 public void clearBlacklist() { 2231 sendMessage(CMD_CLEAR_BLACKLIST); 2232 } 2233 2234 public void enableRssiPolling(boolean enabled) { 2235 sendMessage(CMD_ENABLE_RSSI_POLL, enabled ? 1 : 0, 0); 2236 } 2237 2238 public void enableAllNetworks() { 2239 sendMessage(CMD_ENABLE_ALL_NETWORKS); 2240 } 2241 2242 /** 2243 * Start filtering Multicast v4 packets 2244 */ 2245 public void startFilteringMulticastV4Packets() { 2246 mFilteringMulticastV4Packets.set(true); 2247 sendMessage(CMD_START_PACKET_FILTERING, MULTICAST_V4, 0); 2248 } 2249 2250 /** 2251 * Stop filtering Multicast v4 packets 2252 */ 2253 public void stopFilteringMulticastV4Packets() { 2254 mFilteringMulticastV4Packets.set(false); 2255 sendMessage(CMD_STOP_PACKET_FILTERING, MULTICAST_V4, 0); 2256 } 2257 2258 /** 2259 * Start filtering Multicast v4 packets 2260 */ 2261 public void startFilteringMulticastV6Packets() { 2262 sendMessage(CMD_START_PACKET_FILTERING, MULTICAST_V6, 0); 2263 } 2264 2265 /** 2266 * Stop filtering Multicast v4 packets 2267 */ 2268 public void stopFilteringMulticastV6Packets() { 2269 sendMessage(CMD_STOP_PACKET_FILTERING, MULTICAST_V6, 0); 2270 } 2271 2272 /** 2273 * Set high performance mode of operation. 2274 * Enabling would set active power mode and disable suspend optimizations; 2275 * disabling would set auto power mode and enable suspend optimizations 2276 * 2277 * @param enable true if enable, false otherwise 2278 */ 2279 public void setHighPerfModeEnabled(boolean enable) { 2280 sendMessage(CMD_SET_HIGH_PERF_MODE, enable ? 1 : 0, 0); 2281 } 2282 2283 /** 2284 * Set the country code 2285 * 2286 * @param countryCode following ISO 3166 format 2287 * @param persist {@code true} if the setting should be remembered. 2288 */ 2289 public synchronized void setCountryCode(String countryCode, boolean persist) { 2290 // If it's a good country code, apply after the current 2291 // wifi connection is terminated; ignore resetting of code 2292 // for now (it is unclear what the chipset should do when 2293 // country code is reset) 2294 2295 if (TextUtils.isEmpty(countryCode)) { 2296 log("Ignoring resetting of country code"); 2297 } else { 2298 // if mCountryCodeSequence == 0, it is the first time to set country code, always set 2299 // else only when the new country code is different from the current one to set 2300 int countryCodeSequence = mCountryCodeSequence.get(); 2301 if (countryCodeSequence == 0 || countryCode.equals(mSetCountryCode) == false) { 2302 2303 countryCodeSequence = mCountryCodeSequence.incrementAndGet(); 2304 mSetCountryCode = countryCode; 2305 sendMessage(CMD_SET_COUNTRY_CODE, countryCodeSequence, persist ? 1 : 0, 2306 countryCode); 2307 } 2308 2309 if (persist) { 2310 Settings.Global.putString(mContext.getContentResolver(), 2311 Settings.Global.WIFI_COUNTRY_CODE, 2312 countryCode); 2313 } 2314 } 2315 } 2316 2317 /** 2318 * Get Network object of current wifi network 2319 * @return Network object of current wifi network 2320 */ 2321 public Network getCurrentNetwork() { 2322 if (mNetworkAgent != null) { 2323 return new Network(mNetworkAgent.netId); 2324 } else { 2325 return null; 2326 } 2327 } 2328 2329 /** 2330 * Get the country code 2331 * 2332 * @param countryCode following ISO 3166 format 2333 */ 2334 public String getCountryCode() { 2335 return mSetCountryCode; 2336 } 2337 2338 2339 /** 2340 * Set the operational frequency band 2341 * 2342 * @param band 2343 * @param persist {@code true} if the setting should be remembered. 2344 */ 2345 public void setFrequencyBand(int band, boolean persist) { 2346 if (persist) { 2347 Settings.Global.putInt(mContext.getContentResolver(), 2348 Settings.Global.WIFI_FREQUENCY_BAND, 2349 band); 2350 } 2351 sendMessage(CMD_SET_FREQUENCY_BAND, band, 0); 2352 } 2353 2354 /** 2355 * Enable TDLS for a specific MAC address 2356 */ 2357 public void enableTdls(String remoteMacAddress, boolean enable) { 2358 int enabler = enable ? 1 : 0; 2359 sendMessage(CMD_ENABLE_TDLS, enabler, 0, remoteMacAddress); 2360 } 2361 2362 /** 2363 * Returns the operational frequency band 2364 */ 2365 public int getFrequencyBand() { 2366 return mFrequencyBand.get(); 2367 } 2368 2369 /** 2370 * Returns the wifi configuration file 2371 */ 2372 public String getConfigFile() { 2373 return mWifiConfigStore.getConfigFile(); 2374 } 2375 2376 /** 2377 * Send a message indicating bluetooth adapter connection state changed 2378 */ 2379 public void sendBluetoothAdapterStateChange(int state) { 2380 sendMessage(CMD_BLUETOOTH_ADAPTER_STATE_CHANGE, state, 0); 2381 } 2382 2383 /** 2384 * Send a message indicating a package has been uninstalled. 2385 */ 2386 public void removeAppConfigs(String packageName, int uid) { 2387 // Build partial AppInfo manually - package may not exist in database any more 2388 ApplicationInfo ai = new ApplicationInfo(); 2389 ai.packageName = packageName; 2390 ai.uid = uid; 2391 sendMessage(CMD_REMOVE_APP_CONFIGURATIONS, ai); 2392 } 2393 2394 /** 2395 * Send a message indicating a user has been removed. 2396 */ 2397 public void removeUserConfigs(int userId) { 2398 sendMessage(CMD_REMOVE_USER_CONFIGURATIONS, userId); 2399 } 2400 2401 /** 2402 * Save configuration on supplicant 2403 * 2404 * @return {@code true} if the operation succeeds, {@code false} otherwise 2405 * <p/> 2406 * TODO: deprecate this 2407 */ 2408 public boolean syncSaveConfig(AsyncChannel channel) { 2409 Message resultMsg = channel.sendMessageSynchronously(CMD_SAVE_CONFIG); 2410 boolean result = (resultMsg.arg1 != FAILURE); 2411 resultMsg.recycle(); 2412 return result; 2413 } 2414 2415 public void updateBatteryWorkSource(WorkSource newSource) { 2416 synchronized (mRunningWifiUids) { 2417 try { 2418 if (newSource != null) { 2419 mRunningWifiUids.set(newSource); 2420 } 2421 if (mIsRunning) { 2422 if (mReportedRunning) { 2423 // If the work source has changed since last time, need 2424 // to remove old work from battery stats. 2425 if (mLastRunningWifiUids.diff(mRunningWifiUids)) { 2426 mBatteryStats.noteWifiRunningChanged(mLastRunningWifiUids, 2427 mRunningWifiUids); 2428 mLastRunningWifiUids.set(mRunningWifiUids); 2429 } 2430 } else { 2431 // Now being started, report it. 2432 mBatteryStats.noteWifiRunning(mRunningWifiUids); 2433 mLastRunningWifiUids.set(mRunningWifiUids); 2434 mReportedRunning = true; 2435 } 2436 } else { 2437 if (mReportedRunning) { 2438 // Last reported we were running, time to stop. 2439 mBatteryStats.noteWifiStopped(mLastRunningWifiUids); 2440 mLastRunningWifiUids.clear(); 2441 mReportedRunning = false; 2442 } 2443 } 2444 mWakeLock.setWorkSource(newSource); 2445 } catch (RemoteException ignore) { 2446 } 2447 } 2448 } 2449 2450 @Override 2451 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2452 super.dump(fd, pw, args); 2453 mSupplicantStateTracker.dump(fd, pw, args); 2454 pw.println("mLinkProperties " + mLinkProperties); 2455 pw.println("mWifiInfo " + mWifiInfo); 2456 pw.println("mDhcpResults " + mDhcpResults); 2457 pw.println("mNetworkInfo " + mNetworkInfo); 2458 pw.println("mLastSignalLevel " + mLastSignalLevel); 2459 pw.println("mLastBssid " + mLastBssid); 2460 pw.println("mLastNetworkId " + mLastNetworkId); 2461 pw.println("mOperationalMode " + mOperationalMode); 2462 pw.println("mUserWantsSuspendOpt " + mUserWantsSuspendOpt); 2463 pw.println("mSuspendOptNeedsDisabled " + mSuspendOptNeedsDisabled); 2464 pw.println("Supplicant status " + mWifiNative.status(true)); 2465 pw.println("mLegacyPnoEnabled " + mLegacyPnoEnabled); 2466 pw.println("mSetCountryCode " + mSetCountryCode); 2467 pw.println("mDriverSetCountryCode " + mDriverSetCountryCode); 2468 pw.println("mConnectedModeGScanOffloadStarted " + mConnectedModeGScanOffloadStarted); 2469 pw.println("mGScanPeriodMilli " + mGScanPeriodMilli); 2470 if (mWhiteListedSsids != null && mWhiteListedSsids.length > 0) { 2471 pw.println("SSID whitelist :" ); 2472 for (int i=0; i < mWhiteListedSsids.length; i++) { 2473 pw.println(" " + mWhiteListedSsids[i]); 2474 } 2475 } 2476 mNetworkFactory.dump(fd, pw, args); 2477 mUntrustedNetworkFactory.dump(fd, pw, args); 2478 pw.println(); 2479 mWifiConfigStore.dump(fd, pw, args); 2480 pw.println(); 2481 mWifiLogger.dump(fd, pw, args); 2482 } 2483 2484 /** 2485 * ****************************************************** 2486 * Internal private functions 2487 * ****************************************************** 2488 */ 2489 2490 private void logStateAndMessage(Message message, String state) { 2491 messageHandlingStatus = 0; 2492 if (mLogMessages) { 2493 //long now = SystemClock.elapsedRealtimeNanos(); 2494 //String ts = String.format("[%,d us]", now/1000); 2495 2496 loge(" " + state + " " + getLogRecString(message)); 2497 } 2498 } 2499 2500 /** 2501 * helper, prints the milli time since boot wi and w/o suspended time 2502 */ 2503 String printTime() { 2504 StringBuilder sb = new StringBuilder(); 2505 sb.append(" rt=").append(SystemClock.uptimeMillis()); 2506 sb.append("/").append(SystemClock.elapsedRealtime()); 2507 return sb.toString(); 2508 } 2509 2510 /** 2511 * Return the additional string to be logged by LogRec, default 2512 * 2513 * @param msg that was processed 2514 * @return information to be logged as a String 2515 */ 2516 protected String getLogRecString(Message msg) { 2517 WifiConfiguration config; 2518 Long now; 2519 String report; 2520 String key; 2521 StringBuilder sb = new StringBuilder(); 2522 if (mScreenOn) { 2523 sb.append("!"); 2524 } 2525 if (messageHandlingStatus != MESSAGE_HANDLING_STATUS_UNKNOWN) { 2526 sb.append("(").append(messageHandlingStatus).append(")"); 2527 } 2528 sb.append(smToString(msg)); 2529 if (msg.sendingUid > 0 && msg.sendingUid != Process.WIFI_UID) { 2530 sb.append(" uid=" + msg.sendingUid); 2531 } 2532 switch (msg.what) { 2533 case CMD_STARTED_GSCAN_DBG: 2534 case CMD_STARTED_PNO_DBG: 2535 sb.append(" "); 2536 sb.append(Integer.toString(msg.arg1)); 2537 sb.append(" "); 2538 sb.append(Integer.toString(msg.arg2)); 2539 if (msg.obj != null) { 2540 sb.append(" " + (String)msg.obj); 2541 } 2542 break; 2543 case CMD_RESTART_AUTOJOIN_OFFLOAD: 2544 sb.append(" "); 2545 sb.append(Integer.toString(msg.arg1)); 2546 sb.append(" "); 2547 sb.append(Integer.toString(msg.arg2)); 2548 sb.append("/").append(Integer.toString(mRestartAutoJoinOffloadCounter)); 2549 if (msg.obj != null) { 2550 sb.append(" " + (String)msg.obj); 2551 } 2552 break; 2553 case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION: 2554 sb.append(" "); 2555 sb.append(Integer.toString(msg.arg1)); 2556 sb.append(" "); 2557 sb.append(Integer.toString(msg.arg2)); 2558 sb.append(" halAllowed=").append(useHalBasedAutoJoinOffload()); 2559 sb.append(" scanAllowed=").append(allowFullBandScanAndAssociated()); 2560 sb.append(" autojoinAllowed="); 2561 sb.append(mWifiConfigStore.enableAutoJoinScanWhenAssociated.get()); 2562 sb.append(" withTraffic=").append(getAllowScansWithTraffic()); 2563 sb.append(" tx=").append(mWifiInfo.txSuccessRate); 2564 sb.append("/").append(mWifiConfigStore.maxTxPacketForFullScans); 2565 sb.append(" rx=").append(mWifiInfo.rxSuccessRate); 2566 sb.append("/").append(mWifiConfigStore.maxRxPacketForFullScans); 2567 sb.append(" -> ").append(mConnectedModeGScanOffloadStarted); 2568 break; 2569 case CMD_PNO_NETWORK_FOUND: 2570 sb.append(" "); 2571 sb.append(Integer.toString(msg.arg1)); 2572 sb.append(" "); 2573 sb.append(Integer.toString(msg.arg2)); 2574 if (msg.obj != null) { 2575 ScanResult[] results = (ScanResult[])msg.obj; 2576 for (int i = 0; i < results.length; i++) { 2577 sb.append(" ").append(results[i].SSID).append(" "); 2578 sb.append(results[i].frequency); 2579 sb.append(" ").append(results[i].level); 2580 } 2581 } 2582 break; 2583 case CMD_START_SCAN: 2584 now = System.currentTimeMillis(); 2585 sb.append(" "); 2586 sb.append(Integer.toString(msg.arg1)); 2587 sb.append(" "); 2588 sb.append(Integer.toString(msg.arg2)); 2589 sb.append(" ic="); 2590 sb.append(Integer.toString(sScanAlarmIntentCount)); 2591 if (msg.obj != null) { 2592 Bundle bundle = (Bundle) msg.obj; 2593 Long request = bundle.getLong(SCAN_REQUEST_TIME, 0); 2594 if (request != 0) { 2595 sb.append(" proc(ms):").append(now - request); 2596 } 2597 } 2598 if (mIsScanOngoing) sb.append(" onGoing"); 2599 if (mIsFullScanOngoing) sb.append(" full"); 2600 if (lastStartScanTimeStamp != 0) { 2601 sb.append(" started:").append(lastStartScanTimeStamp); 2602 sb.append(",").append(now - lastStartScanTimeStamp); 2603 } 2604 if (lastScanDuration != 0) { 2605 sb.append(" dur:").append(lastScanDuration); 2606 } 2607 sb.append(" cnt=").append(mDelayedScanCounter); 2608 sb.append(" rssi=").append(mWifiInfo.getRssi()); 2609 sb.append(" f=").append(mWifiInfo.getFrequency()); 2610 sb.append(" sc=").append(mWifiInfo.score); 2611 sb.append(" link=").append(mWifiInfo.getLinkSpeed()); 2612 sb.append(String.format(" tx=%.1f,", mWifiInfo.txSuccessRate)); 2613 sb.append(String.format(" %.1f,", mWifiInfo.txRetriesRate)); 2614 sb.append(String.format(" %.1f ", mWifiInfo.txBadRate)); 2615 sb.append(String.format(" rx=%.1f", mWifiInfo.rxSuccessRate)); 2616 if (lastScanFreqs != null) { 2617 sb.append(" list=").append(lastScanFreqs); 2618 } else { 2619 sb.append(" fiv=").append(fullBandConnectedTimeIntervalMilli); 2620 } 2621 report = reportOnTime(); 2622 if (report != null) { 2623 sb.append(" ").append(report); 2624 } 2625 break; 2626 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 2627 sb.append(" "); 2628 sb.append(Integer.toString(msg.arg1)); 2629 sb.append(" "); 2630 sb.append(Integer.toString(msg.arg2)); 2631 sb.append(printTime()); 2632 StateChangeResult stateChangeResult = (StateChangeResult) msg.obj; 2633 if (stateChangeResult != null) { 2634 sb.append(stateChangeResult.toString()); 2635 } 2636 break; 2637 case WifiManager.SAVE_NETWORK: 2638 case WifiStateMachine.CMD_AUTO_SAVE_NETWORK: 2639 sb.append(" "); 2640 sb.append(Integer.toString(msg.arg1)); 2641 sb.append(" "); 2642 sb.append(Integer.toString(msg.arg2)); 2643 if (lastSavedConfigurationAttempt != null) { 2644 sb.append(" ").append(lastSavedConfigurationAttempt.configKey()); 2645 sb.append(" nid=").append(lastSavedConfigurationAttempt.networkId); 2646 if (lastSavedConfigurationAttempt.hiddenSSID) { 2647 sb.append(" hidden"); 2648 } 2649 if (lastSavedConfigurationAttempt.preSharedKey != null 2650 && !lastSavedConfigurationAttempt.preSharedKey.equals("*")) { 2651 sb.append(" hasPSK"); 2652 } 2653 if (lastSavedConfigurationAttempt.ephemeral) { 2654 sb.append(" ephemeral"); 2655 } 2656 if (lastSavedConfigurationAttempt.selfAdded) { 2657 sb.append(" selfAdded"); 2658 } 2659 sb.append(" cuid=").append(lastSavedConfigurationAttempt.creatorUid); 2660 sb.append(" suid=").append(lastSavedConfigurationAttempt.lastUpdateUid); 2661 } 2662 break; 2663 case WifiManager.FORGET_NETWORK: 2664 sb.append(" "); 2665 sb.append(Integer.toString(msg.arg1)); 2666 sb.append(" "); 2667 sb.append(Integer.toString(msg.arg2)); 2668 if (lastForgetConfigurationAttempt != null) { 2669 sb.append(" ").append(lastForgetConfigurationAttempt.configKey()); 2670 sb.append(" nid=").append(lastForgetConfigurationAttempt.networkId); 2671 if (lastForgetConfigurationAttempt.hiddenSSID) { 2672 sb.append(" hidden"); 2673 } 2674 if (lastForgetConfigurationAttempt.preSharedKey != null) { 2675 sb.append(" hasPSK"); 2676 } 2677 if (lastForgetConfigurationAttempt.ephemeral) { 2678 sb.append(" ephemeral"); 2679 } 2680 if (lastForgetConfigurationAttempt.selfAdded) { 2681 sb.append(" selfAdded"); 2682 } 2683 sb.append(" cuid=").append(lastForgetConfigurationAttempt.creatorUid); 2684 sb.append(" suid=").append(lastForgetConfigurationAttempt.lastUpdateUid); 2685 sb.append(" ajst=").append(lastForgetConfigurationAttempt.autoJoinStatus); 2686 } 2687 break; 2688 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 2689 sb.append(" "); 2690 sb.append(Integer.toString(msg.arg1)); 2691 sb.append(" "); 2692 sb.append(Integer.toString(msg.arg2)); 2693 String bssid = (String) msg.obj; 2694 if (bssid != null && bssid.length() > 0) { 2695 sb.append(" "); 2696 sb.append(bssid); 2697 } 2698 sb.append(" blacklist=" + Boolean.toString(didBlackListBSSID)); 2699 sb.append(printTime()); 2700 break; 2701 case WifiMonitor.SCAN_RESULTS_EVENT: 2702 sb.append(" "); 2703 sb.append(Integer.toString(msg.arg1)); 2704 sb.append(" "); 2705 sb.append(Integer.toString(msg.arg2)); 2706 if (mScanResults != null) { 2707 sb.append(" found="); 2708 sb.append(mScanResults.size()); 2709 } 2710 sb.append(" known=").append(mNumScanResultsKnown); 2711 sb.append(" got=").append(mNumScanResultsReturned); 2712 if (lastScanDuration != 0) { 2713 sb.append(" dur:").append(lastScanDuration); 2714 } 2715 if (mOnTime != 0) { 2716 sb.append(" on:").append(mOnTimeThisScan).append(",").append(mOnTimeScan); 2717 sb.append(",").append(mOnTime); 2718 } 2719 if (mTxTime != 0) { 2720 sb.append(" tx:").append(mTxTimeThisScan).append(",").append(mTxTimeScan); 2721 sb.append(",").append(mTxTime); 2722 } 2723 if (mRxTime != 0) { 2724 sb.append(" rx:").append(mRxTimeThisScan).append(",").append(mRxTimeScan); 2725 sb.append(",").append(mRxTime); 2726 } 2727 sb.append(String.format(" bcn=%d", mRunningBeaconCount)); 2728 sb.append(String.format(" con=%d", mConnectionRequests)); 2729 key = mWifiConfigStore.getLastSelectedConfiguration(); 2730 if (key != null) { 2731 sb.append(" last=").append(key); 2732 } 2733 break; 2734 case WifiMonitor.SCAN_FAILED_EVENT: 2735 break; 2736 case WifiMonitor.NETWORK_CONNECTION_EVENT: 2737 sb.append(" "); 2738 sb.append(Integer.toString(msg.arg1)); 2739 sb.append(" "); 2740 sb.append(Integer.toString(msg.arg2)); 2741 sb.append(" ").append(mLastBssid); 2742 sb.append(" nid=").append(mLastNetworkId); 2743 config = getCurrentWifiConfiguration(); 2744 if (config != null) { 2745 sb.append(" ").append(config.configKey()); 2746 } 2747 sb.append(printTime()); 2748 key = mWifiConfigStore.getLastSelectedConfiguration(); 2749 if (key != null) { 2750 sb.append(" last=").append(key); 2751 } 2752 break; 2753 case CMD_TARGET_BSSID: 2754 case CMD_ASSOCIATED_BSSID: 2755 sb.append(" "); 2756 sb.append(Integer.toString(msg.arg1)); 2757 sb.append(" "); 2758 sb.append(Integer.toString(msg.arg2)); 2759 if (msg.obj != null) { 2760 sb.append(" BSSID=").append((String) msg.obj); 2761 } 2762 if (mTargetRoamBSSID != null) { 2763 sb.append(" Target=").append(mTargetRoamBSSID); 2764 } 2765 sb.append(" roam=").append(Integer.toString(mAutoRoaming)); 2766 sb.append(printTime()); 2767 break; 2768 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 2769 if (msg.obj != null) { 2770 sb.append(" ").append((String) msg.obj); 2771 } 2772 sb.append(" nid=").append(msg.arg1); 2773 sb.append(" reason=").append(msg.arg2); 2774 if (mLastBssid != null) { 2775 sb.append(" lastbssid=").append(mLastBssid); 2776 } 2777 if (mWifiInfo.getFrequency() != -1) { 2778 sb.append(" freq=").append(mWifiInfo.getFrequency()); 2779 sb.append(" rssi=").append(mWifiInfo.getRssi()); 2780 } 2781 if (linkDebouncing) { 2782 sb.append(" debounce"); 2783 } 2784 sb.append(printTime()); 2785 break; 2786 case WifiMonitor.SSID_TEMP_DISABLED: 2787 case WifiMonitor.SSID_REENABLED: 2788 sb.append(" nid=").append(msg.arg1); 2789 if (msg.obj != null) { 2790 sb.append(" ").append((String) msg.obj); 2791 } 2792 config = getCurrentWifiConfiguration(); 2793 if (config != null) { 2794 sb.append(" cur=").append(config.configKey()); 2795 sb.append(" ajst=").append(config.autoJoinStatus); 2796 if (config.selfAdded) { 2797 sb.append(" selfAdded"); 2798 } 2799 if (config.status != 0) { 2800 sb.append(" st=").append(config.status); 2801 sb.append(" rs=").append(config.disableReason); 2802 } 2803 if (config.lastConnected != 0) { 2804 now = System.currentTimeMillis(); 2805 sb.append(" lastconn=").append(now - config.lastConnected).append("(ms)"); 2806 } 2807 if (mLastBssid != null) { 2808 sb.append(" lastbssid=").append(mLastBssid); 2809 } 2810 if (mWifiInfo.getFrequency() != -1) { 2811 sb.append(" freq=").append(mWifiInfo.getFrequency()); 2812 sb.append(" rssi=").append(mWifiInfo.getRssi()); 2813 sb.append(" bssid=").append(mWifiInfo.getBSSID()); 2814 } 2815 } 2816 sb.append(printTime()); 2817 break; 2818 case CMD_RSSI_POLL: 2819 case CMD_UNWANTED_NETWORK: 2820 case WifiManager.RSSI_PKTCNT_FETCH: 2821 sb.append(" "); 2822 sb.append(Integer.toString(msg.arg1)); 2823 sb.append(" "); 2824 sb.append(Integer.toString(msg.arg2)); 2825 if (mWifiInfo.getSSID() != null) 2826 if (mWifiInfo.getSSID() != null) 2827 sb.append(" ").append(mWifiInfo.getSSID()); 2828 if (mWifiInfo.getBSSID() != null) 2829 sb.append(" ").append(mWifiInfo.getBSSID()); 2830 sb.append(" rssi=").append(mWifiInfo.getRssi()); 2831 sb.append(" f=").append(mWifiInfo.getFrequency()); 2832 sb.append(" sc=").append(mWifiInfo.score); 2833 sb.append(" link=").append(mWifiInfo.getLinkSpeed()); 2834 sb.append(String.format(" tx=%.1f,", mWifiInfo.txSuccessRate)); 2835 sb.append(String.format(" %.1f,", mWifiInfo.txRetriesRate)); 2836 sb.append(String.format(" %.1f ", mWifiInfo.txBadRate)); 2837 sb.append(String.format(" rx=%.1f", mWifiInfo.rxSuccessRate)); 2838 sb.append(String.format(" bcn=%d", mRunningBeaconCount)); 2839 report = reportOnTime(); 2840 if (report != null) { 2841 sb.append(" ").append(report); 2842 } 2843 if (wifiScoringReport != null) { 2844 sb.append(wifiScoringReport); 2845 } 2846 if (mConnectedModeGScanOffloadStarted) { 2847 sb.append(" offload-started periodMilli " + mGScanPeriodMilli); 2848 } else { 2849 sb.append(" offload-stopped"); 2850 } 2851 break; 2852 case CMD_AUTO_CONNECT: 2853 case WifiManager.CONNECT_NETWORK: 2854 sb.append(" "); 2855 sb.append(Integer.toString(msg.arg1)); 2856 sb.append(" "); 2857 sb.append(Integer.toString(msg.arg2)); 2858 config = (WifiConfiguration) msg.obj; 2859 if (config != null) { 2860 sb.append(" ").append(config.configKey()); 2861 if (config.visibility != null) { 2862 sb.append(" ").append(config.visibility.toString()); 2863 } 2864 } 2865 if (mTargetRoamBSSID != null) { 2866 sb.append(" ").append(mTargetRoamBSSID); 2867 } 2868 sb.append(" roam=").append(Integer.toString(mAutoRoaming)); 2869 sb.append(printTime()); 2870 config = getCurrentWifiConfiguration(); 2871 if (config != null) { 2872 sb.append(config.configKey()); 2873 if (config.visibility != null) { 2874 sb.append(" ").append(config.visibility.toString()); 2875 } 2876 } 2877 break; 2878 case CMD_AUTO_ROAM: 2879 sb.append(" "); 2880 sb.append(Integer.toString(msg.arg1)); 2881 sb.append(" "); 2882 sb.append(Integer.toString(msg.arg2)); 2883 ScanResult result = (ScanResult) msg.obj; 2884 if (result != null) { 2885 now = System.currentTimeMillis(); 2886 sb.append(" bssid=").append(result.BSSID); 2887 sb.append(" rssi=").append(result.level); 2888 sb.append(" freq=").append(result.frequency); 2889 if (result.seen > 0 && result.seen < now) { 2890 sb.append(" seen=").append(now - result.seen); 2891 } else { 2892 // Somehow the timestamp for this scan result is inconsistent 2893 sb.append(" !seen=").append(result.seen); 2894 } 2895 } 2896 if (mTargetRoamBSSID != null) { 2897 sb.append(" ").append(mTargetRoamBSSID); 2898 } 2899 sb.append(" roam=").append(Integer.toString(mAutoRoaming)); 2900 sb.append(" fail count=").append(Integer.toString(mRoamFailCount)); 2901 sb.append(printTime()); 2902 break; 2903 case CMD_ADD_OR_UPDATE_NETWORK: 2904 sb.append(" "); 2905 sb.append(Integer.toString(msg.arg1)); 2906 sb.append(" "); 2907 sb.append(Integer.toString(msg.arg2)); 2908 if (msg.obj != null) { 2909 config = (WifiConfiguration) msg.obj; 2910 sb.append(" ").append(config.configKey()); 2911 sb.append(" prio=").append(config.priority); 2912 sb.append(" status=").append(config.status); 2913 if (config.BSSID != null) { 2914 sb.append(" ").append(config.BSSID); 2915 } 2916 WifiConfiguration curConfig = getCurrentWifiConfiguration(); 2917 if (curConfig != null) { 2918 if (curConfig.configKey().equals(config.configKey())) { 2919 sb.append(" is current"); 2920 } else { 2921 sb.append(" current=").append(curConfig.configKey()); 2922 sb.append(" prio=").append(curConfig.priority); 2923 sb.append(" status=").append(curConfig.status); 2924 } 2925 } 2926 } 2927 break; 2928 case WifiManager.DISABLE_NETWORK: 2929 case CMD_ENABLE_NETWORK: 2930 sb.append(" "); 2931 sb.append(Integer.toString(msg.arg1)); 2932 sb.append(" "); 2933 sb.append(Integer.toString(msg.arg2)); 2934 key = mWifiConfigStore.getLastSelectedConfiguration(); 2935 if (key != null) { 2936 sb.append(" last=").append(key); 2937 } 2938 config = mWifiConfigStore.getWifiConfiguration(msg.arg1); 2939 if (config != null && (key == null || !config.configKey().equals(key))) { 2940 sb.append(" target=").append(key); 2941 } 2942 break; 2943 case CMD_GET_CONFIGURED_NETWORKS: 2944 sb.append(" "); 2945 sb.append(Integer.toString(msg.arg1)); 2946 sb.append(" "); 2947 sb.append(Integer.toString(msg.arg2)); 2948 sb.append(" num=").append(mWifiConfigStore.getConfiguredNetworksSize()); 2949 break; 2950 case DhcpStateMachine.CMD_PRE_DHCP_ACTION: 2951 sb.append(" "); 2952 sb.append(Integer.toString(msg.arg1)); 2953 sb.append(" "); 2954 sb.append(Integer.toString(msg.arg2)); 2955 sb.append(" txpkts=").append(mWifiInfo.txSuccess); 2956 sb.append(",").append(mWifiInfo.txBad); 2957 sb.append(",").append(mWifiInfo.txRetries); 2958 break; 2959 case DhcpStateMachine.CMD_POST_DHCP_ACTION: 2960 sb.append(" "); 2961 sb.append(Integer.toString(msg.arg1)); 2962 sb.append(" "); 2963 sb.append(Integer.toString(msg.arg2)); 2964 if (msg.arg1 == DhcpStateMachine.DHCP_SUCCESS) { 2965 sb.append(" OK "); 2966 } else if (msg.arg1 == DhcpStateMachine.DHCP_FAILURE) { 2967 sb.append(" FAIL "); 2968 } 2969 if (mLinkProperties != null) { 2970 if (mLinkProperties.hasIPv4Address()) { 2971 sb.append(" v4"); 2972 } 2973 if (mLinkProperties.hasGlobalIPv6Address()) { 2974 sb.append(" v6"); 2975 } 2976 if (mLinkProperties.hasIPv4DefaultRoute()) { 2977 sb.append(" v4r"); 2978 } 2979 if (mLinkProperties.hasIPv6DefaultRoute()) { 2980 sb.append(" v6r"); 2981 } 2982 if (mLinkProperties.hasIPv4DnsServer()) { 2983 sb.append(" v4dns"); 2984 } 2985 if (mLinkProperties.hasIPv6DnsServer()) { 2986 sb.append(" v6dns"); 2987 } 2988 } 2989 break; 2990 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 2991 sb.append(" "); 2992 sb.append(Integer.toString(msg.arg1)); 2993 sb.append(" "); 2994 sb.append(Integer.toString(msg.arg2)); 2995 if (msg.obj != null) { 2996 NetworkInfo info = (NetworkInfo) msg.obj; 2997 NetworkInfo.State state = info.getState(); 2998 NetworkInfo.DetailedState detailedState = info.getDetailedState(); 2999 if (state != null) { 3000 sb.append(" st=").append(state); 3001 } 3002 if (detailedState != null) { 3003 sb.append("/").append(detailedState); 3004 } 3005 } 3006 break; 3007 case CMD_IP_CONFIGURATION_LOST: 3008 int count = -1; 3009 WifiConfiguration c = getCurrentWifiConfiguration(); 3010 if (c != null) count = c.numIpConfigFailures; 3011 sb.append(" "); 3012 sb.append(Integer.toString(msg.arg1)); 3013 sb.append(" "); 3014 sb.append(Integer.toString(msg.arg2)); 3015 sb.append(" failures: "); 3016 sb.append(Integer.toString(count)); 3017 sb.append("/"); 3018 sb.append(Integer.toString(mWifiConfigStore.getMaxDhcpRetries())); 3019 if (mWifiInfo.getBSSID() != null) { 3020 sb.append(" ").append(mWifiInfo.getBSSID()); 3021 } 3022 if (c != null) { 3023 ScanDetailCache scanDetailCache = 3024 mWifiConfigStore.getScanDetailCache(c); 3025 if (scanDetailCache != null) { 3026 for (ScanDetail sd : scanDetailCache.values()) { 3027 ScanResult r = sd.getScanResult(); 3028 if (r.BSSID.equals(mWifiInfo.getBSSID())) { 3029 sb.append(" ipfail=").append(r.numIpConfigFailures); 3030 sb.append(",st=").append(r.autoJoinStatus); 3031 } 3032 } 3033 } 3034 sb.append(" -> ajst=").append(c.autoJoinStatus); 3035 sb.append(" ").append(c.disableReason); 3036 sb.append(" txpkts=").append(mWifiInfo.txSuccess); 3037 sb.append(",").append(mWifiInfo.txBad); 3038 sb.append(",").append(mWifiInfo.txRetries); 3039 } 3040 sb.append(printTime()); 3041 sb.append(String.format(" bcn=%d", mRunningBeaconCount)); 3042 break; 3043 case CMD_UPDATE_LINKPROPERTIES: 3044 sb.append(" "); 3045 sb.append(Integer.toString(msg.arg1)); 3046 sb.append(" "); 3047 sb.append(Integer.toString(msg.arg2)); 3048 if (mLinkProperties != null) { 3049 if (mLinkProperties.hasIPv4Address()) { 3050 sb.append(" v4"); 3051 } 3052 if (mLinkProperties.hasGlobalIPv6Address()) { 3053 sb.append(" v6"); 3054 } 3055 if (mLinkProperties.hasIPv4DefaultRoute()) { 3056 sb.append(" v4r"); 3057 } 3058 if (mLinkProperties.hasIPv6DefaultRoute()) { 3059 sb.append(" v6r"); 3060 } 3061 if (mLinkProperties.hasIPv4DnsServer()) { 3062 sb.append(" v4dns"); 3063 } 3064 if (mLinkProperties.hasIPv6DnsServer()) { 3065 sb.append(" v6dns"); 3066 } 3067 } 3068 break; 3069 case CMD_IP_REACHABILITY_LOST: 3070 if (msg.obj != null) { 3071 sb.append(" ").append((String) msg.obj); 3072 } 3073 break; 3074 case CMD_SET_COUNTRY_CODE: 3075 sb.append(" "); 3076 sb.append(Integer.toString(msg.arg1)); 3077 sb.append(" "); 3078 sb.append(Integer.toString(msg.arg2)); 3079 if (msg.obj != null) { 3080 sb.append(" ").append((String) msg.obj); 3081 } 3082 break; 3083 case CMD_ROAM_WATCHDOG_TIMER: 3084 sb.append(" "); 3085 sb.append(Integer.toString(msg.arg1)); 3086 sb.append(" "); 3087 sb.append(Integer.toString(msg.arg2)); 3088 sb.append(" cur=").append(roamWatchdogCount); 3089 break; 3090 case CMD_DISCONNECTING_WATCHDOG_TIMER: 3091 sb.append(" "); 3092 sb.append(Integer.toString(msg.arg1)); 3093 sb.append(" "); 3094 sb.append(Integer.toString(msg.arg2)); 3095 sb.append(" cur=").append(disconnectingWatchdogCount); 3096 break; 3097 default: 3098 sb.append(" "); 3099 sb.append(Integer.toString(msg.arg1)); 3100 sb.append(" "); 3101 sb.append(Integer.toString(msg.arg2)); 3102 break; 3103 } 3104 3105 return sb.toString(); 3106 } 3107 3108 private void stopPnoOffload() { 3109 3110 // clear the PNO list 3111 if (!WifiNative.setPnoList(null, WifiStateMachine.this)) { 3112 Log.e(TAG, "Failed to stop pno"); 3113 } 3114 3115 } 3116 3117 3118 private boolean configureSsidWhiteList() { 3119 3120 mWhiteListedSsids = mWifiConfigStore.getWhiteListedSsids(getCurrentWifiConfiguration()); 3121 if (mWhiteListedSsids == null || mWhiteListedSsids.length == 0) { 3122 return true; 3123 } 3124 3125 if (!WifiNative.setSsidWhitelist(mWhiteListedSsids)) { 3126 loge("configureSsidWhiteList couldnt program SSID list, size " 3127 + mWhiteListedSsids.length); 3128 return false; 3129 } 3130 3131 loge("configureSsidWhiteList success"); 3132 return true; 3133 } 3134 3135 // In associated more, lazy roam will be looking for 5GHz roam candidate 3136 private boolean configureLazyRoam() { 3137 boolean status; 3138 if (!useHalBasedAutoJoinOffload()) return false; 3139 3140 WifiNative.WifiLazyRoamParams params = mWifiNative.new WifiLazyRoamParams(); 3141 params.A_band_boost_threshold = mWifiConfigStore.bandPreferenceBoostThreshold5.get(); 3142 params.A_band_penalty_threshold = mWifiConfigStore.bandPreferencePenaltyThreshold5.get(); 3143 params.A_band_boost_factor = mWifiConfigStore.bandPreferenceBoostFactor5; 3144 params.A_band_penalty_factor = mWifiConfigStore.bandPreferencePenaltyFactor5; 3145 params.A_band_max_boost = 65; 3146 params.lazy_roam_hysteresis = 25; 3147 params.alert_roam_rssi_trigger = -75; 3148 3149 if (DBG) { 3150 Log.e(TAG, "configureLazyRoam " + params.toString()); 3151 } 3152 3153 if (!WifiNative.setLazyRoam(true, params)) { 3154 3155 Log.e(TAG, "configureLazyRoam couldnt program params"); 3156 3157 return false; 3158 } 3159 if (DBG) { 3160 Log.e(TAG, "configureLazyRoam success"); 3161 } 3162 return true; 3163 } 3164 3165 // In associated more, lazy roam will be looking for 5GHz roam candidate 3166 private boolean stopLazyRoam() { 3167 boolean status; 3168 if (!useHalBasedAutoJoinOffload()) return false; 3169 if (DBG) { 3170 Log.e(TAG, "stopLazyRoam"); 3171 } 3172 return WifiNative.setLazyRoam(false, null); 3173 } 3174 3175 private boolean startGScanConnectedModeOffload(String reason) { 3176 if (DBG) { 3177 if (reason == null) { 3178 reason = ""; 3179 } 3180 loge("startGScanConnectedModeOffload " + reason); 3181 } 3182 stopGScan("startGScanConnectedModeOffload " + reason); 3183 if (!mScreenOn) return false; 3184 3185 if (USE_PAUSE_SCANS) { 3186 mWifiNative.pauseScan(); 3187 } 3188 mPnoEnabled = configurePno(); 3189 if (mPnoEnabled == false) { 3190 if (USE_PAUSE_SCANS) { 3191 mWifiNative.restartScan(); 3192 } 3193 return false; 3194 } 3195 mLazyRoamEnabled = configureLazyRoam(); 3196 if (mLazyRoamEnabled == false) { 3197 if (USE_PAUSE_SCANS) { 3198 mWifiNative.restartScan(); 3199 } 3200 return false; 3201 } 3202 if (mWifiConfigStore.getLastSelectedConfiguration() == null) { 3203 configureSsidWhiteList(); 3204 } 3205 if (!startConnectedGScan(reason)) { 3206 if (USE_PAUSE_SCANS) { 3207 mWifiNative.restartScan(); 3208 } 3209 return false; 3210 } 3211 if (USE_PAUSE_SCANS) { 3212 mWifiNative.restartScan(); 3213 } 3214 mConnectedModeGScanOffloadStarted = true; 3215 if (DBG) { 3216 loge("startGScanConnectedModeOffload success"); 3217 } 3218 return true; 3219 } 3220 3221 private boolean startGScanDisconnectedModeOffload(String reason) { 3222 if (DBG) { 3223 loge("startGScanDisconnectedModeOffload " + reason); 3224 } 3225 stopGScan("startGScanDisconnectedModeOffload " + reason); 3226 if (USE_PAUSE_SCANS) { 3227 mWifiNative.pauseScan(); 3228 } 3229 mPnoEnabled = configurePno(); 3230 if (mPnoEnabled == false) { 3231 if (USE_PAUSE_SCANS) { 3232 mWifiNative.restartScan(); 3233 } 3234 return false; 3235 } 3236 if (!startDisconnectedGScan(reason)) { 3237 if (USE_PAUSE_SCANS) { 3238 mWifiNative.restartScan(); 3239 } 3240 return false; 3241 } 3242 if (USE_PAUSE_SCANS) { 3243 mWifiNative.restartScan(); 3244 } 3245 return true; 3246 } 3247 3248 private boolean configurePno() { 3249 if (!useHalBasedAutoJoinOffload()) return false; 3250 3251 if (mWifiScanner == null) { 3252 log("configurePno: mWifiScanner is null "); 3253 return true; 3254 } 3255 3256 List<WifiNative.WifiPnoNetwork> llist 3257 = mWifiAutoJoinController.getPnoList(getCurrentWifiConfiguration()); 3258 if (llist == null || llist.size() == 0) { 3259 stopPnoOffload(); 3260 log("configurePno: empty PNO list "); 3261 return true; 3262 } 3263 if (DBG) { 3264 log("configurePno: got llist size " + llist.size()); 3265 } 3266 3267 // first program the network we want to look for thru the pno API 3268 WifiNative.WifiPnoNetwork list[] 3269 = (WifiNative.WifiPnoNetwork[]) llist.toArray(new WifiNative.WifiPnoNetwork[0]); 3270 3271 if (!WifiNative.setPnoList(list, WifiStateMachine.this)) { 3272 Log.e(TAG, "Failed to set pno, length = " + list.length); 3273 return false; 3274 } 3275 3276 if (true) { 3277 StringBuilder sb = new StringBuilder(); 3278 for (WifiNative.WifiPnoNetwork network : list) { 3279 sb.append("[").append(network.SSID).append(" auth=").append(network.auth); 3280 sb.append(" flags="); 3281 sb.append(network.flags).append(" rssi").append(network.rssi_threshold); 3282 sb.append("] "); 3283 3284 } 3285 sendMessage(CMD_STARTED_PNO_DBG, 1, (int)mGScanPeriodMilli, sb.toString()); 3286 } 3287 return true; 3288 } 3289 3290 final static int DISCONNECTED_SHORT_SCANS_DURATION_MILLI = 2 * 60 * 1000; 3291 final static int CONNECTED_SHORT_SCANS_DURATION_MILLI = 2 * 60 * 1000; 3292 3293 private boolean startConnectedGScan(String reason) { 3294 // send a scan background request so as to kick firmware 3295 // 5GHz roaming and autojoin 3296 // We do this only if screen is on 3297 WifiScanner.ScanSettings settings; 3298 3299 if (mPnoEnabled || mLazyRoamEnabled) { 3300 settings = new WifiScanner.ScanSettings(); 3301 settings.band = WifiScanner.WIFI_BAND_BOTH; 3302 long now = System.currentTimeMillis(); 3303 3304 if (!mScreenOn || (mGScanStartTimeMilli!= 0 && now > mGScanStartTimeMilli 3305 && ((now - mGScanStartTimeMilli) > CONNECTED_SHORT_SCANS_DURATION_MILLI))) { 3306 settings.periodInMs = mWifiConfigStore.wifiAssociatedLongScanIntervalMilli.get(); 3307 } else { 3308 mGScanStartTimeMilli = now; 3309 settings.periodInMs = mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(); 3310 // if we start offload with short interval, then reconfigure it after a given 3311 // duration of time so as to reduce the scan frequency 3312 int delay = 30 * 1000 + CONNECTED_SHORT_SCANS_DURATION_MILLI; 3313 sendMessageDelayed(CMD_RESTART_AUTOJOIN_OFFLOAD, delay, 3314 mRestartAutoJoinOffloadCounter, " startConnectedGScan " + reason, 3315 (long)delay); 3316 mRestartAutoJoinOffloadCounter++; 3317 } 3318 mGScanPeriodMilli = settings.periodInMs; 3319 settings.reportEvents = WifiScanner.REPORT_EVENT_AFTER_BUFFER_FULL; 3320 if (DBG) { 3321 log("startConnectedScan: settings band="+ settings.band 3322 + " period=" + settings.periodInMs); 3323 } 3324 3325 mWifiScanner.startBackgroundScan(settings, mWifiScanListener); 3326 if (true) { 3327 sendMessage(CMD_STARTED_GSCAN_DBG, 1, (int)mGScanPeriodMilli, reason); 3328 } 3329 } 3330 return true; 3331 } 3332 3333 private boolean startDisconnectedGScan(String reason) { 3334 // send a scan background request so as to kick firmware 3335 // PNO 3336 // This is done in both screen On and screen Off modes 3337 WifiScanner.ScanSettings settings; 3338 3339 if (mWifiScanner == null) { 3340 log("startDisconnectedGScan: no wifi scanner"); 3341 return false; 3342 } 3343 3344 if (mPnoEnabled || mLazyRoamEnabled) { 3345 settings = new WifiScanner.ScanSettings(); 3346 settings.band = WifiScanner.WIFI_BAND_BOTH; 3347 long now = System.currentTimeMillis(); 3348 3349 3350 if (!mScreenOn || (mGScanStartTimeMilli != 0 && now > mGScanStartTimeMilli 3351 && ((now - mGScanStartTimeMilli) > DISCONNECTED_SHORT_SCANS_DURATION_MILLI))) { 3352 settings.periodInMs = mWifiConfigStore.wifiDisconnectedLongScanIntervalMilli.get(); 3353 } else { 3354 settings.periodInMs = mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get(); 3355 mGScanStartTimeMilli = now; 3356 // if we start offload with short interval, then reconfigure it after a given 3357 // duration of time so as to reduce the scan frequency 3358 int delay = 30 * 1000 + DISCONNECTED_SHORT_SCANS_DURATION_MILLI; 3359 sendMessageDelayed(CMD_RESTART_AUTOJOIN_OFFLOAD, delay, 3360 mRestartAutoJoinOffloadCounter, " startDisconnectedGScan " + reason, 3361 (long)delay); 3362 mRestartAutoJoinOffloadCounter++; 3363 } 3364 mGScanPeriodMilli = settings.periodInMs; 3365 settings.reportEvents = WifiScanner.REPORT_EVENT_AFTER_BUFFER_FULL; 3366 if (DBG) { 3367 log("startDisconnectedScan: settings band="+ settings.band 3368 + " period=" + settings.periodInMs); 3369 } 3370 mWifiScanner.startBackgroundScan(settings, mWifiScanListener); 3371 if (true) { 3372 sendMessage(CMD_STARTED_GSCAN_DBG, 1, (int)mGScanPeriodMilli, reason); 3373 } 3374 } 3375 return true; 3376 } 3377 3378 private boolean stopGScan(String reason) { 3379 mGScanStartTimeMilli = 0; 3380 mGScanPeriodMilli = 0; 3381 if (mWifiScanner != null) { 3382 mWifiScanner.stopBackgroundScan(mWifiScanListener); 3383 } 3384 mConnectedModeGScanOffloadStarted = false; 3385 if (true) { 3386 sendMessage(CMD_STARTED_GSCAN_DBG, 0, 0, reason); 3387 } 3388 return true; 3389 } 3390 3391 private void handleScreenStateChanged(boolean screenOn) { 3392 mScreenOn = screenOn; 3393 if (PDBG) { 3394 loge(" handleScreenStateChanged Enter: screenOn=" + screenOn 3395 + " mUserWantsSuspendOpt=" + mUserWantsSuspendOpt 3396 + " state " + getCurrentState().getName() 3397 + " suppState:" + mSupplicantStateTracker.getSupplicantStateName()); 3398 } 3399 enableRssiPolling(screenOn); 3400 if (screenOn) enableAllNetworks(); 3401 if (mUserWantsSuspendOpt.get()) { 3402 if (screenOn) { 3403 sendMessage(CMD_SET_SUSPEND_OPT_ENABLED, 0, 0); 3404 } else { 3405 // Allow 2s for suspend optimizations to be set 3406 mSuspendWakeLock.acquire(2000); 3407 sendMessage(CMD_SET_SUSPEND_OPT_ENABLED, 1, 0); 3408 } 3409 } 3410 mScreenBroadcastReceived.set(true); 3411 3412 getWifiLinkLayerStats(false); 3413 mOnTimeScreenStateChange = mOnTime; 3414 lastScreenStateChangeTimeStamp = lastLinkLayerStatsUpdate; 3415 3416 cancelDelayedScan(); 3417 3418 if (screenOn) { 3419 enableBackgroundScan(false); 3420 setScanAlarm(false); 3421 clearBlacklist(); 3422 3423 fullBandConnectedTimeIntervalMilli 3424 = mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(); 3425 // In either Disconnectedstate or ConnectedState, 3426 // start the scan alarm so as to enable autojoin 3427 if (getCurrentState() == mConnectedState 3428 && allowFullBandScanAndAssociated()) { 3429 if (useHalBasedAutoJoinOffload()) { 3430 startGScanConnectedModeOffload("screenOnConnected"); 3431 } else { 3432 // Scan after 500ms 3433 startDelayedScan(500, null, null); 3434 } 3435 } else if (getCurrentState() == mDisconnectedState) { 3436 if (useHalBasedAutoJoinOffload()) { 3437 startGScanDisconnectedModeOffload("screenOnDisconnected"); 3438 } else { 3439 // Scan after 500ms 3440 startDelayedScan(500, null, null); 3441 } 3442 } 3443 } else { 3444 if (getCurrentState() == mDisconnectedState) { 3445 // Screen Off and Disconnected and chipset doesn't support scan offload 3446 // => start scan alarm 3447 // Screen Off and Disconnected and chipset does support scan offload 3448 // => will use scan offload (i.e. background scan) 3449 if (useHalBasedAutoJoinOffload()) { 3450 startGScanDisconnectedModeOffload("screenOffDisconnected"); 3451 } else { 3452 if (!mBackgroundScanSupported) { 3453 setScanAlarm(true); 3454 } else { 3455 if (!mIsScanOngoing) { 3456 enableBackgroundScan(true); 3457 } 3458 } 3459 } 3460 } else { 3461 enableBackgroundScan(false); 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 // Enable link layer stats gathering 6071 mWifiNative.setWifiLinkLayerStats("wlan0", 1); 6072 6073 if (PDBG) { 6074 loge("Driverstarted State enter done, epno=" + mHalBasedPnoDriverSupported 6075 + " feature=" + mHalFeatureSet); 6076 } 6077 } 6078 6079 @Override 6080 public boolean processMessage(Message message) { 6081 logStateAndMessage(message, getClass().getSimpleName()); 6082 6083 switch(message.what) { 6084 case CMD_START_SCAN: 6085 handleScanRequest(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message); 6086 break; 6087 case CMD_SET_FREQUENCY_BAND: 6088 int band = message.arg1; 6089 if (DBG) log("set frequency band " + band); 6090 if (mWifiNative.setBand(band)) { 6091 6092 if (PDBG) loge("did set frequency band " + band); 6093 6094 mFrequencyBand.set(band); 6095 // Flush old data - like scan results 6096 mWifiNative.bssFlush(); 6097 // Fetch the latest scan results when frequency band is set 6098// startScanNative(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, null); 6099 6100 if (PDBG) loge("done set frequency band " + band); 6101 6102 } else { 6103 loge("Failed to set frequency band " + band); 6104 } 6105 break; 6106 case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE: 6107 mBluetoothConnectionActive = (message.arg1 != 6108 BluetoothAdapter.STATE_DISCONNECTED); 6109 mWifiNative.setBluetoothCoexistenceScanMode(mBluetoothConnectionActive); 6110 break; 6111 case CMD_STOP_DRIVER: 6112 int mode = message.arg1; 6113 6114 /* Already doing a delayed stop */ 6115 if (mInDelayedStop) { 6116 if (DBG) log("Already in delayed stop"); 6117 break; 6118 } 6119 /* disconnect right now, but leave the driver running for a bit */ 6120 mWifiConfigStore.disableAllNetworks(); 6121 6122 mInDelayedStop = true; 6123 mDelayedStopCounter++; 6124 if (DBG) log("Delayed stop message " + mDelayedStopCounter); 6125 6126 /* send regular delayed shut down */ 6127 Intent driverStopIntent = new Intent(ACTION_DELAYED_DRIVER_STOP, null); 6128 driverStopIntent.setPackage(this.getClass().getPackage().getName()); 6129 driverStopIntent.putExtra(DELAYED_STOP_COUNTER, mDelayedStopCounter); 6130 mDriverStopIntent = PendingIntent.getBroadcast(mContext, 6131 DRIVER_STOP_REQUEST, driverStopIntent, 6132 PendingIntent.FLAG_UPDATE_CURRENT); 6133 6134 mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() 6135 + mDriverStopDelayMs, mDriverStopIntent); 6136 break; 6137 case CMD_START_DRIVER: 6138 if (mInDelayedStop) { 6139 mInDelayedStop = false; 6140 mDelayedStopCounter++; 6141 mAlarmManager.cancel(mDriverStopIntent); 6142 if (DBG) log("Delayed stop ignored due to start"); 6143 if (mOperationalMode == CONNECT_MODE) { 6144 mWifiConfigStore.enableAllNetworks(); 6145 } 6146 } 6147 break; 6148 case CMD_DELAYED_STOP_DRIVER: 6149 if (DBG) log("delayed stop " + message.arg1 + " " + mDelayedStopCounter); 6150 if (message.arg1 != mDelayedStopCounter) break; 6151 if (getCurrentState() != mDisconnectedState) { 6152 mWifiNative.disconnect(); 6153 handleNetworkDisconnect(); 6154 } 6155 mWakeLock.acquire(); 6156 mWifiNative.stopDriver(); 6157 mWakeLock.release(); 6158 if (mP2pSupported) { 6159 transitionTo(mWaitForP2pDisableState); 6160 } else { 6161 transitionTo(mDriverStoppingState); 6162 } 6163 break; 6164 case CMD_START_PACKET_FILTERING: 6165 if (message.arg1 == MULTICAST_V6) { 6166 mWifiNative.startFilteringMulticastV6Packets(); 6167 } else if (message.arg1 == MULTICAST_V4) { 6168 mWifiNative.startFilteringMulticastV4Packets(); 6169 } else { 6170 loge("Illegal arugments to CMD_START_PACKET_FILTERING"); 6171 } 6172 break; 6173 case CMD_STOP_PACKET_FILTERING: 6174 if (message.arg1 == MULTICAST_V6) { 6175 mWifiNative.stopFilteringMulticastV6Packets(); 6176 } else if (message.arg1 == MULTICAST_V4) { 6177 mWifiNative.stopFilteringMulticastV4Packets(); 6178 } else { 6179 loge("Illegal arugments to CMD_STOP_PACKET_FILTERING"); 6180 } 6181 break; 6182 case CMD_SET_SUSPEND_OPT_ENABLED: 6183 if (message.arg1 == 1) { 6184 setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, true); 6185 mSuspendWakeLock.release(); 6186 } else { 6187 setSuspendOptimizationsNative(SUSPEND_DUE_TO_SCREEN, false); 6188 } 6189 break; 6190 case CMD_SET_HIGH_PERF_MODE: 6191 if (message.arg1 == 1) { 6192 setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, false); 6193 } else { 6194 setSuspendOptimizationsNative(SUSPEND_DUE_TO_HIGH_PERF, true); 6195 } 6196 break; 6197 case CMD_ENABLE_TDLS: 6198 if (message.obj != null) { 6199 String remoteAddress = (String) message.obj; 6200 boolean enable = (message.arg1 == 1); 6201 mWifiNative.startTdls(remoteAddress, enable); 6202 } 6203 break; 6204 case WifiMonitor.ANQP_DONE_EVENT: 6205 mWifiConfigStore.notifyANQPDone((Long) message.obj, message.arg1 != 0); 6206 break; 6207 default: 6208 return NOT_HANDLED; 6209 } 6210 return HANDLED; 6211 } 6212 @Override 6213 public void exit() { 6214 6215 mWifiLogger.stopLogging(); 6216 6217 mIsRunning = false; 6218 updateBatteryWorkSource(null); 6219 mScanResults = new ArrayList<>(); 6220 6221 final Intent intent = new Intent(WifiManager.WIFI_SCAN_AVAILABLE); 6222 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 6223 intent.putExtra(WifiManager.EXTRA_SCAN_AVAILABLE, WIFI_STATE_DISABLED); 6224 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL); 6225 noteScanEnd(); // wrap up any pending request. 6226 mBufferedScanMsg.clear(); 6227 } 6228 } 6229 6230 class WaitForP2pDisableState extends State { 6231 private State mTransitionToState; 6232 @Override 6233 public void enter() { 6234 switch (getCurrentMessage().what) { 6235 case WifiMonitor.SUP_DISCONNECTION_EVENT: 6236 mTransitionToState = mInitialState; 6237 break; 6238 case CMD_DELAYED_STOP_DRIVER: 6239 mTransitionToState = mDriverStoppingState; 6240 break; 6241 case CMD_STOP_SUPPLICANT: 6242 mTransitionToState = mSupplicantStoppingState; 6243 break; 6244 default: 6245 mTransitionToState = mDriverStoppingState; 6246 break; 6247 } 6248 mWifiP2pChannel.sendMessage(WifiStateMachine.CMD_DISABLE_P2P_REQ); 6249 } 6250 @Override 6251 public boolean processMessage(Message message) { 6252 logStateAndMessage(message, getClass().getSimpleName()); 6253 6254 switch(message.what) { 6255 case WifiStateMachine.CMD_DISABLE_P2P_RSP: 6256 transitionTo(mTransitionToState); 6257 break; 6258 /* Defer wifi start/shut and driver commands */ 6259 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6260 case CMD_START_SUPPLICANT: 6261 case CMD_STOP_SUPPLICANT: 6262 case CMD_START_AP: 6263 case CMD_STOP_AP: 6264 case CMD_START_DRIVER: 6265 case CMD_STOP_DRIVER: 6266 case CMD_SET_OPERATIONAL_MODE: 6267 case CMD_SET_COUNTRY_CODE: 6268 case CMD_SET_FREQUENCY_BAND: 6269 case CMD_START_PACKET_FILTERING: 6270 case CMD_STOP_PACKET_FILTERING: 6271 case CMD_START_SCAN: 6272 case CMD_DISCONNECT: 6273 case CMD_REASSOCIATE: 6274 case CMD_RECONNECT: 6275 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 6276 deferMessage(message); 6277 break; 6278 default: 6279 return NOT_HANDLED; 6280 } 6281 return HANDLED; 6282 } 6283 } 6284 6285 class DriverStoppingState extends State { 6286 @Override 6287 public boolean processMessage(Message message) { 6288 logStateAndMessage(message, getClass().getSimpleName()); 6289 6290 switch(message.what) { 6291 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6292 SupplicantState state = handleSupplicantStateChange(message); 6293 if (state == SupplicantState.INTERFACE_DISABLED) { 6294 transitionTo(mDriverStoppedState); 6295 } 6296 break; 6297 /* Queue driver commands */ 6298 case CMD_START_DRIVER: 6299 case CMD_STOP_DRIVER: 6300 case CMD_SET_COUNTRY_CODE: 6301 case CMD_SET_FREQUENCY_BAND: 6302 case CMD_START_PACKET_FILTERING: 6303 case CMD_STOP_PACKET_FILTERING: 6304 case CMD_START_SCAN: 6305 case CMD_DISCONNECT: 6306 case CMD_REASSOCIATE: 6307 case CMD_RECONNECT: 6308 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 6309 deferMessage(message); 6310 break; 6311 default: 6312 return NOT_HANDLED; 6313 } 6314 return HANDLED; 6315 } 6316 } 6317 6318 class DriverStoppedState extends State { 6319 @Override 6320 public boolean processMessage(Message message) { 6321 logStateAndMessage(message, getClass().getSimpleName()); 6322 switch (message.what) { 6323 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6324 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 6325 SupplicantState state = stateChangeResult.state; 6326 // A WEXT bug means that we can be back to driver started state 6327 // unexpectedly 6328 if (SupplicantState.isDriverActive(state)) { 6329 transitionTo(mDriverStartedState); 6330 } 6331 break; 6332 case CMD_START_DRIVER: 6333 mWakeLock.acquire(); 6334 mWifiNative.startDriver(); 6335 mWakeLock.release(); 6336 transitionTo(mDriverStartingState); 6337 break; 6338 default: 6339 return NOT_HANDLED; 6340 } 6341 return HANDLED; 6342 } 6343 } 6344 6345 class ScanModeState extends State { 6346 private int mLastOperationMode; 6347 @Override 6348 public void enter() { 6349 mLastOperationMode = mOperationalMode; 6350 } 6351 @Override 6352 public boolean processMessage(Message message) { 6353 logStateAndMessage(message, getClass().getSimpleName()); 6354 6355 switch(message.what) { 6356 case CMD_SET_OPERATIONAL_MODE: 6357 if (message.arg1 == CONNECT_MODE) { 6358 6359 if (mLastOperationMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 6360 setWifiState(WIFI_STATE_ENABLED); 6361 // Load and re-enable networks when going back to enabled state 6362 // This is essential for networks to show up after restore 6363 mWifiConfigStore.loadAndEnableAllNetworks(); 6364 mWifiP2pChannel.sendMessage(CMD_ENABLE_P2P); 6365 } else { 6366 mWifiConfigStore.enableAllNetworks(); 6367 } 6368 6369 // Try autojoining with recent network already present in the cache 6370 // If none are found then trigger a scan which will trigger autojoin 6371 // upon reception of scan results event 6372 if (!mWifiAutoJoinController.attemptAutoJoin()) { 6373 startScan(ENABLE_WIFI, 0, null, null); 6374 } 6375 6376 // Loose last selection choice since user toggled WiFi 6377 mWifiConfigStore. 6378 setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID); 6379 6380 mOperationalMode = CONNECT_MODE; 6381 transitionTo(mDisconnectedState); 6382 } else { 6383 // Nothing to do 6384 return HANDLED; 6385 } 6386 break; 6387 // Handle scan. All the connection related commands are 6388 // handled only in ConnectModeState 6389 case CMD_START_SCAN: 6390 handleScanRequest(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message); 6391 break; 6392 default: 6393 return NOT_HANDLED; 6394 } 6395 return HANDLED; 6396 } 6397 } 6398 6399 6400 String smToString(Message message) { 6401 return smToString(message.what); 6402 } 6403 6404 String smToString(int what) { 6405 String s = "unknown"; 6406 switch (what) { 6407 case WifiMonitor.DRIVER_HUNG_EVENT: 6408 s = "DRIVER_HUNG_EVENT"; 6409 break; 6410 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: 6411 s = "AsyncChannel.CMD_CHANNEL_HALF_CONNECTED"; 6412 break; 6413 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: 6414 s = "AsyncChannel.CMD_CHANNEL_DISCONNECTED"; 6415 break; 6416 case CMD_SET_FREQUENCY_BAND: 6417 s = "CMD_SET_FREQUENCY_BAND"; 6418 break; 6419 case CMD_DELAYED_NETWORK_DISCONNECT: 6420 s = "CMD_DELAYED_NETWORK_DISCONNECT"; 6421 break; 6422 case CMD_TEST_NETWORK_DISCONNECT: 6423 s = "CMD_TEST_NETWORK_DISCONNECT"; 6424 break; 6425 case CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER: 6426 s = "CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER"; 6427 break; 6428 case CMD_DISABLE_EPHEMERAL_NETWORK: 6429 s = "CMD_DISABLE_EPHEMERAL_NETWORK"; 6430 break; 6431 case CMD_START_DRIVER: 6432 s = "CMD_START_DRIVER"; 6433 break; 6434 case CMD_STOP_DRIVER: 6435 s = "CMD_STOP_DRIVER"; 6436 break; 6437 case CMD_STOP_SUPPLICANT: 6438 s = "CMD_STOP_SUPPLICANT"; 6439 break; 6440 case CMD_STOP_SUPPLICANT_FAILED: 6441 s = "CMD_STOP_SUPPLICANT_FAILED"; 6442 break; 6443 case CMD_START_SUPPLICANT: 6444 s = "CMD_START_SUPPLICANT"; 6445 break; 6446 case CMD_REQUEST_AP_CONFIG: 6447 s = "CMD_REQUEST_AP_CONFIG"; 6448 break; 6449 case CMD_RESPONSE_AP_CONFIG: 6450 s = "CMD_RESPONSE_AP_CONFIG"; 6451 break; 6452 case CMD_TETHER_STATE_CHANGE: 6453 s = "CMD_TETHER_STATE_CHANGE"; 6454 break; 6455 case CMD_TETHER_NOTIFICATION_TIMED_OUT: 6456 s = "CMD_TETHER_NOTIFICATION_TIMED_OUT"; 6457 break; 6458 case CMD_BLUETOOTH_ADAPTER_STATE_CHANGE: 6459 s = "CMD_BLUETOOTH_ADAPTER_STATE_CHANGE"; 6460 break; 6461 case CMD_ADD_OR_UPDATE_NETWORK: 6462 s = "CMD_ADD_OR_UPDATE_NETWORK"; 6463 break; 6464 case CMD_REMOVE_NETWORK: 6465 s = "CMD_REMOVE_NETWORK"; 6466 break; 6467 case CMD_ENABLE_NETWORK: 6468 s = "CMD_ENABLE_NETWORK"; 6469 break; 6470 case CMD_ENABLE_ALL_NETWORKS: 6471 s = "CMD_ENABLE_ALL_NETWORKS"; 6472 break; 6473 case CMD_AUTO_CONNECT: 6474 s = "CMD_AUTO_CONNECT"; 6475 break; 6476 case CMD_AUTO_ROAM: 6477 s = "CMD_AUTO_ROAM"; 6478 break; 6479 case CMD_AUTO_SAVE_NETWORK: 6480 s = "CMD_AUTO_SAVE_NETWORK"; 6481 break; 6482 case CMD_BOOT_COMPLETED: 6483 s = "CMD_BOOT_COMPLETED"; 6484 break; 6485 case DhcpStateMachine.CMD_START_DHCP: 6486 s = "CMD_START_DHCP"; 6487 break; 6488 case DhcpStateMachine.CMD_STOP_DHCP: 6489 s = "CMD_STOP_DHCP"; 6490 break; 6491 case DhcpStateMachine.CMD_RENEW_DHCP: 6492 s = "CMD_RENEW_DHCP"; 6493 break; 6494 case DhcpStateMachine.CMD_PRE_DHCP_ACTION: 6495 s = "CMD_PRE_DHCP_ACTION"; 6496 break; 6497 case DhcpStateMachine.CMD_POST_DHCP_ACTION: 6498 s = "CMD_POST_DHCP_ACTION"; 6499 break; 6500 case DhcpStateMachine.CMD_PRE_DHCP_ACTION_COMPLETE: 6501 s = "CMD_PRE_DHCP_ACTION_COMPLETE"; 6502 break; 6503 case DhcpStateMachine.CMD_ON_QUIT: 6504 s = "CMD_ON_QUIT"; 6505 break; 6506 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 6507 s = "WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST"; 6508 break; 6509 case WifiManager.DISABLE_NETWORK: 6510 s = "WifiManager.DISABLE_NETWORK"; 6511 break; 6512 case CMD_BLACKLIST_NETWORK: 6513 s = "CMD_BLACKLIST_NETWORK"; 6514 break; 6515 case CMD_CLEAR_BLACKLIST: 6516 s = "CMD_CLEAR_BLACKLIST"; 6517 break; 6518 case CMD_SAVE_CONFIG: 6519 s = "CMD_SAVE_CONFIG"; 6520 break; 6521 case CMD_GET_CONFIGURED_NETWORKS: 6522 s = "CMD_GET_CONFIGURED_NETWORKS"; 6523 break; 6524 case CMD_GET_SUPPORTED_FEATURES: 6525 s = "CMD_GET_SUPPORTED_FEATURES"; 6526 break; 6527 case CMD_UNWANTED_NETWORK: 6528 s = "CMD_UNWANTED_NETWORK"; 6529 break; 6530 case CMD_NETWORK_STATUS: 6531 s = "CMD_NETWORK_STATUS"; 6532 break; 6533 case CMD_GET_LINK_LAYER_STATS: 6534 s = "CMD_GET_LINK_LAYER_STATS"; 6535 break; 6536 case CMD_GET_MATCHING_CONFIG: 6537 s = "CMD_GET_MATCHING_CONFIG"; 6538 break; 6539 case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS: 6540 s = "CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS"; 6541 break; 6542 case CMD_DISCONNECT: 6543 s = "CMD_DISCONNECT"; 6544 break; 6545 case CMD_RECONNECT: 6546 s = "CMD_RECONNECT"; 6547 break; 6548 case CMD_REASSOCIATE: 6549 s = "CMD_REASSOCIATE"; 6550 break; 6551 case CMD_GET_CONNECTION_STATISTICS: 6552 s = "CMD_GET_CONNECTION_STATISTICS"; 6553 break; 6554 case CMD_SET_HIGH_PERF_MODE: 6555 s = "CMD_SET_HIGH_PERF_MODE"; 6556 break; 6557 case CMD_SET_COUNTRY_CODE: 6558 s = "CMD_SET_COUNTRY_CODE"; 6559 break; 6560 case CMD_ENABLE_RSSI_POLL: 6561 s = "CMD_ENABLE_RSSI_POLL"; 6562 break; 6563 case CMD_RSSI_POLL: 6564 s = "CMD_RSSI_POLL"; 6565 break; 6566 case CMD_START_PACKET_FILTERING: 6567 s = "CMD_START_PACKET_FILTERING"; 6568 break; 6569 case CMD_STOP_PACKET_FILTERING: 6570 s = "CMD_STOP_PACKET_FILTERING"; 6571 break; 6572 case CMD_SET_SUSPEND_OPT_ENABLED: 6573 s = "CMD_SET_SUSPEND_OPT_ENABLED"; 6574 break; 6575 case CMD_NO_NETWORKS_PERIODIC_SCAN: 6576 s = "CMD_NO_NETWORKS_PERIODIC_SCAN"; 6577 break; 6578 case CMD_UPDATE_LINKPROPERTIES: 6579 s = "CMD_UPDATE_LINKPROPERTIES"; 6580 break; 6581 case CMD_RELOAD_TLS_AND_RECONNECT: 6582 s = "CMD_RELOAD_TLS_AND_RECONNECT"; 6583 break; 6584 case WifiManager.CONNECT_NETWORK: 6585 s = "CONNECT_NETWORK"; 6586 break; 6587 case WifiManager.SAVE_NETWORK: 6588 s = "SAVE_NETWORK"; 6589 break; 6590 case WifiManager.FORGET_NETWORK: 6591 s = "FORGET_NETWORK"; 6592 break; 6593 case WifiMonitor.SUP_CONNECTION_EVENT: 6594 s = "SUP_CONNECTION_EVENT"; 6595 break; 6596 case WifiMonitor.SUP_DISCONNECTION_EVENT: 6597 s = "SUP_DISCONNECTION_EVENT"; 6598 break; 6599 case WifiMonitor.SCAN_RESULTS_EVENT: 6600 s = "SCAN_RESULTS_EVENT"; 6601 break; 6602 case WifiMonitor.SCAN_FAILED_EVENT: 6603 s = "SCAN_FAILED_EVENT"; 6604 break; 6605 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6606 s = "SUPPLICANT_STATE_CHANGE_EVENT"; 6607 break; 6608 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 6609 s = "AUTHENTICATION_FAILURE_EVENT"; 6610 break; 6611 case WifiMonitor.SSID_TEMP_DISABLED: 6612 s = "SSID_TEMP_DISABLED"; 6613 break; 6614 case WifiMonitor.SSID_REENABLED: 6615 s = "SSID_REENABLED"; 6616 break; 6617 case WifiMonitor.WPS_SUCCESS_EVENT: 6618 s = "WPS_SUCCESS_EVENT"; 6619 break; 6620 case WifiMonitor.WPS_FAIL_EVENT: 6621 s = "WPS_FAIL_EVENT"; 6622 break; 6623 case WifiMonitor.SUP_REQUEST_IDENTITY: 6624 s = "SUP_REQUEST_IDENTITY"; 6625 break; 6626 case WifiMonitor.NETWORK_CONNECTION_EVENT: 6627 s = "NETWORK_CONNECTION_EVENT"; 6628 break; 6629 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 6630 s = "NETWORK_DISCONNECTION_EVENT"; 6631 break; 6632 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 6633 s = "ASSOCIATION_REJECTION_EVENT"; 6634 break; 6635 case CMD_SET_OPERATIONAL_MODE: 6636 s = "CMD_SET_OPERATIONAL_MODE"; 6637 break; 6638 case CMD_START_SCAN: 6639 s = "CMD_START_SCAN"; 6640 break; 6641 case CMD_DISABLE_P2P_RSP: 6642 s = "CMD_DISABLE_P2P_RSP"; 6643 break; 6644 case CMD_DISABLE_P2P_REQ: 6645 s = "CMD_DISABLE_P2P_REQ"; 6646 break; 6647 case WifiWatchdogStateMachine.GOOD_LINK_DETECTED: 6648 s = "GOOD_LINK_DETECTED"; 6649 break; 6650 case WifiWatchdogStateMachine.POOR_LINK_DETECTED: 6651 s = "POOR_LINK_DETECTED"; 6652 break; 6653 case WifiP2pServiceImpl.GROUP_CREATING_TIMED_OUT: 6654 s = "GROUP_CREATING_TIMED_OUT"; 6655 break; 6656 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 6657 s = "P2P_CONNECTION_CHANGED"; 6658 break; 6659 case WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE: 6660 s = "P2P.DISCONNECT_WIFI_RESPONSE"; 6661 break; 6662 case WifiP2pServiceImpl.SET_MIRACAST_MODE: 6663 s = "P2P.SET_MIRACAST_MODE"; 6664 break; 6665 case WifiP2pServiceImpl.BLOCK_DISCOVERY: 6666 s = "P2P.BLOCK_DISCOVERY"; 6667 break; 6668 case WifiP2pServiceImpl.SET_COUNTRY_CODE: 6669 s = "P2P.SET_COUNTRY_CODE"; 6670 break; 6671 case WifiManager.CANCEL_WPS: 6672 s = "CANCEL_WPS"; 6673 break; 6674 case WifiManager.CANCEL_WPS_FAILED: 6675 s = "CANCEL_WPS_FAILED"; 6676 break; 6677 case WifiManager.CANCEL_WPS_SUCCEDED: 6678 s = "CANCEL_WPS_SUCCEDED"; 6679 break; 6680 case WifiManager.START_WPS: 6681 s = "START_WPS"; 6682 break; 6683 case WifiManager.START_WPS_SUCCEEDED: 6684 s = "START_WPS_SUCCEEDED"; 6685 break; 6686 case WifiManager.WPS_FAILED: 6687 s = "WPS_FAILED"; 6688 break; 6689 case WifiManager.WPS_COMPLETED: 6690 s = "WPS_COMPLETED"; 6691 break; 6692 case WifiManager.RSSI_PKTCNT_FETCH: 6693 s = "RSSI_PKTCNT_FETCH"; 6694 break; 6695 case CMD_IP_CONFIGURATION_LOST: 6696 s = "CMD_IP_CONFIGURATION_LOST"; 6697 break; 6698 case CMD_IP_CONFIGURATION_SUCCESSFUL: 6699 s = "CMD_IP_CONFIGURATION_SUCCESSFUL"; 6700 break; 6701 case CMD_IP_REACHABILITY_LOST: 6702 s = "CMD_IP_REACHABILITY_LOST"; 6703 break; 6704 case CMD_STATIC_IP_SUCCESS: 6705 s = "CMD_STATIC_IP_SUCCESSFUL"; 6706 break; 6707 case CMD_STATIC_IP_FAILURE: 6708 s = "CMD_STATIC_IP_FAILURE"; 6709 break; 6710 case DhcpStateMachine.DHCP_SUCCESS: 6711 s = "DHCP_SUCCESS"; 6712 break; 6713 case DhcpStateMachine.DHCP_FAILURE: 6714 s = "DHCP_FAILURE"; 6715 break; 6716 case CMD_TARGET_BSSID: 6717 s = "CMD_TARGET_BSSID"; 6718 break; 6719 case CMD_ASSOCIATED_BSSID: 6720 s = "CMD_ASSOCIATED_BSSID"; 6721 break; 6722 case CMD_REMOVE_APP_CONFIGURATIONS: 6723 s = "CMD_REMOVE_APP_CONFIGURATIONS"; 6724 break; 6725 case CMD_REMOVE_USER_CONFIGURATIONS: 6726 s = "CMD_REMOVE_USER_CONFIGURATIONS"; 6727 break; 6728 case CMD_ROAM_WATCHDOG_TIMER: 6729 s = "CMD_ROAM_WATCHDOG_TIMER"; 6730 break; 6731 case CMD_SCREEN_STATE_CHANGED: 6732 s = "CMD_SCREEN_STATE_CHANGED"; 6733 break; 6734 case CMD_DISCONNECTING_WATCHDOG_TIMER: 6735 s = "CMD_DISCONNECTING_WATCHDOG_TIMER"; 6736 break; 6737 case CMD_RESTART_AUTOJOIN_OFFLOAD: 6738 s = "CMD_RESTART_AUTOJOIN_OFFLOAD"; 6739 break; 6740 case CMD_STARTED_PNO_DBG: 6741 s = "CMD_STARTED_PNO_DBG"; 6742 break; 6743 case CMD_STARTED_GSCAN_DBG: 6744 s = "CMD_STARTED_GSCAN_DBG"; 6745 break; 6746 case CMD_PNO_NETWORK_FOUND: 6747 s = "CMD_PNO_NETWORK_FOUND"; 6748 break; 6749 case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION: 6750 s = "CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION"; 6751 break; 6752 default: 6753 s = "what:" + Integer.toString(what); 6754 break; 6755 } 6756 return s; 6757 } 6758 6759 void registerConnected() { 6760 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 6761 long now_ms = System.currentTimeMillis(); 6762 // We are switching away from this configuration, 6763 // hence record the time we were connected last 6764 WifiConfiguration config = mWifiConfigStore.getWifiConfiguration(mLastNetworkId); 6765 if (config != null) { 6766 config.lastConnected = System.currentTimeMillis(); 6767 config.autoJoinBailedDueToLowRssi = false; 6768 config.setAutoJoinStatus(WifiConfiguration.AUTO_JOIN_ENABLED); 6769 config.numConnectionFailures = 0; 6770 config.numIpConfigFailures = 0; 6771 config.numAuthFailures = 0; 6772 config.numAssociation++; 6773 } 6774 mBadLinkspeedcount = 0; 6775 } 6776 } 6777 6778 void registerDisconnected() { 6779 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 6780 long now_ms = System.currentTimeMillis(); 6781 // We are switching away from this configuration, 6782 // hence record the time we were connected last 6783 WifiConfiguration config = mWifiConfigStore.getWifiConfiguration(mLastNetworkId); 6784 if (config != null) { 6785 config.lastDisconnected = System.currentTimeMillis(); 6786 if (config.ephemeral) { 6787 // Remove ephemeral WifiConfigurations from file 6788 mWifiConfigStore.forgetNetwork(mLastNetworkId); 6789 } 6790 } 6791 } 6792 } 6793 6794 void noteWifiDisabledWhileAssociated() { 6795 // We got disabled by user while we were associated, make note of it 6796 int rssi = mWifiInfo.getRssi(); 6797 WifiConfiguration config = getCurrentWifiConfiguration(); 6798 if (getCurrentState() == mConnectedState 6799 && rssi != WifiInfo.INVALID_RSSI 6800 && config != null) { 6801 boolean is24GHz = mWifiInfo.is24GHz(); 6802 boolean isBadRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdBadRssi24.get()) 6803 || (!is24GHz && rssi < mWifiConfigStore.thresholdBadRssi5.get()); 6804 boolean isLowRSSI = (is24GHz && rssi < mWifiConfigStore.thresholdLowRssi24.get()) 6805 || (!is24GHz && mWifiInfo.getRssi() < mWifiConfigStore.thresholdLowRssi5.get()); 6806 boolean isHighRSSI = (is24GHz && rssi >= mWifiConfigStore.thresholdGoodRssi24.get()) 6807 || (!is24GHz && mWifiInfo.getRssi() >= mWifiConfigStore.thresholdGoodRssi5.get()); 6808 if (isBadRSSI) { 6809 // Take note that we got disabled while RSSI was Bad 6810 config.numUserTriggeredWifiDisableLowRSSI++; 6811 } else if (isLowRSSI) { 6812 // Take note that we got disabled while RSSI was Low 6813 config.numUserTriggeredWifiDisableBadRSSI++; 6814 } else if (!isHighRSSI) { 6815 // Take note that we got disabled while RSSI was Not high 6816 config.numUserTriggeredWifiDisableNotHighRSSI++; 6817 } 6818 } 6819 } 6820 6821 WifiConfiguration getCurrentWifiConfiguration() { 6822 if (mLastNetworkId == WifiConfiguration.INVALID_NETWORK_ID) { 6823 return null; 6824 } 6825 return mWifiConfigStore.getWifiConfiguration(mLastNetworkId); 6826 } 6827 6828 ScanResult getCurrentScanResult() { 6829 WifiConfiguration config = getCurrentWifiConfiguration(); 6830 if (config == null) { 6831 return null; 6832 } 6833 String BSSID = mWifiInfo.getBSSID(); 6834 if (BSSID == null) { 6835 BSSID = mTargetRoamBSSID; 6836 } 6837 ScanDetailCache scanDetailCache = 6838 mWifiConfigStore.getScanDetailCache(config); 6839 6840 if (scanDetailCache == null) { 6841 return null; 6842 } 6843 6844 return scanDetailCache.get(BSSID); 6845 } 6846 6847 String getCurrentBSSID() { 6848 if (linkDebouncing) { 6849 return null; 6850 } 6851 return mLastBssid; 6852 } 6853 6854 class ConnectModeState extends State { 6855 6856 @Override 6857 public void enter() { 6858 connectScanningService(); 6859 } 6860 6861 @Override 6862 public boolean processMessage(Message message) { 6863 WifiConfiguration config; 6864 int netId; 6865 boolean ok; 6866 boolean didDisconnect; 6867 String bssid; 6868 String ssid; 6869 NetworkUpdateResult result; 6870 logStateAndMessage(message, getClass().getSimpleName()); 6871 6872 switch (message.what) { 6873 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 6874 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_ASSOC_FAILURE); 6875 didBlackListBSSID = false; 6876 bssid = (String) message.obj; 6877 if (bssid == null || TextUtils.isEmpty(bssid)) { 6878 // If BSSID is null, use the target roam BSSID 6879 bssid = mTargetRoamBSSID; 6880 } 6881 if (bssid != null) { 6882 // If we have a BSSID, tell configStore to black list it 6883 synchronized(mScanResultCache) { 6884 didBlackListBSSID = mWifiConfigStore.handleBSSIDBlackList 6885 (mLastNetworkId, bssid, false); 6886 } 6887 } 6888 mSupplicantStateTracker.sendMessage(WifiMonitor.ASSOCIATION_REJECTION_EVENT); 6889 break; 6890 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 6891 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_AUTH_FAILURE); 6892 mSupplicantStateTracker.sendMessage(WifiMonitor.AUTHENTICATION_FAILURE_EVENT); 6893 break; 6894 case WifiMonitor.SSID_TEMP_DISABLED: 6895 case WifiMonitor.SSID_REENABLED: 6896 String substr = (String) message.obj; 6897 String en = message.what == WifiMonitor.SSID_TEMP_DISABLED ? 6898 "temp-disabled" : "re-enabled"; 6899 loge("ConnectModeState SSID state=" + en + " nid=" 6900 + Integer.toString(message.arg1) + " [" + substr + "]"); 6901 synchronized(mScanResultCache) { 6902 mWifiConfigStore.handleSSIDStateChange(message.arg1, message.what == 6903 WifiMonitor.SSID_REENABLED, substr, mWifiInfo.getBSSID()); 6904 } 6905 break; 6906 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 6907 SupplicantState state = handleSupplicantStateChange(message); 6908 // A driver/firmware hang can now put the interface in a down state. 6909 // We detect the interface going down and recover from it 6910 if (!SupplicantState.isDriverActive(state)) { 6911 if (mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) { 6912 handleNetworkDisconnect(); 6913 } 6914 log("Detected an interface down, restart driver"); 6915 transitionTo(mDriverStoppedState); 6916 sendMessage(CMD_START_DRIVER); 6917 break; 6918 } 6919 6920 // Supplicant can fail to report a NETWORK_DISCONNECTION_EVENT 6921 // when authentication times out after a successful connection, 6922 // we can figure this from the supplicant state. If supplicant 6923 // state is DISCONNECTED, but the mNetworkInfo says we are not 6924 // disconnected, we need to handle a disconnection 6925 if (!linkDebouncing && state == SupplicantState.DISCONNECTED && 6926 mNetworkInfo.getState() != NetworkInfo.State.DISCONNECTED) { 6927 if (DBG) log("Missed CTRL-EVENT-DISCONNECTED, disconnect"); 6928 handleNetworkDisconnect(); 6929 transitionTo(mDisconnectedState); 6930 } 6931 6932 // If we have COMPLETED a connection to a BSSID, start doing 6933 // DNAv4/DNAv6 -style probing for on-link neighbors of 6934 // interest (e.g. routers); harmless if none are configured. 6935 if (state == SupplicantState.COMPLETED) { 6936 if (mIpReachabilityMonitor != null) { 6937 mIpReachabilityMonitor.probeAll(); 6938 } 6939 } 6940 break; 6941 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 6942 if (message.arg1 == 1) { 6943 mWifiNative.disconnect(); 6944 mTemporarilyDisconnectWifi = true; 6945 } else { 6946 mWifiNative.reconnect(); 6947 mTemporarilyDisconnectWifi = false; 6948 } 6949 break; 6950 case CMD_ADD_OR_UPDATE_NETWORK: 6951 config = (WifiConfiguration) message.obj; 6952 6953 if (!recordUidIfAuthorized(config, message.sendingUid)) { 6954 loge("Not authorized to update network " 6955 + " config=" + config.SSID 6956 + " cnid=" + config.networkId 6957 + " uid=" + message.sendingUid); 6958 replyToMessage(message, message.what, FAILURE); 6959 break; 6960 } 6961 6962 int res = mWifiConfigStore.addOrUpdateNetwork(config, message.sendingUid); 6963 if (res < 0) { 6964 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 6965 } else { 6966 WifiConfiguration curConfig = getCurrentWifiConfiguration(); 6967 if (curConfig != null && config != null) { 6968 if (curConfig.priority < config.priority 6969 && config.status == WifiConfiguration.Status.ENABLED) { 6970 // Interpret this as a connect attempt 6971 // Set the last selected configuration so as to allow the system to 6972 // stick the last user choice without persisting the choice 6973 mWifiConfigStore.setLastSelectedConfiguration(res); 6974 mWifiConfigStore.updateLastConnectUid(config, message.sendingUid); 6975 mWifiConfigStore.writeKnownNetworkHistory(false); 6976 6977 // Remember time of last connection attempt 6978 lastConnectAttempt = System.currentTimeMillis(); 6979 6980 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 6981 6982 // As a courtesy to the caller, trigger a scan now 6983 startScan(ADD_OR_UPDATE_SOURCE, 0, null, null); 6984 } 6985 } 6986 } 6987 replyToMessage(message, CMD_ADD_OR_UPDATE_NETWORK, res); 6988 break; 6989 case CMD_REMOVE_NETWORK: 6990 netId = message.arg1; 6991 if (!mWifiConfigStore.canModifyNetwork(message.sendingUid, netId)) { 6992 loge("Not authorized to remove network " 6993 + " cnid=" + netId 6994 + " uid=" + message.sendingUid); 6995 replyToMessage(message, message.what, FAILURE); 6996 break; 6997 } 6998 6999 ok = mWifiConfigStore.removeNetwork(message.arg1); 7000 if (!ok) { 7001 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7002 } 7003 replyToMessage(message, message.what, ok ? SUCCESS : FAILURE); 7004 break; 7005 case CMD_ENABLE_NETWORK: 7006 boolean others = message.arg2 == 1; 7007 // Tell autojoin the user did try to select to that network 7008 // However, do NOT persist the choice by bumping the priority of the network 7009 if (others) { 7010 mWifiAutoJoinController. 7011 updateConfigurationHistory(message.arg1, true, false); 7012 // Set the last selected configuration so as to allow the system to 7013 // stick the last user choice without persisting the choice 7014 mWifiConfigStore.setLastSelectedConfiguration(message.arg1); 7015 7016 // Remember time of last connection attempt 7017 lastConnectAttempt = System.currentTimeMillis(); 7018 7019 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 7020 } 7021 // Cancel auto roam requests 7022 autoRoamSetBSSID(message.arg1, "any"); 7023 7024 int uid = message.sendingUid; 7025 ok = mWifiConfigStore.enableNetwork(message.arg1, message.arg2 == 1, uid); 7026 if (!ok) { 7027 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7028 } 7029 replyToMessage(message, message.what, ok ? SUCCESS : FAILURE); 7030 break; 7031 case CMD_ENABLE_ALL_NETWORKS: 7032 long time = android.os.SystemClock.elapsedRealtime(); 7033 if (time - mLastEnableAllNetworksTime > MIN_INTERVAL_ENABLE_ALL_NETWORKS_MS) { 7034 mWifiConfigStore.enableAllNetworks(); 7035 mLastEnableAllNetworksTime = time; 7036 } 7037 break; 7038 case WifiManager.DISABLE_NETWORK: 7039 if (mWifiConfigStore.disableNetwork(message.arg1, 7040 WifiConfiguration.DISABLED_BY_WIFI_MANAGER) == true) { 7041 replyToMessage(message, WifiManager.DISABLE_NETWORK_SUCCEEDED); 7042 } else { 7043 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7044 replyToMessage(message, WifiManager.DISABLE_NETWORK_FAILED, 7045 WifiManager.ERROR); 7046 } 7047 break; 7048 case CMD_DISABLE_EPHEMERAL_NETWORK: 7049 config = mWifiConfigStore.disableEphemeralNetwork((String)message.obj); 7050 if (config != null) { 7051 if (config.networkId == mLastNetworkId) { 7052 // Disconnect and let autojoin reselect a new network 7053 sendMessage(CMD_DISCONNECT); 7054 } 7055 } 7056 break; 7057 case CMD_BLACKLIST_NETWORK: 7058 mWifiConfigStore.blackListBssid((String) message.obj); 7059 break; 7060 case CMD_CLEAR_BLACKLIST: 7061 mWifiConfigStore.clearBssidBlacklist(); 7062 break; 7063 case CMD_SAVE_CONFIG: 7064 ok = mWifiConfigStore.saveConfig(); 7065 7066 if (DBG) loge("wifistatemachine did save config " + ok); 7067 replyToMessage(message, CMD_SAVE_CONFIG, ok ? SUCCESS : FAILURE); 7068 7069 // Inform the backup manager about a data change 7070 IBackupManager ibm = IBackupManager.Stub.asInterface( 7071 ServiceManager.getService(Context.BACKUP_SERVICE)); 7072 if (ibm != null) { 7073 try { 7074 ibm.dataChanged("com.android.providers.settings"); 7075 } catch (Exception e) { 7076 // Try again later 7077 } 7078 } 7079 break; 7080 case CMD_GET_CONFIGURED_NETWORKS: 7081 replyToMessage(message, message.what, 7082 mWifiConfigStore.getConfiguredNetworks()); 7083 break; 7084 case WifiMonitor.SUP_REQUEST_IDENTITY: 7085 int networkId = message.arg2; 7086 boolean identitySent = false; 7087 int eapMethod = WifiEnterpriseConfig.Eap.NONE; 7088 7089 if (targetWificonfiguration != null 7090 && targetWificonfiguration.enterpriseConfig != null) { 7091 eapMethod = targetWificonfiguration.enterpriseConfig.getEapMethod(); 7092 } 7093 7094 // For SIM & AKA/AKA' EAP method Only, get identity from ICC 7095 if (targetWificonfiguration != null 7096 && targetWificonfiguration.networkId == networkId 7097 && targetWificonfiguration.allowedKeyManagement 7098 .get(WifiConfiguration.KeyMgmt.IEEE8021X) 7099 && (eapMethod == WifiEnterpriseConfig.Eap.SIM 7100 || eapMethod == WifiEnterpriseConfig.Eap.AKA 7101 || eapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME)) { 7102 TelephonyManager tm = (TelephonyManager) 7103 mContext.getSystemService(Context.TELEPHONY_SERVICE); 7104 if (tm != null) { 7105 String imsi = tm.getSubscriberId(); 7106 String mccMnc = ""; 7107 7108 if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) 7109 mccMnc = tm.getSimOperator(); 7110 7111 String identity = buildIdentity(eapMethod, imsi, mccMnc); 7112 7113 if (!identity.isEmpty()) { 7114 mWifiNative.simIdentityResponse(networkId, identity); 7115 identitySent = true; 7116 } 7117 } 7118 } 7119 if (!identitySent) { 7120 // Supplicant lacks credentials to connect to that network, hence black list 7121 ssid = (String) message.obj; 7122 if (targetWificonfiguration != null && ssid != null 7123 && targetWificonfiguration.SSID != null 7124 && targetWificonfiguration.SSID.equals("\"" + ssid + "\"")) { 7125 mWifiConfigStore.handleSSIDStateChange( 7126 targetWificonfiguration.networkId, false, 7127 "AUTH_FAILED no identity", null); 7128 } 7129 // Disconnect now, as we don't have any way to fullfill 7130 // the supplicant request. 7131 mWifiConfigStore.setLastSelectedConfiguration( 7132 WifiConfiguration.INVALID_NETWORK_ID); 7133 mWifiNative.disconnect(); 7134 } 7135 break; 7136 case WifiMonitor.SUP_REQUEST_SIM_AUTH: 7137 logd("Received SUP_REQUEST_SIM_AUTH"); 7138 SimAuthRequestData requestData = (SimAuthRequestData) message.obj; 7139 if (requestData != null) { 7140 if (requestData.protocol == WifiEnterpriseConfig.Eap.SIM) { 7141 handleGsmAuthRequest(requestData); 7142 } else if (requestData.protocol == WifiEnterpriseConfig.Eap.AKA 7143 || requestData.protocol == WifiEnterpriseConfig.Eap.AKA_PRIME) { 7144 handle3GAuthRequest(requestData); 7145 } 7146 } else { 7147 loge("Invalid sim auth request"); 7148 } 7149 break; 7150 case CMD_GET_PRIVILEGED_CONFIGURED_NETWORKS: 7151 replyToMessage(message, message.what, 7152 mWifiConfigStore.getPrivilegedConfiguredNetworks()); 7153 break; 7154 case CMD_GET_MATCHING_CONFIG: 7155 replyToMessage(message, message.what, 7156 mWifiConfigStore.getMatchingConfig((ScanResult)message.obj)); 7157 break; 7158 /* Do a redundant disconnect without transition */ 7159 case CMD_DISCONNECT: 7160 mWifiConfigStore.setLastSelectedConfiguration 7161 (WifiConfiguration.INVALID_NETWORK_ID); 7162 mWifiNative.disconnect(); 7163 break; 7164 case CMD_RECONNECT: 7165 mWifiAutoJoinController.attemptAutoJoin(); 7166 break; 7167 case CMD_REASSOCIATE: 7168 lastConnectAttempt = System.currentTimeMillis(); 7169 mWifiNative.reassociate(); 7170 break; 7171 case CMD_RELOAD_TLS_AND_RECONNECT: 7172 if (mWifiConfigStore.needsUnlockedKeyStore()) { 7173 logd("Reconnecting to give a chance to un-connected TLS networks"); 7174 mWifiNative.disconnect(); 7175 lastConnectAttempt = System.currentTimeMillis(); 7176 mWifiNative.reconnect(); 7177 } 7178 break; 7179 case CMD_AUTO_ROAM: 7180 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 7181 return HANDLED; 7182 case CMD_AUTO_CONNECT: 7183 /* Work Around: wpa_supplicant can get in a bad state where it returns a non 7184 * associated status to the STATUS command but somehow-someplace still thinks 7185 * it is associated and thus will ignore select/reconnect command with 7186 * following message: 7187 * "Already associated with the selected network - do nothing" 7188 * 7189 * Hence, sends a disconnect to supplicant first. 7190 */ 7191 didDisconnect = false; 7192 if (getCurrentState() != mDisconnectedState) { 7193 /** Supplicant will ignore the reconnect if we are currently associated, 7194 * hence trigger a disconnect 7195 */ 7196 didDisconnect = true; 7197 mWifiNative.disconnect(); 7198 } 7199 7200 /* connect command coming from auto-join */ 7201 config = (WifiConfiguration) message.obj; 7202 netId = message.arg1; 7203 int roam = message.arg2; 7204 loge("CMD_AUTO_CONNECT sup state " 7205 + mSupplicantStateTracker.getSupplicantStateName() 7206 + " my state " + getCurrentState().getName() 7207 + " nid=" + Integer.toString(netId) 7208 + " roam=" + Integer.toString(roam)); 7209 if (config == null) { 7210 loge("AUTO_CONNECT and no config, bail out..."); 7211 break; 7212 } 7213 7214 /* Make sure we cancel any previous roam request */ 7215 autoRoamSetBSSID(netId, config.BSSID); 7216 7217 /* Save the network config */ 7218 loge("CMD_AUTO_CONNECT will save config -> " + config.SSID 7219 + " nid=" + Integer.toString(netId)); 7220 result = mWifiConfigStore.saveNetwork(config, WifiConfiguration.UNKNOWN_UID); 7221 netId = result.getNetworkId(); 7222 loge("CMD_AUTO_CONNECT did save config -> " 7223 + " nid=" + Integer.toString(netId)); 7224 7225 if (deferForUserInput(message, netId, false)) { 7226 break; 7227 } else if (mWifiConfigStore.getWifiConfiguration(netId).userApproved == 7228 WifiConfiguration.USER_BANNED) { 7229 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7230 WifiManager.NOT_AUTHORIZED); 7231 break; 7232 } 7233 7234 // Make sure the network is enabled, since supplicant will not reenable it 7235 mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false); 7236 7237 // If we're autojoining a network that the user or an app explicitly selected, 7238 // keep track of the UID that selected it. 7239 int lastConnectUid = mWifiConfigStore.isLastSelectedConfiguration(config) ? 7240 config.lastConnectUid : WifiConfiguration.UNKNOWN_UID; 7241 7242 if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ false, 7243 lastConnectUid) && mWifiNative.reconnect()) { 7244 lastConnectAttempt = System.currentTimeMillis(); 7245 targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId); 7246 config = mWifiConfigStore.getWifiConfiguration(netId); 7247 if (config != null 7248 && !mWifiConfigStore.isLastSelectedConfiguration(config)) { 7249 // If we autojoined a different config than the user selected one, 7250 // it means we could not see the last user selection, 7251 // or that the last user selection was faulty and ended up blacklisted 7252 // for some reason (in which case the user is notified with an error 7253 // message in the Wifi picker), and thus we managed to auto-join away 7254 // from the selected config. -> in that case we need to forget 7255 // the selection because we don't want to abruptly switch back to it. 7256 // 7257 // Note that the user selection is also forgotten after a period of time 7258 // during which the device has been disconnected. 7259 // The default value is 30 minutes : see the code path at bottom of 7260 // setScanResults() function. 7261 mWifiConfigStore. 7262 setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID); 7263 } 7264 mAutoRoaming = roam; 7265 if (isRoaming() || linkDebouncing) { 7266 transitionTo(mRoamingState); 7267 } else if (didDisconnect) { 7268 transitionTo(mDisconnectingState); 7269 } else { 7270 /* Already in disconnected state, nothing to change */ 7271 } 7272 } else { 7273 loge("Failed to connect config: " + config + " netId: " + netId); 7274 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7275 WifiManager.ERROR); 7276 break; 7277 } 7278 break; 7279 case CMD_REMOVE_APP_CONFIGURATIONS: 7280 mWifiConfigStore.removeNetworksForApp((ApplicationInfo) message.obj); 7281 break; 7282 case CMD_REMOVE_USER_CONFIGURATIONS: 7283 mWifiConfigStore.removeNetworksForUser(message.arg1); 7284 break; 7285 case WifiManager.CONNECT_NETWORK: 7286 /** 7287 * The connect message can contain a network id passed as arg1 on message or 7288 * or a config passed as obj on message. 7289 * For a new network, a config is passed to create and connect. 7290 * For an existing network, a network id is passed 7291 */ 7292 netId = message.arg1; 7293 config = (WifiConfiguration) message.obj; 7294 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 7295 boolean updatedExisting = false; 7296 7297 /* Save the network config */ 7298 if (config != null) { 7299 if (!recordUidIfAuthorized(config, message.sendingUid)) { 7300 loge("Not authorized to update network " 7301 + " config=" + config.SSID 7302 + " cnid=" + config.networkId 7303 + " uid=" + message.sendingUid); 7304 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7305 WifiManager.NOT_AUTHORIZED); 7306 break; 7307 } 7308 7309 String configKey = config.configKey(true /* allowCached */); 7310 WifiConfiguration savedConfig = 7311 mWifiConfigStore.getWifiConfiguration(configKey); 7312 if (savedConfig != null) { 7313 // There is an existing config with this netId, but it wasn't exposed 7314 // (either AUTO_JOIN_DELETED or ephemeral; see WifiConfigStore# 7315 // getConfiguredNetworks). Remove those bits and update the config. 7316 config = savedConfig; 7317 loge("CONNECT_NETWORK updating existing config with id=" + 7318 config.networkId + " configKey=" + configKey); 7319 config.ephemeral = false; 7320 config.autoJoinStatus = WifiConfiguration.AUTO_JOIN_ENABLED; 7321 updatedExisting = true; 7322 } 7323 7324 result = mWifiConfigStore.saveNetwork(config, message.sendingUid); 7325 netId = result.getNetworkId(); 7326 } 7327 config = mWifiConfigStore.getWifiConfiguration(netId); 7328 7329 if (config == null) { 7330 loge("CONNECT_NETWORK no config for id=" + Integer.toString(netId) + " " 7331 + mSupplicantStateTracker.getSupplicantStateName() + " my state " 7332 + getCurrentState().getName()); 7333 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7334 WifiManager.ERROR); 7335 break; 7336 } else { 7337 String wasSkipped = config.autoJoinBailedDueToLowRssi ? " skipped" : ""; 7338 loge("CONNECT_NETWORK id=" + Integer.toString(netId) 7339 + " config=" + config.SSID 7340 + " cnid=" + config.networkId 7341 + " supstate=" + mSupplicantStateTracker.getSupplicantStateName() 7342 + " my state " + getCurrentState().getName() 7343 + " uid = " + message.sendingUid 7344 + wasSkipped); 7345 } 7346 7347 autoRoamSetBSSID(netId, "any"); 7348 7349 if (message.sendingUid == Process.WIFI_UID 7350 || message.sendingUid == Process.SYSTEM_UID) { 7351 // As a sanity measure, clear the BSSID in the supplicant network block. 7352 // If system or Wifi Settings want to connect, they will not 7353 // specify the BSSID. 7354 // If an app however had added a BSSID to this configuration, and the BSSID 7355 // was wrong, Then we would forever fail to connect until that BSSID 7356 // is cleaned up. 7357 clearConfigBSSID(config, "CONNECT_NETWORK"); 7358 } 7359 7360 if (deferForUserInput(message, netId, true)) { 7361 break; 7362 } else if (mWifiConfigStore.getWifiConfiguration(netId).userApproved == 7363 WifiConfiguration.USER_BANNED) { 7364 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7365 WifiManager.NOT_AUTHORIZED); 7366 break; 7367 } 7368 7369 mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE; 7370 7371 /* Tell autojoin the user did try to connect to that network if from settings */ 7372 boolean persist = 7373 mWifiConfigStore.checkConfigOverridePermission(message.sendingUid); 7374 mWifiAutoJoinController.updateConfigurationHistory(netId, true, persist); 7375 7376 mWifiConfigStore.setLastSelectedConfiguration(netId); 7377 7378 didDisconnect = false; 7379 if (mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID 7380 && mLastNetworkId != netId) { 7381 /** Supplicant will ignore the reconnect if we are currently associated, 7382 * hence trigger a disconnect 7383 */ 7384 didDisconnect = true; 7385 mWifiNative.disconnect(); 7386 } 7387 7388 // Make sure the network is enabled, since supplicant will not reenable it 7389 mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false); 7390 7391 if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ true, 7392 message.sendingUid) && mWifiNative.reconnect()) { 7393 lastConnectAttempt = System.currentTimeMillis(); 7394 targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId); 7395 7396 /* The state tracker handles enabling networks upon completion/failure */ 7397 mSupplicantStateTracker.sendMessage(WifiManager.CONNECT_NETWORK); 7398 replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED); 7399 if (didDisconnect) { 7400 /* Expect a disconnection from the old connection */ 7401 transitionTo(mDisconnectingState); 7402 } else if (updatedExisting && getCurrentState() == mConnectedState && 7403 getCurrentWifiConfiguration().networkId == netId) { 7404 // Update the current set of network capabilities, but stay in the 7405 // current state. 7406 updateCapabilities(config); 7407 } else { 7408 /** 7409 * Directly go to disconnected state where we 7410 * process the connection events from supplicant 7411 **/ 7412 transitionTo(mDisconnectedState); 7413 } 7414 } else { 7415 loge("Failed to connect config: " + config + " netId: " + netId); 7416 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 7417 WifiManager.ERROR); 7418 break; 7419 } 7420 break; 7421 case WifiManager.SAVE_NETWORK: 7422 mWifiConnectionStatistics.numWifiManagerJoinAttempt++; 7423 // Fall thru 7424 case WifiStateMachine.CMD_AUTO_SAVE_NETWORK: 7425 lastSavedConfigurationAttempt = null; // Used for debug 7426 config = (WifiConfiguration) message.obj; 7427 if (config == null) { 7428 loge("ERROR: SAVE_NETWORK with null configuration" 7429 + mSupplicantStateTracker.getSupplicantStateName() 7430 + " my state " + getCurrentState().getName()); 7431 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7432 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 7433 WifiManager.ERROR); 7434 break; 7435 } 7436 lastSavedConfigurationAttempt = new WifiConfiguration(config); 7437 int nid = config.networkId; 7438 loge("SAVE_NETWORK id=" + Integer.toString(nid) 7439 + " config=" + config.SSID 7440 + " nid=" + config.networkId 7441 + " supstate=" + mSupplicantStateTracker.getSupplicantStateName() 7442 + " my state " + getCurrentState().getName()); 7443 7444 // Only record the uid if this is user initiated 7445 boolean checkUid = (message.what == WifiManager.SAVE_NETWORK); 7446 if (checkUid && !recordUidIfAuthorized(config, message.sendingUid)) { 7447 loge("Not authorized to update network " 7448 + " config=" + config.SSID 7449 + " cnid=" + config.networkId 7450 + " uid=" + message.sendingUid); 7451 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 7452 WifiManager.NOT_AUTHORIZED); 7453 break; 7454 } 7455 7456 result = mWifiConfigStore.saveNetwork(config, WifiConfiguration.UNKNOWN_UID); 7457 if (result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID) { 7458 if (mWifiInfo.getNetworkId() == result.getNetworkId()) { 7459 if (result.hasIpChanged()) { 7460 // The currently connection configuration was changed 7461 // We switched from DHCP to static or from static to DHCP, or the 7462 // static IP address has changed. 7463 log("Reconfiguring IP on connection"); 7464 // TODO: clear addresses and disable IPv6 7465 // to simplify obtainingIpState. 7466 transitionTo(mObtainingIpState); 7467 } 7468 if (result.hasProxyChanged()) { 7469 log("Reconfiguring proxy on connection"); 7470 updateLinkProperties(CMD_UPDATE_LINKPROPERTIES); 7471 } 7472 } 7473 replyToMessage(message, WifiManager.SAVE_NETWORK_SUCCEEDED); 7474 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_SAVED, config); 7475 7476 if (VDBG) { 7477 loge("Success save network nid=" 7478 + Integer.toString(result.getNetworkId())); 7479 } 7480 7481 synchronized(mScanResultCache) { 7482 /** 7483 * If the command comes from WifiManager, then 7484 * tell autojoin the user did try to modify and save that network, 7485 * and interpret the SAVE_NETWORK as a request to connect 7486 */ 7487 boolean user = message.what == WifiManager.SAVE_NETWORK; 7488 7489 // Did this connect come from settings 7490 boolean persistConnect = 7491 mWifiConfigStore.checkConfigOverridePermission(message.sendingUid); 7492 7493 if (user) { 7494 mWifiConfigStore.updateLastConnectUid(config, message.sendingUid); 7495 mWifiConfigStore.writeKnownNetworkHistory(false); 7496 } 7497 7498 mWifiAutoJoinController.updateConfigurationHistory(result.getNetworkId() 7499 , user, persistConnect); 7500 mWifiAutoJoinController.attemptAutoJoin(); 7501 } 7502 } else { 7503 loge("Failed to save network"); 7504 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 7505 replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED, 7506 WifiManager.ERROR); 7507 } 7508 break; 7509 case WifiManager.FORGET_NETWORK: 7510 // Debug only, remember last configuration that was forgotten 7511 WifiConfiguration toRemove 7512 = mWifiConfigStore.getWifiConfiguration(message.arg1); 7513 if (toRemove == null) { 7514 lastForgetConfigurationAttempt = null; 7515 } else { 7516 lastForgetConfigurationAttempt = new WifiConfiguration(toRemove); 7517 } 7518 // check that the caller owns this network 7519 netId = message.arg1; 7520 7521 if (!mWifiConfigStore.canModifyNetwork(message.sendingUid, netId)) { 7522 loge("Not authorized to forget network " 7523 + " cnid=" + netId 7524 + " uid=" + message.sendingUid); 7525 replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, 7526 WifiManager.NOT_AUTHORIZED); 7527 break; 7528 } 7529 7530 if (mWifiConfigStore.forgetNetwork(message.arg1)) { 7531 replyToMessage(message, WifiManager.FORGET_NETWORK_SUCCEEDED); 7532 broadcastWifiCredentialChanged(WifiManager.WIFI_CREDENTIAL_FORGOT, 7533 (WifiConfiguration) message.obj); 7534 } else { 7535 loge("Failed to forget network"); 7536 replyToMessage(message, WifiManager.FORGET_NETWORK_FAILED, 7537 WifiManager.ERROR); 7538 } 7539 break; 7540 case WifiManager.START_WPS: 7541 WpsInfo wpsInfo = (WpsInfo) message.obj; 7542 WpsResult wpsResult; 7543 switch (wpsInfo.setup) { 7544 case WpsInfo.PBC: 7545 wpsResult = mWifiConfigStore.startWpsPbc(wpsInfo); 7546 break; 7547 case WpsInfo.KEYPAD: 7548 wpsResult = mWifiConfigStore.startWpsWithPinFromAccessPoint(wpsInfo); 7549 break; 7550 case WpsInfo.DISPLAY: 7551 wpsResult = mWifiConfigStore.startWpsWithPinFromDevice(wpsInfo); 7552 break; 7553 default: 7554 wpsResult = new WpsResult(Status.FAILURE); 7555 loge("Invalid setup for WPS"); 7556 break; 7557 } 7558 mWifiConfigStore.setLastSelectedConfiguration 7559 (WifiConfiguration.INVALID_NETWORK_ID); 7560 if (wpsResult.status == Status.SUCCESS) { 7561 replyToMessage(message, WifiManager.START_WPS_SUCCEEDED, wpsResult); 7562 transitionTo(mWpsRunningState); 7563 } else { 7564 loge("Failed to start WPS with config " + wpsInfo.toString()); 7565 replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.ERROR); 7566 } 7567 break; 7568 case WifiMonitor.NETWORK_CONNECTION_EVENT: 7569 if (DBG) log("Network connection established"); 7570 mLastNetworkId = message.arg1; 7571 mLastBssid = (String) message.obj; 7572 7573 mWifiInfo.setBSSID(mLastBssid); 7574 mWifiInfo.setNetworkId(mLastNetworkId); 7575 7576 sendNetworkStateChangeBroadcast(mLastBssid); 7577 transitionTo(mObtainingIpState); 7578 break; 7579 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 7580 // Calling handleNetworkDisconnect here is redundant because we might already 7581 // have called it when leaving L2ConnectedState to go to disconnecting state 7582 // or thru other path 7583 // We should normally check the mWifiInfo or mLastNetworkId so as to check 7584 // if they are valid, and only in this case call handleNEtworkDisconnect, 7585 // TODO: this should be fixed for a L MR release 7586 // The side effect of calling handleNetworkDisconnect twice is that a bunch of 7587 // idempotent commands are executed twice (stopping Dhcp, enabling the SPS mode 7588 // at the chip etc... 7589 if (DBG) log("ConnectModeState: Network connection lost "); 7590 handleNetworkDisconnect(); 7591 transitionTo(mDisconnectedState); 7592 break; 7593 case CMD_PNO_NETWORK_FOUND: 7594 processPnoNetworkFound((ScanResult[])message.obj); 7595 break; 7596 default: 7597 return NOT_HANDLED; 7598 } 7599 return HANDLED; 7600 } 7601 } 7602 7603 private void updateCapabilities(WifiConfiguration config) { 7604 if (config.ephemeral) { 7605 mNetworkCapabilities.removeCapability( 7606 NetworkCapabilities.NET_CAPABILITY_TRUSTED); 7607 } else { 7608 mNetworkCapabilities.addCapability( 7609 NetworkCapabilities.NET_CAPABILITY_TRUSTED); 7610 } 7611 mNetworkAgent.sendNetworkCapabilities(mNetworkCapabilities); 7612 } 7613 7614 private class WifiNetworkAgent extends NetworkAgent { 7615 public WifiNetworkAgent(Looper l, Context c, String TAG, NetworkInfo ni, 7616 NetworkCapabilities nc, LinkProperties lp, int score) { 7617 super(l, c, TAG, ni, nc, lp, score); 7618 } 7619 protected void unwanted() { 7620 // Ignore if we're not the current networkAgent. 7621 if (this != mNetworkAgent) return; 7622 if (DBG) log("WifiNetworkAgent -> Wifi unwanted score " 7623 + Integer.toString(mWifiInfo.score)); 7624 unwantedNetwork(network_status_unwanted_disconnect); 7625 } 7626 7627 @Override 7628 protected void networkStatus(int status) { 7629 if (this != mNetworkAgent) return; 7630 if (status == NetworkAgent.INVALID_NETWORK) { 7631 if (DBG) log("WifiNetworkAgent -> Wifi networkStatus invalid, score=" 7632 + Integer.toString(mWifiInfo.score)); 7633 unwantedNetwork(network_status_unwanted_disable_autojoin); 7634 } else if (status == NetworkAgent.VALID_NETWORK) { 7635 if (DBG && mWifiInfo != null) log("WifiNetworkAgent -> Wifi networkStatus valid, score= " 7636 + Integer.toString(mWifiInfo.score)); 7637 doNetworkStatus(status); 7638 } 7639 } 7640 7641 @Override 7642 protected void saveAcceptUnvalidated(boolean accept) { 7643 if (this != mNetworkAgent) return; 7644 WifiStateMachine.this.sendMessage(CMD_ACCEPT_UNVALIDATED, accept ? 1 : 0); 7645 } 7646 } 7647 7648 void unwantedNetwork(int reason) { 7649 sendMessage(CMD_UNWANTED_NETWORK, reason); 7650 } 7651 7652 void doNetworkStatus(int status) { 7653 sendMessage(CMD_NETWORK_STATUS, status); 7654 } 7655 7656 // rfc4186 & rfc4187: 7657 // create Permanent Identity base on IMSI, 7658 // identity = usernam@realm 7659 // with username = prefix | IMSI 7660 // and realm is derived MMC/MNC tuple according 3GGP spec(TS23.003) 7661 private String buildIdentity(int eapMethod, String imsi, String mccMnc) { 7662 String mcc; 7663 String mnc; 7664 String prefix; 7665 7666 if (imsi == null || imsi.isEmpty()) 7667 return ""; 7668 7669 if (eapMethod == WifiEnterpriseConfig.Eap.SIM) 7670 prefix = "1"; 7671 else if (eapMethod == WifiEnterpriseConfig.Eap.AKA) 7672 prefix = "0"; 7673 else if (eapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME) 7674 prefix = "6"; 7675 else // not a valide EapMethod 7676 return ""; 7677 7678 /* extract mcc & mnc from mccMnc */ 7679 if (mccMnc != null && !mccMnc.isEmpty()) { 7680 mcc = mccMnc.substring(0, 3); 7681 mnc = mccMnc.substring(3); 7682 if (mnc.length() == 2) 7683 mnc = "0" + mnc; 7684 } else { 7685 // extract mcc & mnc from IMSI, assume mnc size is 3 7686 mcc = imsi.substring(0, 3); 7687 mnc = imsi.substring(3, 6); 7688 } 7689 7690 return prefix + imsi + "@wlan.mnc" + mnc + ".mcc" + mcc + ".3gppnetwork.org"; 7691 } 7692 7693 boolean startScanForConfiguration(WifiConfiguration config, boolean restrictChannelList) { 7694 if (config == null) 7695 return false; 7696 7697 // We are still seeing a fairly high power consumption triggered by autojoin scans 7698 // Hence do partial scans only for PSK configuration that are roamable since the 7699 // primary purpose of the partial scans is roaming. 7700 // Full badn scans with exponential backoff for the purpose or extended roaming and 7701 // network switching are performed unconditionally. 7702 ScanDetailCache scanDetailCache = 7703 mWifiConfigStore.getScanDetailCache(config); 7704 if (scanDetailCache == null 7705 || !config.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK) 7706 || scanDetailCache.size() > 6) { 7707 //return true but to not trigger the scan 7708 return true; 7709 } 7710 HashSet<Integer> channels = mWifiConfigStore.makeChannelList(config, 7711 ONE_HOUR_MILLI, restrictChannelList); 7712 if (channels != null && channels.size() != 0) { 7713 StringBuilder freqs = new StringBuilder(); 7714 boolean first = true; 7715 for (Integer channel : channels) { 7716 if (!first) 7717 freqs.append(","); 7718 freqs.append(channel.toString()); 7719 first = false; 7720 } 7721 //if (DBG) { 7722 loge("WifiStateMachine starting scan for " + config.configKey() + " with " + freqs); 7723 //} 7724 // Call wifi native to start the scan 7725 if (startScanNative( 7726 WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, 7727 freqs.toString())) { 7728 // Only count battery consumption if scan request is accepted 7729 noteScanStart(SCAN_ALARM_SOURCE, null); 7730 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OK; 7731 } else { 7732 // used for debug only, mark scan as failed 7733 messageHandlingStatus = MESSAGE_HANDLING_STATUS_HANDLING_ERROR; 7734 } 7735 return true; 7736 } else { 7737 if (DBG) loge("WifiStateMachine no channels for " + config.configKey()); 7738 return false; 7739 } 7740 } 7741 7742 void clearCurrentConfigBSSID(String dbg) { 7743 // Clear the bssid in the current config's network block 7744 WifiConfiguration config = getCurrentWifiConfiguration(); 7745 if (config == null) 7746 return; 7747 clearConfigBSSID(config, dbg); 7748 } 7749 void clearConfigBSSID(WifiConfiguration config, String dbg) { 7750 if (config == null) 7751 return; 7752 if (DBG) { 7753 loge(dbg + " " + mTargetRoamBSSID + " config " + config.configKey() 7754 + " config.bssid " + config.BSSID); 7755 } 7756 config.autoJoinBSSID = "any"; 7757 config.BSSID = "any"; 7758 if (DBG) { 7759 loge(dbg + " " + config.SSID 7760 + " nid=" + Integer.toString(config.networkId)); 7761 } 7762 mWifiConfigStore.saveWifiConfigBSSID(config); 7763 } 7764 7765 class L2ConnectedState extends State { 7766 @Override 7767 public void enter() { 7768 mRssiPollToken++; 7769 if (mEnableRssiPolling) { 7770 sendMessage(CMD_RSSI_POLL, mRssiPollToken, 0); 7771 } 7772 if (mNetworkAgent != null) { 7773 loge("Have NetworkAgent when entering L2Connected"); 7774 setNetworkDetailedState(DetailedState.DISCONNECTED); 7775 } 7776 setNetworkDetailedState(DetailedState.CONNECTING); 7777 7778 if (!TextUtils.isEmpty(mTcpBufferSizes)) { 7779 mLinkProperties.setTcpBufferSizes(mTcpBufferSizes); 7780 } 7781 mNetworkAgent = new WifiNetworkAgent(getHandler().getLooper(), mContext, 7782 "WifiNetworkAgent", mNetworkInfo, mNetworkCapabilitiesFilter, 7783 mLinkProperties, 60); 7784 7785 // We must clear the config BSSID, as the wifi chipset may decide to roam 7786 // from this point on and having the BSSID specified in the network block would 7787 // cause the roam to faile and the device to disconnect 7788 clearCurrentConfigBSSID("L2ConnectedState"); 7789 7790 try { 7791 mIpReachabilityMonitor = new IpReachabilityMonitor( 7792 mInterfaceName, 7793 new IpReachabilityMonitor.Callback() { 7794 @Override 7795 public void notifyLost(InetAddress ip, String logMsg) { 7796 sendMessage(CMD_IP_REACHABILITY_LOST, logMsg); 7797 } 7798 }); 7799 } catch (IllegalArgumentException e) { 7800 Log.wtf("Failed to create IpReachabilityMonitor", e); 7801 } 7802 } 7803 7804 @Override 7805 public void exit() { 7806 if (mIpReachabilityMonitor != null) { 7807 mIpReachabilityMonitor.stop(); 7808 mIpReachabilityMonitor = null; 7809 } 7810 7811 // This is handled by receiving a NETWORK_DISCONNECTION_EVENT in ConnectModeState 7812 // Bug: 15347363 7813 // For paranoia's sake, call handleNetworkDisconnect 7814 // only if BSSID is null or last networkId 7815 // is not invalid. 7816 if (DBG) { 7817 StringBuilder sb = new StringBuilder(); 7818 sb.append("leaving L2ConnectedState state nid=" + Integer.toString(mLastNetworkId)); 7819 if (mLastBssid !=null) { 7820 sb.append(" ").append(mLastBssid); 7821 } 7822 } 7823 if (mLastBssid != null || mLastNetworkId != WifiConfiguration.INVALID_NETWORK_ID) { 7824 handleNetworkDisconnect(); 7825 } 7826 } 7827 7828 @Override 7829 public boolean processMessage(Message message) { 7830 logStateAndMessage(message, getClass().getSimpleName()); 7831 7832 switch (message.what) { 7833 case DhcpStateMachine.CMD_PRE_DHCP_ACTION: 7834 handlePreDhcpSetup(); 7835 break; 7836 case DhcpStateMachine.CMD_POST_DHCP_ACTION: 7837 handlePostDhcpSetup(); 7838 if (message.arg1 == DhcpStateMachine.DHCP_SUCCESS) { 7839 if (DBG) log("WifiStateMachine DHCP successful"); 7840 handleIPv4Success((DhcpResults) message.obj, DhcpStateMachine.DHCP_SUCCESS); 7841 // We advance to mConnectedState because handleIPv4Success will call 7842 // updateLinkProperties, which then sends CMD_IP_CONFIGURATION_SUCCESSFUL. 7843 } else if (message.arg1 == DhcpStateMachine.DHCP_FAILURE) { 7844 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_DHCP_FAILURE); 7845 if (DBG) { 7846 int count = -1; 7847 WifiConfiguration config = getCurrentWifiConfiguration(); 7848 if (config != null) { 7849 count = config.numConnectionFailures; 7850 } 7851 log("WifiStateMachine DHCP failure count=" + count); 7852 } 7853 handleIPv4Failure(DhcpStateMachine.DHCP_FAILURE); 7854 // As above, we transition to mDisconnectingState via updateLinkProperties. 7855 } 7856 break; 7857 case CMD_IP_CONFIGURATION_SUCCESSFUL: 7858 handleSuccessfulIpConfiguration(); 7859 sendConnectedState(); 7860 transitionTo(mConnectedState); 7861 break; 7862 case CMD_IP_CONFIGURATION_LOST: 7863 // Get Link layer stats so that we get fresh tx packet counters. 7864 getWifiLinkLayerStats(true); 7865 handleIpConfigurationLost(); 7866 transitionTo(mDisconnectingState); 7867 break; 7868 case CMD_IP_REACHABILITY_LOST: 7869 if (DBG && message.obj != null) log((String) message.obj); 7870 handleIpReachabilityLost(); 7871 transitionTo(mDisconnectingState); 7872 break; 7873 case CMD_DISCONNECT: 7874 mWifiNative.disconnect(); 7875 transitionTo(mDisconnectingState); 7876 break; 7877 case WifiP2pServiceImpl.DISCONNECT_WIFI_REQUEST: 7878 if (message.arg1 == 1) { 7879 mWifiNative.disconnect(); 7880 mTemporarilyDisconnectWifi = true; 7881 transitionTo(mDisconnectingState); 7882 } 7883 break; 7884 case CMD_SET_OPERATIONAL_MODE: 7885 if (message.arg1 != CONNECT_MODE) { 7886 sendMessage(CMD_DISCONNECT); 7887 deferMessage(message); 7888 if (message.arg1 == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 7889 noteWifiDisabledWhileAssociated(); 7890 } 7891 } 7892 mWifiConfigStore. 7893 setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID); 7894 break; 7895 case CMD_SET_COUNTRY_CODE: 7896 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 7897 deferMessage(message); 7898 break; 7899 case CMD_START_SCAN: 7900 //if (DBG) { 7901 loge("WifiStateMachine CMD_START_SCAN source " + message.arg1 7902 + " txSuccessRate="+String.format( "%.2f", mWifiInfo.txSuccessRate) 7903 + " rxSuccessRate="+String.format( "%.2f", mWifiInfo.rxSuccessRate) 7904 + " targetRoamBSSID=" + mTargetRoamBSSID 7905 + " RSSI=" + mWifiInfo.getRssi()); 7906 //} 7907 if (message.arg1 == SCAN_ALARM_SOURCE) { 7908 // Check if the CMD_START_SCAN message is obsolete (and thus if it should 7909 // not be processed) and restart the scan if needed 7910 boolean shouldScan = 7911 mScreenOn && mWifiConfigStore.enableAutoJoinScanWhenAssociated.get(); 7912 if (!checkAndRestartDelayedScan(message.arg2, 7913 shouldScan, 7914 mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(), 7915 null, null)) { 7916 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 7917 loge("WifiStateMachine L2Connected CMD_START_SCAN source " 7918 + message.arg1 7919 + " " + message.arg2 + ", " + mDelayedScanCounter 7920 + " -> obsolete"); 7921 return HANDLED; 7922 } 7923 if (mP2pConnected.get()) { 7924 loge("WifiStateMachine L2Connected CMD_START_SCAN source " 7925 + message.arg1 7926 + " " + message.arg2 + ", " + mDelayedScanCounter 7927 + " ignore because P2P is connected"); 7928 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 7929 return HANDLED; 7930 } 7931 boolean tryFullBandScan = false; 7932 boolean restrictChannelList = false; 7933 long now_ms = System.currentTimeMillis(); 7934 if (DBG) { 7935 loge("WifiStateMachine CMD_START_SCAN with age=" 7936 + Long.toString(now_ms - lastFullBandConnectedTimeMilli) 7937 + " interval=" + fullBandConnectedTimeIntervalMilli 7938 + " maxinterval=" + maxFullBandConnectedTimeIntervalMilli); 7939 } 7940 if (mWifiInfo != null) { 7941 if (mWifiConfigStore.enableFullBandScanWhenAssociated.get() && 7942 (now_ms - lastFullBandConnectedTimeMilli) 7943 > fullBandConnectedTimeIntervalMilli) { 7944 if (DBG) { 7945 loge("WifiStateMachine CMD_START_SCAN try full band scan age=" 7946 + Long.toString(now_ms - lastFullBandConnectedTimeMilli) 7947 + " interval=" + fullBandConnectedTimeIntervalMilli 7948 + " maxinterval=" + maxFullBandConnectedTimeIntervalMilli); 7949 } 7950 tryFullBandScan = true; 7951 } 7952 7953 if (mWifiInfo.txSuccessRate > 7954 mWifiConfigStore.maxTxPacketForFullScans 7955 || mWifiInfo.rxSuccessRate > 7956 mWifiConfigStore.maxRxPacketForFullScans) { 7957 // Too much traffic at the interface, hence no full band scan 7958 if (DBG) { 7959 loge("WifiStateMachine CMD_START_SCAN " + 7960 "prevent full band scan due to pkt rate"); 7961 } 7962 tryFullBandScan = false; 7963 } 7964 7965 if (mWifiInfo.txSuccessRate > 7966 mWifiConfigStore.maxTxPacketForPartialScans 7967 || mWifiInfo.rxSuccessRate > 7968 mWifiConfigStore.maxRxPacketForPartialScans) { 7969 // Don't scan if lots of packets are being sent 7970 restrictChannelList = true; 7971 if (mWifiConfigStore.alwaysEnableScansWhileAssociated.get() == 0) { 7972 if (DBG) { 7973 loge("WifiStateMachine CMD_START_SCAN source " + message.arg1 7974 + " ...and ignore scans" 7975 + " tx=" + String.format("%.2f", mWifiInfo.txSuccessRate) 7976 + " rx=" + String.format("%.2f", mWifiInfo.rxSuccessRate)); 7977 } 7978 messageHandlingStatus = MESSAGE_HANDLING_STATUS_REFUSED; 7979 return HANDLED; 7980 } 7981 } 7982 } 7983 7984 WifiConfiguration currentConfiguration = getCurrentWifiConfiguration(); 7985 if (DBG) { 7986 loge("WifiStateMachine CMD_START_SCAN full=" + 7987 tryFullBandScan); 7988 } 7989 if (currentConfiguration != null) { 7990 if (fullBandConnectedTimeIntervalMilli 7991 < mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get()) { 7992 // Sanity 7993 fullBandConnectedTimeIntervalMilli 7994 = mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(); 7995 } 7996 if (tryFullBandScan) { 7997 lastFullBandConnectedTimeMilli = now_ms; 7998 if (fullBandConnectedTimeIntervalMilli 7999 < mWifiConfigStore.associatedFullScanMaxIntervalMilli) { 8000 // Increase the interval 8001 fullBandConnectedTimeIntervalMilli 8002 = fullBandConnectedTimeIntervalMilli 8003 * mWifiConfigStore.associatedFullScanBackoff.get() / 8; 8004 8005 if (DBG) { 8006 loge("WifiStateMachine CMD_START_SCAN bump interval =" 8007 + fullBandConnectedTimeIntervalMilli); 8008 } 8009 } 8010 handleScanRequest( 8011 WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message); 8012 } else { 8013 if (!startScanForConfiguration( 8014 currentConfiguration, restrictChannelList)) { 8015 if (DBG) { 8016 loge("WifiStateMachine starting scan, " + 8017 " did not find channels -> full"); 8018 } 8019 lastFullBandConnectedTimeMilli = now_ms; 8020 if (fullBandConnectedTimeIntervalMilli 8021 < mWifiConfigStore.associatedFullScanMaxIntervalMilli) { 8022 // Increase the interval 8023 fullBandConnectedTimeIntervalMilli 8024 = fullBandConnectedTimeIntervalMilli 8025 * mWifiConfigStore.associatedFullScanBackoff.get() / 8; 8026 8027 if (DBG) { 8028 loge("WifiStateMachine CMD_START_SCAN bump interval =" 8029 + fullBandConnectedTimeIntervalMilli); 8030 } 8031 } 8032 handleScanRequest( 8033 WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message); 8034 } 8035 } 8036 8037 } else { 8038 loge("CMD_START_SCAN : connected mode and no configuration"); 8039 messageHandlingStatus = MESSAGE_HANDLING_STATUS_HANDLING_ERROR; 8040 } 8041 } else { 8042 // Not scan alarm source 8043 return NOT_HANDLED; 8044 } 8045 break; 8046 /* Ignore connection to same network */ 8047 case WifiManager.CONNECT_NETWORK: 8048 int netId = message.arg1; 8049 if (mWifiInfo.getNetworkId() == netId) { 8050 break; 8051 } 8052 return NOT_HANDLED; 8053 /* Ignore */ 8054 case WifiMonitor.NETWORK_CONNECTION_EVENT: 8055 break; 8056 case CMD_RSSI_POLL: 8057 if (message.arg1 == mRssiPollToken) { 8058 if (mWifiConfigStore.enableChipWakeUpWhenAssociated.get()) { 8059 if (VVDBG) log(" get link layer stats " + mWifiLinkLayerStatsSupported); 8060 WifiLinkLayerStats stats = getWifiLinkLayerStats(VDBG); 8061 if (stats != null) { 8062 // Sanity check the results provided by driver 8063 if (mWifiInfo.getRssi() != WifiInfo.INVALID_RSSI 8064 && (stats.rssi_mgmt == 0 8065 || stats.beacon_rx == 0)) { 8066 stats = null; 8067 } 8068 } 8069 // Get Info and continue polling 8070 fetchRssiLinkSpeedAndFrequencyNative(); 8071 calculateWifiScore(stats); 8072 } 8073 sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, 8074 mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS); 8075 8076 if (DBG) sendRssiChangeBroadcast(mWifiInfo.getRssi()); 8077 } else { 8078 // Polling has completed 8079 } 8080 break; 8081 case CMD_ENABLE_RSSI_POLL: 8082 cleanWifiScore(); 8083 if (mWifiConfigStore.enableRssiPollWhenAssociated.get()) { 8084 mEnableRssiPolling = (message.arg1 == 1); 8085 } else { 8086 mEnableRssiPolling = false; 8087 } 8088 mRssiPollToken++; 8089 if (mEnableRssiPolling) { 8090 // First poll 8091 fetchRssiLinkSpeedAndFrequencyNative(); 8092 sendMessageDelayed(obtainMessage(CMD_RSSI_POLL, 8093 mRssiPollToken, 0), POLL_RSSI_INTERVAL_MSECS); 8094 } 8095 break; 8096 case WifiManager.RSSI_PKTCNT_FETCH: 8097 RssiPacketCountInfo info = new RssiPacketCountInfo(); 8098 fetchRssiLinkSpeedAndFrequencyNative(); 8099 info.rssi = mWifiInfo.getRssi(); 8100 fetchPktcntNative(info); 8101 replyToMessage(message, WifiManager.RSSI_PKTCNT_FETCH_SUCCEEDED, info); 8102 break; 8103 case CMD_DELAYED_NETWORK_DISCONNECT: 8104 if (!linkDebouncing && mWifiConfigStore.enableLinkDebouncing) { 8105 8106 // Ignore if we are not debouncing 8107 loge("CMD_DELAYED_NETWORK_DISCONNECT and not debouncing - ignore " 8108 + message.arg1); 8109 return HANDLED; 8110 } else { 8111 loge("CMD_DELAYED_NETWORK_DISCONNECT and debouncing - disconnect " 8112 + message.arg1); 8113 8114 linkDebouncing = false; 8115 // If we are still debouncing while this message comes, 8116 // it means we were not able to reconnect within the alloted time 8117 // = LINK_FLAPPING_DEBOUNCE_MSEC 8118 // and thus, trigger a real disconnect 8119 handleNetworkDisconnect(); 8120 transitionTo(mDisconnectedState); 8121 } 8122 break; 8123 case CMD_ASSOCIATED_BSSID: 8124 if ((String) message.obj == null) { 8125 loge("Associated command w/o BSSID"); 8126 break; 8127 } 8128 mLastBssid = (String) message.obj; 8129 if (mLastBssid != null 8130 && (mWifiInfo.getBSSID() == null 8131 || !mLastBssid.equals(mWifiInfo.getBSSID()))) { 8132 mWifiInfo.setBSSID((String) message.obj); 8133 sendNetworkStateChangeBroadcast(mLastBssid); 8134 } 8135 break; 8136 default: 8137 return NOT_HANDLED; 8138 } 8139 8140 return HANDLED; 8141 } 8142 } 8143 8144 class ObtainingIpState extends State { 8145 @Override 8146 public void enter() { 8147 if (DBG) { 8148 String key = ""; 8149 if (getCurrentWifiConfiguration() != null) { 8150 key = getCurrentWifiConfiguration().configKey(); 8151 } 8152 log("enter ObtainingIpState netId=" + Integer.toString(mLastNetworkId) 8153 + " " + key + " " 8154 + " roam=" + mAutoRoaming 8155 + " static=" + mWifiConfigStore.isUsingStaticIp(mLastNetworkId) 8156 + " watchdog= " + obtainingIpWatchdogCount); 8157 } 8158 8159 // Reset link Debouncing, indicating we have successfully re-connected to the AP 8160 // We might still be roaming 8161 linkDebouncing = false; 8162 8163 // Send event to CM & network change broadcast 8164 setNetworkDetailedState(DetailedState.OBTAINING_IPADDR); 8165 8166 // We must clear the config BSSID, as the wifi chipset may decide to roam 8167 // from this point on and having the BSSID specified in the network block would 8168 // cause the roam to faile and the device to disconnect 8169 clearCurrentConfigBSSID("ObtainingIpAddress"); 8170 8171 try { 8172 mNwService.enableIpv6(mInterfaceName); 8173 } catch (RemoteException re) { 8174 loge("Failed to enable IPv6: " + re); 8175 } catch (IllegalStateException e) { 8176 loge("Failed to enable IPv6: " + e); 8177 } 8178 8179 if (!mWifiConfigStore.isUsingStaticIp(mLastNetworkId)) { 8180 if (isRoaming()) { 8181 renewDhcp(); 8182 } else { 8183 // Remove any IP address on the interface in case we're switching from static 8184 // IP configuration to DHCP. This is safe because if we get here when not 8185 // roaming, we don't have a usable address. 8186 clearIPv4Address(mInterfaceName); 8187 startDhcp(); 8188 } 8189 obtainingIpWatchdogCount++; 8190 loge("Start Dhcp Watchdog " + obtainingIpWatchdogCount); 8191 // Get Link layer stats so as we get fresh tx packet counters 8192 getWifiLinkLayerStats(true); 8193 sendMessageDelayed(obtainMessage(CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER, 8194 obtainingIpWatchdogCount, 0), OBTAINING_IP_ADDRESS_GUARD_TIMER_MSEC); 8195 } else { 8196 // stop any running dhcp before assigning static IP 8197 stopDhcp(); 8198 StaticIpConfiguration config = mWifiConfigStore.getStaticIpConfiguration( 8199 mLastNetworkId); 8200 if (config.ipAddress == null) { 8201 loge("Static IP lacks address"); 8202 sendMessage(CMD_STATIC_IP_FAILURE); 8203 } else { 8204 InterfaceConfiguration ifcg = new InterfaceConfiguration(); 8205 ifcg.setLinkAddress(config.ipAddress); 8206 ifcg.setInterfaceUp(); 8207 try { 8208 mNwService.setInterfaceConfig(mInterfaceName, ifcg); 8209 if (DBG) log("Static IP configuration succeeded"); 8210 DhcpResults dhcpResults = new DhcpResults(config); 8211 sendMessage(CMD_STATIC_IP_SUCCESS, dhcpResults); 8212 } catch (RemoteException re) { 8213 loge("Static IP configuration failed: " + re); 8214 sendMessage(CMD_STATIC_IP_FAILURE); 8215 } catch (IllegalStateException e) { 8216 loge("Static IP configuration failed: " + e); 8217 sendMessage(CMD_STATIC_IP_FAILURE); 8218 } 8219 } 8220 } 8221 } 8222 @Override 8223 public boolean processMessage(Message message) { 8224 logStateAndMessage(message, getClass().getSimpleName()); 8225 8226 switch(message.what) { 8227 case CMD_STATIC_IP_SUCCESS: 8228 handleIPv4Success((DhcpResults) message.obj, CMD_STATIC_IP_SUCCESS); 8229 break; 8230 case CMD_STATIC_IP_FAILURE: 8231 handleIPv4Failure(CMD_STATIC_IP_FAILURE); 8232 break; 8233 case CMD_AUTO_CONNECT: 8234 case CMD_AUTO_ROAM: 8235 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8236 break; 8237 case WifiManager.SAVE_NETWORK: 8238 case WifiStateMachine.CMD_AUTO_SAVE_NETWORK: 8239 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 8240 deferMessage(message); 8241 break; 8242 /* Defer any power mode changes since we must keep active power mode at DHCP */ 8243 case CMD_SET_HIGH_PERF_MODE: 8244 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 8245 deferMessage(message); 8246 break; 8247 /* Defer scan request since we should not switch to other channels at DHCP */ 8248 case CMD_START_SCAN: 8249 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DEFERRED; 8250 deferMessage(message); 8251 break; 8252 case CMD_OBTAINING_IP_ADDRESS_WATCHDOG_TIMER: 8253 if (message.arg1 == obtainingIpWatchdogCount) { 8254 loge("ObtainingIpAddress: Watchdog Triggered, count=" 8255 + obtainingIpWatchdogCount); 8256 handleIpConfigurationLost(); 8257 transitionTo(mDisconnectingState); 8258 break; 8259 } 8260 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8261 break; 8262 default: 8263 return NOT_HANDLED; 8264 } 8265 return HANDLED; 8266 } 8267 } 8268 8269 // Note: currently, this state is never used, because WifiWatchdogStateMachine unconditionally 8270 // sets mPoorNetworkDetectionEnabled to false. 8271 class VerifyingLinkState extends State { 8272 @Override 8273 public void enter() { 8274 log(getName() + " enter"); 8275 setNetworkDetailedState(DetailedState.VERIFYING_POOR_LINK); 8276 mWifiConfigStore.updateStatus(mLastNetworkId, DetailedState.VERIFYING_POOR_LINK); 8277 sendNetworkStateChangeBroadcast(mLastBssid); 8278 // End roaming 8279 mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE; 8280 } 8281 @Override 8282 public boolean processMessage(Message message) { 8283 logStateAndMessage(message, getClass().getSimpleName()); 8284 8285 switch (message.what) { 8286 case WifiWatchdogStateMachine.POOR_LINK_DETECTED: 8287 // Stay here 8288 log(getName() + " POOR_LINK_DETECTED: no transition"); 8289 break; 8290 case WifiWatchdogStateMachine.GOOD_LINK_DETECTED: 8291 log(getName() + " GOOD_LINK_DETECTED: transition to CONNECTED"); 8292 sendConnectedState(); 8293 transitionTo(mConnectedState); 8294 break; 8295 default: 8296 if (DBG) log(getName() + " what=" + message.what + " NOT_HANDLED"); 8297 return NOT_HANDLED; 8298 } 8299 return HANDLED; 8300 } 8301 } 8302 8303 private void sendConnectedState() { 8304 // If this network was explicitly selected by the user, evaluate whether to call 8305 // explicitlySelected() so the system can treat it appropriately. 8306 WifiConfiguration config = getCurrentWifiConfiguration(); 8307 if (mWifiConfigStore.isLastSelectedConfiguration(config)) { 8308 boolean prompt = mWifiConfigStore.checkConfigOverridePermission(config.lastConnectUid); 8309 if (DBG) { 8310 log("Network selected by UID " + config.lastConnectUid + " prompt=" + prompt); 8311 } 8312 if (prompt) { 8313 // Selected by the user via Settings or QuickSettings. If this network has Internet 8314 // access, switch to it. Otherwise, switch to it only if the user confirms that they 8315 // really want to switch, or has already confirmed and selected "Don't ask again". 8316 if (DBG) { 8317 log("explictlySelected acceptUnvalidated=" + config.noInternetAccessExpected); 8318 } 8319 mNetworkAgent.explicitlySelected(config.noInternetAccessExpected); 8320 } 8321 } 8322 8323 setNetworkDetailedState(DetailedState.CONNECTED); 8324 mWifiConfigStore.updateStatus(mLastNetworkId, DetailedState.CONNECTED); 8325 sendNetworkStateChangeBroadcast(mLastBssid); 8326 } 8327 8328 class RoamingState extends State { 8329 boolean mAssociated; 8330 @Override 8331 public void enter() { 8332 if (DBG) { 8333 log("RoamingState Enter" 8334 + " mScreenOn=" + mScreenOn ); 8335 } 8336 setScanAlarm(false); 8337 8338 // Make sure we disconnect if roaming fails 8339 roamWatchdogCount++; 8340 loge("Start Roam Watchdog " + roamWatchdogCount); 8341 sendMessageDelayed(obtainMessage(CMD_ROAM_WATCHDOG_TIMER, 8342 roamWatchdogCount, 0), ROAM_GUARD_TIMER_MSEC); 8343 mAssociated = false; 8344 } 8345 @Override 8346 public boolean processMessage(Message message) { 8347 logStateAndMessage(message, getClass().getSimpleName()); 8348 WifiConfiguration config; 8349 switch (message.what) { 8350 case CMD_IP_CONFIGURATION_LOST: 8351 config = getCurrentWifiConfiguration(); 8352 if (config != null) { 8353 mWifiLogger.captureBugReportData(WifiLogger.REPORT_REASON_AUTOROAM_FAILURE); 8354 mWifiConfigStore.noteRoamingFailure(config, 8355 WifiConfiguration.ROAMING_FAILURE_IP_CONFIG); 8356 } 8357 return NOT_HANDLED; 8358 case WifiWatchdogStateMachine.POOR_LINK_DETECTED: 8359 if (DBG) log("Roaming and Watchdog reports poor link -> ignore"); 8360 return HANDLED; 8361 case CMD_UNWANTED_NETWORK: 8362 if (DBG) log("Roaming and CS doesnt want the network -> ignore"); 8363 return HANDLED; 8364 case CMD_SET_OPERATIONAL_MODE: 8365 if (message.arg1 != CONNECT_MODE) { 8366 deferMessage(message); 8367 } 8368 break; 8369 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 8370 /** 8371 * If we get a SUPPLICANT_STATE_CHANGE_EVENT indicating a DISCONNECT 8372 * before NETWORK_DISCONNECTION_EVENT 8373 * And there is an associated BSSID corresponding to our target BSSID, then 8374 * we have missed the network disconnection, transition to mDisconnectedState 8375 * and handle the rest of the events there. 8376 */ 8377 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 8378 if (stateChangeResult.state == SupplicantState.DISCONNECTED 8379 || stateChangeResult.state == SupplicantState.INACTIVE 8380 || stateChangeResult.state == SupplicantState.INTERFACE_DISABLED) { 8381 if (DBG) { 8382 log("STATE_CHANGE_EVENT in roaming state " 8383 + stateChangeResult.toString() ); 8384 } 8385 if (stateChangeResult.BSSID != null 8386 && stateChangeResult.BSSID.equals(mTargetRoamBSSID)) { 8387 handleNetworkDisconnect(); 8388 transitionTo(mDisconnectedState); 8389 } 8390 } 8391 if (stateChangeResult.state == SupplicantState.ASSOCIATED) { 8392 // We completed the layer2 roaming part 8393 mAssociated = true; 8394 if (stateChangeResult.BSSID != null) { 8395 mTargetRoamBSSID = (String) stateChangeResult.BSSID; 8396 } 8397 } 8398 break; 8399 case CMD_ROAM_WATCHDOG_TIMER: 8400 if (roamWatchdogCount == message.arg1) { 8401 if (DBG) log("roaming watchdog! -> disconnect"); 8402 mRoamFailCount++; 8403 handleNetworkDisconnect(); 8404 mWifiNative.disconnect(); 8405 transitionTo(mDisconnectedState); 8406 } 8407 break; 8408 case WifiMonitor.NETWORK_CONNECTION_EVENT: 8409 if (mAssociated) { 8410 if (DBG) log("roaming and Network connection established"); 8411 mLastNetworkId = message.arg1; 8412 mLastBssid = (String) message.obj; 8413 mWifiInfo.setBSSID(mLastBssid); 8414 mWifiInfo.setNetworkId(mLastNetworkId); 8415 mWifiConfigStore.handleBSSIDBlackList(mLastNetworkId, mLastBssid, true); 8416 sendNetworkStateChangeBroadcast(mLastBssid); 8417 transitionTo(mObtainingIpState); 8418 } else { 8419 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8420 } 8421 break; 8422 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 8423 // Throw away but only if it corresponds to the network we're roaming to 8424 String bssid = (String)message.obj; 8425 if (true) { 8426 String target = ""; 8427 if (mTargetRoamBSSID != null) target = mTargetRoamBSSID; 8428 log("NETWORK_DISCONNECTION_EVENT in roaming state" 8429 + " BSSID=" + bssid 8430 + " target=" + target); 8431 } 8432 if (bssid != null && bssid.equals(mTargetRoamBSSID)) { 8433 handleNetworkDisconnect(); 8434 transitionTo(mDisconnectedState); 8435 } 8436 break; 8437 case WifiMonitor.SSID_TEMP_DISABLED: 8438 // Auth error while roaming 8439 loge("SSID_TEMP_DISABLED nid=" + Integer.toString(mLastNetworkId) 8440 + " id=" + Integer.toString(message.arg1) 8441 + " isRoaming=" + isRoaming() 8442 + " roam=" + Integer.toString(mAutoRoaming)); 8443 if (message.arg1 == mLastNetworkId) { 8444 config = getCurrentWifiConfiguration(); 8445 if (config != null) { 8446 mWifiLogger.captureBugReportData( 8447 WifiLogger.REPORT_REASON_AUTOROAM_FAILURE); 8448 mWifiConfigStore.noteRoamingFailure(config, 8449 WifiConfiguration.ROAMING_FAILURE_AUTH_FAILURE); 8450 } 8451 handleNetworkDisconnect(); 8452 transitionTo(mDisconnectingState); 8453 } 8454 return NOT_HANDLED; 8455 case CMD_START_SCAN: 8456 deferMessage(message); 8457 break; 8458 default: 8459 return NOT_HANDLED; 8460 } 8461 return HANDLED; 8462 } 8463 8464 @Override 8465 public void exit() { 8466 loge("WifiStateMachine: Leaving Roaming state"); 8467 } 8468 } 8469 8470 class ConnectedState extends State { 8471 @Override 8472 public void enter() { 8473 String address; 8474 updateDefaultRouteMacAddress(1000); 8475 if (DBG) { 8476 log("Enter ConnectedState " 8477 + " mScreenOn=" + mScreenOn 8478 + " scanperiod=" 8479 + Integer.toString(mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get()) 8480 + " useGscan=" + mHalBasedPnoDriverSupported + "/" 8481 + mWifiConfigStore.enableHalBasedPno.get() 8482 + " mHalBasedPnoEnableInDevSettings " + mHalBasedPnoEnableInDevSettings); 8483 } 8484 if (mScreenOn 8485 && mWifiConfigStore.enableAutoJoinScanWhenAssociated.get()) { 8486 if (useHalBasedAutoJoinOffload()) { 8487 startGScanConnectedModeOffload("connectedEnter"); 8488 } else { 8489 // restart scan alarm 8490 startDelayedScan(mWifiConfigStore.wifiAssociatedShortScanIntervalMilli.get(), 8491 null, null); 8492 } 8493 } 8494 registerConnected(); 8495 lastConnectAttempt = 0; 8496 targetWificonfiguration = null; 8497 // Paranoia 8498 linkDebouncing = false; 8499 8500 // Not roaming anymore 8501 mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE; 8502 8503 if (testNetworkDisconnect) { 8504 testNetworkDisconnectCounter++; 8505 loge("ConnectedState Enter start disconnect test " + 8506 testNetworkDisconnectCounter); 8507 sendMessageDelayed(obtainMessage(CMD_TEST_NETWORK_DISCONNECT, 8508 testNetworkDisconnectCounter, 0), 15000); 8509 } 8510 8511 // Reenable all networks, allow for hidden networks to be scanned 8512 mWifiConfigStore.enableAllNetworks(); 8513 8514 mLastDriverRoamAttempt = 0; 8515 8516 //startLazyRoam(); 8517 } 8518 @Override 8519 public boolean processMessage(Message message) { 8520 WifiConfiguration config = null; 8521 logStateAndMessage(message, getClass().getSimpleName()); 8522 8523 switch (message.what) { 8524 case CMD_RESTART_AUTOJOIN_OFFLOAD: 8525 if ( (int)message.arg2 < mRestartAutoJoinOffloadCounter ) { 8526 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 8527 return HANDLED; 8528 } 8529 /* If we are still in Disconnected state after having discovered a valid 8530 * network this means autojoin didnt managed to associate to the network, 8531 * then restart PNO so as we will try associating to it again. 8532 */ 8533 if (useHalBasedAutoJoinOffload()) { 8534 if (mGScanStartTimeMilli == 0) { 8535 // If offload is not started, then start it... 8536 startGScanConnectedModeOffload("connectedRestart"); 8537 } else { 8538 // If offload is already started, then check if we need to increase 8539 // the scan period and restart the Gscan 8540 long now = System.currentTimeMillis(); 8541 if (mGScanStartTimeMilli != 0 && now > mGScanStartTimeMilli 8542 && ((now - mGScanStartTimeMilli) 8543 > DISCONNECTED_SHORT_SCANS_DURATION_MILLI) 8544 && (mGScanPeriodMilli 8545 < mWifiConfigStore.wifiDisconnectedLongScanIntervalMilli.get())) 8546 { 8547 startConnectedGScan("Connected restart gscan"); 8548 } 8549 } 8550 } 8551 break; 8552 case CMD_UPDATE_ASSOCIATED_SCAN_PERMISSION: 8553 updateAssociatedScanPermission(); 8554 break; 8555 case WifiWatchdogStateMachine.POOR_LINK_DETECTED: 8556 if (DBG) log("Watchdog reports poor link"); 8557 transitionTo(mVerifyingLinkState); 8558 break; 8559 case CMD_UNWANTED_NETWORK: 8560 if (message.arg1 == network_status_unwanted_disconnect) { 8561 mWifiConfigStore.handleBadNetworkDisconnectReport(mLastNetworkId, mWifiInfo); 8562 mWifiNative.disconnect(); 8563 transitionTo(mDisconnectingState); 8564 } else if (message.arg1 == network_status_unwanted_disable_autojoin) { 8565 config = getCurrentWifiConfiguration(); 8566 if (config != null) { 8567 // Disable autojoin 8568 config.numNoInternetAccessReports += 1; 8569 config.dirty = true; 8570 mWifiConfigStore.writeKnownNetworkHistory(false); 8571 } 8572 } 8573 return HANDLED; 8574 case CMD_NETWORK_STATUS: 8575 if (message.arg1 == NetworkAgent.VALID_NETWORK) { 8576 config = getCurrentWifiConfiguration(); 8577 if (config != null) { 8578 if (!config.validatedInternetAccess 8579 || config.numNoInternetAccessReports != 0) { 8580 config.dirty = true; 8581 } 8582 // re-enable autojoin 8583 config.numNoInternetAccessReports = 0; 8584 config.validatedInternetAccess = true; 8585 mWifiConfigStore.writeKnownNetworkHistory(false); 8586 } 8587 } 8588 return HANDLED; 8589 case CMD_ACCEPT_UNVALIDATED: 8590 boolean accept = (message.arg1 != 0); 8591 config = getCurrentWifiConfiguration(); 8592 if (config != null) { 8593 config.noInternetAccessExpected = accept; 8594 } 8595 return HANDLED; 8596 case CMD_TEST_NETWORK_DISCONNECT: 8597 // Force a disconnect 8598 if (message.arg1 == testNetworkDisconnectCounter) { 8599 mWifiNative.disconnect(); 8600 } 8601 break; 8602 case CMD_ASSOCIATED_BSSID: 8603 // ASSOCIATING to a new BSSID while already connected, indicates 8604 // that driver is roaming 8605 mLastDriverRoamAttempt = System.currentTimeMillis(); 8606 String toBSSID = (String)message.obj; 8607 if (toBSSID != null && !toBSSID.equals(mWifiInfo.getBSSID())) { 8608 mWifiConfigStore.driverRoamedFrom(mWifiInfo); 8609 } 8610 return NOT_HANDLED; 8611 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 8612 long lastRoam = 0; 8613 if (mLastDriverRoamAttempt != 0) { 8614 // Calculate time since last driver roam attempt 8615 lastRoam = System.currentTimeMillis() - mLastDriverRoamAttempt; 8616 mLastDriverRoamAttempt = 0; 8617 } 8618 if (unexpectedDisconnectedReason(message.arg2)) { 8619 mWifiLogger.captureBugReportData( 8620 WifiLogger.REPORT_REASON_UNEXPECTED_DISCONNECT); 8621 } 8622 config = getCurrentWifiConfiguration(); 8623 if (mScreenOn 8624 && !linkDebouncing 8625 && config != null 8626 && config.autoJoinStatus == WifiConfiguration.AUTO_JOIN_ENABLED 8627 && !mWifiConfigStore.isLastSelectedConfiguration(config) 8628 && (message.arg2 != 3 /* reason cannot be 3, i.e. locally generated */ 8629 || (lastRoam > 0 && lastRoam < 2000) /* unless driver is roaming */) 8630 && ((ScanResult.is24GHz(mWifiInfo.getFrequency()) 8631 && mWifiInfo.getRssi() > 8632 WifiConfiguration.BAD_RSSI_24) 8633 || (ScanResult.is5GHz(mWifiInfo.getFrequency()) 8634 && mWifiInfo.getRssi() > 8635 WifiConfiguration.BAD_RSSI_5))) { 8636 // Start de-bouncing the L2 disconnection: 8637 // this L2 disconnection might be spurious. 8638 // Hence we allow 7 seconds for the state machine to try 8639 // to reconnect, go thru the 8640 // roaming cycle and enter Obtaining IP address 8641 // before signalling the disconnect to ConnectivityService and L3 8642 startScanForConfiguration(getCurrentWifiConfiguration(), false); 8643 linkDebouncing = true; 8644 8645 sendMessageDelayed(obtainMessage(CMD_DELAYED_NETWORK_DISCONNECT, 8646 0, mLastNetworkId), LINK_FLAPPING_DEBOUNCE_MSEC); 8647 if (DBG) { 8648 log("NETWORK_DISCONNECTION_EVENT in connected state" 8649 + " BSSID=" + mWifiInfo.getBSSID() 8650 + " RSSI=" + mWifiInfo.getRssi() 8651 + " freq=" + mWifiInfo.getFrequency() 8652 + " reason=" + message.arg2 8653 + " -> debounce"); 8654 } 8655 return HANDLED; 8656 } else { 8657 if (DBG) { 8658 int ajst = -1; 8659 if (config != null) ajst = config.autoJoinStatus; 8660 log("NETWORK_DISCONNECTION_EVENT in connected state" 8661 + " BSSID=" + mWifiInfo.getBSSID() 8662 + " RSSI=" + mWifiInfo.getRssi() 8663 + " freq=" + mWifiInfo.getFrequency() 8664 + " was debouncing=" + linkDebouncing 8665 + " reason=" + message.arg2 8666 + " ajst=" + ajst); 8667 } 8668 } 8669 break; 8670 case CMD_AUTO_ROAM: 8671 // Clear the driver roam indication since we are attempting a framework roam 8672 mLastDriverRoamAttempt = 0; 8673 8674 /* Connect command coming from auto-join */ 8675 ScanResult candidate = (ScanResult)message.obj; 8676 String bssid = "any"; 8677 if (candidate != null && candidate.is5GHz()) { 8678 // Only lock BSSID for 5GHz networks 8679 bssid = candidate.BSSID; 8680 } 8681 int netId = mLastNetworkId; 8682 config = getCurrentWifiConfiguration(); 8683 8684 8685 if (config == null) { 8686 loge("AUTO_ROAM and no config, bail out..."); 8687 break; 8688 } 8689 8690 loge("CMD_AUTO_ROAM sup state " 8691 + mSupplicantStateTracker.getSupplicantStateName() 8692 + " my state " + getCurrentState().getName() 8693 + " nid=" + Integer.toString(netId) 8694 + " config " + config.configKey() 8695 + " roam=" + Integer.toString(message.arg2) 8696 + " to " + bssid 8697 + " targetRoamBSSID " + mTargetRoamBSSID); 8698 8699 /* Save the BSSID so as to lock it @ firmware */ 8700 if (!autoRoamSetBSSID(config, bssid) && !linkDebouncing) { 8701 loge("AUTO_ROAM nothing to do"); 8702 // Same BSSID, nothing to do 8703 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 8704 break; 8705 }; 8706 8707 // Make sure the network is enabled, since supplicant will not re-enable it 8708 mWifiConfigStore.enableNetworkWithoutBroadcast(netId, false); 8709 8710 if (deferForUserInput(message, netId, false)) { 8711 break; 8712 } else if (mWifiConfigStore.getWifiConfiguration(netId).userApproved == 8713 WifiConfiguration.USER_BANNED) { 8714 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 8715 WifiManager.NOT_AUTHORIZED); 8716 break; 8717 } 8718 8719 boolean ret = false; 8720 if (mLastNetworkId != netId) { 8721 if (mWifiConfigStore.selectNetwork(config, /* updatePriorities = */ false, 8722 WifiConfiguration.UNKNOWN_UID) && mWifiNative.reconnect()) { 8723 ret = true; 8724 } 8725 } else { 8726 ret = mWifiNative.reassociate(); 8727 } 8728 if (ret) { 8729 lastConnectAttempt = System.currentTimeMillis(); 8730 targetWificonfiguration = mWifiConfigStore.getWifiConfiguration(netId); 8731 8732 // replyToMessage(message, WifiManager.CONNECT_NETWORK_SUCCEEDED); 8733 mAutoRoaming = message.arg2; 8734 transitionTo(mRoamingState); 8735 8736 } else { 8737 loge("Failed to connect config: " + config + " netId: " + netId); 8738 replyToMessage(message, WifiManager.CONNECT_NETWORK_FAILED, 8739 WifiManager.ERROR); 8740 messageHandlingStatus = MESSAGE_HANDLING_STATUS_FAIL; 8741 break; 8742 } 8743 break; 8744 default: 8745 return NOT_HANDLED; 8746 } 8747 return HANDLED; 8748 } 8749 8750 @Override 8751 public void exit() { 8752 loge("WifiStateMachine: Leaving Connected state"); 8753 setScanAlarm(false); 8754 mLastDriverRoamAttempt = 0; 8755 8756 stopLazyRoam(); 8757 8758 mWhiteListedSsids = null; 8759 } 8760 } 8761 8762 class DisconnectingState extends State { 8763 8764 @Override 8765 public void enter() { 8766 8767 if (PDBG) { 8768 loge(" Enter DisconnectingState State scan interval " 8769 + mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get() 8770 + " mLegacyPnoEnabled= " + mLegacyPnoEnabled 8771 + " screenOn=" + mScreenOn); 8772 } 8773 8774 // Make sure we disconnect: we enter this state prior to connecting to a new 8775 // network, waiting for either a DISCONNECT event or a SUPPLICANT_STATE_CHANGE 8776 // event which in this case will be indicating that supplicant started to associate. 8777 // In some cases supplicant doesn't ignore the connect requests (it might not 8778 // find the target SSID in its cache), 8779 // Therefore we end up stuck that state, hence the need for the watchdog. 8780 disconnectingWatchdogCount++; 8781 loge("Start Disconnecting Watchdog " + disconnectingWatchdogCount); 8782 sendMessageDelayed(obtainMessage(CMD_DISCONNECTING_WATCHDOG_TIMER, 8783 disconnectingWatchdogCount, 0), DISCONNECTING_GUARD_TIMER_MSEC); 8784 } 8785 8786 @Override 8787 public boolean processMessage(Message message) { 8788 logStateAndMessage(message, getClass().getSimpleName()); 8789 switch (message.what) { 8790 case CMD_SET_OPERATIONAL_MODE: 8791 if (message.arg1 != CONNECT_MODE) { 8792 deferMessage(message); 8793 } 8794 break; 8795 case CMD_START_SCAN: 8796 deferMessage(message); 8797 return HANDLED; 8798 case CMD_DISCONNECTING_WATCHDOG_TIMER: 8799 if (disconnectingWatchdogCount == message.arg1) { 8800 if (DBG) log("disconnecting watchdog! -> disconnect"); 8801 handleNetworkDisconnect(); 8802 transitionTo(mDisconnectedState); 8803 } 8804 break; 8805 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 8806 /** 8807 * If we get a SUPPLICANT_STATE_CHANGE_EVENT before NETWORK_DISCONNECTION_EVENT 8808 * we have missed the network disconnection, transition to mDisconnectedState 8809 * and handle the rest of the events there 8810 */ 8811 deferMessage(message); 8812 handleNetworkDisconnect(); 8813 transitionTo(mDisconnectedState); 8814 break; 8815 default: 8816 return NOT_HANDLED; 8817 } 8818 return HANDLED; 8819 } 8820 } 8821 8822 class DisconnectedState extends State { 8823 @Override 8824 public void enter() { 8825 // We dont scan frequently if this is a temporary disconnect 8826 // due to p2p 8827 if (mTemporarilyDisconnectWifi) { 8828 mWifiP2pChannel.sendMessage(WifiP2pServiceImpl.DISCONNECT_WIFI_RESPONSE); 8829 return; 8830 } 8831 8832 if (PDBG) { 8833 loge(" Enter DisconnectedState scan interval " 8834 + mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get() 8835 + " mLegacyPnoEnabled= " + mLegacyPnoEnabled 8836 + " screenOn=" + mScreenOn 8837 + " useGscan=" + mHalBasedPnoDriverSupported + "/" 8838 + mWifiConfigStore.enableHalBasedPno.get()); 8839 } 8840 8841 /** clear the roaming state, if we were roaming, we failed */ 8842 mAutoRoaming = WifiAutoJoinController.AUTO_JOIN_IDLE; 8843 8844 if (useHalBasedAutoJoinOffload()) { 8845 startGScanDisconnectedModeOffload("disconnectedEnter"); 8846 } else { 8847 if (mScreenOn) { 8848 /** 8849 * screen lit and => delayed timer 8850 */ 8851 startDelayedScan(mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get(), 8852 null, null); 8853 } else { 8854 /** 8855 * screen dark and PNO supported => scan alarm disabled 8856 */ 8857 if (mBackgroundScanSupported) { 8858 /* If a regular scan result is pending, do not initiate background 8859 * scan until the scan results are returned. This is needed because 8860 * initiating a background scan will cancel the regular scan and 8861 * scan results will not be returned until background scanning is 8862 * cleared 8863 */ 8864 if (!mIsScanOngoing) { 8865 enableBackgroundScan(true); 8866 } 8867 } else { 8868 setScanAlarm(true); 8869 } 8870 } 8871 } 8872 8873 /** 8874 * If we have no networks saved, the supplicant stops doing the periodic scan. 8875 * The scans are useful to notify the user of the presence of an open network. 8876 * Note that these are not wake up scans. 8877 */ 8878 if (mNoNetworksPeriodicScan != 0 && !mP2pConnected.get() 8879 && mWifiConfigStore.getConfiguredNetworks().size() == 0) { 8880 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 8881 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 8882 } 8883 8884 mDisconnectedTimeStamp = System.currentTimeMillis(); 8885 8886 } 8887 @Override 8888 public boolean processMessage(Message message) { 8889 boolean ret = HANDLED; 8890 8891 logStateAndMessage(message, getClass().getSimpleName()); 8892 8893 switch (message.what) { 8894 case CMD_NO_NETWORKS_PERIODIC_SCAN: 8895 if (mP2pConnected.get()) break; 8896 if (mNoNetworksPeriodicScan != 0 && message.arg1 == mPeriodicScanToken && 8897 mWifiConfigStore.getConfiguredNetworks().size() == 0) { 8898 startScan(UNKNOWN_SCAN_SOURCE, -1, null, null); 8899 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 8900 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 8901 } 8902 break; 8903 case WifiManager.FORGET_NETWORK: 8904 case CMD_REMOVE_NETWORK: 8905 case CMD_REMOVE_APP_CONFIGURATIONS: 8906 case CMD_REMOVE_USER_CONFIGURATIONS: 8907 // Set up a delayed message here. After the forget/remove is handled 8908 // the handled delayed message will determine if there is a need to 8909 // scan and continue 8910 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 8911 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 8912 ret = NOT_HANDLED; 8913 break; 8914 case CMD_SET_OPERATIONAL_MODE: 8915 if (message.arg1 != CONNECT_MODE) { 8916 mOperationalMode = message.arg1; 8917 8918 mWifiConfigStore.disableAllNetworks(); 8919 if (mOperationalMode == SCAN_ONLY_WITH_WIFI_OFF_MODE) { 8920 mWifiP2pChannel.sendMessage(CMD_DISABLE_P2P_REQ); 8921 setWifiState(WIFI_STATE_DISABLED); 8922 } 8923 transitionTo(mScanModeState); 8924 } 8925 mWifiConfigStore. 8926 setLastSelectedConfiguration(WifiConfiguration.INVALID_NETWORK_ID); 8927 break; 8928 /* Ignore network disconnect */ 8929 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 8930 break; 8931 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 8932 StateChangeResult stateChangeResult = (StateChangeResult) message.obj; 8933 if (DBG) { 8934 loge("SUPPLICANT_STATE_CHANGE_EVENT state=" + stateChangeResult.state + 8935 " -> state= " + WifiInfo.getDetailedStateOf(stateChangeResult.state) 8936 + " debouncing=" + linkDebouncing); 8937 } 8938 setNetworkDetailedState(WifiInfo.getDetailedStateOf(stateChangeResult.state)); 8939 /* ConnectModeState does the rest of the handling */ 8940 ret = NOT_HANDLED; 8941 break; 8942 case CMD_START_SCAN: 8943 if (!checkOrDeferScanAllowed(message)) { 8944 // The scan request was rescheduled 8945 messageHandlingStatus = MESSAGE_HANDLING_STATUS_REFUSED; 8946 return HANDLED; 8947 } 8948 if (message.arg1 == SCAN_ALARM_SOURCE) { 8949 // Check if the CMD_START_SCAN message is obsolete (and thus if it should 8950 // not be processed) and restart the scan 8951 int period = mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get(); 8952 if (mP2pConnected.get()) { 8953 period = (int)Settings.Global.getLong(mContext.getContentResolver(), 8954 Settings.Global.WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS, 8955 period); 8956 } 8957 if (!checkAndRestartDelayedScan(message.arg2, 8958 true, period, null, null)) { 8959 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 8960 loge("WifiStateMachine Disconnected CMD_START_SCAN source " 8961 + message.arg1 8962 + " " + message.arg2 + ", " + mDelayedScanCounter 8963 + " -> obsolete"); 8964 return HANDLED; 8965 } 8966 /* Disable background scan temporarily during a regular scan */ 8967 enableBackgroundScan(false); 8968 handleScanRequest(WifiNative.SCAN_WITHOUT_CONNECTION_SETUP, message); 8969 ret = HANDLED; 8970 } else { 8971 8972 /* 8973 * The SCAN request is not handled in this state and 8974 * would eventually might/will get handled in the 8975 * parent's state. The PNO, if already enabled had to 8976 * get disabled before the SCAN trigger. Hence, stop 8977 * the PNO if already enabled in this state, though the 8978 * SCAN request is not handled(PNO disable before the 8979 * SCAN trigger in any other state is not the right 8980 * place to issue). 8981 */ 8982 8983 enableBackgroundScan(false); 8984 ret = NOT_HANDLED; 8985 } 8986 break; 8987 case CMD_RESTART_AUTOJOIN_OFFLOAD: 8988 if ( (int)message.arg2 < mRestartAutoJoinOffloadCounter ) { 8989 messageHandlingStatus = MESSAGE_HANDLING_STATUS_OBSOLETE; 8990 return HANDLED; 8991 } 8992 /* If we are still in Disconnected state after having discovered a valid 8993 * network this means autojoin didnt managed to associate to the network, 8994 * then restart PNO so as we will try associating to it again. 8995 */ 8996 if (useHalBasedAutoJoinOffload()) { 8997 if (mGScanStartTimeMilli == 0) { 8998 // If offload is not started, then start it... 8999 startGScanDisconnectedModeOffload("disconnectedRestart"); 9000 } else { 9001 // If offload is already started, then check if we need to increase 9002 // the scan period and restart the Gscan 9003 long now = System.currentTimeMillis(); 9004 if (mGScanStartTimeMilli != 0 && now > mGScanStartTimeMilli 9005 && ((now - mGScanStartTimeMilli) 9006 > DISCONNECTED_SHORT_SCANS_DURATION_MILLI) 9007 && (mGScanPeriodMilli 9008 < mWifiConfigStore.wifiDisconnectedLongScanIntervalMilli.get())) 9009 { 9010 startDisconnectedGScan("disconnected restart gscan"); 9011 } 9012 } 9013 } 9014 break; 9015 case WifiMonitor.SCAN_RESULTS_EVENT: 9016 case WifiMonitor.SCAN_FAILED_EVENT: 9017 /* Re-enable background scan when a pending scan result is received */ 9018 if (!mScreenOn && mIsScanOngoing 9019 && mBackgroundScanSupported 9020 && !useHalBasedAutoJoinOffload()) { 9021 enableBackgroundScan(true); 9022 } 9023 /* Handled in parent state */ 9024 ret = NOT_HANDLED; 9025 break; 9026 case WifiP2pServiceImpl.P2P_CONNECTION_CHANGED: 9027 NetworkInfo info = (NetworkInfo) message.obj; 9028 mP2pConnected.set(info.isConnected()); 9029 if (mP2pConnected.get()) { 9030 int defaultInterval = mContext.getResources().getInteger( 9031 R.integer.config_wifi_scan_interval_p2p_connected); 9032 long scanIntervalMs = Settings.Global.getLong(mContext.getContentResolver(), 9033 Settings.Global.WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS, 9034 defaultInterval); 9035 mWifiNative.setScanInterval((int) scanIntervalMs/1000); 9036 } else if (mWifiConfigStore.getConfiguredNetworks().size() == 0) { 9037 if (DBG) log("Turn on scanning after p2p disconnected"); 9038 sendMessageDelayed(obtainMessage(CMD_NO_NETWORKS_PERIODIC_SCAN, 9039 ++mPeriodicScanToken, 0), mNoNetworksPeriodicScan); 9040 } else { 9041 // If P2P is not connected and there are saved networks, then restart 9042 // scanning at the normal period. This is necessary because scanning might 9043 // have been disabled altogether if WIFI_SCAN_INTERVAL_WHEN_P2P_CONNECTED_MS 9044 // was set to zero. 9045 if (useHalBasedAutoJoinOffload()) { 9046 startGScanDisconnectedModeOffload("p2pRestart"); 9047 } else { 9048 startDelayedScan( 9049 mWifiConfigStore.wifiDisconnectedShortScanIntervalMilli.get(), 9050 null, null); 9051 } 9052 } 9053 break; 9054 case CMD_RECONNECT: 9055 case CMD_REASSOCIATE: 9056 if (mTemporarilyDisconnectWifi) { 9057 // Drop a third party reconnect/reassociate if STA is 9058 // temporarily disconnected for p2p 9059 break; 9060 } else { 9061 // ConnectModeState handles it 9062 ret = NOT_HANDLED; 9063 } 9064 break; 9065 case CMD_SCREEN_STATE_CHANGED: 9066 handleScreenStateChanged(message.arg1 != 0); 9067 break; 9068 default: 9069 ret = NOT_HANDLED; 9070 } 9071 return ret; 9072 } 9073 9074 @Override 9075 public void exit() { 9076 /* No need for a background scan upon exit from a disconnected state */ 9077 enableBackgroundScan(false); 9078 setScanAlarm(false); 9079 } 9080 } 9081 9082 class WpsRunningState extends State { 9083 // Tracks the source to provide a reply 9084 private Message mSourceMessage; 9085 @Override 9086 public void enter() { 9087 mSourceMessage = Message.obtain(getCurrentMessage()); 9088 } 9089 @Override 9090 public boolean processMessage(Message message) { 9091 logStateAndMessage(message, getClass().getSimpleName()); 9092 9093 switch (message.what) { 9094 case WifiMonitor.WPS_SUCCESS_EVENT: 9095 // Ignore intermediate success, wait for full connection 9096 break; 9097 case WifiMonitor.NETWORK_CONNECTION_EVENT: 9098 replyToMessage(mSourceMessage, WifiManager.WPS_COMPLETED); 9099 mSourceMessage.recycle(); 9100 mSourceMessage = null; 9101 deferMessage(message); 9102 transitionTo(mDisconnectedState); 9103 break; 9104 case WifiMonitor.WPS_OVERLAP_EVENT: 9105 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 9106 WifiManager.WPS_OVERLAP_ERROR); 9107 mSourceMessage.recycle(); 9108 mSourceMessage = null; 9109 transitionTo(mDisconnectedState); 9110 break; 9111 case WifiMonitor.WPS_FAIL_EVENT: 9112 // Arg1 has the reason for the failure 9113 if ((message.arg1 != WifiManager.ERROR) || (message.arg2 != 0)) { 9114 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, message.arg1); 9115 mSourceMessage.recycle(); 9116 mSourceMessage = null; 9117 transitionTo(mDisconnectedState); 9118 } else { 9119 if (DBG) log("Ignore unspecified fail event during WPS connection"); 9120 } 9121 break; 9122 case WifiMonitor.WPS_TIMEOUT_EVENT: 9123 replyToMessage(mSourceMessage, WifiManager.WPS_FAILED, 9124 WifiManager.WPS_TIMED_OUT); 9125 mSourceMessage.recycle(); 9126 mSourceMessage = null; 9127 transitionTo(mDisconnectedState); 9128 break; 9129 case WifiManager.START_WPS: 9130 replyToMessage(message, WifiManager.WPS_FAILED, WifiManager.IN_PROGRESS); 9131 break; 9132 case WifiManager.CANCEL_WPS: 9133 if (mWifiNative.cancelWps()) { 9134 replyToMessage(message, WifiManager.CANCEL_WPS_SUCCEDED); 9135 } else { 9136 replyToMessage(message, WifiManager.CANCEL_WPS_FAILED, WifiManager.ERROR); 9137 } 9138 transitionTo(mDisconnectedState); 9139 break; 9140 /** 9141 * Defer all commands that can cause connections to a different network 9142 * or put the state machine out of connect mode 9143 */ 9144 case CMD_STOP_DRIVER: 9145 case CMD_SET_OPERATIONAL_MODE: 9146 case WifiManager.CONNECT_NETWORK: 9147 case CMD_ENABLE_NETWORK: 9148 case CMD_RECONNECT: 9149 case CMD_REASSOCIATE: 9150 case CMD_ENABLE_ALL_NETWORKS: 9151 deferMessage(message); 9152 break; 9153 case CMD_AUTO_CONNECT: 9154 case CMD_AUTO_ROAM: 9155 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 9156 return HANDLED; 9157 case CMD_START_SCAN: 9158 messageHandlingStatus = MESSAGE_HANDLING_STATUS_DISCARD; 9159 return HANDLED; 9160 case WifiMonitor.NETWORK_DISCONNECTION_EVENT: 9161 if (DBG) log("Network connection lost"); 9162 handleNetworkDisconnect(); 9163 break; 9164 case WifiMonitor.ASSOCIATION_REJECTION_EVENT: 9165 if (DBG) log("Ignore Assoc reject event during WPS Connection"); 9166 break; 9167 case WifiMonitor.AUTHENTICATION_FAILURE_EVENT: 9168 // Disregard auth failure events during WPS connection. The 9169 // EAP sequence is retried several times, and there might be 9170 // failures (especially for wps pin). We will get a WPS_XXX 9171 // event at the end of the sequence anyway. 9172 if (DBG) log("Ignore auth failure during WPS connection"); 9173 break; 9174 case WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT: 9175 // Throw away supplicant state changes when WPS is running. 9176 // We will start getting supplicant state changes once we get 9177 // a WPS success or failure 9178 break; 9179 default: 9180 return NOT_HANDLED; 9181 } 9182 return HANDLED; 9183 } 9184 9185 @Override 9186 public void exit() { 9187 mWifiConfigStore.enableAllNetworks(); 9188 mWifiConfigStore.loadConfiguredNetworks(); 9189 } 9190 } 9191 9192 class SoftApStartingState extends State { 9193 @Override 9194 public void enter() { 9195 final Message message = getCurrentMessage(); 9196 if (message.what == CMD_START_AP) { 9197 final WifiConfiguration config = (WifiConfiguration) message.obj; 9198 9199 if (config == null) { 9200 mWifiApConfigChannel.sendMessage(CMD_REQUEST_AP_CONFIG); 9201 } else { 9202 mWifiApConfigChannel.sendMessage(CMD_SET_AP_CONFIG, config); 9203 startSoftApWithConfig(config); 9204 } 9205 } else { 9206 throw new RuntimeException("Illegal transition to SoftApStartingState: " + message); 9207 } 9208 } 9209 @Override 9210 public boolean processMessage(Message message) { 9211 logStateAndMessage(message, getClass().getSimpleName()); 9212 9213 switch(message.what) { 9214 case CMD_START_SUPPLICANT: 9215 case CMD_STOP_SUPPLICANT: 9216 case CMD_START_AP: 9217 case CMD_STOP_AP: 9218 case CMD_START_DRIVER: 9219 case CMD_STOP_DRIVER: 9220 case CMD_SET_OPERATIONAL_MODE: 9221 case CMD_SET_COUNTRY_CODE: 9222 case CMD_SET_FREQUENCY_BAND: 9223 case CMD_START_PACKET_FILTERING: 9224 case CMD_STOP_PACKET_FILTERING: 9225 case CMD_TETHER_STATE_CHANGE: 9226 deferMessage(message); 9227 break; 9228 case WifiStateMachine.CMD_RESPONSE_AP_CONFIG: 9229 WifiConfiguration config = (WifiConfiguration) message.obj; 9230 if (config != null) { 9231 startSoftApWithConfig(config); 9232 } else { 9233 loge("Softap config is null!"); 9234 sendMessage(CMD_START_AP_FAILURE); 9235 } 9236 break; 9237 case CMD_START_AP_SUCCESS: 9238 setWifiApState(WIFI_AP_STATE_ENABLED); 9239 transitionTo(mSoftApStartedState); 9240 break; 9241 case CMD_START_AP_FAILURE: 9242 setWifiApState(WIFI_AP_STATE_FAILED); 9243 transitionTo(mInitialState); 9244 break; 9245 default: 9246 return NOT_HANDLED; 9247 } 9248 return HANDLED; 9249 } 9250 } 9251 9252 class SoftApStartedState extends State { 9253 @Override 9254 public boolean processMessage(Message message) { 9255 logStateAndMessage(message, getClass().getSimpleName()); 9256 9257 switch(message.what) { 9258 case CMD_STOP_AP: 9259 if (DBG) log("Stopping Soft AP"); 9260 /* We have not tethered at this point, so we just shutdown soft Ap */ 9261 try { 9262 mNwService.stopAccessPoint(mInterfaceName); 9263 } catch(Exception e) { 9264 loge("Exception in stopAccessPoint()"); 9265 } 9266 setWifiApState(WIFI_AP_STATE_DISABLED); 9267 transitionTo(mInitialState); 9268 break; 9269 case CMD_START_AP: 9270 // Ignore a start on a running access point 9271 break; 9272 // Fail client mode operation when soft AP is enabled 9273 case CMD_START_SUPPLICANT: 9274 loge("Cannot start supplicant with a running soft AP"); 9275 setWifiState(WIFI_STATE_UNKNOWN); 9276 break; 9277 case CMD_TETHER_STATE_CHANGE: 9278 TetherStateChange stateChange = (TetherStateChange) message.obj; 9279 if (startTethering(stateChange.available)) { 9280 transitionTo(mTetheringState); 9281 } 9282 break; 9283 default: 9284 return NOT_HANDLED; 9285 } 9286 return HANDLED; 9287 } 9288 } 9289 9290 class TetheringState extends State { 9291 @Override 9292 public void enter() { 9293 /* Send ourselves a delayed message to shut down if tethering fails to notify */ 9294 sendMessageDelayed(obtainMessage(CMD_TETHER_NOTIFICATION_TIMED_OUT, 9295 ++mTetherToken, 0), TETHER_NOTIFICATION_TIME_OUT_MSECS); 9296 } 9297 @Override 9298 public boolean processMessage(Message message) { 9299 logStateAndMessage(message, getClass().getSimpleName()); 9300 9301 switch(message.what) { 9302 case CMD_TETHER_STATE_CHANGE: 9303 TetherStateChange stateChange = (TetherStateChange) message.obj; 9304 if (isWifiTethered(stateChange.active)) { 9305 transitionTo(mTetheredState); 9306 } 9307 return HANDLED; 9308 case CMD_TETHER_NOTIFICATION_TIMED_OUT: 9309 if (message.arg1 == mTetherToken) { 9310 loge("Failed to get tether update, shutdown soft access point"); 9311 transitionTo(mSoftApStartedState); 9312 // Needs to be first thing handled 9313 sendMessageAtFrontOfQueue(CMD_STOP_AP); 9314 } 9315 break; 9316 case CMD_START_SUPPLICANT: 9317 case CMD_STOP_SUPPLICANT: 9318 case CMD_START_AP: 9319 case CMD_STOP_AP: 9320 case CMD_START_DRIVER: 9321 case CMD_STOP_DRIVER: 9322 case CMD_SET_OPERATIONAL_MODE: 9323 case CMD_SET_COUNTRY_CODE: 9324 case CMD_SET_FREQUENCY_BAND: 9325 case CMD_START_PACKET_FILTERING: 9326 case CMD_STOP_PACKET_FILTERING: 9327 deferMessage(message); 9328 break; 9329 default: 9330 return NOT_HANDLED; 9331 } 9332 return HANDLED; 9333 } 9334 } 9335 9336 class TetheredState extends State { 9337 @Override 9338 public boolean processMessage(Message message) { 9339 logStateAndMessage(message, getClass().getSimpleName()); 9340 9341 switch(message.what) { 9342 case CMD_TETHER_STATE_CHANGE: 9343 TetherStateChange stateChange = (TetherStateChange) message.obj; 9344 if (!isWifiTethered(stateChange.active)) { 9345 loge("Tethering reports wifi as untethered!, shut down soft Ap"); 9346 setHostApRunning(null, false); 9347 setHostApRunning(null, true); 9348 } 9349 return HANDLED; 9350 case CMD_STOP_AP: 9351 if (DBG) log("Untethering before stopping AP"); 9352 setWifiApState(WIFI_AP_STATE_DISABLING); 9353 stopTethering(); 9354 transitionTo(mUntetheringState); 9355 // More work to do after untethering 9356 deferMessage(message); 9357 break; 9358 default: 9359 return NOT_HANDLED; 9360 } 9361 return HANDLED; 9362 } 9363 } 9364 9365 class UntetheringState extends State { 9366 @Override 9367 public void enter() { 9368 /* Send ourselves a delayed message to shut down if tethering fails to notify */ 9369 sendMessageDelayed(obtainMessage(CMD_TETHER_NOTIFICATION_TIMED_OUT, 9370 ++mTetherToken, 0), TETHER_NOTIFICATION_TIME_OUT_MSECS); 9371 9372 } 9373 @Override 9374 public boolean processMessage(Message message) { 9375 logStateAndMessage(message, getClass().getSimpleName()); 9376 9377 switch(message.what) { 9378 case CMD_TETHER_STATE_CHANGE: 9379 TetherStateChange stateChange = (TetherStateChange) message.obj; 9380 9381 /* Wait till wifi is untethered */ 9382 if (isWifiTethered(stateChange.active)) break; 9383 9384 transitionTo(mSoftApStartedState); 9385 break; 9386 case CMD_TETHER_NOTIFICATION_TIMED_OUT: 9387 if (message.arg1 == mTetherToken) { 9388 loge("Failed to get tether update, force stop access point"); 9389 transitionTo(mSoftApStartedState); 9390 } 9391 break; 9392 case CMD_START_SUPPLICANT: 9393 case CMD_STOP_SUPPLICANT: 9394 case CMD_START_AP: 9395 case CMD_STOP_AP: 9396 case CMD_START_DRIVER: 9397 case CMD_STOP_DRIVER: 9398 case CMD_SET_OPERATIONAL_MODE: 9399 case CMD_SET_COUNTRY_CODE: 9400 case CMD_SET_FREQUENCY_BAND: 9401 case CMD_START_PACKET_FILTERING: 9402 case CMD_STOP_PACKET_FILTERING: 9403 deferMessage(message); 9404 break; 9405 default: 9406 return NOT_HANDLED; 9407 } 9408 return HANDLED; 9409 } 9410 } 9411 9412 /** 9413 * State machine initiated requests can have replyTo set to null indicating 9414 * there are no recepients, we ignore those reply actions. 9415 */ 9416 private void replyToMessage(Message msg, int what) { 9417 if (msg.replyTo == null) return; 9418 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 9419 mReplyChannel.replyToMessage(msg, dstMsg); 9420 } 9421 9422 private void replyToMessage(Message msg, int what, int arg1) { 9423 if (msg.replyTo == null) return; 9424 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 9425 dstMsg.arg1 = arg1; 9426 mReplyChannel.replyToMessage(msg, dstMsg); 9427 } 9428 9429 private void replyToMessage(Message msg, int what, Object obj) { 9430 if (msg.replyTo == null) return; 9431 Message dstMsg = obtainMessageWithWhatAndArg2(msg, what); 9432 dstMsg.obj = obj; 9433 mReplyChannel.replyToMessage(msg, dstMsg); 9434 } 9435 9436 /** 9437 * arg2 on the source message has a unique id that needs to be retained in replies 9438 * to match the request 9439 * <p>see WifiManager for details 9440 */ 9441 private Message obtainMessageWithWhatAndArg2(Message srcMsg, int what) { 9442 Message msg = Message.obtain(); 9443 msg.what = what; 9444 msg.arg2 = srcMsg.arg2; 9445 return msg; 9446 } 9447 9448 /** 9449 * @param wifiCredentialEventType WIFI_CREDENTIAL_SAVED or WIFI_CREDENTIAL_FORGOT 9450 * @param msg Must have a WifiConfiguration obj to succeed 9451 */ 9452 private void broadcastWifiCredentialChanged(int wifiCredentialEventType, 9453 WifiConfiguration config) { 9454 if (config != null && config.preSharedKey != null) { 9455 Intent intent = new Intent(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION); 9456 intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID, config.SSID); 9457 intent.putExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, 9458 wifiCredentialEventType); 9459 mContext.sendBroadcastAsUser(intent, UserHandle.CURRENT, 9460 android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE); 9461 } 9462 } 9463 9464 private static int parseHex(char ch) { 9465 if ('0' <= ch && ch <= '9') { 9466 return ch - '0'; 9467 } else if ('a' <= ch && ch <= 'f') { 9468 return ch - 'a' + 10; 9469 } else if ('A' <= ch && ch <= 'F') { 9470 return ch - 'A' + 10; 9471 } else { 9472 throw new NumberFormatException("" + ch + " is not a valid hex digit"); 9473 } 9474 } 9475 9476 private byte[] parseHex(String hex) { 9477 /* This only works for good input; don't throw bad data at it */ 9478 if (hex == null) { 9479 return new byte[0]; 9480 } 9481 9482 if (hex.length() % 2 != 0) { 9483 throw new NumberFormatException(hex + " is not a valid hex string"); 9484 } 9485 9486 byte[] result = new byte[(hex.length())/2 + 1]; 9487 result[0] = (byte) ((hex.length())/2); 9488 for (int i = 0, j = 1; i < hex.length(); i += 2, j++) { 9489 int val = parseHex(hex.charAt(i)) * 16 + parseHex(hex.charAt(i+1)); 9490 byte b = (byte) (val & 0xFF); 9491 result[j] = b; 9492 } 9493 9494 return result; 9495 } 9496 9497 private static String makeHex(byte[] bytes) { 9498 StringBuilder sb = new StringBuilder(); 9499 for (byte b : bytes) { 9500 sb.append(String.format("%02x", b)); 9501 } 9502 return sb.toString(); 9503 } 9504 9505 private static String makeHex(byte[] bytes, int from, int len) { 9506 StringBuilder sb = new StringBuilder(); 9507 for (int i = 0; i < len; i++) { 9508 sb.append(String.format("%02x", bytes[from+i])); 9509 } 9510 return sb.toString(); 9511 } 9512 9513 private static byte[] concat(byte[] array1, byte[] array2, byte[] array3) { 9514 9515 int len = array1.length + array2.length + array3.length; 9516 9517 if (array1.length != 0) { 9518 len++; /* add another byte for size */ 9519 } 9520 9521 if (array2.length != 0) { 9522 len++; /* add another byte for size */ 9523 } 9524 9525 if (array3.length != 0) { 9526 len++; /* add another byte for size */ 9527 } 9528 9529 byte[] result = new byte[len]; 9530 9531 int index = 0; 9532 if (array1.length != 0) { 9533 result[index] = (byte) (array1.length & 0xFF); 9534 index++; 9535 for (byte b : array1) { 9536 result[index] = b; 9537 index++; 9538 } 9539 } 9540 9541 if (array2.length != 0) { 9542 result[index] = (byte) (array2.length & 0xFF); 9543 index++; 9544 for (byte b : array2) { 9545 result[index] = b; 9546 index++; 9547 } 9548 } 9549 9550 if (array3.length != 0) { 9551 result[index] = (byte) (array3.length & 0xFF); 9552 index++; 9553 for (byte b : array3) { 9554 result[index] = b; 9555 index++; 9556 } 9557 } 9558 return result; 9559 } 9560 9561 private static byte[] concatHex(byte[] array1, byte[] array2) { 9562 9563 int len = array1.length + array2.length; 9564 9565 byte[] result = new byte[len]; 9566 9567 int index = 0; 9568 if (array1.length != 0) { 9569 for (byte b : array1) { 9570 result[index] = b; 9571 index++; 9572 } 9573 } 9574 9575 if (array2.length != 0) { 9576 for (byte b : array2) { 9577 result[index] = b; 9578 index++; 9579 } 9580 } 9581 9582 return result; 9583 } 9584 9585 void handleGsmAuthRequest(SimAuthRequestData requestData) { 9586 if (targetWificonfiguration == null 9587 || targetWificonfiguration.networkId == requestData.networkId) { 9588 logd("id matches targetWifiConfiguration"); 9589 } else { 9590 logd("id does not match targetWifiConfiguration"); 9591 return; 9592 } 9593 9594 TelephonyManager tm = (TelephonyManager) 9595 mContext.getSystemService(Context.TELEPHONY_SERVICE); 9596 9597 if (tm != null) { 9598 StringBuilder sb = new StringBuilder(); 9599 for (String challenge : requestData.data) { 9600 9601 if (challenge == null || challenge.isEmpty()) 9602 continue; 9603 logd("RAND = " + challenge); 9604 9605 byte[] rand = null; 9606 try { 9607 rand = parseHex(challenge); 9608 } catch (NumberFormatException e) { 9609 loge("malformed challenge"); 9610 continue; 9611 } 9612 9613 String base64Challenge = android.util.Base64.encodeToString( 9614 rand, android.util.Base64.NO_WRAP); 9615 /* 9616 * First, try with appType = 2 => USIM according to 9617 * com.android.internal.telephony.PhoneConstants#APPTYPE_xxx 9618 */ 9619 int appType = 2; 9620 String tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge); 9621 if (tmResponse == null) { 9622 /* Then, in case of failure, issue may be due to sim type, retry as a simple sim 9623 * appType = 1 => SIM 9624 */ 9625 appType = 1; 9626 tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge); 9627 } 9628 logv("Raw Response - " + tmResponse); 9629 9630 if (tmResponse != null && tmResponse.length() > 4) { 9631 byte[] result = android.util.Base64.decode(tmResponse, 9632 android.util.Base64.DEFAULT); 9633 logv("Hex Response -" + makeHex(result)); 9634 int sres_len = result[0]; 9635 String sres = makeHex(result, 1, sres_len); 9636 int kc_offset = 1+sres_len; 9637 int kc_len = result[kc_offset]; 9638 String kc = makeHex(result, 1+kc_offset, kc_len); 9639 sb.append(":" + kc + ":" + sres); 9640 logv("kc:" + kc + " sres:" + sres); 9641 } else { 9642 loge("bad response - " + tmResponse); 9643 } 9644 } 9645 9646 String response = sb.toString(); 9647 logv("Supplicant Response -" + response); 9648 mWifiNative.simAuthResponse(requestData.networkId, "GSM-AUTH", response); 9649 } else { 9650 loge("could not get telephony manager"); 9651 } 9652 } 9653 9654 void handle3GAuthRequest(SimAuthRequestData requestData) { 9655 StringBuilder sb = new StringBuilder(); 9656 byte[] rand = null; 9657 byte[] authn = null; 9658 String res_type = "UMTS-AUTH"; 9659 9660 if (targetWificonfiguration == null 9661 || targetWificonfiguration.networkId == requestData.networkId) { 9662 logd("id matches targetWifiConfiguration"); 9663 } else { 9664 logd("id does not match targetWifiConfiguration"); 9665 return; 9666 } 9667 if (requestData.data.length == 2) { 9668 try { 9669 rand = parseHex(requestData.data[0]); 9670 authn = parseHex(requestData.data[1]); 9671 } catch (NumberFormatException e) { 9672 loge("malformed challenge"); 9673 } 9674 } else { 9675 loge("malformed challenge"); 9676 } 9677 9678 String tmResponse = ""; 9679 if (rand != null && authn != null) { 9680 String base64Challenge = android.util.Base64.encodeToString( 9681 concatHex(rand,authn), android.util.Base64.NO_WRAP); 9682 9683 TelephonyManager tm = (TelephonyManager) 9684 mContext.getSystemService(Context.TELEPHONY_SERVICE); 9685 if (tm != null) { 9686 int appType = 2; // 2 => USIM 9687 tmResponse = tm.getIccSimChallengeResponse(appType, base64Challenge); 9688 logv("Raw Response - " + tmResponse); 9689 } else { 9690 loge("could not get telephony manager"); 9691 } 9692 } 9693 9694 if (tmResponse != null && tmResponse.length() > 4) { 9695 byte[] result = android.util.Base64.decode(tmResponse, 9696 android.util.Base64.DEFAULT); 9697 loge("Hex Response - " + makeHex(result)); 9698 byte tag = result[0]; 9699 if (tag == (byte) 0xdb) { 9700 logv("successful 3G authentication "); 9701 int res_len = result[1]; 9702 String res = makeHex(result, 2, res_len); 9703 int ck_len = result[res_len + 2]; 9704 String ck = makeHex(result, res_len + 3, ck_len); 9705 int ik_len = result[res_len + ck_len + 3]; 9706 String ik = makeHex(result, res_len + ck_len + 4, ik_len); 9707 sb.append(":" + ik + ":" + ck + ":" + res); 9708 logv("ik:" + ik + "ck:" + ck + " res:" + res); 9709 } else if (tag == (byte) 0xdc) { 9710 loge("synchronisation failure"); 9711 int auts_len = result[1]; 9712 String auts = makeHex(result, 2, auts_len); 9713 res_type = "UMTS-AUTS"; 9714 sb.append(":" + auts); 9715 logv("auts:" + auts); 9716 } else { 9717 loge("bad response - unknown tag = " + tag); 9718 return; 9719 } 9720 } else { 9721 loge("bad response - " + tmResponse); 9722 return; 9723 } 9724 9725 String response = sb.toString(); 9726 logv("Supplicant Response -" + response); 9727 mWifiNative.simAuthResponse(requestData.networkId, res_type, response); 9728 } 9729 9730 /** 9731 * @param reason reason code from supplicant on network disconnected event 9732 * @return true if this is a suspicious disconnect 9733 */ 9734 static boolean unexpectedDisconnectedReason(int reason) { 9735 return reason == 2 // PREV_AUTH_NOT_VALID 9736 || reason == 6 // CLASS2_FRAME_FROM_NONAUTH_STA 9737 || reason == 7 // FRAME_FROM_NONASSOC_STA 9738 || reason == 8 // STA_HAS_LEFT 9739 || reason == 9 // STA_REQ_ASSOC_WITHOUT_AUTH 9740 || reason == 14 // MICHAEL_MIC_FAILURE 9741 || reason == 15 // 4WAY_HANDSHAKE_TIMEOUT 9742 || reason == 16 // GROUP_KEY_UPDATE_TIMEOUT 9743 || reason == 18 // GROUP_CIPHER_NOT_VALID 9744 || reason == 19 // PAIRWISE_CIPHER_NOT_VALID 9745 || reason == 23 // IEEE_802_1X_AUTH_FAILED 9746 || reason == 34; // DISASSOC_LOW_ACK 9747 } 9748} 9749