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