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