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