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