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