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