summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author Xin Li <delphij@google.com> 2024-09-07 01:10:38 +0000
committer Gerrit Code Review <noreply-gerritcodereview@google.com> 2024-09-07 01:10:38 +0000
commit4e542261ce482f8c4f4dc054550a9a5cdab27332 (patch)
treec145313a1a04c977b08009be38b68764bbd69151
parentbe616a70313a8a5616d9792432936ee93bee8cc6 (diff)
parent7412367aac121d8da3232c5c4aacdab1d6cd08ba (diff)
Merge "Merge 24Q3 to AOSP main" into main
-rw-r--r--TEST_MAPPING16
-rw-r--r--flags/wifi_flags.aconfig28
-rw-r--r--framework/Android.bp3
-rw-r--r--framework/TEST_MAPPING8
-rw-r--r--framework/api/current.txt15
-rw-r--r--framework/api/system-current.txt5
-rw-r--r--framework/java/android/net/wifi/BaseWifiService.java8
-rw-r--r--framework/java/android/net/wifi/IMacAddressListListener.aidl31
-rw-r--r--framework/java/android/net/wifi/IWifiManager.aidl5
-rw-r--r--framework/java/android/net/wifi/SoftApInfo.java4
-rw-r--r--framework/java/android/net/wifi/WifiAvailableChannel.java40
-rw-r--r--framework/java/android/net/wifi/WifiContext.java8
-rw-r--r--framework/java/android/net/wifi/WifiEnterpriseConfig.java2
-rw-r--r--framework/java/android/net/wifi/WifiManager.java65
-rw-r--r--framework/java/android/net/wifi/WifiScanner.java20
-rw-r--r--framework/java/android/net/wifi/WifiTwtSession.java9
-rw-r--r--framework/java/android/net/wifi/WifiUriParser.java44
-rw-r--r--framework/java/android/net/wifi/p2p/IWifiP2pListener.aidl8
-rw-r--r--framework/java/android/net/wifi/p2p/WifiP2pGroup.java16
-rw-r--r--framework/java/android/net/wifi/p2p/WifiP2pManager.java93
-rw-r--r--framework/java/android/net/wifi/rtt/ResponderLocation.java6
-rw-r--r--framework/java/android/net/wifi/twt/TwtSession.java11
-rw-r--r--framework/java/android/net/wifi/util/WifiResourceCache.java115
-rw-r--r--framework/tests/src/android/net/wifi/WifiUriParserTest.java46
-rw-r--r--framework/tests/src/android/net/wifi/rtt/ResponderLocationTest.java45
-rw-r--r--framework/tests/src/android/net/wifi/util/WifiResourceCacheTest.java106
-rw-r--r--service/ServiceWifiResources/res/drawable/stat_notify_wifi_in_range.xml1
-rw-r--r--service/ServiceWifiResources/res/values-es-rUS/strings.xml6
-rw-r--r--service/ServiceWifiResources/res/values-fa/strings.xml10
-rw-r--r--service/ServiceWifiResources/res/values-fr-feminine/strings.xml22
-rw-r--r--service/ServiceWifiResources/res/values-fr-masculine/strings.xml22
-rw-r--r--service/ServiceWifiResources/res/values-fr-neuter/strings.xml22
-rw-r--r--service/ServiceWifiResources/res/values-fr-rCA/strings.xml8
-rw-r--r--service/ServiceWifiResources/res/values-it/strings.xml2
-rw-r--r--service/ServiceWifiResources/res/values-iw/strings.xml2
-rw-r--r--service/ServiceWifiResources/res/values-ky/strings.xml4
-rw-r--r--service/ServiceWifiResources/res/values-mcc310-mnc150/config.xml27
-rw-r--r--service/ServiceWifiResources/res/values-mcc313-mnc100/config.xml27
l---------service/ServiceWifiResources/res/values-mcc313-mnc1301
-rw-r--r--service/ServiceWifiResources/res/values-mn/strings.xml2
-rw-r--r--service/ServiceWifiResources/res/values-ne/strings.xml2
-rw-r--r--service/ServiceWifiResources/res/values-zu/strings.xml8
-rw-r--r--service/ServiceWifiResources/res/values/config.xml27
-rw-r--r--service/ServiceWifiResources/res/values/overlayable.xml4
-rw-r--r--service/TEST_MAPPING5
-rw-r--r--service/java/com/android/server/wifi/ActiveModeWarden.java75
-rw-r--r--service/java/com/android/server/wifi/ApplicationQosPolicyRequestHandler.java39
-rw-r--r--service/java/com/android/server/wifi/ApplicationQosPolicyTrackingTable.java19
-rw-r--r--service/java/com/android/server/wifi/AvailableNetworkNotifier.java4
-rw-r--r--service/java/com/android/server/wifi/BackupRestoreController.java2
-rw-r--r--service/java/com/android/server/wifi/ClientModeImpl.java108
-rw-r--r--service/java/com/android/server/wifi/DeviceConfigFacade.java27
-rw-r--r--service/java/com/android/server/wifi/DppManager.java7
-rw-r--r--service/java/com/android/server/wifi/ExternalScoreUpdateObserverProxy.java10
-rw-r--r--service/java/com/android/server/wifi/HalDeviceManager.java77
-rw-r--r--service/java/com/android/server/wifi/ISupplicantStaIfaceHal.java7
-rw-r--r--service/java/com/android/server/wifi/InsecureEapNetworkHandler.java12
-rw-r--r--service/java/com/android/server/wifi/LinkProbeManager.java359
-rw-r--r--service/java/com/android/server/wifi/MacAddressUtil.java2
-rw-r--r--service/java/com/android/server/wifi/MboOceController.java2
-rw-r--r--service/java/com/android/server/wifi/MultiInternetWifiNetworkFactory.java1
-rw-r--r--service/java/com/android/server/wifi/RssiMonitor.java6
-rw-r--r--service/java/com/android/server/wifi/RunnerHandler.java10
-rw-r--r--service/java/com/android/server/wifi/RunnerState.java17
-rw-r--r--service/java/com/android/server/wifi/ScanDetail.java3
-rw-r--r--service/java/com/android/server/wifi/ScanRequestProxy.java13
-rw-r--r--service/java/com/android/server/wifi/SoftApManager.java66
-rw-r--r--service/java/com/android/server/wifi/SupplicantStaIfaceHal.java12
-rw-r--r--service/java/com/android/server/wifi/SupplicantStaIfaceHalAidlImpl.java77
-rw-r--r--service/java/com/android/server/wifi/SupplicantStaIfaceHalHidlImpl.java48
-rw-r--r--service/java/com/android/server/wifi/SupplicantStaNetworkCallbackAidlImpl.java2
-rw-r--r--service/java/com/android/server/wifi/TwtManager.java49
-rw-r--r--service/java/com/android/server/wifi/WakeupController.java22
-rw-r--r--service/java/com/android/server/wifi/WakeupLock.java6
-rw-r--r--service/java/com/android/server/wifi/WakeupOnboarding.java4
-rw-r--r--service/java/com/android/server/wifi/WifiApConfigStore.java33
-rw-r--r--service/java/com/android/server/wifi/WifiBlocklistMonitor.java29
-rw-r--r--service/java/com/android/server/wifi/WifiCarrierInfoManager.java72
-rw-r--r--service/java/com/android/server/wifi/WifiConfigManager.java63
-rw-r--r--service/java/com/android/server/wifi/WifiConfigStore.java87
-rw-r--r--service/java/com/android/server/wifi/WifiConfigurationUtil.java17
-rw-r--r--service/java/com/android/server/wifi/WifiConnectivityManager.java126
-rw-r--r--service/java/com/android/server/wifi/WifiCountryCode.java47
-rw-r--r--service/java/com/android/server/wifi/WifiDeviceStateChangeManager.java13
-rw-r--r--service/java/com/android/server/wifi/WifiDiagnostics.java25
-rw-r--r--service/java/com/android/server/wifi/WifiDialogManager.java57
-rw-r--r--service/java/com/android/server/wifi/WifiGlobals.java63
-rw-r--r--service/java/com/android/server/wifi/WifiHealthMonitor.java6
-rw-r--r--service/java/com/android/server/wifi/WifiInjector.java82
-rw-r--r--service/java/com/android/server/wifi/WifiLastResortWatchdog.java3
-rw-r--r--service/java/com/android/server/wifi/WifiMetrics.java43
-rw-r--r--service/java/com/android/server/wifi/WifiNative.java123
-rw-r--r--service/java/com/android/server/wifi/WifiNetworkFactory.java24
-rw-r--r--service/java/com/android/server/wifi/WifiNetworkSelector.java160
-rw-r--r--service/java/com/android/server/wifi/WifiNetworkSuggestionsManager.java23
-rw-r--r--service/java/com/android/server/wifi/WifiRoamingConfigStore.java2
-rw-r--r--service/java/com/android/server/wifi/WifiScoreReport.java14
-rw-r--r--service/java/com/android/server/wifi/WifiServiceImpl.java834
-rw-r--r--service/java/com/android/server/wifi/WifiSettingsBackupRestore.java2
-rw-r--r--service/java/com/android/server/wifi/WifiSettingsConfigStore.java13
-rw-r--r--service/java/com/android/server/wifi/WifiSettingsStore.java7
-rw-r--r--service/java/com/android/server/wifi/WifiShellCommand.java307
-rw-r--r--service/java/com/android/server/wifi/WifiThreadRunner.java82
-rw-r--r--service/java/com/android/server/wifi/WifiVendorHal.java13
-rw-r--r--service/java/com/android/server/wifi/WifiVoipDetector.java253
-rw-r--r--service/java/com/android/server/wifi/WrongPasswordNotifier.java1
-rw-r--r--service/java/com/android/server/wifi/aware/WifiAwareNativeManager.java45
-rw-r--r--service/java/com/android/server/wifi/aware/WifiAwareService.java9
-rw-r--r--service/java/com/android/server/wifi/aware/WifiAwareServiceImpl.java3
-rw-r--r--service/java/com/android/server/wifi/aware/WifiAwareStateManager.java136
-rw-r--r--service/java/com/android/server/wifi/hal/IWifiChip.java10
-rw-r--r--service/java/com/android/server/wifi/hal/WifiChip.java20
-rw-r--r--service/java/com/android/server/wifi/hal/WifiChipAidlImpl.java71
-rw-r--r--service/java/com/android/server/wifi/hal/WifiChipHidlImpl.java30
-rw-r--r--service/java/com/android/server/wifi/hal/WifiStaIfaceAidlImpl.java8
-rw-r--r--service/java/com/android/server/wifi/hal/WifiStaIfaceHidlImpl.java11
-rw-r--r--service/java/com/android/server/wifi/hotspot2/ANQPRequestManager.java28
-rw-r--r--service/java/com/android/server/wifi/hotspot2/NetworkDetail.java24
-rw-r--r--service/java/com/android/server/wifi/hotspot2/PasspointManager.java22
-rw-r--r--service/java/com/android/server/wifi/hotspot2/PasspointProvider.java3
-rw-r--r--service/java/com/android/server/wifi/p2p/ISupplicantP2pIfaceHal.java4
-rw-r--r--service/java/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackHidlImpl.java8
-rw-r--r--service/java/com/android/server/wifi/p2p/WifiP2pMetrics.java23
-rw-r--r--service/java/com/android/server/wifi/p2p/WifiP2pNative.java26
-rw-r--r--service/java/com/android/server/wifi/p2p/WifiP2pServiceImpl.java111
-rw-r--r--service/java/com/android/server/wifi/rtt/RttService.java2
-rw-r--r--service/java/com/android/server/wifi/scanner/WifiScannerInternal.java29
-rw-r--r--service/java/com/android/server/wifi/scanner/WifiScanningServiceImpl.java26
-rw-r--r--service/java/com/android/server/wifi/util/ApConfigUtil.java68
-rw-r--r--service/java/com/android/server/wifi/util/InformationElementUtil.java8
-rw-r--r--service/java/com/android/server/wifi/util/KeystoreWrapper.java2
-rw-r--r--service/java/com/android/server/wifi/util/RssiUtil.java21
-rw-r--r--service/java/com/android/server/wifi/util/WifiPermissionsUtil.java15
-rw-r--r--service/java/com/android/server/wifi/util/XmlUtil.java142
-rw-r--r--service/proto/src/metrics.proto3
-rw-r--r--service/tests/wifitests/Android.bp56
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/ActiveModeWardenTest.java60
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/ApplicationQosPolicyRequestHandlerTest.java18
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/ApplicationQosPolicyTrackingTableTest.java46
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/BackupRestoreControllerTest.java4
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/ClientModeImplTest.java129
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/DeviceConfigFacadeTest.java11
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/HalDeviceManagerTest.java84
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/InsecureEapNetworkHandlerTest.java64
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/LinkProbeManagerTest.java374
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java10
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/OuiKeyedDataUtil.java56
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/RssiMonitorTest.java4
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/ScanRequestProxyTest.java3
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/SoftApManagerTest.java271
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/SupplicantStaIfaceHalAidlImplTest.java45
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/SupplicantStaIfaceHalHidlImplTest.java11
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/TwtManagerTest.java85
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WakeupControllerTest.java20
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WakeupLockTest.java13
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WakeupOnboardingTest.java4
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiApConfigStoreTest.java93
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiBlocklistMonitorTest.java51
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiCarrierInfoManagerTest.java24
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java62
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiConfigStoreTest.java123
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiConfigurationTestUtil.java3
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiConfigurationUtilTest.java17
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiConnectivityManagerTest.java68
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiCountryCodeTest.java52
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiDeviceStateChangeManagerTest.java5
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiDiagnosticsTest.java15
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiDialogManagerTest.java29
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiGlobalsTest.java69
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiMetricsTest.java14
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiNativeInterfaceManagementTest.java295
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiNativeTest.java6
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiNetworkFactoryTest.java121
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiNetworkSelectorTest.java181
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiNetworkSuggestionsManagerTest.java130
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiRoamingConfigStoreTest.java4
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiScoreReportTest.java20
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiServiceImplTest.java208
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiSettingsBackupRestoreTest.java10
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiSettingsConfigStoreTest.java4
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiShellCommandTest.java48
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiThreadRunnerTest.java31
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiVendorHalTest.java14
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WifiVoipDetectorTest.java194
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/WrongPasswordNotifierTest.java1
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareDataPathStateManagerTest.java13
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareNativeManagerTest.java44
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareStateManagerTest.java136
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/b2b/WifiRoamingModeManagerTest.java8
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/hal/WifiChipAidlImplTest.java48
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/hal/WifiStaIfaceAidlImplTest.java3
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/hal/WifiStaIfaceHidlImplTest.java5
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/hotspot2/ANQPRequestManagerTest.java121
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/hotspot2/PasspointManagerTest.java36
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackAidlImplTest.java4
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackHidlImplTest.java5
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pMetricsTest.java24
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pNativeInterfaceManagementTest.java27
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pNativeTest.java132
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pServiceImplTest.java53
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/util/ApConfigUtilTest.java69
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/util/InformationElementUtilTest.java8
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/util/RssiUtilTest.java11
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/util/WifiPermissionsUtilTest.java46
-rw-r--r--service/tests/wifitests/src/com/android/server/wifi/util/XmlUtilTest.java14
-rw-r--r--tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/Android.bp1
-rw-r--r--tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/WifiAwareSnippet.java2
-rw-r--r--tests/hostsidetests/multidevices/com.google.snippet.wifi/direct/Android.bp1
208 files changed, 6099 insertions, 3549 deletions
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 0e93c9d139..c1dd1579a7 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -29,5 +29,21 @@
}
]
}
+ ],
+ "wifi-mainline-presubmit": [
+ {
+ "name": "MtsWifiTestCases"
+ },
+ {
+ "name": "CtsWifiTestCases",
+ "options": [
+ {
+ "exclude-annotation": "android.net.wifi.cts.VirtualDeviceNotSupported"
+ },
+ {
+ "exclude-annotation": "com.android.compatibility.common.util.NonMainlineTest"
+ }
+ ]
+ }
]
}
diff --git a/flags/wifi_flags.aconfig b/flags/wifi_flags.aconfig
index deb86c987d..2da04a5284 100644
--- a/flags/wifi_flags.aconfig
+++ b/flags/wifi_flags.aconfig
@@ -24,6 +24,7 @@ flag {
flag {
name: "network_provider_battery_charging_status"
+ is_exported: true
namespace: "wifi"
description: "Control the API that allows setting / reading the NetworkProviderInfo's battery charging status"
bug: "305067231"
@@ -31,6 +32,7 @@ flag {
flag {
name: "shared_connectivity_broadcast_receiver_test_api"
+ is_exported: true
namespace: "wifi"
description: "Control the test API for SharedConnectivityManager's getBroadcastReceiver() method"
bug: "305067231"
@@ -45,6 +47,7 @@ flag {
flag {
name: "android_v_wifi_api"
+ is_exported: true
namespace: "wifi"
description: "For new API added to Android V"
bug: "319927407"
@@ -58,3 +61,28 @@ flag {
bug: "295792510"
is_fixed_read_only: true
}
+
+flag {
+ name: "get_channel_width_api"
+ namespace: "wifi"
+ description: "Add new API to get channel width"
+ bug: "335358378"
+ is_fixed_read_only: true
+}
+
+flag {
+ name: "voip_detection"
+ namespace: "wifi"
+ description: "Detect VoIP over Wifi and execute optimization"
+ bug: "295885471"
+ is_fixed_read_only: true
+}
+
+flag {
+ name: "get_bssid_blocklist_api"
+ is_exported: true
+ namespace: "wifi"
+ description: "Add new API to get BSSID blocklist"
+ bug: "336109216"
+ is_fixed_read_only: true
+} \ No newline at end of file
diff --git a/framework/Android.bp b/framework/Android.bp
index fe6fdce004..58b1fc4b6b 100644
--- a/framework/Android.bp
+++ b/framework/Android.bp
@@ -188,6 +188,9 @@ java_sdk_library {
"framework-tethering.stubs.module_lib",
],
},
+ api_srcs: [
+ ":wifi_javadoc_only_files",
+ ],
jarjar_rules: ":wifi-jarjar-rules",
diff --git a/framework/TEST_MAPPING b/framework/TEST_MAPPING
index 1eb3a9aa3c..d52846655b 100644
--- a/framework/TEST_MAPPING
+++ b/framework/TEST_MAPPING
@@ -18,5 +18,13 @@
{
"name": "FrameworksWifiTests[com.google.android.wifi.apex]"
}
+ ],
+ "wifi-mainline-presubmit": [
+ {
+ "name": "FrameworksWifiApiTests"
+ },
+ {
+ "name": "FrameworksWifiTests"
+ }
]
}
diff --git a/framework/api/current.txt b/framework/api/current.txt
index ccdd8a7daa..a277bca42c 100644
--- a/framework/api/current.txt
+++ b/framework/api/current.txt
@@ -145,6 +145,7 @@ package android.net.wifi {
public final class WifiAvailableChannel implements android.os.Parcelable {
ctor public WifiAvailableChannel(int, int);
method public int describeContents();
+ method @FlaggedApi("com.android.wifi.flags.get_channel_width_api") public int getChannelWidth();
method public int getFrequencyMhz();
method public int getOperationalModes();
method public void writeToParcel(@NonNull android.os.Parcel, int);
@@ -1424,6 +1425,12 @@ package android.net.wifi.p2p {
field public static final String EXTRA_WIFI_P2P_GROUP = "p2pGroupInfo";
field public static final String EXTRA_WIFI_P2P_INFO = "wifiP2pInfo";
field public static final String EXTRA_WIFI_STATE = "wifi_p2p_state";
+ field @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public static final int GROUP_CREATION_FAILURE_REASON_CONNECTION_CANCELLED = 0; // 0x0
+ field @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public static final int GROUP_CREATION_FAILURE_REASON_GROUP_REMOVED = 4; // 0x4
+ field @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public static final int GROUP_CREATION_FAILURE_REASON_INVITATION_FAILED = 5; // 0x5
+ field @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public static final int GROUP_CREATION_FAILURE_REASON_PROVISION_DISCOVERY_FAILED = 3; // 0x3
+ field @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public static final int GROUP_CREATION_FAILURE_REASON_TIMED_OUT = 1; // 0x1
+ field @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public static final int GROUP_CREATION_FAILURE_REASON_USER_REJECTED = 2; // 0x2
field public static final int NO_SERVICE_REQUESTS = 3; // 0x3
field public static final int P2P_UNSUPPORTED = 1; // 0x1
field public static final String WIFI_P2P_CONNECTION_CHANGED_ACTION = "android.net.wifi.p2p.CONNECTION_STATE_CHANGE";
@@ -1515,18 +1522,18 @@ package android.net.wifi.p2p {
@FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public static interface WifiP2pManager.WifiP2pListener {
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onDeviceConfigurationChanged(@Nullable android.net.wifi.p2p.WifiP2pDevice);
- method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onDiscoveryStateChanged(boolean);
+ method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onDiscoveryStateChanged(int);
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onFrequencyChanged(@NonNull android.net.wifi.p2p.WifiP2pInfo, @NonNull android.net.wifi.p2p.WifiP2pGroup);
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onGroupCreated(@NonNull android.net.wifi.p2p.WifiP2pInfo, @NonNull android.net.wifi.p2p.WifiP2pGroup);
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onGroupCreating();
- method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onGroupCreationFailed();
+ method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onGroupCreationFailed(int);
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onGroupNegotiationRejectedByUser();
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onGroupRemoved();
- method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onListenStateChanged(boolean);
+ method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onListenStateChanged(int);
+ method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onP2pStateChanged(int);
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onPeerClientDisconnected(@NonNull android.net.wifi.p2p.WifiP2pInfo, @NonNull android.net.wifi.p2p.WifiP2pGroup);
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onPeerClientJoined(@NonNull android.net.wifi.p2p.WifiP2pInfo, @NonNull android.net.wifi.p2p.WifiP2pGroup);
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onPeerListChanged(@NonNull android.net.wifi.p2p.WifiP2pDeviceList);
- method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public default void onStateChanged(boolean);
}
public final class WifiP2pWfdInfo implements android.os.Parcelable {
diff --git a/framework/api/system-current.txt b/framework/api/system-current.txt
index 7e7b0f0b0e..d06e48ac5e 100644
--- a/framework/api/system-current.txt
+++ b/framework/api/system-current.txt
@@ -719,6 +719,7 @@ package android.net.wifi {
method @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS) public void factoryReset();
method @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD, android.Manifest.permission.NETWORK_STACK}) public void forget(int, @Nullable android.net.wifi.WifiManager.ActionListener);
method @NonNull @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD}) public java.util.List<android.util.Pair<android.net.wifi.WifiConfiguration,java.util.Map<java.lang.Integer,java.util.List<android.net.wifi.ScanResult>>>> getAllMatchingWifiConfigs(@NonNull java.util.List<android.net.wifi.ScanResult>);
+ method @FlaggedApi("com.android.wifi.flags.get_bssid_blocklist_api") @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD}) public void getBssidBlocklist(@NonNull java.util.List<android.net.wifi.WifiSsid>, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.util.List<android.net.MacAddress>>);
method @Nullable @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.ACCESS_COARSE_LOCATION}) public String getCountryCode();
method @Nullable @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.Manifest.permission.NETWORK_SETUP_WIZARD}) public android.net.Network getCurrentNetwork();
method public static int getEasyConnectMaxAllowedResponderDeviceInfoLength();
@@ -1743,12 +1744,12 @@ package android.net.wifi.twt {
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") @NonNull public android.net.wifi.twt.TwtRequest.Builder setLinkId(@IntRange(from=0x0, to=0xf) int);
}
- @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public interface TwtSession extends java.lang.AutoCloseable {
- method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public void close();
+ @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public interface TwtSession {
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public int getMloLinkId();
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public void getStats(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<android.os.Bundle>);
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public int getWakeDurationMicros();
method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public long getWakeIntervalMicros();
+ method @FlaggedApi("com.android.wifi.flags.android_v_wifi_api") public void teardown();
field public static final String TWT_STATS_KEY_INT_AVERAGE_EOSP_DURATION_MICROS = "key_avg_eosp_dur";
field public static final String TWT_STATS_KEY_INT_AVERAGE_RX_PACKET_COUNT = "key_avg_rx_pkt_count";
field public static final String TWT_STATS_KEY_INT_AVERAGE_RX_PACKET_SIZE = "key_avg_rx_pkt_size";
diff --git a/framework/java/android/net/wifi/BaseWifiService.java b/framework/java/android/net/wifi/BaseWifiService.java
index 8a1dad8518..5f58810584 100644
--- a/framework/java/android/net/wifi/BaseWifiService.java
+++ b/framework/java/android/net/wifi/BaseWifiService.java
@@ -232,6 +232,12 @@ public class BaseWifiService extends IWifiManager.Stub {
}
@Override
+ public void getBssidBlocklist(ParceledListSlice<WifiSsid> ssids,
+ IMacAddressListListener listener) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
public void setMacRandomizationSettingPasspointEnabled(String fqdn, boolean enable) {
throw new UnsupportedOperationException();
}
@@ -247,7 +253,7 @@ public class BaseWifiService extends IWifiManager.Stub {
}
@Override
- public List<ScanResult> getScanResults(String callingPackage, String callingFeatureId) {
+ public ParceledListSlice getScanResults(String callingPackage, String callingFeatureId) {
throw new UnsupportedOperationException();
}
diff --git a/framework/java/android/net/wifi/IMacAddressListListener.aidl b/framework/java/android/net/wifi/IMacAddressListListener.aidl
new file mode 100644
index 0000000000..45c9941848
--- /dev/null
+++ b/framework/java/android/net/wifi/IMacAddressListListener.aidl
@@ -0,0 +1,31 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi;
+
+import android.net.MacAddress;
+
+import com.android.modules.utils.ParceledListSlice;
+
+/**
+ * Interface for IMacAddressListListener.
+ *
+ * @hide
+ */
+oneway interface IMacAddressListListener
+{
+ void onResult(in ParceledListSlice<MacAddress> value);
+} \ No newline at end of file
diff --git a/framework/java/android/net/wifi/IWifiManager.aidl b/framework/java/android/net/wifi/IWifiManager.aidl
index bbe667211e..0a6e210249 100644
--- a/framework/java/android/net/wifi/IWifiManager.aidl
+++ b/framework/java/android/net/wifi/IWifiManager.aidl
@@ -41,6 +41,7 @@ import android.net.wifi.INetworkRequestMatchCallback;
import android.net.wifi.IOnWifiActivityEnergyInfoListener;
import android.net.wifi.IOnWifiDriverCountryCodeChangedListener;
import android.net.wifi.IWifiNetworkStateChangedListener;
+import android.net.wifi.IMacAddressListListener;
import android.net.wifi.IOnWifiUsabilityStatsListener;
import android.net.wifi.IPnoScanResultsCallback;
import android.net.wifi.IScanResultsCallback;
@@ -156,10 +157,12 @@ interface IWifiManager
boolean startScan(String packageName, String featureId);
- List<ScanResult> getScanResults(String callingPackage, String callingFeatureId);
+ ParceledListSlice getScanResults(String callingPackage, String callingFeatureId);
void getChannelData(in IListListener listener, String packageName, in Bundle extras);
+ void getBssidBlocklist(in ParceledListSlice<WifiSsid> ssids, in IMacAddressListListener listener);
+
boolean disconnect(String packageName);
boolean reconnect(String packageName);
diff --git a/framework/java/android/net/wifi/SoftApInfo.java b/framework/java/android/net/wifi/SoftApInfo.java
index 23d680dfce..f4440e9e74 100644
--- a/framework/java/android/net/wifi/SoftApInfo.java
+++ b/framework/java/android/net/wifi/SoftApInfo.java
@@ -37,7 +37,9 @@ import java.util.List;
import java.util.Objects;
/**
- * A class representing information about SoftAp.
+ * A class representing information about a specific SoftAP instance. A SoftAP instance may be a
+ * single band AP or a bridged AP (across multiple bands). To get the state of the AP interface
+ * itself, use {@link android.net.wifi.WifiManager.SoftApCallback#onStateChanged(SoftApState)}.
* {@see WifiManager}
*
* @hide
diff --git a/framework/java/android/net/wifi/WifiAvailableChannel.java b/framework/java/android/net/wifi/WifiAvailableChannel.java
index 11a4054c52..4f3596d688 100644
--- a/framework/java/android/net/wifi/WifiAvailableChannel.java
+++ b/framework/java/android/net/wifi/WifiAvailableChannel.java
@@ -15,12 +15,15 @@
*/
package android.net.wifi;
+import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.os.Parcel;
import android.os.Parcelable;
+import com.android.wifi.flags.Flags;
+
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Objects;
@@ -124,9 +127,23 @@ public final class WifiAvailableChannel implements Parcelable {
*/
private @OpMode int mOpModes;
+ /**
+ * Wifi channel bandwidth.
+ */
+ private @WifiAnnotations.ChannelWidth int mChannelWidth;
+
public WifiAvailableChannel(int freq, @OpMode int opModes) {
+ this(freq, opModes, ScanResult.CHANNEL_WIDTH_20MHZ);
+ }
+
+ /**
+ * @hide
+ */
+ public WifiAvailableChannel(int freq, @OpMode int opModes,
+ @WifiAnnotations.ChannelWidth int channelWidth) {
mFrequency = freq;
mOpModes = opModes;
+ mChannelWidth = channelWidth;
}
private WifiAvailableChannel(@NonNull Parcel in) {
@@ -136,6 +153,7 @@ public final class WifiAvailableChannel implements Parcelable {
private void readFromParcel(@NonNull Parcel in) {
mFrequency = in.readInt();
mOpModes = in.readInt();
+ mChannelWidth = in.readInt();
}
/**
@@ -164,6 +182,20 @@ public final class WifiAvailableChannel implements Parcelable {
| FILTER_CELLULAR_COEXISTENCE;
}
+ /**
+ * Get the channel bandwidth, which indicates the amount of frequency spectrum allocated for
+ * data transmission within a channel.
+ *
+ * @return the bandwidth representation of the Wi-Fi channel from
+ * {@link ScanResult#CHANNEL_WIDTH_20MHZ}, {@link ScanResult#CHANNEL_WIDTH_40MHZ},
+ * {@link ScanResult#CHANNEL_WIDTH_80MHZ}, {@link ScanResult#CHANNEL_WIDTH_160MHZ},
+ * {@link ScanResult#CHANNEL_WIDTH_80MHZ_PLUS_MHZ} or {@link ScanResult#CHANNEL_WIDTH_320MHZ}.
+ */
+ @FlaggedApi(Flags.FLAG_GET_CHANNEL_WIDTH_API)
+ public @WifiAnnotations.ChannelWidth int getChannelWidth() {
+ return mChannelWidth;
+ }
+
@Override
public int describeContents() {
return 0;
@@ -175,12 +207,13 @@ public final class WifiAvailableChannel implements Parcelable {
if (o == null || getClass() != o.getClass()) return false;
WifiAvailableChannel that = (WifiAvailableChannel) o;
return mFrequency == that.mFrequency
- && mOpModes == that.mOpModes;
+ && mOpModes == that.mOpModes
+ && mChannelWidth == that.mChannelWidth;
}
@Override
public int hashCode() {
- return Objects.hash(mFrequency, mOpModes);
+ return Objects.hash(mFrequency, mOpModes, mChannelWidth);
}
@Override
@@ -188,6 +221,8 @@ public final class WifiAvailableChannel implements Parcelable {
StringBuilder sbuf = new StringBuilder();
sbuf.append("mFrequency = ")
.append(mFrequency)
+ .append(", mChannelWidth = ")
+ .append(mChannelWidth)
.append(", mOpModes = ")
.append(String.format("%x", mOpModes));
return sbuf.toString();
@@ -197,6 +232,7 @@ public final class WifiAvailableChannel implements Parcelable {
public void writeToParcel(@NonNull Parcel dest, int flags) {
dest.writeInt(mFrequency);
dest.writeInt(mOpModes);
+ dest.writeInt(mChannelWidth);
}
public static final @android.annotation.NonNull Creator<WifiAvailableChannel> CREATOR =
diff --git a/framework/java/android/net/wifi/WifiContext.java b/framework/java/android/net/wifi/WifiContext.java
index f94f6d45a5..f8d808e429 100644
--- a/framework/java/android/net/wifi/WifiContext.java
+++ b/framework/java/android/net/wifi/WifiContext.java
@@ -26,6 +26,7 @@ import android.content.pm.ResolveInfo;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.net.wifi.util.Environment;
+import android.net.wifi.util.WifiResourceCache;
import android.os.UserHandle;
import android.util.Log;
import android.util.SparseArray;
@@ -63,9 +64,11 @@ public class WifiContext extends ContextWrapper {
private Context mResourcesApkContext;
private SparseArray<WifiStringResourceWrapper> mWifiStringResourceWrapperSparseArray =
new SparseArray<>();
+ private WifiResourceCache mWifiResourceCache;
public WifiContext(@NonNull Context contextBase) {
super(contextBase);
+ mWifiResourceCache = new WifiResourceCache(this);
}
/** Get the package name of ServiceWifiResources.apk */
@@ -196,6 +199,10 @@ public class WifiContext extends ContextWrapper {
return mWifiThemeFromApk;
}
+ public WifiResourceCache getResourceCache() {
+ return mWifiResourceCache;
+ }
+
/** Get the package name that service-wifi runs under. */
public String getServiceWifiPackageName() {
return SERVICE_WIFI_PACKAGE_NAME;
@@ -211,6 +218,7 @@ public class WifiContext extends ContextWrapper {
mWifiThemeFromApk = null;
mResourcesApkContext = null;
mWifiStringResourceWrapperSparseArray.clear();
+ mWifiResourceCache.reset();
}
/**
diff --git a/framework/java/android/net/wifi/WifiEnterpriseConfig.java b/framework/java/android/net/wifi/WifiEnterpriseConfig.java
index e141d3bcbd..71d98e1afa 100644
--- a/framework/java/android/net/wifi/WifiEnterpriseConfig.java
+++ b/framework/java/android/net/wifi/WifiEnterpriseConfig.java
@@ -272,7 +272,7 @@ public class WifiEnterpriseConfig implements Parcelable {
* Each entry includes the supported field's key and its maximum allowed length.
*/
private static final Map<String, Integer> SUPPORTED_FIELDS = Map.ofEntries(
- Map.entry(ALTSUBJECT_MATCH_KEY, 256),
+ Map.entry(ALTSUBJECT_MATCH_KEY, 1024),
Map.entry(ANON_IDENTITY_KEY, 1024),
Map.entry(CA_CERT_KEY, CERTIFICATE_MAX_LENGTH),
Map.entry(CA_PATH_KEY, 4096),
diff --git a/framework/java/android/net/wifi/WifiManager.java b/framework/java/android/net/wifi/WifiManager.java
index 1f76a20e09..7bd0c0d591 100644
--- a/framework/java/android/net/wifi/WifiManager.java
+++ b/framework/java/android/net/wifi/WifiManager.java
@@ -4518,12 +4518,26 @@ public class WifiManager {
* {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission
* and {@link android.Manifest.permission#ACCESS_WIFI_STATE} permission
* in order to get valid results.
+ *
+ * <p>
+ * When an Access Point’s beacon or probe response includes a Multi-BSSID Element, the
+ * returned scan results should include separate scan result for each BSSID within the
+ * Multi-BSSID Information Element. This includes both transmitted and non-transmitted BSSIDs.
+ * Original Multi-BSSID Element will be included in the Information Elements attached to
+ * each of the scan results.
+ * Note: This is the expected behavior for devices supporting 11ax (WiFi-6) and above, and an
+ * optional requirement for devices running with older WiFi generations.
+ * </p>
*/
@RequiresPermission(allOf = {ACCESS_WIFI_STATE, ACCESS_FINE_LOCATION})
public List<ScanResult> getScanResults() {
try {
- return mService.getScanResults(mContext.getOpPackageName(),
- mContext.getAttributionTag());
+ ParceledListSlice<ScanResult> parceledList = mService
+ .getScanResults(mContext.getOpPackageName(), mContext.getAttributionTag());
+ if (parceledList == null) {
+ return Collections.emptyList();
+ }
+ return parceledList.getList();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -7413,7 +7427,7 @@ public class WifiManager {
* <li> This API will cause reconnect if the current active connection is marked metered.</li>
*
* @param networkId the ID of the network as returned by {@link #addNetwork} or {@link
- * getConfiguredNetworks}.
+ * #getConfiguredNetworks()}.
* @param listener for callbacks on success or failure. Can be null.
* @throws IllegalStateException if the WifiManager instance needs to be
* initialized again
@@ -9604,6 +9618,44 @@ public class WifiManager {
}
/**
+ * Gets the list of BSSIDs which are currently disabled for Wi-Fi auto-join connections.
+ *
+ * @param ssids If empty, then get all currently disabled BSSIDs.
+ * If non-empty, then only get currently disabled BSSIDs with matching SSIDs.
+ * @param executor The executor to execute the callback of the {@code resultListener} object.
+ * @param resultListener callback to retrieve the blocked BSSIDs
+ *
+ * @hide
+ */
+ @SystemApi
+ @FlaggedApi(Flags.FLAG_GET_BSSID_BLOCKLIST_API)
+ @RequiresPermission(anyOf = {
+ android.Manifest.permission.NETWORK_SETTINGS,
+ android.Manifest.permission.NETWORK_SETUP_WIZARD})
+ public void getBssidBlocklist(@NonNull List<WifiSsid> ssids,
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull Consumer<List<MacAddress>> resultListener) {
+ Objects.requireNonNull(ssids, "ssids cannot be null");
+ Objects.requireNonNull(executor, "executor cannot be null");
+ Objects.requireNonNull(resultListener, "resultsCallback cannot be null");
+ try {
+ mService.getBssidBlocklist(
+ new ParceledListSlice<>(ssids),
+ new IMacAddressListListener.Stub() {
+ @Override
+ public void onResult(ParceledListSlice<MacAddress> value) {
+ Binder.clearCallingIdentity();
+ executor.execute(() -> {
+ resultListener.accept(value.getList());
+ });
+ }
+ });
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* Abstract class for scan results callback. Should be extended by applications and set when
* calling {@link WifiManager#registerScanResultsCallback(Executor, ScanResultsCallback)}.
*/
@@ -11581,10 +11633,6 @@ public class WifiManager {
})
public void addCustomDhcpOptions(@NonNull WifiSsid ssid, @NonNull byte[] oui,
@NonNull List<DhcpOption> options) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "addCustomDhcpOptions: ssid="
- + ssid + ", oui=" + Arrays.toString(oui) + ", options=" + options);
- }
try {
mService.addCustomDhcpOptions(ssid, oui, options);
} catch (RemoteException e) {
@@ -11607,9 +11655,6 @@ public class WifiManager {
android.Manifest.permission.OVERRIDE_WIFI_CONFIG
})
public void removeCustomDhcpOptions(@NonNull WifiSsid ssid, @NonNull byte[] oui) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "removeCustomDhcpOptions: ssid=" + ssid + ", oui=" + Arrays.toString(oui));
- }
try {
mService.removeCustomDhcpOptions(ssid, oui);
} catch (RemoteException e) {
diff --git a/framework/java/android/net/wifi/WifiScanner.java b/framework/java/android/net/wifi/WifiScanner.java
index 93ea0b0bad..b9c6f428d3 100644
--- a/framework/java/android/net/wifi/WifiScanner.java
+++ b/framework/java/android/net/wifi/WifiScanner.java
@@ -1554,6 +1554,16 @@ public class WifiScanner {
/**
* Retrieve the most recent scan results from a single scan request.
+ *
+ * <p>
+ * When an Access Point’s beacon or probe response includes a Multi-BSSID Element, the
+ * returned scan results should include separate scan result for each BSSID within the
+ * Multi-BSSID Information Element. This includes both transmitted and non-transmitted BSSIDs.
+ * Original Multi-BSSID Element will be included in the Information Elements attached to
+ * each of the scan results.
+ * Note: This is the expected behavior for devices supporting 11ax (WiFi-6) and above, and an
+ * optional requirement for devices running with older WiFi generations.
+ * </p>
*/
@NonNull
@RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
@@ -1569,6 +1579,16 @@ public class WifiScanner {
/**
* Retrieve the scan data cached by the hardware.
*
+ * <p>
+ * When an Access Point’s beacon or probe response includes a Multi-BSSID Element, the
+ * returned scan results should include separate scan result for each BSSID within the
+ * Multi-BSSID Information Element. This includes both transmitted and non-transmitted BSSIDs.
+ * Original Multi-BSSID Element will be included in the Information Elements attached to
+ * each of the scan results.
+ * Note: This is the expected behavior for devices supporting 11ax (WiFi-6) and above, and an
+ * optional requirement for devices running with older WiFi generations.
+ * </p>
+ *
* @param executor The executor on which callback will be invoked.
* @param resultsCallback An asynchronous callback that will return the cached scan data.
*
diff --git a/framework/java/android/net/wifi/WifiTwtSession.java b/framework/java/android/net/wifi/WifiTwtSession.java
index c6e570ed9f..0967415d42 100644
--- a/framework/java/android/net/wifi/WifiTwtSession.java
+++ b/framework/java/android/net/wifi/WifiTwtSession.java
@@ -86,14 +86,11 @@ public class WifiTwtSession implements TwtSession {
mMloLinkId = mloLinkId;
mOwner = owner;
mSessionId = sessionId;
- mCloseGuard.open("close");
+ mCloseGuard.open("teardown");
}
- /**
- * Closes this resource, relinquishing any underlying resources.
- */
@Override
- public void close() {
+ public void teardown() {
try {
WifiManager mgr = mMgr.get();
if (mgr == null) {
@@ -103,8 +100,6 @@ public class WifiTwtSession implements TwtSession {
mgr.teardownTwtSession(mSessionId);
mMgr.clear();
mCloseGuard.close();
- } catch (Exception e) {
- Log.e(TAG, "Failed to close WifiTwtSession.");
} finally {
Reference.reachabilityFence(this);
}
diff --git a/framework/java/android/net/wifi/WifiUriParser.java b/framework/java/android/net/wifi/WifiUriParser.java
index 926678a314..ada1fa97ba 100644
--- a/framework/java/android/net/wifi/WifiUriParser.java
+++ b/framework/java/android/net/wifi/WifiUriParser.java
@@ -19,6 +19,7 @@ import android.annotation.FlaggedApi;
import android.annotation.NonNull;
import android.annotation.SystemApi;
import android.text.TextUtils;
+import android.util.Log;
import androidx.annotation.VisibleForTesting;
@@ -64,6 +65,7 @@ public class WifiUriParser {
static final String PREFIX_ZXING_SSID = "S:";
static final String PREFIX_ZXING_PASSWORD = "P:";
static final String PREFIX_ZXING_HIDDEN_SSID = "H:";
+ static final String PREFIX_ZXING_TRANSITION_DISABLE = "R:";
static final String DELIMITER_QR_CODE = ";";
@@ -73,6 +75,8 @@ public class WifiUriParser {
static final String SECURITY_WPA_PSK = "WPA";
static final String SECURITY_SAE = "SAE";
+ private static final String SECURITY_ADB = "ADB";
+
private WifiUriParser() {}
/**
@@ -122,7 +126,10 @@ public class WifiUriParser {
String ssid = getValueOrNull(keyValueList, PREFIX_ZXING_SSID);
String password = getValueOrNull(keyValueList, PREFIX_ZXING_PASSWORD);
String hiddenSsidString = getValueOrNull(keyValueList, PREFIX_ZXING_HIDDEN_SSID);
+ String transitionDisabledValue = getValueOrNull(keyValueList,
+ PREFIX_ZXING_TRANSITION_DISABLE);
boolean hiddenSsid = "true".equalsIgnoreCase(hiddenSsidString);
+ boolean isTransitionDisabled = "1".equalsIgnoreCase(transitionDisabledValue);
// "\", ";", "," and ":" are escaped with a backslash "\", should remove at first
security = removeBackSlash(security);
@@ -130,7 +137,8 @@ public class WifiUriParser {
password = removeBackSlash(password);
if (isValidConfig(security, ssid, password)) {
config = generatetWifiConfiguration(
- security, ssid, password, hiddenSsid, WifiConfiguration.INVALID_NETWORK_ID);
+ security, ssid, password, hiddenSsid, WifiConfiguration.INVALID_NETWORK_ID,
+ isTransitionDisabled);
}
if (config == null) {
@@ -229,21 +237,20 @@ public class WifiUriParser {
* @return WifiConfiguration from parsing result
*/
private static WifiConfiguration generatetWifiConfiguration(
- String security, String ssid, String preSharedKey, boolean hiddenSsid, int networkId) {
+ String security, String ssid, String preSharedKey, boolean hiddenSsid, int networkId,
+ boolean isTransitionDisabled) {
final WifiConfiguration wifiConfiguration = new WifiConfiguration();
wifiConfiguration.SSID = addQuotationIfNeeded(ssid);
wifiConfiguration.hiddenSSID = hiddenSsid;
wifiConfiguration.networkId = networkId;
if (TextUtils.isEmpty(security) || SECURITY_NO_PASSWORD.equals(security)) {
- List<SecurityParams> securityParamsList = new ArrayList<>();
- securityParamsList.add(
- SecurityParams.createSecurityParamsBySecurityType(
- WifiConfiguration.SECURITY_TYPE_OPEN));
- securityParamsList.add(
- SecurityParams.createSecurityParamsBySecurityType(
- WifiConfiguration.SECURITY_TYPE_OWE));
- wifiConfiguration.setSecurityParams(securityParamsList);
+ wifiConfiguration.setSecurityParams(
+ Arrays.asList(
+ SecurityParams.createSecurityParamsBySecurityType(
+ WifiConfiguration.SECURITY_TYPE_OPEN),
+ SecurityParams.createSecurityParamsBySecurityType(
+ WifiConfiguration.SECURITY_TYPE_OWE)));
return wifiConfiguration;
}
@@ -259,7 +266,17 @@ public class WifiUriParser {
wifiConfiguration.wepKeys[0] = addQuotationIfNeeded(preSharedKey);
}
} else if (security.startsWith(SECURITY_WPA_PSK)) {
- wifiConfiguration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_PSK);
+ List<SecurityParams> securityParamsList = new ArrayList<>();
+ SecurityParams scannedSecurityParam = SecurityParams.createSecurityParamsBySecurityType(
+ WifiConfiguration.SECURITY_TYPE_PSK);
+ securityParamsList.add(scannedSecurityParam);
+ if (isTransitionDisabled) {
+ scannedSecurityParam.setEnabled(false);
+ securityParamsList.add(
+ SecurityParams.createSecurityParamsBySecurityType(
+ WifiConfiguration.SECURITY_TYPE_SAE));
+ }
+ wifiConfiguration.setSecurityParams(securityParamsList);
if (preSharedKey.matches("[0-9A-Fa-f]{64}")) {
wifiConfiguration.preSharedKey = preSharedKey;
@@ -271,6 +288,11 @@ public class WifiUriParser {
if (preSharedKey.length() != 0) {
wifiConfiguration.preSharedKey = addQuotationIfNeeded(preSharedKey);
}
+ } else if (security.startsWith(SECURITY_ADB)) {
+ Log.i(TAG, "Specific security key: ADB");
+ if (preSharedKey.length() != 0) {
+ wifiConfiguration.preSharedKey = addQuotationIfNeeded(preSharedKey);
+ }
} else {
throw new IllegalArgumentException("Unsupported security");
}
diff --git a/framework/java/android/net/wifi/p2p/IWifiP2pListener.aidl b/framework/java/android/net/wifi/p2p/IWifiP2pListener.aidl
index 4f9467101e..084050be42 100644
--- a/framework/java/android/net/wifi/p2p/IWifiP2pListener.aidl
+++ b/framework/java/android/net/wifi/p2p/IWifiP2pListener.aidl
@@ -28,15 +28,15 @@ import android.net.wifi.p2p.WifiP2pGroupList;
*/
oneway interface IWifiP2pListener
{
- void onStateChanged(boolean p2pEnabled);
- void onDiscoveryStateChanged(boolean started);
- void onListenStateChanged(boolean started);
+ void onP2pStateChanged(int state);
+ void onDiscoveryStateChanged(int state);
+ void onListenStateChanged(int state);
void onDeviceConfigurationChanged(in WifiP2pDevice p2pDevice);
void onPeerListChanged(in WifiP2pDeviceList p2pDeviceList);
void onPersistentGroupsChanged(in WifiP2pGroupList p2pGroupList);
void onGroupCreating();
void onGroupNegotiationRejectedByUser();
- void onGroupCreationFailed();
+ void onGroupCreationFailed(int reason);
void onGroupCreated(in WifiP2pInfo p2pInfo, in WifiP2pGroup p2pGroup);
void onPeerClientJoined(in WifiP2pInfo p2pInfo, in WifiP2pGroup p2pGroup);
void onPeerClientDisconnected(in WifiP2pInfo p2pInfo, in WifiP2pGroup p2pGroup);
diff --git a/framework/java/android/net/wifi/p2p/WifiP2pGroup.java b/framework/java/android/net/wifi/p2p/WifiP2pGroup.java
index fe9ad03e08..1edc97b422 100644
--- a/framework/java/android/net/wifi/p2p/WifiP2pGroup.java
+++ b/framework/java/android/net/wifi/p2p/WifiP2pGroup.java
@@ -284,9 +284,13 @@ public class WifiP2pGroup implements Parcelable {
/** @hide */
public void setClientInterfaceMacAddress(@NonNull String deviceAddress,
@NonNull final MacAddress interfaceMacAddress) {
+ if (null == interfaceMacAddress) {
+ Log.e("setClientInterfaceMacAddress", "cannot set null interface mac address");
+ return;
+ }
for (WifiP2pDevice client : mClients) {
if (client.deviceAddress.equals(deviceAddress)) {
- Log.i("setClientInterfaceMacAddress", " device: " + deviceAddress
+ Log.i("setClientInterfaceMacAddress", "device: " + deviceAddress
+ " interfaceAddress: " + interfaceMacAddress.toString());
client.setInterfaceMacAddress(interfaceMacAddress);
break;
@@ -296,8 +300,16 @@ public class WifiP2pGroup implements Parcelable {
/** @hide */
public void setClientIpAddress(@NonNull final MacAddress interfaceMacAddress,
@NonNull final InetAddress ipAddress) {
+ if (null == interfaceMacAddress) {
+ Log.e("setClientIpAddress", "cannot set IP address with null interface mac address");
+ return;
+ }
+ if (null == ipAddress) {
+ Log.e("setClientIpAddress", "Null IP - Failed to set IP address in WifiP2pDevice");
+ return;
+ }
for (WifiP2pDevice client : mClients) {
- if (client.getInterfaceMacAddress().equals(interfaceMacAddress)) {
+ if (interfaceMacAddress.equals(client.getInterfaceMacAddress())) {
Log.i("setClientIpAddress", "Update the IP address"
+ " device: " + client.deviceAddress + " interfaceAddress: "
+ interfaceMacAddress.toString() + " IP: " + ipAddress.getHostAddress());
diff --git a/framework/java/android/net/wifi/p2p/WifiP2pManager.java b/framework/java/android/net/wifi/p2p/WifiP2pManager.java
index 830d3f4643..0969060784 100644
--- a/framework/java/android/net/wifi/p2p/WifiP2pManager.java
+++ b/framework/java/android/net/wifi/p2p/WifiP2pManager.java
@@ -24,6 +24,7 @@ import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
+import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.annotation.SystemService;
import android.compat.annotation.UnsupportedAppUsage;
@@ -1262,10 +1263,12 @@ public class WifiP2pManager {
* @see #WIFI_P2P_STATE_CHANGED_ACTION
* @see #requestP2pState(Channel, P2pStateListener)
*
- * @param p2pEnabled indicates whether Wi-Fi p2p is enabled or disabled.
+ * @param state indicates whether Wi-Fi p2p is enabled or disabled.
+ * @see #WIFI_P2P_STATE_ENABLED
+ * @see #WIFI_P2P_STATE_DISABLED
*/
@FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
- default void onStateChanged(boolean p2pEnabled) {
+ default void onP2pStateChanged(@WifiP2pState int state) {
}
/**
@@ -1273,10 +1276,12 @@ public class WifiP2pManager {
* @see #WIFI_P2P_DISCOVERY_CHANGED_ACTION
* @see #requestDiscoveryState(Channel, DiscoveryStateListener)
*
- * @param started indicates whether discovery has started or stopped.
+ * @param state indicates whether discovery has started or stopped.
+ * @see #WIFI_P2P_DISCOVERY_STARTED
+ * @see #WIFI_P2P_DISCOVERY_STOPPED
*/
@FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
- default void onDiscoveryStateChanged(boolean started) {
+ default void onDiscoveryStateChanged(@WifiP2pDiscoveryState int state) {
}
/**
@@ -1284,10 +1289,12 @@ public class WifiP2pManager {
* @see #ACTION_WIFI_P2P_LISTEN_STATE_CHANGED
* @see #getListenState(Channel, Executor, Consumer)
*
- * @param started indicates whether listen has started or stopped.
+ * @param state indicates whether listen has started or stopped.
+ * @see #WIFI_P2P_LISTEN_STARTED
+ * @see #WIFI_P2P_LISTEN_STOPPED
*/
@FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
- default void onListenStateChanged(boolean started) {
+ default void onListenStateChanged(@WifiP2pListenState int state) {
}
/**
@@ -1343,9 +1350,11 @@ public class WifiP2pManager {
/**
* Called when group creation has failed.
+ *
+ * @param reason provides the group creation failure reason.
*/
@FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
- default void onGroupCreationFailed() {
+ default void onGroupCreationFailed(@GroupCreationFailureReason int reason) {
}
/**
@@ -1401,6 +1410,58 @@ public class WifiP2pManager {
}
/**
+ * P2p group creation failed because the connection has been cancelled.
+ * Used in {@link WifiP2pListener#onGroupCreationFailed(int reason)}.
+ */
+ @FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
+ public static final int GROUP_CREATION_FAILURE_REASON_CONNECTION_CANCELLED = 0;
+ /**
+ * P2p group creation failed because it has timed out.
+ * Used in {@link WifiP2pListener#onGroupCreationFailed(int reason)}.
+ */
+ @FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
+ public static final int GROUP_CREATION_FAILURE_REASON_TIMED_OUT = 1;
+ /**
+ * P2p group creation failed because user has rejected.
+ * Used in {@link WifiP2pListener#onGroupCreationFailed(int reason)}.
+ */
+ @FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
+ public static final int GROUP_CREATION_FAILURE_REASON_USER_REJECTED = 2;
+ /**
+ * P2p group creation failed because provision discovery has failed.
+ * Used in {@link WifiP2pListener#onGroupCreationFailed(int reason)}.
+ */
+ @FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
+ public static final int GROUP_CREATION_FAILURE_REASON_PROVISION_DISCOVERY_FAILED = 3;
+ /**
+ * P2p group creation failed because the group has been removed.
+ * Used in {@link WifiP2pListener#onGroupCreationFailed(int reason)}.
+ */
+ @FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
+ public static final int GROUP_CREATION_FAILURE_REASON_GROUP_REMOVED = 4;
+ /**
+ * P2p group creation failed because invitation has failed.
+ * Used in {@link WifiP2pListener#onGroupCreationFailed(int reason)}.
+ */
+ @FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
+ public static final int GROUP_CREATION_FAILURE_REASON_INVITATION_FAILED = 5;
+
+ /**
+ * @hide
+ */
+ @IntDef(prefix = {"GROUP_CREATION_FAILURE_REASON_"}, value = {
+ GROUP_CREATION_FAILURE_REASON_CONNECTION_CANCELLED,
+ GROUP_CREATION_FAILURE_REASON_TIMED_OUT,
+ GROUP_CREATION_FAILURE_REASON_USER_REJECTED,
+ GROUP_CREATION_FAILURE_REASON_PROVISION_DISCOVERY_FAILED,
+ GROUP_CREATION_FAILURE_REASON_GROUP_REMOVED,
+ GROUP_CREATION_FAILURE_REASON_INVITATION_FAILED
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface GroupCreationFailureReason {
+ }
+
+ /**
* Helper class to support wifi p2p listener.
*/
private static class OnWifiP2pListenerProxy extends IWifiP2pListener.Stub {
@@ -1418,21 +1479,21 @@ public class WifiP2pManager {
}
@Override
- public void onStateChanged(boolean p2pEnabled) {
+ public void onP2pStateChanged(@WifiP2pState int state) {
Binder.clearCallingIdentity();
- mExecutor.execute(() -> mListener.onStateChanged(p2pEnabled));
+ mExecutor.execute(() -> mListener.onP2pStateChanged(state));
}
@Override
- public void onDiscoveryStateChanged(boolean started) {
+ public void onDiscoveryStateChanged(@WifiP2pDiscoveryState int state) {
Binder.clearCallingIdentity();
- mExecutor.execute(() -> mListener.onDiscoveryStateChanged(started));
+ mExecutor.execute(() -> mListener.onDiscoveryStateChanged(state));
}
@Override
- public void onListenStateChanged(boolean started) {
+ public void onListenStateChanged(@WifiP2pListenState int state) {
Binder.clearCallingIdentity();
- mExecutor.execute(() -> mListener.onListenStateChanged(started));
+ mExecutor.execute(() -> mListener.onListenStateChanged(state));
}
@Override
@@ -1466,9 +1527,9 @@ public class WifiP2pManager {
}
@Override
- public void onGroupCreationFailed() {
+ public void onGroupCreationFailed(@GroupCreationFailureReason int reason) {
Binder.clearCallingIdentity();
- mExecutor.execute(() -> mListener.onGroupCreationFailed());
+ mExecutor.execute(() -> mListener.onGroupCreationFailed(reason));
}
@Override
@@ -2187,6 +2248,7 @@ public class WifiP2pManager {
android.Manifest.permission.ACCESS_FINE_LOCATION
}, conditional = true)
@FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
+ @SuppressLint("ExecutorRegistration") // WifiP2pManager is using the async channel
public void startPeerDiscovery(
@NonNull Channel channel,
@NonNull WifiP2pDiscoveryConfig config,
@@ -2443,6 +2505,7 @@ public class WifiP2pManager {
android.Manifest.permission.ACCESS_FINE_LOCATION
}, conditional = true)
@FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
+ @SuppressLint("ExecutorRegistration") // WifiP2pManager is using the async channel
public void startListening(
@NonNull Channel channel,
@NonNull WifiP2pExtListenParams params,
diff --git a/framework/java/android/net/wifi/rtt/ResponderLocation.java b/framework/java/android/net/wifi/rtt/ResponderLocation.java
index 42cc52d8d6..c77160cf45 100644
--- a/framework/java/android/net/wifi/rtt/ResponderLocation.java
+++ b/framework/java/android/net/wifi/rtt/ResponderLocation.java
@@ -671,9 +671,9 @@ public final class ResponderLocation implements Parcelable {
long zHeightUncertainty =
subelementZFields[SUBELEMENT_Z_HEIGHT_ABOVE_FLOOR_UNCERTAINTY_INDEX];
- if (zHeightUncertainty > 0 && zHeightUncertainty < Z_MAX_HEIGHT_UNCERTAINTY_FACTOR) {
- mHeightAboveFloorUncertaintyMeters =
- Math.pow(2, Z_FLOOR_HEIGHT_FRACTION_BITS - zHeightUncertainty - 1);
+ if (zHeightUncertainty >= 0 && zHeightUncertainty < Z_MAX_HEIGHT_UNCERTAINTY_FACTOR) {
+ mHeightAboveFloorUncertaintyMeters = zHeightUncertainty == 0
+ ? 0 : Math.pow(2, Z_FLOOR_HEIGHT_FRACTION_BITS - zHeightUncertainty - 1);
} else {
return false;
}
diff --git a/framework/java/android/net/wifi/twt/TwtSession.java b/framework/java/android/net/wifi/twt/TwtSession.java
index 639a5a024e..7c7f2a3127 100644
--- a/framework/java/android/net/wifi/twt/TwtSession.java
+++ b/framework/java/android/net/wifi/twt/TwtSession.java
@@ -37,7 +37,7 @@ import java.util.function.Consumer;
*/
@SystemApi
@FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
-public interface TwtSession extends AutoCloseable {
+public interface TwtSession {
/**
* Bundle key to get average number of received packets in each wake duration
*/
@@ -116,12 +116,11 @@ public interface TwtSession extends AutoCloseable {
@NonNull Consumer<Bundle> resultCallback);
/**
- * Close the session relinquishing any underlying resources. See
- * {@link TwtSessionCallback#onTeardown(int)} and {@link TwtSessionCallback#onFailure(int)}.
+ * Teardown the session. See {@link TwtSessionCallback#onTeardown(int)}. Also closes this
+ * session, relinquishing any underlying resources.
*
- * Note: Only the owner of the session can close it.
+ * @throws SecurityException if the caller does not have permission.
*/
@FlaggedApi(Flags.FLAG_ANDROID_V_WIFI_API)
- @Override
- void close();
+ void teardown();
}
diff --git a/framework/java/android/net/wifi/util/WifiResourceCache.java b/framework/java/android/net/wifi/util/WifiResourceCache.java
new file mode 100644
index 0000000000..89d7cb964a
--- /dev/null
+++ b/framework/java/android/net/wifi/util/WifiResourceCache.java
@@ -0,0 +1,115 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi.util;
+
+import android.content.Context;
+
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * A class to cache the Wifi resource value and provide override mechanism from shell
+ * @hide
+ */
+public class WifiResourceCache {
+ private final Context mContext;
+
+ private final Map<String, Boolean> mBooleanResourceMap;
+ private final Map<String, Integer> mIntegerResourceMap;
+
+ public WifiResourceCache(Context context) {
+ mContext = context;
+ mBooleanResourceMap = new HashMap<>();
+ mIntegerResourceMap = new HashMap<>();
+ }
+
+ /**
+ * Get and cache the boolean value as {@link android.content.res.Resources#getBoolean(int)}
+ */
+ public boolean getBoolean(int resourceId, String resourceName) {
+ return mBooleanResourceMap.computeIfAbsent(resourceName,
+ v -> mContext.getResources().getBoolean(resourceId));
+ }
+
+ /**
+ * Get and cache the integer value as {@link android.content.res.Resources#getInteger(int)}
+ */
+ public int getInteger(int resourceId, String resourceName) {
+ return mIntegerResourceMap.computeIfAbsent(resourceName,
+ v -> mContext.getResources().getInteger(resourceId));
+ }
+
+ /**
+ * Override the target boolean value
+ *
+ * @param resourceName the resource overlay name
+ * @param value override to this value
+ */
+ public void overrideBooleanValue(String resourceName, boolean value) {
+ mBooleanResourceMap.put(resourceName, value);
+ }
+
+ /**
+ * Override the target boolean value
+ */
+ public void restoreBooleanValue(String resourceName) {
+ mBooleanResourceMap.remove(resourceName);
+ }
+
+ /**
+ * Override the target integer value
+ * @param resourceName the resource overlay name
+ * @param value override to this value
+ */
+ public void overrideIntegerValue(String resourceName, int value) {
+ mIntegerResourceMap.put(resourceName, value);
+ }
+
+ /**
+ * Override the target integer value
+ */
+ public void restoreIntegerValue(String resourceName) {
+ mIntegerResourceMap.remove(resourceName);
+ }
+
+ /**
+ * Dump of current resource value
+ */
+ public void dump(PrintWriter pw) {
+ pw.println("Dump of WifiResourceCache");
+ pw.println("WifiResourceCache - resource value Begin ----");
+
+ for (Map.Entry<String, Integer> resourceEntry : mIntegerResourceMap.entrySet()) {
+ pw.println("Resource Name: " + resourceEntry.getKey()
+ + ", value: " + resourceEntry.getValue());
+ }
+ for (Map.Entry<String, Boolean> resourceEntry : mBooleanResourceMap.entrySet()) {
+ pw.println("Resource Name: " + resourceEntry.getKey()
+ + ", value: " + resourceEntry.getValue());
+ }
+ pw.println("WifiResourceCache - resource value End ----");
+ }
+
+ /**
+ * Remove all override value and set to default
+ */
+ public void reset() {
+ mBooleanResourceMap.clear();
+ mIntegerResourceMap.clear();
+ }
+}
diff --git a/framework/tests/src/android/net/wifi/WifiUriParserTest.java b/framework/tests/src/android/net/wifi/WifiUriParserTest.java
index c38974bb59..396c677676 100644
--- a/framework/tests/src/android/net/wifi/WifiUriParserTest.java
+++ b/framework/tests/src/android/net/wifi/WifiUriParserTest.java
@@ -29,6 +29,7 @@ import com.google.common.collect.ImmutableList;
import org.junit.Test;
+import java.util.Collections;
import java.util.List;
/** Unit tests for {@link com.android.server.wifi.WifiUriParser}. */
@@ -44,7 +45,6 @@ public class WifiUriParserTest {
private void verifyZxParsing(
UriParserResults uri,
String expectedSSID,
- int expectedAuthType,
List<SecurityParams> expectedSecurityParamsList,
String expectedPreShareKey,
boolean isWep) {
@@ -52,7 +52,6 @@ public class WifiUriParserTest {
WifiConfiguration config = uri.getWifiConfiguration();
assertNotNull(config);
assertThat(config.SSID).isEqualTo(expectedSSID);
- assertThat(config.getAuthType()).isEqualTo(expectedAuthType);
if (isWep) {
assertThat(config.wepKeys[0]).isEqualTo(expectedPreShareKey);
} else {
@@ -78,7 +77,6 @@ public class WifiUriParserTest {
verifyZxParsing(
uri,
"\"testAbC\"",
- WifiConfiguration.KeyMgmt.NONE,
expectedSecurityParamsList,
null,
false);
@@ -87,7 +85,6 @@ public class WifiUriParserTest {
verifyZxParsing(
uri,
"\"testAbC\"",
- WifiConfiguration.KeyMgmt.NONE,
expectedSecurityParamsList,
null,
false);
@@ -101,7 +98,6 @@ public class WifiUriParserTest {
verifyZxParsing(
uri,
"\"reallyLONGone\"",
- WifiConfiguration.KeyMgmt.NONE,
expectedSecurityParamsList,
"\"somepasswo#%^**123rd\"",
true);
@@ -110,7 +106,6 @@ public class WifiUriParserTest {
verifyZxParsing(
uri,
"\"reallyLONGone\"",
- WifiConfiguration.KeyMgmt.NONE,
expectedSecurityParamsList,
"\"somepassword\"",
true);
@@ -124,7 +119,6 @@ public class WifiUriParserTest {
verifyZxParsing(
uri,
"\"anotherone\"",
- WifiConfiguration.KeyMgmt.WPA_PSK,
expectedSecurityParamsList,
"\"3#=3j9asicla\"",
false);
@@ -133,7 +127,6 @@ public class WifiUriParserTest {
verifyZxParsing(
uri,
"\"anotherone\"",
- WifiConfiguration.KeyMgmt.WPA_PSK,
expectedSecurityParamsList,
"\"abcdefghihklmn\"",
false);
@@ -147,7 +140,6 @@ public class WifiUriParserTest {
verifyZxParsing(
uri,
"\"xx\"",
- WifiConfiguration.KeyMgmt.SAE,
expectedSecurityParamsList,
"\"a\"",
false);
@@ -156,10 +148,44 @@ public class WifiUriParserTest {
verifyZxParsing(
uri,
"\"xx\"",
- WifiConfiguration.KeyMgmt.SAE,
expectedSecurityParamsList,
"\"a\"",
false);
+ // Test ADB
+ uri = WifiUriParser.parseUri("WIFI:T:ADB;S:myname;P:mypass;;");
+ verifyZxParsing(
+ uri,
+ "\"myname\"",
+ Collections.emptyList(),
+ "\"mypass\"",
+ false);
+ // Test transition disable value
+ expectedSecurityParamsList =
+ ImmutableList.of(
+ SecurityParams.createSecurityParamsBySecurityType(
+ WifiConfiguration.SECURITY_TYPE_PSK));
+ uri = WifiUriParser.parseUri("WIFI:S:anotherone;T:WPA;R:0;P:3#=3j9asicla");
+ verifyZxParsing(
+ uri,
+ "\"anotherone\"",
+ expectedSecurityParamsList,
+ "\"3#=3j9asicla\"",
+ false);
+
+ SecurityParams pskButDisableed = SecurityParams.createSecurityParamsBySecurityType(
+ WifiConfiguration.SECURITY_TYPE_PSK);
+ pskButDisableed.setEnabled(false);
+ expectedSecurityParamsList =
+ ImmutableList.of(pskButDisableed,
+ SecurityParams.createSecurityParamsBySecurityType(
+ WifiConfiguration.SECURITY_TYPE_SAE));
+ uri = WifiUriParser.parseUri("WIFI:S:anotherone;T:WPA;R:1;P:3#=3j9asicla");
+ verifyZxParsing(
+ uri,
+ "\"anotherone\"",
+ expectedSecurityParamsList,
+ "\"3#=3j9asicla\"",
+ false);
}
@Test
diff --git a/framework/tests/src/android/net/wifi/rtt/ResponderLocationTest.java b/framework/tests/src/android/net/wifi/rtt/ResponderLocationTest.java
index f9f25ab002..5d257c9d46 100644
--- a/framework/tests/src/android/net/wifi/rtt/ResponderLocationTest.java
+++ b/framework/tests/src/android/net/wifi/rtt/ResponderLocationTest.java
@@ -16,6 +16,10 @@
package android.net.wifi.rtt;
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
+import static junit.framework.Assert.assertTrue;
+
import android.location.Address;
import android.location.Location;
import android.net.MacAddress;
@@ -23,10 +27,6 @@ import android.os.Parcel;
import android.util.SparseArray;
import android.webkit.MimeTypeMap;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertFalse;
-import static junit.framework.Assert.assertTrue;
-
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@@ -87,6 +87,17 @@ public class ResponderLocationTest {
(byte) 0x0e, // STA Height Uncertainty
};
+ private static final byte[] sTestZHeightSEUncertaintyUnset = {
+ (byte) 0x04, // Subelement Z
+ (byte) 6, // Length always 6
+ (byte) 0x00, // LSB STA Floor Info (2 bytes)
+ (byte) 0x01, // MSB
+ (byte) 0xcd, // LSB Height(m) (3 bytes)
+ (byte) 0x2c,
+ (byte) 0x00, // MSB Height(m)
+ (byte) 0x00, // STA Height Uncertainty
+ };
+
private static final byte[] sTestUsageSE1 = {
(byte) 0x06, // Subelement Usage Rights
(byte) 1, // Length 1 (with no retention limit)
@@ -403,6 +414,32 @@ public class ResponderLocationTest {
}
/**
+ * Test for a valid Z (Height) subelement with unset uncertainty following an LCI subelement.
+ */
+ @Test
+ public void testLciValidZBufferSEAfterLciWithUnsetUncertainty() {
+ byte[] testBufferTmp = concatenateArrays(sTestLciIeHeader, sTestLciSE);
+ byte[] testBuffer = concatenateArrays(testBufferTmp, sTestZHeightSEUncertaintyUnset);
+ ResponderLocation responderLocation =
+ new ResponderLocation(testBuffer, sTestLcrBufferHeader);
+
+ boolean isValid = responderLocation.isValid();
+ boolean isZValid = responderLocation.isZaxisSubelementValid();
+ boolean isLciValid = responderLocation.isLciSubelementValid();
+ double staFloorNumber = responderLocation.getFloorNumber();
+ double staHeightAboveFloorMeters = responderLocation.getHeightAboveFloorMeters();
+ double staHeightAboveFloorUncertaintyMeters =
+ responderLocation.getHeightAboveFloorUncertaintyMeters();
+
+ assertTrue(isValid);
+ assertTrue(isZValid);
+ assertTrue(isLciValid);
+ assertEquals(4.0, staFloorNumber);
+ assertEquals(2.8, staHeightAboveFloorMeters, HEIGHT_TOLERANCE_METERS);
+ assertEquals(0.0, staHeightAboveFloorUncertaintyMeters);
+ }
+
+ /**
* Test for a valid Usage Policy that is unrestrictive
*/
@Test
diff --git a/framework/tests/src/android/net/wifi/util/WifiResourceCacheTest.java b/framework/tests/src/android/net/wifi/util/WifiResourceCacheTest.java
new file mode 100644
index 0000000000..54f9add266
--- /dev/null
+++ b/framework/tests/src/android/net/wifi/util/WifiResourceCacheTest.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.wifi.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.res.Resources;
+import android.net.wifi.WifiContext;
+
+import androidx.test.filters.SmallTest;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@SmallTest
+public class WifiResourceCacheTest {
+ private static final int TEST_ID = 12345;
+ private static final String TEST_NAME = "test_name";
+ private static final int VALUE_1 = 10;
+ private static final int VALUE_2 = 20;
+ @Mock WifiContext mWifiContext;
+ @Mock Resources mResources;
+ private WifiResourceCache mWifiResourceCache;
+ @Before
+ public void setup() {
+ MockitoAnnotations.initMocks(this);
+ when(mWifiContext.getResources()).thenReturn(mResources);
+ mWifiResourceCache = new WifiResourceCache(mWifiContext);
+ }
+
+ @Test
+ public void testGetBooleanResource() {
+ when(mResources.getBoolean(TEST_ID)).thenReturn(true);
+ assertTrue(mWifiResourceCache.getBoolean(TEST_ID, TEST_NAME));
+ assertTrue(mWifiResourceCache.getBoolean(TEST_ID, TEST_NAME));
+ verify(mResources).getBoolean(TEST_ID);
+ }
+
+ @Test
+ public void testGetIntegerResource() {
+ when(mResources.getInteger(TEST_ID)).thenReturn(VALUE_1);
+ assertEquals(VALUE_1, mWifiResourceCache.getInteger(TEST_ID, TEST_NAME));
+ assertEquals(VALUE_1, mWifiResourceCache.getInteger(TEST_ID, TEST_NAME));
+ verify(mResources).getInteger(TEST_ID);
+ }
+
+ @Test
+ public void testOverrideBooleanResource() {
+ when(mResources.getBoolean(TEST_ID)).thenReturn(true);
+ assertTrue(mWifiResourceCache.getBoolean(TEST_ID, TEST_NAME));
+ mWifiResourceCache.overrideBooleanValue(TEST_NAME, false);
+ assertFalse(mWifiResourceCache.getBoolean(TEST_ID, TEST_NAME));
+ mWifiResourceCache.restoreBooleanValue(TEST_NAME);
+ assertTrue(mWifiResourceCache.getBoolean(TEST_ID, TEST_NAME));
+ verify(mResources, times(2)).getBoolean(TEST_ID);
+ }
+
+ @Test
+ public void testOverrideIntegerResource() {
+ when(mResources.getInteger(TEST_ID)).thenReturn(VALUE_1);
+ assertEquals(VALUE_1, mWifiResourceCache.getInteger(TEST_ID, TEST_NAME));
+ mWifiResourceCache.overrideIntegerValue(TEST_NAME, VALUE_2);
+ assertEquals(VALUE_2, mWifiResourceCache.getInteger(TEST_ID, TEST_NAME));
+ mWifiResourceCache.restoreIntegerValue(TEST_NAME);
+ assertEquals(VALUE_1, mWifiResourceCache.getInteger(TEST_ID, TEST_NAME));
+ verify(mResources, times(2)).getInteger(TEST_ID);
+ }
+
+ @Test
+ public void testReset() {
+ when(mResources.getBoolean(TEST_ID)).thenReturn(true);
+ when(mResources.getInteger(TEST_ID)).thenReturn(VALUE_1);
+ assertTrue(mWifiResourceCache.getBoolean(TEST_ID, TEST_NAME));
+ assertEquals(VALUE_1, mWifiResourceCache.getInteger(TEST_ID, TEST_NAME));
+ mWifiResourceCache.overrideBooleanValue(TEST_NAME, false);
+ mWifiResourceCache.overrideIntegerValue(TEST_NAME, VALUE_2);
+ assertEquals(VALUE_2, mWifiResourceCache.getInteger(TEST_ID, TEST_NAME));
+ assertFalse(mWifiResourceCache.getBoolean(TEST_ID, TEST_NAME));
+ mWifiResourceCache.reset();
+ assertTrue(mWifiResourceCache.getBoolean(TEST_ID, TEST_NAME));
+ assertEquals(VALUE_1, mWifiResourceCache.getInteger(TEST_ID, TEST_NAME));
+ verify(mResources, times(2)).getBoolean(TEST_ID);
+ verify(mResources, times(2)).getInteger(TEST_ID);
+ }
+}
diff --git a/service/ServiceWifiResources/res/drawable/stat_notify_wifi_in_range.xml b/service/ServiceWifiResources/res/drawable/stat_notify_wifi_in_range.xml
index a271ca5224..1c143eec90 100644
--- a/service/ServiceWifiResources/res/drawable/stat_notify_wifi_in_range.xml
+++ b/service/ServiceWifiResources/res/drawable/stat_notify_wifi_in_range.xml
@@ -14,6 +14,7 @@ Copyright (C) 2014 The Android Open Source Project
limitations under the License.
-->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
+ android:autoMirrored="true"
android:width="26.0dp"
android:height="24.0dp"
android:viewportWidth="26.0"
diff --git a/service/ServiceWifiResources/res/values-es-rUS/strings.xml b/service/ServiceWifiResources/res/values-es-rUS/strings.xml
index 200eb24cba..72f5b3ec61 100644
--- a/service/ServiceWifiResources/res/values-es-rUS/strings.xml
+++ b/service/ServiceWifiResources/res/values-es-rUS/strings.xml
@@ -126,8 +126,8 @@
<string name="wifi_interface_priority_approve" msgid="7877379614986261096">"Permitir"</string>
<string name="wifi_interface_priority_reject" msgid="1378461018835886777">"No permitir"</string>
<string name="wifi_interface_priority_interface_name_sta" msgid="5107477901500010776">"STA"</string>
- <string name="wifi_interface_priority_interface_name_ap" msgid="161777054136866061">"Hotspot Wi-Fi"</string>
- <string name="wifi_interface_priority_interface_name_ap_bridge" msgid="1270364818879977821">"Hotspot Wi-Fi"</string>
+ <string name="wifi_interface_priority_interface_name_ap" msgid="161777054136866061">"Hotspot de Wi-Fi"</string>
+ <string name="wifi_interface_priority_interface_name_ap_bridge" msgid="1270364818879977821">"Hotspot de Wi-Fi"</string>
<string name="wifi_interface_priority_interface_name_p2p" msgid="1278122698099149708">"Wi-Fi directo"</string>
<string name="wifi_interface_priority_interface_name_nan" msgid="8812888073122966870">"Reconocimiento de Wi-Fi"</string>
<string name="wifi_ca_cert_dialog_title" msgid="3872340345882915806">"¿Es una red segura?"</string>
@@ -152,7 +152,7 @@
<string name="wifi_ca_cert_dialog_preT_message_hint" msgid="5682518783200852031">"A la red <xliff:g id="SSID">%1$s</xliff:g> le falta un certificado."</string>
<string name="wifi_ca_cert_dialog_preT_message_link" msgid="6325483132538546884">"Obtén más información para agregar certificados"</string>
<string name="wifi_ca_cert_notification_preT_title" msgid="7255129934648316663">"No se pudo verificar esta red"</string>
- <string name="wifi_ca_cert_notification_preT_message" msgid="4565553176090475724">"A la red <xliff:g id="SSID">%1$s</xliff:g> le falta un certificado. Presiona a fin de obtener más información para agregar certificados."</string>
+ <string name="wifi_ca_cert_notification_preT_message" msgid="4565553176090475724">"A la red <xliff:g id="SSID">%1$s</xliff:g> le falta un certificado. Presiona para obtener más información sobre cómo agregar certificados."</string>
<string name="wifi_ca_cert_notification_preT_continue_text" msgid="1525418430746943670">"Conectar de todos modos"</string>
<string name="wifi_ca_cert_notification_preT_abort_text" msgid="8307996031461071854">"No conectar"</string>
<string name="wifi_enable_request_dialog_title" msgid="3577459145316177148">"¿Deseas permitir que <xliff:g id="APP_NAME">%1$s</xliff:g> desactive el Wi‑Fi?"</string>
diff --git a/service/ServiceWifiResources/res/values-fa/strings.xml b/service/ServiceWifiResources/res/values-fa/strings.xml
index c1012ffb3f..c11fd9820f 100644
--- a/service/ServiceWifiResources/res/values-fa/strings.xml
+++ b/service/ServiceWifiResources/res/values-fa/strings.xml
@@ -21,7 +21,7 @@
<string name="wifi_available_title_connecting" msgid="7233590022728579868">"‏درحال اتصال به شبکه Wi‑Fi..."</string>
<string name="wifi_available_title_connected" msgid="6329493859989844201">"‏به شبکه Wi‑Fi متصل شد"</string>
<string name="wifi_available_title_failed_to_connect" msgid="4840833680513368639">"‏به شبکه Wi-Fi متصل نشد"</string>
- <string name="wifi_available_content_failed_to_connect" msgid="4330035988269701861">"برای دیدن همه شبکه‌ها ضربه بزنید"</string>
+ <string name="wifi_available_content_failed_to_connect" msgid="4330035988269701861">"برای دیدن همه شبکه‌ها تک‌ضرب بزنید"</string>
<string name="wifi_available_action_connect" msgid="5636634933476946222">"اتصال"</string>
<string name="wifi_available_action_all_networks" msgid="8491109932336522211">"همه شبکه‌ها"</string>
<string name="notification_channel_network_status" msgid="1631786866932924838">"وضعیت شبکه"</string>
@@ -63,7 +63,7 @@
<string name="wifi_p2p_frequency_conflict_message" msgid="8535404941723941766">"‏وقتی دستگاهتان به <xliff:g id="DEVICE_NAME">%1$s</xliff:g> متصل است، اتصال آن به Wi-Fi موقتاً قطع می‌شود"</string>
<string name="dlg_ok" msgid="254496739491689405">"تأیید"</string>
<string name="wifi_cannot_connect_with_randomized_mac_title" msgid="2344570489693915253">"اتصال به <xliff:g id="SSID">%1$s</xliff:g> امکان‌پذیر نیست"</string>
- <string name="wifi_cannot_connect_with_randomized_mac_message" msgid="4834133226521813352">"برای تغییر تنظیم حریم خصوصی ضربه بزنید و دوباره امتحان کنید"</string>
+ <string name="wifi_cannot_connect_with_randomized_mac_message" msgid="4834133226521813352">"برای تغییر تنظیم حریم خصوصی تک‌ضرب بزنید و دوباره امتحان کنید"</string>
<string name="wifi_disable_mac_randomization_dialog_title" msgid="2054540994993681606">"تنظیم حریم خصوصی تغییر کند؟"</string>
<string name="wifi_disable_mac_randomization_dialog_message" msgid="8874064864332248988">"برای اتصال، <xliff:g id="SSID">%1$s</xliff:g> باید از «مک آدرس» دستگاهتان که شناسه‌ای منحصربه‌فرد است استفاده کند. درحال‌حاضر، تنظیم حریم خصوصی شما برای این شبکه از شناسه تصادفی استفاده می‌کند. \n\nاین تغییر ممکن است به دستگاه‌های اطراف امکان دهد مکان دستگاهتان را ردیابی کنند."</string>
<string name="wifi_disable_mac_randomization_dialog_confirm_text" msgid="6954419863076751626">"تغییر تنظیم"</string>
@@ -117,7 +117,7 @@
<item msgid="2705387186478280792">"‏<xliff:g id="CARRIER_ID_PREFIX">:::1839:::</xliff:g><xliff:g id="SSID">%1$s</xliff:g> : هنگام اتصال به Verizon Wi-Fi مشکلی وجود دارد. (خطا = نامشخص)"</item>
</string-array>
<string name="wifi_softap_auto_shutdown_timeout_expired_title" msgid="4896534374569504484">"نقطه اتصال خاموش شد"</string>
- <string name="wifi_softap_auto_shutdown_timeout_expired_summary" msgid="7975476698140267728">"هیچ دستگاهی متصل نیست. برای اصلاح ضربه بزنید."</string>
+ <string name="wifi_softap_auto_shutdown_timeout_expired_summary" msgid="7975476698140267728">"هیچ دستگاهی متصل نیست. برای اصلاح تک‌ضرب بزنید."</string>
<string name="wifi_sim_required_title" msgid="2262227800991155459">"‏Wi-Fi قطع شد."</string>
<string name="wifi_sim_required_message" msgid="284812212346125745">"برای متصل شدن به <xliff:g id="SSID">%1$s</xliff:g>، یک سیم‌کارت <xliff:g id="CARRIER_NAME">%2$s</xliff:g> در دستگاه قرار دهید"</string>
<string name="wifi_interface_priority_title" msgid="5117627874976875544">"<xliff:g id="APP">%1$s</xliff:g> می‌خواهد از منبع شبکه‌ای استفاده کند"</string>
@@ -141,7 +141,7 @@
<string name="wifi_ca_cert_dialog_message_signature_name_text" msgid="8455163626514894233">"‏اثر انگشت SHA-256:\n<xliff:g id="VALUE">%1$s</xliff:g>\n\n"</string>
<string name="wifi_ca_cert_dialog_message_contact_text" msgid="5799083318641183815">"تماس:\n<xliff:g id="VALUE">%1$s</xliff:g>\n\n"</string>
<string name="wifi_ca_cert_notification_title" msgid="537569884930429796">"شبکه باید تأیید شود"</string>
- <string name="wifi_ca_cert_notification_message" msgid="6413248690626616961">"قبل‌از متصل شدن، جزئیات شبکه را برای <xliff:g id="SSID">%1$s</xliff:g> مرور کنید. برای ادامه، ضربه بزنید."</string>
+ <string name="wifi_ca_cert_notification_message" msgid="6413248690626616961">"قبل‌از متصل شدن، جزئیات شبکه را برای <xliff:g id="SSID">%1$s</xliff:g> مرور کنید. برای ادامه، تک‌ضرب بزنید."</string>
<string name="wifi_ca_cert_failed_to_install_ca_cert" msgid="4864192219789736195">"گواهینامه نصب نشد."</string>
<string name="wifi_tofu_invalid_cert_chain_title" msgid="332710627417595752">"اتصال به <xliff:g id="VALUE">%1$s</xliff:g> ممکن نیست"</string>
<string name="wifi_tofu_invalid_cert_chain_message" msgid="7047987920029432392">"زنجیره گواهینامه سرور نامعتبر است."</string>
@@ -152,7 +152,7 @@
<string name="wifi_ca_cert_dialog_preT_message_hint" msgid="5682518783200852031">"شبکه <xliff:g id="SSID">%1$s</xliff:g> فاقد گواهینامه است."</string>
<string name="wifi_ca_cert_dialog_preT_message_link" msgid="6325483132538546884">"با نحوه افزودن گواهینامه‌ها آشنا شوید"</string>
<string name="wifi_ca_cert_notification_preT_title" msgid="7255129934648316663">"تأیید این شبکه ممکن نیست"</string>
- <string name="wifi_ca_cert_notification_preT_message" msgid="4565553176090475724">"شبکه <xliff:g id="SSID">%1$s</xliff:g> فاقد گواهینامه است. برای آشنایی با نحوه افزودن گواهینامه، ضربه بزنید."</string>
+ <string name="wifi_ca_cert_notification_preT_message" msgid="4565553176090475724">"شبکه <xliff:g id="SSID">%1$s</xliff:g> فاقد گواهینامه است. برای آشنایی با نحوه افزودن گواهینامه، تک‌ضرب بزنید."</string>
<string name="wifi_ca_cert_notification_preT_continue_text" msgid="1525418430746943670">"درهرصورت متصل شود"</string>
<string name="wifi_ca_cert_notification_preT_abort_text" msgid="8307996031461071854">"متصل نشود"</string>
<string name="wifi_enable_request_dialog_title" msgid="3577459145316177148">"‏به <xliff:g id="APP_NAME">%1$s</xliff:g> اجازه می‌دهید Wi‑Fi را روشن کند؟"</string>
diff --git a/service/ServiceWifiResources/res/values-fr-feminine/strings.xml b/service/ServiceWifiResources/res/values-fr-feminine/strings.xml
new file mode 100644
index 0000000000..bc890db014
--- /dev/null
+++ b/service/ServiceWifiResources/res/values-fr-feminine/strings.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string-array name="wifi_eap_error_message_code_32763_carrier_overrides">
+ <item msgid="591026649262091217">"<xliff:g id="CARRIER_ID_PREFIX">:::1839:::</xliff:g> <xliff:g id="SSID">%1$s</xliff:g> : vous êtes déjà connectée à Verizon Wi-Fi Access. (Erreur 32763)"</item>
+ </string-array>
+</resources>
diff --git a/service/ServiceWifiResources/res/values-fr-masculine/strings.xml b/service/ServiceWifiResources/res/values-fr-masculine/strings.xml
new file mode 100644
index 0000000000..9ed7470594
--- /dev/null
+++ b/service/ServiceWifiResources/res/values-fr-masculine/strings.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string-array name="wifi_eap_error_message_code_32763_carrier_overrides">
+ <item msgid="591026649262091217">"<xliff:g id="CARRIER_ID_PREFIX">:::1839:::</xliff:g> <xliff:g id="SSID">%1$s</xliff:g> : vous êtes déjà connecté à Verizon Wi-Fi Access. (Erreur 32763)"</item>
+ </string-array>
+</resources>
diff --git a/service/ServiceWifiResources/res/values-fr-neuter/strings.xml b/service/ServiceWifiResources/res/values-fr-neuter/strings.xml
new file mode 100644
index 0000000000..025a654e2d
--- /dev/null
+++ b/service/ServiceWifiResources/res/values-fr-neuter/strings.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- Copyright (C) 2019 The Android Open Source Project
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+
+<resources xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string-array name="wifi_eap_error_message_code_32763_carrier_overrides">
+ <item msgid="591026649262091217">"<xliff:g id="CARRIER_ID_PREFIX">:::1839:::</xliff:g> <xliff:g id="SSID">%1$s</xliff:g> : vous êtes déjà connecté·e à Verizon Wi-Fi Access. (Erreur 32763)"</item>
+ </string-array>
+</resources>
diff --git a/service/ServiceWifiResources/res/values-fr-rCA/strings.xml b/service/ServiceWifiResources/res/values-fr-rCA/strings.xml
index ff9cceaf2b..30c082acf1 100644
--- a/service/ServiceWifiResources/res/values-fr-rCA/strings.xml
+++ b/service/ServiceWifiResources/res/values-fr-rCA/strings.xml
@@ -48,8 +48,8 @@
<string name="wifi_watchdog_network_disabled" msgid="5769226742956006362">"Impossible de se connecter au Wi-Fi."</string>
<string name="wifi_watchdog_network_disabled_detailed" msgid="1725243835135539125">" dispose d\'une connexion Internet faible."</string>
<string name="wifi_connect_alert_title" msgid="2368200646665663612">"Autoriser la connexion?"</string>
- <string name="wifi_connect_alert_message" msgid="7226456300982080746">"L\'application %1$s souhaite se connecter au réseau Wi-Fi %2$s."</string>
- <string name="wifi_connect_default_application" msgid="8917703737222707062">"Une application"</string>
+ <string name="wifi_connect_alert_message" msgid="7226456300982080746">"L\'appli %1$s souhaite se connecter au réseau Wi-Fi %2$s."</string>
+ <string name="wifi_connect_default_application" msgid="8917703737222707062">"Une appli"</string>
<string name="accept" msgid="8346431649376483879">"Accepter"</string>
<string name="decline" msgid="4172251727603762084">"Refuser"</string>
<string name="ok" msgid="847575529546290102">"OK"</string>
@@ -86,7 +86,7 @@
</string-array>
<string name="wifi_eap_error_message_code_32763" msgid="4467733260757049969">"<xliff:g id="SSID">%1$s</xliff:g> : erreur d\'authentification EAP 32763"</string>
<string-array name="wifi_eap_error_message_code_32763_carrier_overrides">
- <item msgid="591026649262091217">"<xliff:g id="CARRIER_ID_PREFIX">:::1839:::</xliff:g><xliff:g id="SSID">%1$s</xliff:g> : vous êtes déjà connecté à Verizon Wi-Fi Access. (erreur =  32763)"</item>
+ <item msgid="591026649262091217">"<xliff:g id="CARRIER_ID_PREFIX">:::1839:::</xliff:g><xliff:g id="SSID">%1$s</xliff:g> : votre connexion à Verizon Wi-Fi Access est déjà établie. (Erreur = 32763)"</item>
</string-array>
<string name="wifi_eap_error_message_code_32764" msgid="7349538467012877101">"<xliff:g id="SSID">%1$s</xliff:g> : erreur d\'authentification EAP 32764"</string>
<string-array name="wifi_eap_error_message_code_32764_carrier_overrides">
@@ -122,7 +122,7 @@
<string name="wifi_sim_required_message" msgid="284812212346125745">"Pour vous connecter à <xliff:g id="SSID">%1$s</xliff:g>, insérez une carte SIM de <xliff:g id="CARRIER_NAME">%2$s</xliff:g>"</string>
<string name="wifi_interface_priority_title" msgid="5117627874976875544">"<xliff:g id="APP">%1$s</xliff:g> souhaite utiliser une ressource de réseautage"</string>
<string name="wifi_interface_priority_message" msgid="4253391172756140313">"Cela peut causer des problèmes pour <xliff:g id="APPS">%3$s</xliff:g>."</string>
- <string name="wifi_interface_priority_message_plural" msgid="8178086373318831859">"Cela peut entraîner des problèmes pour ces applications : <xliff:g id="APPS">%3$s</xliff:g>."</string>
+ <string name="wifi_interface_priority_message_plural" msgid="8178086373318831859">"Cela peut entraîner des problèmes pour ces applis : <xliff:g id="APPS">%3$s</xliff:g>."</string>
<string name="wifi_interface_priority_approve" msgid="7877379614986261096">"Autoriser"</string>
<string name="wifi_interface_priority_reject" msgid="1378461018835886777">"Ne pas autoriser"</string>
<string name="wifi_interface_priority_interface_name_sta" msgid="5107477901500010776">"STA"</string>
diff --git a/service/ServiceWifiResources/res/values-it/strings.xml b/service/ServiceWifiResources/res/values-it/strings.xml
index d029f4e01c..2ce762d241 100644
--- a/service/ServiceWifiResources/res/values-it/strings.xml
+++ b/service/ServiceWifiResources/res/values-it/strings.xml
@@ -55,7 +55,7 @@
<string name="ok" msgid="847575529546290102">"OK"</string>
<string name="wifi_p2p_invitation_sent_title" msgid="6552639940428040869">"Invito inviato"</string>
<string name="wifi_p2p_invitation_to_connect_title" msgid="8917157937652519251">"Invito a connettersi"</string>
- <string name="wifi_p2p_invitation_seconds_remaining" msgid="4214101104506918344">"{0,plural, =1{Accetta entro # secondo.}many{Accetta entro # secondi.}other{Accetta entro # secondi.}}"</string>
+ <string name="wifi_p2p_invitation_seconds_remaining" msgid="4214101104506918344">"{0,plural, =1{Accetta entro # secondo.}many{Accetta entro # di secondi.}other{Accetta entro # secondi.}}"</string>
<string name="wifi_p2p_from_message" msgid="5921308150192756898">"Da:"</string>
<string name="wifi_p2p_to_message" msgid="3809923305696994787">"A:"</string>
<string name="wifi_p2p_enter_pin_message" msgid="5200220251738047620">"Inserisci il PIN richiesto:"</string>
diff --git a/service/ServiceWifiResources/res/values-iw/strings.xml b/service/ServiceWifiResources/res/values-iw/strings.xml
index 3bd7d33c0f..df298ff6a4 100644
--- a/service/ServiceWifiResources/res/values-iw/strings.xml
+++ b/service/ServiceWifiResources/res/values-iw/strings.xml
@@ -56,7 +56,7 @@
<string name="wifi_p2p_invitation_sent_title" msgid="6552639940428040869">"ההזמנה נשלחה"</string>
<string name="wifi_p2p_invitation_to_connect_title" msgid="8917157937652519251">"הזמנה להתחבר"</string>
<string name="wifi_p2p_invitation_seconds_remaining" msgid="4214101104506918344">"{0,plural, =1{עליך לאשר תוך שנייה אחת.}one{עליך לאשר תוך # שניות.}two{עליך לאשר תוך # שניות.}other{עליך לאשר תוך # שניות.}}"</string>
- <string name="wifi_p2p_from_message" msgid="5921308150192756898">"מאת:"</string>
+ <string name="wifi_p2p_from_message" msgid="5921308150192756898">"מ:"</string>
<string name="wifi_p2p_to_message" msgid="3809923305696994787">"אל:"</string>
<string name="wifi_p2p_enter_pin_message" msgid="5200220251738047620">"יש להקליד את קוד האימות הנדרש:"</string>
<string name="wifi_p2p_show_pin_message" msgid="1000091690967930798">"קוד אימות:"</string>
diff --git a/service/ServiceWifiResources/res/values-ky/strings.xml b/service/ServiceWifiResources/res/values-ky/strings.xml
index 1dac1db9f7..e8c22b77fc 100644
--- a/service/ServiceWifiResources/res/values-ky/strings.xml
+++ b/service/ServiceWifiResources/res/values-ky/strings.xml
@@ -155,9 +155,9 @@
<string name="wifi_ca_cert_notification_preT_message" msgid="4565553176090475724">"Тармактын <xliff:g id="SSID">%1$s</xliff:g> тастыктамасы жок. Тастыктамаларды кошконду үйрөнүп алыңыз."</string>
<string name="wifi_ca_cert_notification_preT_continue_text" msgid="1525418430746943670">"Баары бир туташуу"</string>
<string name="wifi_ca_cert_notification_preT_abort_text" msgid="8307996031461071854">"Туташпасын"</string>
- <string name="wifi_enable_request_dialog_title" msgid="3577459145316177148">"<xliff:g id="APP_NAME">%1$s</xliff:g> колдонмосуна Wi‑Fi\'ды күйгүзүүгө уруксат берилсинби?"</string>
+ <string name="wifi_enable_request_dialog_title" msgid="3577459145316177148">"<xliff:g id="APP_NAME">%1$s</xliff:g> колдонмосуна Wi‑Fi\'ды күйгүзүүгө уруксат бересизби?"</string>
<string name="wifi_enable_request_dialog_message" msgid="6395169178524938278">"Wi‑Fi\'ды Ыкчам жөндөөлөрдөн өчүрсөңүз болот"</string>
- <string name="wifi_enable_request_dialog_positive_button" msgid="6050832555821470466">"Уруксат берүү"</string>
+ <string name="wifi_enable_request_dialog_positive_button" msgid="6050832555821470466">"Ооба"</string>
<string name="wifi_enable_request_dialog_negative_button" msgid="4754219902374918882">"Тыюу салуу"</string>
<string name="wifi_enabled_apm_first_time_title" msgid="4814302384637588804">"Wi‑Fi учак режиминде күйгүзүлөт"</string>
<string name="wifi_enabled_apm_first_time_message" msgid="6416193199042203037">"Эгер Wi-Fi күйүк бойдон калса, кийинки жолу учак режимине өткөнүңүздө түзмөгүңүз аны эстеп калат"</string>
diff --git a/service/ServiceWifiResources/res/values-mcc310-mnc150/config.xml b/service/ServiceWifiResources/res/values-mcc310-mnc150/config.xml
new file mode 100644
index 0000000000..39eaadb4a5
--- /dev/null
+++ b/service/ServiceWifiResources/res/values-mcc310-mnc150/config.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2023 The Android Open Source Project
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string-array translatable="false" name="config_wifiOobPseudonymEnabled_carrier_overrides">
+ <item><xliff:g id="carrier_id_prefix">:::1779:::</xliff:g>true</item>
+ </string-array>
+
+ <!-- Carrier specific override for the URL of entitlement server retrieving OOB pseudonym. -->
+ <string-array translatable="false" name="config_wifiOobPseudonymEntitlementServerUrl_carrier_overrides">
+ <item><xliff:g id="carrier_id_prefix">:::1779:::</xliff:g>https://sentitlement2.mobile.att.net/WFC</item>
+ </string-array>
+</resources>
diff --git a/service/ServiceWifiResources/res/values-mcc313-mnc100/config.xml b/service/ServiceWifiResources/res/values-mcc313-mnc100/config.xml
new file mode 100644
index 0000000000..83b0368e2b
--- /dev/null
+++ b/service/ServiceWifiResources/res/values-mcc313-mnc100/config.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2023 The Android Open Source Project
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+
+<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
+ <string-array translatable="false" name="config_wifiOobPseudonymEnabled_carrier_overrides">
+ <item><xliff:g id="carrier_id_prefix">:::2119:::</xliff:g>true</item>
+ </string-array>
+
+ <!-- Carrier specific override for the URL of entitlement server retrieving OOB pseudonym. -->
+ <string-array translatable="false" name="config_wifiOobPseudonymEntitlementServerUrl_carrier_overrides">
+ <item><xliff:g id="carrier_id_prefix">:::2119:::</xliff:g>https://sentitlement2.mobile.att.net/WFC</item>
+ </string-array>
+</resources>
diff --git a/service/ServiceWifiResources/res/values-mcc313-mnc130 b/service/ServiceWifiResources/res/values-mcc313-mnc130
new file mode 120000
index 0000000000..2d21ee5bae
--- /dev/null
+++ b/service/ServiceWifiResources/res/values-mcc313-mnc130
@@ -0,0 +1 @@
+values-mcc313-mnc100 \ No newline at end of file
diff --git a/service/ServiceWifiResources/res/values-mn/strings.xml b/service/ServiceWifiResources/res/values-mn/strings.xml
index 9ab92aca8f..293e732b10 100644
--- a/service/ServiceWifiResources/res/values-mn/strings.xml
+++ b/service/ServiceWifiResources/res/values-mn/strings.xml
@@ -65,7 +65,7 @@
<string name="wifi_cannot_connect_with_randomized_mac_title" msgid="2344570489693915253">"<xliff:g id="SSID">%1$s</xliff:g>-д холбогдож чадсангүй"</string>
<string name="wifi_cannot_connect_with_randomized_mac_message" msgid="4834133226521813352">"Нууцлалын тохиргоог өөрчлөхийн тулд товшоод, дахин оролдоно уу"</string>
<string name="wifi_disable_mac_randomization_dialog_title" msgid="2054540994993681606">"Нууцлалын тохиргоог өөрчлөх үү?"</string>
- <string name="wifi_disable_mac_randomization_dialog_message" msgid="8874064864332248988">"Холбогдохын тулд <xliff:g id="SSID">%1$s</xliff:g> нь таны төхөөрөмжийн өвөрмөц таниулбар болох MAC хаягийг ашиглах хэрэгтэй байна. Одоогоор энэ сүлжээнд зориулсан таны нууцлалын тохиргоо нь санамсаргүй сонгосон таниулбарыг ашиглаж байна. \n\nЭнэ нь ойролцоох төхөөрөмжүүдэд таны төхөөрөмжийн байршлыг тандахыг зөвшөөрч болзошгүй."</string>
+ <string name="wifi_disable_mac_randomization_dialog_message" msgid="8874064864332248988">"Холбогдохын тулд <xliff:g id="SSID">%1$s</xliff:g> нь таны төхөөрөмжийн өвөрмөц танигч болох MAC хаягийг ашиглах хэрэгтэй байна. Одоогоор энэ сүлжээнд зориулсан таны нууцлалын тохиргоо нь санамсаргүй сонгосон таниулбарыг ашиглаж байна. \n\nЭнэ нь ойролцоох төхөөрөмжүүдэд таны төхөөрөмжийн байршлыг тандахыг зөвшөөрч болзошгүй."</string>
<string name="wifi_disable_mac_randomization_dialog_confirm_text" msgid="6954419863076751626">"Тохиргоог өөрчлөх"</string>
<string name="wifi_disable_mac_randomization_dialog_success" msgid="5849155828154391387">"Тохиргоог шинэчиллээ. Дахин холбогдохыг оролдоно уу."</string>
<string name="wifi_disable_mac_randomization_dialog_failure" msgid="2894643619143813096">"Нууцлалын тохиргоог өөрчлөх боломжгүй байна"</string>
diff --git a/service/ServiceWifiResources/res/values-ne/strings.xml b/service/ServiceWifiResources/res/values-ne/strings.xml
index e4a33a2f0f..aa5ac4b49c 100644
--- a/service/ServiceWifiResources/res/values-ne/strings.xml
+++ b/service/ServiceWifiResources/res/values-ne/strings.xml
@@ -118,7 +118,7 @@
</string-array>
<string name="wifi_softap_auto_shutdown_timeout_expired_title" msgid="4896534374569504484">"हटस्पट निष्क्रिय पारिएको छ"</string>
<string name="wifi_softap_auto_shutdown_timeout_expired_summary" msgid="7975476698140267728">"कुनै यन्त्र जोडिएको छैन। परिमार्जन गर्न ट्याप गर्नुहोस्।"</string>
- <string name="wifi_sim_required_title" msgid="2262227800991155459">"Wi-Fi विच्छेद गरियो।"</string>
+ <string name="wifi_sim_required_title" msgid="2262227800991155459">"Wi-Fi डिस्कनेक्ट गरियो।"</string>
<string name="wifi_sim_required_message" msgid="284812212346125745">"<xliff:g id="SSID">%1$s</xliff:g> मा जोडिन <xliff:g id="CARRIER_NAME">%2$s</xliff:g> को SIM सम्मिलित गर्नुहोस्"</string>
<string name="wifi_interface_priority_title" msgid="5117627874976875544">"<xliff:g id="APP">%1$s</xliff:g> कुनै नेटवर्किङ स्रोत प्रयोग गर्न चाहन्छ"</string>
<string name="wifi_interface_priority_message" msgid="4253391172756140313">"यसले गर्दा <xliff:g id="APPS">%3$s</xliff:g> मा समस्या आउन सक्छ।"</string>
diff --git a/service/ServiceWifiResources/res/values-zu/strings.xml b/service/ServiceWifiResources/res/values-zu/strings.xml
index d8e04f070e..5820703694 100644
--- a/service/ServiceWifiResources/res/values-zu/strings.xml
+++ b/service/ServiceWifiResources/res/values-zu/strings.xml
@@ -64,11 +64,11 @@
<string name="dlg_ok" msgid="254496739491689405">"KULUNGILE"</string>
<string name="wifi_cannot_connect_with_randomized_mac_title" msgid="2344570489693915253">"Ayikwazi ukuxhumeka ku-<xliff:g id="SSID">%1$s</xliff:g>"</string>
<string name="wifi_cannot_connect_with_randomized_mac_message" msgid="4834133226521813352">"Thepha ukuze ushintshe izilungiselelo zobumfihlo uphinde uzame futhi"</string>
- <string name="wifi_disable_mac_randomization_dialog_title" msgid="2054540994993681606">"Shintsha isilungiselelo sobumfihlo?"</string>
+ <string name="wifi_disable_mac_randomization_dialog_title" msgid="2054540994993681606">"Shintsha isethingi yobumfihlo?"</string>
<string name="wifi_disable_mac_randomization_dialog_message" msgid="8874064864332248988">"Ukuze uxhume, i-<xliff:g id="SSID">%1$s</xliff:g> idinga ukusebenzisa ikheli lakho ledivayisi ye-MAC, inkomba ehlukile. Okwamanje, izilungiselelo zemfihlo yakho ngale nethiwekhi zisebenzisa inkomba engahleliwe. \n\nLokhu kungavumela indawo yedivayisi yakho ukuthi ilandelelwe amadivayisi aseduze."</string>
- <string name="wifi_disable_mac_randomization_dialog_confirm_text" msgid="6954419863076751626">"Shintsha isilungiselelo"</string>
- <string name="wifi_disable_mac_randomization_dialog_success" msgid="5849155828154391387">"Isilungiselelo sibuyekeziwe. Zama ukuxhuma futhi."</string>
- <string name="wifi_disable_mac_randomization_dialog_failure" msgid="2894643619143813096">"Ayikwazi ukushintsha isilungiselelo sobumfihlo"</string>
+ <string name="wifi_disable_mac_randomization_dialog_confirm_text" msgid="6954419863076751626">"Shintsha isethingi"</string>
+ <string name="wifi_disable_mac_randomization_dialog_success" msgid="5849155828154391387">"Isethingi sibuyekeziwe. Zama ukuxhuma futhi."</string>
+ <string name="wifi_disable_mac_randomization_dialog_failure" msgid="2894643619143813096">"Ayikwazi ukushintsha isethingi yobumfihlo"</string>
<string name="wifi_disable_mac_randomization_dialog_network_not_found" msgid="7359256966900782004">"Inethiwekhi ayitholiwe"</string>
<string name="wifi_eap_error_message_code_32756" msgid="2620877003804313434">"<xliff:g id="SSID">%1$s</xliff:g> : Iphutha lokugunyaza le-EAP 32756"</string>
<!-- no translation found for wifi_eap_error_message_code_32756_carrier_overrides:0 (9114567205305206743) -->
diff --git a/service/ServiceWifiResources/res/values/config.xml b/service/ServiceWifiResources/res/values/config.xml
index f7793b40db..ab73f3ac90 100644
--- a/service/ServiceWifiResources/res/values/config.xml
+++ b/service/ServiceWifiResources/res/values/config.xml
@@ -1315,4 +1315,31 @@
<!-- Boolean indicating whether the device supports d2d allowed control when infra STA is disabled -->
<bool translatable="false" name ="config_wifiD2dAllowedControlSupportedWhenInfraStaDisabled">false</bool>
+
+ <!-- Boolean indicating whether the device supports WEP allowed control or not -->
+ <bool translatable="false" name ="config_wifiWepAllowedControlSupported">true</bool>
+
+ <!-- Array describing MAC OUI list to block TWT session setup request. If the primary station is
+ connected to an AP with a MAC address OUI (https://standards-oui.ieee.org/oui/oui.txt)
+ matching with any of entries in this blocked list, WifiManager#setupTwtSession() will fail
+ with TwtSessionCallback#onFailure(errorCode = TWT_ERROR_CODE_AP_OUI_BLOCKLISTED).
+ -->
+ <integer-array translatable="false" name="config_wifiTwtBlockedOuiList">
+ <!-- Below is a sample configuration for this list:
+ <item>0x001122</item>
+ <item>0x334455</item>
+ -->
+ </integer-array>
+
+ <!-- Wi-Fi chip supports single link MLO SoftAp instances in the bridged mode -->
+ <bool translatable="false" name="config_wifiSoftApSingleLinkMloInBridgedModeSupported">false</bool>
+
+ <!-- Boolean indicating whether Target Wake Time (TWT) feature is supported or not. This flag
+ overrides the device's TWT capability if set to false. If the device supports TWT and this
+ overlay parameter is set to false, the application cannot set up a TWT session. Also, the
+ API WifiManager#getTwtCapabilities returns TWT unsupported even if the device is capable
+ of setting up TWT session.
+ -->
+ <bool translatable="false" name="config_wifiTwtSupported">true</bool>
+
</resources>
diff --git a/service/ServiceWifiResources/res/values/overlayable.xml b/service/ServiceWifiResources/res/values/overlayable.xml
index 15e4b84bec..e736668dd1 100644
--- a/service/ServiceWifiResources/res/values/overlayable.xml
+++ b/service/ServiceWifiResources/res/values/overlayable.xml
@@ -341,6 +341,10 @@
<item type="integer" name="config_wifi80211azMinTimeBetweenNtbMeasurementsMicros"/>
<item type="integer" name="config_wifi80211azMaxTimeBetweenNtbMeasurementsMicros"/>
<item type="bool" name="config_wifiD2dAllowedControlSupportedWhenInfraStaDisabled" />
+ <item type="array" name="config_wifiTwtBlockedOuiList" />
+ <item type="bool" name="config_wifiSoftApSingleLinkMloInBridgedModeSupported" />
+ <item type="bool" name="config_wifiTwtSupported" />
+ <item type="bool" name="config_wifiWepAllowedControlSupported" />
<!-- Params from config.xml that can be overlayed -->
diff --git a/service/TEST_MAPPING b/service/TEST_MAPPING
index 3d2718482c..6bb0f8e31c 100644
--- a/service/TEST_MAPPING
+++ b/service/TEST_MAPPING
@@ -18,5 +18,10 @@
{
"name": "FrameworksWifiTests[com.google.android.wifi.apex]"
}
+ ],
+ "wifi-mainline-presubmit": [
+ {
+ "name": "FrameworksWifiTests"
+ }
]
}
diff --git a/service/java/com/android/server/wifi/ActiveModeWarden.java b/service/java/com/android/server/wifi/ActiveModeWarden.java
index 5678e087a9..fc6392c949 100644
--- a/service/java/com/android/server/wifi/ActiveModeWarden.java
+++ b/service/java/com/android/server/wifi/ActiveModeWarden.java
@@ -217,9 +217,9 @@ public class ActiveModeWarden {
}
/**
- * Get the request WorkSource for secondary LOCAL-ONLY CMM
+ * Get the request WorkSource for secondary CMM
*
- * @return the WorkSources of the current secondary LOCAL-ONLY CMMs
+ * @return the WorkSources of the current secondary CMMs
*/
public Set<WorkSource> getSecondaryRequestWs() {
synchronized (mServiceApiLock) {
@@ -411,18 +411,17 @@ public class ActiveModeWarden {
wifiNative.registerStatusListener(isReady -> {
if (!isReady && !mIsShuttingdown) {
- mHandler.post(() -> {
- Log.e(TAG, "One of the native daemons died. Triggering recovery");
- wifiDiagnostics.triggerBugReportDataCapture(
- WifiDiagnostics.REPORT_REASON_WIFINATIVE_FAILURE);
-
- // immediately trigger SelfRecovery if we receive a notice about an
- // underlying daemon failure
- // Note: SelfRecovery has a circular dependency with ActiveModeWarden and is
- // instantiated after ActiveModeWarden, so use WifiInjector to get the instance
- // instead of directly passing in SelfRecovery in the constructor.
+ Log.e(TAG, "One of the native daemons died. Triggering recovery");
+ mWifiInjector.getWifiConfigManager().writeDataToStorage();
+ wifiDiagnostics.triggerBugReportDataCapture(
+ WifiDiagnostics.REPORT_REASON_WIFINATIVE_FAILURE);
+
+ // immediately trigger SelfRecovery if we receive a notice about an
+ // underlying daemon failure
+ // Note: SelfRecovery has a circular dependency with ActiveModeWarden and is
+ // instantiated after ActiveModeWarden, so use WifiInjector to get the instance
+ // instead of directly passing in SelfRecovery in the constructor.
mWifiInjector.getSelfRecovery().trigger(SelfRecovery.REASON_WIFINATIVE_FAILURE);
- });
}
});
@@ -719,7 +718,9 @@ public class ActiveModeWarden {
}
}, new IntentFilter(TelephonyManager.ACTION_EMERGENCY_CALL_STATE_CHANGED));
}
- mWifiGlobals.setD2dStaConcurrencySupported(mWifiNative.isP2pStaConcurrencySupported());
+ mWifiGlobals.setD2dStaConcurrencySupported(
+ mWifiNative.isP2pStaConcurrencySupported()
+ || mWifiNative.isNanStaConcurrencySupported());
// Initialize the supported feature set.
setSupportedFeatureSet(mWifiNative.getSupportedFeatureSet(null),
mWifiNative.isStaApConcurrencySupported(),
@@ -1418,7 +1419,7 @@ public class ActiveModeWarden {
ConcreteClientModeManager manager = mWifiInjector.makeClientModeManager(
listener, requestorWs, role, mVerboseLoggingEnabled);
mClientModeManagers.add(manager);
- if (ROLE_CLIENT_LOCAL_ONLY.equals(role)) {
+ if (ROLE_CLIENT_SECONDARY_LONG_LIVED.equals(role) || ROLE_CLIENT_LOCAL_ONLY.equals(role)) {
synchronized (mServiceApiLock) {
mRequestWs.add(new WorkSource(requestorWs));
}
@@ -1439,7 +1440,7 @@ public class ActiveModeWarden {
synchronized (mServiceApiLock) {
mRequestWs.remove(manager.getRequestorWs());
}
- if (ROLE_CLIENT_LOCAL_ONLY.equals(role)) {
+ if (ROLE_CLIENT_SECONDARY_LONG_LIVED.equals(role) || ROLE_CLIENT_LOCAL_ONLY.equals(role)) {
synchronized (mServiceApiLock) {
mRequestWs.add(new WorkSource(requestorWs));
}
@@ -1661,6 +1662,7 @@ public class ActiveModeWarden {
invokeOnPrimaryClientModeManagerChangedCallbacks(
mLastPrimaryClientModeManager, clientModeManager);
mLastPrimaryClientModeManager = clientModeManager;
+ setCurrentNetwork(clientModeManager.getCurrentNetwork());
}
setSupportedFeatureSet(
// If primary doesn't exist, DefaultClientModeManager getInterfaceName name
@@ -1694,7 +1696,8 @@ public class ActiveModeWarden {
private void onStoppedOrStartFailure(ConcreteClientModeManager clientModeManager) {
mClientModeManagers.remove(clientModeManager);
- if (ROLE_CLIENT_LOCAL_ONLY.equals(clientModeManager.getPreviousRole())) {
+ if (ROLE_CLIENT_SECONDARY_LONG_LIVED.equals(clientModeManager.getPreviousRole())
+ || ROLE_CLIENT_LOCAL_ONLY.equals(clientModeManager.getPreviousRole())) {
synchronized (mServiceApiLock) {
mRequestWs.remove(clientModeManager.getRequestorWs());
}
@@ -2157,7 +2160,7 @@ public class ActiveModeWarden {
public void exitImpl() {
}
- private void checkAndHandleAirplaneModeState() {
+ private void checkAndHandleAirplaneModeState(String loggingPackageName) {
if (mSettingsStore.isAirplaneModeOn()) {
log("Airplane mode toggled");
if (!mSettingsStore.shouldWifiRemainEnabledWhenApmEnabled()) {
@@ -2165,7 +2168,7 @@ public class ActiveModeWarden {
shutdownWifi();
// onStopped will move the state machine to "DisabledState".
mLastCallerInfoManager.put(WifiManager.API_WIFI_ENABLED, Process.myTid(),
- Process.WIFI_UID, -1, "android_apm", false);
+ Process.WIFI_UID, -1, loggingPackageName, false);
}
} else {
log("Airplane mode disabled, determine next state");
@@ -2175,7 +2178,7 @@ public class ActiveModeWarden {
mFacade.getSettingsWorkSource(mContext));
transitionTo(mEnabledState);
mLastCallerInfoManager.put(WifiManager.API_WIFI_ENABLED, Process.myTid(),
- Process.WIFI_UID, -1, "android_apm", true);
+ Process.WIFI_UID, -1, loggingPackageName, true);
}
// wifi should remain disabled, do not need to transition
}
@@ -2211,7 +2214,7 @@ public class ActiveModeWarden {
log("Satellite mode is on - return");
break;
}
- checkAndHandleAirplaneModeState();
+ checkAndHandleAirplaneModeState("android_apm");
break;
case CMD_UPDATE_AP_CAPABILITY:
updateCapabilityToSoftApModeManager((SoftApCapability) msg.obj, msg.arg1);
@@ -2223,9 +2226,12 @@ public class ActiveModeWarden {
if (mSettingsStore.isSatelliteModeOn()) {
log("Satellite mode is on, disable wifi");
shutdownWifi();
+ mLastCallerInfoManager.put(WifiManager.API_WIFI_ENABLED,
+ Process.myTid(), Process.WIFI_UID, -1, "satellite_mode",
+ false);
} else {
log("Satellite mode is off, determine next stage");
- checkAndHandleAirplaneModeState();
+ checkAndHandleAirplaneModeState("satellite_mode");
}
break;
default:
@@ -2263,6 +2269,7 @@ public class ActiveModeWarden {
// those secondary CMMs knows to abort properly, and won't react in strange
// ways to the primary switching to scan only mode later.
stopSecondaryClientModeManagers();
+ mWifiInjector.getWifiConnectivityManager().resetOnWifiDisable();
}
switchAllPrimaryOrScanOnlyClientModeManagers();
} else {
@@ -2270,6 +2277,7 @@ public class ActiveModeWarden {
}
} else {
stopAllClientModeManagers();
+ mWifiInjector.getWifiConnectivityManager().resetOnWifiDisable();
}
}
@@ -2427,7 +2435,8 @@ public class ActiveModeWarden {
if (mAllowRootToGetLocalOnlyCmm && curUid == 0) { // 0 is root UID.
continue;
}
- if (mWifiPermissionsUtil.checkEnterCarModePrioritized(curUid)) {
+ if (curUid != Process.SYSTEM_UID
+ && mWifiPermissionsUtil.checkEnterCarModePrioritized(curUid)) {
requestInfo.listener.onAnswer(primaryManager);
if (mVerboseLoggingEnabled) {
Log.w(TAG, "Uid " + curUid
@@ -2587,6 +2596,26 @@ public class ActiveModeWarden {
}
return HANDLED;
}
+ case CMD_SATELLITE_MODE_CHANGED:
+ if (mSettingsStore.isSatelliteModeOn()) {
+ log("Satellite mode is on, disable wifi");
+ shutdownWifi();
+ mLastCallerInfoManager.put(WifiManager.API_WIFI_ENABLED,
+ Process.myTid(), Process.WIFI_UID, -1, "satellite_mode",
+ false);
+ } else {
+ if (!hasPrimaryOrScanOnlyModeManager()) {
+ // Enabling SoftAp while wifi is off could result in
+ // ActiveModeWarden being in enabledState without a CMM.
+ // Defer to the default state in this case to handle the satellite
+ // mode state change which may result in enabling wifi if necessary.
+ log("Satellite mode is off in enabled state - "
+ + "and no primary manager");
+ return NOT_HANDLED;
+ }
+ log("Satellite mode is off in enabled state. Return handled");
+ }
+ break;
case CMD_AP_STOPPED:
case CMD_AP_START_FAILURE:
if (hasAnyModeManager()) {
diff --git a/service/java/com/android/server/wifi/ApplicationQosPolicyRequestHandler.java b/service/java/com/android/server/wifi/ApplicationQosPolicyRequestHandler.java
index e7bcddca94..f5893d5817 100644
--- a/service/java/com/android/server/wifi/ApplicationQosPolicyRequestHandler.java
+++ b/service/java/com/android/server/wifi/ApplicationQosPolicyRequestHandler.java
@@ -30,6 +30,7 @@ import android.os.RemoteException;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.modules.utils.build.SdkLevel;
import com.android.wifi.resources.R;
import java.io.PrintWriter;
@@ -353,23 +354,33 @@ public class ApplicationQosPolicyRequestHandler {
* Request to send all tracked policies to the specified interface.
*
* @param ifaceName Interface name to send the policies to.
- * @param includeUplink Whether stored uplink policies should be queued on this interface.
+ * @param apSupportsQosChars Whether the AP connected on this interface
+ * supports QosCharacteristics.
*/
- public void queueAllPoliciesOnIface(String ifaceName, boolean includeUplink) {
- List<QosPolicyParams> policyList = new ArrayList<>(mPolicyTrackingTable
- .getAllPolicies(QosPolicyParams.DIRECTION_DOWNLINK));
- if (includeUplink) {
- Log.i(TAG, "Including uplink policies");
- policyList.addAll(
- mPolicyTrackingTable.getAllPolicies(QosPolicyParams.DIRECTION_UPLINK));
- }
+ public void queueAllPoliciesOnIface(String ifaceName, boolean apSupportsQosChars) {
+ List<QosPolicyParams> policiesWithoutQosChars =
+ mPolicyTrackingTable.getAllPolicies(false);
+ List<QosPolicyParams> policiesWithQosChars = SdkLevel.isAtLeastV() && apSupportsQosChars
+ ? mPolicyTrackingTable.getAllPolicies(true) : Collections.emptyList();
+ int totalNumPolicies = policiesWithoutQosChars.size() + policiesWithQosChars.size();
+
Log.i(TAG, "Queueing all policies on iface=" + ifaceName + ". numPolicies="
- + policyList.size());
- if (policyList.isEmpty()) return;
+ + totalNumPolicies);
+ Log.i(TAG, policiesWithQosChars.size() + " policies contain QosCharacteristics");
+ if (totalNumPolicies == 0) return;
+
+ // Divide policies into batches of size MAX_POLICIES_PER_TRANSACTION. Separate batches
+ // should be created for policies that contain QosCharacteristics, and those that do
+ // not contain them.
+ List<List<QosPolicyParams>> batches = new ArrayList<>();
+ if (!policiesWithoutQosChars.isEmpty()) {
+ batches.addAll(divideRequestIntoBatches(policiesWithoutQosChars));
+ }
+ if (!policiesWithQosChars.isEmpty()) {
+ batches.addAll(divideRequestIntoBatches(policiesWithQosChars));
+ }
- // Divide policyList into batches of size MAX_POLICIES_PER_TRANSACTION,
- // and queue each batch on the specified interface.
- List<List<QosPolicyParams>> batches = divideRequestIntoBatches(policyList);
+ // Queue all batches on the specified interface.
for (List<QosPolicyParams> batch : batches) {
QueuedRequest request = new QueuedRequest(
REQUEST_TYPE_ADD, batch, null, null, null, DEFAULT_UID);
diff --git a/service/java/com/android/server/wifi/ApplicationQosPolicyTrackingTable.java b/service/java/com/android/server/wifi/ApplicationQosPolicyTrackingTable.java
index 869bc0dca3..d8509d4b3d 100644
--- a/service/java/com/android/server/wifi/ApplicationQosPolicyTrackingTable.java
+++ b/service/java/com/android/server/wifi/ApplicationQosPolicyTrackingTable.java
@@ -19,6 +19,8 @@ package com.android.server.wifi;
import android.net.wifi.QosPolicyParams;
import android.net.wifi.WifiManager;
+import com.android.modules.utils.build.SdkLevel;
+
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
@@ -26,6 +28,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
+import java.util.stream.Stream;
/**
* Table containing application-added QoS policies that are being tracked by the framework.
@@ -214,18 +217,20 @@ public class ApplicationQosPolicyTrackingTable {
/**
* Get all policies that are tracked by this table.
*
- * @param direction Direction of the policies to retrieve.
+ * @param shouldContainQosChars Whether the returned policies should contain QosCharacteristics.
+ * Only applicable if SDK >= V.
* @return List of policies, or empty list if there are no policies in the table.
*/
- public List<QosPolicyParams> getAllPolicies(@QosPolicyParams.Direction int direction) {
+ public List<QosPolicyParams> getAllPolicies(boolean shouldContainQosChars) {
if (mPolicyHashToPolicyMap.isEmpty()) {
return new ArrayList<>();
}
- return mPolicyHashToPolicyMap
- .values()
- .stream()
- .filter(p -> p.getDirection() == direction)
- .toList();
+ Stream<QosPolicyParams> policyStream = mPolicyHashToPolicyMap.values().stream();
+ if (SdkLevel.isAtLeastV()) {
+ policyStream = policyStream.filter(p ->
+ shouldContainQosChars == (p.getQosCharacteristics() != null));
+ }
+ return policyStream.toList();
}
/**
diff --git a/service/java/com/android/server/wifi/AvailableNetworkNotifier.java b/service/java/com/android/server/wifi/AvailableNetworkNotifier.java
index 03d6cf567c..447155fe34 100644
--- a/service/java/com/android/server/wifi/AvailableNetworkNotifier.java
+++ b/service/java/com/android/server/wifi/AvailableNetworkNotifier.java
@@ -484,7 +484,7 @@ public class AvailableNetworkNotifier {
private void addNetworkToBlocklist(String ssid) {
mBlocklistedSsids.add(ssid);
mWifiMetrics.setNetworkRecommenderBlocklistSize(mTag, mBlocklistedSsids.size());
- mConfigManager.saveToStore(false /* forceWrite */);
+ mConfigManager.saveToStore();
Log.d(mTag, "Network is added to the network notification blocklist: "
+ "\"" + ssid + "\"");
}
@@ -497,7 +497,7 @@ public class AvailableNetworkNotifier {
return;
}
mWifiMetrics.setNetworkRecommenderBlocklistSize(mTag, mBlocklistedSsids.size());
- mConfigManager.saveToStore(false /* forceWrite */);
+ mConfigManager.saveToStore();
Log.d(mTag, "Network is removed from the network notification blocklist: "
+ "\"" + ssid + "\"");
}
diff --git a/service/java/com/android/server/wifi/BackupRestoreController.java b/service/java/com/android/server/wifi/BackupRestoreController.java
index 2908185ed5..374743b8cb 100644
--- a/service/java/com/android/server/wifi/BackupRestoreController.java
+++ b/service/java/com/android/server/wifi/BackupRestoreController.java
@@ -45,7 +45,7 @@ public class BackupRestoreController {
private final WifiSettingsBackupRestore mWifiSettingsBackupRestore;
private final Clock mClock;
- private static final String XML_TAG_DOCUMENT_HEADER = "WifiBackupDataUnion";
+ private static final String XML_TAG_DOCUMENT_HEADER = "WifiSettingsBackupData";
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("MM-dd HH:mm:ss.SSS");
/**
diff --git a/service/java/com/android/server/wifi/ClientModeImpl.java b/service/java/com/android/server/wifi/ClientModeImpl.java
index 77be0be9e2..913ac9bf7b 100644
--- a/service/java/com/android/server/wifi/ClientModeImpl.java
+++ b/service/java/com/android/server/wifi/ClientModeImpl.java
@@ -247,7 +247,6 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
private final PasspointManager mPasspointManager;
private final WifiDataStall mWifiDataStall;
private final RssiMonitor mRssiMonitor;
- private final LinkProbeManager mLinkProbeManager;
private final MboOceController mMboOceController;
private final McastLockManagerFilterController mMcastLockManagerFilterController;
private final ActivityManager mActivityManager;
@@ -692,6 +691,12 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
private final ApplicationQosPolicyRequestHandler mApplicationQosPolicyRequestHandler;
+ @VisibleForTesting
+ public static final String X509_CERTIFICATE_EXPIRED_ERROR_STRING = "certificate has expired";
+ @VisibleForTesting
+ public static final int EAP_FAILURE_CODE_CERTIFICATE_EXPIRED = 32768;
+ private boolean mCurrentConnectionReportedCertificateExpired = false;
+
/** Note that this constructor will also start() the StateMachine. */
public ClientModeImpl(
@@ -731,7 +736,6 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
@NonNull WifiNative wifiNative,
@NonNull WrongPasswordNotifier wrongPasswordNotifier,
@NonNull WifiTrafficPoller wifiTrafficPoller,
- @NonNull LinkProbeManager linkProbeManager,
long id,
@NonNull BatteryStatsManager batteryStatsManager,
@NonNull SupplicantStateTracker supplicantStateTracker,
@@ -766,7 +770,6 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
mEapFailureNotifier = eapFailureNotifier;
mSimRequiredNotifier = simRequiredNotifier;
mWifiTrafficPoller = wifiTrafficPoller;
- mLinkProbeManager = linkProbeManager;
mMboOceController = mboOceController;
mWifiCarrierInfoManager = wifiCarrierInfoManager;
mWifiPseudonymManager = wifiPseudonymManager;
@@ -1655,9 +1658,14 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
if (mContext.getResources().getBoolean(R.bool.config_wifi11axSupportOverride)) {
cap.setWifiStandardSupport(ScanResult.WIFI_STANDARD_11AX, true);
}
- // Enable WPA3 SAE auto-upgrade offload
+ // The Wi-Fi Alliance has introduced the WPA3 security update for Wi-Fi 7, which
+ // mandates cross-AKM (Authenticated Key Management) roaming between three AKMs
+ // (AKM: 24(SAE-EXT-KEY), AKM:8(SAE) and AKM:2(PSK)). If the station supports
+ // AKM 24(SAE-EXT-KEY), it is recommended to enable WPA3 SAE auto-upgrade offload,
+ // provided that the driver indicates that the maximum number of AKM suites allowed in
+ // connection requests is three or more.
if (Flags.getDeviceCrossAkmRoamingSupport() && SdkLevel.isAtLeastV()
- && cap.getMaxNumberAkms() >= 2) {
+ && cap.getMaxNumberAkms() >= 3) {
mWifiGlobals.setWpa3SaeUpgradeOffloadEnabled();
}
@@ -1893,7 +1901,8 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
*/
public boolean syncQueryPasspointIcon(long bssid, String fileName) {
return mWifiThreadRunner.call(
- () -> mPasspointManager.queryPasspointIcon(bssid, fileName), false);
+ () -> mPasspointManager.queryPasspointIcon(bssid, fileName), false,
+ TAG + "#syncQueryPasspointIcon");
}
@Override
@@ -1945,7 +1954,8 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
IProvisioningCallback callback) {
return mWifiThreadRunner.call(
() -> mPasspointManager.startSubscriptionProvisioning(
- callingUid, provider, callback), false);
+ callingUid, provider, callback), false,
+ TAG + "#syncStartSubscriptionProvisioning");
}
/**
@@ -2712,7 +2722,10 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
private void updateMloLinkFromPollResults(MloLink link, WifiSignalPollResults pollResults) {
if (link == null) return;
int linkId = link.getLinkId();
- link.setRssi(pollResults.getRssi(linkId));
+ int rssi = RssiUtil.calculateAdjustedRssi(pollResults.getRssi(linkId));
+ if (rssi > WifiInfo.INVALID_RSSI) {
+ link.setRssi(rssi);
+ }
link.setTxLinkSpeedMbps(pollResults.getTxLinkSpeed(linkId));
link.setRxLinkSpeedMbps(pollResults.getRxLinkSpeed(linkId));
link.setChannel(ScanResult.convertFrequencyMhzToChannelIfSupported(
@@ -2755,7 +2768,7 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
return stats;
}
- int newRssi = pollResults.getRssi();
+ int newRssi = RssiUtil.calculateAdjustedRssi(pollResults.getRssi());
int newTxLinkSpeed = pollResults.getTxLinkSpeed();
int newFrequency = pollResults.getFrequency();
int newRxLinkSpeed = pollResults.getRxLinkSpeed();
@@ -2781,6 +2794,9 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
* set Tx link speed only if it is valid
*/
if (newTxLinkSpeed > 0) {
+ if (newTxLinkSpeed != mWifiInfo.getTxLinkSpeedMbps() && SdkLevel.isAtLeastV()) {
+ updateNetworkCapabilities = true;
+ }
mWifiInfo.setLinkSpeed(newTxLinkSpeed);
mWifiInfo.setTxLinkSpeedMbps(newTxLinkSpeed);
}
@@ -2788,6 +2804,9 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
* set Rx link speed only if it is valid
*/
if (newRxLinkSpeed > 0) {
+ if (newRxLinkSpeed != mWifiInfo.getRxLinkSpeedMbps() && SdkLevel.isAtLeastV()) {
+ updateNetworkCapabilities = true;
+ }
mWifiInfo.setRxLinkSpeedMbps(newRxLinkSpeed);
}
if (newFrequency > 0) {
@@ -2796,18 +2815,9 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
}
mWifiInfo.setFrequency(newFrequency);
}
+
// updateLinkBandwidth() requires the latest frequency information
- if (newRssi > WifiInfo.INVALID_RSSI && newRssi < WifiInfo.MAX_RSSI) {
- /*
- * Positive RSSI is possible when devices are close(~0m apart) to each other.
- * And there are some driver/firmware implementation, where they avoid
- * reporting large negative rssi values by adding 256.
- * so adjust the valid rssi reports for such implementations.
- */
- if (newRssi > (WifiInfo.INVALID_RSSI + 256)) {
- Log.wtf(getTag(), "Error! +ve value RSSI: " + newRssi);
- newRssi -= 256;
- }
+ if (newRssi > WifiInfo.INVALID_RSSI) {
int oldRssi = mWifiInfo.getRssi();
mWifiInfo.setRssi(newRssi);
/*
@@ -2834,10 +2844,6 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
updateLinkBandwidthAndCapabilities(stats, updateNetworkCapabilities, txBytes,
rxBytes);
mLastSignalLevel = newSignalLevel;
- } else {
- mWifiInfo.setRssi(WifiInfo.INVALID_RSSI);
- updateCapabilities();
- mLastSignalLevel = -1;
}
mWifiConfigManager.updateScanDetailCacheFromWifiInfo(mWifiInfo);
/*
@@ -3432,6 +3438,8 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
mLastConnectionCapabilities.apTidToLinkMapNegotiationSupported);
mWifiMetrics.setConnectionMaxSupportedLinkSpeedMbps(mInterfaceName,
maxTxLinkSpeedMbps, maxRxLinkSpeedMbps);
+ mWifiMetrics.setConnectionChannelWidth(mInterfaceName,
+ mLastConnectionCapabilities.channelBandwidth);
if (mLastConnectionCapabilities.wifiStandard == ScanResult.WIFI_STANDARD_11BE) {
updateMloLinkAddrAndStates(mWifiNative.getConnectionMloLinksInfo(mInterfaceName));
updateBlockListAffiliatedBssids();
@@ -3511,6 +3519,10 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
mWakeupController.setLastDisconnectInfo(matchInfo);
}
mRssiMonitor.reset();
+ // On disconnect, restore roaming mode to normal
+ if (!newConnectionInProgress) {
+ enableRoaming(true);
+ }
}
clearTargetBssid("handleNetworkDisconnect");
@@ -3567,6 +3579,7 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
mLastNetworkId = WifiConfiguration.INVALID_NETWORK_ID;
mLastSubId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
mCurrentConnectionDetectedCaptivePortal = false;
+ mCurrentConnectionReportedCertificateExpired = false;
mLastSimBasedConnectionCarrierName = null;
mNudFailureCounter = new Pair<>(0L, 0);
checkAbnormalDisconnectionAndTakeBugReport();
@@ -4783,6 +4796,7 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
break;
}
mCurrentConnectionDetectedCaptivePortal = false;
+ mCurrentConnectionReportedCertificateExpired = false;
mTargetNetworkId = netId;
// Update scorecard while there is still state from existing connection
mLastScanRssi = mWifiConfigManager.findScanRssi(netId,
@@ -5366,7 +5380,7 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
public boolean isAffiliatedLinkBssid(@NonNull MacAddress bssid) {
List<MloLink> links = mWifiInfo.getAffiliatedMloLinks();
for (MloLink link: links) {
- if (link.getApMacAddress().equals(bssid)) {
+ if (bssid.equals(link.getApMacAddress())) {
return true;
}
}
@@ -5510,7 +5524,8 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
return;
}
mWifiThreadRunner.post(
- () -> mRssiMonitor.updateAppThresholdsAndStartMonitor(thresholds));
+ () -> mRssiMonitor.updateAppThresholdsAndStartMonitor(thresholds),
+ TAG + "#onSignalStrengthThresholdsUpdated");
}
@Override
@@ -5831,6 +5846,7 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
mApplicationQosPolicyRequestHandler.queueAllPoliciesOnIface(
mInterfaceName, mostRecentConnectionSupports11ax());
}
+ mWifiNative.resendMscs(mInterfaceName);
updateLayer2Information();
updateCurrentConnectionInfo();
transitionTo(mL3ProvisioningState);
@@ -5936,6 +5952,12 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
logEventIfManagedNetwork(getConnectingWifiConfigurationInternal(),
eventInfo.eventCode, eventInfo.bssid,
eventInfo.reasonString);
+ if (!TextUtils.isEmpty(eventInfo.reasonString)
+ && eventInfo.reasonString.contains(
+ X509_CERTIFICATE_EXPIRED_ERROR_STRING)) {
+ mCurrentConnectionReportedCertificateExpired = true;
+ Log.e(getTag(), "Current connection attempt detected expired certificate");
+ }
break;
}
case CMD_DISCONNECT: {
@@ -6225,6 +6247,9 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
disableReason = WifiConfiguration.NetworkSelectionStatus
.DISABLED_AUTHENTICATION_NO_SUBSCRIPTION;
}
+ if (mCurrentConnectionReportedCertificateExpired && errorCode <= 0) {
+ errorCode = EAP_FAILURE_CODE_CERTIFICATE_EXPIRED;
+ }
}
mWifiConfigManager.updateNetworkSelectionStatus(
mTargetNetworkId, disableReason);
@@ -6426,10 +6451,9 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
mRssiPollToken++;
if (mEnableRssiPolling) {
- if (isPrimary()) {
- mLinkProbeManager.resetOnNewConnection();
- }
sendMessage(CMD_RSSI_POLL, mRssiPollToken, 0);
+ } else {
+ updateLinkLayerStatsRssiAndScoreReport();
}
sendNetworkChangeBroadcast(DetailedState.CONNECTING);
// If this network was explicitly selected by the user, evaluate whether to inform
@@ -6665,9 +6689,6 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
if (message.arg1 == mRssiPollToken) {
updateLinkLayerStatsRssiDataStallScoreReport();
mWifiScoreCard.noteSignalPoll(mWifiInfo);
- if (isPrimary()) {
- mLinkProbeManager.updateConnectionStats(mWifiInfo, mInterfaceName);
- }
// Update the polling interval as needed before sending the delayed message
// so that the next polling can happen after the updated interval
if (isPrimary()) {
@@ -6693,9 +6714,6 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
if (mEnableRssiPolling) {
// First poll
mLastSignalLevel = -1;
- if (isPrimary()) {
- mLinkProbeManager.resetOnScreenTurnedOn();
- }
long txBytes = mFacade.getTotalTxBytes() - mFacade.getMobileTxBytes();
long rxBytes = mFacade.getTotalRxBytes() - mFacade.getMobileRxBytes();
updateLinkLayerStatsRssiSpeedFrequencyCapabilities(txBytes, rxBytes);
@@ -7326,7 +7344,6 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
WifiConfiguration config = getConnectedWifiConfigurationInternal();
mWifiScoreReport.startConnectedNetworkScorer(
mNetworkAgent.getNetwork().getNetId(), isRecentlySelectedByTheUser(config));
- updateLinkLayerStatsRssiAndScoreReport();
mWifiScoreCard.noteIpConfiguration(mWifiInfo);
// too many places to record L3 failure with too many failure reasons.
// So only record success here.
@@ -7334,10 +7351,16 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
updateCurrentConnectionInfo();
sendConnectedState();
// Set the roaming policy for the currently connected network
- if (isPrimary() && getClientRoleForMetrics(config)
+ if (getClientRoleForMetrics(config)
!= WifiStatsLog.WIFI_CONNECTION_RESULT_REPORTED__ROLE__ROLE_CLIENT_LOCAL_ONLY) {
- mWifiInjector.getWifiRoamingModeManager().applyWifiRoamingMode(
- mInterfaceName, mWifiInfo.getSSID());
+ if (isPrimary()) {
+ mWifiInjector.getWifiRoamingModeManager().applyWifiRoamingMode(
+ mInterfaceName, mWifiInfo.getSSID());
+ }
+ if (SdkLevel.isAtLeastV() && mWifiInjector.getWifiVoipDetector() != null) {
+ mWifiInjector.getWifiVoipDetector().notifyWifiConnected(true,
+ isPrimary(), mInterfaceName);
+ }
}
}
@@ -7595,6 +7618,11 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
WifiConnectivityManager.WIFI_STATE_TRANSITIONING);
mWifiLastResortWatchdog.connectedStateTransition(false);
+ // Always notify Voip detector module.
+ if (SdkLevel.isAtLeastV() && mWifiInjector.getWifiVoipDetector() != null) {
+ mWifiInjector.getWifiVoipDetector().notifyWifiConnected(false,
+ isPrimary(), mInterfaceName);
+ }
}
}
@@ -8641,7 +8669,7 @@ public class ClientModeImpl extends StateMachine implements ClientMode {
return false;
}
- return mWifiConfigManager.saveToStore(true);
+ return mWifiConfigManager.saveToStore();
}
/**
diff --git a/service/java/com/android/server/wifi/DeviceConfigFacade.java b/service/java/com/android/server/wifi/DeviceConfigFacade.java
index f9080462b4..ec5c4bfef9 100644
--- a/service/java/com/android/server/wifi/DeviceConfigFacade.java
+++ b/service/java/com/android/server/wifi/DeviceConfigFacade.java
@@ -220,6 +220,7 @@ public class DeviceConfigFacade {
private boolean mSoftwarePnoEnabled;
private boolean mIncludePasspointSsidsInPnoScans;
private boolean mHandleRssiOrganicKernelFailuresEnabled;
+ private Set<String> mDisabledAutoBugreports = Collections.EMPTY_SET;
private final Handler mWifiHandler;
@@ -421,6 +422,24 @@ public class DeviceConfigFacade {
"include_passpoint_ssids_in_pno_scans", true);
mHandleRssiOrganicKernelFailuresEnabled = DeviceConfig.getBoolean(NAMESPACE,
"handle_rssi_organic_kernel_failures_enabled", true);
+ mDisabledAutoBugreports = getDisabledAutoBugreports();
+ }
+
+ private Set<String> getDisabledAutoBugreports() {
+ String rawList = DeviceConfig.getString(NAMESPACE,
+ "disabled_auto_bugreport_title_and_description", null);
+ if (rawList == null || rawList.isEmpty()) {
+ return Collections.EMPTY_SET;
+ }
+ Set<String> result = new ArraySet<>();
+ String[] list = rawList.split(",");
+ for (String cur : list) {
+ if (cur.length() == 0) {
+ continue;
+ }
+ result.add(cur);
+ }
+ return Collections.unmodifiableSet(result);
}
private Set<String> getUnmodifiableSetQuoted(String key) {
@@ -918,6 +937,14 @@ public class DeviceConfigFacade {
mOobPseudonymFeatureFlagChangedListener = listener;
}
+ /**
+ * Get the set of bugreports that are explicitly disabled.
+ * @return A Set of String to indicate disabled auto-bugreports trigger points.
+ */
+ public Set<String> getDisabledAutoBugreportTitleAndDetails() {
+ return mDisabledAutoBugreports;
+ }
+
public FeatureFlags getFeatureFlags() {
return mFeatureFlags;
}
diff --git a/service/java/com/android/server/wifi/DppManager.java b/service/java/com/android/server/wifi/DppManager.java
index 76a8f63e54..c8bf111b9d 100644
--- a/service/java/com/android/server/wifi/DppManager.java
+++ b/service/java/com/android/server/wifi/DppManager.java
@@ -1094,8 +1094,13 @@ public class DppManager {
logd("binderDied: uid=" + dppRequestInfo.uid);
mHandler.post(() -> {
- dppRequestInfo.isGeneratingSelfConfiguration = false;
// Clean up supplicant resource
+ if (mDppRequestInfo == null) {
+ Log.e(TAG, "binderDied event without a request information object");
+ return;
+ }
+ mDppRequestInfo.isGeneratingSelfConfiguration = false;
+
if (mDppRequestInfo.authRole == DPP_AUTH_ROLE_INITIATOR) {
if (!mWifiNative.stopDppInitiator(mClientIfaceName)) {
Log.e(TAG, "Failed to stop DPP Initiator");
diff --git a/service/java/com/android/server/wifi/ExternalScoreUpdateObserverProxy.java b/service/java/com/android/server/wifi/ExternalScoreUpdateObserverProxy.java
index 9936bd0531..8efb235b44 100644
--- a/service/java/com/android/server/wifi/ExternalScoreUpdateObserverProxy.java
+++ b/service/java/com/android/server/wifi/ExternalScoreUpdateObserverProxy.java
@@ -87,7 +87,7 @@ public class ExternalScoreUpdateObserverProxy extends IScoreUpdateObserver.Stub
}
mCountNullCallback = 0;
mCallback.notifyScoreUpdate(sessionId, score);
- });
+ }, TAG + "#notifyScoreUpdate");
}
@Override
@@ -100,7 +100,7 @@ public class ExternalScoreUpdateObserverProxy extends IScoreUpdateObserver.Stub
}
mCountNullCallback = 0;
mCallback.triggerUpdateOfWifiUsabilityStats(sessionId);
- });
+ }, TAG + "#triggerUpdateOfWifiUsabilityStats");
}
@Override
@@ -115,7 +115,7 @@ public class ExternalScoreUpdateObserverProxy extends IScoreUpdateObserver.Stub
}
mCountNullCallback = 0;
mCallback.notifyStatusUpdate(sessionId, isUsable);
- });
+ }, TAG + "#notifyStatusUpdate");
}
@Override
@@ -130,7 +130,7 @@ public class ExternalScoreUpdateObserverProxy extends IScoreUpdateObserver.Stub
}
mCountNullCallback = 0;
mCallback.requestNudOperation(sessionId);
- });
+ }, TAG + "#requestNudOperation");
}
@Override
@@ -145,6 +145,6 @@ public class ExternalScoreUpdateObserverProxy extends IScoreUpdateObserver.Stub
}
mCountNullCallback = 0;
mCallback.blocklistCurrentBssid(sessionId);
- });
+ }, TAG + "#blocklistCurrentBssid");
}
}
diff --git a/service/java/com/android/server/wifi/HalDeviceManager.java b/service/java/com/android/server/wifi/HalDeviceManager.java
index 3e950d9fea..99f929c8f3 100644
--- a/service/java/com/android/server/wifi/HalDeviceManager.java
+++ b/service/java/com/android/server/wifi/HalDeviceManager.java
@@ -181,6 +181,13 @@ public class HalDeviceManager {
}
/**
+ * Returns whether or not the concurrency combo is loaded from the driver.
+ */
+ public boolean isConcurrencyComboLoadedFromDriver() {
+ return mIsConcurrencyComboLoadedFromDriver;
+ }
+
+ /**
* Enables verbose logging.
*/
public void enableVerboseLogging(boolean verboseEnabled) {
@@ -1546,7 +1553,7 @@ public class HalDeviceManager {
private void managerStatusListenerDispatch() {
synchronized (mLock) {
for (ManagerStatusListenerProxy cb : mManagerStatusListeners) {
- cb.trigger(false);
+ cb.action();
}
}
}
@@ -2497,11 +2504,6 @@ public class HalDeviceManager {
return false;
}
- // dispatch listeners on other threads to prevent race conditions in case the HAL is
- // blocking and they get notification about destruction from HAL before cleaning up
- // status.
- dispatchDestroyedListeners(name, type, true);
-
boolean success = false;
switch (type) {
case WifiChip.IFACE_TYPE_STA:
@@ -2523,7 +2525,7 @@ public class HalDeviceManager {
}
// dispatch listeners no matter what status
- dispatchDestroyedListeners(name, type, false);
+ dispatchDestroyedListeners(name, type);
if (validateRttController) {
// Try to update the RttController
updateRttControllerWhenInterfaceChanges();
@@ -2542,12 +2544,10 @@ public class HalDeviceManager {
// cache entries for the called listeners
// onlyOnOtherThreads = true: only call listeners on other threads
// onlyOnOtherThreads = false: call all listeners
- private void dispatchDestroyedListeners(String name, int type, boolean onlyOnOtherThreads) {
+ private void dispatchDestroyedListeners(String name, int type) {
if (VDBG) Log.d(TAG, "dispatchDestroyedListeners: iface(name)=" + name);
-
- List<InterfaceDestroyedListenerProxy> triggerList = new ArrayList<>();
synchronized (mLock) {
- InterfaceCacheEntry entry = mInterfaceInfoCache.get(Pair.create(name, type));
+ InterfaceCacheEntry entry = mInterfaceInfoCache.remove(Pair.create(name, type));
if (entry == null) {
Log.e(TAG, "dispatchDestroyedListeners: no cache entry for iface(name)=" + name);
return;
@@ -2557,19 +2557,10 @@ public class HalDeviceManager {
entry.destroyedListeners.iterator();
while (iterator.hasNext()) {
InterfaceDestroyedListenerProxy listener = iterator.next();
- if (!onlyOnOtherThreads || !listener.requestedToRunInCurrentThread()) {
- triggerList.add(listener);
- iterator.remove();
- }
- }
- if (!onlyOnOtherThreads) { // leave entry until final call to *all* callbacks
- mInterfaceInfoCache.remove(Pair.create(name, type));
+ iterator.remove();
+ listener.action();
}
}
-
- for (InterfaceDestroyedListenerProxy listener : triggerList) {
- listener.trigger(isWaitForDestroyedListenersMockable());
- }
}
// dispatch all destroyed listeners registered to all interfaces
@@ -2588,7 +2579,7 @@ public class HalDeviceManager {
}
for (InterfaceDestroyedListenerProxy listener : triggerList) {
- listener.trigger(false);
+ listener.action();
}
}
@@ -2627,46 +2618,6 @@ public class HalDeviceManager {
return mListener.hashCode();
}
- public boolean requestedToRunInCurrentThread() {
- if (mHandler == null) return true;
- long currentTid = mWifiInjector.getCurrentThreadId();
- long handlerTid = mHandler.getLooper().getThread().getId();
- return currentTid == handlerTid;
- }
-
- void trigger(boolean isRunAtFront) {
- // TODO(b/199792691): The thread check is needed to preserve the existing
- // assumptions of synchronous execution of the "onDestroyed" callback as much as
- // possible. This is needed to prevent regressions caused by posting to the handler
- // thread changing the code execution order.
- // When all wifi services (ie. WifiAware, WifiP2p) get moved to the wifi handler
- // thread, remove this thread check and the Handler#post() and simply always
- // invoke the callback directly.
- if (mFeatureFlags.singleWifiThread()) {
- action();
- return;
- }
- if (requestedToRunInCurrentThread()) {
- // Already running on the same handler thread. Trigger listener synchronously.
- action();
- } else if (isRunAtFront) {
- // Current thread is not the thread the listener should be invoked on.
- // Post action to the intended thread and run synchronously.
- new WifiThreadRunner(mHandler).runAtFront(() -> {
- action();
- });
- } else {
- // Current thread is not the thread the listener should be invoked on.
- // Post action to the intended thread.
- if (mHandler instanceof RunnerHandler) {
- RunnerHandler rh = (RunnerHandler) mHandler;
- rh.postToFront(() -> action());
- } else {
- mHandler.postAtFrontOfQueue(() -> action());
- }
- }
- }
-
protected void action() {}
ListenerProxy(LISTENER listener, Handler handler, String tag) {
diff --git a/service/java/com/android/server/wifi/ISupplicantStaIfaceHal.java b/service/java/com/android/server/wifi/ISupplicantStaIfaceHal.java
index 77d71e0eec..6796b2e904 100644
--- a/service/java/com/android/server/wifi/ISupplicantStaIfaceHal.java
+++ b/service/java/com/android/server/wifi/ISupplicantStaIfaceHal.java
@@ -840,6 +840,13 @@ interface ISupplicantStaIfaceHal {
default void enableMscs(@NonNull MscsParams mscsParams, String ifaceName) {}
/**
+ * Resend the previously configured MSCS parameters on this interface, if any exist.
+ *
+ * @param ifaceName Name of the interface.
+ */
+ default void resendMscs(String ifaceName) {};
+
+ /**
* Disable Mirrored Stream Classification Service (MSCS).
*
* @param ifaceName Name of the interface.
diff --git a/service/java/com/android/server/wifi/InsecureEapNetworkHandler.java b/service/java/com/android/server/wifi/InsecureEapNetworkHandler.java
index 43a19234e6..f80f0ae186 100644
--- a/service/java/com/android/server/wifi/InsecureEapNetworkHandler.java
+++ b/service/java/com/android/server/wifi/InsecureEapNetworkHandler.java
@@ -383,6 +383,18 @@ public class InsecureEapNetworkHandler {
Log.d(TAG, cert.getSubjectX500Principal().getName());
}
+ if (null == mPendingServerCertSubjectInfo) {
+ handleError(mCurrentTofuConfig.SSID);
+ Log.d(TAG, "No valid subject info in Server cert for TLS-based connection.");
+ return false;
+ }
+
+ if (null == mPendingServerCertIssuerInfo) {
+ handleError(mCurrentTofuConfig.SSID);
+ Log.d(TAG, "No valid issuer info in Server cert for TLS-based connection.");
+ return false;
+ }
+
if (!configureServerValidationMethod()) {
Log.e(TAG, "Server cert chain is invalid.");
String ssid = mCurrentTofuConfig.SSID;
diff --git a/service/java/com/android/server/wifi/LinkProbeManager.java b/service/java/com/android/server/wifi/LinkProbeManager.java
deleted file mode 100644
index 26d2416f23..0000000000
--- a/service/java/com/android/server/wifi/LinkProbeManager.java
+++ /dev/null
@@ -1,359 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.wifi;
-
-import android.content.Context;
-import android.net.MacAddress;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.nl80211.WifiNl80211Manager;
-import android.os.Handler;
-import android.util.Log;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.server.wifi.util.TimedQuotaManager;
-import com.android.wifi.resources.R;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.time.Duration;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Tracks state that decides if a link probe should be performed. If so, trigger a link probe to
- * evaluate connection quality.
- */
-public class LinkProbeManager {
- private static final String TAG = "WifiLinkProbeManager";
-
- private static final int WIFI_LINK_PROBING_ENABLED_DEFAULT = 1; // 1 = enabled
-
- // TODO(112029045): Use constants from ScoringParams instead
- @VisibleForTesting static final int RSSI_THRESHOLD = -70;
- @VisibleForTesting static final int LINK_SPEED_THRESHOLD_MBPS = 15; // in megabits per second
- /** Minimum delay before probing after the last probe. */
- @VisibleForTesting static final long DELAY_BETWEEN_PROBES_MS = 6000;
- /** Minimum delay before probing after screen turned on. */
- @VisibleForTesting static final long SCREEN_ON_DELAY_MS = 6000;
- /**
- * Minimum delay before probing after last increase of the Tx success counter (which indicates
- * that a data frame (i.e. not counting management frame) was successfully transmitted).
- */
- @VisibleForTesting static final long DELAY_AFTER_TX_SUCCESS_MS = 6000;
-
- @VisibleForTesting static final long MAX_PROBE_COUNT_IN_PERIOD =
- WifiMetrics.MAX_LINK_PROBE_STA_EVENTS;
- @VisibleForTesting static final long PERIOD_MILLIS = Duration.ofDays(1).toMillis();
-
- @VisibleForTesting static final int[] EXPERIMENT_DELAYS_MS = {3000, 6000, 9000, 12000, 15000};
- @VisibleForTesting static final int[] EXPERIMENT_RSSIS = {-65, -70, -75};
- @VisibleForTesting static final int[] EXPERIMENT_LINK_SPEEDS = {10, 15, 20};
- private List<Experiment> mExperiments = new ArrayList<>();
-
- private final Clock mClock;
- private final WifiNative mWifiNative;
- private final WifiMetrics mWifiMetrics;
- private final FrameworkFacade mFrameworkFacade;
- private final Handler mHandler;
- private final Context mContext;
-
- private Boolean mLinkProbingSupported = null;
-
- private boolean mVerboseLoggingEnabled = false;
-
- /**
- * Tracks the last timestamp when a link probe was triggered. Link probing only occurs when at
- * least {@link #DELAY_BETWEEN_PROBES_MS} has passed since the last link probe.
- */
- private long mLastLinkProbeTimestampMs;
- /**
- * Tracks the last timestamp when {@link WifiInfo#txSuccess} was increased i.e. the last time a
- * Tx was successful. Link probing only occurs when at least {@link #DELAY_AFTER_TX_SUCCESS_MS}
- * has passed since the last Tx success.
- * This is also reset to the current time when {@link #resetOnNewConnection()} is called, so
- * that a link probe only occurs at least {@link #DELAY_AFTER_TX_SUCCESS_MS} after a new
- * connection is made.
- */
- private long mLastTxSuccessIncreaseTimestampMs;
- /**
- * Stores the last value of {@link WifiInfo#txSuccess}. The current value of
- * {@link WifiInfo#txSuccess} is compared against the last value to determine whether there was
- * a successful Tx.
- */
- private long mLastTxSuccessCount;
- /**
- * Tracks the last timestamp when the screen turned on. Link probing only occurs when at least
- * {@link #SCREEN_ON_DELAY_MS} has passed since the last time the screen was turned on.
- */
- private long mLastScreenOnTimestampMs;
- private final TimedQuotaManager mTimedQuotaManager;
-
- public LinkProbeManager(Clock clock, WifiNative wifiNative, WifiMetrics wifiMetrics,
- FrameworkFacade frameworkFacade, Handler handler, Context context) {
- mClock = clock;
- mWifiNative = wifiNative;
- mWifiMetrics = wifiMetrics;
- mFrameworkFacade = frameworkFacade;
- mHandler = handler;
- mContext = context;
- mTimedQuotaManager = new TimedQuotaManager(clock, MAX_PROBE_COUNT_IN_PERIOD, PERIOD_MILLIS);
-
- initExperiments();
- }
-
- private boolean isLinkProbingSupported() {
- if (mLinkProbingSupported == null) {
- mLinkProbingSupported = mContext.getResources()
- .getBoolean(R.bool.config_wifi_link_probing_supported);
- if (mLinkProbingSupported) {
- resetOnNewConnection();
- resetOnScreenTurnedOn();
- }
- }
- return mLinkProbingSupported;
- }
-
- /** enables/disables wifi verbose logging */
- public void enableVerboseLogging(boolean enable) {
- mVerboseLoggingEnabled = enable;
- }
-
- /** dumps internal state */
- public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
- pw.println("Dump of LinkProbeManager");
- pw.println("LinkProbeManager - link probing supported by device: "
- + isLinkProbingSupported());
- pw.println("LinkProbeManager - mLastLinkProbeTimestampMs: " + mLastLinkProbeTimestampMs);
- pw.println("LinkProbeManager - mLastTxSuccessIncreaseTimestampMs: "
- + mLastTxSuccessIncreaseTimestampMs);
- pw.println("LinkProbeManager - mLastTxSuccessCount: " + mLastTxSuccessCount);
- pw.println("LinkProbeManager - mLastScreenOnTimestampMs: " + mLastScreenOnTimestampMs);
- pw.println("LinkProbeManager - mTimedQuotaManager: " + mTimedQuotaManager);
- }
-
- /**
- * When connecting to a new network, reset internal state.
- */
- public void resetOnNewConnection() {
- mExperiments.forEach(Experiment::resetOnNewConnection);
- if (!isLinkProbingSupported()) return;
-
- long now = mClock.getElapsedSinceBootMillis();
- mLastLinkProbeTimestampMs = now;
- mLastTxSuccessIncreaseTimestampMs = now;
- mLastTxSuccessCount = 0;
- }
-
- /**
- * When RSSI poll events are stopped and restarted (usually screen turned off then back on),
- * reset internal state.
- */
- public void resetOnScreenTurnedOn() {
- mExperiments.forEach(Experiment::resetOnScreenTurnedOn);
- if (!isLinkProbingSupported()) return;
-
- mLastScreenOnTimestampMs = mClock.getElapsedSinceBootMillis();
- }
-
- /**
- * Based on network conditions provided by WifiInfo, decides if a link probe should be
- * performed. If so, trigger a link probe and report the results to WifiMetrics.
- *
- * @param wifiInfo the updated WifiInfo
- * @param interfaceName the interface that the link probe should be performed on, if applicable.
- */
- public void updateConnectionStats(WifiInfo wifiInfo, String interfaceName) {
- mExperiments.forEach(e -> e.updateConnectionStats(wifiInfo));
-
- if (!isLinkProbingSupported()) return;
-
- long now = mClock.getElapsedSinceBootMillis();
-
- // at least 1 tx succeeded since last update
- if (mLastTxSuccessCount < wifiInfo.txSuccess) {
- mLastTxSuccessIncreaseTimestampMs = now;
- }
- mLastTxSuccessCount = wifiInfo.txSuccess;
-
- // maximum 1 link probe every DELAY_BETWEEN_PROBES_MS
- long timeSinceLastLinkProbeMs = now - mLastLinkProbeTimestampMs;
- if (timeSinceLastLinkProbeMs < DELAY_BETWEEN_PROBES_MS) {
- return;
- }
-
- // if tx succeeded at least once in the last DELAY_AFTER_TX_SUCCESS_MS, don't need to probe
- long timeSinceLastTxSuccessIncreaseMs = now - mLastTxSuccessIncreaseTimestampMs;
- if (timeSinceLastTxSuccessIncreaseMs < DELAY_AFTER_TX_SUCCESS_MS) {
- return;
- }
-
- // if not enough time has passed since the screen last turned on, don't probe
- long timeSinceLastScreenOnMs = now - mLastScreenOnTimestampMs;
- if (timeSinceLastScreenOnMs < SCREEN_ON_DELAY_MS) {
- return;
- }
-
- // can skip probing if RSSI is valid and high and link speed is fast
- int rssi = wifiInfo.getRssi();
- int linkSpeed = wifiInfo.getLinkSpeed();
- if (rssi != WifiInfo.INVALID_RSSI && rssi > RSSI_THRESHOLD
- && linkSpeed > LINK_SPEED_THRESHOLD_MBPS) {
- return;
- }
-
- if (!mTimedQuotaManager.requestQuota()) {
- return;
- }
-
- if (mVerboseLoggingEnabled) {
- Log.d(TAG, "link probing triggered with conditions: timeSinceLastLinkProbeMs="
- + timeSinceLastLinkProbeMs
- + " timeSinceLastTxSuccessIncreaseMs=" + timeSinceLastTxSuccessIncreaseMs
- + " rssi=" + rssi + " linkSpeed=" + linkSpeed);
- }
-
- // TODO(b/112029045): also report MCS rate to metrics when supported by driver
- mWifiNative.probeLink(
- interfaceName,
- MacAddress.fromString(wifiInfo.getBSSID()),
- new WifiNl80211Manager.SendMgmtFrameCallback() {
- @Override
- public void onAck(int elapsedTimeMs) {
- if (mVerboseLoggingEnabled) {
- Log.d(TAG, "link probing success, elapsedTimeMs="
- + elapsedTimeMs);
- }
- mWifiMetrics.logLinkProbeSuccess(interfaceName,
- timeSinceLastTxSuccessIncreaseMs, rssi, linkSpeed, elapsedTimeMs);
- }
-
- @Override
- public void onFailure(int reason) {
- if (mVerboseLoggingEnabled) {
- Log.d(TAG, "link probing failure, reason=" + reason);
- }
- mWifiMetrics.logLinkProbeFailure(interfaceName,
- timeSinceLastTxSuccessIncreaseMs, rssi, linkSpeed, reason);
- }
- },
- -1); // placeholder, lets driver determine MCS rate
- mLastLinkProbeTimestampMs = mClock.getElapsedSinceBootMillis();
- }
-
- private void initExperiments() {
- for (int delay : EXPERIMENT_DELAYS_MS) {
- for (int rssiThreshold : EXPERIMENT_RSSIS) {
- for (int linkSpeedThreshold: EXPERIMENT_LINK_SPEEDS) {
- Experiment experiment = new Experiment(mClock, mWifiMetrics,
- delay, delay, delay, rssiThreshold, linkSpeedThreshold);
- mExperiments.add(experiment);
- }
- }
- }
- }
-
- // TODO(b/131091030): remove once experiment is over
- private static class Experiment {
-
- private final Clock mClock;
- private final WifiMetrics mWifiMetrics;
- private final int mScreenOnDelayMs;
- private final int mNoTxDelayMs;
- private final int mDelayBetweenProbesMs;
- private final int mRssiThreshold;
- private final int mLinkSpeedThreshold;
- private final String mExperimentId;
-
- private long mLastLinkProbeTimestampMs;
- private long mLastTxSuccessIncreaseTimestampMs;
- private long mLastTxSuccessCount;
- private long mLastScreenOnTimestampMs;
-
- Experiment(Clock clock, WifiMetrics wifiMetrics,
- int screenOnDelayMs, int noTxDelayMs, int delayBetweenProbesMs,
- int rssiThreshold, int linkSpeedThreshold) {
- mClock = clock;
- mWifiMetrics = wifiMetrics;
- mScreenOnDelayMs = screenOnDelayMs;
- mNoTxDelayMs = noTxDelayMs;
- mDelayBetweenProbesMs = delayBetweenProbesMs;
- mRssiThreshold = rssiThreshold;
- mLinkSpeedThreshold = linkSpeedThreshold;
-
- mExperimentId = getExperimentId();
-
- resetOnNewConnection();
- resetOnScreenTurnedOn();
- }
-
- private String getExperimentId() {
- return "[screenOnDelay=" + mScreenOnDelayMs + ','
- + "noTxDelay=" + mNoTxDelayMs + ','
- + "delayBetweenProbes=" + mDelayBetweenProbesMs + ','
- + "rssiThreshold=" + mRssiThreshold + ','
- + "linkSpeedThreshold=" + mLinkSpeedThreshold + ']';
- }
-
- void resetOnNewConnection() {
- long now = mClock.getElapsedSinceBootMillis();
- mLastLinkProbeTimestampMs = now;
- mLastTxSuccessIncreaseTimestampMs = now;
- mLastTxSuccessCount = 0;
- }
-
- void resetOnScreenTurnedOn() {
- mLastScreenOnTimestampMs = mClock.getElapsedSinceBootMillis();
- }
-
- void updateConnectionStats(WifiInfo wifiInfo) {
- long now = mClock.getElapsedSinceBootMillis();
-
- if (mLastTxSuccessCount < wifiInfo.txSuccess) {
- mLastTxSuccessIncreaseTimestampMs = now;
- }
- mLastTxSuccessCount = wifiInfo.txSuccess;
-
- long timeSinceLastLinkProbeMs = now - mLastLinkProbeTimestampMs;
- if (timeSinceLastLinkProbeMs < mDelayBetweenProbesMs) {
- return;
- }
-
- // if tx succeeded at least once in the last LINK_PROBE_INTERVAL_MS, don't need to probe
- long timeSinceLastTxSuccessIncreaseMs = now - mLastTxSuccessIncreaseTimestampMs;
- if (timeSinceLastTxSuccessIncreaseMs < mNoTxDelayMs) {
- return;
- }
-
- long timeSinceLastScreenOnMs = now - mLastScreenOnTimestampMs;
- if (timeSinceLastScreenOnMs < SCREEN_ON_DELAY_MS) {
- return;
- }
-
- // can skip probing if RSSI is valid and high and link speed is fast
- int rssi = wifiInfo.getRssi();
- int linkSpeed = wifiInfo.getLinkSpeed();
- if (rssi != WifiInfo.INVALID_RSSI && rssi > mRssiThreshold
- && linkSpeed > mLinkSpeedThreshold) {
- return;
- }
-
- mWifiMetrics.incrementLinkProbeExperimentProbeCount(mExperimentId);
-
- mLastLinkProbeTimestampMs = mClock.getElapsedSinceBootMillis();
- }
- }
-}
diff --git a/service/java/com/android/server/wifi/MacAddressUtil.java b/service/java/com/android/server/wifi/MacAddressUtil.java
index 828227e604..2781105f38 100644
--- a/service/java/com/android/server/wifi/MacAddressUtil.java
+++ b/service/java/com/android/server/wifi/MacAddressUtil.java
@@ -115,7 +115,7 @@ public class MacAddressUtil {
/**
* calculate the persistent randomized MAC for SoftAp
*/
- public MacAddress calculatePersistentMacForSap(String key, int uid) {
+ public synchronized MacAddress calculatePersistentMacForSap(String key, int uid) {
if (key == null) {
return null;
}
diff --git a/service/java/com/android/server/wifi/MboOceController.java b/service/java/com/android/server/wifi/MboOceController.java
index ad8e770c6e..2b5e9102f2 100644
--- a/service/java/com/android/server/wifi/MboOceController.java
+++ b/service/java/com/android/server/wifi/MboOceController.java
@@ -128,7 +128,7 @@ public class MboOceController {
Log.d(TAG, "Cell Data: " + dataAvailable);
}
clientModeManager.setMboCellularDataStatus(dataAvailable);
- }
+ }, TAG + "#onDataConnectionStateChanged"
);
}
};
diff --git a/service/java/com/android/server/wifi/MultiInternetWifiNetworkFactory.java b/service/java/com/android/server/wifi/MultiInternetWifiNetworkFactory.java
index ac5cbe2fd3..cb149b7bc5 100644
--- a/service/java/com/android/server/wifi/MultiInternetWifiNetworkFactory.java
+++ b/service/java/com/android/server/wifi/MultiInternetWifiNetworkFactory.java
@@ -243,7 +243,6 @@ public class MultiInternetWifiNetworkFactory extends NetworkFactory {
+ " Uid " + state.networkRequest.getRequestorUid()
+ " PackageName " + state.networkRequest.getRequestorPackageName());
}
- mLocalLog.dump(fd, pw, args);
mMultiInternetManager.dump(fd, pw, args);
}
}
diff --git a/service/java/com/android/server/wifi/RssiMonitor.java b/service/java/com/android/server/wifi/RssiMonitor.java
index ff90819927..9e2867cbeb 100644
--- a/service/java/com/android/server/wifi/RssiMonitor.java
+++ b/service/java/com/android/server/wifi/RssiMonitor.java
@@ -81,9 +81,11 @@ public class RssiMonitor {
// the actions are same as calling handleRssiBreachRestartRssiMonitor(curRssi) directly.
if (mEnableClientRssiMonitor && curRssi
<= mWifiGlobals.getClientRssiMonitorThresholdDbm()) {
- mWifiThreadRunner.post(() -> processClientRssiThresholdBreached(curRssi));
+ mWifiThreadRunner.post(() -> processClientRssiThresholdBreached(curRssi),
+ TAG + "#processClientRssiThresholdBreached");
} else {
- mWifiThreadRunner.post(() -> handleRssiBreachRestartRssiMonitor(curRssi));
+ mWifiThreadRunner.post(() -> handleRssiBreachRestartRssiMonitor(curRssi),
+ TAG + "#handleRssiBreachRestartRssiMonitor");
}
}
}
diff --git a/service/java/com/android/server/wifi/RunnerHandler.java b/service/java/com/android/server/wifi/RunnerHandler.java
index 2456cf1986..78b7b12a4f 100644
--- a/service/java/com/android/server/wifi/RunnerHandler.java
+++ b/service/java/com/android/server/wifi/RunnerHandler.java
@@ -42,7 +42,7 @@ import java.util.Set;
public class RunnerHandler extends Handler {
private static final String TAG = "WifiThreadRunner";
- private static final String KEY_SIGNATURE = "KEY_RUNNER_HANDLER_SIGNATURE";
+ public static final String KEY_SIGNATURE = "KEY_RUNNER_HANDLER_SIGNATURE";
private static final String KEY_WHEN = "KEY_RUNNER_HANDLER_WHEN";
private static final int METRICS_THRESHOLD_MILLIS = 100;
@@ -101,10 +101,12 @@ public class RunnerHandler extends Handler {
@Override
public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
- String signature = getSignature(new Throwable("RunnerHandler:").getStackTrace(),
- msg.getCallback());
Bundle bundle = msg.getData();
- bundle.putString(KEY_SIGNATURE, signature);
+ if (bundle.getString(KEY_SIGNATURE) == null) {
+ String signature = getSignature(new Throwable("RunnerHandler:").getStackTrace(),
+ msg.getCallback());
+ bundle.putString(KEY_SIGNATURE, signature);
+ }
return super.sendMessageAtTime(msg, uptimeMillis);
}
diff --git a/service/java/com/android/server/wifi/RunnerState.java b/service/java/com/android/server/wifi/RunnerState.java
index 5dbe65c493..e6a8573826 100644
--- a/service/java/com/android/server/wifi/RunnerState.java
+++ b/service/java/com/android/server/wifi/RunnerState.java
@@ -62,7 +62,10 @@ public abstract class RunnerState extends State {
public boolean processMessage(Message message) {
long startTime = System.currentTimeMillis();
- String signatureToLog = getMessageLogRec(message.what);
+ String signatureToLog = getMessageLogRec(message);
+ if (signatureToLog == null) {
+ signatureToLog = getMessageLogRec(message.what);
+ }
Trace.traceBegin(Trace.TRACE_TAG_NETWORK, signatureToLog);
boolean ret = processMessageImpl(message);
Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
@@ -128,5 +131,15 @@ public abstract class RunnerState extends State {
* @param what message 'what' field
* @return Readable string
*/
- public abstract String getMessageLogRec(int what);
+ public String getMessageLogRec(int what) {
+ return null;
+ };
+
+ /**
+ * Implement this to translate a message into a readable String
+ * @return Readable string
+ */
+ public String getMessageLogRec(Message message) {
+ return null;
+ };
}
diff --git a/service/java/com/android/server/wifi/ScanDetail.java b/service/java/com/android/server/wifi/ScanDetail.java
index ccae57e244..59eb16af85 100644
--- a/service/java/com/android/server/wifi/ScanDetail.java
+++ b/service/java/com/android/server/wifi/ScanDetail.java
@@ -61,6 +61,7 @@ public class ScanDetail {
boolean isPasspoint = false;
boolean is80211McResponder = false;
boolean isTwtResponder = false;
+ boolean is11azNtbResponder = false;
if (networkDetail != null) {
hessid = networkDetail.getHESSID();
anqpDomainId = networkDetail.getAnqpDomainID();
@@ -75,6 +76,7 @@ public class ScanDetail {
&& networkDetail.getHSRelease() != null;
is80211McResponder = networkDetail.is80211McResponderSupport();
isTwtResponder = networkDetail.isIndividualTwtSupported();
+ is11azNtbResponder = networkDetail.is80211azNtbResponder();
}
sBuilder.clear();
mScanResult = sBuilder
@@ -88,6 +90,7 @@ public class ScanDetail {
.setFrequency(frequency)
.setTsf(tsf)
.setIsTwtResponder(isTwtResponder)
+ .setIs80211azNtbRTTResponder(is11azNtbResponder)
.build();
mSeen = System.currentTimeMillis();
mScanResult.seen = mSeen;
diff --git a/service/java/com/android/server/wifi/ScanRequestProxy.java b/service/java/com/android/server/wifi/ScanRequestProxy.java
index c5af30effe..e8651652a5 100644
--- a/service/java/com/android/server/wifi/ScanRequestProxy.java
+++ b/service/java/com/android/server/wifi/ScanRequestProxy.java
@@ -31,7 +31,6 @@ import android.net.wifi.WifiManager;
import android.net.wifi.WifiScanner;
import android.net.wifi.util.ScanResultUtil;
import android.os.Bundle;
-import android.os.Handler;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.UserHandle;
@@ -93,7 +92,7 @@ public class ScanRequestProxy {
public static final int PARTIAL_SCAN_CACHE_SIZE = 200;
private final Context mContext;
- private final Handler mHandler;
+ private final WifiThreadRunner mWifiThreadRunner;
private final AppOpsManager mAppOps;
private final ActivityManager mActivityManager;
private final WifiInjector mWifiInjector;
@@ -238,9 +237,9 @@ public class ScanRequestProxy {
ScanRequestProxy(Context context, AppOpsManager appOpsManager, ActivityManager activityManager,
WifiInjector wifiInjector, WifiConfigManager configManager,
WifiPermissionsUtil wifiPermissionUtil, WifiMetrics wifiMetrics, Clock clock,
- Handler handler, WifiSettingsConfigStore settingsConfigStore) {
+ WifiThreadRunner runner, WifiSettingsConfigStore settingsConfigStore) {
mContext = context;
- mHandler = handler;
+ mWifiThreadRunner = runner;
mAppOps = appOpsManager;
mActivityManager = activityManager;
mWifiInjector = wifiInjector;
@@ -280,7 +279,8 @@ public class ScanRequestProxy {
// Register the global scan listener.
if (mWifiScanner != null) {
mWifiScanner.registerScanListener(
- new WifiScannerInternal.ScanListener(new GlobalScanListener(), mHandler));
+ new WifiScannerInternal.ScanListener(new GlobalScanListener(),
+ mWifiThreadRunner));
}
}
return mWifiScanner != null;
@@ -558,7 +558,8 @@ public class ScanRequestProxy {
.retrieveHiddenNetworkList(false));
}
mWifiScanner.startScan(settings,
- new WifiScannerInternal.ScanListener(new ScanRequestProxyScanListener(), mHandler),
+ new WifiScannerInternal.ScanListener(new ScanRequestProxyScanListener(),
+ mWifiThreadRunner),
workSource);
return true;
}
diff --git a/service/java/com/android/server/wifi/SoftApManager.java b/service/java/com/android/server/wifi/SoftApManager.java
index 9e9f8126bb..a0ceb41f96 100644
--- a/service/java/com/android/server/wifi/SoftApManager.java
+++ b/service/java/com/android/server/wifi/SoftApManager.java
@@ -39,6 +39,7 @@ import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiScanner;
import android.net.wifi.WifiSsid;
+import android.net.wifi.nl80211.DeviceWiphyCapabilities;
import android.os.BatteryManager;
import android.os.Handler;
import android.os.Looper;
@@ -840,6 +841,9 @@ public class SoftApManager implements ActiveModeManager {
Log.d(getTag(), "startSoftAp: band " + mCurrentSoftApConfiguration.getBand());
}
+ updateApState(WifiManager.WIFI_AP_STATE_ENABLING,
+ WifiManager.WIFI_AP_STATE_DISABLED, 0);
+
int startResult = setMacAddress();
if (startResult != START_RESULT_SUCCESS) {
return startResult;
@@ -1039,9 +1043,7 @@ public class SoftApManager implements ActiveModeManager {
private final InterfaceCallback mWifiNativeInterfaceCallback = new InterfaceCallback() {
@Override
public void onDestroyed(String ifaceName) {
- if (mApInterfaceName != null && mApInterfaceName.equals(ifaceName)) {
- sendMessage(CMD_INTERFACE_DESTROYED);
- }
+ sendMessage(CMD_INTERFACE_DESTROYED, ifaceName);
}
@Override
@@ -1170,6 +1172,7 @@ public class SoftApManager implements ActiveModeManager {
break;
case CMD_START:
boolean isCountryCodeChanged = false;
+ boolean shouldwaitForDriverCountryCodeIfNoCountryToSet = false;
mRequestorWs = (WorkSource) message.obj;
WifiSsid wifiSsid = mCurrentSoftApConfiguration != null
? mCurrentSoftApConfiguration.getWifiSsid() : null;
@@ -1178,6 +1181,12 @@ public class SoftApManager implements ActiveModeManager {
handleStartSoftApFailure(START_RESULT_FAILURE_GENERAL);
break;
}
+ if (TextUtils.isEmpty(mCountryCode) && mContext.getResources().getBoolean(
+ R.bool.config_wifiDriverSupportedNl80211RegChangedEvent)) {
+ Log.i(getTag(), "No country code set in the framework."
+ + " Should Wait for driver country code update to start AP");
+ shouldwaitForDriverCountryCodeIfNoCountryToSet = true;
+ }
if (!TextUtils.isEmpty(mCountryCode)
&& !TextUtils.equals(
mCountryCode, mCurrentSoftApCapability.getCountryCode())) {
@@ -1304,16 +1313,6 @@ public class SoftApManager implements ActiveModeManager {
break;
}
- if (SdkLevel.isAtLeastT()
- && mCurrentSoftApConfiguration.isIeee80211beEnabled()
- && !mCurrentSoftApCapability.areFeaturesSupported(
- SoftApCapability.SOFTAP_FEATURE_IEEE80211_BE)) {
- Log.d(getTag(), "11BE is not supported, removing from configuration");
- mCurrentSoftApConfiguration = new SoftApConfiguration
- .Builder(mCurrentSoftApConfiguration)
- .setIeee80211beEnabled(false)
- .build();
- }
mApInterfaceName = mWifiNative.setupInterfaceForSoftApMode(
mWifiNativeInterfaceCallback, mRequestorWs,
mCurrentSoftApConfiguration.getBand(), isBridgeRequired(),
@@ -1329,14 +1328,31 @@ public class SoftApManager implements ActiveModeManager {
}
break;
}
+
+ if (SdkLevel.isAtLeastT()
+ && mCurrentSoftApConfiguration.isIeee80211beEnabled()) {
+ DeviceWiphyCapabilities capabilities =
+ mWifiNative.getDeviceWiphyCapabilities(
+ mApInterfaceName, isBridgeRequired());
+ if (!ApConfigUtil.is11beAllowedForThisConfiguration(capabilities,
+ mContext, mCurrentSoftApConfiguration, isBridgedMode())) {
+ Log.d(getTag(), "11BE is not allowed,"
+ + " removing from configuration");
+ mCurrentSoftApConfiguration = new SoftApConfiguration.Builder(
+ mCurrentSoftApConfiguration).setIeee80211beEnabled(
+ false).build();
+ }
+ }
+
mSoftApNotifier.dismissSoftApShutdownTimeoutExpiredNotification();
- updateApState(WifiManager.WIFI_AP_STATE_ENABLING,
- WifiManager.WIFI_AP_STATE_DISABLED, 0);
- if (!setCountryCode()) {
+
+ if (!shouldwaitForDriverCountryCodeIfNoCountryToSet && !setCountryCode()) {
handleStartSoftApFailure(START_RESULT_FAILURE_SET_COUNTRY_CODE);
break;
}
- if (isCountryCodeChanged) {
+ // Wait for driver country code if driver supports regulatory change event.
+ if (isCountryCodeChanged
+ || shouldwaitForDriverCountryCodeIfNoCountryToSet) {
Log.i(getTag(), "Need to wait for driver country code update before"
+ " starting");
transitionTo(mWaitingForDriverCountryCodeChangedState);
@@ -1410,12 +1426,14 @@ public class SoftApManager implements ActiveModeManager {
@Override
public boolean processMessageImpl(Message message) {
if (message.what == CMD_DRIVER_COUNTRY_CODE_CHANGED) {
- if (!TextUtils.equals(mCountryCode, (String) message.obj)) {
+ if (!TextUtils.isEmpty(mCountryCode)
+ && !TextUtils.equals(mCountryCode, (String) message.obj)) {
Log.i(getTag(), "Ignore country code changed: " + message.obj);
return HANDLED;
}
Log.i(getTag(), "Driver country code change to " + message.obj
+ ", continue starting.");
+ mCountryCode = (String) message.obj;
mCurrentSoftApCapability.setCountryCode(mCountryCode);
mCurrentSoftApCapability =
ApConfigUtil.updateSoftApCapabilityWithAvailableChannelList(
@@ -2017,7 +2035,17 @@ public class SoftApManager implements ActiveModeManager {
removeIfaceInstanceFromBridgedApIface(idleInstance);
break;
case CMD_INTERFACE_DESTROYED:
- Log.d(getTag(), "Interface was cleanly destroyed.");
+ String ifaceName = (String) message.obj;
+ Log.d(getTag(), "Interface: " + ifaceName + " was cleanly destroyed.");
+ if (mApInterfaceName == null) {
+ Log.e(getTag(), "softAp interface is null"
+ + " - Drop interface destroyed message");
+ break;
+ }
+ if (!mApInterfaceName.equals(ifaceName)) {
+ Log.d(getTag(), "Drop stale interface destroyed message");
+ break;
+ }
updateApState(WifiManager.WIFI_AP_STATE_DISABLING,
WifiManager.WIFI_AP_STATE_ENABLED, 0);
mIfaceIsDestroyed = true;
diff --git a/service/java/com/android/server/wifi/SupplicantStaIfaceHal.java b/service/java/com/android/server/wifi/SupplicantStaIfaceHal.java
index 302053b9e0..eb6f4609df 100644
--- a/service/java/com/android/server/wifi/SupplicantStaIfaceHal.java
+++ b/service/java/com/android/server/wifi/SupplicantStaIfaceHal.java
@@ -2383,6 +2383,18 @@ public class SupplicantStaIfaceHal {
}
/**
+ * See comments for {@link ISupplicantStaIfaceHal#resendMscs(String)}
+ */
+ public void resendMscs(String ifaceName) {
+ String methodStr = "resendMscs";
+ if (mStaIfaceHal == null) {
+ handleNullHal(methodStr);
+ return;
+ }
+ mStaIfaceHal.resendMscs(ifaceName);
+ }
+
+ /**
* See comments for {@link ISupplicantStaIfaceHal#disableMscs(String)}
*/
public void disableMscs(String ifaceName) {
diff --git a/service/java/com/android/server/wifi/SupplicantStaIfaceHalAidlImpl.java b/service/java/com/android/server/wifi/SupplicantStaIfaceHalAidlImpl.java
index 7722e4accb..1bcf4b742d 100644
--- a/service/java/com/android/server/wifi/SupplicantStaIfaceHalAidlImpl.java
+++ b/service/java/com/android/server/wifi/SupplicantStaIfaceHalAidlImpl.java
@@ -106,7 +106,9 @@ import com.android.server.wifi.util.NativeUtil;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
+import java.util.ArrayDeque;
import java.util.ArrayList;
+import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -152,7 +154,8 @@ public class SupplicantStaIfaceHalAidlImpl implements ISupplicantStaIfaceHal {
private Map<String, SupplicantStaNetworkHalAidlImpl>
mCurrentNetworkRemoteHandles = new HashMap<>();
private Map<String, WifiConfiguration> mCurrentNetworkLocalConfigs = new HashMap<>();
- private Map<String, WifiSsid> mCurrentNetworkFallbackSsids = new HashMap<>();
+ private Map<String, Deque<WifiSsid>> mCurrentNetworkFallbackSsids = new HashMap<>();
+ private Map<String, WifiSsid> mCurrentNetworkFirstSsid = new HashMap<>();
private Map<String, List<Pair<SupplicantStaNetworkHalAidlImpl, WifiConfiguration>>>
mLinkedNetworkLocalAndRemoteConfigs = new HashMap<>();
@VisibleForTesting
@@ -171,6 +174,7 @@ public class SupplicantStaIfaceHalAidlImpl implements ISupplicantStaIfaceHal {
private CountDownLatch mWaitForDeathLatch;
private INonStandardCertCallback mNonStandardCertCallback;
private SupplicantStaIfaceHal.QosScsResponseCallback mQosScsResponseCallback;
+ private MscsParams mLastMscsParams;
private class SupplicantDeathRecipient implements DeathRecipient {
@Override
@@ -638,18 +642,24 @@ public class SupplicantStaIfaceHalAidlImpl implements ISupplicantStaIfaceHal {
}
/**
- * Connects to the fallback SSID (if any) of the current network upon a network not found
- * notification.
+ * Connects to the next fallback SSID (if any) of the current network upon a network not found
+ * notification. If all the fallback SSIDs have been tried, return to the first SSID and go
+ * through the fallbacks again.
+ *
+ * Returns false if there's no fallback SSID to connect to, or if we've wrapped back to the
+ * first SSID.
*/
public boolean connectToFallbackSsid(@NonNull String ifaceName) {
synchronized (mLock) {
- WifiSsid fallbackSsid = mCurrentNetworkFallbackSsids.remove(ifaceName);
- if (fallbackSsid == null) {
+ Deque<WifiSsid> fallbackSsids = mCurrentNetworkFallbackSsids.get(ifaceName);
+ if (fallbackSsids == null || fallbackSsids.isEmpty()) {
return false;
}
- Log.d(TAG, "connectToFallbackSsid " + fallbackSsid);
- return connectToNetwork(
- ifaceName, getCurrentNetworkLocalConfig(ifaceName), fallbackSsid);
+ WifiSsid nextSsid = fallbackSsids.removeFirst();
+ fallbackSsids.addLast(nextSsid);
+ Log.d(TAG, "connectToFallbackSsid " + nextSsid);
+ connectToNetwork(ifaceName, getCurrentNetworkLocalConfig(ifaceName), nextSsid);
+ return !Objects.equals(nextSsid, mCurrentNetworkFirstSsid.get(ifaceName));
}
}
@@ -696,7 +706,6 @@ public class SupplicantStaIfaceHalAidlImpl implements ISupplicantStaIfaceHal {
mCurrentNetworkRemoteHandles.remove(ifaceName);
mCurrentNetworkLocalConfigs.remove(ifaceName);
mLinkedNetworkLocalAndRemoteConfigs.remove(ifaceName);
- mCurrentNetworkFallbackSsids.remove(ifaceName);
if (!removeAllNetworks(ifaceName)) {
Log.e(TAG, "Failed to remove existing networks");
return false;
@@ -705,25 +714,27 @@ public class SupplicantStaIfaceHalAidlImpl implements ISupplicantStaIfaceHal {
if (actualSsid != null) {
supplicantConfig.SSID = actualSsid.toString();
} else {
+ mCurrentNetworkFallbackSsids.remove(ifaceName);
+ mCurrentNetworkFirstSsid.remove(ifaceName);
if (config.SSID != null) {
// No actual SSID supplied, so select from the network selection BSSID
// or the latest candidate BSSID.
WifiSsid configSsid = WifiSsid.fromString(config.SSID);
WifiSsid supplicantSsid = mSsidTranslator.getOriginalSsid(config);
if (supplicantSsid != null) {
+ Log.d(TAG, "Selecting supplicant SSID " + supplicantSsid);
supplicantConfig.SSID = supplicantSsid.toString();
- List<WifiSsid> allPossibleSsids = mSsidTranslator
- .getAllPossibleOriginalSsids(configSsid);
- WifiSsid selectedSsid = mSsidTranslator.getOriginalSsid(config);
- allPossibleSsids.remove(selectedSsid);
- if (!allPossibleSsids.isEmpty()) {
- // Store the unused SSID to fallback on in
+
+ Deque<WifiSsid> fallbackSsids = new ArrayDeque<>(mSsidTranslator
+ .getAllPossibleOriginalSsids(configSsid));
+ fallbackSsids.remove(supplicantSsid);
+ if (!fallbackSsids.isEmpty()) {
+ // Store the unused SSIDs to fallback on in
// connectToFallbackSsid(String) if the chosen SSID isn't found.
- mCurrentNetworkFallbackSsids.put(
- ifaceName, allPossibleSsids.get(0));
+ fallbackSsids.addLast(supplicantSsid);
+ mCurrentNetworkFallbackSsids.put(ifaceName, fallbackSsids);
+ mCurrentNetworkFirstSsid.put(ifaceName, supplicantSsid);
}
- Log.d(TAG, "Selecting supplicant SSID " + supplicantSsid);
- supplicantConfig.SSID = supplicantSsid.toString();
}
// Set the actual translation of the original SSID in case the untranslated
// SSID has an ambiguous encoding.
@@ -3919,7 +3930,32 @@ public class SupplicantStaIfaceHalAidlImpl implements ISupplicantStaIfaceHal {
if (!isServiceVersionAtLeast(3)) {
return;
}
- String methodStr = "enableMscs";
+ configureMscsInternal(mscsParams, ifaceName);
+ mLastMscsParams = mscsParams;
+ }
+ }
+
+ /**
+ * See comments for {@link ISupplicantStaIfaceHal#resendMscs(String)}
+ */
+ public void resendMscs(String ifaceName) {
+ synchronized (mLock) {
+ if (!isServiceVersionAtLeast(3)) {
+ return;
+ }
+ if (mLastMscsParams == null) {
+ return;
+ }
+ configureMscsInternal(mLastMscsParams, ifaceName);
+ }
+ }
+
+ private void configureMscsInternal(@NonNull MscsParams mscsParams, String ifaceName) {
+ synchronized (mLock) {
+ if (!isServiceVersionAtLeast(3)) {
+ return;
+ }
+ String methodStr = "configureMscsInternal";
ISupplicantStaIface iface = checkStaIfaceAndLogFailure(ifaceName, methodStr);
if (iface == null) {
return;
@@ -3945,6 +3981,7 @@ public class SupplicantStaIfaceHalAidlImpl implements ISupplicantStaIfaceHal {
return;
}
String methodStr = "disableMscs";
+ mLastMscsParams = null;
ISupplicantStaIface iface = checkStaIfaceAndLogFailure(ifaceName, methodStr);
if (iface == null) {
return;
diff --git a/service/java/com/android/server/wifi/SupplicantStaIfaceHalHidlImpl.java b/service/java/com/android/server/wifi/SupplicantStaIfaceHalHidlImpl.java
index 5a431b7e38..fbd031259d 100644
--- a/service/java/com/android/server/wifi/SupplicantStaIfaceHalHidlImpl.java
+++ b/service/java/com/android/server/wifi/SupplicantStaIfaceHalHidlImpl.java
@@ -73,7 +73,9 @@ import com.android.server.wifi.util.NativeUtil;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
+import java.util.ArrayDeque;
import java.util.ArrayList;
+import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -119,7 +121,8 @@ public class SupplicantStaIfaceHalHidlImpl implements ISupplicantStaIfaceHal {
private Map<String, SupplicantStaNetworkHalHidlImpl> mCurrentNetworkRemoteHandles =
new HashMap<>();
private Map<String, WifiConfiguration> mCurrentNetworkLocalConfigs = new HashMap<>();
- private Map<String, WifiSsid> mCurrentNetworkFallbackSsids = new HashMap<>();
+ private Map<String, Deque<WifiSsid>> mCurrentNetworkFallbackSsids = new HashMap<>();
+ private Map<String, WifiSsid> mCurrentNetworkFirstSsid = new HashMap<>();
private Map<String, List<Pair<SupplicantStaNetworkHalHidlImpl, WifiConfiguration>>>
mLinkedNetworkLocalAndRemoteConfigs = new HashMap<>();
@VisibleForTesting
@@ -973,18 +976,24 @@ public class SupplicantStaIfaceHalHidlImpl implements ISupplicantStaIfaceHal {
}
/**
- * Connects to the fallback SSID (if any) of the current network upon a network not found
- * notification.
+ * Connects to the next fallback SSID (if any) of the current network upon a network not found
+ * notification. If all the fallback SSIDs have been tried, return to the first SSID and go
+ * through the fallbacks again.
+ *
+ * Returns false if there's no fallback SSID to connect to, or if we've wrapped back to the
+ * first SSID.
*/
public boolean connectToFallbackSsid(@NonNull String ifaceName) {
synchronized (mLock) {
- WifiSsid fallbackSsid = mCurrentNetworkFallbackSsids.remove(ifaceName);
- if (fallbackSsid == null) {
+ Deque<WifiSsid> fallbackSsids = mCurrentNetworkFallbackSsids.get(ifaceName);
+ if (fallbackSsids == null || fallbackSsids.isEmpty()) {
return false;
}
- Log.d(TAG, "connectToFallbackSsid " + fallbackSsid);
- return connectToNetwork(
- ifaceName, getCurrentNetworkLocalConfig(ifaceName), fallbackSsid);
+ WifiSsid nextSsid = fallbackSsids.removeFirst();
+ fallbackSsids.addLast(nextSsid);
+ Log.d(TAG, "connectToFallbackSsid " + nextSsid);
+ connectToNetwork(ifaceName, getCurrentNetworkLocalConfig(ifaceName), nextSsid);
+ return !Objects.equals(nextSsid, mCurrentNetworkFirstSsid.get(ifaceName));
}
}
@@ -1031,7 +1040,6 @@ public class SupplicantStaIfaceHalHidlImpl implements ISupplicantStaIfaceHal {
mCurrentNetworkRemoteHandles.remove(ifaceName);
mCurrentNetworkLocalConfigs.remove(ifaceName);
mLinkedNetworkLocalAndRemoteConfigs.remove(ifaceName);
- mCurrentNetworkFallbackSsids.remove(ifaceName);
if (!removeAllNetworks(ifaceName)) {
loge("Failed to remove existing networks");
return false;
@@ -1040,25 +1048,27 @@ public class SupplicantStaIfaceHalHidlImpl implements ISupplicantStaIfaceHal {
if (actualSsid != null) {
supplicantConfig.SSID = actualSsid.toString();
} else {
+ mCurrentNetworkFallbackSsids.remove(ifaceName);
+ mCurrentNetworkFirstSsid.remove(ifaceName);
if (config.SSID != null) {
// No actual SSID supplied, so select from the network selection BSSID
// or the latest candidate BSSID.
WifiSsid configSsid = WifiSsid.fromString(config.SSID);
WifiSsid supplicantSsid = mSsidTranslator.getOriginalSsid(config);
if (supplicantSsid != null) {
+ Log.d(TAG, "Selecting supplicant SSID " + supplicantSsid);
supplicantConfig.SSID = supplicantSsid.toString();
- List<WifiSsid> allPossibleSsids = mSsidTranslator
- .getAllPossibleOriginalSsids(configSsid);
- WifiSsid selectedSsid = mSsidTranslator.getOriginalSsid(config);
- allPossibleSsids.remove(selectedSsid);
- if (!allPossibleSsids.isEmpty()) {
- // Store the unused SSID to fallback on in
+
+ Deque<WifiSsid> fallbackSsids = new ArrayDeque<>(mSsidTranslator
+ .getAllPossibleOriginalSsids(configSsid));
+ fallbackSsids.remove(supplicantSsid);
+ if (!fallbackSsids.isEmpty()) {
+ // Store the unused SSIDs to fallback on in
// connectToFallbackSsid(String) if the chosen SSID isn't found.
- mCurrentNetworkFallbackSsids.put(
- ifaceName, allPossibleSsids.get(0));
+ fallbackSsids.addLast(supplicantSsid);
+ mCurrentNetworkFallbackSsids.put(ifaceName, fallbackSsids);
+ mCurrentNetworkFirstSsid.put(ifaceName, supplicantSsid);
}
- Log.d(TAG, "Selecting supplicant SSID " + supplicantSsid);
- supplicantConfig.SSID = supplicantSsid.toString();
}
// Set the actual translation of the original SSID in case the untranslated
// SSID has an ambiguous encoding.
diff --git a/service/java/com/android/server/wifi/SupplicantStaNetworkCallbackAidlImpl.java b/service/java/com/android/server/wifi/SupplicantStaNetworkCallbackAidlImpl.java
index 21d3426f56..219c716a22 100644
--- a/service/java/com/android/server/wifi/SupplicantStaNetworkCallbackAidlImpl.java
+++ b/service/java/com/android/server/wifi/SupplicantStaNetworkCallbackAidlImpl.java
@@ -177,7 +177,7 @@ class SupplicantStaNetworkCallbackAidlImpl extends ISupplicantStaNetworkCallback
return;
}
String certHash = byteArrayToString(certHashBytes);
- if (null == subject) {
+ if (null == certHash) {
mNetworkHal.logCallback(
"onServerCertificateAvailable: cannot convert cert hash bytes to string.");
return;
diff --git a/service/java/com/android/server/wifi/TwtManager.java b/service/java/com/android/server/wifi/TwtManager.java
index 27a8c84290..2d1333ffe1 100644
--- a/service/java/com/android/server/wifi/TwtManager.java
+++ b/service/java/com/android/server/wifi/TwtManager.java
@@ -18,6 +18,7 @@ package com.android.server.wifi;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.AlarmManager;
+import android.net.MacAddress;
import android.net.wifi.ITwtCallback;
import android.net.wifi.ITwtCapabilitiesListener;
import android.net.wifi.ITwtStatsListener;
@@ -31,9 +32,12 @@ import android.os.Handler;
import android.os.IBinder;
import android.os.IInterface;
import android.os.RemoteException;
+import android.util.ArraySet;
import android.util.Log;
import android.util.SparseArray;
+import com.android.wifi.resources.R;
+
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
@@ -92,12 +96,13 @@ class TwtManager {
private final Clock mClock;
private final AlarmManager mAlarmManager;
private final Handler mHandler;
-
+ ArraySet<Integer> mBlockedOuiSet = new ArraySet<>();
private final WifiNative mWifiNative;
private final WifiNativeTwtEvents mWifiNativeTwtEvents;
private final AlarmManager.OnAlarmListener mTimeoutListener = () -> {
startGarbageCollector();
};
+ private final WifiInjector mWifiInjector;
/**
* Whenever primary clientModeManager identified by the interface name gets disconnected, reset
@@ -116,6 +121,7 @@ class TwtManager {
TwtManager(@NonNull WifiInjector wifiInjector, @NonNull ClientModeImplMonitor cmiMonitor,
@NonNull WifiNative wifiNative, @NonNull Handler handler, @NonNull Clock clock,
int maxSessions, int startOffset) {
+ mWifiInjector = wifiInjector;
mAlarmManager = wifiInjector.getAlarmManager();
mHandler = handler;
mClock = clock;
@@ -125,6 +131,13 @@ class TwtManager {
mWifiNative = wifiNative;
mWifiNativeTwtEvents = new WifiNativeTwtEvents();
cmiMonitor.registerListener(new ClientModeImplListenerInternal());
+ int[] ouis = wifiInjector.getContext().getResources().getIntArray(
+ R.array.config_wifiTwtBlockedOuiList);
+ if (ouis != null) {
+ for (int oui : ouis) {
+ mBlockedOuiSet.add(oui);
+ }
+ }
}
/**
@@ -471,7 +484,7 @@ class TwtManager {
public void getTwtCapabilities(@Nullable String interfaceName,
@NonNull ITwtCapabilitiesListener listener) {
try {
- if (interfaceName == null) {
+ if (interfaceName == null || !isTwtSupported()) {
listener.onResult(getDefaultTwtCapabilities());
return;
}
@@ -490,9 +503,20 @@ class TwtManager {
* @param twtRequest TWT request parameters
* @param iTwtCallback Callback for the TWT setup command
* @param callingUid Caller UID
+ * @param bssid BSSID
*/
public void setupTwtSession(@Nullable String interfaceName, @NonNull TwtRequest twtRequest,
- @NonNull ITwtCallback iTwtCallback, int callingUid) {
+ @NonNull ITwtCallback iTwtCallback, int callingUid, @NonNull String bssid) {
+ if (!isTwtSupported() || !isTwtCapable(interfaceName)) {
+ notifyFailure(iTwtCallback, CallbackType.SETUP,
+ TwtSessionCallback.TWT_ERROR_CODE_NOT_SUPPORTED);
+ return;
+ }
+ if (isOuiBlockListed(bssid)) {
+ notifyFailure(iTwtCallback, CallbackType.SETUP,
+ TwtSessionCallback.TWT_ERROR_CODE_AP_OUI_BLOCKLISTED);
+ return;
+ }
if (!registerInterface(interfaceName)) {
notifyFailure(iTwtCallback, CallbackType.SETUP,
TwtSessionCallback.TWT_ERROR_CODE_NOT_AVAILABLE);
@@ -509,6 +533,25 @@ class TwtManager {
}
}
+ private boolean isTwtSupported() {
+ return mWifiInjector.getContext().getResources().getBoolean(
+ R.bool.config_wifiTwtSupported);
+ }
+
+ private boolean isTwtCapable(String interfaceName) {
+ if (interfaceName == null) return false;
+ Bundle twtCapabilities = mWifiNative.getTwtCapabilities(interfaceName);
+ if (twtCapabilities == null) return false;
+ return twtCapabilities.getBoolean(WifiManager.TWT_CAPABILITIES_KEY_BOOLEAN_TWT_REQUESTER);
+ }
+
+ private boolean isOuiBlockListed(@NonNull String bssid) {
+ if (mBlockedOuiSet.isEmpty()) return false;
+ byte[] macBytes = MacAddress.fromString(bssid).toByteArray();
+ int oui = (macBytes[0] & 0xFF) << 16 | (macBytes[1] & 0xFF) << 8 | (macBytes[2] & 0xFF);
+ return mBlockedOuiSet.contains(oui);
+ }
+
/**
* Teardown the TWT session
*
diff --git a/service/java/com/android/server/wifi/WakeupController.java b/service/java/com/android/server/wifi/WakeupController.java
index 445984226a..8b0a698eb9 100644
--- a/service/java/com/android/server/wifi/WakeupController.java
+++ b/service/java/com/android/server/wifi/WakeupController.java
@@ -211,7 +211,7 @@ public class WakeupController {
if (mIsActive != isActive) {
Log.d(TAG, "Setting active to " + isActive);
mIsActive = isActive;
- mWifiConfigManager.saveToStore(false /* forceWrite */);
+ mWifiConfigManager.saveToStore();
}
}
@@ -285,6 +285,11 @@ public class WakeupController {
*/
public void start() {
Log.d(TAG, "start()");
+ // If already active, we don't want to restart the session, so return early.
+ if (mIsActive) {
+ mWifiWakeMetrics.recordIgnoredStart();
+ return;
+ }
if (getGoodSavedNetworksAndSuggestions().isEmpty()) {
Log.i(TAG, "Ignore wakeup start since there are no good networks.");
return;
@@ -292,11 +297,6 @@ public class WakeupController {
mWifiInjector.getWifiScanner().registerScanListener(
new HandlerExecutor(mHandler), mScanListener);
- // If already active, we don't want to restart the session, so return early.
- if (mIsActive) {
- mWifiWakeMetrics.recordIgnoredStart();
- return;
- }
setActive(true);
// ensure feature is enabled and store data has been read before performing work
@@ -423,7 +423,7 @@ public class WakeupController {
* @param scanResults The scan results with which to update the controller
*/
private void handleScanResults(Collection<ScanResult> scanResults) {
- if (!isEnabledAndReady()) {
+ if (!isEnabledAndReady() || !mIsActive) {
Log.d(TAG, "Attempted to handleScanResults while not enabled");
return;
}
@@ -486,16 +486,14 @@ public class WakeupController {
}
/**
- * Whether the feature is currently enabled.
+ * Whether the feature is currently enabled and usable.
*
- * <p>This method checks both the Settings value and the store data to ensure that it has been
+ * <p>This method checks both the Settings values and the store data to ensure that it has been
* read.
*/
@VisibleForTesting
boolean isEnabledAndReady() {
- synchronized (mLock) {
- return mWifiWakeupEnabled && mWakeupConfigStoreData.hasBeenRead();
- }
+ return isUsable() && mWakeupConfigStoreData.hasBeenRead();
}
/** Dumps wakeup controller state. */
diff --git a/service/java/com/android/server/wifi/WakeupLock.java b/service/java/com/android/server/wifi/WakeupLock.java
index 3a1d097fc2..672632f6a6 100644
--- a/service/java/com/android/server/wifi/WakeupLock.java
+++ b/service/java/com/android/server/wifi/WakeupLock.java
@@ -79,7 +79,7 @@ public class WakeupLock {
Log.d(TAG, "Lock set. Number of networks: " + mLockedNetworks.size());
- mWifiConfigManager.saveToStore(false /* forceWrite */);
+ mWifiConfigManager.saveToStore();
}
/**
@@ -160,7 +160,7 @@ public class WakeupLock {
}
if (hasChanged) {
- mWifiConfigManager.saveToStore(false /* forceWrite */);
+ mWifiConfigManager.saveToStore();
}
// Set initialized if the lock has handled enough scans, and log the event
@@ -206,7 +206,7 @@ public class WakeupLock {
}
if (hasChanged) {
- mWifiConfigManager.saveToStore(false /* forceWrite */);
+ mWifiConfigManager.saveToStore();
}
if (isUnlocked()) {
diff --git a/service/java/com/android/server/wifi/WakeupOnboarding.java b/service/java/com/android/server/wifi/WakeupOnboarding.java
index f08e2f3703..331fc975ee 100644
--- a/service/java/com/android/server/wifi/WakeupOnboarding.java
+++ b/service/java/com/android/server/wifi/WakeupOnboarding.java
@@ -146,7 +146,7 @@ public class WakeupOnboarding {
if (mTotalNotificationsShown >= NOTIFICATIONS_UNTIL_ONBOARDED) {
setOnboarded();
} else {
- mWifiConfigManager.saveToStore(false /* forceWrite */);
+ mWifiConfigManager.saveToStore();
}
}
@@ -185,7 +185,7 @@ public class WakeupOnboarding {
}
Log.d(TAG, "Setting user as onboarded.");
mIsOnboarded = true;
- mWifiConfigManager.saveToStore(false /* forceWrite */);
+ mWifiConfigManager.saveToStore();
}
/** Returns the {@link WakeupConfigStoreData.DataSource} for the onboarded status. */
diff --git a/service/java/com/android/server/wifi/WifiApConfigStore.java b/service/java/com/android/server/wifi/WifiApConfigStore.java
index b5546a234c..f4d062279b 100644
--- a/service/java/com/android/server/wifi/WifiApConfigStore.java
+++ b/service/java/com/android/server/wifi/WifiApConfigStore.java
@@ -21,6 +21,8 @@ import static android.net.wifi.SoftApConfiguration.SECURITY_TYPE_WPA3_OWE_TRANSI
import static android.net.wifi.SoftApConfiguration.SECURITY_TYPE_WPA3_SAE;
import static android.net.wifi.SoftApConfiguration.SECURITY_TYPE_WPA3_SAE_TRANSITION;
+import static com.android.server.wifi.WifiSettingsConfigStore.WIFI_STATIC_CHIP_INFO;
+
import android.annotation.NonNull;
import android.app.compat.CompatChanges;
import android.content.Context;
@@ -85,6 +87,8 @@ public class WifiApConfigStore {
private final WifiConfigManager mWifiConfigManager;
private final ActiveModeWarden mActiveModeWarden;
private final WifiNative mWifiNative;
+ private final HalDeviceManager mHalDeviceManager;
+ private final WifiSettingsConfigStore mWifiSettingsConfigStore;
private boolean mHasNewDataToSerialize = false;
private boolean mForceApChannel = false;
private int mForcedApBand;
@@ -145,6 +149,26 @@ public class WifiApConfigStore {
mMacAddressUtil = wifiInjector.getMacAddressUtil();
mIsAutoAppendLowerBandEnabled = mContext.getResources().getBoolean(
R.bool.config_wifiSoftapAutoAppendLowerBandsToBandConfigurationEnabled);
+ mHalDeviceManager = wifiInjector.getHalDeviceManager();
+ mWifiSettingsConfigStore = wifiInjector.getSettingsConfigStore();
+ mWifiSettingsConfigStore.registerChangeListener(WIFI_STATIC_CHIP_INFO,
+ (key, value) -> {
+ if (mPersistentWifiApConfig != null
+ && mHalDeviceManager.isConcurrencyComboLoadedFromDriver()) {
+ Log.i(TAG, "Chip capability is updated, check config");
+ SoftApConfiguration.Builder configBuilder =
+ new SoftApConfiguration.Builder(mPersistentWifiApConfig);
+ if (SdkLevel.isAtLeastS()
+ && mPersistentWifiApConfig.getBands().length > 1) {
+ // Current band setting is dual band, check if device supports it.
+ if (!ApConfigUtil.isBridgedModeSupported(mContext, mWifiNative)) {
+ Log.i(TAG, "Chip doesn't support bridgedAp, reset to default band");
+ configBuilder.setBand(generateDefaultBand(mContext));
+ persistConfigAndTriggerBackupManagerProxy(configBuilder.build());
+ }
+ }
+ }
+ }, mHandler);
}
/**
@@ -388,7 +412,7 @@ public class WifiApConfigStore {
mLastConfiguredPassphrase = config.getPassphrase();
}
mHasNewDataToSerialize = true;
- mHandler.post(() -> mWifiConfigManager.saveToStore(true));
+ mHandler.post(() -> mWifiConfigManager.saveToStore());
mBackupManagerProxy.notifyDataChanged();
}
@@ -418,8 +442,11 @@ public class WifiApConfigStore {
// It is new overlay configuration, it should always false in R. Add SdkLevel.isAtLeastS for
// lint check
- if (ApConfigUtil.isBridgedModeSupported(mContext, mWifiNative)) {
- if (SdkLevel.isAtLeastS()) {
+ if (SdkLevel.isAtLeastS()) {
+ boolean isBridgedModeSupported = mHalDeviceManager.isConcurrencyComboLoadedFromDriver()
+ ? ApConfigUtil.isBridgedModeSupported(mContext, mWifiNative)
+ : ApConfigUtil.isBridgedModeSupportedInConfig(mContext);
+ if (isBridgedModeSupported) {
int[] dual_bands = new int[] {
SoftApConfiguration.BAND_2GHZ,
SoftApConfiguration.BAND_2GHZ | SoftApConfiguration.BAND_5GHZ};
diff --git a/service/java/com/android/server/wifi/WifiBlocklistMonitor.java b/service/java/com/android/server/wifi/WifiBlocklistMonitor.java
index adf313da24..179f7f32c0 100644
--- a/service/java/com/android/server/wifi/WifiBlocklistMonitor.java
+++ b/service/java/com/android/server/wifi/WifiBlocklistMonitor.java
@@ -20,6 +20,7 @@ import static android.net.wifi.WifiConfiguration.NetworkSelectionStatus.DISABLE_
import android.annotation.IntDef;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
@@ -279,12 +280,14 @@ public class WifiBlocklistMonitor {
*/
private long getBlocklistDurationWithExponentialBackoff(int failureStreak,
int baseBlocklistDurationMs) {
+ long disableDurationMs = baseBlocklistDurationMs;
failureStreak = Math.min(failureStreak, mContext.getResources().getInteger(
R.integer.config_wifiBssidBlocklistMonitorFailureStreakCap));
- if (failureStreak < 1) {
- return baseBlocklistDurationMs;
+ if (failureStreak >= 1) {
+ disableDurationMs =
+ (long) (Math.pow(2.0, (double) failureStreak) * baseBlocklistDurationMs);
}
- return (long) (Math.pow(2.0, (double) failureStreak) * baseBlocklistDurationMs);
+ return Math.min(disableDurationMs, mWifiGlobals.getWifiConfigMaxDisableDurationMs());
}
/**
@@ -887,6 +890,23 @@ public class WifiBlocklistMonitor {
}
/**
+ * Gets the currently blocked BSSIDs without causing any updates.
+ * @param ssids The set of SSIDs to get blocked BSSID for, or null to get this information for
+ * all SSIDs.
+ * @return The list of currently blocked BSSIDs.
+ */
+ public List<String> getBssidBlocklistForSsids(@Nullable Set<String> ssids) {
+ List<String> results = new ArrayList<>();
+ for (Map.Entry<String, BssidStatus> entryMap : mBssidStatusMap.entrySet()) {
+ BssidStatus bssidStatus = entryMap.getValue();
+ if (bssidStatus.isInBlocklist && (ssids == null || ssids.contains(bssidStatus.ssid))) {
+ results.add(bssidStatus.bssid);
+ }
+ }
+ return results;
+ }
+
+ /**
* Sends the BSSIDs belonging to the input SSID down to the firmware to prevent auto-roaming
* to those BSSIDs.
* @param ssids
@@ -1391,7 +1411,8 @@ public class WifiBlocklistMonitor {
break;
}
}
- return mClock.getElapsedSinceBootMillis() + disableDurationMs;
+ return mClock.getElapsedSinceBootMillis() + Math.min(
+ disableDurationMs, mWifiGlobals.getWifiConfigMaxDisableDurationMs());
}
/**
diff --git a/service/java/com/android/server/wifi/WifiCarrierInfoManager.java b/service/java/com/android/server/wifi/WifiCarrierInfoManager.java
index 82fba84a67..1936abb7ae 100644
--- a/service/java/com/android/server/wifi/WifiCarrierInfoManager.java
+++ b/service/java/com/android/server/wifi/WifiCarrierInfoManager.java
@@ -54,6 +54,10 @@ import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyCallback;
import android.telephony.TelephonyManager;
+import android.telephony.ims.ImsManager;
+import android.telephony.ims.ImsMmTelManager;
+import android.telephony.ims.feature.MmTelFeature;
+import android.telephony.ims.stub.ImsRegistrationImplBase;
import android.text.TextUtils;
import android.util.ArraySet;
import android.util.Base64;
@@ -188,6 +192,9 @@ public class WifiCarrierInfoManager {
private final WifiMetrics mWifiMetrics;
private final Clock mClock;
private final WifiPseudonymManager mWifiPseudonymManager;
+
+ private ImsManager mImsManager;
+ private Map<Integer, ImsMmTelManager> mImsMmTelManagerMap = new HashMap<>();
/**
* Cached Map of <subscription ID, CarrierConfig PersistableBundle> since retrieving the
* PersistableBundle from CarrierConfigManager is somewhat expensive as it has hundreds of
@@ -526,6 +533,7 @@ public class WifiCarrierInfoManager {
@Override
public void onSubscriptionsChanged() {
mActiveSubInfos = mSubscriptionManager.getCompleteActiveSubscriptionInfoList();
+ mImsMmTelManagerMap.clear();
updateSubIdsInNetworkFactoryFilters(mActiveSubInfos);
mSubIdToSimInfoSparseArray.clear();
mSubscriptionGroupMap.clear();
@@ -1545,22 +1553,26 @@ public class WifiCarrierInfoManager {
Log.v(TAG, "Raw Response - " + tmResponse);
}
- boolean goodReponse = false;
+ boolean goodResponse = false;
if (tmResponse != null && tmResponse.length() > 4) {
byte[] result = Base64.decode(tmResponse, Base64.DEFAULT);
Log.e(TAG, "Hex Response - " + makeHex(result));
byte tag = result[0];
if (tag == (byte) 0xdb) {
Log.v(TAG, "successful 3G authentication ");
- int resLen = result[1];
- String res = makeHex(result, 2, resLen);
- int ckLen = result[resLen + 2];
- String ck = makeHex(result, resLen + 3, ckLen);
- int ikLen = result[resLen + ckLen + 3];
- String ik = makeHex(result, resLen + ckLen + 4, ikLen);
- sb.append(":" + ik + ":" + ck + ":" + res);
- Log.v(TAG, "ik:" + ik + "ck:" + ck + " res:" + res);
- goodReponse = true;
+ try {
+ int resLen = result[1];
+ String res = makeHex(result, 2, resLen);
+ int ckLen = result[resLen + 2];
+ String ck = makeHex(result, resLen + 3, ckLen);
+ int ikLen = result[resLen + ckLen + 3];
+ String ik = makeHex(result, resLen + ckLen + 4, ikLen);
+ sb.append(":" + ik + ":" + ck + ":" + res);
+ Log.v(TAG, "ik:" + ik + "ck:" + ck + " res:" + res);
+ goodResponse = true;
+ } catch (ArrayIndexOutOfBoundsException e) {
+ Log.e(TAG, "ArrayIndexOutOfBoundsException in get3GAuthResponse: " + e);
+ }
} else if (tag == (byte) 0xdc) {
Log.e(TAG, "synchronisation failure");
int autsLen = result[1];
@@ -1568,7 +1580,7 @@ public class WifiCarrierInfoManager {
resType = WifiNative.SIM_AUTH_RESP_TYPE_UMTS_AUTS;
sb.append(":" + auts);
Log.v(TAG, "auts:" + auts);
- goodReponse = true;
+ goodResponse = true;
} else {
Log.e(TAG, "bad response - unknown tag = " + tag);
}
@@ -1576,7 +1588,7 @@ public class WifiCarrierInfoManager {
Log.e(TAG, "bad response - " + tmResponse);
}
- if (goodReponse) {
+ if (goodResponse) {
String response = sb.toString();
Log.v(TAG, "Supplicant Response -" + response);
return new SimAuthResponseData(resType, response);
@@ -2170,7 +2182,7 @@ public class WifiCarrierInfoManager {
// Set the flag to let WifiConfigStore that we have new data to write.
mHasNewUserDataToSerialize = true;
mHasNewSharedDataToSerialize = true;
- if (!mWifiInjector.getWifiConfigManager().saveToStore(true)) {
+ if (!mWifiInjector.getWifiConfigManager().saveToStore()) {
Log.w(TAG, "Failed to save to store");
}
}
@@ -2329,6 +2341,40 @@ public class WifiCarrierInfoManager {
return ret;
}
+ /**
+ * Check if wifi calling is being available.
+ */
+ public boolean isWifiCallingAvailable() {
+ if (mActiveSubInfos == null || mActiveSubInfos.isEmpty()) {
+ return false;
+ }
+ if (mImsManager == null) {
+ mImsManager = mContext.getSystemService(ImsManager.class);
+ }
+ for (SubscriptionInfo subInfo : mActiveSubInfos) {
+ int subscriptionId = subInfo.getSubscriptionId();
+ try {
+ if (mImsManager != null) {
+ ImsMmTelManager imsMmTelManager = mImsMmTelManagerMap.get(subscriptionId);
+ if (imsMmTelManager == null) {
+ imsMmTelManager = mImsManager.getImsMmTelManager(subscriptionId);
+ mImsMmTelManagerMap.put(subscriptionId, imsMmTelManager);
+ }
+ if (imsMmTelManager != null
+ && imsMmTelManager.isAvailable(
+ MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
+ ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN)) {
+ Log.d(TAG, "WifiCalling is available on subId " + subscriptionId);
+ return true;
+ }
+ }
+ } catch (RuntimeException e) {
+ Log.d(TAG, "RuntimeException while checking if wifi calling is available: " + e);
+ }
+ }
+ return false;
+ }
+
private boolean isOobPseudonymFeatureEnabledInResource(int carrierId) {
WifiStringResourceWrapper wifiStringResourceWrapper =
mContext.getStringResourceWrapper(getMatchingSubId(carrierId), carrierId);
diff --git a/service/java/com/android/server/wifi/WifiConfigManager.java b/service/java/com/android/server/wifi/WifiConfigManager.java
index d2f26183c3..9b0af36429 100644
--- a/service/java/com/android/server/wifi/WifiConfigManager.java
+++ b/service/java/com/android/server/wifi/WifiConfigManager.java
@@ -133,7 +133,7 @@ public class WifiConfigManager {
new AlarmManager.OnAlarmListener() {
public void onAlarm() {
if (mBufferedWritePending) {
- writeBufferedData(true);
+ writeBufferedData();
}
}
};
@@ -1728,7 +1728,7 @@ public class WifiConfigManager {
: WifiManager.CHANGE_REASON_CONFIG_CHANGE, newConfig);
// Unless the added network is ephemeral or Passpoint, persist the network update/addition.
if (!config.ephemeral && !config.isPasspoint()) {
- saveToStore(true);
+ saveToStore();
}
for (OnNetworkUpdateListener listener : mListeners) {
@@ -1779,7 +1779,7 @@ public class WifiConfigManager {
*/
public void incrementNumRebootsSinceLastUse() {
getInternalConfiguredNetworks().forEach(config -> config.numRebootsSinceLastUse++);
- saveToStore(false);
+ saveToStore();
}
private boolean isDeviceOwnerProfileOwnerOrSystem(int uid, String packageName) {
@@ -1983,7 +1983,7 @@ public class WifiConfigManager {
sendConfiguredNetworkChangedBroadcast(WifiManager.CHANGE_REASON_REMOVED, config);
// Unless the removed network is ephemeral or Passpoint, persist the network removal.
if (!config.ephemeral && !config.isPasspoint()) {
- saveToStore(true);
+ saveToStore();
}
for (OnNetworkUpdateListener listener : mListeners) {
listener.onNetworkRemoved(
@@ -2202,7 +2202,7 @@ public class WifiConfigManager {
// may need to update the wrong password text.
sendConfiguredNetworkChangedBroadcast(WifiManager.CHANGE_REASON_CONFIG_CHANGE, config);
}
- saveToStore(false);
+ saveToStore();
return true;
}
@@ -2309,7 +2309,7 @@ public class WifiConfigManager {
return false;
}
mWifiBlocklistMonitor.clearBssidBlocklistForSsid(config.SSID);
- saveToStore(true);
+ saveToStore();
return true;
}
@@ -2348,7 +2348,7 @@ public class WifiConfigManager {
networkId, NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER)) {
return false;
}
- saveToStore(true);
+ saveToStore();
return true;
}
@@ -2378,7 +2378,7 @@ public class WifiConfigManager {
}
sendConfiguredNetworkChangedBroadcast(WifiManager.CHANGE_REASON_CONFIG_CHANGE, config);
if (!config.ephemeral) {
- saveToStore(true);
+ saveToStore();
}
return true;
}
@@ -2449,7 +2449,7 @@ public class WifiConfigManager {
setNetworkStatus(config, WifiConfiguration.Status.CURRENT);
config.isCurrentlyConnected = true;
config.setIsUserSelected(isUserSelected);
- saveToStore(false);
+ saveToStore();
return true;
}
@@ -2493,7 +2493,7 @@ public class WifiConfigManager {
}
config.isCurrentlyConnected = false;
config.setIsUserSelected(false);
- saveToStore(false);
+ saveToStore();
return true;
}
@@ -2654,7 +2654,7 @@ public class WifiConfigManager {
config.numNoInternetAccessReports = 0;
config.getNetworkSelectionStatus().setHasEverValidatedInternetAccess(true);
}
- saveToStore(false);
+ saveToStore();
return true;
}
@@ -3199,7 +3199,7 @@ public class WifiConfigManager {
+ mUserTemporarilyDisabledList.size() + ", maxDisableDurationMinutes:"
+ maxDisableDurationMinutes);
removeUserChoiceFromDisabledNetwork(network, uid);
- saveToStore(false);
+ saveToStore();
}
/**
@@ -3377,7 +3377,7 @@ public class WifiConfigManager {
}
// Switch out the user store file.
if (loadFromUserStoreAfterUnlockOrSwitch(userId)) {
- writeBufferedData(true);
+ writeBufferedData();
mPendingUnlockStoreRead = false;
}
}
@@ -3415,7 +3415,7 @@ public class WifiConfigManager {
return new HashSet<>();
}
if (mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(mCurrentUserId))) {
- writeBufferedData(true);
+ writeBufferedData();
}
// Remove any private networks of the old user before switching the userId.
Set<Integer> removedNetworkIds = clearInternalDataForUser(mCurrentUserId);
@@ -3474,7 +3474,7 @@ public class WifiConfigManager {
}
if (userId == mCurrentUserId
&& mUserManager.isUserUnlockingOrUnlocked(UserHandle.of(mCurrentUserId))) {
- writeBufferedData(true);
+ writeBufferedData();
clearInternalDataForUser(mCurrentUserId);
}
}
@@ -3775,20 +3775,16 @@ public class WifiConfigManager {
/**
* Save the current snapshot of the in-memory lists to the config store.
*
- * @param forceWrite Whether the write needs to be forced or not.
* @return Whether the write was successful or not, this is applicable only for force writes.
*/
- public synchronized boolean saveToStore(boolean forceWrite) {
+ public synchronized boolean saveToStore() {
if (mPendingStoreRead) {
Log.e(TAG, "Cannot save to store before store is read!");
return false;
}
- if (mFeatureFlags.delaySaveToStore()) {
- // When feature enabled, always do a delay write
- startBufferedWriteAlarm();
- return true;
- }
- return writeBufferedData(forceWrite);
+ // When feature enabled, always do a delay write
+ startBufferedWriteAlarm();
+ return true;
}
/** Helper method to start a buffered write alarm if one doesn't already exist. */
@@ -3812,7 +3808,7 @@ public class WifiConfigManager {
}
}
- private boolean writeBufferedData(Boolean forceWrite) {
+ private boolean writeBufferedData() {
stopBufferedWriteAlarm();
ArrayList<WifiConfiguration> sharedConfigurations = new ArrayList<>();
ArrayList<WifiConfiguration> userConfigurations = new ArrayList<>();
@@ -3867,7 +3863,7 @@ public class WifiConfigManager {
try {
long start = mClock.getElapsedSinceBootMillis();
- mWifiConfigStore.write(forceWrite);
+ mWifiConfigStore.write();
mWifiMetrics.wifiConfigStored((int) (mClock.getElapsedSinceBootMillis() - start));
} catch (IOException | IllegalStateException e) {
Log.wtf(TAG, "Writing to store failed. Saved networks maybe lost!", e);
@@ -4313,7 +4309,7 @@ public class WifiConfigManager {
return;
}
internalConfig.setSecurityParamsIsAddedByAutoUpgrade(securityType, isAddedByAutoUpgrade);
- saveToStore(true);
+ saveToStore();
}
private static final int SUBJECT_ALTERNATIVE_NAMES_EMAIL = 1;
@@ -4432,11 +4428,12 @@ public class WifiConfigManager {
Log.d(TAG, "Set altSubjectMatch to " + altSubjectNames);
}
newConfig.enterpriseConfig.setAltSubjectMatch(altSubjectNames);
+ } else {
+ if (mVerboseLoggingEnabled) {
+ Log.d(TAG, "Set domainSuffixMatch to " + serverCertInfo.commonName);
+ }
+ newConfig.enterpriseConfig.setDomainSuffixMatch(serverCertInfo.commonName);
}
- if (mVerboseLoggingEnabled) {
- Log.d(TAG, "Set domainSuffixMatch to " + serverCertInfo.commonName);
- }
- newConfig.enterpriseConfig.setDomainSuffixMatch(serverCertInfo.commonName);
newConfig.enterpriseConfig.setUserApproveNoCaCert(false);
// Trigger an update to install CA certificate and the corresponding configuration.
NetworkUpdateResult result = addOrUpdateNetwork(newConfig, internalConfig.creatorUid);
@@ -4569,13 +4566,13 @@ public class WifiConfigManager {
}
/**
- * Handle the device shutdown, should write all cached data to the storage
+ * Write all cached data to the storage
*/
- public void handleShutDown() {
+ public void writeDataToStorage() {
if (mPendingStoreRead) {
Log.e(TAG, "Cannot save to store before store is read!");
return;
}
- writeBufferedData(true);
+ writeBufferedData();
}
}
diff --git a/service/java/com/android/server/wifi/WifiConfigStore.java b/service/java/com/android/server/wifi/WifiConfigStore.java
index c541584215..076c256d2d 100644
--- a/service/java/com/android/server/wifi/WifiConfigStore.java
+++ b/service/java/com/android/server/wifi/WifiConfigStore.java
@@ -21,11 +21,8 @@ import static java.lang.Math.toIntExact;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
-import android.app.AlarmManager;
-import android.content.Context;
import android.net.wifi.WifiMigration;
import android.net.wifi.util.Environment;
-import android.os.Handler;
import android.os.UserHandle;
import android.util.AtomicFile;
import android.util.Log;
@@ -74,7 +71,7 @@ import java.util.stream.Stream;
* NOTE:
* <li>Modules can register their {@StoreData} using
* {@link WifiConfigStore#registerStoreData(StoreData)} directly, but should
- * use {@link WifiConfigManager#saveToStore(boolean)} for any writes.</li>
+ * use {@link WifiConfigManager#saveToStore()} for any writes.</li>
* <li>{@link WifiConfigManager} controls {@link WifiConfigStore} and initiates read at bootup and
* store file changes on user switch.</li>
* <li>Not thread safe!</li>
@@ -150,10 +147,6 @@ public class WifiConfigStore {
*/
private static final String TAG = "WifiConfigStore";
/**
- * Time interval for buffering file writes for non-forced writes
- */
- private static final int BUFFERED_WRITE_ALARM_INTERVAL_MS = 10 * 1000;
- /**
* Config store file name for general shared store file.
*/
private static final String STORE_FILE_NAME_SHARED_GENERAL = "WifiConfigStore.xml";
@@ -181,14 +174,6 @@ public class WifiConfigStore {
put(STORE_FILE_USER_NETWORK_SUGGESTIONS, STORE_FILE_NAME_USER_NETWORK_SUGGESTIONS);
}};
/**
- * Handler instance to post alarm timeouts to
- */
- private final Handler mEventHandler;
- /**
- * Alarm manager instance to start buffer timeout alarms.
- */
- private final AlarmManager mAlarmManager;
- /**
* Clock instance to retrieve timestamps for alarms.
*/
private final Clock mClock;
@@ -207,23 +192,6 @@ public class WifiConfigStore {
* Verbose logging flag.
*/
private boolean mVerboseLoggingEnabled = false;
- /**
- * Flag to indicate if there is a buffered write pending.
- */
- private boolean mBufferedWritePending = false;
- /**
- * Alarm listener for flushing out any buffered writes.
- */
- private final AlarmManager.OnAlarmListener mBufferedWriteListener =
- new AlarmManager.OnAlarmListener() {
- public void onAlarm() {
- try {
- writeBufferedData();
- } catch (IOException e) {
- Log.wtf(TAG, "Buffered write failed", e);
- }
- }
- };
/**
* List of data containers.
@@ -234,19 +202,14 @@ public class WifiConfigStore {
* Create a new instance of WifiConfigStore.
* Note: The store file instances have been made inputs to this class to ease unit-testing.
*
- * @param context context to use for retrieving the alarm manager.
- * @param handler handler instance to post alarm timeouts to.
- * @param clock clock instance to retrieve timestamps for alarms.
- * @param wifiMetrics Metrics instance.
+ * @param clock clock instance to retrieve timestamps for alarms.
+ * @param wifiMetrics Metrics instance.
* @param sharedStores List of {@link StoreFile} instances pointing to the shared store files.
* This should be retrieved using {@link #createSharedFiles(boolean)}
* method.
*/
- public WifiConfigStore(Context context, Handler handler, Clock clock, WifiMetrics wifiMetrics,
+ public WifiConfigStore(Clock clock, WifiMetrics wifiMetrics,
List<StoreFile> sharedStores) {
-
- mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
- mEventHandler = handler;
mClock = clock;
mWifiMetrics = wifiMetrics;
mStoreDataList = new ArrayList<>();
@@ -397,11 +360,8 @@ public class WifiConfigStore {
* API to write the data provided by registered store data to config stores.
* The method writes the user specific configurations to user specific config store and the
* shared configurations to shared config store.
- *
- * @param forceSync boolean to force write the config stores now. if false, the writes are
- * buffered and written after the configured interval.
*/
- public void write(boolean forceSync)
+ public void write()
throws XmlPullParserException, IOException {
boolean hasAnyNewData = false;
// Serialize the provided data and send it to the respective stores. The actual write will
@@ -422,18 +382,7 @@ public class WifiConfigStore {
}
}
}
-
if (hasAnyNewData) {
- // Every write provides a new snapshot to be persisted, so |forceSync| flag overrides
- // any pending buffer writes.
- if (forceSync) {
- writeBufferedData();
- } else {
- startBufferedWriteAlarm();
- }
- } else if (forceSync && mBufferedWritePending) {
- // no new data to write, but there is a pending buffered write. So, |forceSync| should
- // flush that out.
writeBufferedData();
}
}
@@ -473,34 +422,10 @@ public class WifiConfigStore {
}
/**
- * Helper method to start a buffered write alarm if one doesn't already exist.
- */
- private void startBufferedWriteAlarm() {
- if (!mBufferedWritePending) {
- mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
- mClock.getElapsedSinceBootMillis() + BUFFERED_WRITE_ALARM_INTERVAL_MS,
- BUFFERED_WRITE_ALARM_TAG, mBufferedWriteListener, mEventHandler);
- mBufferedWritePending = true;
- }
- }
-
- /**
- * Helper method to stop a buffered write alarm if one exists.
- */
- private void stopBufferedWriteAlarm() {
- if (mBufferedWritePending) {
- mAlarmManager.cancel(mBufferedWriteListener);
- mBufferedWritePending = false;
- }
- }
-
- /**
* Helper method to actually perform the writes to the file. This flushes out any write data
* being buffered in the respective stores and cancels any pending buffer write alarms.
*/
private void writeBufferedData() throws IOException {
- stopBufferedWriteAlarm();
-
long writeStartTime = mClock.getElapsedSinceBootMillis();
for (StoreFile sharedStoreFile : mSharedStores) {
sharedStoreFile.writeBufferedRawData();
@@ -687,8 +612,6 @@ public class WifiConfigStore {
}
}
- // Stop any pending buffered writes, if any.
- stopBufferedWriteAlarm();
mUserStores = userStores;
// Now read from the user store files.
diff --git a/service/java/com/android/server/wifi/WifiConfigurationUtil.java b/service/java/com/android/server/wifi/WifiConfigurationUtil.java
index 3d14b8a002..4421fcd08e 100644
--- a/service/java/com/android/server/wifi/WifiConfigurationUtil.java
+++ b/service/java/com/android/server/wifi/WifiConfigurationUtil.java
@@ -62,9 +62,7 @@ public class WifiConfigurationUtil {
* Constants used for validating external config objects.
*/
private static final int ENCLOSING_QUOTES_LEN = 2;
- private static final int SSID_UTF_8_MIN_LEN = 1 + ENCLOSING_QUOTES_LEN;
- private static final int SSID_UTF_8_MAX_LEN = 32 + ENCLOSING_QUOTES_LEN;
- private static final int SSID_HEX_MIN_LEN = 2;
+ private static final int SSID_PLAINTEXT_MAX_LEN = 32 + ENCLOSING_QUOTES_LEN;
private static final int SSID_HEX_MAX_LEN = 64;
private static final int PSK_ASCII_MIN_LEN = 8 + ENCLOSING_QUOTES_LEN;
private static final int SAE_ASCII_MIN_LEN = 1 + ENCLOSING_QUOTES_LEN;
@@ -453,9 +451,16 @@ public class WifiConfigurationUtil {
Log.e(TAG, "validateSsid failed: empty string");
return false;
}
- if (!ssid.startsWith("\"") && ssid.length() > SSID_HEX_MAX_LEN) {
- Log.e(TAG, "validateSsid failed: hex ssid " + ssid + " longer than 32 bytes");
- return false;
+ if (ssid.startsWith("\"")) {
+ if (ssid.length() > SSID_PLAINTEXT_MAX_LEN) {
+ Log.e(TAG, "validateSsid failed: plaintext ssid " + ssid + " longer than 32 chars");
+ return false;
+ }
+ } else {
+ if (ssid.length() > SSID_HEX_MAX_LEN) {
+ Log.e(TAG, "validateSsid failed: hex ssid " + ssid + " longer than 32 bytes");
+ return false;
+ }
}
WifiSsid wifiSsid;
try {
diff --git a/service/java/com/android/server/wifi/WifiConnectivityManager.java b/service/java/com/android/server/wifi/WifiConnectivityManager.java
index b0bc07ab68..59d8934edf 100644
--- a/service/java/com/android/server/wifi/WifiConnectivityManager.java
+++ b/service/java/com/android/server/wifi/WifiConnectivityManager.java
@@ -184,6 +184,7 @@ public class WifiConnectivityManager {
private final FrameworkFacade mFrameworkFacade;
private final WifiPermissionsUtil mWifiPermissionsUtil;
private final WifiDialogManager mWifiDialogManager;
+ private final WifiThreadRunner mWifiThreadRunner;
private WifiScannerInternal mScanner;
private final MultiInternetManager mMultiInternetManager;
@@ -334,7 +335,7 @@ public class WifiConnectivityManager {
SingleScanListener singleScanListener = new SingleScanListener(false);
mScanner.startScan(settings,
new WifiScannerInternal.ScanListener(singleScanListener,
- mEventHandler));
+ mWifiThreadRunner));
mWifiMetrics.incrementConnectivityOneshotScanCount();
}
};
@@ -544,6 +545,47 @@ public class WifiConnectivityManager {
return true;
}
+ private boolean shouldSkipSufficiencyCheck(boolean hasExistingSecondaryCmm) {
+ if (hasExistingSecondaryCmm) {
+ // Secondary CMM already exists. NetworkSelector will evaluate if network selection
+ // should proceed
+ return false;
+ }
+
+ // Otherwise check the various secondary use-cases. Network selection should be triggered
+ // if any secondary use-case is available.
+ if (mOemPaidConnectionAllowed || mOemPrivateConnectionAllowed) {
+ // prefer OEM PAID requestor if it exists.
+ WorkSource oemPaidOrOemPrivateRequestorWs =
+ mOemPaidConnectionRequestorWs != null
+ ? mOemPaidConnectionRequestorWs
+ : mOemPrivateConnectionRequestorWs;
+ if (oemPaidOrOemPrivateRequestorWs == null) {
+ Log.e(TAG, "Both mOemPaidConnectionRequestorWs & mOemPrivateConnectionRequestorWs "
+ + "are null!");
+ }
+ if (oemPaidOrOemPrivateRequestorWs != null
+ && mActiveModeWarden.canRequestMoreClientModeManagersInRole(
+ oemPaidOrOemPrivateRequestorWs,
+ ROLE_CLIENT_SECONDARY_LONG_LIVED, false)) {
+ return true;
+ }
+ }
+ if (isMultiInternetConnectionRequested()) {
+ if (mMultiInternetConnectionRequestorWs == null) {
+ Log.e(TAG, "mMultiInternetConnectionRequestorWs is null!");
+ } else if (mActiveModeWarden.canRequestMoreClientModeManagersInRole(
+ mMultiInternetConnectionRequestorWs, ROLE_CLIENT_SECONDARY_LONG_LIVED, false)) {
+ return true;
+ }
+ }
+ if (mActiveModeWarden.canRequestMoreClientModeManagersInRole(
+ ActiveModeWarden.INTERNAL_REQUESTOR_WS, ROLE_CLIENT_SECONDARY_TRANSIENT, false)) {
+ return true;
+ }
+ return false;
+ }
+
/**
* Handles 'onResult' callbacks for the Periodic, Single & Pno ScanListener.
* Executes selection of potential network candidates, initiation of connection attempt to that
@@ -583,40 +625,7 @@ public class WifiConnectivityManager {
}
cmmStates.add(cmmState);
}
- // We don't have any existing secondary CMM, but are we allowed to create a secondary CMM
- // and do we have a request for OEM_PAID/OEM_PRIVATE request? If yes, we need to perform
- // network selection to check if we have any potential candidate for the secondary CMM
- // creation.
- if (!hasExistingSecondaryCmm
- && (mOemPaidConnectionAllowed || mOemPrivateConnectionAllowed)) {
- // prefer OEM PAID requestor if it exists.
- WorkSource oemPaidOrOemPrivateRequestorWs =
- mOemPaidConnectionRequestorWs != null
- ? mOemPaidConnectionRequestorWs
- : mOemPrivateConnectionRequestorWs;
- if (oemPaidOrOemPrivateRequestorWs == null) {
- Log.e(TAG, "Both mOemPaidConnectionRequestorWs & mOemPrivateConnectionRequestorWs "
- + "are null!");
- }
- if (oemPaidOrOemPrivateRequestorWs != null
- && mActiveModeWarden.canRequestMoreClientModeManagersInRole(
- oemPaidOrOemPrivateRequestorWs,
- ROLE_CLIENT_SECONDARY_LONG_LIVED, false)) {
- // Add a placeholder CMM state to ensure network selection is performed for a
- // potential second STA creation.
- cmmStates.add(new WifiNetworkSelector.ClientModeManagerState());
- hasExistingSecondaryCmm = true;
- }
- }
- // If secondary cmm has not been created and need to connect secondary internet
- if (!hasExistingSecondaryCmm && isMultiInternetConnectionRequested()) {
- if (mMultiInternetConnectionRequestorWs == null) {
- Log.e(TAG, "mMultiInternetConnectionRequestorWs is null!");
- } else if (mActiveModeWarden.canRequestMoreClientModeManagersInRole(
- mMultiInternetConnectionRequestorWs, ROLE_CLIENT_SECONDARY_LONG_LIVED, false)) {
- cmmStates.add(new WifiNetworkSelector.ClientModeManagerState());
- }
- }
+ boolean skipSufficiencyCheck = shouldSkipSufficiencyCheck(hasExistingSecondaryCmm);
// Check if any blocklisted BSSIDs can be freed.
List<ScanDetail> enabledDetails =
@@ -639,7 +648,7 @@ public class WifiConnectivityManager {
List<WifiCandidates.Candidate> candidates = mNetworkSelector.getCandidatesFromScan(
scanDetails, bssidBlocklist, cmmStates, mUntrustedConnectionAllowed,
mOemPaidConnectionAllowed, mOemPrivateConnectionAllowed,
- mRestrictedConnectionAllowedUids, isMultiInternetConnectionRequested());
+ mRestrictedConnectionAllowedUids, skipSufficiencyCheck);
mLatestCandidates = candidates;
mLatestCandidatesTimestampMs = mClock.getElapsedSinceBootMillis();
@@ -1357,6 +1366,7 @@ public class WifiConnectivityManager {
mOpenNetworkNotifier = openNetworkNotifier;
mWifiMetrics = wifiMetrics;
mEventHandler = handler;
+ mWifiThreadRunner = new WifiThreadRunner(mEventHandler);
mClock = clock;
mLocalLog = localLog;
mWifiScoreCard = scoreCard;
@@ -1389,10 +1399,10 @@ public class WifiConnectivityManager {
new InternalMultiInternetConnectionStatusListener());
mAllSingleScanListener = new AllSingleScanListener();
mInternalAllSingleScanListener = new WifiScannerInternal.ScanListener(
- mAllSingleScanListener, mEventHandler);
+ mAllSingleScanListener, mWifiThreadRunner);
mPnoScanListener = new PnoScanListener();
mInternalPnoScanListener = new WifiScannerInternal.ScanListener(mPnoScanListener,
- mEventHandler);
+ mWifiThreadRunner);
mPnoScanPasspointSsids = new ArraySet<>();
wifiDeviceStateChangeManager.registerStateChangeCallback(
new WifiDeviceStateChangeManager.StateChangeCallback() {
@@ -1482,6 +1492,11 @@ public class WifiConnectivityManager {
clientModeManager.getConnectedBssid());
ScanResult scanResultCandidate =
candidate.getNetworkSelectionStatus().getCandidate();
+ if (scanResultCandidate == null) {
+ localLog("isClientModeManagerConnectedOrConnectingToCandidate(" + clientModeManager
+ + "): bad candidate - " + candidate.SSID + " scanResult is null!");
+ return connectingOrConnectedToTarget;
+ }
String targetBssid = scanResultCandidate.BSSID;
return connectingOrConnectedToTarget
&& Objects.equals(targetBssid, connectedOrConnectingBssid);
@@ -1670,7 +1685,7 @@ public class WifiConnectivityManager {
primaryManager.onNetworkSwitchRejected(candidate.networkId,
candidate.getNetworkSelectionStatus().getNetworkSelectionBSSID());
}),
- new WifiThreadRunner(mEventHandler));
+ mWifiThreadRunner);
mNetworkSwitchDialog.launchDialog();
mDialogCandidateNetId = candidate.networkId;
}
@@ -2317,7 +2332,7 @@ public class WifiConnectivityManager {
SingleScanListener singleScanListener =
new SingleScanListener(isFullBandScan);
mScanner.startScan(settings,
- new WifiScannerInternal.ScanListener(singleScanListener, mEventHandler));
+ new WifiScannerInternal.ScanListener(singleScanListener, mWifiThreadRunner));
mWifiMetrics.incrementConnectivityOneshotScanCount();
}
@@ -3423,6 +3438,24 @@ public class WifiConnectivityManager {
}
/**
+ * Reset states when Wi-Fi is getting disabled.
+ */
+ public void resetOnWifiDisable() {
+ mNetworkSelector.resetOnDisable();
+ mConfigManager.enableTemporaryDisabledNetworks();
+ mConfigManager.stopRestrictingAutoJoinToSubscriptionId();
+ mConfigManager.clearUserTemporarilyDisabledList();
+ mConfigManager.removeAllEphemeralOrPasspointConfiguredNetworks();
+ // Flush ANQP cache if configured to do so
+ if (mWifiGlobals.flushAnqpCacheOnWifiToggleOffEvent()) {
+ mPasspointManager.clearAnqpRequestsAndFlushCache();
+ }
+ if (mEnablePnoScanAfterWifiToggle) {
+ mPnoScanEnabledByFramework = true;
+ }
+ }
+
+ /**
* Inform WiFi is enabled for connection or not
*/
private void setWifiEnabled(boolean enable) {
@@ -3431,18 +3464,7 @@ public class WifiConnectivityManager {
localLog("Set WiFi " + (enable ? "enabled" : "disabled"));
if (!enable) {
- mNetworkSelector.resetOnDisable();
- mConfigManager.enableTemporaryDisabledNetworks();
- mConfigManager.stopRestrictingAutoJoinToSubscriptionId();
- mConfigManager.clearUserTemporarilyDisabledList();
- mConfigManager.removeAllEphemeralOrPasspointConfiguredNetworks();
- // Flush ANQP cache if configured to do so
- if (mWifiGlobals.flushAnqpCacheOnWifiToggleOffEvent()) {
- mPasspointManager.clearAnqpRequestsAndFlushCache();
- }
- if (mEnablePnoScanAfterWifiToggle) {
- mPnoScanEnabledByFramework = true;
- }
+ resetOnWifiDisable();
}
mWifiEnabled = enable;
updateRunningState();
diff --git a/service/java/com/android/server/wifi/WifiCountryCode.java b/service/java/com/android/server/wifi/WifiCountryCode.java
index 46c23937c9..4d4bc0bb0c 100644
--- a/service/java/com/android/server/wifi/WifiCountryCode.java
+++ b/service/java/com/android/server/wifi/WifiCountryCode.java
@@ -23,12 +23,7 @@ import android.annotation.Nullable;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.os.SystemProperties;
-import android.telephony.SubscriptionInfo;
-import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
-import android.telephony.ims.ImsMmTelManager;
-import android.telephony.ims.feature.MmTelFeature;
-import android.telephony.ims.stub.ImsRegistrationImplBase;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.Log;
@@ -78,6 +73,7 @@ public class WifiCountryCode {
private final WifiSettingsConfigStore mSettingsConfigStore;
private final Clock mClock;
private final WifiPermissionsUtil mWifiPermissionsUtil;
+ private final WifiCarrierInfoManager mWifiCarrierInfoManager;
private List<ChangeListener> mListeners = new ArrayList<>();
private boolean mVerboseLoggingEnabled = false;
private boolean mIsCountryCodePendingToUpdateToCmm = true; // default to true for first update.
@@ -210,7 +206,8 @@ public class WifiCountryCode {
WifiNative wifiNative,
@NonNull WifiSettingsConfigStore settingsConfigStore,
Clock clock,
- WifiPermissionsUtil wifiPermissionsUtil) {
+ WifiPermissionsUtil wifiPermissionsUtil,
+ @NonNull WifiCarrierInfoManager wifiCarrierInfoManager) {
mContext = context;
mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
mActiveModeWarden = activeModeWarden;
@@ -219,6 +216,7 @@ public class WifiCountryCode {
mSettingsConfigStore = settingsConfigStore;
mClock = clock;
mWifiPermissionsUtil = wifiPermissionsUtil;
+ mWifiCarrierInfoManager = wifiCarrierInfoManager;
mActiveModeWarden.registerModeChangeCallback(new ModeChangeCallbackInternal());
clientModeImplMonitor.registerListener(new ClientModeListenerInternal());
@@ -309,41 +307,6 @@ public class WifiCountryCode {
return mContext.getPackageManager().hasSystemFeature(FEATURE_TELEPHONY_CALLING);
}
- /**
- * Check if Wi-Fi calling is available.
- *
- * This method can only be called if device has calling feature (see hasCalling()).
- */
- private boolean isWifiCallingAvailable() {
- SubscriptionManager subscriptionManager =
- mContext.getSystemService(SubscriptionManager.class);
- if (subscriptionManager == null) {
- Log.d(TAG, "SubscriptionManager not found");
- return false;
- }
-
- List<SubscriptionInfo> subInfoList = subscriptionManager
- .getCompleteActiveSubscriptionInfoList();
- if (subInfoList == null) {
- Log.d(TAG, "Active SubscriptionInfo list not found");
- return false;
- }
- for (SubscriptionInfo subInfo : subInfoList) {
- int subscriptionId = subInfo.getSubscriptionId();
- try {
- if (ImsMmTelManager.createForSubscriptionId(subscriptionId).isAvailable(
- MmTelFeature.MmTelCapabilities.CAPABILITY_TYPE_VOICE,
- ImsRegistrationImplBase.REGISTRATION_TECH_IWLAN)) {
- Log.d(TAG, "WifiCalling is available on subId " + subscriptionId);
- return true;
- }
- } catch (RuntimeException e) {
- Log.d(TAG, "RuntimeException while checking if wifi calling is available: " + e);
- }
- }
- return false;
- }
-
private void initializeTelephonyCountryCodeIfNeeded() {
// If we don't have telephony country code set yet, poll it.
if (mTelephonyCountryCode == null) {
@@ -547,7 +510,7 @@ public class WifiCountryCode {
}
private boolean shouldDisconnectWifiToForceUpdate() {
- if (!hasCalling() || isWifiCallingAvailable()) {
+ if (!hasCalling() || mWifiCarrierInfoManager.isWifiCallingAvailable()) {
return false;
}
diff --git a/service/java/com/android/server/wifi/WifiDeviceStateChangeManager.java b/service/java/com/android/server/wifi/WifiDeviceStateChangeManager.java
index 5fa82fea8a..74df0a5324 100644
--- a/service/java/com/android/server/wifi/WifiDeviceStateChangeManager.java
+++ b/service/java/com/android/server/wifi/WifiDeviceStateChangeManager.java
@@ -66,16 +66,15 @@ public class WifiDeviceStateChangeManager {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
- if (TextUtils.equals(action, Intent.ACTION_SCREEN_ON)) {
- handleScreenStateChanged(true);
- } else if (TextUtils.equals(action, Intent.ACTION_SCREEN_OFF)) {
- handleScreenStateChanged(false);
+ if (TextUtils.equals(action, Intent.ACTION_SCREEN_ON)
+ || TextUtils.equals(action, Intent.ACTION_SCREEN_OFF)) {
+ mHandler.post(() ->
+ handleScreenStateChanged(TextUtils.equals(action,
+ Intent.ACTION_SCREEN_ON)));
}
}
},
- filter,
- null,
- mHandler);
+ filter);
handleScreenStateChanged(mPowerManager.isInteractive());
mIsWifiServiceStarted = true;
}
diff --git a/service/java/com/android/server/wifi/WifiDiagnostics.java b/service/java/com/android/server/wifi/WifiDiagnostics.java
index 19fece6fdb..4c488685ec 100644
--- a/service/java/com/android/server/wifi/WifiDiagnostics.java
+++ b/service/java/com/android/server/wifi/WifiDiagnostics.java
@@ -1023,6 +1023,24 @@ public class WifiDiagnostics {
}
}
+ private boolean shouldTakeBugreport(String bugTitle, String bugDetail) {
+ long currentTimeMs = mClock.getWallClockMillis();
+ long timeSinceLastUploadMs = currentTimeMs - mLastBugReportTime;
+ if (timeSinceLastUploadMs
+ < mWifiInjector.getDeviceConfigFacade().getBugReportMinWindowMs()
+ && mLastBugReportTime > 0) {
+ Log.d(TAG, "Bugreport was filed recently, skip " + bugTitle + "(" + bugDetail + ")");
+ return false;
+ }
+ String titleAndDetail = bugTitle + bugDetail;
+ if (mWifiInjector.getDeviceConfigFacade().getDisabledAutoBugreportTitleAndDetails()
+ .contains(titleAndDetail)) {
+ Log.d(TAG, "Bugreport explicitly disabled " + bugTitle + "(" + bugDetail + ")");
+ return false;
+ }
+ return true;
+ }
+
/**
* Initiates a system-level bug report if there is no bug report taken recently.
* This is done in a non-blocking fashion.
@@ -1035,12 +1053,7 @@ public class WifiDiagnostics {
return;
}
- long currentTimeMs = mClock.getWallClockMillis();
- long timeSinceLastUploadMs = currentTimeMs - mLastBugReportTime;
- if (timeSinceLastUploadMs
- < mWifiInjector.getDeviceConfigFacade().getBugReportMinWindowMs()
- && mLastBugReportTime > 0) {
- Log.d(TAG, "Bugreport was filed recently, skip " + bugTitle + "(" + bugDetail + ")");
+ if (!shouldTakeBugreport(bugTitle, bugDetail)) {
return;
}
diff --git a/service/java/com/android/server/wifi/WifiDialogManager.java b/service/java/com/android/server/wifi/WifiDialogManager.java
index c189590ef6..cc175b61c7 100644
--- a/service/java/com/android/server/wifi/WifiDialogManager.java
+++ b/service/java/com/android/server/wifi/WifiDialogManager.java
@@ -115,7 +115,7 @@ public class WifiDialogManager {
dialogHandle.cancelDialog();
}
}
- });
+ }, TAG + "#onReceive");
}
};
@@ -232,9 +232,11 @@ public class WifiDialogManager {
@AnyThread
public void launchDialog() {
if (mInternalHandle != null) {
- mWifiThreadRunner.post(() -> mInternalHandle.launchDialog(0));
+ mWifiThreadRunner.post(() -> mInternalHandle.launchDialog(0),
+ TAG + "#launchDialog");
} else if (mLegacyHandle != null) {
- mWifiThreadRunner.post(() -> mLegacyHandle.launchDialog(0));
+ mWifiThreadRunner.post(() -> mLegacyHandle.launchDialog(0),
+ TAG + "#launchDialog");
}
}
@@ -246,9 +248,11 @@ public class WifiDialogManager {
@AnyThread
public void launchDialog(long timeoutMs) {
if (mInternalHandle != null) {
- mWifiThreadRunner.post(() -> mInternalHandle.launchDialog(timeoutMs));
+ mWifiThreadRunner.post(() -> mInternalHandle.launchDialog(timeoutMs),
+ TAG + "#launchDialogTimeout");
} else if (mLegacyHandle != null) {
- mWifiThreadRunner.post(() -> mLegacyHandle.launchDialog(timeoutMs));
+ mWifiThreadRunner.post(() -> mLegacyHandle.launchDialog(timeoutMs),
+ TAG + "#launchDialogTimeout");
}
}
@@ -259,9 +263,11 @@ public class WifiDialogManager {
@AnyThread
public void dismissDialog() {
if (mInternalHandle != null) {
- mWifiThreadRunner.post(() -> mInternalHandle.dismissDialog());
+ mWifiThreadRunner.post(() -> mInternalHandle.dismissDialog(),
+ TAG + "#dismissDialog");
} else if (mLegacyHandle != null) {
- mWifiThreadRunner.post(() -> mLegacyHandle.dismissDialog());
+ mWifiThreadRunner.post(() -> mLegacyHandle.dismissDialog(),
+ TAG + "#dismissDialog");
}
}
}
@@ -393,6 +399,7 @@ public class WifiDialogManager {
private class SimpleDialogHandle extends DialogHandleInternal {
@Nullable private final SimpleDialogCallback mCallback;
@Nullable private final WifiThreadRunner mCallbackThreadRunner;
+ private final String mTitle;
SimpleDialogHandle(
final String title,
@@ -405,6 +412,7 @@ public class WifiDialogManager {
final String neutralButtonText,
@Nullable final SimpleDialogCallback callback,
@Nullable final WifiThreadRunner callbackThreadRunner) {
+ mTitle = title;
Intent intent = getBaseLaunchIntent(WifiManager.DIALOG_TYPE_SIMPLE);
if (intent != null) {
intent.putExtra(WifiManager.EXTRA_DIALOG_TITLE, title)
@@ -424,28 +432,32 @@ public class WifiDialogManager {
void notifyOnPositiveButtonClicked() {
if (mCallbackThreadRunner != null && mCallback != null) {
- mCallbackThreadRunner.post(mCallback::onPositiveButtonClicked);
+ mCallbackThreadRunner.post(mCallback::onPositiveButtonClicked,
+ mTitle + "#onPositiveButtonClicked");
}
unregisterDialog();
}
void notifyOnNegativeButtonClicked() {
if (mCallbackThreadRunner != null && mCallback != null) {
- mCallbackThreadRunner.post(mCallback::onNegativeButtonClicked);
+ mCallbackThreadRunner.post(mCallback::onNegativeButtonClicked,
+ mTitle + "#onNegativeButtonClicked");
}
unregisterDialog();
}
void notifyOnNeutralButtonClicked() {
if (mCallbackThreadRunner != null && mCallback != null) {
- mCallbackThreadRunner.post(mCallback::onNeutralButtonClicked);
+ mCallbackThreadRunner.post(mCallback::onNeutralButtonClicked,
+ mTitle + "#onNeutralButtonClicked");
}
unregisterDialog();
}
void notifyOnCancelled() {
if (mCallbackThreadRunner != null && mCallback != null) {
- mCallbackThreadRunner.post(mCallback::onCancelled);
+ mCallbackThreadRunner.post(mCallback::onCancelled,
+ mTitle + "#onCancelled");
}
unregisterDialog();
}
@@ -534,7 +546,8 @@ public class WifiDialogManager {
Log.v(TAG, "Positive button pressed for legacy simple dialog");
}
if (mCallbackThreadRunner != null && mCallback != null) {
- mCallbackThreadRunner.post(mCallback::onPositiveButtonClicked);
+ mCallbackThreadRunner.post(mCallback::onPositiveButtonClicked,
+ mTitle + "#onPositiveButtonClicked");
}
})
.setNegativeButton(mNegativeButtonText, (dialogNegative, which) -> {
@@ -542,7 +555,8 @@ public class WifiDialogManager {
Log.v(TAG, "Negative button pressed for legacy simple dialog");
}
if (mCallbackThreadRunner != null && mCallback != null) {
- mCallbackThreadRunner.post(mCallback::onNegativeButtonClicked);
+ mCallbackThreadRunner.post(mCallback::onNegativeButtonClicked,
+ mTitle + "#onNegativeButtonClicked");
}
})
.setNeutralButton(mNeutralButtonText, (dialogNeutral, which) -> {
@@ -550,7 +564,8 @@ public class WifiDialogManager {
Log.v(TAG, "Neutral button pressed for legacy simple dialog");
}
if (mCallbackThreadRunner != null && mCallback != null) {
- mCallbackThreadRunner.post(mCallback::onNeutralButtonClicked);
+ mCallbackThreadRunner.post(mCallback::onNeutralButtonClicked,
+ mTitle + "#onNeutralButtonClicked");
}
})
.setOnCancelListener((dialogCancel) -> {
@@ -558,7 +573,8 @@ public class WifiDialogManager {
Log.v(TAG, "Legacy simple dialog cancelled.");
}
if (mCallbackThreadRunner != null && mCallback != null) {
- mCallbackThreadRunner.post(mCallback::onCancelled);
+ mCallbackThreadRunner.post(mCallback::onCancelled,
+ mTitle + "#onCancelled");
}
})
.setOnDismissListener((dialogDismiss) -> {
@@ -569,7 +585,7 @@ public class WifiDialogManager {
}
mAlertDialog = null;
mActiveLegacySimpleDialogs.remove(this);
- });
+ }, mTitle + "#onDismiss");
})
.create();
mAlertDialog.setCanceledOnTouchOutside(mContext.getResources().getBoolean(
@@ -595,7 +611,8 @@ public class WifiDialogManager {
}
if (mTimeoutMs > 0) {
mTimeoutRunnable = mAlertDialog::cancel;
- mWifiThreadRunner.postDelayed(mTimeoutRunnable, mTimeoutMs);
+ mWifiThreadRunner.postDelayed(mTimeoutRunnable, mTimeoutMs,
+ TAG + "#cancelDialog");
}
mActiveLegacySimpleDialogs.add(this);
}
@@ -897,14 +914,16 @@ public class WifiDialogManager {
void notifyOnAccepted(@Nullable String optionalPin) {
if (mCallbackThreadRunner != null && mCallback != null) {
- mCallbackThreadRunner.post(() -> mCallback.onAccepted(optionalPin));
+ mCallbackThreadRunner.post(() -> mCallback.onAccepted(optionalPin),
+ "P2pInvitationReceivedDialogHandle" + "#notifyOnAccepted");
}
unregisterDialog();
}
void notifyOnDeclined() {
if (mCallbackThreadRunner != null && mCallback != null) {
- mCallbackThreadRunner.post(mCallback::onDeclined);
+ mCallbackThreadRunner.post(mCallback::onDeclined,
+ "P2pInvitationReceivedDialogHandle" + "#notifyOnDeclined");
}
unregisterDialog();
}
diff --git a/service/java/com/android/server/wifi/WifiGlobals.java b/service/java/com/android/server/wifi/WifiGlobals.java
index 454d8c25c7..f83dd79ef8 100644
--- a/service/java/com/android/server/wifi/WifiGlobals.java
+++ b/service/java/com/android/server/wifi/WifiGlobals.java
@@ -17,9 +17,10 @@
package com.android.server.wifi;
import android.annotation.Nullable;
-import android.content.Context;
import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiContext;
import android.net.wifi.WifiManager;
+import android.net.wifi.util.WifiResourceCache;
import android.util.ArraySet;
import android.util.Log;
import android.util.SparseArray;
@@ -38,7 +39,6 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
-import java.util.function.BiFunction;
import javax.annotation.concurrent.ThreadSafe;
@@ -48,7 +48,8 @@ import javax.annotation.concurrent.ThreadSafe;
public class WifiGlobals {
private static final String TAG = "WifiGlobals";
- private final Context mContext;
+ private final WifiContext mContext;
+ private final WifiResourceCache mWifiResourceCache;
private final AtomicInteger mPollRssiIntervalMillis = new AtomicInteger(-1);
private final AtomicBoolean mIpReachabilityDisconnectEnabled = new AtomicBoolean(true);
@@ -83,9 +84,8 @@ public class WifiGlobals {
private final boolean mAdjustPollRssiIntervalEnabled;
private final boolean mWifiInterfaceAddedSelfRecoveryEnabled;
private final int mNetworkNotFoundEventThreshold;
- private boolean mIsBackgroundScanSupported;
private boolean mIsSwPnoEnabled;
- private final boolean mIsWepDeprecated;
+ private boolean mWepAllowedControlSupported;
private final boolean mIsWpaPersonalDeprecated;
private final Map<String, List<String>> mCountryCodeToAfcServers;
private final long mWifiConfigMaxDisableDurationMs;
@@ -97,15 +97,14 @@ public class WifiGlobals {
private boolean mDisableNudDisconnectsForWapiInSpecificCc = false;
private boolean mD2dAllowedControlSupportedWhenInfraStaDisabled = false;
private Set<String> mMacRandomizationUnsupportedSsidPrefixes = new ArraySet<>();
- private Map<String, BiFunction<String, Boolean, Boolean>> mOverrideMethods = new HashMap<>();
private SparseArray<SparseArray<CarrierSpecificEapFailureConfig>>
mCarrierSpecificEapFailureConfigMapPerCarrierId = new SparseArray<>();
- public WifiGlobals(Context context) {
+ public WifiGlobals(WifiContext context) {
mContext = context;
-
+ mWifiResourceCache = context.getResourceCache();
mIsWpa3SaeUpgradeEnabled = mContext.getResources()
.getBoolean(R.bool.config_wifiSaeUpgradeEnabled);
mIsWpa3SaeUpgradeOffloadEnabled = mContext.getResources()
@@ -160,12 +159,10 @@ public class WifiGlobals {
R.bool.config_wifiDisableNudDisconnectsForWapiInSpecificCc);
mNetworkNotFoundEventThreshold = mContext.getResources().getInteger(
R.integer.config_wifiNetworkNotFoundEventThreshold);
- mIsBackgroundScanSupported = mContext.getResources()
- .getBoolean(R.bool.config_wifi_background_scan_support);
mIsSwPnoEnabled = mContext.getResources()
.getBoolean(R.bool.config_wifiSwPnoEnabled);
- mIsWepDeprecated = mContext.getResources()
- .getBoolean(R.bool.config_wifiWepDeprecated);
+ mWepAllowedControlSupported = mContext.getResources()
+ .getBoolean(R.bool.config_wifiWepAllowedControlSupported);
mIsWpaPersonalDeprecated = mContext.getResources()
.getBoolean(R.bool.config_wifiWpaPersonalDeprecated);
mIsAfcSupportedOnDevice = mContext.getResources().getBoolean(R.bool.config_wifiAfcSupported)
@@ -187,23 +184,6 @@ public class WifiGlobals {
}
}
loadCarrierSpecificEapFailureConfigMap();
- mOverrideMethods.put("config_wifi_background_scan_support",
- new BiFunction<String, Boolean, Boolean>() {
- @Override
- public Boolean apply(String value , Boolean isEnabled) {
- // reset to default
- if (!isEnabled) {
- mIsBackgroundScanSupported = mContext.getResources()
- .getBoolean(R.bool.config_wifi_background_scan_support);
- return true;
- }
- if ("true".equals(value) || "false".equals(value)) {
- mIsBackgroundScanSupported = Boolean.parseBoolean(value);
- return true;
- }
- return false;
- }
- });
}
/**
@@ -365,7 +345,9 @@ public class WifiGlobals {
* @return boolean true if WEP networks are deprecated, false otherwise.
*/
public boolean isWepDeprecated() {
- return mIsWepDeprecated || !mIsWepAllowed.get();
+ return mWifiResourceCache.getBoolean(R.bool.config_wifiWepDeprecated,
+ "config_wifiWepDeprecated")
+ || (mWepAllowedControlSupported && !mIsWepAllowed.get());
}
/**
@@ -374,7 +356,8 @@ public class WifiGlobals {
* @return boolean true if WEP networks are supported, false otherwise.
*/
public boolean isWepSupported() {
- return !mIsWepDeprecated;
+ return !mWifiResourceCache.getBoolean(R.bool.config_wifiWepDeprecated,
+ "config_wifiWepDeprecated");
}
/**
@@ -607,7 +590,9 @@ public class WifiGlobals {
* Get whether background scan is supported.
*/
public boolean isBackgroundScanSupported() {
- return mIsBackgroundScanSupported;
+ return mWifiResourceCache
+ .getBoolean(R.bool.config_wifi_background_scan_support,
+ "config_wifi_background_scan_support");
};
/**
@@ -690,17 +675,6 @@ public class WifiGlobals {
return mWifiConfigMaxDisableDurationMs;
}
- /**
- * Force Overlay Config Value for background scan.
- */
- public boolean forceOverlayConfigValue(String configString, String value,
- boolean isEnabled) {
- if (!mOverrideMethods.containsKey(configString)) {
- return false;
- }
- return mOverrideMethods.get(configString).apply(value, isEnabled);
- }
-
/** Dump method for debugging */
public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
pw.println("Dump of WifiGlobals");
@@ -729,11 +703,10 @@ public class WifiGlobals {
+ mWifiInterfaceAddedSelfRecoveryEnabled);
pw.println("mDisableUnwantedNetworkOnLowRssi=" + mDisableUnwantedNetworkOnLowRssi);
pw.println("mNetworkNotFoundEventThreshold=" + mNetworkNotFoundEventThreshold);
- pw.println("mIsBackgroundScanSupported=" + mIsBackgroundScanSupported);
pw.println("mIsSwPnoEnabled=" + mIsSwPnoEnabled);
- pw.println("mIsWepDeprecated=" + mIsWepDeprecated);
pw.println("mIsWpaPersonalDeprecated=" + mIsWpaPersonalDeprecated);
pw.println("mIsWepAllowed=" + mIsWepAllowed.get());
+ pw.println("mWepAllowedControlSupported=" + mWepAllowedControlSupported);
pw.println("mDisableFirmwareRoamingInIdleMode=" + mDisableFirmwareRoamingInIdleMode);
pw.println("mRepeatedNudFailuresThreshold=" + mRepeatedNudFailuresThreshold);
pw.println("mRepeatedNudFailuresWindowMs=" + mRepeatedNudFailuresWindowMs);
diff --git a/service/java/com/android/server/wifi/WifiHealthMonitor.java b/service/java/com/android/server/wifi/WifiHealthMonitor.java
index 34dba47922..dd4126c6cf 100644
--- a/service/java/com/android/server/wifi/WifiHealthMonitor.java
+++ b/service/java/com/android/server/wifi/WifiHealthMonitor.java
@@ -107,6 +107,7 @@ public class WifiHealthMonitor {
private final Clock mClock;
private final AlarmManager mAlarmManager;
private final RunnerHandler mHandler;
+ private final WifiThreadRunner mWifiThreadRunner;
private final WifiNative mWifiNative;
private final WifiInjector mWifiInjector;
private final DeviceConfigFacade mDeviceConfigFacade;
@@ -159,6 +160,7 @@ public class WifiHealthMonitor {
mWifiScoreCard = wifiScoreCard;
mAlarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
mHandler = handler;
+ mWifiThreadRunner = new WifiThreadRunner(mHandler);
mWifiNative = wifiNative;
mDeviceConfigFacade = deviceConfigFacade;
mActiveModeWarden = activeModeWarden;
@@ -271,7 +273,7 @@ public class WifiHealthMonitor {
if (mScanner == null) return;
// Register for all single scan results
mScanner.registerScanListener(
- new WifiScannerInternal.ScanListener(new ScanListener(), mHandler));
+ new WifiScannerInternal.ScanListener(new ScanListener(), mWifiThreadRunner));
}
/**
@@ -319,7 +321,7 @@ public class WifiHealthMonitor {
}
private void setPostBootDetectionAlarm() {
- mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
+ mAlarmManager.set(AlarmManager.ELAPSED_REALTIME,
mClock.getElapsedSinceBootMillis() + POST_BOOT_DETECTION_WAIT_TIME_MS,
POST_BOOT_DETECTION_TIMER_TAG,
mPostBootDetectionListener, mHandler);
diff --git a/service/java/com/android/server/wifi/WifiInjector.java b/service/java/com/android/server/wifi/WifiInjector.java
index ff699bbc57..9553434380 100644
--- a/service/java/com/android/server/wifi/WifiInjector.java
+++ b/service/java/com/android/server/wifi/WifiInjector.java
@@ -157,7 +157,6 @@ public class WifiInjector {
private final FeatureFlags mFeatureFlags;
private final UserManager mUserManager;
private final HandlerThread mWifiHandlerThread;
- private final HandlerThread mWifiP2pServiceHandlerThread;
private final HandlerThread mPasspointProvisionerHandlerThread;
private final HandlerThread mWifiDiagnosticsHandlerThread;
private final WifiTrafficPoller mWifiTrafficPoller;
@@ -207,8 +206,6 @@ public class WifiInjector {
private final WifiPermissionsWrapper mWifiPermissionsWrapper;
private final WifiPermissionsUtil mWifiPermissionsUtil;
private final PasspointManager mPasspointManager;
- private HandlerThread mWifiAwareHandlerThread;
- private HandlerThread mRttHandlerThread;
private final HalDeviceManager mHalDeviceManager;
private final WifiStateTracker mWifiStateTracker;
private final SelfRecovery mSelfRecovery;
@@ -222,7 +219,6 @@ public class WifiInjector {
private final DppMetrics mDppMetrics;
private final DppManager mDppManager;
private final WifiPulledAtomLogger mWifiPulledAtomLogger;
- private final LinkProbeManager mLinkProbeManager;
private IpMemoryStore mIpMemoryStore;
private final WifiThreadRunner mWifiThreadRunner;
private final WifiBlocklistMonitor mWifiBlocklistMonitor;
@@ -272,6 +268,7 @@ public class WifiInjector {
@NonNull private final ApplicationQosPolicyRequestHandler mApplicationQosPolicyRequestHandler;
private final WifiRoamingModeManager mWifiRoamingModeManager;
private final TwtManager mTwtManager;
+ private final WifiVoipDetector mWifiVoipDetector;
public WifiInjector(WifiContext context) {
if (context == null) {
@@ -331,8 +328,6 @@ public class WifiInjector {
mWifiDialogManager = new WifiDialogManager(mContext, mWifiThreadRunner, mFrameworkFacade,
this);
mSsidTranslator = new SsidTranslator(mContext, wifiHandler);
- mWifiP2pServiceHandlerThread = new HandlerThread("WifiP2pService");
- mWifiP2pServiceHandlerThread.start();
mPasspointProvisionerHandlerThread =
new HandlerThread("PasspointProvisionerHandlerThread");
mPasspointProvisionerHandlerThread.start();
@@ -384,7 +379,7 @@ public class WifiInjector {
mKeyStore = keyStore;
mWifiKeyStore = new WifiKeyStore(mContext, mKeyStore, mFrameworkFacade);
// New config store
- mWifiConfigStore = new WifiConfigStore(mContext, wifiHandler, mClock, mWifiMetrics,
+ mWifiConfigStore = new WifiConfigStore(mClock, mWifiMetrics,
WifiConfigStore.createSharedFiles(mFrameworkFacade.isNiapModeOn(mContext)));
mWifiPseudonymManager =
new WifiPseudonymManager(
@@ -458,8 +453,8 @@ public class WifiInjector {
mScanRequestProxy = new ScanRequestProxy(mContext,
mContext.getSystemService(AppOpsManager.class),
mContext.getSystemService(ActivityManager.class),
- this, mWifiConfigManager,
- mWifiPermissionsUtil, mWifiMetrics, mClock, wifiHandler, mSettingsConfigStore);
+ this, mWifiConfigManager, mWifiPermissionsUtil, mWifiMetrics, mClock,
+ mWifiThreadRunner, mSettingsConfigStore);
mWifiBlocklistMonitor.setScanRequestProxy(mScanRequestProxy);
mSarManager = new SarManager(mContext, makeTelephonyManager(), wifiLooper,
mWifiNative, mWifiDeviceStateChangeManager);
@@ -500,8 +495,6 @@ public class WifiInjector {
WifiChannelUtilization wifiChannelUtilizationConnected =
new WifiChannelUtilization(mClock, mContext);
mWifiMetrics.setWifiChannelUtilization(wifiChannelUtilizationConnected);
- mLinkProbeManager = new LinkProbeManager(mClock, mWifiNative, mWifiMetrics,
- mFrameworkFacade, wifiHandler, mContext);
mDefaultClientModeManager = new DefaultClientModeManager();
mExternalScoreUpdateObserverProxy =
new ExternalScoreUpdateObserverProxy(mWifiThreadRunner);
@@ -534,7 +527,8 @@ public class WifiInjector {
mContext, mCmiMonitor, mSettingsStore, wifiHandler, mClock);
mExternalPnoScanRequestManager = new ExternalPnoScanRequestManager(wifiHandler, mContext);
mCountryCode = new WifiCountryCode(mContext, mActiveModeWarden, mWifiP2pMetrics,
- mCmiMonitor, mWifiNative, mSettingsConfigStore, mClock, mWifiPermissionsUtil);
+ mCmiMonitor, mWifiNative, mSettingsConfigStore, mClock, mWifiPermissionsUtil,
+ mWifiCarrierInfoManager);
mWifiConnectivityManager = new WifiConnectivityManager(
mContext, mScoringParams, mWifiConfigManager,
mWifiNetworkSuggestionsManager, mWifiNetworkSelector,
@@ -629,6 +623,12 @@ public class WifiInjector {
mTwtManager = new TwtManager(this, mCmiMonitor, mWifiNative, wifiHandler, mClock,
WifiTwtSession.MAX_TWT_SESSIONS, 1);
mBackupRestoreController = new BackupRestoreController(mWifiSettingsBackupRestore, mClock);
+ if (mFeatureFlags.voipDetection() && SdkLevel.isAtLeastV()) {
+ mWifiVoipDetector = new WifiVoipDetector(mContext, wifiHandler, this,
+ mWifiCarrierInfoManager);
+ } else {
+ mWifiVoipDetector = null;
+ }
}
/**
@@ -669,7 +669,6 @@ public class WifiInjector {
mWifiConfigManager.enableVerboseLogging(verboseEnabled);
mPasspointManager.enableVerboseLogging(verboseEnabled);
mWifiNetworkFactory.enableVerboseLogging(verboseEnabled);
- mLinkProbeManager.enableVerboseLogging(verboseEnabled);
mMboOceController.enableVerboseLogging(verboseEnabled);
mWifiScoreCard.enableVerboseLogging(verboseEnabled);
mWifiHealthMonitor.enableVerboseLogging(verboseEnabled);
@@ -715,13 +714,6 @@ public class WifiInjector {
return mFrameworkFacade;
}
- public HandlerThread getWifiP2pServiceHandlerThread() {
- if (mFeatureFlags.singleWifiThread()) {
- return mWifiHandlerThread;
- }
- return mWifiP2pServiceHandlerThread;
- }
-
public HandlerThread getPasspointProvisionerHandlerThread() {
return mPasspointProvisionerHandlerThread;
}
@@ -738,13 +730,6 @@ public class WifiInjector {
mMockWifiModem = mockWifiServiceUtil;
}
- /**
- * Wrapper method for getting the current native Java Thread ID of the current thread.
- */
- public long getCurrentThreadId() {
- return Thread.currentThread().getId();
- }
-
public WifiTrafficPoller getWifiTrafficPoller() {
return mWifiTrafficPoller;
}
@@ -896,7 +881,7 @@ public class WifiInjector {
mLockManager, mFrameworkFacade, mWifiHandlerThread.getLooper(),
mWifiNative, new WrongPasswordNotifier(mContext, mFrameworkFacade,
mWifiNotificationManager),
- mWifiTrafficPoller, mLinkProbeManager, mClock.getElapsedSinceBootMillis(),
+ mWifiTrafficPoller, mClock.getElapsedSinceBootMillis(),
mBatteryStats, supplicantStateTracker, mMboOceController, mWifiCarrierInfoManager,
mWifiPseudonymManager,
new EapFailureNotifier(mContext, mFrameworkFacade, mWifiCarrierInfoManager,
@@ -1015,38 +1000,6 @@ public class WifiInjector {
return mWifiPermissionsWrapper;
}
- /**
- * Returns a singleton instance of a HandlerThread for injection. Uses lazy initialization.
- *
- * TODO: share worker thread with other Wi-Fi handlers (b/27924886)
- */
- public HandlerThread getWifiAwareHandlerThread() {
- if (mFeatureFlags.singleWifiThread()) {
- return mWifiHandlerThread;
- }
- if (mWifiAwareHandlerThread == null) { // lazy initialization
- mWifiAwareHandlerThread = new HandlerThread("wifiAwareService");
- mWifiAwareHandlerThread.start();
- }
- return mWifiAwareHandlerThread;
- }
-
- /**
- * Returns a singleton instance of a HandlerThread for injection. Uses lazy initialization.
- *
- * TODO: share worker thread with other Wi-Fi handlers (b/27924886)
- */
- public HandlerThread getRttHandlerThread() {
- if (mFeatureFlags.singleWifiThread()) {
- return mWifiHandlerThread;
- }
- if (mRttHandlerThread == null) { // lazy initialization
- mRttHandlerThread = new HandlerThread("wifiRttService");
- mRttHandlerThread.start();
- }
- return mRttHandlerThread;
- }
-
public MacAddressUtil getMacAddressUtil() {
return mMacAddressUtil;
}
@@ -1263,10 +1216,6 @@ public class WifiInjector {
return mDefaultClientModeManager;
}
- public LinkProbeManager getLinkProbeManager() {
- return mLinkProbeManager;
- }
-
public MultiInternetManager getMultiInternetManager() {
return mMultiInternetManager;
}
@@ -1341,4 +1290,9 @@ public class WifiInjector {
public BackupRestoreController getBackupRestoreController() {
return mBackupRestoreController;
}
+
+ @Nullable
+ public WifiVoipDetector getWifiVoipDetector() {
+ return mWifiVoipDetector;
+ }
}
diff --git a/service/java/com/android/server/wifi/WifiLastResortWatchdog.java b/service/java/com/android/server/wifi/WifiLastResortWatchdog.java
index 462e2b92ef..079ab35605 100644
--- a/service/java/com/android/server/wifi/WifiLastResortWatchdog.java
+++ b/service/java/com/android/server/wifi/WifiLastResortWatchdog.java
@@ -217,7 +217,8 @@ public class WifiLastResortWatchdog {
+ "Actually took " + durationMs + " milliseconds.";
logv("Triggering bug report for abnormal connection time.");
mWifiThreadRunner.post(() ->
- mWifiDiagnostics.takeBugReport(bugTitle, bugDetail));
+ mWifiDiagnostics.takeBugReport(bugTitle, bugDetail),
+ TAG + "#" + msg.what);
}
}
// Should reset last connection time after each connection regardless if bugreport
diff --git a/service/java/com/android/server/wifi/WifiMetrics.java b/service/java/com/android/server/wifi/WifiMetrics.java
index 806363d6eb..93cb2ab8d8 100644
--- a/service/java/com/android/server/wifi/WifiMetrics.java
+++ b/service/java/com/android/server/wifi/WifiMetrics.java
@@ -711,6 +711,7 @@ public class WifiMetrics {
private boolean mIsEcpsPriorityAccessSupported = false;
private NetworkDetail.HSRelease mHsRelease = NetworkDetail.HSRelease.Unknown;
private ApType6GHz mApType6GHz = ApType6GHz.AP_TYPE_6GHZ_UNKNOWN;
+ public @WifiAnnotations.ChannelWidth int mChannelWidth = ScanResult.UNSPECIFIED;
public String toString() {
StringBuilder sb = new StringBuilder();
@@ -746,6 +747,7 @@ public class WifiMetrics {
sb.append(", mApType6Ghz=" + mApType6GHz);
sb.append(", mIsEcpsPriorityAccessSupported=" + mIsEcpsPriorityAccessSupported);
sb.append(", mHsRelease=" + mHsRelease);
+ sb.append(", mChannelWidth" + mChannelWidth);
}
return sb.toString();
}
@@ -2129,6 +2131,20 @@ public class WifiMetrics {
}
/**
+ * Set channel width of the current connection.
+ */
+ public void setConnectionChannelWidth(String interfaceName,
+ @WifiAnnotations.ChannelWidth int channelWidth) {
+ synchronized (mLock) {
+ ConnectionEvent currentConnectionEvent = mCurrentConnectionEventPerIface.get(
+ interfaceName);
+ if (currentConnectionEvent != null) {
+ currentConnectionEvent.mRouterFingerPrint.mChannelWidth = channelWidth;
+ }
+ }
+ }
+
+ /**
* Set the max link speed supported by current network
*/
public void setConnectionMaxSupportedLinkSpeedMbps(
@@ -2646,6 +2662,25 @@ public class WifiMetrics {
== WifiStatsLog.WIFI_CONNECTION_RESULT_REPORTED__PASSPOINT_ROAMING_TYPE__ROAMING_RCOI_OPENROAMING_SETTLED;
}
+ private int convertChannelWidthToProto(@WifiAnnotations.ChannelWidth int channelWidth) {
+ switch(channelWidth) {
+ case ScanResult.CHANNEL_WIDTH_20MHZ:
+ return WifiStatsLog.WIFI_AP_CAPABILITIES_REPORTED__CHANNEL_WIDTH_MHZ__CHANNEL_WIDTH_20MHZ;
+ case ScanResult.CHANNEL_WIDTH_40MHZ:
+ return WifiStatsLog.WIFI_AP_CAPABILITIES_REPORTED__CHANNEL_WIDTH_MHZ__CHANNEL_WIDTH_40MHZ;
+ case ScanResult.CHANNEL_WIDTH_80MHZ:
+ return WifiStatsLog.WIFI_AP_CAPABILITIES_REPORTED__CHANNEL_WIDTH_MHZ__CHANNEL_WIDTH_80MHZ;
+ case ScanResult.CHANNEL_WIDTH_160MHZ:
+ return WifiStatsLog.WIFI_AP_CAPABILITIES_REPORTED__CHANNEL_WIDTH_MHZ__CHANNEL_WIDTH_160MHZ;
+ case ScanResult.CHANNEL_WIDTH_80MHZ_PLUS_MHZ:
+ return WifiStatsLog.WIFI_AP_CAPABILITIES_REPORTED__CHANNEL_WIDTH_MHZ__CHANNEL_WIDTH_80MHZ_PLUS_MHZ;
+ case ScanResult.CHANNEL_WIDTH_320MHZ:
+ return WifiStatsLog.WIFI_AP_CAPABILITIES_REPORTED__CHANNEL_WIDTH_MHZ__CHANNEL_WIDTH_320MHZ;
+ default:
+ return WifiStatsLog.WIFI_AP_CAPABILITIES_REPORTED__CHANNEL_WIDTH_MHZ__CHANNEL_WIDTH_UNKNOWN;
+ }
+ }
+
private void reportRouterCapabilities(RouterFingerPrint r) {
WifiStatsLog.write(WifiStatsLog.WIFI_AP_CAPABILITIES_REPORTED,
r.mIsFrameworkInitiatedRoaming, r.mRouterFingerPrintProto.channelInfo,
@@ -2661,7 +2696,8 @@ public class WifiMetrics {
r.mIsBroadcastTwtSupported, r.mIsRestrictedTwtSupported, r.mIs11McSupported,
r.mIs11AzSupported, convertHsReleasetoProto(r.mHsRelease),
r.mRouterFingerPrintProto.isPasspointHomeProvider,
- convertApType6GhzToProto(r.mApType6GHz), r.mIsEcpsPriorityAccessSupported);
+ convertApType6GhzToProto(r.mApType6GHz), r.mIsEcpsPriorityAccessSupported,
+ convertChannelWidthToProto(r.mChannelWidth));
}
/**
@@ -2705,7 +2741,8 @@ public class WifiMetrics {
toMetricEapType(mCurrentSession.mConnectionEvent.mEapType),
toMetricPhase2Method(mCurrentSession.mConnectionEvent.mPhase2Method),
mCurrentSession.mConnectionEvent.mPasspointRoamingType,
- mCurrentSession.mConnectionEvent.mCarrierId);
+ mCurrentSession.mConnectionEvent.mCarrierId,
+ mCurrentSession.mConnectionEvent.mUid);
mPreviousSession = mCurrentSession;
mCurrentSession = null;
@@ -2854,7 +2891,7 @@ public class WifiMetrics {
currentConnectionEvent.mRouterFingerPrint.mIsTwtRequired = networkDetail.isTwtRequired();
currentConnectionEvent.mRouterFingerPrint.mIsFilsSupported = networkDetail.isFilsCapable();
currentConnectionEvent.mRouterFingerPrint.mIs11AzSupported =
- networkDetail.is11azSupported();
+ networkDetail.is80211azNtbResponder() || networkDetail.is80211azTbResponder();
currentConnectionEvent.mRouterFingerPrint.mIs11McSupported =
networkDetail.is80211McResponderSupport();
currentConnectionEvent.mRouterFingerPrint.mIsMboSupported = networkDetail.isMboSupported();
diff --git a/service/java/com/android/server/wifi/WifiNative.java b/service/java/com/android/server/wifi/WifiNative.java
index 103d7982a6..9ec97ee493 100644
--- a/service/java/com/android/server/wifi/WifiNative.java
+++ b/service/java/com/android/server/wifi/WifiNative.java
@@ -20,6 +20,7 @@ import static android.net.wifi.WifiManager.WIFI_FEATURE_OWE;
import static com.android.server.wifi.HalDeviceManager.HDM_CREATE_IFACE_AP;
import static com.android.server.wifi.HalDeviceManager.HDM_CREATE_IFACE_AP_BRIDGE;
+import static com.android.server.wifi.HalDeviceManager.HDM_CREATE_IFACE_NAN;
import static com.android.server.wifi.HalDeviceManager.HDM_CREATE_IFACE_STA;
import static com.android.server.wifi.HalDeviceManager.HDM_CREATE_IFACE_P2P;
import static com.android.server.wifi.WifiSettingsConfigStore.WIFI_NATIVE_SUPPORTED_FEATURES;
@@ -75,6 +76,8 @@ import com.android.internal.util.HexDump;
import com.android.modules.utils.build.SdkLevel;
import com.android.server.wifi.SupplicantStaIfaceHal.QosPolicyStatus;
import com.android.server.wifi.hal.WifiChip;
+import com.android.server.wifi.hal.WifiHal;
+import com.android.server.wifi.hal.WifiNanIface;
import com.android.server.wifi.hotspot2.NetworkDetail;
import com.android.server.wifi.mockwifi.MockWifiServiceUtil;
import com.android.server.wifi.proto.WifiStatsLog;
@@ -368,9 +371,10 @@ public class WifiNative {
public static final int IFACE_TYPE_STA_FOR_CONNECTIVITY = 1;
public static final int IFACE_TYPE_STA_FOR_SCAN = 2;
public static final int IFACE_TYPE_P2P = 3;
+ public static final int IFACE_TYPE_NAN = 4;
@IntDef({IFACE_TYPE_AP, IFACE_TYPE_STA_FOR_CONNECTIVITY, IFACE_TYPE_STA_FOR_SCAN,
- IFACE_TYPE_P2P})
+ IFACE_TYPE_P2P, IFACE_TYPE_NAN})
@Retention(RetentionPolicy.SOURCE)
public @interface IfaceType{}
@@ -390,6 +394,7 @@ public class WifiNative {
public long featureSet;
public int bandsSupported;
public DeviceWiphyCapabilities phyCapabilities;
+ public WifiHal.WifiInterface iface;
Iface(int id, @Iface.IfaceType int type) {
this.id = id;
@@ -927,11 +932,11 @@ public class WifiNative {
private class VendorHalDeathHandlerInternal implements VendorHalDeathEventHandler {
@Override
public void onDeath() {
- synchronized (mLock) {
+ mHandler.post(() -> {
Log.i(TAG, "Vendor HAL died. Cleaning up internal state.");
onNativeDaemonDeath();
mWifiMetrics.incrementNumHalCrashes();
- }
+ });
}
}
@@ -941,11 +946,11 @@ public class WifiNative {
private class WificondDeathHandlerInternal implements Runnable {
@Override
public void run() {
- synchronized (mLock) {
+ mHandler.post(() -> {
Log.i(TAG, "wificond died. Cleaning up internal state.");
onNativeDaemonDeath();
mWifiMetrics.incrementNumWificondCrashes();
- }
+ });
}
}
@@ -956,11 +961,9 @@ public class WifiNative {
@Override
public void onDeath() {
mHandler.post(() -> {
- synchronized (mLock) {
- Log.i(TAG, "wpa_supplicant died. Cleaning up internal state.");
- onNativeDaemonDeath();
- mWifiMetrics.incrementNumSupplicantCrashes();
- }
+ Log.i(TAG, "wpa_supplicant died. Cleaning up internal state.");
+ onNativeDaemonDeath();
+ mWifiMetrics.incrementNumSupplicantCrashes();
});
}
}
@@ -971,11 +974,11 @@ public class WifiNative {
private class HostapdDeathHandlerInternal implements HostapdDeathEventHandler {
@Override
public void onDeath() {
- synchronized (mLock) {
+ mHandler.post(() -> {
Log.i(TAG, "hostapd died. Cleaning up internal state.");
onNativeDaemonDeath();
mWifiMetrics.incrementNumHostapdCrashes();
- }
+ });
}
}
@@ -1290,6 +1293,46 @@ public class WifiNative {
}
/**
+ * Helper function to handle creation of Nan iface.
+ */
+ public Iface createNanIface(
+ HalDeviceManager.InterfaceDestroyedListener nanInterfaceDestroyedListener,
+ Handler handler, WorkSource requestorWs) {
+ synchronized (mLock) {
+ // Make sure HAL is started for Nan
+ if (!startHal()) {
+ Log.e(TAG, "Failed to start Hal");
+ return null;
+ }
+ // maintain iface status in WifiNative
+ Iface iface = mIfaceMgr.allocateIface(Iface.IFACE_TYPE_NAN);
+ if (iface != null) {
+ WifiNanIface nanIface = mWifiInjector.getHalDeviceManager().createNanIface(
+ nanInterfaceDestroyedListener, handler, requestorWs);
+ if (nanIface != null) {
+ iface.iface = nanIface;
+ return iface;
+ }
+ }
+ Log.e(TAG, "Failed to allocate new Nan iface");
+ stopHalAndWificondIfNecessary();
+ return null;
+ }
+ }
+
+ /**
+ * Teardown Nan iface with input interface Id which was returned by createP2pIface.
+ *
+ * @param interfaceId the interface identify which was gerenated when creating P2p iface.
+ */
+ public void teardownNanIface(int interfaceId) {
+ synchronized (mLock) {
+ mIfaceMgr.removeIface(interfaceId);
+ stopHalAndWificondIfNecessary();
+ }
+ }
+
+ /**
* Get list of instance name from this bridged AP iface.
*
* @param ifaceName Name of the bridged interface.
@@ -3775,6 +3818,19 @@ public class WifiNative {
}
/**
+ * Returns whether Nan + STA concurrency is supported or not.
+ */
+ public boolean isNanStaConcurrencySupported() {
+ synchronized (mLock) {
+ return mWifiVendorHal.canDeviceSupportCreateTypeCombo(
+ new SparseArray<Integer>() {{
+ put(HDM_CREATE_IFACE_STA, 1);
+ put(HDM_CREATE_IFACE_NAN, 1);
+ }});
+ }
+ }
+
+ /**
* Returns whether a new AP iface can be created or not.
*/
public boolean isItPossibleToCreateApIface(@NonNull WorkSource requestorWs) {
@@ -4845,6 +4901,20 @@ public class WifiNative {
* @return the device capabilities for this interface
*/
public DeviceWiphyCapabilities getDeviceWiphyCapabilities(@NonNull String ifaceName) {
+ return getDeviceWiphyCapabilities(ifaceName, false);
+ }
+
+ /**
+ * Get the Wiphy capabilities of a device for a given interface
+ * If the interface is not associated with one,
+ * it will be read from the device through wificond
+ *
+ * @param ifaceName name of the interface
+ * @param isBridgedAp If the iface is bridge AP iface or not.
+ * @return the device capabilities for this interface
+ */
+ public DeviceWiphyCapabilities getDeviceWiphyCapabilities(@NonNull String ifaceName,
+ boolean isBridgedAp) {
synchronized (mLock) {
Iface iface = mIfaceMgr.getIface(ifaceName);
if (iface == null) {
@@ -4852,7 +4922,15 @@ public class WifiNative {
return null;
}
if (iface.phyCapabilities == null) {
- iface.phyCapabilities = mWifiCondManager.getDeviceWiphyCapabilities(ifaceName);
+ if (isBridgedAp) {
+ List<String> instances = getBridgedApInstances(ifaceName);
+ if (instances != null && instances.size() != 0) {
+ iface.phyCapabilities = mWifiCondManager.getDeviceWiphyCapabilities(
+ instances.get(0));
+ }
+ } else {
+ iface.phyCapabilities = mWifiCondManager.getDeviceWiphyCapabilities(ifaceName);
+ }
}
if (iface.phyCapabilities != null
&& iface.phyCapabilities.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE)
@@ -5335,6 +5413,15 @@ public class WifiNative {
}
/**
+ * Resend the previously configured MSCS parameters on this interface, if any exist.
+ *
+ * @param ifaceName Name of the interface.
+ */
+ public void resendMscs(String ifaceName) {
+ mSupplicantStaIfaceHal.resendMscs(ifaceName);
+ }
+
+ /**
* Disable Mirrored Stream Classification Service (MSCS).
*
* @param ifaceName Name of the interface.
@@ -5444,4 +5531,14 @@ public class WifiNative {
public boolean getStatsTwtSession(int commandId, String interfaceName, int sessionId) {
return mWifiVendorHal.getStatsTwtSession(commandId, interfaceName, sessionId);
}
+
+ /**
+ * Sets the wifi VoIP mode.
+ *
+ * @param mode Voip mode as defined by the enum |WifiVoipMode|
+ * @return true if successful, false otherwise.
+ */
+ public boolean setVoipMode(@WifiChip.WifiVoipMode int mode) {
+ return mWifiVendorHal.setVoipMode(mode);
+ }
}
diff --git a/service/java/com/android/server/wifi/WifiNetworkFactory.java b/service/java/com/android/server/wifi/WifiNetworkFactory.java
index 7d5fd28642..dc58ee4154 100644
--- a/service/java/com/android/server/wifi/WifiNetworkFactory.java
+++ b/service/java/com/android/server/wifi/WifiNetworkFactory.java
@@ -112,6 +112,8 @@ public class WifiNetworkFactory extends NetworkFactory {
@VisibleForTesting
public static final int USER_SELECTED_NETWORK_CONNECT_RETRY_MAX = 3; // max of 3 retries.
@VisibleForTesting
+ public static final int USER_APPROVED_SCAN_RETRY_MAX = 3; // max of 3 retries.
+ @VisibleForTesting
public static final String UI_START_INTENT_ACTION =
"com.android.settings.wifi.action.NETWORK_REQUEST";
@VisibleForTesting
@@ -174,6 +176,7 @@ public class WifiNetworkFactory extends NetworkFactory {
private boolean mShouldHaveInternetCapabilities = false;
private Set<Integer> mConnectedUids = new ArraySet<>();
private int mUserSelectedNetworkConnectRetryCount;
+ private int mUserApprovedScanRetryCount;
// Map of bssid to latest scan results for all scan results matching a request. Will be
// - null, if there are no active requests.
// - empty, if there are no matching scan results received for the active request.
@@ -629,7 +632,7 @@ public class WifiNetworkFactory extends NetworkFactory {
private void saveToStore() {
// Set the flag to let WifiConfigStore that we have new data to write.
mHasNewDataToSerialize = true;
- if (!mWifiConfigManager.saveToStore(true)) {
+ if (!mWifiConfigManager.saveToStore()) {
Log.w(TAG, "Failed to save to store");
}
}
@@ -939,6 +942,7 @@ public class WifiNetworkFactory extends NetworkFactory {
mActiveMatchedScanResults.values());
}
}
+ mUserApprovedScanRetryCount = 0;
startPeriodicScans();
}
}
@@ -1286,7 +1290,7 @@ public class WifiNetworkFactory extends NetworkFactory {
return;
}
- if (!mPendingConnectionSuccess) {
+ if (!mPendingConnectionSuccess || mActiveSpecificNetworkRequest == null) {
if (mConnectedSpecificNetworkRequest != null) {
Log.w(TAG, "Connection is terminated, cancelling "
+ mConnectedSpecificNetworkRequest);
@@ -1435,12 +1439,8 @@ public class WifiNetworkFactory extends NetworkFactory {
mConnectedSpecificNetworkRequestSpecifier = mActiveSpecificNetworkRequestSpecifier;
mConnectedUids.clear();
}
- if (mActiveSpecificNetworkRequest.getRequestorUid() == 0) {
- // For shell test call from root
- mConnectedUids.add(Process.SYSTEM_UID);
- } else {
- mConnectedUids.add(mActiveSpecificNetworkRequest.getRequestorUid());
- }
+
+ mConnectedUids.add(mActiveSpecificNetworkRequest.getRequestorUid());
mActiveSpecificNetworkRequest = null;
mActiveSpecificNetworkRequestSpecifier = null;
mSkipUserDialogue = false;
@@ -1613,6 +1613,13 @@ public class WifiNetworkFactory extends NetworkFactory {
Log.e(TAG, "Scan triggered when periodic scanning paused. Ignoring...");
return;
}
+ if (mVerboseLoggingEnabled) {
+ Log.v(TAG, "mUserSelectedScanRetryCount: " + mUserApprovedScanRetryCount);
+ }
+ if (mSkipUserDialogue && mUserApprovedScanRetryCount >= USER_APPROVED_SCAN_RETRY_MAX) {
+ cleanupActiveRequest();
+ return;
+ }
mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
mClock.getElapsedSinceBootMillis() + PERIODIC_SCAN_INTERVAL_MS,
TAG, mPeriodicScanTimerListener, mHandler);
@@ -1631,6 +1638,7 @@ public class WifiNetworkFactory extends NetworkFactory {
if (mVerboseLoggingEnabled) {
Log.v(TAG, "Starting the next scan for " + mActiveSpecificNetworkRequestSpecifier);
}
+ mUserApprovedScanRetryCount++;
// Create a worksource using the caller's UID.
WorkSource workSource = new WorkSource(mActiveSpecificNetworkRequest.getRequestorUid());
mWifiScanner.startScan(
diff --git a/service/java/com/android/server/wifi/WifiNetworkSelector.java b/service/java/com/android/server/wifi/WifiNetworkSelector.java
index 621d750995..12598a5d7b 100644
--- a/service/java/com/android/server/wifi/WifiNetworkSelector.java
+++ b/service/java/com/android/server/wifi/WifiNetworkSelector.java
@@ -21,6 +21,8 @@ import static android.net.wifi.WifiNetworkSelectionConfig.ASSOCIATED_NETWORK_SEL
import static android.net.wifi.WifiNetworkSelectionConfig.ASSOCIATED_NETWORK_SELECTION_OVERRIDE_ENABLED;
import static android.net.wifi.WifiNetworkSelectionConfig.ASSOCIATED_NETWORK_SELECTION_OVERRIDE_NONE;
+import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_PRIMARY;
+
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -426,12 +428,7 @@ public class WifiNetworkSelector {
}
- private boolean isNetworkSelectionNeeded(@NonNull List<ScanDetail> scanDetails,
- @NonNull List<ClientModeManagerState> cmmStates) {
- if (scanDetails.size() == 0) {
- localLog("Empty connectivity scan results. Skip network selection.");
- return false;
- }
+ private boolean isNetworkSelectionNeeded(@NonNull List<ClientModeManagerState> cmmStates) {
for (ClientModeManagerState cmmState : cmmStates) {
// network selection needed by this CMM instance, perform network selection
if (isNetworkSelectionNeededForCmm(cmmState)) {
@@ -814,8 +811,10 @@ public class WifiNetworkSelector {
if (seenNetworks.contains(tempConfig.getProfileKey())) {
Log.wtf(TAG, "user connected network is a loop, use candidate:"
+ candidate);
- mWifiConfigManager.setLegacyUserConnectChoice(candidate,
- candidate.getNetworkSelectionStatus().getCandidate().level);
+ if (candidate.getNetworkSelectionStatus().getCandidate() != null) {
+ mWifiConfigManager.setLegacyUserConnectChoice(candidate,
+ candidate.getNetworkSelectionStatus().getCandidate().level);
+ }
break;
}
seenNetworks.add(tempConfig.getProfileKey());
@@ -927,6 +926,7 @@ public class WifiNetworkSelector {
public final boolean ipProvisioningTimedOut;
/** Currently connected network */
public final WifiInfo wifiInfo;
+ public final ActiveModeManager.ClientRole role;
ClientModeManagerState(@NonNull ClientModeManager clientModeManager) {
ifaceName = clientModeManager.getInterfaceName();
@@ -934,6 +934,7 @@ public class WifiNetworkSelector {
disconnected = clientModeManager.isDisconnected();
ipProvisioningTimedOut = clientModeManager.isIpProvisioningTimedOut();
wifiInfo = clientModeManager.getConnectionInfo();
+ role = clientModeManager.getRole();
}
ClientModeManagerState() {
@@ -942,16 +943,19 @@ public class WifiNetworkSelector {
disconnected = true;
wifiInfo = new WifiInfo();
ipProvisioningTimedOut = false;
+ role = null;
}
@VisibleForTesting
ClientModeManagerState(@NonNull String ifaceName, boolean connected, boolean disconnected,
- @NonNull WifiInfo wifiInfo, boolean ipProvisioningTimedOut) {
+ @NonNull WifiInfo wifiInfo, boolean ipProvisioningTimedOut,
+ ActiveModeManager.ClientRole role) {
this.ifaceName = ifaceName;
this.connected = connected;
this.disconnected = disconnected;
this.wifiInfo = wifiInfo;
this.ipProvisioningTimedOut = ipProvisioningTimedOut;
+ this.role = role;
}
@Override
@@ -962,6 +966,7 @@ public class WifiNetworkSelector {
return Objects.equals(ifaceName, thatCmmState.ifaceName)
&& connected == thatCmmState.connected
&& disconnected == thatCmmState.disconnected
+ && role == thatCmmState.role
// Since wifiinfo does not have equals currently.
&& Objects.equals(wifiInfo.getSSID(), thatCmmState.wifiInfo.getSSID())
&& Objects.equals(wifiInfo.getBSSID(), thatCmmState.wifiInfo.getBSSID());
@@ -970,12 +975,13 @@ public class WifiNetworkSelector {
@Override
public int hashCode() {
return Objects.hash(ifaceName, connected, disconnected,
- wifiInfo.getSSID(), wifiInfo.getBSSID());
+ wifiInfo.getSSID(), wifiInfo.getBSSID(), role);
}
@Override
public String toString() {
return "ClientModeManagerState: " + ifaceName
+ + ", role:" + role
+ ", connection state: "
+ (connected ? " connected" : (disconnected ? " disconnected" : "unknown"))
+ ", WifiInfo: " + wifiInfo;
@@ -1036,6 +1042,20 @@ public class WifiNetworkSelector {
mLastSelectionWeightEnabled = enabled;
}
+ private String getConnectChoiceKey(@NonNull List<ClientModeManagerState> cmmStates) {
+ for (ClientModeManagerState cmmState : cmmStates) {
+ if (cmmState.role != ROLE_CLIENT_PRIMARY) {
+ continue;
+ }
+ WifiConfiguration currentNetwork =
+ mWifiConfigManager.getConfiguredNetwork(cmmState.wifiInfo.getNetworkId());
+ if (currentNetwork != null) {
+ return currentNetwork.getNetworkSelectionStatus().getConnectChoice();
+ }
+ }
+ return null;
+ }
+
/**
* Returns the list of Candidates from networks in range.
*
@@ -1048,15 +1068,14 @@ public class WifiNetworkSelector {
* @param oemPaidNetworkAllowed True if oem paid networks are allowed for connection
* @param oemPrivateNetworkAllowed True if oem private networks are allowed for connection
* @param restrictedNetworkAllowedUids a set of Uids are allowed for restricted network
- * @param multiInternetNetworkAllowed True if multi internet networks are allowed for
- * connection.
+ * @param skipSufficiencyCheck True to skip network sufficiency check
* @return list of valid Candidate(s)
*/
public List<WifiCandidates.Candidate> getCandidatesFromScan(
@NonNull List<ScanDetail> scanDetails, @NonNull Set<String> bssidBlocklist,
@NonNull List<ClientModeManagerState> cmmStates, boolean untrustedNetworkAllowed,
boolean oemPaidNetworkAllowed, boolean oemPrivateNetworkAllowed,
- Set<Integer> restrictedNetworkAllowedUids, boolean multiInternetNetworkAllowed) {
+ Set<Integer> restrictedNetworkAllowedUids, boolean skipSufficiencyCheck) {
mFilteredNetworks.clear();
mConnectableNetworks.clear();
if (scanDetails.size() == 0) {
@@ -1071,58 +1090,78 @@ public class WifiNetworkSelector {
for (NetworkNominator registeredNominator : mNominators) {
registeredNominator.update(scanDetails);
}
- // Update the matching profiles into WifiConfigManager, help displaying Passpoint networks
- // in Wifi Picker
- mWifiInjector.getPasspointNetworkNominateHelper().updatePasspointConfig(scanDetails);
-
- // Shall we start network selection at all?
- if (!multiInternetNetworkAllowed && !isNetworkSelectionNeeded(scanDetails, cmmStates)) {
- return null;
- }
// Filter out unwanted networks.
mFilteredNetworks = filterScanResults(scanDetails, bssidBlocklist, cmmStates);
if (mFilteredNetworks.size() == 0) {
return null;
}
+ // Update the matching profiles into WifiConfigManager, help displaying Passpoint networks
+ // in Wifi Picker
+ mWifiInjector.getPasspointNetworkNominateHelper().updatePasspointConfig(mFilteredNetworks);
+
+ boolean networkSelectionNeeded = skipSufficiencyCheck
+ || isNetworkSelectionNeeded(cmmStates);
+ final String userConnectChoiceKey;
+ if (!networkSelectionNeeded) {
+ if (!isAssociatedNetworkSelectionEnabled()) {
+ // Skip network selection based on connect choice because associated network
+ // selection is disabled.
+ return null;
+ }
+ userConnectChoiceKey = getConnectChoiceKey(cmmStates);
+ if (userConnectChoiceKey == null) {
+ return null;
+ }
+ // Continue candidate selection but only allow the user connect choice as candidate
+ localLog("Current network is sufficient. Continue network selection only "
+ + "considering user connect choice: " + userConnectChoiceKey);
+ } else {
+ userConnectChoiceKey = null;
+ }
WifiCandidates wifiCandidates = new WifiCandidates(mWifiScoreCard, mContext);
- for (ClientModeManagerState cmmState : cmmStates) {
- // Always get the current BSSID from WifiInfo in case that firmware initiated
- // roaming happened.
- String currentBssid = cmmState.wifiInfo.getBSSID();
- WifiConfiguration currentNetwork =
- mWifiConfigManager.getConfiguredNetwork(cmmState.wifiInfo.getNetworkId());
- if (currentNetwork != null) {
- wifiCandidates.setCurrent(currentNetwork.networkId, currentBssid);
- // We always want the current network to be a candidate so that it can participate.
- // It may also get re-added by a nominator, in which case this fallback
- // will be replaced.
- MacAddress bssid = MacAddress.fromString(currentBssid);
- SecurityParams params = currentNetwork.getNetworkSelectionStatus()
- .getLastUsedSecurityParams();
- if (null == params) {
- localLog("No known candidate security params for current network.");
- continue;
+ if (userConnectChoiceKey == null) {
+ // Add connected network as candidates unless only considering connect choice.
+ for (ClientModeManagerState cmmState : cmmStates) {
+ // Always get the current BSSID from WifiInfo in case that firmware initiated
+ // roaming happened.
+ String currentBssid = cmmState.wifiInfo.getBSSID();
+ WifiConfiguration currentNetwork =
+ mWifiConfigManager.getConfiguredNetwork(cmmState.wifiInfo.getNetworkId());
+ if (currentNetwork != null) {
+ wifiCandidates.setCurrent(currentNetwork.networkId, currentBssid);
+ // We always want the current network to be a candidate so that it can
+ // participate.
+ // It may also get re-added by a nominator, in which case this fallback
+ // will be replaced.
+ MacAddress bssid = MacAddress.fromString(currentBssid);
+ SecurityParams params = currentNetwork.getNetworkSelectionStatus()
+ .getLastUsedSecurityParams();
+ if (null == params) {
+ localLog("No known candidate security params for current network.");
+ continue;
+ }
+ WifiCandidates.Key key = new WifiCandidates.Key(
+ ScanResultMatchInfo.fromWifiConfiguration(currentNetwork),
+ bssid, currentNetwork.networkId,
+ params.getSecurityType());
+ ScanDetail scanDetail = findScanDetailForBssid(mFilteredNetworks, currentBssid);
+ int predictedTputMbps = (scanDetail == null) ? 0
+ : predictThroughput(scanDetail);
+ wifiCandidates.add(key, currentNetwork,
+ NetworkNominator.NOMINATOR_ID_CURRENT,
+ cmmState.wifiInfo.getRssi(),
+ cmmState.wifiInfo.getFrequency(),
+ ScanResult.CHANNEL_WIDTH_20MHZ, // channel width unavailable in WifiInfo
+ calculateLastSelectionWeight(currentNetwork.networkId,
+ WifiConfiguration.isMetered(currentNetwork, cmmState.wifiInfo)),
+ WifiConfiguration.isMetered(currentNetwork, cmmState.wifiInfo),
+ isFromCarrierOrPrivilegedApp(currentNetwork),
+ predictedTputMbps,
+ (scanDetail != null) ? scanDetail.getScanResult().getApMldMacAddress()
+ : null);
}
- WifiCandidates.Key key = new WifiCandidates.Key(
- ScanResultMatchInfo.fromWifiConfiguration(currentNetwork),
- bssid, currentNetwork.networkId,
- params.getSecurityType());
- ScanDetail scanDetail = findScanDetailForBssid(mFilteredNetworks, currentBssid);
- int predictedTputMbps = (scanDetail == null) ? 0 : predictThroughput(scanDetail);
- wifiCandidates.add(key, currentNetwork,
- NetworkNominator.NOMINATOR_ID_CURRENT,
- cmmState.wifiInfo.getRssi(),
- cmmState.wifiInfo.getFrequency(),
- ScanResult.CHANNEL_WIDTH_20MHZ, // channel width not available in WifiInfo
- calculateLastSelectionWeight(currentNetwork.networkId,
- WifiConfiguration.isMetered(currentNetwork, cmmState.wifiInfo)),
- WifiConfiguration.isMetered(currentNetwork, cmmState.wifiInfo),
- isFromCarrierOrPrivilegedApp(currentNetwork),
- predictedTputMbps,
- (scanDetail != null) ? scanDetail.getScanResult().getApMldMacAddress()
- : null);
}
}
@@ -1141,6 +1180,10 @@ public class WifiNetworkSelector {
WifiCandidates.Key key = wifiCandidates.keyFromScanDetailAndConfig(
scanDetail, config);
if (key != null) {
+ if (userConnectChoiceKey != null
+ && !userConnectChoiceKey.equals(config.getProfileKey())) {
+ return;
+ }
boolean metered = false;
for (ClientModeManagerState cmmState : cmmStates) {
if (isEverMetered(config, cmmState.wifiInfo, scanDetail)) {
@@ -1399,6 +1442,7 @@ public class WifiNetworkSelector {
.getConfiguredNetworkWithPassword(config.networkId);
if (configWithPassword.isSecurityType(WifiConfiguration.SECURITY_TYPE_PSK)
&& configWithPassword.isSecurityType(WifiConfiguration.SECURITY_TYPE_SAE)
+ && configWithPassword.preSharedKey != null
&& !configWithPassword.preSharedKey.startsWith("\"")
&& configWithPassword.preSharedKey.length() == 64
&& configWithPassword.preSharedKey.matches("[0-9A-Fa-f]{64}")) {
@@ -1415,9 +1459,11 @@ public class WifiNetworkSelector {
private void updateSecurityParamsForTransitionModeIfNecessary(
ScanResult scanResult, SecurityParams params) {
if (params.isSecurityType(WifiConfiguration.SECURITY_TYPE_SAE)
+ && params.isAddedByAutoUpgrade()
&& ScanResultUtil.isScanResultForPskSaeTransitionNetwork(scanResult)) {
params.setRequirePmf(false);
} else if (params.isSecurityType(WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE)
+ && params.isAddedByAutoUpgrade()
&& ScanResultUtil.isScanResultForWpa3EnterpriseTransitionNetwork(scanResult)) {
params.setRequirePmf(false);
}
@@ -1464,7 +1510,7 @@ public class WifiNetworkSelector {
/**
* Using the registered Scorers, choose the best network from the list of Candidate(s).
* The ScanDetailCache is also updated here.
- * @param candidates - Candidates to perferm network selection on.
+ * @param candidates - Candidates to perform network selection on.
* @param overrideEnabled If it is allowed to override candidate with User Connect Choice.
* @return WifiConfiguration - the selected network, or null.
*/
diff --git a/service/java/com/android/server/wifi/WifiNetworkSuggestionsManager.java b/service/java/com/android/server/wifi/WifiNetworkSuggestionsManager.java
index b43798659a..60f4d948cb 100644
--- a/service/java/com/android/server/wifi/WifiNetworkSuggestionsManager.java
+++ b/service/java/com/android/server/wifi/WifiNetworkSuggestionsManager.java
@@ -379,7 +379,8 @@ public class WifiNetworkSuggestionsManager {
config.shared = false;
config.allowAutojoin = isAutojoinEnabled;
if (config.enterpriseConfig
- != null && config.enterpriseConfig.isAuthenticationSimBased()) {
+ != null && config.enterpriseConfig.isAuthenticationSimBased()
+ && anonymousIdentity != null) {
config.enterpriseConfig.setAnonymousIdentity(anonymousIdentity);
}
config.getNetworkSelectionStatus().setConnectChoice(connectChoice);
@@ -466,6 +467,7 @@ public class WifiNetworkSuggestionsManager {
private boolean mIsLastUserApprovalUiDialog = false;
private boolean mUserDataLoaded = false;
+ private boolean mIsDeviceShuttingDown = false;
/**
* Keep a set of packageNames which is treated as carrier provider.
@@ -708,7 +710,7 @@ public class WifiNetworkSuggestionsManager {
private void saveToStore() {
// Set the flag to let WifiConfigStore that we have new data to write.
mHasNewDataToSerialize = true;
- if (!mWifiConfigManager.saveToStore(true)) {
+ if (!mWifiConfigManager.saveToStore()) {
Log.w(TAG, "Failed to save to store");
}
}
@@ -900,8 +902,9 @@ public class WifiNetworkSuggestionsManager {
Log.e(TAG, "UID " + uid + " not visible to the current user");
return WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL;
}
- if (!mUserDataLoaded) {
- Log.e(TAG, "Add Network suggestion before boot complete is not allowed.");
+ if (!mUserDataLoaded || mIsDeviceShuttingDown) {
+ Log.e(TAG, "Add Network suggestion before boot complete or when device is "
+ + "shutting down is not allowed.");
return WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL;
}
if (networkSuggestions == null || networkSuggestions.isEmpty()) {
@@ -1392,8 +1395,9 @@ public class WifiNetworkSuggestionsManager {
Log.e(TAG, "UID " + uid + " not visible to the current user");
return WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL;
}
- if (!mUserDataLoaded) {
- Log.e(TAG, "Remove Network suggestion before boot complete is not allowed.");
+ if (!mUserDataLoaded || mIsDeviceShuttingDown) {
+ Log.e(TAG, "Remove Network suggestion before boot complete or when device is "
+ + "shutting down is not allowed.");
return WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL;
}
if (networkSuggestions == null) {
@@ -2874,4 +2878,11 @@ public class WifiNetworkSuggestionsManager {
}
saveToStore();
}
+
+ /**
+ * Handle device shut down
+ */
+ public void handleShutDown() {
+ mIsDeviceShuttingDown = true;
+ }
}
diff --git a/service/java/com/android/server/wifi/WifiRoamingConfigStore.java b/service/java/com/android/server/wifi/WifiRoamingConfigStore.java
index adce4365fc..bc3b780d71 100644
--- a/service/java/com/android/server/wifi/WifiRoamingConfigStore.java
+++ b/service/java/com/android/server/wifi/WifiRoamingConfigStore.java
@@ -65,7 +65,7 @@ public class WifiRoamingConfigStore {
*/
private void triggerSaveToStore() {
mHasNewDataToSerialize = true;
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
}
/**
diff --git a/service/java/com/android/server/wifi/WifiScoreReport.java b/service/java/com/android/server/wifi/WifiScoreReport.java
index 43c87a60d5..107a6449bd 100644
--- a/service/java/com/android/server/wifi/WifiScoreReport.java
+++ b/service/java/com/android/server/wifi/WifiScoreReport.java
@@ -43,6 +43,7 @@ import androidx.annotation.RequiresApi;
import com.android.internal.annotations.VisibleForTesting;
import com.android.modules.utils.build.SdkLevel;
import com.android.server.wifi.ActiveModeManager.ClientRole;
+import com.android.server.wifi.util.RssiUtil;
import com.android.server.wifi.util.StringUtil;
import com.android.wifi.resources.R;
@@ -204,7 +205,7 @@ public class WifiScoreReport {
// redundant codes below and in ClientModeImpl#fetchRssiLinkSpeedAndFrequencyNative.
WifiSignalPollResults pollResults = mWifiNative.signalPoll(mInterfaceName);
if (pollResults != null) {
- int newRssi = pollResults.getRssi();
+ int newRssi = RssiUtil.calculateAdjustedRssi(pollResults.getRssi());
int newTxLinkSpeed = pollResults.getTxLinkSpeed();
int newFrequency = pollResults.getFrequency();
int newRxLinkSpeed = pollResults.getRxLinkSpeed();
@@ -220,14 +221,8 @@ public class WifiScoreReport {
link.setBand(ScanResult.toBand(pollResults.getFrequency(linkId)));
}
- if (newRssi > WifiInfo.INVALID_RSSI && newRssi < WifiInfo.MAX_RSSI) {
- if (newRssi > (WifiInfo.INVALID_RSSI + 256)) {
- Log.wtf(TAG, "Error! +ve value RSSI: " + newRssi);
- newRssi -= 256;
- }
+ if (newRssi > WifiInfo.INVALID_RSSI) {
mWifiInfo.setRssi(newRssi);
- } else {
- mWifiInfo.setRssi(WifiInfo.INVALID_RSSI);
}
/*
* set Tx link speed only if it is valid
@@ -459,7 +454,8 @@ public class WifiScoreReport {
*/
@Override
public void binderDied() {
- mWifiThreadRunner.post(() -> revertToDefaultConnectedScorer());
+ mWifiThreadRunner.post(() -> revertToDefaultConnectedScorer(),
+ "WifiConnectedNetworkScorerHolder#binderDied");
}
/**
diff --git a/service/java/com/android/server/wifi/WifiServiceImpl.java b/service/java/com/android/server/wifi/WifiServiceImpl.java
index 4e53489199..30066a2387 100644
--- a/service/java/com/android/server/wifi/WifiServiceImpl.java
+++ b/service/java/com/android/server/wifi/WifiServiceImpl.java
@@ -112,6 +112,7 @@ import android.net.wifi.ILastCallerListener;
import android.net.wifi.IListListener;
import android.net.wifi.ILocalOnlyConnectionStatusListener;
import android.net.wifi.ILocalOnlyHotspotCallback;
+import android.net.wifi.IMacAddressListListener;
import android.net.wifi.IMapListener;
import android.net.wifi.INetworkRequestMatchCallback;
import android.net.wifi.IOnWifiActivityEnergyInfoListener;
@@ -167,6 +168,7 @@ import android.net.wifi.twt.TwtRequest;
import android.net.wifi.twt.TwtSession;
import android.net.wifi.twt.TwtSessionCallback;
import android.net.wifi.util.ScanResultUtil;
+import android.net.wifi.util.WifiResourceCache;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
@@ -191,6 +193,7 @@ import android.telephony.PhoneStateListener;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
+import android.util.ArraySet;
import android.util.EventLog;
import android.util.Log;
import android.util.Pair;
@@ -332,6 +335,7 @@ public class WifiServiceImpl extends BaseWifiService {
private static final String CERT_INSTALLER_PKG = "com.android.certinstaller";
private final WifiSettingsConfigStore mSettingsConfigStore;
+ private final WifiResourceCache mWifiResourceCache;
/**
* Callback for use with LocalOnlyHotspot to unregister requesting applications upon death.
@@ -366,7 +370,7 @@ public class WifiServiceImpl extends BaseWifiService {
mActiveModeWarden.updateSoftApCapability(
mTetheredSoftApTracker.getSoftApCapability(),
WifiManager.IFACE_IP_MODE_TETHERED);
- });
+ }, this.getClass().getSimpleName() + "#onActiveDataSubscriptionIdChanged");
}
}
@@ -510,9 +514,9 @@ public class WifiServiceImpl extends BaseWifiService {
}
}
-
public WifiServiceImpl(WifiContext context, WifiInjector wifiInjector) {
mContext = context;
+ mWifiResourceCache = mContext.getResourceCache();
mWifiInjector = wifiInjector;
mClock = wifiInjector.getClock();
@@ -602,6 +606,15 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiInjector.getWifiScanAlwaysAvailableSettingsCompatibility().initialize();
mWifiInjector.getWifiNotificationManager().createNotificationChannels();
// Align the value between config stroe (i.e.WifiConfigStore.xml) and WifiGlobals.
+ mSettingsConfigStore.registerChangeListener(WIFI_WEP_ALLOWED,
+ (key, value) -> {
+ if (mWifiGlobals.isWepAllowed() != value) {
+ // It should only happen when settings is restored from cloud.
+ handleWepAllowedChanged(value);
+ Log.i(TAG, "(Cloud Restoration) Wep allowed is changed to " + value);
+ }
+ },
+ new Handler(mWifiHandlerThread.getLooper()));
mWifiGlobals.setWepAllowed(mSettingsConfigStore.get(WIFI_WEP_ALLOWED));
mContext.registerReceiver(
new BroadcastReceiver() {
@@ -721,7 +734,7 @@ public class WifiServiceImpl extends BaseWifiService {
registerForCarrierConfigChange();
mWifiInjector.getAdaptiveConnectivityEnabledSettingObserver().initialize();
mIsWifiServiceStarted = true;
- });
+ }, TAG + "#checkAndStartWifi");
}
private void setPulledAtomCallbacks() {
@@ -772,7 +785,8 @@ public class WifiServiceImpl extends BaseWifiService {
for (ClientModeManager cmm : mActiveModeWarden.getClientModeManagers()) {
cmm.resetSimAuthNetworks(resetReason);
}
- mWifiThreadRunner.post(mWifiNetworkSuggestionsManager::updateCarrierPrivilegedApps);
+ mWifiThreadRunner.post(mWifiNetworkSuggestionsManager::updateCarrierPrivilegedApps,
+ TAG + "#resetCarrierNetworks$1");
if (resetReason == RESET_SIM_REASON_SIM_INSERTED) {
// clear the blocklists in case any SIM based network were disabled due to the SIM
// not being available.
@@ -784,7 +798,8 @@ public class WifiServiceImpl extends BaseWifiService {
// mWifiNetworkSuggestionsManager#updateCarrierPrivilegedApps
mWifiThreadRunner.post(() -> mWifiConfigManager
.removeEphemeralCarrierNetworks(mWifiCarrierInfoManager
- .getCurrentCarrierPrivilegedPackages()));
+ .getCurrentCarrierPrivilegedPackages()),
+ TAG + "#resetCarrierNetworks$2");
}
}
@@ -871,7 +886,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiInjector.getWifiDeviceStateChangeManager().handleBootCompleted();
setPulledAtomCallbacks();
mTwtManager.registerWifiNativeTwtEvents();
- });
+ }, TAG + "#handleBootCompleted");
}
public void handleUserSwitch(int userId) {
@@ -880,17 +895,19 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
mWifiConfigManager.handleUserSwitch(userId);
resetNotificationManager();
- });
+ }, TAG + "#handleUserSwitch");
}
public void handleUserUnlock(int userId) {
Log.d(TAG, "Handle user unlock " + userId);
- mWifiThreadRunner.post(() -> mWifiConfigManager.handleUserUnlock(userId));
+ mWifiThreadRunner.post(() -> mWifiConfigManager.handleUserUnlock(userId),
+ TAG + "#handleUserUnlock");
}
public void handleUserStop(int userId) {
Log.d(TAG, "Handle user stop " + userId);
- mWifiThreadRunner.post(() -> mWifiConfigManager.handleUserStop(userId));
+ mWifiThreadRunner.post(() -> mWifiConfigManager.handleUserStop(userId),
+ TAG + "#handleUserStop");
}
/**
@@ -929,7 +946,8 @@ public class WifiServiceImpl extends BaseWifiService {
mLastCallerInfoManager.put(WifiManager.API_START_SCAN, Process.myTid(),
callingUid, Binder.getCallingPid(), packageName, true);
Boolean scanSuccess = mWifiThreadRunner.call(() ->
- mScanRequestProxy.startScan(callingUid, packageName), null);
+ mScanRequestProxy.startScan(callingUid, packageName), null,
+ TAG + "#startScan");
if (scanSuccess == null) {
sendFailedScanBroadcast();
return false;
@@ -1007,6 +1025,9 @@ public class WifiServiceImpl extends BaseWifiService {
}
private void handleShutDown() {
+ if (mVerboseLoggingEnabled) {
+ Log.v(TAG, "handleShutDown");
+ }
// Direct call to notify ActiveModeWarden as soon as possible with the assumption that
// notifyShuttingDown() doesn't have codes that may cause concurrentModificationException,
// e.g., access to a collection.
@@ -1017,7 +1038,8 @@ public class WifiServiceImpl extends BaseWifiService {
// before memory store write triggered by mMemoryStoreImpl.stop().
mWifiScoreCard.resetAllConnectionStates();
mMemoryStoreImpl.stop();
- mWifiConfigManager.handleShutDown();
+ mWifiConfigManager.writeDataToStorage();
+ mWifiNetworkSuggestionsManager.handleShutDown();
}
private boolean checkNetworkSettingsPermission(int pid, int uid) {
@@ -1182,10 +1204,7 @@ public class WifiServiceImpl extends BaseWifiService {
&& !isGuestUser())
|| isPrivileged(pid, uid)
|| mWifiPermissionsUtil.isAdmin(uid, packageName)
- || mWifiPermissionsUtil.isSystem(packageName, uid)
- // TODO(b/140540984): Remove this bypass.
- || (mWifiPermissionsUtil.checkSystemAlertWindowPermission(uid, packageName)
- && !isGuestUser());
+ || mWifiPermissionsUtil.isSystem(packageName, uid);
}
private boolean isGuestUser() {
@@ -1233,7 +1252,7 @@ public class WifiServiceImpl extends BaseWifiService {
private ClientModeManager getPrimaryClientModeManagerBlockingThreadSafe() {
return mWifiThreadRunner.call(
() -> mActiveModeWarden.getPrimaryClientModeManager(),
- mDefaultClientModeManager);
+ mDefaultClientModeManager, TAG + "#getPrimaryClientModeManagerBlockingThreadSafe");
}
/**
@@ -1282,13 +1301,19 @@ public class WifiServiceImpl extends BaseWifiService {
return false;
}
- // If user restriction is set, only DO/PO is allowed to toggle wifi
- if (SdkLevel.isAtLeastT() && mUserManager.hasUserRestrictionForUser(
- UserManager.DISALLOW_CHANGE_WIFI_STATE,
- UserHandle.getUserHandleForUid(callingUid))
- && !isDeviceOrProfileOwner(callingUid, packageName)) {
- mLog.err("setWifiEnabled with user restriction: only DO/PO can toggle wifi").flush();
- return false;
+ long ident = Binder.clearCallingIdentity();
+ try {
+ // If user restriction is set, only DO/PO is allowed to toggle wifi
+ if (SdkLevel.isAtLeastT() && mUserManager.hasUserRestrictionForUser(
+ UserManager.DISALLOW_CHANGE_WIFI_STATE,
+ UserHandle.getUserHandleForUid(callingUid))
+ && !isDeviceOrProfileOwner(callingUid, packageName)) {
+ mLog.err(
+ "setWifiEnabled with user restriction: only DO/PO can toggle wifi").flush();
+ return false;
+ }
+ } finally {
+ Binder.restoreCallingIdentity(ident);
}
// Show a user-confirmation dialog for legacy third-party apps targeting less than Q.
@@ -1303,7 +1328,7 @@ public class WifiServiceImpl extends BaseWifiService {
return;
}
showWifiEnableRequestDialog(callingUid, callingPid, packageName);
- });
+ }, TAG + "#setWifiEnabled");
return true;
}
setWifiEnabledInternal(packageName, enable, callingUid, callingPid, isPrivileged);
@@ -1331,12 +1356,13 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiEnableRequestDialogHandles.valueAt(i).dismissDialog();
}
mWifiEnableRequestDialogHandles.clear();
- });
+ }, TAG + "#setWifiEnabledInternal$1");
}
if (mWifiPermissionsUtil.checkNetworkSettingsPermission(callingUid)) {
if (enable) {
mWifiThreadRunner.post(
- () -> mWifiConnectivityManager.setAutoJoinEnabledExternal(true, false));
+ () -> mWifiConnectivityManager.setAutoJoinEnabledExternal(true, false),
+ TAG + "#setWifiEnabledInternal$2");
mWifiMetrics.logUserActionEvent(UserActionEvent.EVENT_TOGGLE_WIFI_ON);
} else {
WifiInfo wifiInfo = mActiveModeWarden.getConnectionInfo();
@@ -1428,7 +1454,7 @@ public class WifiServiceImpl extends BaseWifiService {
if (!mActiveModeWarden.registerSubsystemRestartCallback(callback)) {
Log.e(TAG, "registerSubsystemRestartCallback: Failed to register callback");
}
- });
+ }, TAG + "#registerSubsystemRestartCallback");
}
@RequiresApi(Build.VERSION_CODES.S)
@@ -1445,7 +1471,7 @@ public class WifiServiceImpl extends BaseWifiService {
if (!mActiveModeWarden.unregisterSubsystemRestartCallback(callback)) {
Log.e(TAG, "unregisterSubsystemRestartCallback: Failed to register callback");
}
- });
+ }, TAG + "#unregisterSubsystemRestartCallback");
}
/**
@@ -1464,7 +1490,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
mWifiThreadRunner.post(() -> {
mActiveModeWarden.addWifiNetworkStateChangedListener(listener);
- });
+ }, TAG + "#addWifiNetworkStateChangedListener");
}
/**
@@ -1484,7 +1510,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
mWifiThreadRunner.post(() -> {
mActiveModeWarden.removeWifiNetworkStateChangedListener(listener);
- });
+ }, TAG + "#removeWifiNetworkStateChangedListener");
}
@RequiresApi(Build.VERSION_CODES.S)
@@ -1502,7 +1528,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiMetrics.logUserActionEvent(UserActionEvent.EVENT_RESTART_WIFI_SUB_SYSTEM,
wifiInfo == null ? -1 : wifiInfo.getNetworkId());
mWifiInjector.getSelfRecovery().trigger(REASON_API_CALL);
- });
+ }, TAG + "#restartWifiSubsystem");
}
/**
@@ -1521,7 +1547,7 @@ public class WifiServiceImpl extends BaseWifiService {
// This is only needed for pre-T.
if (state == WifiManager.WIFI_STATE_ENABLING && !SdkLevel.isAtLeastT()) {
state = mWifiThreadRunner.call(() -> mActiveModeWarden.getWifiState(),
- WifiManager.WIFI_STATE_ENABLING);
+ WifiManager.WIFI_STATE_ENABLING, TAG + "#getWifiEnabledState");
}
if (mVerboseLoggingEnabled) {
mLog.info("getWifiEnabledState uid=% state=%").c(Binder.getCallingUid()).c(
@@ -1565,7 +1591,8 @@ public class WifiServiceImpl extends BaseWifiService {
enforceNetworkStackPermission();
mLog.info("updateInterfaceIpState uid=%").c(Binder.getCallingUid()).flush();
// hand off the work to our handler thread
- mWifiThreadRunner.post(() -> mLohsSoftApTracker.updateInterfaceIpState(ifaceName, mode));
+ mWifiThreadRunner.post(() -> mLohsSoftApTracker.updateInterfaceIpState(ifaceName, mode),
+ TAG + "#updateInterfaceIpState");
}
/**
@@ -1600,7 +1627,8 @@ public class WifiServiceImpl extends BaseWifiService {
return;
}
mWifiThreadRunner.post(() ->
- mCoexManager.setCoexUnsafeChannels(unsafeChannels, restrictions));
+ mCoexManager.setCoexUnsafeChannels(unsafeChannels, restrictions),
+ TAG + "#setCoexUnsafeChannels");
}
/**
@@ -1619,7 +1647,8 @@ public class WifiServiceImpl extends BaseWifiService {
if (mVerboseLoggingEnabled) {
mLog.info("registerCoexCallback uid=%").c(Binder.getCallingUid()).flush();
}
- mWifiThreadRunner.post(() -> mCoexManager.registerRemoteCoexCallback(callback));
+ mWifiThreadRunner.post(() -> mCoexManager.registerRemoteCoexCallback(callback),
+ TAG + "#registerCoexCallback");
}
/**
@@ -1656,7 +1685,8 @@ public class WifiServiceImpl extends BaseWifiService {
if (mVerboseLoggingEnabled) {
mLog.info("unregisterCoexCallback uid=%").c(Binder.getCallingUid()).flush();
}
- mWifiThreadRunner.post(() -> mCoexManager.unregisterRemoteCoexCallback(callback));
+ mWifiThreadRunner.post(() -> mCoexManager.unregisterRemoteCoexCallback(callback),
+ TAG + "#unregisterCoexCallback");
}
/**
@@ -1738,7 +1768,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
/**
- * see {@link WifiManager#startTetheredHotspotRequest(TetheringManager.TetheringRequest)}
+ * see {@link WifiManager#startTetheredHotspot(TetheringManager.TetheringRequest, Executor, WifiManager.SoftApCallback)}
* @param request TetheringRequest details of the Soft AP.
* @return {@code true} if softap start was triggered
* @throws SecurityException if the caller does not have permission to start softap
@@ -1771,7 +1801,7 @@ public class WifiServiceImpl extends BaseWifiService {
return;
}
- mLog.info("startTetheredHotspotRequest uid=%").c(callingUid).flush();
+ mLog.info("startTetheredHotspot uid=%").c(callingUid).flush();
startTetheredHotspotInternal(new SoftApModeConfiguration(
WifiManager.IFACE_IP_MODE_TETHERED, null /* config */,
mTetheredSoftApTracker.getSoftApCapability(),
@@ -1941,7 +1971,7 @@ public class WifiServiceImpl extends BaseWifiService {
if (mLohsSoftApTracker != null) {
mLohsSoftApTracker.notifyNewCountryCodeChangePending(countryCode);
}
- });
+ }, this.getClass().getSimpleName() + "#onCountryCodeChangePending");
}
@Override
@@ -2024,7 +2054,7 @@ public class WifiServiceImpl extends BaseWifiService {
mRegisteredDriverCountryCodeListeners.finishBroadcast();
}
mAfcManager.onCountryCodeChange(countryCode);
- });
+ }, this.getClass().getSimpleName() + "#onCountryCodeChangePending");
}
}
@@ -2440,7 +2470,7 @@ public class WifiServiceImpl extends BaseWifiService {
if (mLocalOnlyHotspotRequests.isEmpty()) {
mWifiThreadRunner.post(() -> {
startForFirstRequestLocked(request);
- });
+ }, "LohsSoftApTracker#start");
} else if (mLohsInterfaceMode == WifiManager.IFACE_IP_MODE_LOCAL_ONLY) {
// LOHS has already started up for an earlier request, so we can send the
@@ -2634,7 +2664,7 @@ public class WifiServiceImpl extends BaseWifiService {
Log.e(TAG, "registerSoftApCallback: Failed to add callback");
return;
}
- });
+ }, TAG + "#registerSoftApCallback");
}
/**
@@ -2662,7 +2692,8 @@ public class WifiServiceImpl extends BaseWifiService {
// post operation to handler thread
mWifiThreadRunner.post(() ->
- mTetheredSoftApTracker.unregisterSoftApCallback(callback));
+ mTetheredSoftApTracker.unregisterSoftApCallback(callback),
+ TAG + "#unregisterSoftApCallback");
}
/**
@@ -2744,19 +2775,18 @@ public class WifiServiceImpl extends BaseWifiService {
}
}
- // verify that tethering is not disabled
- if (mUserManager.hasUserRestrictionForUser(
- UserManager.DISALLOW_CONFIG_TETHERING, UserHandle.getUserHandleForUid(uid))) {
- return LocalOnlyHotspotCallback.ERROR_TETHERING_DISALLOWED;
- }
-
- mLastCallerInfoManager.put(WifiManager.API_START_LOCAL_ONLY_HOTSPOT, Process.myTid(),
- uid, Binder.getCallingPid(), packageName, true);
-
final WorkSource requestorWs = new WorkSource(uid, packageName);
// the app should be in the foreground
long ident = Binder.clearCallingIdentity();
try {
+ // verify that tethering is not disabled
+ if (mUserManager.hasUserRestrictionForUser(
+ UserManager.DISALLOW_CONFIG_TETHERING, UserHandle.getUserHandleForUid(uid))) {
+ return LocalOnlyHotspotCallback.ERROR_TETHERING_DISALLOWED;
+ }
+
+ mLastCallerInfoManager.put(WifiManager.API_START_LOCAL_ONLY_HOTSPOT, Process.myTid(),
+ uid, Binder.getCallingPid(), packageName, true);
// also need to verify that Locations services are enabled.
// bypass shell with root uid
if (uid != Process.ROOT_UID
@@ -2830,7 +2860,7 @@ public class WifiServiceImpl extends BaseWifiService {
Log.e(TAG, "registerSoftApCallback: Failed to add callback");
return;
}
- });
+ }, TAG + "#registerLocalOnlyHotspotSoftApCallback");
}
@Override
@@ -2852,7 +2882,8 @@ public class WifiServiceImpl extends BaseWifiService {
// post operation to handler thread
mWifiThreadRunner.post(() ->
- mLohsSoftApTracker.unregisterSoftApCallback(callback));
+ mLohsSoftApTracker.unregisterSoftApCallback(callback),
+ TAG + "#unregisterLocalOnlyHotspotSoftApCallback");
}
/**
@@ -2956,7 +2987,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#queryLastConfiguredTetheredApPassphraseSinceBoot");
}
/**
@@ -3076,7 +3107,8 @@ public class WifiServiceImpl extends BaseWifiService {
return false;
}
mLog.info("disconnect uid=%").c(callingUid).flush();
- mWifiThreadRunner.post(() -> mActiveModeWarden.getPrimaryClientModeManager().disconnect());
+ mWifiThreadRunner.post(() -> mActiveModeWarden.getPrimaryClientModeManager().disconnect(),
+ TAG + "#disconnect");
return true;
}
@@ -3098,7 +3130,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
mActiveModeWarden.getPrimaryClientModeManager().reconnect(new WorkSource(callingUid));
- });
+ }, TAG + "#reconnect");
return true;
}
@@ -3118,7 +3150,8 @@ public class WifiServiceImpl extends BaseWifiService {
return false;
}
mLog.info("reassociate uid=%").c(callingUid).flush();
- mWifiThreadRunner.post(() -> mActiveModeWarden.getPrimaryClientModeManager().reassociate());
+ mWifiThreadRunner.post(() -> mActiveModeWarden.getPrimaryClientModeManager().reassociate(),
+ TAG + "#reassociate");
return true;
}
@@ -3189,7 +3222,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, "onWifiActivityEnergyInfo: RemoteException -- ", e);
}
- });
+ }, TAG + "#getWifiActivityEnergyInfoAsync");
}
private WifiActivityEnergyInfo getWifiActivityEnergyInfo() {
@@ -3281,7 +3314,7 @@ public class WifiServiceImpl extends BaseWifiService {
int finalTargetConfigUid = targetConfigUid;
List<WifiConfiguration> configs = mWifiThreadRunner.call(
() -> mWifiConfigManager.getSavedNetworks(finalTargetConfigUid),
- Collections.emptyList());
+ Collections.emptyList(), TAG + "#getConfiguredNetworks");
if (isTargetSdkLessThanQOrPrivileged && !callerNetworksOnly) {
return new ParceledListSlice<>(
WifiConfigurationUtil.convertMultiTypeConfigsToLegacyConfigs(configs, false));
@@ -3345,7 +3378,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
List<WifiConfiguration> configs = mWifiThreadRunner.call(
() -> mWifiConfigManager.getConfiguredNetworksWithPasswords(),
- Collections.emptyList());
+ Collections.emptyList(), TAG + "#getPrivilegedConfiguredNetworks");
return new ParceledListSlice<>(
WifiConfigurationUtil.convertMultiTypeConfigsToLegacyConfigs(configs, false));
}
@@ -3381,7 +3414,8 @@ public class WifiServiceImpl extends BaseWifiService {
return null;
}
WifiConfiguration config = mWifiThreadRunner.call(
- () -> mWifiConfigManager.getConfiguredNetworkWithPassword(networkId), null);
+ () -> mWifiConfigManager.getConfiguredNetworkWithPassword(networkId), null,
+ TAG + "#getPrivilegedConnectedNetwork");
if (config == null) {
if (mVerboseLoggingEnabled) {
mLog.info("getPrivilegedConnectedNetwork failed to get config").flush();
@@ -3420,7 +3454,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
mNetworkSelectionConfig = nsConfig;
mWifiConnectivityManager.setNetworkSelectionConfig(nsConfig);
- });
+ }, TAG + "#setNetworkSelectionConfig");
mLastCallerInfoManager.put(
WifiManager.API_SET_NETWORK_SELECTION_CONFIG,
Process.myTid(),
@@ -3473,7 +3507,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#getNetworkSelectionConfig");
}
/**
@@ -3556,7 +3590,7 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("scanSchedule=% scanType=% uid=%").c(Arrays.toString(scanScheduleSeconds))
.c(Arrays.toString(scanType)).c(uid).flush();
mWifiThreadRunner.post(() -> mWifiConnectivityManager.setExternalScreenOnScanSchedule(
- scanScheduleSeconds, scanType));
+ scanScheduleSeconds, scanType), TAG + "#setScreenOnScanSchedule");
mLastCallerInfoManager.put(WifiManager.API_SET_SCAN_SCHEDULE, Process.myTid(),
uid, Binder.getCallingPid(), "<unknown>",
scanScheduleSeconds != null);
@@ -3579,7 +3613,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
mLog.info("delayMs=% uid=%").c(delayMs).c(uid).flush();
mWifiThreadRunner.post(() ->
- mWifiConnectivityManager.setOneShotScreenOnConnectivityScanDelayMillis(delayMs));
+ mWifiConnectivityManager.setOneShotScreenOnConnectivityScanDelayMillis(delayMs),
+ TAG + "#setOneShotScreenOnConnectivityScanDelayMillis");
mLastCallerInfoManager.put(WifiManager.API_SET_ONE_SHOT_SCREEN_ON_CONNECTIVITY_SCAN_DELAY,
Process.myTid(), uid, Binder.getCallingPid(), "<unknown>",
delayMs > 0);
@@ -3609,7 +3644,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
return mWifiThreadRunner.call(
() -> mPasspointManager.getAllMatchingPasspointProfilesForScanResults(scanResults),
- Collections.emptyMap());
+ Collections.emptyMap(),
+ TAG + "#getAllMatchingPasspointProfilesForScanResults");
}
/**
@@ -3632,7 +3668,7 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("setSsidsAllowlist uid=%").c(uid).flush();
}
mWifiThreadRunner.post(() ->
- mWifiBlocklistMonitor.setSsidsAllowlist(ssids));
+ mWifiBlocklistMonitor.setSsidsAllowlist(ssids), TAG + "#setSsidsAllowlist");
}
/**
@@ -3655,7 +3691,8 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("getSsidsAllowlist uid=%").c(uid).flush();
}
return mWifiThreadRunner.call(
- () -> mWifiBlocklistMonitor.getSsidsAllowlist(), Collections.EMPTY_LIST);
+ () -> mWifiBlocklistMonitor.getSsidsAllowlist(), Collections.EMPTY_LIST,
+ TAG + "#getSsidsAllowlist");
}
/**
@@ -3679,7 +3716,8 @@ public class WifiServiceImpl extends BaseWifiService {
return Collections.emptyMap();
}
return mWifiThreadRunner.call(
- () -> mPasspointManager.getMatchingOsuProviders(scanResults), Collections.emptyMap());
+ () -> mPasspointManager.getMatchingOsuProviders(scanResults), Collections.emptyMap(),
+ TAG + "#getMatchingOsuProviders");
}
/**
@@ -3704,7 +3742,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
return mWifiThreadRunner.call(
() -> mPasspointManager.getMatchingPasspointConfigsForOsuProviders(osuProviders),
- Collections.emptyMap());
+ Collections.emptyMap(), TAG + "#getMatchingPasspointConfigsForOsuProviders");
}
/**
@@ -3731,7 +3769,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
return mWifiThreadRunner.call(
() -> mPasspointManager.getWifiConfigsForPasspointProfiles(fqdnList),
- Collections.emptyList());
+ Collections.emptyList(), TAG + "#getWifiConfigsForPasspointProfiles");
}
/**
@@ -3761,7 +3799,8 @@ public class WifiServiceImpl extends BaseWifiService {
return mWifiThreadRunner.call(
() -> mWifiNetworkSuggestionsManager
.getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(scanResults),
- Collections.emptyList());
+ Collections.emptyList(),
+ TAG + "#getWifiConfigForMatchedNetworkSuggestionsSharedWithUser");
}
/**
@@ -3857,27 +3896,38 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("addOrUpdateNetwork not allowed for uid=%").c(callingUid).flush();
return -1;
}
- if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_WIFI,
- UserHandle.of(mWifiPermissionsUtil.getCurrentUser()))
- && isCamera && !isAdmin) {
- mLog.info("addOrUpdateNetwork not allowed for the camera apps and therefore the user "
- + "when DISALLOW_CONFIG_WIFI user restriction is set").flush();
- return -1;
- }
- if (SdkLevel.isAtLeastT() && mUserManager.hasUserRestrictionForUser(
- UserManager.DISALLOW_ADD_WIFI_CONFIG, UserHandle.getUserHandleForUid(callingUid))) {
- if (mWifiPermissionsUtil.isTargetSdkLessThan(
- packageName, Build.VERSION_CODES.Q, callingUid)
- && !(isPrivileged || isAdmin || isSystem)) {
- mLog.info("addOrUpdateNetwork not allowed for normal apps targeting SDK less than "
- + "Q when the DISALLOW_ADD_WIFI_CONFIG user restriction is set").flush();
+ long ident = Binder.clearCallingIdentity();
+ try {
+ if (mUserManager.hasUserRestrictionForUser(UserManager.DISALLOW_CONFIG_WIFI,
+ UserHandle.of(mWifiPermissionsUtil.getCurrentUser()))
+ && isCamera && !isAdmin) {
+ mLog.info(
+ "addOrUpdateNetwork not allowed for the camera apps and therefore the "
+ + "user when DISALLOW_CONFIG_WIFI user restriction is set").flush();
return -1;
}
- if (isCamera && !isAdmin) {
- mLog.info("addOrUpdateNetwork not allowed for camera apps and therefore the user "
- + "when the DISALLOW_ADD_WIFI_CONFIG user restriction is set").flush();
- return -1;
+ if (SdkLevel.isAtLeastT() && mUserManager.hasUserRestrictionForUser(
+ UserManager.DISALLOW_ADD_WIFI_CONFIG,
+ UserHandle.getUserHandleForUid(callingUid))) {
+ if (mWifiPermissionsUtil.isTargetSdkLessThan(
+ packageName, Build.VERSION_CODES.Q, callingUid)
+ && !(isPrivileged || isAdmin || isSystem)) {
+ mLog.info(
+ "addOrUpdateNetwork not allowed for normal apps targeting "
+ + "SDK less than Q when the DISALLOW_ADD_WIFI_CONFIG "
+ + "user restriction is set").flush();
+ return -1;
+ }
+ if (isCamera && !isAdmin) {
+ mLog.info(
+ "addOrUpdateNetwork not allowed for camera apps and therefore the "
+ + "user when the DISALLOW_ADD_WIFI_CONFIG "
+ + "user restriction is set").flush();
+ return -1;
+ }
}
+ } finally {
+ Binder.restoreCallingIdentity(ident);
}
mLog.info("addOrUpdateNetwork uid=%").c(callingUid).flush();
@@ -3936,7 +3986,8 @@ public class WifiServiceImpl extends BaseWifiService {
NetworkUpdateResult result = mWifiThreadRunner.call(
() -> mWifiConfigManager.addOrUpdateNetwork(config, attributedCreatorUid,
attributedCreatorPackage, overrideCreator),
- new NetworkUpdateResult(WifiConfiguration.INVALID_NETWORK_ID));
+ new NetworkUpdateResult(WifiConfiguration.INVALID_NETWORK_ID),
+ TAG + "#addOrUpdateNetworkInternal");
return new AddNetworkResult(result.getStatusCode(), result.getNetworkId());
}
@@ -3974,7 +4025,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
mLog.info("removeNetwork uid=%").c(callingUid).flush();
return mWifiThreadRunner.call(
- () -> mWifiConfigManager.removeNetwork(netId, callingUid, packageName), false);
+ () -> mWifiConfigManager.removeNetwork(netId, callingUid, packageName), false,
+ TAG + "#removeNetwork");
}
@Override
@@ -3989,7 +4041,8 @@ public class WifiServiceImpl extends BaseWifiService {
+ "of an organization owned device");
}
return mWifiThreadRunner.call(
- () -> mWifiConfigManager.removeNonCallerConfiguredNetwork(callingUid), false);
+ () -> mWifiConfigManager.removeNonCallerConfiguredNetwork(callingUid), false,
+ TAG + "#removeNonCallerConfiguredNetworks");
}
/**
@@ -4020,7 +4073,7 @@ public class WifiServiceImpl extends BaseWifiService {
new NetworkUpdateResult(netId),
new ActionListenerWrapper(connectListener),
callingUid, packageName, null)
- )
+ ), TAG + "#triggerConnectAndReturnStatus"
);
// now wait for response.
try {
@@ -4078,7 +4131,8 @@ public class WifiServiceImpl extends BaseWifiService {
} else {
return mWifiThreadRunner.call(
() -> mWifiConfigManager.enableNetwork(netId, false, callingUid, packageName),
- false);
+ false,
+ TAG + "#enableNetwork");
}
}
@@ -4104,7 +4158,8 @@ public class WifiServiceImpl extends BaseWifiService {
callingUid, Binder.getCallingPid(), packageName, true);
mLog.info("disableNetwork uid=%").c(callingUid).flush();
return mWifiThreadRunner.call(
- () -> mWifiConfigManager.disableNetwork(netId, callingUid, packageName), false);
+ () -> mWifiConfigManager.disableNetwork(netId, callingUid, packageName), false,
+ TAG + "#disableNetwork");
}
/**
@@ -4151,7 +4206,7 @@ public class WifiServiceImpl extends BaseWifiService {
// primary STA disconnecting (such as promoting the secondary to primary), potentially
// resulting in messy and unexpected state transitions.
mActiveModeWarden.getPrimaryClientModeManager().disconnect();
- });
+ }, TAG + "#startRestrictingAutoJoinToSubscriptionId");
}
/**
@@ -4170,7 +4225,8 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("stopRestrictingAutoJoinToSubscriptionId uid=%")
.c(Binder.getCallingUid()).flush();
mWifiThreadRunner.post(() ->
- mWifiConfigManager.stopRestrictingAutoJoinToSubscriptionId());
+ mWifiConfigManager.stopRestrictingAutoJoinToSubscriptionId(),
+ TAG + "#stopRestrictingAutoJoinToSubscriptionId");
}
/**
@@ -4205,7 +4261,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
boolean finalIsDeviceAdmin = isDeviceAdmin;
mWifiThreadRunner.post(() -> mWifiConnectivityManager.setAutoJoinEnabledExternal(choice,
- finalIsDeviceAdmin));
+ finalIsDeviceAdmin), TAG + "#allowAutojoinGlobal");
mLastCallerInfoManager.put(WifiManager.API_AUTOJOIN_GLOBAL, Process.myTid(),
callingUid, Binder.getCallingPid(), "<unknown>", choice);
}
@@ -4231,7 +4287,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#queryAutojoinGlobal");
}
/**
@@ -4284,7 +4340,7 @@ public class WifiServiceImpl extends BaseWifiService {
: UserActionEvent.EVENT_CONFIGURE_AUTO_CONNECT_OFF, netId);
}
}
- });
+ }, TAG + "#allowAutojoin");
}
/**
@@ -4302,7 +4358,54 @@ public class WifiServiceImpl extends BaseWifiService {
int callingUid = Binder.getCallingUid();
mLog.info("allowAutojoinPasspoint=% uid=%").c(enableAutojoin).c(callingUid).flush();
mWifiThreadRunner.post(
- () -> mPasspointManager.enableAutojoin(null, fqdn, enableAutojoin));
+ () -> mPasspointManager.enableAutojoin(null, fqdn, enableAutojoin),
+ TAG + "#allowAutojoinPasspoint");
+ }
+
+ /**
+ * See {@link WifiManager#getBssidBlocklist(List, Executor, Consumer)}
+ * @param ssids the list of ssids to get BSSID blocklist for.
+ * @param listener returns the results
+ */
+ @Override
+ public void getBssidBlocklist(@NonNull ParceledListSlice<WifiSsid> ssids,
+ @NonNull IMacAddressListListener listener) {
+ if (ssids == null) {
+ throw new IllegalArgumentException("Null ssids");
+ }
+ if (listener == null) {
+ throw new IllegalArgumentException("Null listener");
+ }
+ int uid = Binder.getCallingUid();
+ if (!mWifiPermissionsUtil.checkNetworkSettingsPermission(uid)
+ && !mWifiPermissionsUtil.checkNetworkSetupWizardPermission(uid)) {
+ throw new SecurityException("No permission to call getBssidBlocklist");
+ }
+ Set<String> ssidSet;
+ if (!ssids.getList().isEmpty()) {
+ ssidSet = new ArraySet<>();
+ for (WifiSsid ssid : ssids.getList()) {
+ ssidSet.add(ssid.toString());
+ }
+ } else {
+ ssidSet = null;
+ }
+ mWifiThreadRunner.post(() -> {
+ try {
+ List<String> bssids = mWifiBlocklistMonitor.getBssidBlocklistForSsids(ssidSet);
+ List<MacAddress> macAddresses = new ArrayList<>();
+ for (String bssid : bssids) {
+ try {
+ macAddresses.add(MacAddress.fromString(bssid));
+ } catch (Exception e) {
+ Log.e(TAG, "getBssidBlocklist failed to convert MAC address: " + bssid);
+ }
+ }
+ listener.onResult(new ParceledListSlice(macAddresses));
+ } catch (RemoteException e) {
+ Log.e(TAG, e.getMessage(), e);
+ }
+ }, TAG + "#getBssidBlocklist");
}
/**
@@ -4322,7 +4425,8 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("setMacRandomizationSettingPasspointEnabled=% uid=%")
.c(enable).c(callingUid).flush();
mWifiThreadRunner.post(
- () -> mPasspointManager.enableMacRandomization(fqdn, enable));
+ () -> mPasspointManager.enableMacRandomization(fqdn, enable),
+ TAG + "#setMacRandomizationSettingPasspointEnabled");
}
/**
@@ -4341,7 +4445,8 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("setPasspointMeteredOverride=% uid=%")
.c(meteredOverride).c(callingUid).flush();
mWifiThreadRunner.post(
- () -> mPasspointManager.setMeteredOverride(fqdn, meteredOverride));
+ () -> mPasspointManager.setMeteredOverride(fqdn, meteredOverride),
+ TAG + "#setPasspointMeteredOverride");
}
/**
@@ -4410,7 +4515,7 @@ public class WifiServiceImpl extends BaseWifiService {
getClientModeManagerIfSecondaryCmmRequestedByCallerPresent(
uid, callingPackage)
.getConnectionInfo(),
- new WifiInfo());
+ new WifiInfo(), TAG + "#getConnectionInfo");
} else {
// If no caller
wifiInfo = mActiveModeWarden.getConnectionInfo();
@@ -4475,7 +4580,8 @@ public class WifiServiceImpl extends BaseWifiService {
* @return the list of results
*/
@Override
- public List<ScanResult> getScanResults(String callingPackage, String callingFeatureId) {
+ @Nullable public ParceledListSlice<ScanResult> getScanResults(String callingPackage,
+ String callingFeatureId) {
enforceAccessPermission();
int uid = Binder.getCallingUid();
long ident = Binder.clearCallingIdentity();
@@ -4486,15 +4592,16 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiPermissionsUtil.enforceCanAccessScanResults(callingPackage, callingFeatureId,
uid, null);
List<ScanResult> scanResults = mWifiThreadRunner.call(
- mScanRequestProxy::getScanResults, Collections.emptyList());
+ mScanRequestProxy::getScanResults, Collections.emptyList(),
+ TAG + "#getScanResults");
if (scanResults.size() > 200) {
Log.i(TAG, "too many scan results, may break binder transaction");
}
- return scanResults;
+ return new ParceledListSlice<>(scanResults);
} catch (SecurityException e) {
Log.w(TAG, "Permission violation - getScanResults not allowed for uid="
+ uid + ", packageName=" + callingPackage + ", reason=" + e);
- return new ArrayList<>();
+ return null;
} finally {
Binder.restoreCallingIdentity(ident);
}
@@ -4522,7 +4629,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#getChannelData");
}
private List<Bundle> getChannelDataInternal() {
@@ -4576,7 +4683,7 @@ public class WifiServiceImpl extends BaseWifiService {
networkSuggestions, scanResults);
}
},
- Collections.emptyMap());
+ Collections.emptyMap(), TAG + "#getMatchingScanResults");
} catch (SecurityException e) {
Log.w(TAG, "Permission violation - getMatchingScanResults not allowed for uid="
+ uid + ", packageName=" + callingPackage + ", reason + e");
@@ -4607,12 +4714,18 @@ public class WifiServiceImpl extends BaseWifiService {
.c(callingUid).flush();
return false;
}
- if (SdkLevel.isAtLeastT() && mUserManager.hasUserRestrictionForUser(
- UserManager.DISALLOW_ADD_WIFI_CONFIG, UserHandle.getUserHandleForUid(callingUid))
- && !mWifiPermissionsUtil.isAdmin(callingUid, packageName)) {
- mLog.info("addOrUpdatePasspointConfiguration only allowed for admin"
- + "when the DISALLOW_ADD_WIFI_CONFIG user restriction is set").flush();
- return false;
+ long ident = Binder.clearCallingIdentity();
+ try {
+ if (SdkLevel.isAtLeastT() && mUserManager.hasUserRestrictionForUser(
+ UserManager.DISALLOW_ADD_WIFI_CONFIG,
+ UserHandle.getUserHandleForUid(callingUid))
+ && !mWifiPermissionsUtil.isAdmin(callingUid, packageName)) {
+ mLog.info("addOrUpdatePasspointConfiguration only allowed for admin"
+ + "when the DISALLOW_ADD_WIFI_CONFIG user restriction is set").flush();
+ return false;
+ }
+ } finally {
+ Binder.restoreCallingIdentity(ident);
}
mLog.info("addorUpdatePasspointConfiguration uid=%").c(callingUid).flush();
return mWifiThreadRunner.call(
@@ -4630,7 +4743,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
}
return success;
- }, false);
+ }, false, TAG + "#addOrUpdatePasspointConfiguration");
}
/**
@@ -4664,7 +4777,7 @@ public class WifiServiceImpl extends BaseWifiService {
final boolean privilegedFinal = privileged;
return mWifiThreadRunner.call(
() -> mPasspointManager.removeProvider(uid, privilegedFinal, uniqueId, fqdn),
- false);
+ false, TAG + "#removePasspointConfigurationInternal");
}
/**
@@ -4689,7 +4802,7 @@ public class WifiServiceImpl extends BaseWifiService {
final boolean privilegedFinal = privileged;
return mWifiThreadRunner.call(
() -> mPasspointManager.getProviderConfigs(uid, privilegedFinal),
- Collections.emptyList());
+ Collections.emptyList(), TAG + "#getPasspointConfigurations");
}
/**
@@ -4703,7 +4816,7 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("queryPasspointIcon uid=%").c(Binder.getCallingUid()).flush();
mWifiThreadRunner.post(() -> {
mActiveModeWarden.getPrimaryClientModeManager().syncQueryPasspointIcon(bssid, fileName);
- });
+ }, TAG + "#queryPasspointIcon");
}
/**
@@ -4769,7 +4882,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, "registerDriverCountryCodeChangedListener: remote exception -- " + e);
}
- });
+ }, TAG + "#registerDriverCountryCodeChangedListener");
}
/**
@@ -4800,7 +4913,8 @@ public class WifiServiceImpl extends BaseWifiService {
// post operation to handler thread
mWifiThreadRunner.post(() ->
- mCountryCodeTracker.unregisterDriverCountryCodeChangedListener(listener));
+ mCountryCodeTracker.unregisterDriverCountryCodeChangedListener(listener),
+ TAG + "#unregisterDriverCountryCodeChangedListener");
}
/**
@@ -4847,7 +4961,8 @@ public class WifiServiceImpl extends BaseWifiService {
.c(Binder.getCallingUid()).c(countryCode).flush();
}
// Post operation to handler thread
- mWifiThreadRunner.post(() -> mCountryCode.setOverrideCountryCode(countryCode));
+ mWifiThreadRunner.post(() -> mCountryCode.setOverrideCountryCode(countryCode),
+ TAG + "#setOverrideCountryCode");
}
/**
@@ -4866,7 +4981,8 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("clearCountryCode uid=%").c(Binder.getCallingUid()).flush();
}
// Post operation to handler thread
- mWifiThreadRunner.post(() -> mCountryCode.clearOverrideCountryCode());
+ mWifiThreadRunner.post(() -> mCountryCode.clearOverrideCountryCode(),
+ TAG + "#clearOverrideCountryCode");
}
/**
@@ -4892,7 +5008,8 @@ public class WifiServiceImpl extends BaseWifiService {
.c(Binder.getCallingUid()).c(countryCode).flush();
}
// Post operation to handler thread
- mWifiThreadRunner.post(() -> mCountryCode.setDefaultCountryCode(countryCode));
+ mWifiThreadRunner.post(() -> mCountryCode.setDefaultCountryCode(countryCode),
+ TAG + "#setDefaultCountryCode");
}
@Override
@@ -4968,7 +5085,7 @@ public class WifiServiceImpl extends BaseWifiService {
public boolean isWifiStandardSupported(@WifiStandard int standard) {
return mWifiThreadRunner.call(
() -> mActiveModeWarden.getPrimaryClientModeManager().isWifiStandardSupported(
- standard), false);
+ standard), false, TAG + "#isWifiStandardSupported");
}
/**
@@ -4988,7 +5105,8 @@ public class WifiServiceImpl extends BaseWifiService {
DhcpResultsParcelable dhcpResults = mWifiThreadRunner.call(
() -> getClientModeManagerIfSecondaryCmmRequestedByCallerPresent(
callingUid, packageName)
- .syncGetDhcpResultsParcelable(), new DhcpResultsParcelable());
+ .syncGetDhcpResultsParcelable(), new DhcpResultsParcelable(),
+ TAG + "#getDhcpInfo");
DhcpInfo info = new DhcpInfo();
@@ -5130,7 +5248,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#enableTdlsWithRemoteIpAddress");
}
@Override
@@ -5147,7 +5265,7 @@ public class WifiServiceImpl extends BaseWifiService {
enable);
mWifiThreadRunner.post(() ->
mActiveModeWarden.getPrimaryClientModeManager().enableTdls(
- remoteMacAddress, enable));
+ remoteMacAddress, enable), TAG + "#enableTdlsWithMacAddress");
}
/**
@@ -5178,7 +5296,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#enableTdlsWithRemoteMacAddress");
}
/**
@@ -5197,7 +5315,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#isTdlsOperationCurrentlyAvailable");
}
/**
@@ -5220,7 +5338,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#getMaxSupportedConcurrentTdlsSessions");
}
/**
@@ -5239,7 +5357,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#getNumberOfEnabledTdlsSessions");
}
/**
@@ -5257,7 +5375,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
mLog.info("disableEphemeralNetwork uid=%").c(callingUid).flush();
mWifiThreadRunner.post(() -> mWifiConfigManager.userTemporarilyDisabledNetwork(network,
- callingUid));
+ callingUid), TAG + "#disableEphemeralNetwork");
}
private void removeAppStateInternal(int uid, @NonNull String pkgName) {
@@ -5478,13 +5596,17 @@ public class WifiServiceImpl extends BaseWifiService {
pw.println();
mLastCallerInfoManager.dump(pw);
pw.println();
- mWifiInjector.getLinkProbeManager().dump(fd, pw, args);
- pw.println();
mWifiNative.dump(pw);
pw.println();
mWifiInjector.getWifiRoamingModeManager().dump(fd, pw, args);
+ if (SdkLevel.isAtLeastV() && mWifiInjector.getWifiVoipDetector() != null) {
+ pw.println();
+ mWifiInjector.getWifiVoipDetector().dump(fd, pw, args);
+ }
+ pw.println();
+ mWifiResourceCache.dump(pw);
}
- });
+ }, TAG + "#dump");
}
@Override
@@ -5510,7 +5632,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
return mWifiThreadRunner.call(() ->
- mWifiLockManager.acquireWifiLock(lockMode, tag, binder, updatedWs), false);
+ mWifiLockManager.acquireWifiLock(lockMode, tag, binder, updatedWs), false,
+ TAG + "#acquireWifiLock");
}
@Override
@@ -5529,7 +5652,8 @@ public class WifiServiceImpl extends BaseWifiService {
? new WorkSource(Binder.getCallingUid(), packageName) : ws;
mWifiThreadRunner.run(() ->
- mWifiLockManager.updateWifiLockWorkSource(binder, updatedWs));
+ mWifiLockManager.updateWifiLockWorkSource(binder, updatedWs),
+ TAG + "#updateWifiLockWorkSource");
}
@Override
@@ -5540,7 +5664,8 @@ public class WifiServiceImpl extends BaseWifiService {
mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
return mWifiThreadRunner.call(() ->
- mWifiLockManager.releaseWifiLock(binder), false);
+ mWifiLockManager.releaseWifiLock(binder), false,
+ TAG + "#releaseWifiLock");
}
@Override
@@ -5634,7 +5759,8 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiGlobals.setVerboseLoggingLevel(verboseLoggingLevel);
if (WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY == mVerboseLoggingLevel) {
mWifiThreadRunner.postDelayed(mAutoDisableShowKeyVerboseLoggingModeRunnable,
- AUTO_DISABLE_SHOW_KEY_COUNTDOWN_MILLIS);
+ AUTO_DISABLE_SHOW_KEY_COUNTDOWN_MILLIS,
+ TAG + "#AutoDisableShowKeyVerboseLoggingMode");
}
updateVerboseLoggingEnabled();
final boolean halVerboseEnabled =
@@ -5656,6 +5782,9 @@ public class WifiServiceImpl extends BaseWifiService {
mApplicationQosPolicyRequestHandler.enableVerboseLogging(mVerboseLoggingEnabled);
mWifiSettingsBackupRestore.enableVerboseLogging(mVerboseLoggingEnabled);
mBackupRestoreController.enableVerboseLogging(mVerboseLoggingEnabled);
+ if (SdkLevel.isAtLeastV() && mWifiInjector.getWifiVoipDetector() != null) {
+ mWifiInjector.getWifiVoipDetector().enableVerboseLogging(mVerboseLoggingEnabled);
+ }
}
@Override
@@ -5685,22 +5814,26 @@ public class WifiServiceImpl extends BaseWifiService {
int callingUid = Binder.getCallingUid();
mWifiPermissionsUtil.checkPackage(callingUid, packageName);
mLog.info("factoryReset uid=%").c(callingUid).flush();
- if (mUserManager.hasUserRestrictionForUser(
- UserManager.DISALLOW_NETWORK_RESET,
- UserHandle.getUserHandleForUid(callingUid))) {
- return;
- }
- if (!mUserManager.hasUserRestrictionForUser(
- UserManager.DISALLOW_CONFIG_TETHERING,
- UserHandle.getUserHandleForUid(callingUid))) {
- // Turn mobile hotspot off
- stopSoftApInternal(WifiManager.IFACE_IP_MODE_UNSPECIFIED);
- }
-
- if (mUserManager.hasUserRestrictionForUser(
- UserManager.DISALLOW_CONFIG_WIFI,
- UserHandle.getUserHandleForUid(callingUid))) {
- return;
+ long ident = Binder.clearCallingIdentity();
+ try {
+ if (mUserManager.hasUserRestrictionForUser(
+ UserManager.DISALLOW_NETWORK_RESET,
+ UserHandle.getUserHandleForUid(callingUid))) {
+ return;
+ }
+ if (!mUserManager.hasUserRestrictionForUser(
+ UserManager.DISALLOW_CONFIG_TETHERING,
+ UserHandle.getUserHandleForUid(callingUid))) {
+ // Turn mobile hotspot off
+ stopSoftApInternal(WifiManager.IFACE_IP_MODE_UNSPECIFIED);
+ }
+ if (mUserManager.hasUserRestrictionForUser(
+ UserManager.DISALLOW_CONFIG_WIFI,
+ UserHandle.getUserHandleForUid(callingUid))) {
+ return;
+ }
+ } finally {
+ Binder.restoreCallingIdentity(ident);
}
// Delete all Wifi SSIDs
mWifiThreadRunner.run(() -> {
@@ -5714,11 +5847,11 @@ public class WifiServiceImpl extends BaseWifiService {
}
mWifiConfigManager.removeNetwork(network.networkId, callingUid, packageName);
}
- });
+ }, TAG + "#factoryReset1");
// Delete all Passpoint configurations
List<PasspointConfiguration> configs = mWifiThreadRunner.call(
() -> mPasspointManager.getProviderConfigs(WIFI_UID /* ignored */, true),
- Collections.emptyList());
+ Collections.emptyList(), TAG + "#factoryReset2");
for (PasspointConfiguration config : configs) {
removePasspointConfigurationInternal(null, config.getUniqueId());
}
@@ -5736,7 +5869,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiCarrierInfoManager.clear();
notifyFactoryReset();
mContext.resetResourceCache();
- });
+ }, TAG + "#factoryReset3");
}
/**
@@ -5812,7 +5945,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#retrieveWifiBackupData");
}
/**
@@ -5831,7 +5964,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
mLog.info("restoreWifiBackupData uid=%").c(Binder.getCallingUid()).flush();
mBackupRestoreController.parserBackupDataAndDispatch(data);
- });
+ }, TAG + "#restoreWifiBackupData");
}
/**
@@ -5845,39 +5978,37 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("retrieveBackupData uid=%").c(Binder.getCallingUid()).flush();
Log.d(TAG, "Retrieving backup data");
List<WifiConfiguration> wifiConfigurations = mWifiThreadRunner.call(
- () -> mWifiConfigManager.getConfiguredNetworksWithPasswords(), null);
+ () -> mWifiConfigManager.getConfiguredNetworksWithPasswords(), null,
+ TAG + "#retrieveBackupData");
byte[] backupData =
mWifiBackupRestore.retrieveBackupDataFromConfigurations(wifiConfigurations);
Log.d(TAG, "Retrieved backup data");
return backupData;
}
- private final class NetworkUpdater implements Runnable {
- private final int mCallingUid;
- private final List<WifiConfiguration> mConfigurations;
- private final int mStartIdx;
- private final int mBatchNum;
-
- NetworkUpdater(int callingUid, List<WifiConfiguration> configurations, int startIdx,
- int batchNum) {
- mCallingUid = callingUid;
- mConfigurations = configurations;
- mStartIdx = startIdx;
- mBatchNum = batchNum;
+ /**
+ * Helper method to restore networks retrieved from backup data.
+ *
+ * @param configurations list of WifiConfiguration objects parsed from the backup data.
+ */
+ @VisibleForTesting
+ void restoreNetworks(List<WifiConfiguration> configurations) {
+ if (configurations == null) {
+ Log.w(TAG, "No wifi configuration to restore.");
+ return;
}
-
- @Override
- public void run() {
- final int nextStartIdx = Math.min(mStartIdx + mBatchNum, mConfigurations.size());
- for (int i = mStartIdx; i < nextStartIdx; i++) {
- WifiConfiguration configuration = mConfigurations.get(i);
- int networkId;
- if (CompatChanges.isChangeEnabled(NOT_OVERRIDE_EXISTING_NETWORKS_ON_RESTORE,
- mCallingUid)) {
- networkId = mWifiConfigManager.addNetwork(configuration, mCallingUid)
+ int callingUid = Binder.getCallingUid();
+ if (configurations.isEmpty()) return;
+ mWifiThreadRunner.post(() -> {
+ boolean notOverrideExisting = CompatChanges
+ .isChangeEnabled(NOT_OVERRIDE_EXISTING_NETWORKS_ON_RESTORE, callingUid);
+ int networkId;
+ for (WifiConfiguration configuration : configurations) {
+ if (notOverrideExisting) {
+ networkId = mWifiConfigManager.addNetwork(configuration, callingUid)
.getNetworkId();
} else {
- networkId = mWifiConfigManager.addOrUpdateNetwork(configuration, mCallingUid)
+ networkId = mWifiConfigManager.addOrUpdateNetwork(configuration, callingUid)
.getNetworkId();
}
if (networkId == WifiConfiguration.INVALID_NETWORK_ID) {
@@ -5886,45 +6017,12 @@ public class WifiServiceImpl extends BaseWifiService {
+ " database");
} else {
// Enable all networks restored.
- mWifiConfigManager.enableNetwork(networkId, false, mCallingUid, null);
+ mWifiConfigManager.enableNetwork(networkId, false, callingUid, null);
// Restore auto-join param.
mWifiConfigManager.allowAutojoin(networkId, configuration.allowAutojoin);
}
}
- if (nextStartIdx < mConfigurations.size()) {
- mWifiThreadRunner.post(new NetworkUpdater(mCallingUid, mConfigurations,
- nextStartIdx, mBatchNum));
- }
- Log.d(TAG, "Restored backup data index " + nextStartIdx + " of total "
- + mConfigurations.size() + " configs ");
- }
- }
-
- /**
- * Helper method to restore networks retrieved from backup data.
- *
- * @param configurations list of WifiConfiguration objects parsed from the backup data.
- */
- @VisibleForTesting
- void restoreNetworks(List<WifiConfiguration> configurations) {
- if (configurations == null) {
- Log.w(TAG, "No wifi configuration to restore.");
- return;
- }
- int callingUid = Binder.getCallingUid();
- if (configurations.isEmpty()) return;
- final int batchNum =
- mDeviceConfigFacade.getFeatureFlags().delaySaveToStore()
- ? 0
- : mContext.getResources()
- .getInteger(
- R.integer.config_wifiConfigurationRestoreNetworksBatchNum);
- mWifiThreadRunner.post(
- new NetworkUpdater(
- callingUid,
- configurations,
- 0,
- batchNum > 0 ? batchNum : configurations.size()));
+ }, TAG + "#restoreNetworks");
}
/**
@@ -5950,7 +6048,7 @@ public class WifiServiceImpl extends BaseWifiService {
enforceNetworkSettingsPermission();
mLog.info("retrieveSoftApBackupData uid=%").c(Binder.getCallingUid()).flush();
SoftApConfiguration config = mWifiThreadRunner.call(mWifiApConfigStore::getApConfiguration,
- new SoftApConfiguration.Builder().build());
+ new SoftApConfiguration.Builder().build(), TAG + "#retrieveSoftApBackupData");
byte[] backupData =
mSoftApBackupRestore.retrieveBackupDataFromSoftApConfiguration(config);
Log.d(TAG, "Retrieved soft ap backup data");
@@ -6042,7 +6140,8 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("registerTrafficStateCallback uid=%").c(Binder.getCallingUid()).flush();
}
// Post operation to handler thread
- mWifiThreadRunner.post(() -> mWifiTrafficPoller.addCallback(callback));
+ mWifiThreadRunner.post(() -> mWifiTrafficPoller.addCallback(callback),
+ TAG + "#registerTrafficStateCallback");
}
/**
@@ -6060,7 +6159,8 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("unregisterTrafficStateCallback uid=%").c(Binder.getCallingUid()).flush();
}
// Post operation to handler thread
- mWifiThreadRunner.post(() -> mWifiTrafficPoller.removeCallback(callback));
+ mWifiThreadRunner.post(() -> mWifiTrafficPoller.removeCallback(callback),
+ TAG + "#unregisterTrafficStateCallback");
}
private long getSupportedFeaturesInternal() {
@@ -6091,7 +6191,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
// Post operation to handler thread
mWifiThreadRunner.post(() ->
- mWifiInjector.getWifiNetworkFactory().addCallback(callback));
+ mWifiInjector.getWifiNetworkFactory().addCallback(callback),
+ TAG + "#registerNetworkRequestMatchCallback");
}
/**
@@ -6111,7 +6212,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
// Post operation to handler thread
mWifiThreadRunner.post(() ->
- mWifiInjector.getWifiNetworkFactory().removeCallback(callback));
+ mWifiInjector.getWifiNetworkFactory().removeCallback(callback),
+ TAG + "#unregisterNetworkRequestMatchCallback");
}
/**
@@ -6133,21 +6235,26 @@ public class WifiServiceImpl extends BaseWifiService {
int callingUid = Binder.getCallingUid();
int callingPid = Binder.getCallingPid();
- if (SdkLevel.isAtLeastT()) {
- boolean isUserRestrictionSet = mUserManager.hasUserRestrictionForUser(
- UserManager.DISALLOW_ADD_WIFI_CONFIG,
- UserHandle.getUserHandleForUid(callingUid));
- boolean isCarrierApp = mWifiInjector.makeTelephonyManager()
- .checkCarrierPrivilegesForPackageAnyPhone(callingPackageName)
- == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
- boolean hasPermission = !isUserRestrictionSet
- || isCarrierApp
- || isPrivileged(callingPid, callingUid)
- || mWifiPermissionsUtil.isSystem(callingPackageName, callingUid)
- || mWifiPermissionsUtil.isAdmin(callingUid, callingPackageName);
- if (!hasPermission) {
- return WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_RESTRICTED_BY_ADMIN;
+ long ident = Binder.clearCallingIdentity();
+ try {
+ if (SdkLevel.isAtLeastT()) {
+ boolean isUserRestrictionSet = mUserManager.hasUserRestrictionForUser(
+ UserManager.DISALLOW_ADD_WIFI_CONFIG,
+ UserHandle.getUserHandleForUid(callingUid));
+ boolean isCarrierApp = mWifiInjector.makeTelephonyManager()
+ .checkCarrierPrivilegesForPackageAnyPhone(callingPackageName)
+ == TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS;
+ boolean hasPermission = !isUserRestrictionSet
+ || isCarrierApp
+ || isPrivileged(callingPid, callingUid)
+ || mWifiPermissionsUtil.isSystem(callingPackageName, callingUid)
+ || mWifiPermissionsUtil.isAdmin(callingUid, callingPackageName);
+ if (!hasPermission) {
+ return WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_RESTRICTED_BY_ADMIN;
+ }
}
+ } finally {
+ Binder.restoreCallingIdentity(ident);
}
if (mVerboseLoggingEnabled) {
@@ -6156,7 +6263,8 @@ public class WifiServiceImpl extends BaseWifiService {
int success = mWifiThreadRunner.call(() -> mWifiNetworkSuggestionsManager.add(
networkSuggestions, callingUid, callingPackageName, callingFeatureId),
- WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL);
+ WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL,
+ TAG + "#addNetworkSuggestions");
if (success != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
Log.e(TAG, "Failed to add network suggestions");
}
@@ -6189,7 +6297,8 @@ public class WifiServiceImpl extends BaseWifiService {
int success = mWifiThreadRunner.call(() -> mWifiNetworkSuggestionsManager.remove(
networkSuggestions, callingUid, callingPackageName,
- action), WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL);
+ action), WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL,
+ TAG + "#removeNetworkSuggestions");
if (success != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
Log.e(TAG, "Failed to remove network suggestions");
}
@@ -6211,7 +6320,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
return mWifiThreadRunner.call(() ->
mWifiNetworkSuggestionsManager.get(callingPackageName, callingUid),
- Collections.emptyList());
+ Collections.emptyList(), TAG + "#getNetworkSuggestions");
}
/**
@@ -6233,7 +6342,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
String result = mWifiThreadRunner.call(
() -> mActiveModeWarden.getPrimaryClientModeManager().getFactoryMacAddress(),
- null);
+ null, TAG + "#getFactoryMacAddresses");
// result can be empty array if either: WifiThreadRunner.call() timed out, or
// ClientModeImpl.getFactoryMacAddress() returned null.
// In this particular instance, we don't differentiate the two types of nulls.
@@ -6264,7 +6373,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiHealthMonitor.setDeviceMobilityState(state);
mWifiDataStall.setDeviceMobilityState(state);
mActiveModeWarden.setDeviceMobilityState(state);
- });
+ }, TAG + "#setDeviceMobilityState");
}
/**
@@ -6318,7 +6427,8 @@ public class WifiServiceImpl extends BaseWifiService {
mDppManager.startDppAsConfiguratorInitiator(
uid, packageName,
mActiveModeWarden.getPrimaryClientModeManager().getInterfaceName(),
- binder, enrolleeUri, selectedNetworkId, netRole, callback)));
+ binder, enrolleeUri, selectedNetworkId, netRole, callback)),
+ TAG + "#startDppAsConfiguratorInitiator");
}
/**
@@ -6355,7 +6465,8 @@ public class WifiServiceImpl extends BaseWifiService {
mMakeBeforeBreakManager.stopAllSecondaryTransientClientModeManagers(() ->
mDppManager.startDppAsEnrolleeInitiator(uid,
mActiveModeWarden.getPrimaryClientModeManager().getInterfaceName(),
- binder, configuratorUri, callback)));
+ binder, configuratorUri, callback)),
+ TAG + "#startDppAsEnrolleeInitiator");
}
/**
@@ -6412,7 +6523,8 @@ public class WifiServiceImpl extends BaseWifiService {
mMakeBeforeBreakManager.stopAllSecondaryTransientClientModeManagers(() ->
mDppManager.startDppAsEnrolleeResponder(uid,
mActiveModeWarden.getPrimaryClientModeManager().getInterfaceName(),
- binder, deviceInfo, curve, callback)));
+ binder, deviceInfo, curve, callback)),
+ TAG + "#startDppAsEnrolleeResponder");
}
/**
@@ -6425,7 +6537,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
final int uid = getMockableCallingUid();
- mWifiThreadRunner.post(() -> mDppManager.stopDppSession(uid));
+ mWifiThreadRunner.post(() -> mDppManager.stopDppSession(uid),
+ TAG + "#stopDppSession");
}
/**
@@ -6489,7 +6602,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
// Post operation to handler thread
mWifiThreadRunner.post(() ->
- mWifiMetrics.addOnWifiUsabilityListener(listener));
+ mWifiMetrics.addOnWifiUsabilityListener(listener),
+ TAG + "#addOnWifiUsabilityStatsListener");
}
/**
@@ -6513,7 +6627,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
// Post operation to handler thread
mWifiThreadRunner.post(() ->
- mWifiMetrics.removeOnWifiUsabilityListener(listener));
+ mWifiMetrics.removeOnWifiUsabilityListener(listener),
+ TAG + "#removeOnWifiUsabilityStatsListener");
}
/**
@@ -6540,7 +6655,7 @@ public class WifiServiceImpl extends BaseWifiService {
String ifaceName = mActiveModeWarden.getPrimaryClientModeManager().getInterfaceName();
mWifiMetrics.incrementWifiUsabilityScoreCount(
ifaceName, seqNum, score, predictionHorizonSec);
- });
+ }, TAG + "#updateWifiUsabilityScore");
}
/**
@@ -6588,7 +6703,10 @@ public class WifiServiceImpl extends BaseWifiService {
public void connect(WifiConfiguration config, int netId, @Nullable IActionListener callback,
@NonNull String packageName, Bundle extras) {
int uid = getMockableCallingUid();
- if (!isPrivileged(Binder.getCallingPid(), uid)) {
+ if (!isPrivileged(Binder.getCallingPid(), uid)
+ // TODO(b/343881335): Longer term, we need a specific permission
+ // for NFC.
+ && UserHandle.getAppId(uid) != Process.NFC_UID) {
throw new SecurityException(TAG + ": Permission denied");
}
if (packageName == null) {
@@ -6761,7 +6879,7 @@ public class WifiServiceImpl extends BaseWifiService {
mConnectHelper.connectToNetwork(
result, wrapper, uidToUse, packageNameToUse,
attributionTagToUse));
- });
+ }, TAG + "#connect");
}
/**
@@ -6797,7 +6915,7 @@ public class WifiServiceImpl extends BaseWifiService {
} else {
wrapper.sendFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR);
}
- });
+ }, TAG + "#save");
}
/**
@@ -6828,7 +6946,7 @@ public class WifiServiceImpl extends BaseWifiService {
Log.e(TAG, "Failed to remove network");
wrapper.sendFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR);
}
- });
+ }, TAG + "#forget");
}
/**
@@ -6847,20 +6965,25 @@ public class WifiServiceImpl extends BaseWifiService {
if (!mWifiInjector.getScanRequestProxy().registerScanResultsCallback(callback)) {
Log.e(TAG, "registerScanResultsCallback: Failed to register callback");
}
- });
+ }, TAG + "#registerScanResultsCallback");
}
/**
* See {@link WifiManager#registerScanResultsCallback(WifiManager.ScanResultsCallback)}
*/
public void unregisterScanResultsCallback(@NonNull IScanResultsCallback callback) {
+ if (callback == null) {
+ throw new IllegalArgumentException("callback must not be null");
+ }
+ enforceAccessPermission();
+
if (mVerboseLoggingEnabled) {
mLog.info("unregisterScanResultCallback uid=%").c(Binder.getCallingUid()).flush();
}
- enforceAccessPermission();
// post operation to handler thread
mWifiThreadRunner.post(() -> mWifiInjector.getScanRequestProxy()
- .unregisterScanResultsCallback(callback));
+ .unregisterScanResultsCallback(callback),
+ TAG + "#unregisterScanResultsCallback");
}
@@ -6887,7 +7010,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
mWifiThreadRunner.post(() ->
mWifiNetworkSuggestionsManager
- .registerSuggestionConnectionStatusListener(listener, packageName, uid));
+ .registerSuggestionConnectionStatusListener(listener, packageName, uid),
+ TAG + "#registerSuggestionConnectionStatusListener");
}
/**
@@ -6908,7 +7032,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
mWifiThreadRunner.post(() ->
mWifiNetworkSuggestionsManager
- .unregisterSuggestionConnectionStatusListener(listener, packageName, uid));
+ .unregisterSuggestionConnectionStatusListener(listener, packageName, uid),
+ TAG + "#unregisterSuggestionConnectionStatusListener");
}
/**
@@ -6939,7 +7064,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
mWifiThreadRunner.post(() ->
mWifiNetworkFactory.addLocalOnlyConnectionStatusListener(listener, packageName,
- featureId));
+ featureId), TAG + "#addLocalOnlyConnectionStatusListener");
}
/**
@@ -6969,7 +7094,8 @@ public class WifiServiceImpl extends BaseWifiService {
.c(uid).flush();
}
mWifiThreadRunner.post(() ->
- mWifiNetworkFactory.removeLocalOnlyConnectionStatusListener(listener, packageName));
+ mWifiNetworkFactory.removeLocalOnlyConnectionStatusListener(listener, packageName),
+ TAG + "#removeLocalOnlyConnectionStatusListener");
}
@Override
@@ -7007,7 +7133,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
mWifiConnectivityManager.setPnoScanEnabledByFramework(enabled,
enablePnoScanAfterWifiToggle);
- });
+ }, TAG + "#setPnoScanEnabled");
}
/**
@@ -7056,7 +7182,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#setExternalPnoScanRequest");
}
/**
@@ -7073,7 +7199,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
mWifiThreadRunner.post(() -> {
mWifiConnectivityManager.clearExternalPnoScanRequest(uid);
- });
+ }, TAG + "#clearExternalPnoScanRequest");
}
/**
@@ -7109,7 +7235,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#getLastCallerInfoForApi");
}
/**
@@ -7141,7 +7267,7 @@ public class WifiServiceImpl extends BaseWifiService {
// Post operation to handler thread
return mWifiThreadRunner.call(
() -> mActiveModeWarden.setWifiConnectedNetworkScorer(binder, scorer, callingUid),
- false);
+ false, TAG + "#setWifiConnectedNetworkScorer");
}
/**
@@ -7155,7 +7281,8 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("clearWifiConnectedNetworkScorer uid=%").c(Binder.getCallingUid()).flush();
}
// Post operation to handler thread
- mWifiThreadRunner.post(() -> mActiveModeWarden.clearWifiConnectedNetworkScorer());
+ mWifiThreadRunner.post(() -> mActiveModeWarden.clearWifiConnectedNetworkScorer(),
+ TAG + "#clearWifiConnectedNetworkScorer");
}
/**
@@ -7283,7 +7410,8 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("addSuggestionUserApprovalStatusListener uid=%").c(uid).flush();
}
mWifiThreadRunner.post(() -> mWifiNetworkSuggestionsManager
- .addSuggestionUserApprovalStatusListener(listener, packageName, uid));
+ .addSuggestionUserApprovalStatusListener(listener, packageName, uid),
+ TAG + "#addSuggestionUserApprovalStatusListener");
}
/**
@@ -7312,7 +7440,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
mWifiThreadRunner.post(() ->
mWifiNetworkSuggestionsManager
- .removeSuggestionUserApprovalStatusListener(listener, packageName, uid));
+ .removeSuggestionUserApprovalStatusListener(listener, packageName, uid),
+ TAG + "#removeSuggestionUserApprovalStatusListener");
}
/**
@@ -7336,7 +7465,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
removeAppStateInternal(targetAppUid, targetAppPackageName);
- });
+ }, TAG + "#removeAppState");
}
/**
@@ -7386,7 +7515,10 @@ public class WifiServiceImpl extends BaseWifiService {
if ((band & ScanResult.toBand(freq)) == 0) {
continue;
}
- channels.add(new WifiAvailableChannel(freq, WifiAvailableChannel.OP_MODE_SAP));
+ // TODO b/340956906: Save and retrieve channel width in config store along with
+ // frequency.
+ channels.add(new WifiAvailableChannel(freq, WifiAvailableChannel.OP_MODE_SAP,
+ ScanResult.CHANNEL_WIDTH_20MHZ));
}
return channels;
}
@@ -7442,7 +7574,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
}
List<WifiAvailableChannel> channels = mWifiThreadRunner.call(
- () -> mWifiNative.getUsableChannels(band, mode, filter), null);
+ () -> mWifiNative.getUsableChannels(band, mode, filter), null,
+ TAG + "#getUsableChannels");
if (channels == null) {
throw new UnsupportedOperationException();
}
@@ -7470,7 +7603,8 @@ public class WifiServiceImpl extends BaseWifiService {
android.Manifest.permission.NETWORK_MANAGED_PROVISIONING,
android.Manifest.permission.NETWORK_CARRIER_PROVISIONING);
}
- mWifiThreadRunner.post(mPasspointManager::clearAnqpRequestsAndFlushCache);
+ mWifiThreadRunner.post(mPasspointManager::clearAnqpRequestsAndFlushCache,
+ TAG + "#flushPasspointAnqpCache");
}
/**
@@ -7484,7 +7618,8 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("isWifiPasspointEnabled uid=%").c(Binder.getCallingUid()).flush();
}
// Post operation to handler thread
- return mWifiThreadRunner.call(() -> mPasspointManager.isWifiPasspointEnabled(), false);
+ return mWifiThreadRunner.call(() -> mPasspointManager.isWifiPasspointEnabled(), false,
+ TAG + "#isWifiPasspointEnabled");
}
/**
@@ -7505,8 +7640,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
// Post operation to handler thread
- mWifiThreadRunner.post(() ->
- mPasspointManager.setWifiPasspointEnabled(enabled)
+ mWifiThreadRunner.post(() -> mPasspointManager.setWifiPasspointEnabled(enabled),
+ TAG + "#setWifiPasspointEnabled"
);
}
@@ -7549,7 +7684,8 @@ public class WifiServiceImpl extends BaseWifiService {
// Post operation to handler thread
return mWifiThreadRunner.call(
() -> mMultiInternetManager.getStaConcurrencyForMultiInternetMode(),
- WifiManager.WIFI_MULTI_INTERNET_MODE_DISABLED);
+ WifiManager.WIFI_MULTI_INTERNET_MODE_DISABLED,
+ TAG + "#getStaConcurrencyForMultiInternetMode");
}
/**
@@ -7574,7 +7710,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
// Post operation to handler thread
return mWifiThreadRunner.call(() ->
- mMultiInternetManager.setStaConcurrencyForMultiInternetMode(mode), false);
+ mMultiInternetManager.setStaConcurrencyForMultiInternetMode(mode), false,
+ TAG + "#setStaConcurrencyForMultiInternetMode");
}
/**
@@ -7616,7 +7753,7 @@ public class WifiServiceImpl extends BaseWifiService {
continue;
}
}
- });
+ }, TAG + "#notifyMinimumRequiredWifiSecurityLevelChanged");
}
/**
@@ -7657,7 +7794,7 @@ public class WifiServiceImpl extends BaseWifiService {
continue;
}
}
- });
+ }, TAG + "#notifyWifiSsidPolicyChanged");
}
/**
@@ -7673,8 +7810,8 @@ public class WifiServiceImpl extends BaseWifiService {
.c(uid).c(pid).c(dialogId).c(reply)
.flush();
}
- mWifiThreadRunner.post(() ->
- mWifiDialogManager.replyToSimpleDialog(dialogId, reply));
+ mWifiThreadRunner.post(() -> mWifiDialogManager.replyToSimpleDialog(dialogId, reply),
+ TAG + "#replyToSimpleDialog");
}
/**
@@ -7692,9 +7829,8 @@ public class WifiServiceImpl extends BaseWifiService {
.c(uid).c(pid).c(dialogId).c(accepted).c(optionalPin)
.flush();
}
- mWifiThreadRunner.post(() ->
- mWifiDialogManager.replyToP2pInvitationReceivedDialog(
- dialogId, accepted, optionalPin)
+ mWifiThreadRunner.post(() -> mWifiDialogManager.replyToP2pInvitationReceivedDialog(
+ dialogId, accepted, optionalPin), TAG + "#replyToP2pInvitationReceivedDialog"
);
}
@@ -7706,7 +7842,12 @@ public class WifiServiceImpl extends BaseWifiService {
@NonNull List<DhcpOption> options) {
enforceAnyPermissionOf(android.Manifest.permission.NETWORK_SETTINGS,
android.Manifest.permission.OVERRIDE_WIFI_CONFIG);
- mWifiThreadRunner.post(() -> mWifiConfigManager.addCustomDhcpOptions(ssid, oui, options));
+ if (mVerboseLoggingEnabled) {
+ Log.v(TAG, "addCustomDhcpOptions: ssid="
+ + ssid + ", oui=" + Arrays.toString(oui) + ", options=" + options);
+ }
+ mWifiThreadRunner.post(() -> mWifiConfigManager.addCustomDhcpOptions(ssid, oui, options),
+ TAG + "#addCustomDhcpOptions");
}
/**
@@ -7716,7 +7857,11 @@ public class WifiServiceImpl extends BaseWifiService {
public void removeCustomDhcpOptions(@NonNull WifiSsid ssid, @NonNull byte[] oui) {
enforceAnyPermissionOf(android.Manifest.permission.NETWORK_SETTINGS,
android.Manifest.permission.OVERRIDE_WIFI_CONFIG);
- mWifiThreadRunner.post(() -> mWifiConfigManager.removeCustomDhcpOptions(ssid, oui));
+ if (mVerboseLoggingEnabled) {
+ Log.v(TAG, "removeCustomDhcpOptions: ssid=" + ssid + ", oui=" + Arrays.toString(oui));
+ }
+ mWifiThreadRunner.post(() -> mWifiConfigManager.removeCustomDhcpOptions(ssid, oui),
+ TAG + "#removeCustomDhcpOptions");
}
/**
@@ -7802,7 +7947,7 @@ public class WifiServiceImpl extends BaseWifiService {
Log.e(TAG,
"Failed calling back with results of isItPossibleToCreateInterface - " + e);
}
- });
+ }, TAG + "#reportCreateInterfaceImpact");
}
@Override
public int getMaxNumberOfChannelsPerRequest() {
@@ -7896,7 +8041,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
mApplicationQosPolicyRequestHandler.queueAddRequest(
policyParamsList, listener, binder, uid);
- });
+ }, TAG + "#addQosPolicies");
}
/**
@@ -7927,7 +8072,7 @@ public class WifiServiceImpl extends BaseWifiService {
List<Integer> policyIdList = Arrays.stream(policyIds).boxed().toList();
mWifiThreadRunner.post(() -> {
mApplicationQosPolicyRequestHandler.queueRemoveRequest(policyIdList, uid);
- });
+ }, TAG + "#removeQosPolicies");
}
/**
@@ -7951,7 +8096,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
mApplicationQosPolicyRequestHandler.queueRemoveAllRequest(uid);
- });
+ }, TAG + "#removeAllQosPolicies");
}
/**
@@ -7967,7 +8112,8 @@ public class WifiServiceImpl extends BaseWifiService {
throw new IllegalArgumentException("intervalMs should not be smaller than 0");
}
mWifiThreadRunner.post(() -> mActiveModeWarden.getPrimaryClientModeManager()
- .setLinkLayerStatsPollingInterval(intervalMs));
+ .setLinkLayerStatsPollingInterval(intervalMs),
+ TAG + "#setLinkLayerStatsPollingInterval");
}
/**
@@ -7988,7 +8134,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#getLinkLayerStatsPollingInterval");
}
/**
@@ -8018,7 +8164,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#setMloMode");
}
/**
@@ -8045,7 +8191,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#getMloMode");
}
/**
@@ -8067,7 +8213,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
mWifiThreadRunner.post(() -> {
mWifiLockManager.addWifiLowLatencyLockListener(listener);
- });
+ }, TAG + "#addWifiLowLatencyLockListener");
}
/**
@@ -8083,7 +8229,7 @@ public class WifiServiceImpl extends BaseWifiService {
}
mWifiThreadRunner.post(() -> {
mWifiLockManager.removeWifiLowLatencyLockListener(listener);
- });
+ }, TAG + "#removeWifiLowLatencyLockListener");
}
private String getPackageName(Bundle extras) {
@@ -8128,7 +8274,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#getMaxMloAssociationLinkCount");
}
/**
@@ -8160,7 +8306,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#getMaxMloStrLinkCount");
}
/**
@@ -8205,7 +8351,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#getSupportedSimultaneousBandCombinations");
}
/**
@@ -8245,22 +8391,26 @@ public class WifiServiceImpl extends BaseWifiService {
mLog.info("setWepAllowed=% uid=%").c(isAllowed).c(callingUid).flush();
mWifiThreadRunner.post(() -> {
mSettingsConfigStore.put(WIFI_WEP_ALLOWED, isAllowed);
- mWifiGlobals.setWepAllowed(isAllowed);
- if (!isAllowed) {
- for (ClientModeManager clientModeManager
- : mActiveModeWarden.getClientModeManagers()) {
- if (!(clientModeManager instanceof ConcreteClientModeManager)) {
- continue;
- }
- ConcreteClientModeManager cmm = (ConcreteClientModeManager) clientModeManager;
- WifiInfo info = cmm.getConnectionInfo();
- if (info != null
- && info.getCurrentSecurityType() == WifiInfo.SECURITY_TYPE_WEP) {
- clientModeManager.disconnect();
- }
+ handleWepAllowedChanged(isAllowed);
+ }, TAG + "#setWepAllowed");
+ }
+
+ private void handleWepAllowedChanged(boolean isAllowed) {
+ mWifiGlobals.setWepAllowed(isAllowed);
+ if (!isAllowed) {
+ for (ClientModeManager clientModeManager
+ : mActiveModeWarden.getClientModeManagers()) {
+ if (!(clientModeManager instanceof ConcreteClientModeManager)) {
+ continue;
+ }
+ ConcreteClientModeManager cmm = (ConcreteClientModeManager) clientModeManager;
+ WifiInfo info = cmm.getConnectionInfo();
+ if (info != null
+ && info.getCurrentSecurityType() == WifiInfo.SECURITY_TYPE_WEP) {
+ clientModeManager.disconnect();
}
}
- });
+ }
}
/**
@@ -8282,7 +8432,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#setWepAllowed");
}
/**
@@ -8302,7 +8452,7 @@ public class WifiServiceImpl extends BaseWifiService {
for (ClientModeManager cmm : clientModeManagers) {
mWifiNative.enableMscs(mscsParams, cmm.getInterfaceName());
}
- });
+ }, TAG + "#enableMscs");
}
/**
@@ -8321,7 +8471,7 @@ public class WifiServiceImpl extends BaseWifiService {
for (ClientModeManager cmm : clientModeManagers) {
mWifiNative.disableMscs(cmm.getInterfaceName());
}
- });
+ }, TAG + "#disableMscs");
}
/**
@@ -8346,7 +8496,8 @@ public class WifiServiceImpl extends BaseWifiService {
throw new SecurityException("Uid " + callingUid
+ " is not allowed to query the global dhcp hostname restriction");
}
- mWifiThreadRunner.post(() -> mWifiGlobals.setSendDhcpHostnameRestriction(restriction));
+ mWifiThreadRunner.post(() -> mWifiGlobals.setSendDhcpHostnameRestriction(restriction),
+ TAG + "#setSendDhcpHostnameRestriction");
}
/**
@@ -8375,19 +8526,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
- }
-
- /**
- * Force Overlay Config for testing
- */
- public boolean forceOverlayConfigValue(String configString, String value, boolean isEnabled) {
- int uid = Binder.getCallingUid();
- if (!mWifiPermissionsUtil.checkNetworkSettingsPermission(uid)) {
- throw new SecurityException(TAG + " Uid " + uid
- + " Missing NETWORK_SETTINGS permission");
- }
- return mWifiGlobals.forceOverlayConfigValue(configString, value, isEnabled);
+ }, TAG + "#querySendDhcpHostnameRestriction");
}
/**
@@ -8423,7 +8562,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
mWifiInjector.getWifiRoamingModeManager().setPerSsidRoamingMode(ssid,
roamingMode, isDeviceOwner);
- });
+ }, TAG + "#setPerSsidRoamingMode");
}
/**
@@ -8454,7 +8593,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
mWifiInjector.getWifiRoamingModeManager().removePerSsidRoamingMode(
ssid, isDeviceOwner);
- });
+ }, TAG + "#removePerSsidRoamingMode");
}
/**
@@ -8491,7 +8630,7 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage());
}
- });
+ }, TAG + "#getPerSsidRoamingModes");
}
/**
@@ -8513,7 +8652,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
mTwtManager.getTwtCapabilities(
mActiveModeWarden.getPrimaryClientModeManager().getInterfaceName(), listener);
- });
+ }, TAG + "#getTwtCapabilities");
}
/**
@@ -8538,17 +8677,19 @@ public class WifiServiceImpl extends BaseWifiService {
}
mWifiThreadRunner.post(() -> {
try {
- if (!mActiveModeWarden.getPrimaryClientModeManager().isConnected()) {
+ String bssid = mActiveModeWarden.getPrimaryClientModeManager().getConnectedBssid();
+ if (!mActiveModeWarden.getPrimaryClientModeManager().isConnected()
+ || bssid == null) {
iTwtCallback.onFailure(TwtSessionCallback.TWT_ERROR_CODE_NOT_AVAILABLE);
return;
}
mTwtManager.setupTwtSession(
mActiveModeWarden.getPrimaryClientModeManager().getInterfaceName(),
- twtRequest, iTwtCallback, callingUid);
+ twtRequest, iTwtCallback, callingUid, bssid);
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#setupTwtSession");
}
/**
@@ -8573,7 +8714,7 @@ public class WifiServiceImpl extends BaseWifiService {
mTwtManager.getStatsTwtSession(
mActiveModeWarden.getPrimaryClientModeManager().getInterfaceName(),
iTwtStatsListener, sessionId);
- });
+ }, TAG + "#getStatsTwtSession");
}
/**
@@ -8592,7 +8733,7 @@ public class WifiServiceImpl extends BaseWifiService {
mWifiThreadRunner.post(() -> {
mTwtManager.tearDownTwtSession(
mActiveModeWarden.getPrimaryClientModeManager().getInterfaceName(), sessionId);
- });
+ }, TAG + "#teardownTwtSession");
}
/**
@@ -8607,7 +8748,8 @@ public class WifiServiceImpl extends BaseWifiService {
}
mLog.info("setD2dAllowedWhenInfraStaDisabled=% uid=%").c(isAllowed).c(callingUid).flush();
mWifiThreadRunner.post(
- () -> mSettingsConfigStore.put(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED, isAllowed));
+ () -> mSettingsConfigStore.put(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED, isAllowed),
+ TAG + "#setD2dAllowedWhenInfraStaDisabled");
}
/**
@@ -8624,6 +8766,6 @@ public class WifiServiceImpl extends BaseWifiService {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#queryD2dAllowedWhenInfraStaDisabled");
}
}
diff --git a/service/java/com/android/server/wifi/WifiSettingsBackupRestore.java b/service/java/com/android/server/wifi/WifiSettingsBackupRestore.java
index 71f815232a..e539655c9e 100644
--- a/service/java/com/android/server/wifi/WifiSettingsBackupRestore.java
+++ b/service/java/com/android/server/wifi/WifiSettingsBackupRestore.java
@@ -42,7 +42,7 @@ public class WifiSettingsBackupRestore {
private static final String TAG = "WifiSettingsBackupRestore";
public static final String XML_TAG_SECTION_HEADER_WIFI_SETTINGS_DATA =
- "WifiSettingsBackData";
+ "WifiSettingsSection";
private WifiSettingsConfigStore mWifiSettingsConfigStore;
private Map<String, WifiSettingsConfigStore.Key> mRestoreSettingsMap = new HashMap<>();
diff --git a/service/java/com/android/server/wifi/WifiSettingsConfigStore.java b/service/java/com/android/server/wifi/WifiSettingsConfigStore.java
index 052e6f2ae6..17af39fdd8 100644
--- a/service/java/com/android/server/wifi/WifiSettingsConfigStore.java
+++ b/service/java/com/android/server/wifi/WifiSettingsConfigStore.java
@@ -40,6 +40,7 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.Objects;
@@ -202,9 +203,9 @@ public class WifiSettingsConfigStore {
new Key<>("d2d_allowed_when_infra_sta_disabled", false);
// List of all keys which require to backup and restore.
- @SuppressWarnings("DoubleBraceInitialization")
- private static final ArrayList<Key> sBackupRestoreKeys = new ArrayList<>() {{
- add(WIFI_WEP_ALLOWED); }};
+ private static final List<Key> sBackupRestoreKeys = List.of(
+ WIFI_WEP_ALLOWED,
+ D2D_ALLOWED_WHEN_INFRA_STA_DISABLED);
/******** Wifi shared pref keys ***************/
private final Context mContext;
@@ -253,7 +254,7 @@ public class WifiSettingsConfigStore {
return sKeys;
}
- public ArrayList<Key> getAllBackupRestoreKeys() {
+ public List<Key> getAllBackupRestoreKeys() {
return sBackupRestoreKeys;
}
@@ -286,7 +287,7 @@ public class WifiSettingsConfigStore {
private void triggerSaveToStoreAndInvokeAllListeners() {
mHandler.post(() -> {
mHasNewDataToSerialize = true;
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
invokeAllListeners();
});
@@ -298,7 +299,7 @@ public class WifiSettingsConfigStore {
private <T> void triggerSaveToStoreAndInvokeListeners(@NonNull Key<T> key) {
mHandler.post(() -> {
mHasNewDataToSerialize = true;
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
invokeListeners(key);
});
diff --git a/service/java/com/android/server/wifi/WifiSettingsStore.java b/service/java/com/android/server/wifi/WifiSettingsStore.java
index bf7870c5eb..a84346b77f 100644
--- a/service/java/com/android/server/wifi/WifiSettingsStore.java
+++ b/service/java/com/android/server/wifi/WifiSettingsStore.java
@@ -44,6 +44,7 @@ public class WifiSettingsStore {
* WIFI_ENABLED_APM_OVERRIDE
* WIFI_DISABLED_APM_ON
*/
+ private static final String TAG = "WifiSettingsStore";
@VisibleForTesting
public static final int WIFI_DISABLED = 0;
@VisibleForTesting
@@ -263,7 +264,8 @@ public class WifiSettingsStore {
NOTIFICATION_NOT_SHOWN) == NOTIFICATION_NOT_SHOWN) {
mWifiThreadRunner.post(
() -> showNotification(R.string.wifi_enabled_apm_first_time_title,
- R.string.wifi_enabled_apm_first_time_message));
+ R.string.wifi_enabled_apm_first_time_message),
+ TAG + "#handleWifiToggled");
setUserSecureIntegerSetting(
APM_WIFI_ENABLED_NOTIFICATION, NOTIFICATION_SHOWN);
}
@@ -316,7 +318,8 @@ public class WifiSettingsStore {
&& !isBluetoothEnabledOnApm()) {
mWifiThreadRunner.post(
() -> showNotification(R.string.apm_enabled_first_time_title,
- R.string.apm_enabled_first_time_message));
+ R.string.apm_enabled_first_time_message),
+ TAG + "#handleAirplaneModeToggled");
setUserSecureIntegerSetting(APM_WIFI_NOTIFICATION, NOTIFICATION_SHOWN);
}
} else {
diff --git a/service/java/com/android/server/wifi/WifiShellCommand.java b/service/java/com/android/server/wifi/WifiShellCommand.java
index 98807410f7..8b68e3a2a2 100644
--- a/service/java/com/android/server/wifi/WifiShellCommand.java
+++ b/service/java/com/android/server/wifi/WifiShellCommand.java
@@ -76,6 +76,7 @@ import android.net.wifi.WifiNetworkSuggestion;
import android.net.wifi.WifiScanner;
import android.net.wifi.WifiSsid;
import android.net.wifi.util.ScanResultUtil;
+import android.net.wifi.util.WifiResourceCache;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
@@ -151,6 +152,8 @@ public class WifiShellCommand extends BasicShellCommandHandler {
private static final String[] NON_PRIVILEGED_COMMANDS = {
"add-suggestion",
"forget-network",
+ "connect-network",
+ "add-network",
"get-country-code",
"help",
"-h",
@@ -168,9 +171,7 @@ public class WifiShellCommand extends BasicShellCommandHandler {
"set-passpoint-enabled",
"set-multi-internet-state",
"start-scan",
- "start-softap",
"status",
- "stop-softap",
"query-interface",
"interface-priority-interactive-mode",
"set-one-shot-screen-on-delay-ms",
@@ -183,6 +184,8 @@ public class WifiShellCommand extends BasicShellCommandHandler {
"get-mock-wifimodem-service",
"set-mock-wifimodem-methods",
"force-overlay-config-value",
+ "get-softap-supported-features",
+ "get-overlay-config-values"
};
private static final Map<String, Pair<NetworkRequest, ConnectivityManager.NetworkCallback>>
@@ -214,6 +217,7 @@ public class WifiShellCommand extends BasicShellCommandHandler {
private final WifiDiagnostics mWifiDiagnostics;
private final DeviceConfigFacade mDeviceConfig;
private final AfcManager mAfcManager;
+ private final WifiInjector mWifiInjector;
private static final int[] OP_MODE_LIST = {
WifiAvailableChannel.OP_MODE_STA,
WifiAvailableChannel.OP_MODE_SAP,
@@ -438,6 +442,7 @@ public class WifiShellCommand extends BasicShellCommandHandler {
WifiShellCommand(WifiInjector wifiInjector, WifiServiceImpl wifiService, WifiContext context,
WifiGlobals wifiGlobals, WifiThreadRunner wifiThreadRunner) {
+ mWifiInjector = wifiInjector;
mWifiGlobals = wifiGlobals;
mWifiThreadRunner = wifiThreadRunner;
mActiveModeWarden = wifiInjector.getActiveModeWarden();
@@ -552,8 +557,10 @@ public class WifiShellCommand extends BasicShellCommandHandler {
case "network-suggestions-set-user-approved": {
String packageName = getNextArgRequired();
boolean approved = getNextArgRequiredTrueOrFalse("yes", "no");
- mWifiNetworkSuggestionsManager.setHasUserApprovedForApp(approved,
- Binder.getCallingUid(), packageName);
+ mWifiThreadRunner.post(() -> mWifiNetworkSuggestionsManager
+ .setHasUserApprovedForApp(approved,
+ Binder.getCallingUid(), packageName),
+ "shell#setHasUserApprovedForApp");
return 0;
}
case "network-suggestions-has-user-approved": {
@@ -601,7 +608,7 @@ public class WifiShellCommand extends BasicShellCommandHandler {
final int carrierId = Integer.parseInt(arg1);
mWifiThreadRunner.post(() ->
mWifiCarrierInfoManager.clearImsiPrivacyExemptionForCarrier(
- carrierId));
+ carrierId), TAG + "#" + cmd);
} catch (NumberFormatException e) {
pw.println("Invalid argument to "
+ "'imsi-protection-exemption-clear-user-approved-for-carrier' "
@@ -612,7 +619,8 @@ public class WifiShellCommand extends BasicShellCommandHandler {
}
case "network-requests-remove-user-approved-access-points": {
String packageName = getNextArgRequired();
- mWifiThreadRunner.post(() -> mWifiNetworkFactory.removeApp(packageName));
+ mWifiThreadRunner.post(() -> mWifiNetworkFactory.removeApp(packageName),
+ TAG + "#" + cmd);
return 0;
}
case "clear-user-disabled-networks": {
@@ -961,7 +969,7 @@ public class WifiShellCommand extends BasicShellCommandHandler {
return 0;
case "list-scan-results":
List<ScanResult> scanResults =
- mWifiService.getScanResults(SHELL_PACKAGE_NAME, null);
+ mScanRequestProxy.getScanResults();
if (scanResults.isEmpty()) {
pw.println("No scan results");
} else {
@@ -1009,9 +1017,6 @@ public class WifiShellCommand extends BasicShellCommandHandler {
WifiConfiguration config = buildWifiConfiguration(pw);
mWifiService.connect(config, -1, actionListener, SHELL_PACKAGE_NAME,
new Bundle());
- // wait for status.
- countDownLatch.await(500, TimeUnit.MILLISECONDS);
- setAutoJoin(pw, config.SSID, config.allowAutojoin);
return 0;
}
case "add-network": {
@@ -1031,9 +1036,6 @@ public class WifiShellCommand extends BasicShellCommandHandler {
};
WifiConfiguration config = buildWifiConfiguration(pw);
mWifiService.save(config, actionListener, SHELL_PACKAGE_NAME);
- // wait for status.
- countDownLatch.await(500, TimeUnit.MILLISECONDS);
- setAutoJoin(pw, config.SSID, config.allowAutojoin);
return 0;
}
case "forget-network": {
@@ -1224,7 +1226,10 @@ public class WifiShellCommand extends BasicShellCommandHandler {
ConnectivityManager.NetworkCallback networkCallback =
new ConnectivityManager.NetworkCallback();
pw.println("Adding request: " + networkRequest);
- mConnectivityManager.requestNetwork(networkRequest, networkCallback);
+ mWifiThreadRunner.post(() -> mConnectivityManager
+ .requestNetwork(networkRequest, networkCallback),
+ "shell#add-request");
+
sActiveRequests.put(ssid, Pair.create(networkRequest, networkCallback));
return 0;
}
@@ -1237,7 +1242,9 @@ public class WifiShellCommand extends BasicShellCommandHandler {
return -1;
}
pw.println("Removing request: " + nrAndNc.first);
- mConnectivityManager.unregisterNetworkCallback(nrAndNc.second);
+ mWifiThreadRunner.post(() -> mConnectivityManager
+ .unregisterNetworkCallback(nrAndNc.second),
+ "shell#remove-request");
return 0;
}
case "remove-all-requests":
@@ -1248,7 +1255,9 @@ public class WifiShellCommand extends BasicShellCommandHandler {
for (Pair<NetworkRequest, ConnectivityManager.NetworkCallback> nrAndNc
: sActiveRequests.values()) {
pw.println("Removing request: " + nrAndNc.first);
- mConnectivityManager.unregisterNetworkCallback(nrAndNc.second);
+ mWifiThreadRunner.post(() ->
+ mConnectivityManager.unregisterNetworkCallback(nrAndNc.second),
+ "shell#remove-request");
}
sActiveRequests.clear();
return 0;
@@ -1925,7 +1934,8 @@ public class WifiShellCommand extends BasicShellCommandHandler {
location.setLongitude(longitude);
location.setLatitude(latitude);
location.setAltitude(height);
- mWifiThreadRunner.post(() -> mAfcManager.onLocationChange(location, true));
+ mWifiThreadRunner.post(() -> mAfcManager.onLocationChange(location, true),
+ TAG + "#" + cmd);
pw.println("The updated location with longitude of " + longitude + " degrees, "
+ "latitude of " + latitude + " degrees, and height of " + height
+ " meters was passed into the Afc Manager onLocationChange method.");
@@ -2048,7 +2058,7 @@ public class WifiShellCommand extends BasicShellCommandHandler {
queue.offer("Setting the allowed AFC channels and frequencies "
+ "failed.");
}
- });
+ }, TAG + "#" + cmd);
// block until msg is received, or timed out
String msg = queue.poll(3000, TimeUnit.MILLISECONDS);
@@ -2113,7 +2123,7 @@ public class WifiShellCommand extends BasicShellCommandHandler {
mWifiThreadRunner.post(() -> {
mAfcManager.setServerUrlAndRequestPropertyPairs(url, requestProperties);
- });
+ }, TAG + "#" + cmd);
pw.println("The URL is set to " + url);
pw.println("The request properties are set to: ");
@@ -2154,15 +2164,45 @@ public class WifiShellCommand extends BasicShellCommandHandler {
}
return 0;
case "force-overlay-config-value":
- String value = getNextArgRequired();
- String configString = getNextArgRequired();
- boolean isEnabled = getNextArgRequiredTrueOrFalse("enabled", "disabled");
- if (mWifiService.forceOverlayConfigValue(configString, value, isEnabled)) {
- pw.print("true");
- } else {
- pw.print("fail to force overlay config value: " + configString);
+ int uid = Binder.getCallingUid();
+ if (!mWifiInjector.getWifiPermissionsUtil()
+ .checkNetworkSettingsPermission(Binder.getCallingUid())) {
+ pw.println("current shell caller Uid " + uid
+ + " Missing NETWORK_SETTINGS permission");
return -1;
}
+ WifiResourceCache resourceCache = mContext.getResourceCache();
+ String type = getNextArgRequired();
+ String overlayName = getNextArgRequired();
+ boolean isEnabled = getNextArgRequiredTrueOrFalse("enabled", "disabled");
+ switch (type) {
+ case "bool" -> {
+ boolean value = false;
+ if (isEnabled) {
+ value = getNextArgRequiredTrueOrFalse("true", "false");
+ resourceCache.overrideBooleanValue(overlayName, value);
+ } else {
+ resourceCache.restoreBooleanValue(overlayName);
+ }
+ }
+ case "integer" -> {
+ int value = 0;
+ if (isEnabled) {
+ value = Integer.parseInt(getNextArgRequired());
+ resourceCache.overrideIntegerValue(overlayName, value);
+ } else {
+ resourceCache.restoreIntegerValue(overlayName);
+ }
+ }
+ default -> {
+ pw.print("require a valid type of the overlay");
+ return -1;
+ }
+ }
+ pw.println("true");
+ return 0;
+ case "get-overlay-config-values":
+ mContext.getResourceCache().dump(pw);
return 0;
default:
return handleDefaultCommands(cmd);
@@ -2536,7 +2576,7 @@ public class WifiShellCommand extends BasicShellCommandHandler {
// So, find scan result with the best rssi level to set in the request.
if (bssid == null && !nullBssid && !noSsid) {
ScanResult matchingScanResult =
- mWifiService.getScanResults(SHELL_PACKAGE_NAME, null)
+ mScanRequestProxy.getScanResults()
.stream()
.filter(s -> s.SSID.equals(ssid))
.max(Comparator.comparingInt(s -> s.level))
@@ -2611,28 +2651,6 @@ public class WifiShellCommand extends BasicShellCommandHandler {
return cellChannels;
}
- private void setAutoJoin(PrintWriter pw, String ssid, boolean allowAutojoin) {
- // For suggestions, this will work only if the config has already been added
- // to WifiConfigManager.
- Bundle extras = new Bundle();
- if (SdkLevel.isAtLeastS()) {
- extras.putParcelable(WifiManager.EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE,
- mContext.getAttributionSource());
- }
- WifiConfiguration retrievedConfig =
- mWifiService.getPrivilegedConfiguredNetworks(SHELL_PACKAGE_NAME, null, extras)
- .getList()
- .stream()
- .filter(n -> n.SSID.equals(ssid))
- .findAny()
- .orElse(null);
- if (retrievedConfig == null) {
- pw.println("Cannot retrieve config, autojoin setting skipped.");
- return;
- }
- mWifiService.allowAutojoin(retrievedConfig.networkId, allowAutojoin);
- }
-
private int sendLinkProbe(PrintWriter pw) throws InterruptedException {
// Note: should match WifiNl80211Manager#SEND_MGMT_FRAME_TIMEOUT_MS
final int sendMgmtFrameTimeoutMs = 1000;
@@ -2650,7 +2668,7 @@ public class WifiShellCommand extends BasicShellCommandHandler {
queue.offer("Link probe failed with reason "
+ LinkProbeCallback.failureReasonToString(reason));
}
- }, -1));
+ }, -1), TAG + "#sendLinkProbe");
// block until msg is received, or timed out
String msg = queue.poll(sendMgmtFrameTimeoutMs + 1000, TimeUnit.MILLISECONDS);
@@ -2775,6 +2793,48 @@ public class WifiShellCommand extends BasicShellCommandHandler {
pw.println(" Enables/disables Wifi on this device.");
pw.println(" set-scan-always-available enabled|disabled");
pw.println(" Sets whether scanning should be available even when wifi is off.");
+ pw.println(" connect-network <ssid> open|owe|wpa2|wpa3|wep [<passphrase>] [-x] [-m] "
+ + "[-d] [-b <bssid>] [-r auto|none|persistent|non_persistent]");
+ pw.println(" Connect to a network with provided params and add to saved networks list");
+ pw.println(" <ssid> - SSID of the network");
+ pw.println(" open|owe|wpa2|wpa3|wep - Security type of the network.");
+ pw.println(" - Use 'open' or 'owe' for networks with no passphrase");
+ pw.println(" - 'open' - Open networks (Most prevalent)");
+ pw.println(" - 'owe' - Enhanced open networks");
+ pw.println(" - Use 'wpa2' or 'wpa3' or 'wep' for networks with passphrase");
+ pw.println(" - 'wpa2' - WPA-2 PSK networks (Most prevalent)");
+ pw.println(" - 'wpa3' - WPA-3 PSK networks");
+ pw.println(" - 'wep' - WEP network. Passphrase should be bytes in hex or encoded"
+ + " into String using UTF-8");
+ pw.println(" -x - Specifies the SSID as hex digits instead of plain text");
+ pw.println(" -m - Mark the network metered.");
+ pw.println(" -d - Mark the network autojoin disabled.");
+ pw.println(" -h - Mark the network hidden.");
+ pw.println(" -p - Mark the network private (not shared).");
+ pw.println(" -b <bssid> - Set specific BSSID.");
+ pw.println(" -r auto|none|persistent|non_persistent - MAC randomization scheme for the"
+ + " network");
+ pw.println(" add-network <ssid> open|owe|wpa2|wpa3|wep [<passphrase>] [-x] [-m] [-d] "
+ + "[-b <bssid>] [-r auto|none|persistent|non_persistent]");
+ pw.println(" Add/update saved network with provided params");
+ pw.println(" <ssid> - SSID of the network");
+ pw.println(" open|owe|wpa2|wpa3|wep - Security type of the network.");
+ pw.println(" - Use 'open' or 'owe' for networks with no passphrase");
+ pw.println(" - 'open' - Open networks (Most prevalent)");
+ pw.println(" - 'owe' - Enhanced open networks");
+ pw.println(" - Use 'wpa2' or 'wpa3' for networks with passphrase");
+ pw.println(" - 'wpa2' - WPA-2 PSK networks (Most prevalent)");
+ pw.println(" - 'wpa3' - WPA-3 PSK networks");
+ pw.println(" - 'wep' - WEP network. Passphrase should be bytes in hex or encoded"
+ + " into String using UTF-8");
+ pw.println(" -x - Specifies the SSID as hex digits instead of plain text");
+ pw.println(" -m - Mark the network metered.");
+ pw.println(" -d - Mark the network autojoin disabled.");
+ pw.println(" -h - Mark the network hidden.");
+ pw.println(" -p - Mark the network private (not shared).");
+ pw.println(" -b <bssid> - Set specific BSSID.");
+ pw.println(" -r auto|none|persistent|non_persistent - MAC randomization scheme for the"
+ + " network");
pw.println(" list-scan-results");
pw.println(" Lists the latest scan results");
pw.println(" start-scan");
@@ -2865,45 +2925,6 @@ public class WifiShellCommand extends BasicShellCommandHandler {
pw.println(" reset-connected-score");
pw.println(" Turns on the default connected scorer.");
pw.println(" Note: Will clear any external scorer set.");
- pw.println(
- " start-softap <ssid> (open|wpa2|wpa3|wpa3_transition|owe|owe_transition)"
- + " <passphrase> [-b 2|5|6|any|bridged|bridged_2_5|bridged_2_6|bridged_5_6]"
- + " [-x] [-w 20|40|80|160|320] [-f <int> [<int>]]");
- pw.println(" Start softap with provided params");
- pw.println(" Note that the shell command doesn't activate internet tethering. In some "
- + "devices, internet sharing is possible when Wi-Fi STA is also enabled and is"
- + "associated to another AP with internet access.");
- pw.println(" <ssid> - SSID of the network");
- pw.println(" open|wpa2|wpa3|wpa3_transition|owe|owe_transition - Security type of the "
- + "network.");
- pw.println(" - Use 'open', 'owe', 'owe_transition' for networks with no passphrase");
- pw.println(" - Use 'wpa2', 'wpa3', 'wpa3_transition' for networks with passphrase");
- pw.println(" -b 2|5|6|any|bridged|bridged_2_5|bridged_2_6|bridged_5_6 - select the"
- + " preferred bands.");
- pw.println(" - Use '2' to select 2.4GHz band as the preferred band");
- pw.println(" - Use '5' to select 5GHz band as the preferred band");
- pw.println(" - Use '6' to select 6GHz band as the preferred band");
- pw.println(" - Use 'any' to indicate no band preference");
- pw.println(" - Use 'bridged' to indicate bridged AP which enables APs on both "
- + "2.4G + 5G");
- pw.println(" - Use 'bridged_2_5' to indicate bridged AP which enables APs on both "
- + "2.4G + 5G");
- pw.println(" - Use 'bridged_2_6' to indicate bridged AP which enables APs on both "
- + "2.4G + 6G");
- pw.println(" - Use 'bridged_5_6' to indicate bridged AP which enables APs on both "
- + "5G + 6G");
- pw.println(" Note: If the band option is not provided, 2.4GHz is the preferred band.");
- pw.println(" The exact channel is auto-selected by FW unless overridden by "
- + "force-softap-channel command or '-f <int> <int>' option");
- pw.println(" -f <int> <int> - force exact channel frequency for operation channel");
- pw.println(" Note: -f <int> <int> - must be the last option");
- pw.println(" For example:");
- pw.println(" Use '-f 2412' to enable single Soft Ap on 2412");
- pw.println(" Use '-f 2412 5745' to enable bridged dual Soft Ap on 2412 and 5745");
- pw.println(" -x - Specifies the SSID as hex digits instead of plain text (T and above)");
- pw.println(" -w 20|40|80|160|320 - select the maximum channel bandwidth (MHz)");
- pw.println(" stop-softap");
- pw.println(" Stop softap (hotspot)");
pw.println(" pmksa-flush <networkId>");
pw.println(" - Flush the local PMKSA cache associated with the network id."
+ " Use list-networks to retrieve <networkId> for the network");
@@ -2978,61 +2999,26 @@ public class WifiShellCommand extends BasicShellCommandHandler {
pw.println(" '31' - band 2.4, 5, 6 and 60 GHz with DFS channels");
pw.println(" get-cached-scan-data");
pw.println(" Gets scan data cached by the firmware");
- pw.println(" force-overlay-config-value <overlayName> <configString> enabled|disabled");
- pw.println(" Force overlay to a specified value. See below for supported overlays.");
+ pw.println(" force-overlay-config-value bool|integer <overlayName> enabled|disabled"
+ + "<configValue>");
+ pw.println(" Force overlay to a specified value.");
+ pw.println(" bool|integer - specified the type of the overlay");
pw.println(" <overlayName> - name of the overlay whose value is overridden.");
- pw.println(" - Currently supports:");
- pw.println(" - config_wifi_background_scan_support: accepts boolean "
- + "<configString> = true|false.");
- pw.println(" <configString> - override value of the overlay. See above for accepted "
- + "values per overlay.");
pw.println(" enabled|disabled: enable the override or disable it and revert to using "
+ "the built-in value.");
+ pw.println(" <configValue> - override value of the overlay."
+ + "Must match the overlay type");
+ pw.println(" get-overlay-config-values");
+ pw.println(" Get current overlay value in resource cache.");
+ pw.println(" get-softap-supported-features");
+ pw.println(" Gets softap supported features. Will print 'wifi_softap_acs_supported'");
+ pw.println(" and/or 'wifi_softap_wpa3_sae_supported',");
+ pw.println(" and/or 'wifi_softap_bridged_ap_supported',");
+ pw.println(" and/or 'wifi_softap_bridged_ap_with_sta_supported',");
+ pw.println(" each on a separate line.");
}
private void onHelpPrivileged(PrintWriter pw) {
- pw.println(" connect-network <ssid> open|owe|wpa2|wpa3|wep [<passphrase>] [-x] [-m] "
- + "[-d] [-b <bssid>] [-r auto|none|persistent|non_persistent]");
- pw.println(" Connect to a network with provided params and add to saved networks list");
- pw.println(" <ssid> - SSID of the network");
- pw.println(" open|owe|wpa2|wpa3|wep - Security type of the network.");
- pw.println(" - Use 'open' or 'owe' for networks with no passphrase");
- pw.println(" - 'open' - Open networks (Most prevalent)");
- pw.println(" - 'owe' - Enhanced open networks");
- pw.println(" - Use 'wpa2' or 'wpa3' or 'wep' for networks with passphrase");
- pw.println(" - 'wpa2' - WPA-2 PSK networks (Most prevalent)");
- pw.println(" - 'wpa3' - WPA-3 PSK networks");
- pw.println(" - 'wep' - WEP network. Passphrase should be bytes in hex or encoded"
- + " into String using UTF-8");
- pw.println(" -x - Specifies the SSID as hex digits instead of plain text");
- pw.println(" -m - Mark the network metered.");
- pw.println(" -d - Mark the network autojoin disabled.");
- pw.println(" -h - Mark the network hidden.");
- pw.println(" -p - Mark the network private (not shared).");
- pw.println(" -b <bssid> - Set specific BSSID.");
- pw.println(" -r auto|none|persistent|non_persistent - MAC randomization scheme for the"
- + " network");
- pw.println(" add-network <ssid> open|owe|wpa2|wpa3|wep [<passphrase>] [-x] [-m] [-d] "
- + "[-b <bssid>] [-r auto|none|persistent|non_persistent]");
- pw.println(" Add/update saved network with provided params");
- pw.println(" <ssid> - SSID of the network");
- pw.println(" open|owe|wpa2|wpa3|wep - Security type of the network.");
- pw.println(" - Use 'open' or 'owe' for networks with no passphrase");
- pw.println(" - 'open' - Open networks (Most prevalent)");
- pw.println(" - 'owe' - Enhanced open networks");
- pw.println(" - Use 'wpa2' or 'wpa3' for networks with passphrase");
- pw.println(" - 'wpa2' - WPA-2 PSK networks (Most prevalent)");
- pw.println(" - 'wpa3' - WPA-3 PSK networks");
- pw.println(" - 'wep' - WEP network. Passphrase should be bytes in hex or encoded"
- + " into String using UTF-8");
- pw.println(" -x - Specifies the SSID as hex digits instead of plain text");
- pw.println(" -m - Mark the network metered.");
- pw.println(" -d - Mark the network autojoin disabled.");
- pw.println(" -h - Mark the network hidden.");
- pw.println(" -p - Mark the network private (not shared).");
- pw.println(" -b <bssid> - Set specific BSSID.");
- pw.println(" -r auto|none|persistent|non_persistent - MAC randomization scheme for the"
- + " network");
pw.println(" set-poll-rssi-interval-msecs <int>");
pw.println(" Sets the interval between RSSI polls to <int> milliseconds.");
pw.println(" get-poll-rssi-interval-msecs");
@@ -3057,6 +3043,45 @@ public class WifiShellCommand extends BasicShellCommandHandler {
pw.println(" Clears the user disabled networks list.");
pw.println(" send-link-probe");
pw.println(" Manually triggers a link probe.");
+ pw.println(
+ " start-softap <ssid> (open|wpa2|wpa3|wpa3_transition|owe|owe_transition)"
+ + " <passphrase> [-b 2|5|6|any|bridged|bridged_2_5|bridged_2_6|bridged_5_6]"
+ + " [-x] [-w 20|40|80|160|320] [-f <int> [<int>]]");
+ pw.println(" Start softap with provided params");
+ pw.println(" Note that the shell command doesn't activate internet tethering. In some "
+ + "devices, internet sharing is possible when Wi-Fi STA is also enabled and is"
+ + "associated to another AP with internet access.");
+ pw.println(" <ssid> - SSID of the network");
+ pw.println(" open|wpa2|wpa3|wpa3_transition|owe|owe_transition - Security type of the "
+ + "network.");
+ pw.println(" - Use 'open', 'owe', 'owe_transition' for networks with no passphrase");
+ pw.println(" - Use 'wpa2', 'wpa3', 'wpa3_transition' for networks with passphrase");
+ pw.println(" -b 2|5|6|any|bridged|bridged_2_5|bridged_2_6|bridged_5_6 - select the"
+ + " preferred bands.");
+ pw.println(" - Use '2' to select 2.4GHz band as the preferred band");
+ pw.println(" - Use '5' to select 5GHz band as the preferred band");
+ pw.println(" - Use '6' to select 6GHz band as the preferred band");
+ pw.println(" - Use 'any' to indicate no band preference");
+ pw.println(" - Use 'bridged' to indicate bridged AP which enables APs on both "
+ + "2.4G + 5G");
+ pw.println(" - Use 'bridged_2_5' to indicate bridged AP which enables APs on both "
+ + "2.4G + 5G");
+ pw.println(" - Use 'bridged_2_6' to indicate bridged AP which enables APs on both "
+ + "2.4G + 6G");
+ pw.println(" - Use 'bridged_5_6' to indicate bridged AP which enables APs on both "
+ + "5G + 6G");
+ pw.println(" Note: If the band option is not provided, 2.4GHz is the preferred band.");
+ pw.println(" The exact channel is auto-selected by FW unless overridden by "
+ + "force-softap-channel command or '-f <int> <int>' option");
+ pw.println(" -f <int> <int> - force exact channel frequency for operation channel");
+ pw.println(" Note: -f <int> <int> - must be the last option");
+ pw.println(" For example:");
+ pw.println(" Use '-f 2412' to enable single Soft Ap on 2412");
+ pw.println(" Use '-f 2412 5745' to enable bridged dual Soft Ap on 2412 and 5745");
+ pw.println(" -x - Specifies the SSID as hex digits instead of plain text (T and above)");
+ pw.println(" -w 20|40|80|160|320 - select the maximum channel bandwidth (MHz)");
+ pw.println(" stop-softap");
+ pw.println(" Stop softap (hotspot)");
pw.println(" force-softap-band enabled <int> | disabled");
pw.println(" Forces soft AP band to 2|5|6");
pw.println(" force-softap-channel enabled <int> | disabled [-w <maxBandwidth>]");
@@ -3072,12 +3097,6 @@ public class WifiShellCommand extends BasicShellCommandHandler {
pw.println(" Sets whether wifi watchdog should trigger recovery");
pw.println(" get-wifi-watchdog");
pw.println(" Gets setting of wifi watchdog trigger recovery.");
- pw.println(" get-softap-supported-features");
- pw.println(" Gets softap supported features. Will print 'wifi_softap_acs_supported'");
- pw.println(" and/or 'wifi_softap_wpa3_sae_supported',");
- pw.println(" and/or 'wifi_softap_bridged_ap_supported',");
- pw.println(" and/or 'wifi_softap_bridged_ap_with_sta_supported',");
- pw.println(" each on a separate line.");
pw.println(" settings-reset");
pw.println(" Initiates wifi settings reset");
pw.println(" allow-root-to-get-local-only-cmm enabled|disabled");
diff --git a/service/java/com/android/server/wifi/WifiThreadRunner.java b/service/java/com/android/server/wifi/WifiThreadRunner.java
index c3210de5c9..859d96d078 100644
--- a/service/java/com/android/server/wifi/WifiThreadRunner.java
+++ b/service/java/com/android/server/wifi/WifiThreadRunner.java
@@ -16,13 +16,18 @@
package com.android.server.wifi;
+import static com.android.server.wifi.RunnerHandler.KEY_SIGNATURE;
+
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.os.Handler;
import android.os.Looper;
+import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
+import androidx.annotation.Keep;
+
import com.android.internal.annotations.VisibleForTesting;
import com.android.server.wifi.util.GeneralUtil.Mutable;
@@ -37,6 +42,7 @@ import javax.annotation.concurrent.ThreadSafe;
* their corresponding main thread for servicing incoming AIDL calls.
*/
@ThreadSafe
+@Keep
public class WifiThreadRunner {
private static final String TAG = "WifiThreadRunner";
@@ -76,11 +82,11 @@ public class WifiThreadRunner {
* handling nulls.
*/
@Nullable
- public <T> T call(@NonNull Supplier<T> supplier, T valueToReturnOnTimeout) {
+ public <T> T call(@NonNull Supplier<T> supplier, T valueToReturnOnTimeout, String taskName) {
Mutable<T> result = new Mutable<>();
boolean runWithScissorsSuccess = runWithScissors(mHandler,
() -> result.value = supplier.get(),
- RUN_WITH_SCISSORS_TIMEOUT_MILLIS, false);
+ RUN_WITH_SCISSORS_TIMEOUT_MILLIS, false, taskName);
if (runWithScissorsSuccess) {
return result.value;
} else {
@@ -99,6 +105,13 @@ public class WifiThreadRunner {
}
/**
+ * TODO(b/342976570): remove when we are sure no more usage
+ */
+ public <T> T call(@NonNull Supplier<T> supplier, T valueToReturnOnTimeout) {
+ return call(supplier, valueToReturnOnTimeout, null);
+ }
+
+ /**
* Runs a Runnable on the main Wifi thread and <b>blocks</b> the calling thread until the
* Runnable completes execution on the main Wifi thread.
*
@@ -106,9 +119,10 @@ public class WifiThreadRunner {
*
* @return true if the runnable executed successfully, false otherwise
*/
- public boolean run(@NonNull Runnable runnable) {
+ public boolean run(@NonNull Runnable runnable, String taskName) {
boolean runWithScissorsSuccess =
- runWithScissors(mHandler, runnable, RUN_WITH_SCISSORS_TIMEOUT_MILLIS, false);
+ runWithScissors(mHandler, runnable, RUN_WITH_SCISSORS_TIMEOUT_MILLIS, false,
+ taskName);
if (runWithScissorsSuccess) {
return true;
} else {
@@ -122,6 +136,13 @@ public class WifiThreadRunner {
}
/**
+ * TODO(b/342976570): remove when we are sure no more usage
+ */
+ public boolean run(@NonNull Runnable runnable) {
+ return run(runnable, null);
+ }
+
+ /**
* Runs a Runnable on the main Wifi thread on the next iteration and <b>blocks</b> the calling
* thread until the Runnable completes execution on the main Wifi thread.
*
@@ -129,9 +150,10 @@ public class WifiThreadRunner {
*
* @return true if the runnable executed successfully, false otherwise
*/
- public boolean runAtFront(@NonNull Runnable runnable) {
+ public boolean runAtFront(@NonNull Runnable runnable, String taskName) {
boolean runWithScissorsSuccess =
- runWithScissors(mHandler, runnable, RUN_WITH_SCISSORS_TIMEOUT_MILLIS, true);
+ runWithScissors(mHandler, runnable, RUN_WITH_SCISSORS_TIMEOUT_MILLIS, true,
+ taskName);
if (runWithScissorsSuccess) {
return true;
} else {
@@ -176,26 +198,39 @@ public class WifiThreadRunner {
}
/**
- * Asynchronously runs a Runnable on the main Wifi thread.
- *
+ * Asynchronously runs a Runnable on the main Wifi thread. With specified task name for metrics
+ * logging
* @return true if the runnable was successfully posted <b>(not executed)</b> to the main Wifi
* thread, false otherwise
+ * @param runnable The Runnable that will be executed.
+ * @param taskName The task name for performance logging
+ */
+ public boolean post(@NonNull Runnable runnable, @Nullable String taskName) {
+ Message m = Message.obtain(mHandler, runnable);
+ m.getData().putString(KEY_SIGNATURE, taskName);
+ return mHandler.sendMessage(m);
+ }
+
+ /**
+ * TODO(b/342976570): remove when we are sure no more usage
*/
public boolean post(@NonNull Runnable runnable) {
- return mHandler.post(runnable);
+ return post(runnable, null);
}
/**
* Asynchronously runs a Runnable on the main Wifi thread with delay.
*
- * @param runnable The Runnable that will be executed.
+ * @param runnable The Runnable that will be executed.
* @param delayMillis The delay (in milliseconds) until the Runnable
- * will be executed.
+ * will be executed.
* @return true if the runnable was successfully posted <b>(not executed)</b> to the main Wifi
* thread, false otherwise
*/
- public boolean postDelayed(@NonNull Runnable runnable, long delayMillis) {
- return mHandler.postDelayed(runnable, delayMillis);
+ public boolean postDelayed(@NonNull Runnable runnable, long delayMillis, String taskName) {
+ Message m = Message.obtain(mHandler, runnable);
+ m.getData().putString(KEY_SIGNATURE, taskName);
+ return mHandler.sendMessageDelayed(m, delayMillis);
}
/**
@@ -255,20 +290,18 @@ public class WifiThreadRunner {
* (TODO: We should fix this by making MessageQueue aware of blocking runnables.)
* </p>
*
- * @param r The Runnable that will be executed synchronously.
+ * @param r The Runnable that will be executed synchronously.
* @param timeout The timeout in milliseconds, or 0 to wait indefinitely.
* @param atFront Message needs to be posted at the front of the queue or not.
- *
* @return Returns true if the Runnable was successfully executed.
- * Returns false on failure, usually because the
- * looper processing the message queue is exiting.
- *
+ * Returns false on failure, usually because the
+ * looper processing the message queue is exiting.
* @hide This method is prone to abuse and should probably not be in the API.
* If we ever do make it part of the API, we might want to rename it to something
* less funny like runUnsafe().
*/
private boolean runWithScissors(@NonNull Handler handler, @NonNull Runnable r,
- long timeout, boolean atFront) {
+ long timeout, boolean atFront, String taskName) {
if (r == null) {
throw new IllegalArgumentException("runnable must not be null");
}
@@ -287,7 +320,7 @@ public class WifiThreadRunner {
}
BlockingRunnable br = new BlockingRunnable(r);
- return br.postAndWait(handler, timeout, atFront);
+ return br.postAndWait(handler, timeout, atFront, taskName);
}
private static final class BlockingRunnable implements Runnable {
@@ -310,13 +343,16 @@ public class WifiThreadRunner {
}
}
- public boolean postAndWait(Handler handler, long timeout, boolean atFront) {
+ public boolean postAndWait(Handler handler, long timeout, boolean atFront,
+ String taskName) {
+ Message m = Message.obtain(handler, this);
+ m.getData().putString(KEY_SIGNATURE, taskName);
if (atFront) {
- if (!handler.postAtFrontOfQueue(this)) {
+ if (!handler.sendMessageAtFrontOfQueue(m)) {
return false;
}
} else {
- if (!handler.post(this)) {
+ if (!handler.sendMessage(m)) {
return false;
}
}
diff --git a/service/java/com/android/server/wifi/WifiVendorHal.java b/service/java/com/android/server/wifi/WifiVendorHal.java
index 9e50b0b1d4..d8714ff6e3 100644
--- a/service/java/com/android/server/wifi/WifiVendorHal.java
+++ b/service/java/com/android/server/wifi/WifiVendorHal.java
@@ -2162,4 +2162,17 @@ public class WifiVendorHal {
return wifiStaIface.getStatsTwtSession(cmdId, sessionId);
}
}
+
+ /**
+ * Sets the wifi VoIP mode.
+ *
+ * @param mode Voip mode as defined by the enum |WifiVoipMode|
+ * @return true if successful, false otherwise.
+ */
+ public boolean setVoipMode(@WifiChip.WifiVoipMode int mode) {
+ synchronized (sLock) {
+ if (mWifiChip == null) return false;
+ return mWifiChip.setVoipMode(mode);
+ }
+ }
}
diff --git a/service/java/com/android/server/wifi/WifiVoipDetector.java b/service/java/com/android/server/wifi/WifiVoipDetector.java
new file mode 100644
index 0000000000..5754bc3ef8
--- /dev/null
+++ b/service/java/com/android/server/wifi/WifiVoipDetector.java
@@ -0,0 +1,253 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi;
+
+import static android.media.AudioManager.MODE_COMMUNICATION_REDIRECT;
+import static android.media.AudioManager.MODE_IN_COMMUNICATION;
+
+import android.annotation.NonNull;
+import android.content.Context;
+import android.media.AudioManager;
+import android.os.Build;
+import android.os.Handler;
+import android.telephony.CallAttributes;
+import android.telephony.TelephonyCallback;
+import android.telephony.TelephonyManager;
+import android.util.LocalLog;
+import android.util.Log;
+
+import androidx.annotation.RequiresApi;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.modules.utils.HandlerExecutor;
+import com.android.server.wifi.hal.WifiChip;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Class used to detect Wi-Fi VoIP call status
+ */
+@RequiresApi(Build.VERSION_CODES.VANILLA_ICE_CREAM)
+public class WifiVoipDetector {
+ private static final String TAG = "WifiVoipDetector";
+
+ private final Context mContext;
+ private final Handler mHandler;
+ private final HandlerExecutor mHandlerExecutor;
+ private final WifiInjector mWifiInjector;
+ private final LocalLog mLocalLog;
+
+ private final WifiCarrierInfoManager mWifiCarrierInfoManager;
+
+ private AudioManager mAudioManager;
+ private TelephonyManager mTelephonyManager;
+
+ private WifiCallingStateListener mWifiCallingStateListener;
+ private AudioModeListener mAudioModeListener;
+
+ private int mCurrentMode = WifiChip.WIFI_VOIP_MODE_OFF;
+ private boolean mIsMonitoring = false;
+ private boolean mIsWifiConnected = false;
+ private boolean mIsOTTCallOn = false;
+ private boolean mIsVoWifiOn = false;
+ private boolean mVerboseLoggingEnabled = false;
+
+ private Map<String, Boolean> mConnectedWifiIfaceMap = new HashMap<>();
+
+ public WifiVoipDetector(@NonNull Context context, @NonNull Handler handler,
+ @NonNull WifiInjector wifiInjector,
+ @NonNull WifiCarrierInfoManager wifiCarrierInfoManager) {
+ mContext = context;
+ mHandler = handler;
+ mHandlerExecutor = new HandlerExecutor(mHandler);
+ mWifiInjector = wifiInjector;
+ mWifiCarrierInfoManager = wifiCarrierInfoManager;
+ mLocalLog = new LocalLog(32);
+ }
+
+ /**
+ * Enable verbose logging for WifiConnectivityManager.
+ */
+ public void enableVerboseLogging(boolean verbose) {
+ mVerboseLoggingEnabled = verbose;
+ }
+
+ @VisibleForTesting
+ public class WifiCallingStateListener extends TelephonyCallback
+ implements TelephonyCallback.CallAttributesListener {
+
+ @Override
+ public void onCallAttributesChanged(@NonNull CallAttributes callAttributes) {
+ boolean isVoWifion = callAttributes.getNetworkType()
+ == TelephonyManager.NETWORK_TYPE_IWLAN;
+ if (isVoWifion == mIsVoWifiOn) {
+ return;
+ }
+ mIsVoWifiOn = isVoWifion;
+ String log = (mIsVoWifiOn ? "Enter" : "Leave") + " IWLAN Call";
+ mLocalLog.log(log);
+ if (mVerboseLoggingEnabled) {
+ Log.d(TAG, log);
+ }
+ executeWifiVoIPOptimization();
+ }
+ }
+
+ @VisibleForTesting
+ public class AudioModeListener implements AudioManager.OnModeChangedListener {
+ @Override
+ public void onModeChanged(int audioMode) {
+ boolean isOTTCallOn = audioMode == MODE_IN_COMMUNICATION
+ || audioMode == MODE_COMMUNICATION_REDIRECT;
+ if (isOTTCallOn == mIsOTTCallOn) {
+ return;
+ }
+ mIsOTTCallOn = isOTTCallOn;
+ String log = "Audio mode (" + (mIsOTTCallOn ? "Enter" : "Leave")
+ + " OTT) onModeChanged to " + audioMode;
+ mLocalLog.log(log);
+ if (mVerboseLoggingEnabled) {
+ Log.d(TAG, log);
+ }
+ executeWifiVoIPOptimization();
+ }
+ }
+
+ /**
+ * Notify wifi is connected or not to start monitoring the VoIP status.
+ *
+ * @param isConnected whether or not wif is connected.
+ * @param isPrimary the connected client mode is primary or not
+ * @param ifaceName the interface name of connected client momde
+ */
+ public void notifyWifiConnected(boolean isConnected, boolean isPrimary, String ifaceName) {
+ if (isConnected) {
+ mConnectedWifiIfaceMap.put(ifaceName, isPrimary);
+ if (isPrimary) {
+ mIsWifiConnected = true;
+ }
+ } else {
+ Boolean isPrimaryBefore = mConnectedWifiIfaceMap.remove(ifaceName);
+ if (mConnectedWifiIfaceMap.size() > 0) {
+ if (isPrimaryBefore != null && isPrimaryBefore.booleanValue()) {
+ if (isPrimary) {
+ // Primary client mode is disconnected.
+ mIsWifiConnected = false;
+ } else {
+ // Previous primary was changed to secondary && there is another client mode
+ // which will be primary mode. (MBB use case).
+ return;
+ }
+ }
+ } else {
+ // No any client mode is connected.
+ mIsWifiConnected = false;
+ }
+ }
+ if (mIsWifiConnected) {
+ startMonitoring();
+ } else {
+ stopMonitoring();
+ }
+ }
+
+ private boolean isWifiVoipOn() {
+ return (mIsWifiConnected && mIsOTTCallOn) || mIsVoWifiOn;
+ }
+
+ private void executeWifiVoIPOptimization() {
+ final boolean wifiVipOn = isWifiVoipOn();
+ int newMode = wifiVipOn ? WifiChip.WIFI_VOIP_MODE_VOICE : WifiChip.WIFI_VOIP_MODE_OFF;
+ if (mCurrentMode != newMode) {
+ String log = "Update voip over wifi to new mode: " + newMode;
+ if (!mWifiInjector.getWifiNative().setVoipMode(newMode)) {
+ log = "Failed to set Voip Mode to " + newMode + " (maybe not supported?)";
+ } else {
+ mCurrentMode = newMode;
+ }
+ mLocalLog.log(log);
+ if (mVerboseLoggingEnabled) {
+ Log.d(TAG, log);
+ }
+ }
+ }
+
+ private void startMonitoring() {
+ if (mIsMonitoring) {
+ return;
+ }
+ mIsMonitoring = true;
+ if (mAudioManager == null) {
+ mAudioManager = mContext.getSystemService(AudioManager.class);
+ }
+ if (mTelephonyManager == null) {
+ mTelephonyManager = mWifiInjector.makeTelephonyManager();
+ }
+ if (mWifiCallingStateListener == null) {
+ mWifiCallingStateListener = new WifiCallingStateListener();
+ }
+ if (mAudioModeListener == null) {
+ mAudioModeListener = new AudioModeListener();
+ }
+ if (mTelephonyManager != null) {
+ mIsVoWifiOn = mWifiCarrierInfoManager.isWifiCallingAvailable();
+ mTelephonyManager.registerTelephonyCallback(
+ mHandlerExecutor, mWifiCallingStateListener);
+ }
+ if (mAudioManager != null) {
+ int audioMode = mAudioManager.getMode();
+ mIsOTTCallOn = audioMode == MODE_IN_COMMUNICATION
+ || audioMode == MODE_COMMUNICATION_REDIRECT;
+ mAudioManager.addOnModeChangedListener(mHandlerExecutor, mAudioModeListener);
+ }
+ executeWifiVoIPOptimization();
+ }
+
+ private void stopMonitoring() {
+ if (!mIsMonitoring) {
+ return;
+ }
+ mIsMonitoring = false;
+ if (mAudioModeListener != null) {
+ mAudioManager.removeOnModeChangedListener(mAudioModeListener);
+ }
+ if (mWifiCallingStateListener != null) {
+ mTelephonyManager.unregisterTelephonyCallback(mWifiCallingStateListener);
+ mWifiCallingStateListener = null;
+ }
+ mIsOTTCallOn = false;
+ mIsVoWifiOn = false;
+ mIsWifiConnected = false;
+ executeWifiVoIPOptimization();
+ }
+
+ /**
+ * Dump output for debugging.
+ */
+ public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
+ pw.println("Dump of WifiVoipDetector:");
+ mLocalLog.dump(fd, pw, args);
+ pw.println("mIsMonitoring = " + mIsMonitoring);
+ pw.println("mIsOTTCallOn = " + mIsOTTCallOn);
+ pw.println("mIsVoWifiOn = " + mIsVoWifiOn);
+ pw.println("mIsWifiConnected = " + mIsWifiConnected);
+ pw.println("mCurrentMode = " + mCurrentMode);
+ }
+}
diff --git a/service/java/com/android/server/wifi/WrongPasswordNotifier.java b/service/java/com/android/server/wifi/WrongPasswordNotifier.java
index 21311c851d..56e85a8a07 100644
--- a/service/java/com/android/server/wifi/WrongPasswordNotifier.java
+++ b/service/java/com/android/server/wifi/WrongPasswordNotifier.java
@@ -97,6 +97,7 @@ public class WrongPasswordNotifier {
Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS)
.setPackage(settingsPackage)
.putExtra("wifi_start_connect_ssid", utf8Ssid.toString());
+ intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
CharSequence title = mContext.getString(
com.android.wifi.resources.R.string.wifi_available_title_failed_to_connect);
Notification.Builder builder = mFrameworkFacade.makeNotificationBuilder(mContext,
diff --git a/service/java/com/android/server/wifi/aware/WifiAwareNativeManager.java b/service/java/com/android/server/wifi/aware/WifiAwareNativeManager.java
index 1cdd58ca3d..7cb82f0437 100644
--- a/service/java/com/android/server/wifi/aware/WifiAwareNativeManager.java
+++ b/service/java/com/android/server/wifi/aware/WifiAwareNativeManager.java
@@ -23,7 +23,9 @@ import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
import com.android.server.wifi.HalDeviceManager;
+import com.android.server.wifi.WifiNative;
import com.android.server.wifi.hal.WifiNanIface;
+import com.android.wifi.flags.FeatureFlags;
import java.io.FileDescriptor;
import java.io.PrintWriter;
@@ -40,17 +42,24 @@ public class WifiAwareNativeManager {
private WifiAwareStateManager mWifiAwareStateManager;
private HalDeviceManager mHalDeviceManager;
+ private WifiNative mWifiNative;
private Handler mHandler;
private WifiAwareNativeCallback mWifiAwareNativeCallback;
+ private final FeatureFlags mFeatureFlags;
private WifiNanIface mWifiNanIface = null;
+ private WifiNative.Iface mNanIface;
private InterfaceDestroyedListener mInterfaceDestroyedListener;
private int mReferenceCount = 0;
WifiAwareNativeManager(WifiAwareStateManager awareStateManager,
HalDeviceManager halDeviceManager,
- WifiAwareNativeCallback wifiAwareNativeCallback) {
+ WifiAwareNativeCallback wifiAwareNativeCallback,
+ WifiNative wifiNative,
+ FeatureFlags featureFlags) {
mWifiAwareStateManager = awareStateManager;
mHalDeviceManager = halDeviceManager;
+ mWifiNative = wifiNative;
+ mFeatureFlags = featureFlags;
mWifiAwareNativeCallback = wifiAwareNativeCallback;
}
@@ -82,7 +91,7 @@ public class WifiAwareNativeManager {
if (mHalDeviceManager.isStarted()) {
mWifiAwareStateManager.tryToGetAwareCapability();
} else {
- awareIsDown(false);
+ awareIsDown(mWifiAwareStateManager.isD2dAllowedWhenStaDisabled());
}
}
}, mHandler);
@@ -118,25 +127,27 @@ public class WifiAwareNativeManager {
}
if (mHalDeviceManager == null) {
Log.e(TAG, "tryToGetAware: mHalDeviceManager is null!?");
- awareIsDown(false);
+ awareIsDown(mWifiAwareStateManager.isD2dAllowedWhenStaDisabled());
return;
}
mInterfaceDestroyedListener = new InterfaceDestroyedListener();
- WifiNanIface iface = mHalDeviceManager.createNanIface(mInterfaceDestroyedListener,
+ mNanIface = mWifiNative.createNanIface(mInterfaceDestroyedListener,
mHandler, requestorWs);
- if (iface == null) {
+ if (mNanIface != null) {
+ mWifiNanIface = (WifiNanIface) mNanIface.iface;
+ }
+ if (mWifiNanIface == null) {
Log.e(TAG, "Was not able to obtain a WifiNanIface (even though enabled!?)");
awareIsDown(true);
} else {
if (mVerboseLoggingEnabled) Log.v(TAG, "Obtained a WifiNanIface");
- if (!iface.registerFrameworkCallback(mWifiAwareNativeCallback)) {
+ if (!mWifiNanIface.registerFrameworkCallback(mWifiAwareNativeCallback)) {
Log.e(TAG, "Unable to register callback with WifiNanIface");
- mHalDeviceManager.removeIface(iface);
- awareIsDown(false);
+ mHalDeviceManager.removeIface(mWifiNanIface);
+ awareIsDown(mWifiAwareStateManager.isD2dAllowedWhenStaDisabled());
return;
}
- mWifiNanIface = iface;
mReferenceCount = 1;
mWifiNanIface.enableVerboseLogging(mVerboseLoggingEnabled);
}
@@ -168,6 +179,13 @@ public class WifiAwareNativeManager {
mInterfaceDestroyedListener.active = false;
mInterfaceDestroyedListener = null;
mHalDeviceManager.removeIface(mWifiNanIface);
+ if (mNanIface != null) {
+ final int nanIfaceId = mNanIface.id;
+ // HAL may be stop when Nan is toredown,
+ // clean mNanIface first to avoid infinite loop in clean up
+ mNanIface = null;
+ mWifiNative.teardownNanIface(nanIfaceId);
+ }
mWifiNanIface = null;
mWifiAwareNativeCallback.resetChannelInfo();
}
@@ -188,7 +206,7 @@ public class WifiAwareNativeManager {
}
if (mHalDeviceManager == null) {
Log.e(TAG, "tryToGetAware: mHalDeviceManager is null!?");
- awareIsDown(false);
+ awareIsDown(mWifiAwareStateManager.isD2dAllowedWhenStaDisabled());
return false;
}
@@ -202,6 +220,13 @@ public class WifiAwareNativeManager {
Log.d(TAG, "awareIsDown: mWifiNanIface=" + mWifiNanIface
+ ", mReferenceCount =" + mReferenceCount);
}
+ if (mNanIface != null) {
+ final int nanIfaceId = mNanIface.id;
+ // HAL may be stop when Nan is toredown,
+ // clean mNanIface first to avoid infinite loop in clean up
+ mNanIface = null;
+ mWifiNative.teardownNanIface(nanIfaceId);
+ }
mWifiNanIface = null;
mReferenceCount = 0;
mWifiAwareStateManager.disableUsage(markAsAvailable);
diff --git a/service/java/com/android/server/wifi/aware/WifiAwareService.java b/service/java/com/android/server/wifi/aware/WifiAwareService.java
index 9ad3320bfb..5a2f65ce48 100644
--- a/service/java/com/android/server/wifi/aware/WifiAwareService.java
+++ b/service/java/com/android/server/wifi/aware/WifiAwareService.java
@@ -24,6 +24,8 @@ import android.util.Log;
import com.android.server.SystemService;
import com.android.server.wifi.HalDeviceManager;
import com.android.server.wifi.WifiInjector;
+import com.android.server.wifi.WifiNative;
+import com.android.wifi.flags.FeatureFlags;
/**
* Service implementing Wi-Fi Aware functionality. Delegates actual interface
@@ -54,13 +56,16 @@ public final class WifiAwareService extends SystemService {
}
HalDeviceManager halDeviceManager = wifiInjector.getHalDeviceManager();
+ WifiNative wifiNative = wifiInjector.getWifiNative();
+ FeatureFlags featureFlags = wifiInjector.getDeviceConfigFacade().getFeatureFlags();
WifiAwareStateManager wifiAwareStateManager = new WifiAwareStateManager(wifiInjector,
new PairingConfigManager());
WifiAwareNativeCallback wifiAwareNativeCallback = new WifiAwareNativeCallback(
wifiAwareStateManager);
WifiAwareNativeManager wifiAwareNativeManager = new WifiAwareNativeManager(
- wifiAwareStateManager, halDeviceManager, wifiAwareNativeCallback);
+ wifiAwareStateManager, halDeviceManager, wifiAwareNativeCallback,
+ wifiNative, featureFlags);
WifiAwareNativeApi wifiAwareNativeApi = new WifiAwareNativeApi(wifiAwareNativeManager);
wifiAwareStateManager.setNative(wifiAwareNativeManager, wifiAwareNativeApi);
WifiAwareShellCommand wifiAwareShellCommand = new WifiAwareShellCommand();
@@ -68,7 +73,7 @@ public final class WifiAwareService extends SystemService {
wifiAwareShellCommand.register("native_cb", wifiAwareNativeCallback);
wifiAwareShellCommand.register("state_mgr", wifiAwareStateManager);
- HandlerThread awareHandlerThread = wifiInjector.getWifiAwareHandlerThread();
+ HandlerThread awareHandlerThread = wifiInjector.getWifiHandlerThread();
mImpl.start(awareHandlerThread, wifiAwareStateManager, wifiAwareShellCommand,
wifiInjector.getWifiMetrics().getWifiAwareMetrics(),
wifiInjector.getWifiPermissionsUtil(),
diff --git a/service/java/com/android/server/wifi/aware/WifiAwareServiceImpl.java b/service/java/com/android/server/wifi/aware/WifiAwareServiceImpl.java
index 8d0e2ce51a..468b8b84b8 100644
--- a/service/java/com/android/server/wifi/aware/WifiAwareServiceImpl.java
+++ b/service/java/com/android/server/wifi/aware/WifiAwareServiceImpl.java
@@ -198,7 +198,8 @@ public class WifiAwareServiceImpl extends IWifiAwareManager.Stub {
public AwareResources getAvailableAwareResources() {
enforceAccessPermission();
return new WifiThreadRunner(mHandler)
- .call(() -> mStateManager.getAvailableAwareResources(), null);
+ .call(() -> mStateManager.getAvailableAwareResources(), null,
+ TAG + "#getAvailableAwareResources");
}
@Override
diff --git a/service/java/com/android/server/wifi/aware/WifiAwareStateManager.java b/service/java/com/android/server/wifi/aware/WifiAwareStateManager.java
index 14a60547a1..a4fd8ad693 100644
--- a/service/java/com/android/server/wifi/aware/WifiAwareStateManager.java
+++ b/service/java/com/android/server/wifi/aware/WifiAwareStateManager.java
@@ -27,6 +27,7 @@ import static android.net.wifi.aware.WifiAwareManager.WIFI_AWARE_SUSPEND_INTERNA
import static android.net.wifi.aware.WifiAwareManager.WIFI_AWARE_SUSPEND_INVALID_SESSION;
import static android.net.wifi.aware.WifiAwareManager.WIFI_AWARE_SUSPEND_REDUNDANT_REQUEST;
+import static com.android.server.wifi.WifiSettingsConfigStore.D2D_ALLOWED_WHEN_INFRA_STA_DISABLED;
import static com.android.server.wifi.aware.WifiAwareMetrics.convertNanStatusCodeToWifiStatsLogEnum;
import static com.android.server.wifi.hal.WifiNanIface.NanStatusCode.NOT_SUPPORTED;
import static com.android.server.wifi.hal.WifiNanIface.NanStatusCode.NO_CONNECTION;
@@ -117,7 +118,9 @@ import com.android.server.wifi.Clock;
import com.android.server.wifi.HalDeviceManager;
import com.android.server.wifi.InterfaceConflictManager;
import com.android.server.wifi.RunnerState;
+import com.android.server.wifi.WifiGlobals;
import com.android.server.wifi.WifiInjector;
+import com.android.server.wifi.WifiSettingsConfigStore;
import com.android.server.wifi.aware.PairingConfigManager.PairingSecurityAssociationInfo;
import com.android.server.wifi.hal.WifiNanIface.NanStatusCode;
import com.android.server.wifi.proto.WifiStatsLog;
@@ -125,6 +128,7 @@ import com.android.server.wifi.util.NetdWrapper;
import com.android.server.wifi.util.WaitingState;
import com.android.server.wifi.util.WifiPermissionsUtil;
import com.android.server.wifi.util.WifiPermissionsWrapper;
+import com.android.wifi.flags.FeatureFlags;
import com.android.wifi.resources.R;
import org.json.JSONException;
@@ -374,6 +378,9 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
private Handler mHandler;
private final WifiInjector mWifiInjector;
private final PairingConfigManager mPairingConfigManager;
+ private final WifiSettingsConfigStore mSettingsConfigStore;
+ private final WifiGlobals mWifiGlobals;
+ private final FeatureFlags mFeatureFlags;
private final SparseArray<WifiAwareClientState> mClients = new SparseArray<>();
private ConfigRequest mCurrentAwareConfiguration = null;
@@ -437,6 +444,9 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
PairingConfigManager pairingConfigManager) {
mWifiInjector = wifiInjector;
mPairingConfigManager = pairingConfigManager;
+ mWifiGlobals = mWifiInjector.getWifiGlobals();
+ mFeatureFlags = mWifiInjector.getDeviceConfigFacade().getFeatureFlags();
+ mSettingsConfigStore = mWifiInjector.getSettingsConfigStore();
onReset();
}
@@ -575,7 +585,8 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
List<WifiAvailableChannel> channels = mWifiInjector.getWifiThreadRunner().call(
() -> mWifiInjector.getWifiNative().getUsableChannels(band,
OP_MODE_WIFI_AWARE,
- WifiAvailableChannel.FILTER_NAN_INSTANT_MODE), null);
+ WifiAvailableChannel.FILTER_NAN_INSTANT_MODE), null,
+ TAG + "#get_instant_communication_channel");
StringBuilder out = new StringBuilder();
for (WifiAvailableChannel channel : channels) {
out.append(channel.toString());
@@ -682,7 +693,13 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
mPowerManager = mContext.getSystemService(PowerManager.class);
mWifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
+ }
+ /**
+ * Initialize the late-initialization sub-services: depend on other services already existing.
+ */
+ public void startLate() {
+ delayedInitialization();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON);
intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
@@ -727,7 +744,7 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
if (mVerboseLoggingEnabled) {
Log.v(TAG, "onReceive: MODE_CHANGED_ACTION: intent=" + intent);
}
- if (wifiPermissionsUtil.isLocationModeEnabled()) {
+ if (mWifiPermissionsUtil.isLocationModeEnabled()) {
enableUsage();
} else {
if (SdkLevel.isAtLeastT()) {
@@ -753,19 +770,41 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
}
boolean isEnabled =
intent.getIntExtra(
- WifiManager.EXTRA_WIFI_STATE,
- WifiManager.WIFI_STATE_UNKNOWN)
+ WifiManager.EXTRA_WIFI_STATE,
+ WifiManager.WIFI_STATE_UNKNOWN)
== WifiManager.WIFI_STATE_ENABLED;
if (isEnabled) {
enableUsage();
} else {
- disableUsage(false);
+ if (!isD2dAllowedWhenStaDisabled()) {
+ disableUsage(false);
+ }
}
}
},
intentFilter,
null,
mHandler);
+ mSettingsConfigStore.registerChangeListener(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED,
+ (key, value) -> {
+ // Check setting & wifi enabled status only when feature is supported.
+ if (mWifiGlobals.isD2dSupportedWhenInfraStaDisabled()) {
+ if (mSettingsConfigStore.get(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED)) {
+ enableUsage();
+ } else if (mWifiManager.getWifiState()
+ != WifiManager.WIFI_STATE_ENABLED) {
+ disableUsage(false);
+ }
+ }
+ }, mHandler);
+ if (isD2dAllowedWhenStaDisabled()) {
+ enableUsage();
+ }
+ }
+
+ public boolean isD2dAllowedWhenStaDisabled() {
+ return mWifiGlobals.isD2dSupportedWhenInfraStaDisabled()
+ && mSettingsConfigStore.get(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED);
}
private class CountryCodeChangeCallback implements
@@ -784,13 +823,6 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
}
/**
- * Initialize the late-initialization sub-services: depend on other services already existing.
- */
- public void startLate() {
- delayedInitialization();
- }
-
- /**
* Try to get capability if it is null.
*/
public void tryToGetAwareCapability() {
@@ -1432,10 +1464,13 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
return;
}
if (mWifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
- if (mVerboseLoggingEnabled) {
- Log.d(TAG, "enableUsage(): while Wi-Fi is disabled - ignoring");
+ if (!isD2dAllowedWhenStaDisabled()) {
+ if (mVerboseLoggingEnabled) {
+ Log.d(TAG, "enableUsage(): while Wi-Fi is disabled"
+ + " & D2D isn't allowed - ignoring");
+ }
+ return;
}
- return;
}
Message msg = mSm.obtainMessage(MESSAGE_TYPE_COMMAND);
msg.arg1 = COMMAND_TYPE_ENABLE_USAGE;
@@ -2342,6 +2377,31 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
};
}
+ private String messageToString(Message msg) {
+ StringBuilder sb = new StringBuilder();
+
+ String s = getWhatToString(msg.what);
+ if (s == null) {
+ s = "<unknown>";
+ }
+ sb.append(s).append("/");
+
+ if (msg.what == MESSAGE_TYPE_NOTIFICATION || msg.what == MESSAGE_TYPE_COMMAND
+ || msg.what == MESSAGE_TYPE_RESPONSE) {
+ s = getWhatToString(msg.arg1);
+ if (s == null) {
+ s = "<unknown>";
+ }
+ sb.append(s);
+ }
+
+ if (msg.what == MESSAGE_TYPE_RESPONSE || msg.what == MESSAGE_TYPE_RESPONSE_TIMEOUT) {
+ sb.append(" (Transaction ID=").append(msg.arg2).append(")");
+ }
+
+ return sb.toString();
+ }
+
public void onAwareDownCleanupSendQueueState() {
mSendQueueBlocked = false;
mHostQueuedSendMessages.clear();
@@ -2355,9 +2415,10 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
}
@Override
- public String getMessageLogRec(int what) {
+ public String getMessageLogRec(Message message) {
return WifiAwareStateManager.class.getSimpleName() + "."
- + DefaultState.class.getSimpleName() + "." + getWhatToString(what);
+ + DefaultState.class.getSimpleName() + "." + getWhatToString(message.what)
+ + "#" + getWhatToString(message.arg1);
}
@Override
@@ -2424,9 +2485,10 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
}
@Override
- public String getMessageLogRec(int what) {
+ public String getMessageLogRec(Message message) {
return WifiAwareStateManager.class.getSimpleName() + "."
- + WaitState.class.getSimpleName() + "." + getWhatToString(what);
+ + WaitState.class.getSimpleName() + "." + getWhatToString(message.what)
+ + "#" + getWhatToString(message.arg1);
}
@Override
@@ -2475,9 +2537,10 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
}
@Override
- public String getMessageLogRec(int what) {
+ public String getMessageLogRec(Message message) {
return WifiAwareStateManager.class.getSimpleName() + "."
- + WaitForResponseState.class.getSimpleName() + "." + getWhatToString(what);
+ + WaitForResponseState.class.getSimpleName() + "."
+ + getWhatToString(message.what) + "#" + getWhatToString(message.arg1);
}
@Override
@@ -3659,7 +3722,7 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
@Override
protected String getLogRecString(Message msg) {
- StringBuilder sb = new StringBuilder(WifiAwareStateManager.messageToString(msg));
+ StringBuilder sb = new StringBuilder(messageToString(msg));
if (msg.what == MESSAGE_TYPE_COMMAND
&& mCurrentTransactionId != TRANSACTION_ID_IGNORE) {
@@ -3867,6 +3930,7 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
mCurrentIdentityNotification = false;
mInstantCommModeClientRequest = INSTANT_MODE_DISABLED;
mAwareMetrics.reportAwareInstantModeEnabled(false);
+ mSm.onAwareDownCleanupSendQueueState();
deferDisableAware(true);
return false;
}
@@ -5609,31 +5673,6 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
return instantMode;
}
- private static String messageToString(Message msg) {
- StringBuilder sb = new StringBuilder();
-
- String s = sSmToString.get(msg.what);
- if (s == null) {
- s = "<unknown>";
- }
- sb.append(s).append("/");
-
- if (msg.what == MESSAGE_TYPE_NOTIFICATION || msg.what == MESSAGE_TYPE_COMMAND
- || msg.what == MESSAGE_TYPE_RESPONSE) {
- s = sSmToString.get(msg.arg1);
- if (s == null) {
- s = "<unknown>";
- }
- sb.append(s);
- }
-
- if (msg.what == MESSAGE_TYPE_RESPONSE || msg.what == MESSAGE_TYPE_RESPONSE_TIMEOUT) {
- sb.append(" (Transaction ID=").append(msg.arg2).append(")");
- }
-
- return sb.toString();
- }
-
/**
* Just a proxy to call {@link WifiAwareDataPathStateManager#createAllInterfaces()} for test.
*/
@@ -5696,7 +5735,8 @@ public class WifiAwareStateManager implements WifiAwareShellCommand.DelegatedShe
}
List<WifiAvailableChannel> channels = mWifiInjector.getWifiThreadRunner().call(
() -> mWifiInjector.getWifiNative().getUsableChannels(WifiScanner.WIFI_BAND_5_GHZ,
- OP_MODE_WIFI_AWARE, WifiAvailableChannel.FILTER_NAN_INSTANT_MODE), null);
+ OP_MODE_WIFI_AWARE, WifiAvailableChannel.FILTER_NAN_INSTANT_MODE), null,
+ TAG + "#getAwareInstantCommunicationChannel");
if (channels == null || channels.isEmpty()) {
if (mVerboseLoggingEnabled) {
Log.v(TAG, "No available instant communication mode channel");
diff --git a/service/java/com/android/server/wifi/hal/IWifiChip.java b/service/java/com/android/server/wifi/hal/IWifiChip.java
index cbc8351f13..7e3e7dbfcb 100644
--- a/service/java/com/android/server/wifi/hal/IWifiChip.java
+++ b/service/java/com/android/server/wifi/hal/IWifiChip.java
@@ -470,4 +470,14 @@ public interface IWifiChip {
* @return whether the channel allowance was set successfully.
*/
boolean setAfcChannelAllowance(WifiChip.AfcChannelAllowance afcChannelAllowance);
+
+ /**
+ * Sets the wifi VoIP mode.
+ *
+ * @param mode Voip mode as defined by the enum |WifiVoipMode|
+ * @return true if successful, false otherwise.
+ */
+ default boolean setVoipMode(@WifiChip.WifiVoipMode int mode) {
+ return false;
+ }
}
diff --git a/service/java/com/android/server/wifi/hal/WifiChip.java b/service/java/com/android/server/wifi/hal/WifiChip.java
index f8ff890ae5..19d52b8518 100644
--- a/service/java/com/android/server/wifi/hal/WifiChip.java
+++ b/service/java/com/android/server/wifi/hal/WifiChip.java
@@ -104,6 +104,18 @@ public class WifiChip {
public @interface WifiAntennaMode {}
/**
+ * Supported VoIP mode.
+ */
+ public static final int WIFI_VOIP_MODE_OFF = 0;
+ public static final int WIFI_VOIP_MODE_VOICE = 1;
+ @IntDef(prefix = { "WIFI_VOIP_MODE_" }, value = {
+ WIFI_VOIP_MODE_OFF,
+ WIFI_VOIP_MODE_VOICE,
+ })
+ @Retention(RetentionPolicy.SOURCE)
+ public @interface WifiVoipMode {}
+
+ /**
* Response containing a value and a status code.
*
* @param <T> Type of value that should be returned.
@@ -957,4 +969,12 @@ public class WifiChip {
return validateAndCall("setAfcChannelAllowance", false,
() -> mWifiChip.setAfcChannelAllowance(afcChannelAllowance));
}
+
+ /**
+ * See comments for {@link IWifiChip#setVoipMode(int)}
+ */
+ public boolean setVoipMode(@WifiVoipMode int mode) {
+ return validateAndCall("setVoipMode", false,
+ () -> mWifiChip.setVoipMode(mode));
+ }
}
diff --git a/service/java/com/android/server/wifi/hal/WifiChipAidlImpl.java b/service/java/com/android/server/wifi/hal/WifiChipAidlImpl.java
index 78851bdcec..f9e4ce2232 100644
--- a/service/java/com/android/server/wifi/hal/WifiChipAidlImpl.java
+++ b/service/java/com/android/server/wifi/hal/WifiChipAidlImpl.java
@@ -16,6 +16,11 @@
package com.android.server.wifi.hal;
+import static android.hardware.wifi.WifiChannelWidthInMhz.WIDTH_160;
+import static android.hardware.wifi.WifiChannelWidthInMhz.WIDTH_320;
+import static android.hardware.wifi.WifiChannelWidthInMhz.WIDTH_40;
+import static android.hardware.wifi.WifiChannelWidthInMhz.WIDTH_80;
+import static android.hardware.wifi.WifiChannelWidthInMhz.WIDTH_80P80;
import static android.net.wifi.CoexUnsafeChannel.POWER_CAP_NONE;
import android.annotation.NonNull;
@@ -32,6 +37,7 @@ import android.hardware.wifi.IWifiChip.LatencyMode;
import android.hardware.wifi.IWifiChip.MultiStaUseCase;
import android.hardware.wifi.IWifiChip.TxPowerScenario;
import android.hardware.wifi.IWifiChip.UsableChannelFilter;
+import android.hardware.wifi.IWifiChip.VoipMode;
import android.hardware.wifi.IWifiChipEventCallback;
import android.hardware.wifi.IWifiNanIface;
import android.hardware.wifi.IWifiP2pIface;
@@ -52,6 +58,8 @@ import android.hardware.wifi.WifiStatusCode;
import android.hardware.wifi.WifiUsableChannel;
import android.net.wifi.CoexUnsafeChannel;
import android.net.wifi.OuiKeyedData;
+import android.net.wifi.ScanResult;
+import android.net.wifi.WifiAnnotations;
import android.net.wifi.WifiAvailableChannel;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiScanner;
@@ -83,6 +91,7 @@ public class WifiChipAidlImpl implements IWifiChip {
private final Object mLock = new Object();
private Context mContext;
private SsidTranslator mSsidTranslator;
+ private long mHalFeatureSet;
public WifiChipAidlImpl(@NonNull android.hardware.wifi.IWifiChip chip,
@NonNull Context context, @NonNull SsidTranslator ssidTranslator) {
@@ -401,8 +410,8 @@ public class WifiChipAidlImpl implements IWifiChip {
synchronized (mLock) {
try {
if (!checkIfaceAndLogFailure(methodStr)) return featuresResp;
- long halFeatureSet = mWifiChip.getFeatureSet();
- featuresResp.setValue(halToFrameworkChipFeatureSet(halFeatureSet));
+ mHalFeatureSet = mWifiChip.getFeatureSet();
+ featuresResp.setValue(halToFrameworkChipFeatureSet(mHalFeatureSet));
featuresResp.setStatusCode(WifiHal.WIFI_STATUS_SUCCESS);
} catch (RemoteException e) {
handleRemoteException(e, methodStr);
@@ -688,7 +697,8 @@ public class WifiChipAidlImpl implements IWifiChip {
List<WifiAvailableChannel> frameworkChannels = new ArrayList<>();
for (WifiUsableChannel ch : halChannels) {
frameworkChannels.add(new WifiAvailableChannel(
- ch.channel, halToFrameworkIfaceMode(ch.ifaceModeMask)));
+ ch.channel, halToFrameworkIfaceMode(ch.ifaceModeMask),
+ halToFrameworkChannelWidth(ch.channelBandwidth)));
}
return frameworkChannels;
} catch (RemoteException e) {
@@ -702,6 +712,23 @@ public class WifiChipAidlImpl implements IWifiChip {
}
}
+ private @WifiAnnotations.ChannelWidth int halToFrameworkChannelWidth(int channelBandwidth) {
+ switch(channelBandwidth) {
+ case WIDTH_40:
+ return ScanResult.CHANNEL_WIDTH_40MHZ;
+ case WIDTH_80:
+ return ScanResult.CHANNEL_WIDTH_80MHZ;
+ case WIDTH_160:
+ return ScanResult.CHANNEL_WIDTH_160MHZ;
+ case WIDTH_80P80:
+ return ScanResult.CHANNEL_WIDTH_80MHZ_PLUS_MHZ;
+ case WIDTH_320:
+ return ScanResult.CHANNEL_WIDTH_320MHZ;
+ default:
+ return ScanResult.CHANNEL_WIDTH_20MHZ;
+ }
+ }
+
/**
* See comments for {@link IWifiChip#registerCallback(WifiChip.Callback)}
*/
@@ -1131,6 +1158,32 @@ public class WifiChipAidlImpl implements IWifiChip {
}
}
+ /**
+ * See comments for {@link IWifiChip#setVoipMode(int)}
+ */
+ @Override
+ public boolean setVoipMode(@WifiChip.WifiVoipMode int mode) {
+ final String methodStr = "setVoipMode";
+ synchronized (mLock) {
+ try {
+ if (!checkIfaceAndLogFailure(methodStr)
+ || !WifiHalAidlImpl.isServiceVersionAtLeast(2)
+ || !bitmapContains(mHalFeatureSet, FeatureSetMask.SET_VOIP_MODE)) {
+ return false;
+ }
+ mWifiChip.setVoipMode(frameworkToHalVoipMode(mode));
+ return true;
+ } catch (RemoteException e) {
+ handleRemoteException(e, methodStr);
+ } catch (ServiceSpecificException e) {
+ handleServiceSpecificException(e, methodStr);
+ } catch (IllegalArgumentException e) {
+ handleIllegalArgumentException(e, methodStr);
+ }
+ return false;
+ }
+ }
+
private class ChipEventCallback extends IWifiChipEventCallback.Stub {
@Override
public void onChipReconfigured(int modeId) throws RemoteException {
@@ -1520,6 +1573,18 @@ public class WifiChipAidlImpl implements IWifiChip {
return halFilter;
}
+ private static int frameworkToHalVoipMode(@WifiChip.WifiVoipMode int mode)
+ throws IllegalArgumentException {
+ switch (mode) {
+ case WifiChip.WIFI_VOIP_MODE_OFF:
+ return VoipMode.OFF;
+ case WifiChip.WIFI_VOIP_MODE_VOICE:
+ return VoipMode.VOICE;
+ default:
+ throw new IllegalArgumentException("bad voip mode " + mode);
+ }
+ }
+
private static boolean bitmapContains(long bitmap, long expectedBit) {
return (bitmap & expectedBit) != 0;
}
diff --git a/service/java/com/android/server/wifi/hal/WifiChipHidlImpl.java b/service/java/com/android/server/wifi/hal/WifiChipHidlImpl.java
index 430f96adf3..31101ac116 100644
--- a/service/java/com/android/server/wifi/hal/WifiChipHidlImpl.java
+++ b/service/java/com/android/server/wifi/hal/WifiChipHidlImpl.java
@@ -16,6 +16,11 @@
package com.android.server.wifi.hal;
+import static android.hardware.wifi.V1_6.WifiChannelWidthInMhz.WIDTH_160;
+import static android.hardware.wifi.V1_6.WifiChannelWidthInMhz.WIDTH_320;
+import static android.hardware.wifi.V1_6.WifiChannelWidthInMhz.WIDTH_40;
+import static android.hardware.wifi.V1_6.WifiChannelWidthInMhz.WIDTH_80;
+import static android.hardware.wifi.V1_6.WifiChannelWidthInMhz.WIDTH_80P80;
import static android.net.wifi.CoexUnsafeChannel.POWER_CAP_NONE;
import android.annotation.NonNull;
@@ -37,6 +42,8 @@ import android.hardware.wifi.V1_6.WifiRadioCombination;
import android.hardware.wifi.V1_6.WifiRadioConfiguration;
import android.net.wifi.CoexUnsafeChannel;
import android.net.wifi.OuiKeyedData;
+import android.net.wifi.ScanResult;
+import android.net.wifi.WifiAnnotations;
import android.net.wifi.WifiAvailableChannel;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiScanner;
@@ -1042,7 +1049,8 @@ public class WifiChipHidlImpl implements IWifiChip {
channelResp.value = new ArrayList<>();
for (android.hardware.wifi.V1_6.WifiUsableChannel ch : channels) {
channelResp.value.add(new WifiAvailableChannel(ch.channel,
- halToFrameworkIfaceMode(ch.ifaceModeMask)));
+ halToFrameworkIfaceMode(ch.ifaceModeMask),
+ halToFrameworkChannelWidth(ch.channelBandwidth)));
}
}
});
@@ -1056,7 +1064,8 @@ public class WifiChipHidlImpl implements IWifiChip {
channelResp.value = new ArrayList<>();
for (android.hardware.wifi.V1_5.WifiUsableChannel ch : channels) {
channelResp.value.add(new WifiAvailableChannel(ch.channel,
- halToFrameworkIfaceMode(ch.ifaceModeMask)));
+ halToFrameworkIfaceMode(ch.ifaceModeMask),
+ halToFrameworkChannelWidth(ch.channelBandwidth)));
}
}
});
@@ -1067,6 +1076,23 @@ public class WifiChipHidlImpl implements IWifiChip {
return channelResp.value;
}
+ private @WifiAnnotations.ChannelWidth int halToFrameworkChannelWidth(int channelBandwidth) {
+ switch (channelBandwidth) {
+ case WIDTH_40:
+ return ScanResult.CHANNEL_WIDTH_40MHZ;
+ case WIDTH_80:
+ return ScanResult.CHANNEL_WIDTH_80MHZ;
+ case WIDTH_160:
+ return ScanResult.CHANNEL_WIDTH_160MHZ;
+ case WIDTH_80P80:
+ return ScanResult.CHANNEL_WIDTH_80MHZ_PLUS_MHZ;
+ case WIDTH_320:
+ return ScanResult.CHANNEL_WIDTH_320MHZ;
+ default:
+ return ScanResult.CHANNEL_WIDTH_20MHZ;
+ }
+ }
+
private boolean registerCallbackInternal(String methodStr, WifiChip.Callback callback) {
if (mFrameworkCallback != null) {
Log.e(TAG, "Framework callback is already registered");
diff --git a/service/java/com/android/server/wifi/hal/WifiStaIfaceAidlImpl.java b/service/java/com/android/server/wifi/hal/WifiStaIfaceAidlImpl.java
index 628bfc5918..8cb199a0f4 100644
--- a/service/java/com/android/server/wifi/hal/WifiStaIfaceAidlImpl.java
+++ b/service/java/com/android/server/wifi/hal/WifiStaIfaceAidlImpl.java
@@ -95,12 +95,16 @@ public class WifiStaIfaceAidlImpl implements IWifiStaIface {
private Context mContext;
private SsidTranslator mSsidTranslator;
+ private final boolean mWifiLinkLayerAllRadiosStatsAggregationEnabled;
+
public WifiStaIfaceAidlImpl(@NonNull android.hardware.wifi.IWifiStaIface staIface,
@NonNull Context context, @NonNull SsidTranslator ssidTranslator) {
mWifiStaIface = staIface;
mContext = context;
mSsidTranslator = ssidTranslator;
mHalCallback = new StaIfaceEventCallback();
+ mWifiLinkLayerAllRadiosStatsAggregationEnabled = mContext.getResources()
+ .getBoolean(R.bool.config_wifiLinkLayerAllRadiosStatsAggregationEnabled);
}
/**
@@ -1485,9 +1489,7 @@ public class WifiStaIfaceAidlImpl implements IWifiStaIface {
private void aggregateFrameworkRadioStatsFromAidl(int radioIndex,
WifiLinkLayerStats stats, StaLinkLayerRadioStats aidlRadioStats) {
- if (!mContext.getResources()
- .getBoolean(R.bool.config_wifiLinkLayerAllRadiosStatsAggregationEnabled)
- && radioIndex > 0) {
+ if (!mWifiLinkLayerAllRadiosStatsAggregationEnabled && radioIndex > 0) {
return;
}
// Aggregate the radio stats from all the radios
diff --git a/service/java/com/android/server/wifi/hal/WifiStaIfaceHidlImpl.java b/service/java/com/android/server/wifi/hal/WifiStaIfaceHidlImpl.java
index 0472f89ef9..399fd2c377 100644
--- a/service/java/com/android/server/wifi/hal/WifiStaIfaceHidlImpl.java
+++ b/service/java/com/android/server/wifi/hal/WifiStaIfaceHidlImpl.java
@@ -78,6 +78,7 @@ public class WifiStaIfaceHidlImpl implements IWifiStaIface {
private SsidTranslator mSsidTranslator;
private static final int DEFAULT_LINK = 0;
private static final int NUM_OF_LINKS = 1;
+ private final boolean mWifiLinkLayerAllRadiosStatsAggregationEnabled;
public WifiStaIfaceHidlImpl(@NonNull android.hardware.wifi.V1_0.IWifiStaIface staIface,
@NonNull Context context, @NonNull SsidTranslator ssidTranslator) {
@@ -85,6 +86,8 @@ public class WifiStaIfaceHidlImpl implements IWifiStaIface {
mContext = context;
mSsidTranslator = ssidTranslator;
mHalCallback = new StaIfaceEventCallback();
+ mWifiLinkLayerAllRadiosStatsAggregationEnabled = mContext.getResources()
+ .getBoolean(R.bool.config_wifiLinkLayerAllRadiosStatsAggregationEnabled);
}
/**
@@ -1285,9 +1288,7 @@ public class WifiStaIfaceHidlImpl implements IWifiStaIface {
private void aggregateFrameworkRadioStatsFromHidl_1_3(int radioIndex,
WifiLinkLayerStats stats,
android.hardware.wifi.V1_3.StaLinkLayerRadioStats hidlRadioStats) {
- if (!mContext.getResources()
- .getBoolean(R.bool.config_wifiLinkLayerAllRadiosStatsAggregationEnabled)
- && radioIndex > 0) {
+ if (!mWifiLinkLayerAllRadiosStatsAggregationEnabled && radioIndex > 0) {
return;
}
// Aggregate the radio stats from all the radios
@@ -1334,9 +1335,7 @@ public class WifiStaIfaceHidlImpl implements IWifiStaIface {
private void aggregateFrameworkRadioStatsFromHidl_1_6(int radioIndex,
WifiLinkLayerStats stats,
android.hardware.wifi.V1_6.StaLinkLayerRadioStats hidlRadioStats) {
- if (!mContext.getResources()
- .getBoolean(R.bool.config_wifiLinkLayerAllRadiosStatsAggregationEnabled)
- && radioIndex > 0) {
+ if (!mWifiLinkLayerAllRadiosStatsAggregationEnabled && radioIndex > 0) {
return;
}
// Aggregate the radio stats from all the radios
diff --git a/service/java/com/android/server/wifi/hotspot2/ANQPRequestManager.java b/service/java/com/android/server/wifi/hotspot2/ANQPRequestManager.java
index 993412eb30..28b1628345 100644
--- a/service/java/com/android/server/wifi/hotspot2/ANQPRequestManager.java
+++ b/service/java/com/android/server/wifi/hotspot2/ANQPRequestManager.java
@@ -155,32 +155,12 @@ public class ANQPRequestManager {
* Roaming Consortium ANQP element will be requested
* @param hsReleaseVer Indicates Hotspot 2.0 Release version. When set to R2 or higher,
* the Release 2 ANQP elements {@link #R2_ANQP_BASE_SET} will be requested
- * @return true if a request was sent successfully
*/
- public boolean requestANQPElements(long bssid, ANQPNetworkKey anqpNetworkKey, boolean rcOIs,
+ public void requestANQPElements(long bssid, ANQPNetworkKey anqpNetworkKey, boolean rcOIs,
NetworkDetail.HSRelease hsReleaseVer) {
- if (mFeatureFlags.anqpRequestWaitForResponse()) {
- // Put the new request in the queue, process it if possible(no more pending request)
- mPendingRequest.offer(new AnqpRequest(bssid, rcOIs, hsReleaseVer, anqpNetworkKey));
- processNextRequest();
- return true;
- }
- // Check if we are allow to send the request now.
- if (!canSendRequestNow(bssid)) {
- return false;
- }
-
- // No need to hold off future requests for send failures.
- if (!mPasspointHandler.requestANQP(bssid, getRequestElementIDs(rcOIs, hsReleaseVer))) {
- return false;
- }
-
- // Update hold off info on when we are allowed to send the next ANQP request to
- // the given AP.
- updateHoldOffInfo(bssid);
-
- mPendingQueries.put(bssid, anqpNetworkKey);
- return true;
+ // Put the new request in the queue, process it if possible(no more pending request)
+ mPendingRequest.offer(new AnqpRequest(bssid, rcOIs, hsReleaseVer, anqpNetworkKey));
+ processNextRequest();
}
private void processNextRequest() {
diff --git a/service/java/com/android/server/wifi/hotspot2/NetworkDetail.java b/service/java/com/android/server/wifi/hotspot2/NetworkDetail.java
index 3cedd6afe3..e2facfe698 100644
--- a/service/java/com/android/server/wifi/hotspot2/NetworkDetail.java
+++ b/service/java/com/android/server/wifi/hotspot2/NetworkDetail.java
@@ -161,8 +161,9 @@ public class NetworkDetail {
// 6 GHz Access Point Type
private final InformationElementUtil.ApType6GHz mApType6GHz;
- // IEEE 802.11az
- private final boolean mIs11azSupported;
+ // IEEE 802.11az non-trigger based & trigger based
+ private final boolean mIs11azNtbResponder;
+ private final boolean mIs11azTbResponder;
// MLO Attributes
private MacAddress mMldMacAddress = null;
@@ -372,8 +373,8 @@ public class NetworkDetail {
mEpcsPriorityAccessSupported = ehtCapabilities.isEpcsPriorityAccessSupported();
mFilsCapable = extendedCapabilities.isFilsCapable();
mApType6GHz = heOperation.getApType6GHz();
- mIs11azSupported = extendedCapabilities.isTriggerBasedRangingRespSupported()
- || extendedCapabilities.isNonTriggerBasedRangingRespSupported();
+ mIs11azNtbResponder = extendedCapabilities.is80211azNtbResponder();
+ mIs11azTbResponder = extendedCapabilities.is80211azTbResponder();
int channelWidth = ScanResult.UNSPECIFIED;
int centerFreq0 = mPrimaryFreq;
int centerFreq1 = 0;
@@ -564,7 +565,8 @@ public class NetworkDetail {
mEpcsPriorityAccessSupported = base.mEpcsPriorityAccessSupported;
mFilsCapable = base.mFilsCapable;
mApType6GHz = base.mApType6GHz;
- mIs11azSupported = base.mIs11azSupported;
+ mIs11azNtbResponder = base.mIs11azNtbResponder;
+ mIs11azTbResponder = base.mIs11azTbResponder;
}
public NetworkDetail complete(Map<Constants.ANQPElementType, ANQPElement> anqpElements) {
@@ -794,10 +796,16 @@ public class NetworkDetail {
return mOceSupported;
}
- /** Return whether the AP supports IEEE 802.11az **/
- public boolean is11azSupported() {
- return mIs11azSupported;
+ /** Return whether the AP supports IEEE 802.11az non-trigger based ranging **/
+ public boolean is80211azNtbResponder() {
+ return mIs11azNtbResponder;
}
+
+ /** Return whether the AP supports IEEE 802.11az trigger based ranging **/
+ public boolean is80211azTbResponder() {
+ return mIs11azTbResponder;
+ }
+
/**
* Return whether the AP requires HE stations to participate either in individual TWT
* agreements or Broadcast TWT operation.
diff --git a/service/java/com/android/server/wifi/hotspot2/PasspointManager.java b/service/java/com/android/server/wifi/hotspot2/PasspointManager.java
index c5f2c3cf0e..d588e02a72 100644
--- a/service/java/com/android/server/wifi/hotspot2/PasspointManager.java
+++ b/service/java/com/android/server/wifi/hotspot2/PasspointManager.java
@@ -306,7 +306,7 @@ public class PasspointManager {
}
});
if (modified.get()) {
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
}
}
@@ -322,7 +322,7 @@ public class PasspointManager {
if (provider != null) {
provider.setUserConnectChoice(null, 0);
}
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
}
/**
@@ -581,7 +581,7 @@ public class PasspointManager {
mProviders.put(config.getUniqueId(), newProvider);
if (!isFromSuggestion) {
// Suggestions will be handled by the WifiNetworkSuggestionsManager
- mWifiConfigManager.saveToStore(true /* forceWrite */);
+ mWifiConfigManager.saveToStore();
}
if (!isFromSuggestion && newProvider.getPackageName() != null) {
startTrackingAppOpsChange(newProvider.getPackageName(), uid);
@@ -632,7 +632,7 @@ public class PasspointManager {
mWifiConfigManager.removeConnectChoiceFromAllNetworks(uniqueId);
if (!provider.isFromSuggestion()) {
// Suggestions will be handled by the WifiNetworkSuggestionsManager
- mWifiConfigManager.saveToStore(true /* forceWrite */);
+ mWifiConfigManager.saveToStore();
}
// Stop monitoring the package if there is no Passpoint profile installed by the package
@@ -728,7 +728,7 @@ public class PasspointManager {
provider.getPackageName(), provider.isFromSuggestion());
}
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
return true;
}
@@ -752,7 +752,7 @@ public class PasspointManager {
}
}
if (found) {
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
}
return found;
}
@@ -783,7 +783,7 @@ public class PasspointManager {
}
}
if (found) {
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
}
return found;
}
@@ -811,7 +811,7 @@ public class PasspointManager {
}
}
if (found) {
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
}
return found;
}
@@ -953,7 +953,7 @@ public class PasspointManager {
}
}
if (anyProviderUpdated) {
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
}
if (allMatches.size() != 0) {
for (Pair<PasspointProvider, PasspointMatch> match : allMatches) {
@@ -1644,7 +1644,7 @@ public class PasspointManager {
PasspointProvider provider = mProviders.get(configuration.getProfileKey());
if (provider != null) {
provider.setAnonymousIdentity(configuration.enterpriseConfig.getAnonymousIdentity());
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
}
}
@@ -1653,7 +1653,7 @@ public class PasspointManager {
*/
public void resetSimPasspointNetwork() {
mProviders.values().forEach(p -> p.setAnonymousIdentity(null));
- mWifiConfigManager.saveToStore(true);
+ mWifiConfigManager.saveToStore();
}
/**
diff --git a/service/java/com/android/server/wifi/hotspot2/PasspointProvider.java b/service/java/com/android/server/wifi/hotspot2/PasspointProvider.java
index de0be198bd..d000db5ed1 100644
--- a/service/java/com/android/server/wifi/hotspot2/PasspointProvider.java
+++ b/service/java/com/android/server/wifi/hotspot2/PasspointProvider.java
@@ -351,7 +351,8 @@ public class PasspointProvider {
// Install the client private key & certificate.
if (mConfig.getCredential().getClientPrivateKey() != null
- && mConfig.getCredential().getClientCertificateChain() != null) {
+ && mConfig.getCredential().getClientCertificateChain() != null
+ && mConfig.getCredential().getCertCredential() != null) {
String keyName = ALIAS_HS_TYPE + mProviderId;
PrivateKey clientKey = mConfig.getCredential().getClientPrivateKey();
X509Certificate clientCert = getClientCertificate(
diff --git a/service/java/com/android/server/wifi/p2p/ISupplicantP2pIfaceHal.java b/service/java/com/android/server/wifi/p2p/ISupplicantP2pIfaceHal.java
index 4abfdd7415..72f669bb53 100644
--- a/service/java/com/android/server/wifi/p2p/ISupplicantP2pIfaceHal.java
+++ b/service/java/com/android/server/wifi/p2p/ISupplicantP2pIfaceHal.java
@@ -619,7 +619,7 @@ interface ISupplicantP2pIfaceHal {
* Note: Aidl only.
*/
default boolean registerDeathHandler(@NonNull WifiNative.SupplicantDeathEventHandler handler) {
- return false;
+ return true;
};
/**
@@ -629,6 +629,6 @@ interface ISupplicantP2pIfaceHal {
* Note: Aidl only.
*/
default boolean deregisterDeathHandler() {
- return false;
+ return true;
};
}
diff --git a/service/java/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackHidlImpl.java b/service/java/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackHidlImpl.java
index e1d9499287..0cb0cd2354 100644
--- a/service/java/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackHidlImpl.java
+++ b/service/java/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackHidlImpl.java
@@ -19,6 +19,7 @@ package com.android.server.wifi.p2p;
import android.annotation.NonNull;
import android.hardware.wifi.supplicant.V1_0.ISupplicantP2pIfaceCallback;
import android.hardware.wifi.supplicant.V1_0.WpsConfigMethods;
+import android.net.MacAddress;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
@@ -489,18 +490,19 @@ public class SupplicantP2pIfaceCallbackHidlImpl extends ISupplicantP2pIfaceCallb
mMonitor.broadcastP2pServiceDiscoveryResponse(mInterface, response);
}
- private WifiP2pDevice createStaEventDevice(byte[] srcAddress, byte[] p2pDeviceAddress) {
+ private WifiP2pDevice createStaEventDevice(byte[] interfaceAddress, byte[] p2pDeviceAddress) {
WifiP2pDevice device = new WifiP2pDevice();
byte[] deviceAddressBytes;
// Legacy STAs may not supply a p2pDeviceAddress (signaled by a zero'd p2pDeviceAddress)
- // In this case, use srcAddress instead
+ // In this case, use interfaceAddress instead
if (!Arrays.equals(NativeUtil.ANY_MAC_BYTES, p2pDeviceAddress)) {
deviceAddressBytes = p2pDeviceAddress;
} else {
- deviceAddressBytes = srcAddress;
+ deviceAddressBytes = interfaceAddress;
}
try {
device.deviceAddress = NativeUtil.macAddressFromByteArray(deviceAddressBytes);
+ device.setInterfaceMacAddress(MacAddress.fromBytes(interfaceAddress));
} catch (Exception e) {
Log.e(TAG, "Could not decode MAC address", e);
return null;
diff --git a/service/java/com/android/server/wifi/p2p/WifiP2pMetrics.java b/service/java/com/android/server/wifi/p2p/WifiP2pMetrics.java
index b2d2ea740d..d62f9e47f8 100644
--- a/service/java/com/android/server/wifi/p2p/WifiP2pMetrics.java
+++ b/service/java/com/android/server/wifi/p2p/WifiP2pMetrics.java
@@ -18,6 +18,7 @@ package com.android.server.wifi.p2p;
import static android.os.Process.SYSTEM_UID;
+import android.annotation.Nullable;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
@@ -230,6 +231,8 @@ public class WifiP2pMetrics {
sb.append(event.staFrequencyMhz);
sb.append(", uid=");
sb.append(event.uid);
+ sb.append(", attributionTag=");
+ sb.append(event.attributionTag);
sb.append(", connectivityLevelFailureCode=").append(
getConnectivityLevelFailureCodeToString(
event.connectivityLevelFailureCode));
@@ -381,10 +384,15 @@ public class WifiP2pMetrics {
* @param connectionType indicate this connection is fresh or reinvoke.
* @param config configuration used for this connection.
* @param groupRole groupRole used for this connection.
+ * @param uid uid of caller app
+ * @param attributionTag attributionTag of caller app
*/
public void startConnectionEvent(int connectionType, WifiP2pConfig config, int groupRole,
- int uid) {
+ int uid, @Nullable String attributionTag) {
synchronized (mLock) {
+ if (attributionTag == null) {
+ attributionTag = "";
+ }
StringBuilder stringBuilder = new StringBuilder("Start connection event");
if (mCurrentConnectionEvent == null) {
stringBuilder.append(", mCurrentConnectionEvent:null");
@@ -394,6 +402,7 @@ public class WifiP2pMetrics {
.append(", curGroupRole:")
.append(getGroupRoleToString(mCurrentConnectionEvent.groupRole))
.append(", curUid:").append(mCurrentConnectionEvent.uid)
+ .append(", attributionTag:").append(mCurrentConnectionEvent.attributionTag)
.append(", curConnectivityLevelFailureCode:")
.append(getConnectivityLevelFailureCodeToString(
mCurrentConnectionEvent.connectivityLevelFailureCode));
@@ -401,7 +410,8 @@ public class WifiP2pMetrics {
stringBuilder.append(", startConnectionType:")
.append(getconnectionTypeToString(connectionType))
.append(", startGroupRole:").append(getGroupRoleToString(groupRole))
- .append(", startUid:").append(uid);
+ .append(", startUid:").append(uid)
+ .append(", startAttributionTag:").append(attributionTag);
Log.d(TAG, stringBuilder.toString());
// handle overlapping connection event first.
if (mCurrentConnectionEvent != null) {
@@ -426,6 +436,7 @@ public class WifiP2pMetrics {
}
mCurrentConnectionEvent.staFrequencyMhz = getWifiStaFrequency();
mCurrentConnectionEvent.uid = uid;
+ mCurrentConnectionEvent.attributionTag = attributionTag;
if (mLastConnectionEventUid == uid && mCurrentConnectionEventStartTime < (
mLastConnectionEventStartTime + MAX_CONNECTION_ATTEMPT_TIME_INTERVAL_MS)) {
mLastConnectionTryCount += 1;
@@ -464,6 +475,7 @@ public class WifiP2pMetrics {
.append(getGroupRoleToString(mCurrentConnectionEvent.groupRole))
.append(", curUid:")
.append(mCurrentConnectionEvent.uid)
+ .append(", attributionTag:").append(mCurrentConnectionEvent.attributionTag)
.append(", curConnectivityLevelFailureCode:")
.append(getConnectivityLevelFailureCodeToString(
mCurrentConnectionEvent.connectivityLevelFailureCode));
@@ -474,9 +486,9 @@ public class WifiP2pMetrics {
if (mCurrentConnectionEvent == null) {
// Reinvoking a group with invitation will be handled in supplicant.
// There won't be a connection starting event in framework.
- // THe framework only get the connection ending event in GroupStarted state.
+ // The framework only gets the connection ending event in GroupStarted state.
startConnectionEvent(P2pConnectionEvent.CONNECTION_REINVOKE, null,
- GroupEvent.GROUP_UNKNOWN, SYSTEM_UID);
+ GroupEvent.GROUP_UNKNOWN, SYSTEM_UID, null);
}
mCurrentConnectionEvent.durationTakenToConnectMillis = (int)
@@ -497,7 +509,8 @@ public class WifiP2pMetrics {
mCurrentConnectionEvent.uid,
mIsCountryCodeWorldMode,
mCurrentConnectionEvent.fallbackToNegotiationOnInviteStatusInfoUnavailable,
- mCurrentConnectionEvent.tryCount);
+ mCurrentConnectionEvent.tryCount,
+ mCurrentConnectionEvent.attributionTag);
mCurrentConnectionEvent = null;
if (P2pConnectionEvent.CLF_NONE == failure) {
mLastConnectionTryCount = 0;
diff --git a/service/java/com/android/server/wifi/p2p/WifiP2pNative.java b/service/java/com/android/server/wifi/p2p/WifiP2pNative.java
index c32d593836..edbf956ace 100644
--- a/service/java/com/android/server/wifi/p2p/WifiP2pNative.java
+++ b/service/java/com/android/server/wifi/p2p/WifiP2pNative.java
@@ -96,8 +96,7 @@ public class WifiP2pNative {
public void teardownAndInvalidate(@Nullable String ifaceName) {
synchronized (mLock) {
- if (mFeatureFlags.d2dWhenInfraStaOff()
- && !mSupplicantP2pIfaceHal.deregisterDeathHandler()) {
+ if (!mSupplicantP2pIfaceHal.deregisterDeathHandler()) {
Log.i(TAG, "Failed to deregister p2p supplicant death handler");
}
if (!TextUtils.isEmpty(ifaceName)) {
@@ -186,8 +185,7 @@ public class WifiP2pNative {
* Close supplicant connection.
*/
public void stopP2pSupplicantIfNecessary() {
- if (mFeatureFlags.d2dWhenInfraStaOff()
- && mSupplicantP2pIfaceHal.isInitializationStarted()) {
+ if (mSupplicantP2pIfaceHal.isInitializationStarted()) {
mSupplicantP2pIfaceHal.terminate();
}
}
@@ -238,14 +236,10 @@ public class WifiP2pNative {
mInterfaceDestroyedListener = (null == destroyedListener)
? null
: new InterfaceDestroyedListenerInternal(destroyedListener);
- if (mFeatureFlags.d2dWhenInfraStaOff()) {
- mP2pIface = mWifiNative.createP2pIface(mInterfaceDestroyedListener, handler,
- requestorWs);
- if (mP2pIface != null) {
- mP2pIfaceName = mP2pIface.name;
- }
- } else {
- mP2pIfaceName = createP2pIface(handler, requestorWs);
+ mP2pIface = mWifiNative.createP2pIface(mInterfaceDestroyedListener, handler,
+ requestorWs);
+ if (mP2pIface != null) {
+ mP2pIfaceName = mP2pIface.name;
}
if (mP2pIfaceName == null) {
Log.e(TAG, "Failed to create P2p iface");
@@ -267,8 +261,7 @@ public class WifiP2pNative {
mWifiMetrics.incrementNumSetupP2pInterfaceFailureDueToSupplicant();
return null;
}
- if (mFeatureFlags.d2dWhenInfraStaOff()
- && !mSupplicantP2pIfaceHal.registerDeathHandler(
+ if (!mSupplicantP2pIfaceHal.registerDeathHandler(
new SupplicantDeathHandlerInternal())) {
Log.e(TAG, "Failed to register supplicant death handler"
+ "(because hidl supplicant?)");
@@ -297,11 +290,6 @@ public class WifiP2pNative {
if (mP2pIfaceName != null) {
mHalDeviceManager.removeP2pIface(mP2pIfaceName);
Log.i(TAG, "P2P interface teardown completed");
- if (!mFeatureFlags.d2dWhenInfraStaOff()) {
- if (null != mInterfaceDestroyedListener) {
- mInterfaceDestroyedListener.teardownAndInvalidate(mP2pIfaceName);
- }
- }
}
} else {
Log.i(TAG, "HAL is not supported. Destroy listener for the interface.");
diff --git a/service/java/com/android/server/wifi/p2p/WifiP2pServiceImpl.java b/service/java/com/android/server/wifi/p2p/WifiP2pServiceImpl.java
index 7b0583bfca..e004bc4660 100644
--- a/service/java/com/android/server/wifi/p2p/WifiP2pServiceImpl.java
+++ b/service/java/com/android/server/wifi/p2p/WifiP2pServiceImpl.java
@@ -711,7 +711,7 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
mP2pSupported = mContext.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_WIFI_DIRECT);
- HandlerThread wifiP2pThread = mWifiInjector.getWifiP2pServiceHandlerThread();
+ HandlerThread wifiP2pThread = mWifiInjector.getWifiHandlerThread();
mClientHandler = new ClientHandler(TAG, wifiP2pThread.getLooper());
mWifiNative = mWifiInjector.getWifiP2pNative();
mLastCallerInfoManager = mWifiInjector.getLastCallerInfoManager();
@@ -882,6 +882,7 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
if (staticIpConfig != null) {
config = new ProvisioningConfiguration.Builder()
.withoutIpReachabilityMonitor()
+ .withRandomMacAddress()
.withStaticConfiguration(staticIpConfig).build();
}
}
@@ -889,6 +890,7 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
// start DHCP provisioning
config = new ProvisioningConfiguration.Builder()
.withoutIpReachabilityMonitor()
+ .withRandomMacAddress()
.withPreDhcpAction(30 * 1000)
.withProvisioningTimeoutMs(36 * 1000)
.build();
@@ -1133,23 +1135,23 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
mWifiP2pListeners.unregister(listener);
}
- private void onStateChanged(boolean p2pEnabled) {
+ private void onP2pStateChanged(@WifiP2pManager.WifiP2pState int state) {
int numCallbacks = mWifiP2pListeners.beginBroadcast();
for (int i = 0; i < numCallbacks; i++) {
try {
- mWifiP2pListeners.getBroadcastItem(i).onStateChanged(p2pEnabled);
+ mWifiP2pListeners.getBroadcastItem(i).onP2pStateChanged(state);
} catch (RemoteException e) {
- Log.e(TAG, "Failure calling onStateChanged" + e);
+ Log.e(TAG, "Failure calling onP2pStateChanged" + e);
}
}
mWifiP2pListeners.finishBroadcast();
}
- private void onDiscoveryStateChanged(boolean started) {
+ private void onDiscoveryStateChanged(@WifiP2pManager.WifiP2pDiscoveryState int state) {
int numCallbacks = mWifiP2pListeners.beginBroadcast();
for (int i = 0; i < numCallbacks; i++) {
try {
- mWifiP2pListeners.getBroadcastItem(i).onDiscoveryStateChanged(started);
+ mWifiP2pListeners.getBroadcastItem(i).onDiscoveryStateChanged(state);
} catch (RemoteException e) {
Log.e(TAG, "Failure calling onDiscoveryStateChanged" + e);
}
@@ -1157,11 +1159,11 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
mWifiP2pListeners.finishBroadcast();
}
- private void onListenStateChanged(boolean started) {
+ private void onListenStateChanged(@WifiP2pManager.WifiP2pListenState int state) {
int numCallbacks = mWifiP2pListeners.beginBroadcast();
for (int i = 0; i < numCallbacks; i++) {
try {
- mWifiP2pListeners.getBroadcastItem(i).onListenStateChanged(started);
+ mWifiP2pListeners.getBroadcastItem(i).onListenStateChanged(state);
} catch (RemoteException e) {
Log.e(TAG, "Failure calling onListenStateChanged" + e);
}
@@ -1229,11 +1231,11 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
mWifiP2pListeners.finishBroadcast();
}
- private void onGroupCreationFailed() {
+ private void onGroupCreationFailed(@WifiP2pManager.GroupCreationFailureReason int reason) {
int numCallbacks = mWifiP2pListeners.beginBroadcast();
for (int i = 0; i < numCallbacks; i++) {
try {
- mWifiP2pListeners.getBroadcastItem(i).onGroupCreationFailed();
+ mWifiP2pListeners.getBroadcastItem(i).onGroupCreationFailed(reason);
} catch (RemoteException e) {
Log.e(TAG, "Failure calling onGroupCreationFailed" + e);
}
@@ -1517,7 +1519,7 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
}
if (wifistate == WifiManager.WIFI_STATE_ENABLED
|| wifistate == WifiManager.WIFI_STATE_DISABLING) {
- checkAndSendP2pStateChangedBroadcast();
+ getHandler().post(() -> checkAndSendP2pStateChangedBroadcast());
}
}
}, new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
@@ -1815,14 +1817,15 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
}
private void reportConnectionEventTakeBugReportIfOverlapped(int connectionType,
- WifiP2pConfig config, int groupRole, int uid) {
+ WifiP2pConfig config, int groupRole, int uid, String attributionTag) {
if (mWifiP2pMetrics.hasOngoingConnection()) {
takeBugReportP2pFailureIfNeeded("Wi-Fi BugReport (P2P "
+ mWifiP2pMetrics.getP2pGroupRoleString()
+ " overlapping connection attempt)",
"new and old connection attempts overlap");
}
- mWifiP2pMetrics.startConnectionEvent(connectionType, config, groupRole, uid);
+ mWifiP2pMetrics.startConnectionEvent(connectionType, config, groupRole, uid,
+ attributionTag);
}
private void takeBugReportP2pFailureIfNeeded(String bugTitle, String bugDetail) {
@@ -2392,6 +2395,7 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
mGroup = (WifiP2pGroup) message.obj;
loge("Unexpected group creation, remove " + mGroup);
mWifiNative.p2pGroupRemove(mGroup.getInterface());
+ mGroup = null;
break;
case WifiP2pMonitor.P2P_GROUP_FORMATION_FAILURE_EVENT:
// A group formation failure is always followed by
@@ -3582,13 +3586,14 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
break;
}
int uid = message.sendingUid;
+ String attributionTag = getCallingFeatureId(uid, message.replyTo);
Bundle extras = message.getData()
.getBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE);
boolean hasPermission = false;
if (isPlatformOrTargetSdkLessThanT(packageName, uid)) {
hasPermission = mWifiPermissionsUtil.checkCanAccessWifiDirect(
packageName,
- getCallingFeatureId(message.sendingUid, message.replyTo),
+ attributionTag,
uid, false);
} else {
hasPermission = checkNearbyDevicesPermission(uid, packageName,
@@ -3616,7 +3621,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
if (mWifiNative.p2pGroupAdd(config, true)) {
reportConnectionEventTakeBugReportIfOverlapped(
P2pConnectionEvent.CONNECTION_FAST,
- config, WifiMetricsProto.GroupEvent.GROUP_CLIENT, uid);
+ config, WifiMetricsProto.GroupEvent.GROUP_CLIENT, uid,
+ attributionTag);
smTransition(this, mGroupNegotiationState);
} else {
loge("Cannot join a group with config.");
@@ -3634,12 +3640,12 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
if (reinvokePersistentGroup(config, false)) {
mWifiP2pMetrics.startConnectionEvent(
P2pConnectionEvent.CONNECTION_REINVOKE,
- config, GroupEvent.GROUP_UNKNOWN, uid);
+ config, GroupEvent.GROUP_UNKNOWN, uid, attributionTag);
smTransition(this, mGroupNegotiationState);
} else {
mWifiP2pMetrics.startConnectionEvent(
P2pConnectionEvent.CONNECTION_FRESH,
- config, GroupEvent.GROUP_UNKNOWN, uid);
+ config, GroupEvent.GROUP_UNKNOWN, uid, attributionTag);
smTransition(this, mProvisionDiscoveryState);
}
}
@@ -3684,7 +3690,7 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
mJoinExistingGroup = false;
mWifiP2pMetrics.startConnectionEvent(
P2pConnectionEvent.CONNECTION_FRESH,
- config, GroupEvent.GROUP_UNKNOWN, Process.SYSTEM_UID);
+ config, GroupEvent.GROUP_UNKNOWN, Process.SYSTEM_UID, null);
smTransition(this, mUserAuthorizingNegotiationRequestState);
break;
case WifiP2pMonitor.P2P_INVITATION_RECEIVED_EVENT:
@@ -3734,7 +3740,7 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
mJoinExistingGroup = true;
mWifiP2pMetrics.startConnectionEvent(
P2pConnectionEvent.CONNECTION_FRESH,
- config, GroupEvent.GROUP_UNKNOWN, Process.SYSTEM_UID);
+ config, GroupEvent.GROUP_UNKNOWN, Process.SYSTEM_UID, null);
smTransition(this, mUserAuthorizingInviteRequestState);
break;
case WifiP2pMonitor.P2P_PROV_DISC_PBC_REQ_EVENT:
@@ -3776,13 +3782,14 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
break;
}
int uid = message.sendingUid;
+ String attributionTag = getCallingFeatureId(uid, message.replyTo);
Bundle extras = message.getData()
.getBundle(WifiP2pManager.EXTRA_PARAM_KEY_BUNDLE);
boolean hasPermission;
if (isPlatformOrTargetSdkLessThanT(packageName, uid)) {
hasPermission = mWifiPermissionsUtil.checkCanAccessWifiDirect(
packageName,
- getCallingFeatureId(message.sendingUid, message.replyTo),
+ attributionTag,
uid, false);
} else {
hasPermission = checkNearbyDevicesPermission(uid, packageName,
@@ -3810,7 +3817,7 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
}
reportConnectionEventTakeBugReportIfOverlapped(
P2pConnectionEvent.CONNECTION_FAST,
- config, GroupEvent.GROUP_OWNER, uid);
+ config, GroupEvent.GROUP_OWNER, uid, attributionTag);
ret = mWifiNative.p2pGroupAdd(config, false);
}
} else if (netId == WifiP2pGroup.NETWORK_ID_PERSISTENT) {
@@ -3819,18 +3826,18 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
if (netId != -1) {
mWifiP2pMetrics.startConnectionEvent(
P2pConnectionEvent.CONNECTION_REINVOKE,
- null, GroupEvent.GROUP_OWNER, uid);
+ null, GroupEvent.GROUP_OWNER, uid, attributionTag);
ret = mWifiNative.p2pGroupAdd(netId);
} else {
mWifiP2pMetrics.startConnectionEvent(
P2pConnectionEvent.CONNECTION_LOCAL,
- null, GroupEvent.GROUP_OWNER, uid);
+ null, GroupEvent.GROUP_OWNER, uid, attributionTag);
ret = mWifiNative.p2pGroupAdd(true);
}
} else {
mWifiP2pMetrics.startConnectionEvent(
P2pConnectionEvent.CONNECTION_LOCAL,
- null, GroupEvent.GROUP_OWNER, uid);
+ null, GroupEvent.GROUP_OWNER, uid, attributionTag);
ret = mWifiNative.p2pGroupAdd(false);
}
@@ -3873,6 +3880,7 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
} else {
loge("Unexpected group creation, remove " + mGroup);
mWifiNative.p2pGroupRemove(mGroup.getInterface());
+ mGroup = null;
}
break;
case WifiP2pManager.START_LISTEN:
@@ -4042,7 +4050,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
"P2p rejection resume after delay - originated from "
+ getWhatToString(message.what));
if (message.arg2 == WifiP2pManager.CANCEL_CONNECT) {
- handleGroupCreationFailure();
+ handleGroupCreationFailure(WifiP2pManager
+ .GROUP_CREATION_FAILURE_REASON_CONNECTION_CANCELLED);
if (message.obj != null) {
replyToMessage(
(Message) message.obj,
@@ -4117,7 +4126,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
}
mWifiP2pMetrics.endConnectionEvent(
P2pConnectionEvent.CLF_TIMEOUT);
- handleGroupCreationFailure();
+ handleGroupCreationFailure(
+ WifiP2pManager.GROUP_CREATION_FAILURE_REASON_TIMED_OUT);
smTransition(this, mInactiveState);
}
break;
@@ -4278,7 +4288,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
delay);
} else {
mWifiNative.p2pCancelConnect();
- handleGroupCreationFailure();
+ handleGroupCreationFailure(
+ WifiP2pManager.GROUP_CREATION_FAILURE_REASON_USER_REJECTED);
smTransition(this, mInactiveState);
}
break;
@@ -4291,7 +4302,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
break;
case WifiP2pMonitor.P2P_PROV_DISC_FAILURE_EVENT:
loge("provision discovery failed status: " + message.arg1);
- handleGroupCreationFailure();
+ handleGroupCreationFailure(WifiP2pManager
+ .GROUP_CREATION_FAILURE_REASON_PROVISION_DISCOVERY_FAILED);
smTransition(this, mInactiveState);
break;
case WifiP2pManager.SET_CONNECTION_REQUEST_RESULT: {
@@ -4376,7 +4388,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
break;
case WifiP2pMonitor.P2P_PROV_DISC_FAILURE_EVENT:
loge("provision discovery failed status: " + message.arg1);
- handleGroupCreationFailure();
+ handleGroupCreationFailure(WifiP2pManager
+ .GROUP_CREATION_FAILURE_REASON_PROVISION_DISCOVERY_FAILED);
smTransition(this, mInactiveState);
break;
case WifiP2pManager.SET_CONNECTION_REQUEST_RESULT:
@@ -4532,7 +4545,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
mWifiNative.p2pCancelConnect();
mWifiP2pMetrics.endConnectionEvent(
P2pConnectionEvent.CLF_PROV_DISC_FAIL);
- handleGroupCreationFailure();
+ handleGroupCreationFailure(WifiP2pManager
+ .GROUP_CREATION_FAILURE_REASON_PROVISION_DISCOVERY_FAILED);
smTransition(this, mInactiveState);
break;
default:
@@ -4636,6 +4650,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
}
mWifiNative.setP2pGroupIdle(mGroup.getInterface(), GROUP_IDLE_TIME_S);
+ Log.d(TAG, "start Ip client with provisioning mode: "
+ + mSavedPeerConfig.getGroupClientIpProvisioningMode());
startIpClient(mGroup.getInterface(), getHandler(),
mSavedPeerConfig.getGroupClientIpProvisioningMode(),
mGroup.p2pClientEapolIpInfo);
@@ -4690,7 +4706,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
}
mWifiP2pMetrics.endConnectionEvent(
P2pConnectionEvent.CLF_GROUP_REMOVED);
- handleGroupCreationFailure();
+ handleGroupCreationFailure(
+ WifiP2pManager.GROUP_CREATION_FAILURE_REASON_GROUP_REMOVED);
smTransition(this, mInactiveState);
break;
case WifiP2pMonitor.P2P_GROUP_FORMATION_FAILURE_EVENT:
@@ -4761,7 +4778,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
} else {
mWifiP2pMetrics.endConnectionEvent(
P2pConnectionEvent.CLF_INVITATION_FAIL);
- handleGroupCreationFailure();
+ handleGroupCreationFailure(
+ WifiP2pManager.GROUP_CREATION_FAILURE_REASON_INVITATION_FAILED);
smTransition(this, mInactiveState);
}
break;
@@ -4769,7 +4787,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
loge("Peer rejected the connection request - status: " + message.arg1);
mWifiP2pMetrics.endConnectionEvent(
P2pConnectionEvent.CLF_GROUP_REMOVED);
- handleGroupCreationFailure();
+ handleGroupCreationFailure(WifiP2pManager
+ .GROUP_CREATION_FAILURE_REASON_PROVISION_DISCOVERY_FAILED);
smTransition(this, mInactiveState);
break;
case WifiP2pMonitor.AP_STA_CONNECTED_EVENT:
@@ -4919,7 +4938,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
mFrequencyConflictDialogPreT = null;
mWifiP2pMetrics.endConnectionEvent(
P2pConnectionEvent.CLF_USER_REJECT);
- handleGroupCreationFailure();
+ handleGroupCreationFailure(
+ WifiP2pManager.GROUP_CREATION_FAILURE_REASON_USER_REJECTED);
smTransition(this, mInactiveState);
break;
case DROP_WIFI_USER_ACCEPT:
@@ -5639,12 +5659,9 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
public boolean isWifiP2pAvailable() {
if (mIsP2pDisallowedByAdmin) return false;
- if (mFeatureFlags.d2dWhenInfraStaOff()) {
- return mIsWifiEnabled
- || (mSettingsConfigStore.get(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED)
- && mWifiGlobals.isD2dSupportedWhenInfraStaDisabled());
- }
- return mIsWifiEnabled;
+ return mIsWifiEnabled
+ || (mSettingsConfigStore.get(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED)
+ && mWifiGlobals.isD2dSupportedWhenInfraStaDisabled());
}
public void checkAndSendP2pStateChangedBroadcast() {
@@ -5659,7 +5676,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
}
private void sendP2pStateChangedBroadcast(boolean enabled) {
- onStateChanged(enabled);
+ onP2pStateChanged(enabled ? WifiP2pManager.WIFI_P2P_STATE_ENABLED
+ : WifiP2pManager.WIFI_P2P_STATE_DISABLED);
final Intent intent = new Intent(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
if (enabled) {
@@ -5677,7 +5695,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
mDiscoveryStarted = started;
if (mVerboseLoggingEnabled) logd("discovery change broadcast " + started);
- onDiscoveryStateChanged(started);
+ onDiscoveryStateChanged(started ? WifiP2pManager.WIFI_P2P_DISCOVERY_STARTED
+ : WifiP2pManager.WIFI_P2P_DISCOVERY_STOPPED);
final Intent intent = new Intent(WifiP2pManager.WIFI_P2P_DISCOVERY_CHANGED_ACTION);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
@@ -5692,7 +5711,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
mListenStarted = started;
if (mVerboseLoggingEnabled) logd("wifi p2p listen change broadcast " + started);
- onListenStateChanged(started);
+ onListenStateChanged(started ? WifiP2pManager.WIFI_P2P_LISTEN_STARTED
+ : WifiP2pManager.WIFI_P2P_LISTEN_STOPPED);
final Intent intent = new Intent(WifiP2pManager.ACTION_WIFI_P2P_LISTEN_STATE_CHANGED);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
@@ -6931,7 +6951,8 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
return true;
}
- private void handleGroupCreationFailure() {
+ private void handleGroupCreationFailure(
+ @WifiP2pManager.GroupCreationFailureReason int reason) {
// A group is formed, but the tethering request is not proceed.
if (null != mGroup) {
// Clear any timeout that was set. This is essential for devices
@@ -6942,7 +6963,7 @@ public class WifiP2pServiceImpl extends IWifiP2pManager.Stub {
}
resetWifiP2pInfo();
mDetailedState = NetworkInfo.DetailedState.FAILED;
- onGroupCreationFailed();
+ onGroupCreationFailed(reason);
sendP2pConnectionChangedBroadcast();
// Remove only the peer we failed to connect to so that other devices discovered
diff --git a/service/java/com/android/server/wifi/rtt/RttService.java b/service/java/com/android/server/wifi/rtt/RttService.java
index fdfc55f901..aa13c0b6c0 100644
--- a/service/java/com/android/server/wifi/rtt/RttService.java
+++ b/service/java/com/android/server/wifi/rtt/RttService.java
@@ -55,7 +55,7 @@ public class RttService extends SystemService {
return;
}
- HandlerThread handlerThread = wifiInjector.getRttHandlerThread();
+ HandlerThread handlerThread = wifiInjector.getWifiHandlerThread();
WifiPermissionsUtil wifiPermissionsUtil = wifiInjector.getWifiPermissionsUtil();
RttMetrics rttMetrics = wifiInjector.getWifiMetrics().getRttMetrics();
WifiAwareManager awareManager = getContext().getSystemService(WifiAwareManager.class);
diff --git a/service/java/com/android/server/wifi/scanner/WifiScannerInternal.java b/service/java/com/android/server/wifi/scanner/WifiScannerInternal.java
index 148f15ea6f..862b4cbdab 100644
--- a/service/java/com/android/server/wifi/scanner/WifiScannerInternal.java
+++ b/service/java/com/android/server/wifi/scanner/WifiScannerInternal.java
@@ -21,12 +21,12 @@ import android.annotation.Nullable;
import android.net.wifi.IWifiScannerListener;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiScanner;
-import android.os.Handler;
import android.os.Process;
import android.os.WorkSource;
import android.util.Log;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.wifi.WifiThreadRunner;
import java.util.Collections;
import java.util.List;
@@ -44,16 +44,16 @@ public abstract class WifiScannerInternal {
public static class ScanListener extends IWifiScannerListener.Stub {
private static final String TAG = "WifiScannerInternal";
private final WifiScanner.ScanListener mScanListener;
- private final Handler mHandler;
+ private final WifiThreadRunner mWifiThreadRunner;
/**
* Local scan listener constructor
* @param scanListener WifiScanner listener
* @param handler handler for the listener
*/
- public ScanListener(WifiScanner.ScanListener scanListener, Handler handler) {
+ public ScanListener(WifiScanner.ScanListener scanListener, WifiThreadRunner runner) {
mScanListener = scanListener;
- mHandler = handler;
+ mWifiThreadRunner = runner;
}
/**
@@ -67,30 +67,29 @@ public abstract class WifiScannerInternal {
@Override
public void onSuccess() {
- mHandler.post(() -> {
- mScanListener.onSuccess();
- });
+ mWifiThreadRunner.post(mScanListener::onSuccess,
+ TAG + "#onSuccess");
}
@Override
public void onFailure(int reason, String description) {
- mHandler.post(() -> {
+ mWifiThreadRunner.post(() -> {
mScanListener.onFailure(reason, description);
- });
+ }, TAG + "#onFailure");
}
@Override
public void onResults(WifiScanner.ScanData[] scanDatas) {
- mHandler.post(() -> {
+ mWifiThreadRunner.post(() -> {
mScanListener.onResults(scanDatas);
- });
+ }, TAG + "#onResults");
}
@Override
public void onFullResult(ScanResult fullScanResult) {
- mHandler.post(() -> {
+ mWifiThreadRunner.post(() -> {
mScanListener.onFullResult(fullScanResult);
- });
+ }, TAG + "#onFullResult");
}
@Override
@@ -106,9 +105,9 @@ public abstract class WifiScannerInternal {
}
WifiScanner.PnoScanListener pnoScanListener =
(WifiScanner.PnoScanListener) mScanListener;
- mHandler.post(() -> {
+ mWifiThreadRunner.post(() -> {
pnoScanListener.onPnoNetworkFound(scanResult);
- });
+ }, TAG + "#onPnoNetworkFound");
}
}
diff --git a/service/java/com/android/server/wifi/scanner/WifiScanningServiceImpl.java b/service/java/com/android/server/wifi/scanner/WifiScanningServiceImpl.java
index 77383f643b..2c07b4cc5a 100644
--- a/service/java/com/android/server/wifi/scanner/WifiScanningServiceImpl.java
+++ b/service/java/com/android/server/wifi/scanner/WifiScanningServiceImpl.java
@@ -158,7 +158,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
if (mChannelHelper == null) return new ChannelSpec[0][0];
mChannelHelper.updateChannels();
return mChannelHelper.getAvailableScanChannels(band);
- }, new ChannelSpec[0][0]);
+ }, new ChannelSpec[0][0], TAG + "#getAvailableChannels");
if (channelSpecs == null) {
channelSpecs = new ChannelSpec[0][0];
}
@@ -219,7 +219,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
mPnoScanStateMachine.sendMessage(Message.obtain(msg));
mLastCallerInfoManager.put(WifiManager.API_SCANNING_ENABLED, tid,
Binder.getCallingUid(), Binder.getCallingPid(), packageName, enable);
- });
+ }, TAG + "#setScanningEnabled");
return true;
}
@@ -250,7 +250,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
logScanRequest("registerScanListener", client, null, null, null);
mSingleScanListeners.addRequest(client, null, null);
client.replySucceeded();
- });
+ }, TAG + "#registerScanListener");
}
@Override
@@ -277,7 +277,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
logScanRequest("deregisterScanListener", client, null, null, null);
mSingleScanListeners.removeRequest(client);
client.cleanup();
- });
+ }, TAG + "#unregisterScanListener");
}
@Override
@@ -307,7 +307,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
msg.obj = new ScanParams(listener, settings, workSource);
msg.sendingUid = uid;
mBackgroundScanStateMachine.sendMessage(msg);
- });
+ }, TAG + "#startBackgroundScan");
}
@Override
@@ -409,7 +409,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
msg.obj = new ScanParams(listener, settings, workSource);
msg.sendingUid = uid;
mSingleScanStateMachine.sendMessage(msg);
- });
+ }, TAG + "#startScan");
}
@Override
@@ -437,7 +437,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
msg.obj = new ScanParams(listener, null, null);
msg.sendingUid = uid;
mSingleScanStateMachine.sendMessage(msg);
- });
+ }, TAG + "#stopScan");
}
@Override
@@ -455,7 +455,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
return new ArrayList<>();
}
return mWifiThreadRunner.call(() -> mSingleScanStateMachine.filterCachedScanResultsByAge(),
- new ArrayList<ScanResult>());
+ new ArrayList<ScanResult>(), TAG + "#getSingleScanResults");
}
@@ -477,7 +477,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
} catch (RemoteException e) {
Log.e(TAG, e.getMessage(), e);
}
- });
+ }, TAG + "#getCachedScanData");
}
@Override
@@ -507,7 +507,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
msg.obj = new ScanParams(listener, scanSettings, pnoSettings, null, packageName, null);
msg.sendingUid = uid;
mPnoScanStateMachine.sendMessage(msg);
- });
+ }, TAG + "#startPnoScan");
}
@Override
@@ -539,7 +539,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
msg.obj = new ScanParams(listener, null, null);
msg.sendingUid = uid;
mPnoScanStateMachine.sendMessage(msg);
- });
+ }, TAG + "#stopPnoScan");
}
@Override
@@ -728,7 +728,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
mBackgroundScanStateMachine.start();
mSingleScanStateMachine.start();
mPnoScanStateMachine.start();
- });
+ }, TAG + "#startService");
}
/**
@@ -3083,7 +3083,7 @@ public class WifiScanningServiceImpl extends IWifiScanner.Stub {
Log.i(TAG, "binder died: client listener: " + mListener);
}
cleanup();
- });
+ }, TAG + "#binderDied");
}
};
diff --git a/service/java/com/android/server/wifi/util/ApConfigUtil.java b/service/java/com/android/server/wifi/util/ApConfigUtil.java
index f8528ac8c7..bbc8d4b5e3 100644
--- a/service/java/com/android/server/wifi/util/ApConfigUtil.java
+++ b/service/java/com/android/server/wifi/util/ApConfigUtil.java
@@ -47,11 +47,13 @@ import android.net.wifi.WifiClient;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiScanner;
+import android.net.wifi.nl80211.DeviceWiphyCapabilities;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.modules.utils.build.SdkLevel;
import com.android.server.wifi.SoftApManager;
import com.android.server.wifi.WifiNative;
@@ -809,6 +811,59 @@ public class ApConfigUtil {
}
/**
+ * As per IEEE specification, 11BE mode should be disabled for the following
+ * security types.
+ * - OPEN
+ * - WPA2-Personal
+ * Also, disable 11BE in OWE-Transition as SoftAp run in bridged mode with one instance in open
+ * mode.
+ */
+ @VisibleForTesting
+ static boolean is11beDisabledForSecurityType(
+ @SoftApConfiguration.SecurityType int type) {
+ switch(type) {
+ case SoftApConfiguration.SECURITY_TYPE_OPEN:
+ case SoftApConfiguration.SECURITY_TYPE_WPA2_PSK:
+ case SoftApConfiguration.SECURITY_TYPE_WPA3_OWE_TRANSITION:
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Check if IEEE80211BE is allowed for the given softAp configuration.
+ *
+ * @param capabilities capabilities of the device to check support for IEEE80211BE support.
+ * @param context The caller context used to get the OEM configuration for support for
+ * IEEE80211BE & single link MLO in bridged mode from the resource file.
+ * @param config The current {@link SoftApConfiguration}.
+ * @param isBridgedMode true if bridged mode is enabled, false otherwise.
+ *
+ * @return true if IEEE80211BE is allowed for the given configuration, false otherwise.
+ */
+ public static boolean is11beAllowedForThisConfiguration(DeviceWiphyCapabilities capabilities,
+ @NonNull Context context,
+ SoftApConfiguration config,
+ boolean isBridgedMode) {
+ if (!ApConfigUtil.isIeee80211beSupported(context)) {
+ return false;
+ }
+ if (capabilities == null || !capabilities.isWifiStandardSupported(
+ ScanResult.WIFI_STANDARD_11BE)) {
+ return false;
+ }
+ if (isBridgedMode
+ && !context.getResources().getBoolean(
+ R.bool.config_wifiSoftApSingleLinkMloInBridgedModeSupported)) {
+ return false;
+ }
+ if (is11beDisabledForSecurityType(config.getSecurityType())) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
* Update AP band and channel based on the provided country code and band.
* This will also set
* @param wifiNative reference to WifiNative
@@ -1088,6 +1143,19 @@ public class ApConfigUtil {
}});
}
+ /**
+ * Helper function to get whether or not device claim support bridged AP.
+ * (i.e. In resource file)
+ *
+ * @param context the caller context used to get value from resource file.
+ * @return true if supported, false otherwise.
+ */
+ public static boolean isBridgedModeSupportedInConfig(@NonNull Context context) {
+ return SdkLevel.isAtLeastS() && context.getResources().getBoolean(
+ R.bool.config_wifiBridgedSoftApSupported);
+ }
+
+
/**
* Helper function to get HAL support STA + bridged AP or not.
*
diff --git a/service/java/com/android/server/wifi/util/InformationElementUtil.java b/service/java/com/android/server/wifi/util/InformationElementUtil.java
index c72cb6ebcb..57643b9c01 100644
--- a/service/java/com/android/server/wifi/util/InformationElementUtil.java
+++ b/service/java/com/android/server/wifi/util/InformationElementUtil.java
@@ -1773,7 +1773,7 @@ public class InformationElementUtil {
private static final int FILS_CAPABILITY_BIT = 72;
private static final int TWT_REQUESTER_CAPABILITY_BIT = 77;
private static final int TWT_RESPONDER_CAPABILITY_BIT = 78;
- private static final int NO_TB_RANGING_RESPONDER = 90;
+ private static final int NON_TB_RANGING_RESPONDER = 90;
private static final int TB_RANGING_RESPONDER = 91;
public BitSet capabilitiesBitSet;
@@ -1782,7 +1782,7 @@ public class InformationElementUtil {
* @return true if Trigger based ranging responder supported. Refer P802.11az/D7.0,
* September 2022, section 9.4.2.26 Extended Capabilities element.
*/
- public boolean isTriggerBasedRangingRespSupported() {
+ public boolean is80211azTbResponder() {
return capabilitiesBitSet.get(TB_RANGING_RESPONDER);
}
@@ -1790,8 +1790,8 @@ public class InformationElementUtil {
* @return true if Non trigger based ranging responder supported. Refer P802.11az/D7.0,
* September 2022, section 9.4.2.26 Extended Capabilities element.
*/
- public boolean isNonTriggerBasedRangingRespSupported() {
- return capabilitiesBitSet.get(NO_TB_RANGING_RESPONDER);
+ public boolean is80211azNtbResponder() {
+ return capabilitiesBitSet.get(NON_TB_RANGING_RESPONDER);
}
/**
diff --git a/service/java/com/android/server/wifi/util/KeystoreWrapper.java b/service/java/com/android/server/wifi/util/KeystoreWrapper.java
index 2149b7d702..adb53af684 100644
--- a/service/java/com/android/server/wifi/util/KeystoreWrapper.java
+++ b/service/java/com/android/server/wifi/util/KeystoreWrapper.java
@@ -73,7 +73,7 @@ public class KeystoreWrapper {
return null;
}
Log.e(TAG, "Unexpected exception caught in getHmacSHA256ForUid", e);
- throw e;
+ return null;
}
}
diff --git a/service/java/com/android/server/wifi/util/RssiUtil.java b/service/java/com/android/server/wifi/util/RssiUtil.java
index 134970af59..aac8cd54a8 100644
--- a/service/java/com/android/server/wifi/util/RssiUtil.java
+++ b/service/java/com/android/server/wifi/util/RssiUtil.java
@@ -17,6 +17,7 @@ package com.android.server.wifi.util;
import android.annotation.NonNull;
import android.content.Context;
+import android.net.wifi.WifiInfo;
import com.android.wifi.resources.R;
@@ -24,6 +25,26 @@ import com.android.wifi.resources.R;
public class RssiUtil {
private RssiUtil() {}
+ /**
+ * Apply known fixes to a RSSi from signal poll and return INVALID_RSSI to indicate the data
+ * is invalid.
+ */
+ public static int calculateAdjustedRssi(int rssi) {
+ if (rssi > WifiInfo.INVALID_RSSI && rssi < WifiInfo.MAX_RSSI) {
+ /*
+ * Positive RSSI is possible when devices are close(~0m apart) to each other.
+ * And there are some driver/firmware implementation, where they avoid
+ * reporting large negative rssi values by adding 256.
+ * so adjust the valid rssi reports for such implementations.
+ */
+ if (rssi > (WifiInfo.INVALID_RSSI + 256)) {
+ return rssi - 256;
+ }
+ return rssi;
+ }
+ return WifiInfo.INVALID_RSSI;
+ }
+
/** Calculate RSSI level from RSSI using overlaid RSSI level thresholds. */
public static int calculateSignalLevel(Context context, int rssi) {
int[] thresholds = getRssiLevelThresholds(context);
diff --git a/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java b/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java
index 7eafbb9fb2..614b0df42d 100644
--- a/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java
+++ b/service/java/com/android/server/wifi/util/WifiPermissionsUtil.java
@@ -180,6 +180,7 @@ public class WifiPermissionsUtil {
try {
enforceNearbyDevicesPermission(attributionSource, checkForLocation, message);
} catch (SecurityException e) {
+ Log.e(TAG, "checkNearbyDevicesPermission - " + e);
return false;
}
return true;
@@ -914,20 +915,6 @@ public class WifiPermissionsUtil {
}
/**
- * Returns true if the |callingUid|/\callingPackage| holds SYSTEM_ALERT_WINDOW permission.
- */
- public boolean checkSystemAlertWindowPermission(int callingUid, String callingPackage) {
- final int mode = mAppOps.noteOpNoThrow(AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW, callingUid,
- callingPackage, null, null);
- if (mode == AppOpsManager.MODE_DEFAULT) {
- return mWifiPermissionsWrapper.getUidPermission(
- Manifest.permission.SYSTEM_ALERT_WINDOW, callingUid)
- == PackageManager.PERMISSION_GRANTED;
- }
- return mode == AppOpsManager.MODE_ALLOWED;
- }
-
- /**
* Returns the DevicePolicyManager from context
*/
public static DevicePolicyManager retrieveDevicePolicyManagerFromContext(Context context) {
diff --git a/service/java/com/android/server/wifi/util/XmlUtil.java b/service/java/com/android/server/wifi/util/XmlUtil.java
index 9dc3bbf248..e0bb9e5f28 100644
--- a/service/java/com/android/server/wifi/util/XmlUtil.java
+++ b/service/java/com/android/server/wifi/util/XmlUtil.java
@@ -29,6 +29,7 @@ import android.net.ProxyInfo;
import android.net.RouteInfo;
import android.net.StaticIpConfiguration;
import android.net.Uri;
+import android.net.wifi.OuiKeyedData;
import android.net.wifi.ScanResult;
import android.net.wifi.SecurityParams;
import android.net.wifi.SoftApConfiguration;
@@ -39,6 +40,7 @@ import android.net.wifi.WifiManager;
import android.net.wifi.WifiMigration;
import android.net.wifi.WifiSsid;
import android.os.ParcelUuid;
+import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
@@ -50,6 +52,8 @@ import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
@@ -86,6 +90,11 @@ import java.util.Locale;
public class XmlUtil {
private static final String TAG = "WifiXmlUtil";
+ public static final String XML_TAG_VENDOR_DATA_LIST = "VendorDataList";
+ public static final String XML_TAG_OUI_KEYED_DATA = "OuiKeyedData";
+ public static final String XML_TAG_VENDOR_DATA_OUI = "VendorDataOui";
+ public static final String XML_TAG_PERSISTABLE_BUNDLE = "PersistableBundle";
+
/**
* Ensure that the XML stream is at a start tag or the end of document.
*
@@ -688,6 +697,9 @@ public class XmlUtil {
.getBssidAllowlistInternal()));
}
writeDppConfigurationToXml(out, configuration, encryptionUtil);
+ if (SdkLevel.isAtLeastV()) {
+ writeVendorDataListToXml(out, configuration.getVendorData());
+ }
}
private static List<String> covertMacAddressListToStringList(List<MacAddress> macList) {
@@ -1120,6 +1132,12 @@ public class XmlUtil {
dppNetAccessKey = readEncrytepdBytesFromXml(encryptionUtil, in,
outerTagDepth);
break;
+ case XML_TAG_VENDOR_DATA_LIST:
+ if (SdkLevel.isAtLeastV()) {
+ configuration.setVendorData(
+ parseVendorDataListFromXml(in, outerTagDepth + 1));
+ }
+ break;
default:
Log.w(TAG, "Ignoring unknown tag found: " + tagName);
break;
@@ -2178,6 +2196,9 @@ public class XmlUtil {
softApConfig.getPersistentRandomizedMacAddress().toString());
}
}
+ if (SdkLevel.isAtLeastV()) {
+ writeVendorDataListToXml(out, softApConfig.getVendorData());
+ }
} // End of writeSoftApConfigurationToXml
/**
@@ -2373,6 +2394,12 @@ public class XmlUtil {
passphrase = readSoftApPassphraseFromXml(in, outerTagDepth,
shouldExpectEncryptedCredentials, encryptionUtil);
break;
+ case XML_TAG_VENDOR_DATA_LIST:
+ if (SdkLevel.isAtLeastV()) {
+ softApConfigBuilder.setVendorData(
+ parseVendorDataListFromXml(in, outerTagDepth + 1));
+ }
+ break;
default:
Log.w(TAG, "Ignoring unknown tag found: " + tagName);
break;
@@ -2461,5 +2488,118 @@ public class XmlUtil {
return new String(passphraseBytes);
}
}
-}
+ /**
+ * Write the provided vendor data list to XML.
+ *
+ * @param out XmlSerializer instance pointing to the XML stream
+ * @param vendorDataList Vendor data list
+ */
+ private static void writeVendorDataListToXml(
+ XmlSerializer out, List<OuiKeyedData> vendorDataList)
+ throws XmlPullParserException, IOException {
+ if (vendorDataList == null || vendorDataList.isEmpty()) {
+ return;
+ }
+ XmlUtil.writeNextSectionStart(out, XML_TAG_VENDOR_DATA_LIST);
+ for (OuiKeyedData data : vendorDataList) {
+ writeOuiKeyedDataToXml(out, data);
+ }
+ XmlUtil.writeNextSectionEnd(out, XML_TAG_VENDOR_DATA_LIST);
+ }
+
+ private static void writeOuiKeyedDataToXml(
+ XmlSerializer out, OuiKeyedData ouiKeyedData)
+ throws XmlPullParserException, IOException {
+ // PersistableBundle cannot be written directly to XML
+ // Use byte[] as an intermediate data structure
+ if (ouiKeyedData == null) return;
+ byte[] bundleBytes;
+ try {
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ ouiKeyedData.getData().writeToStream(outputStream);
+ bundleBytes = outputStream.toByteArray();
+ } catch (Exception e) {
+ Log.e(TAG, "Unable to write PersistableBundle to byte[]");
+ return;
+ }
+ XmlUtil.writeNextSectionStart(out, XML_TAG_OUI_KEYED_DATA);
+ XmlUtil.writeNextValue(out, XML_TAG_VENDOR_DATA_OUI, ouiKeyedData.getOui());
+ XmlUtil.writeNextValue(out, XML_TAG_PERSISTABLE_BUNDLE, bundleBytes);
+ XmlUtil.writeNextSectionEnd(out, XML_TAG_OUI_KEYED_DATA);
+ }
+
+ /**
+ * Parses the vendor data list from the provided XML stream .
+ *
+ * @param in XmlPullParser instance pointing to the XML stream
+ * @param outerTagDepth depth of the outer tag in the XML document
+ * @return List of OuiKeyedData if successful, empty list otherwise
+ */
+ private static List<OuiKeyedData> parseVendorDataListFromXml(
+ XmlPullParser in, int outerTagDepth)
+ throws XmlPullParserException, IOException, IllegalArgumentException {
+ List<OuiKeyedData> vendorDataList = new ArrayList<>();
+ while (!XmlUtil.isNextSectionEnd(in, outerTagDepth)) {
+ String tagName = in.getName();
+ if (tagName == null) {
+ throw new XmlPullParserException("Unexpected null tag found");
+ }
+ switch (tagName) {
+ case XML_TAG_OUI_KEYED_DATA:
+ OuiKeyedData data = parseOuiKeyedDataFromXml(in, outerTagDepth + 1);
+ if (data != null) {
+ vendorDataList.add(data);
+ }
+ break;
+ default:
+ Log.w(TAG, "Ignoring unknown tag found: " + tagName);
+ break;
+ }
+ }
+ return vendorDataList;
+ }
+
+ private static PersistableBundle readPersistableBundleFromBytes(byte[] bundleBytes) {
+ try {
+ ByteArrayInputStream inputStream = new ByteArrayInputStream(bundleBytes);
+ return PersistableBundle.readFromStream(inputStream);
+ } catch (Exception e) {
+ Log.e(TAG, "Unable to read PersistableBundle from byte[]");
+ return null;
+ }
+ }
+
+ private static OuiKeyedData parseOuiKeyedDataFromXml(
+ XmlPullParser in, int outerTagDepth)
+ throws XmlPullParserException, IOException, IllegalArgumentException {
+ int oui = 0;
+ PersistableBundle bundle = null;
+
+ while (!XmlUtil.isNextSectionEnd(in, outerTagDepth)) {
+ String[] valueName = new String[1];
+ Object value = XmlUtil.readCurrentValue(in, valueName);
+ if (valueName[0] == null) {
+ throw new XmlPullParserException("Missing value name");
+ }
+ switch (valueName[0]) {
+ case XML_TAG_VENDOR_DATA_OUI:
+ oui = (int) value;
+ break;
+ case XML_TAG_PERSISTABLE_BUNDLE:
+ bundle = readPersistableBundleFromBytes((byte[]) value);
+ break;
+ default:
+ Log.e(TAG, "Unknown value name found: " + valueName[0]);
+ break;
+ }
+ }
+
+ try {
+ return new OuiKeyedData.Builder(oui, bundle).build();
+ } catch (Exception e) {
+ Log.e(TAG, "Unable to build OuiKeyedData");
+ return null;
+ }
+ }
+}
diff --git a/service/proto/src/metrics.proto b/service/proto/src/metrics.proto
index 9183dc7b4a..a27864fb87 100644
--- a/service/proto/src/metrics.proto
+++ b/service/proto/src/metrics.proto
@@ -3071,6 +3071,9 @@ message P2pConnectionEvent {
// The try count of connection
optional int32 try_count = 13;
+
+ // The Attribution tag to identify the caller
+ optional string attribution_tag = 14;
}
// GroupEvent tracking group information from GroupStarted to GroupRemoved.
diff --git a/service/tests/wifitests/Android.bp b/service/tests/wifitests/Android.bp
index bd82d8d7b9..7349dcbdb0 100644
--- a/service/tests/wifitests/Android.bp
+++ b/service/tests/wifitests/Android.bp
@@ -98,9 +98,33 @@ android_test {
"com.android.server.wifi.AdaptiveConnectivityEnabledSettingObserver",
"com.android.server.wifi.AdaptiveConnectivityEnabledSettingObserver$*",
"com.android.server.wifi.AdaptiveConnectivityEnabledSettingObserver.**",
+ "com.android.server.wifi.AfcClient",
+ "com.android.server.wifi.AfcClient$*",
+ "com.android.server.wifi.AfcClient.**",
+ "com.android.server.wifi.AfcEllipseLocation",
+ "com.android.server.wifi.AfcEllipseLocation$*",
+ "com.android.server.wifi.AfcEllipseLocation.**",
+ "com.android.server.wifi.AfcLocation",
+ "com.android.server.wifi.AfcLocation$*",
+ "com.android.server.wifi.AfcLocation.**",
+ "com.android.server.wifi.AfcLocationUtil",
+ "com.android.server.wifi.AfcLocationUtil$*",
+ "com.android.server.wifi.AfcLocationUtil.**",
+ "com.android.server.wifi.AfcManager",
+ "com.android.server.wifi.AfcManager$*",
+ "com.android.server.wifi.AfcManager.**",
+ "com.android.server.wifi.AfcServerResponse",
+ "com.android.server.wifi.AfcServerResponse$*",
+ "com.android.server.wifi.AfcServerResponse.**",
"com.android.server.wifi.AggressiveConnectedScore",
"com.android.server.wifi.AggressiveConnectedScore$*",
"com.android.server.wifi.AggressiveConnectedScore.**",
+ "com.android.server.wifi.ApplicationQosPolicyRequestHandler",
+ "com.android.server.wifi.ApplicationQosPolicyRequestHandler$*",
+ "com.android.server.wifi.ApplicationQosPolicyRequestHandler.**",
+ "com.android.server.wifi.ApplicationQosPolicyTrackingTable",
+ "com.android.server.wifi.ApplicationQosPolicyTrackingTable$*",
+ "com.android.server.wifi.ApplicationQosPolicyTrackingTable.**",
"com.android.server.wifi.AssocRejectEventInfo",
"com.android.server.wifi.AssocRejectEventInfo$*",
"com.android.server.wifi.AssocRejectEventInfo.**",
@@ -113,6 +137,9 @@ android_test {
"com.android.server.wifi.BackupManagerProxy",
"com.android.server.wifi.BackupManagerProxy$*",
"com.android.server.wifi.BackupManagerProxy.**",
+ "com.android.server.wifi.BackupRestoreController",
+ "com.android.server.wifi.BackupRestoreController$*",
+ "com.android.server.wifi.BackupRestoreController.**",
"com.android.server.wifi.BubbleFunScorer",
"com.android.server.wifi.BubbleFunScorer$*",
"com.android.server.wifi.BubbleFunScorer.**",
@@ -123,7 +150,7 @@ android_test {
"com.android.server.wifi.ByteBufferReader$*",
"com.android.server.wifi.ByteBufferReader.**",
"com.android.server.wifi.CertificateEventInfo",
- "com.android.server.wifi.CertificateEventInfo*",
+ "com.android.server.wifi.CertificateEventInfo$*",
"com.android.server.wifi.CertificateEventInfo.**",
"com.android.server.wifi.ClientMode",
"com.android.server.wifi.ClientMode$*",
@@ -188,9 +215,6 @@ android_test {
"com.android.server.wifi.DppMetrics",
"com.android.server.wifi.DppMetrics$*",
"com.android.server.wifi.DppMetrics.**",
- "com.android.server.wifi.DtimMultiplierController",
- "com.android.server.wifi.DtimMultiplierController$*",
- "com.android.server.wifi.DtimMultiplierController.**",
"com.android.server.wifi.EapFailureNotifier",
"com.android.server.wifi.EapFailureNotifier$*",
"com.android.server.wifi.EapFailureNotifier.**",
@@ -245,9 +269,6 @@ android_test {
"com.android.server.wifi.LastMileLogger",
"com.android.server.wifi.LastMileLogger$*",
"com.android.server.wifi.LastMileLogger.**",
- "com.android.server.wifi.LinkProbeManager",
- "com.android.server.wifi.LinkProbeManager$*",
- "com.android.server.wifi.LinkProbeManager.**",
"com.android.server.wifi.LocalOnlyHotspotRequestInfo",
"com.android.server.wifi.LocalOnlyHotspotRequestInfo$*",
"com.android.server.wifi.LocalOnlyHotspotRequestInfo.**",
@@ -455,6 +476,9 @@ android_test {
"com.android.server.wifi.ThroughputScorer",
"com.android.server.wifi.ThroughputScorer$*",
"com.android.server.wifi.ThroughputScorer.**",
+ "com.android.server.wifi.TwtManager",
+ "com.android.server.wifi.TwtManager$*",
+ "com.android.server.wifi.TwtManager.**",
"com.android.server.wifi.UntrustedWifiNetworkFactory",
"com.android.server.wifi.UntrustedWifiNetworkFactory$*",
"com.android.server.wifi.UntrustedWifiNetworkFactory.**",
@@ -527,6 +551,9 @@ android_test {
"com.android.server.wifi.WifiDataStall",
"com.android.server.wifi.WifiDataStall$*",
"com.android.server.wifi.WifiDataStall.**",
+ "com.android.server.wifi.WifiDeviceStateChangeManager",
+ "com.android.server.wifi.WifiDeviceStateChangeManager$*",
+ "com.android.server.wifi.WifiDeviceStateChangeManager.**",
"com.android.server.wifi.WifiDiagnostics",
"com.android.server.wifi.WifiDiagnostics$*",
"com.android.server.wifi.WifiDiagnostics.**",
@@ -599,6 +626,12 @@ android_test {
"com.android.server.wifi.WifiPseudonymManager",
"com.android.server.wifi.WifiPseudonymManager$*",
"com.android.server.wifi.WifiPseudonymManager.**",
+ "com.android.server.wifi.WifiPulledAtomLogger",
+ "com.android.server.wifi.WifiPulledAtomLogger$*",
+ "com.android.server.wifi.WifiPulledAtomLogger.**",
+ "com.android.server.wifi.WifiRoamingConfigStore",
+ "com.android.server.wifi.WifiRoamingConfigStore$*",
+ "com.android.server.wifi.WifiRoamingConfigStore.**",
"com.android.server.wifi.WifiScanAlwaysAvailableSettingsCompatibility",
"com.android.server.wifi.WifiScanAlwaysAvailableSettingsCompatibility$*",
"com.android.server.wifi.WifiScanAlwaysAvailableSettingsCompatibility.**",
@@ -614,6 +647,9 @@ android_test {
"com.android.server.wifi.WifiServiceImpl",
"com.android.server.wifi.WifiServiceImpl$*",
"com.android.server.wifi.WifiServiceImpl.**",
+ "com.android.server.wifi.WifiSettingsBackupRestore",
+ "com.android.server.wifi.WifiSettingsBackupRestore$*",
+ "com.android.server.wifi.WifiSettingsBackupRestore.**",
"com.android.server.wifi.WifiSettingsConfigStore",
"com.android.server.wifi.WifiSettingsConfigStore$*",
"com.android.server.wifi.WifiSettingsConfigStore.**",
@@ -686,6 +722,9 @@ android_test {
"com.android.server.wifi.aware.WifiAwareStateManager",
"com.android.server.wifi.aware.WifiAwareStateManager$*",
"com.android.server.wifi.aware.WifiAwareStateManager.**",
+ "com.android.server.wifi.b2b.WifiRoamingModeManager",
+ "com.android.server.wifi.b2b.WifiRoamingModeManager$*",
+ "com.android.server.wifi.b2b.WifiRoamingModeManager.**",
"com.android.server.wifi.coex.CoexManager",
"com.android.server.wifi.coex.CoexManager$*",
"com.android.server.wifi.coex.CoexManager.**",
@@ -1043,6 +1082,9 @@ android_test {
"com.android.server.wifi.hotspot2.soap.command.SppCommand",
"com.android.server.wifi.hotspot2.soap.command.SppCommand$*",
"com.android.server.wifi.hotspot2.soap.command.SppCommand.**",
+ "com.android.server.wifi.mockwifi.MockSupplicantManager",
+ "com.android.server.wifi.mockwifi.MockSupplicantManager$*",
+ "com.android.server.wifi.mockwifi.MockSupplicantManager.**",
"com.android.server.wifi.mockwifi.MockWifiNl80211Manager",
"com.android.server.wifi.mockwifi.MockWifiNl80211Manager$*",
"com.android.server.wifi.mockwifi.MockWifiNl80211Manager.**",
diff --git a/service/tests/wifitests/src/com/android/server/wifi/ActiveModeWardenTest.java b/service/tests/wifitests/src/com/android/server/wifi/ActiveModeWardenTest.java
index fd98347e3b..78f28fb507 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/ActiveModeWardenTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/ActiveModeWardenTest.java
@@ -188,6 +188,8 @@ public class ActiveModeWardenTest extends WifiBaseTest {
@Mock WifiSettingsConfigStore mSettingsConfigStore;
@Mock LastCallerInfoManager mLastCallerInfoManager;
@Mock WifiGlobals mWifiGlobals;
+ @Mock WifiConnectivityManager mWifiConnectivityManager;
+ @Mock WifiConfigManager mWifiConfigManager;
Listener<ConcreteClientModeManager> mClientListener;
Listener<SoftApManager> mSoftApListener;
@@ -220,6 +222,8 @@ public class ActiveModeWardenTest extends WifiBaseTest {
when(mWifiInjector.getHalDeviceManager()).thenReturn(mHalDeviceManager);
when(mWifiInjector.getUserManager()).thenReturn(mUserManager);
when(mWifiInjector.getWifiHandlerLocalLog()).thenReturn(mLocalLog);
+ when(mWifiInjector.getWifiConnectivityManager()).thenReturn(mWifiConnectivityManager);
+ when(mWifiInjector.getWifiConfigManager()).thenReturn(mWifiConfigManager);
when(mClientModeManager.getRole()).thenReturn(ROLE_CLIENT_PRIMARY);
when(mClientModeManager.getInterfaceName()).thenReturn(WIFI_IFACE_NAME);
when(mContext.getResources()).thenReturn(mResources);
@@ -276,7 +280,7 @@ public class ActiveModeWardenTest extends WifiBaseTest {
mLooper.dispatchAll();
verify(mWifiMetrics).noteWifiEnabledDuringBoot(false);
-
+ verify(mWifiGlobals).setD2dStaConcurrencySupported(false);
verify(mWifiNative).registerStatusListener(mStatusListenerCaptor.capture());
verify(mWifiNative).initialize();
mWifiNativeStatusListener = mStatusListenerCaptor.getValue();
@@ -377,6 +381,8 @@ public class ActiveModeWardenTest extends WifiBaseTest {
when(mSettingsStore.isWifiToggleEnabled()).thenReturn(true);
mActiveModeWarden.wifiToggled(TEST_WORKSOURCE);
mLooper.dispatchAll();
+ assertNull(mActiveModeWarden.getCurrentNetwork());
+
when(mClientModeManager.getRole()).thenReturn(ROLE_CLIENT_PRIMARY);
when(mClientModeManager.getCurrentNetwork()).thenReturn(mNetwork);
when(mWifiNative.getSupportedFeatureSet(WIFI_IFACE_NAME)).thenReturn(testFeatureSet);
@@ -404,6 +410,7 @@ public class ActiveModeWardenTest extends WifiBaseTest {
verify(mScanRequestProxy, times(4)).enableScanning(true, true);
assertEquals(mClientModeManager, mActiveModeWarden.getPrimaryClientModeManager());
verify(mModeChangeCallback).onActiveModeManagerRoleChanged(mClientModeManager);
+ assertEquals(mNetwork, mActiveModeWarden.getCurrentNetwork());
}
private void enterScanOnlyModeActiveState() throws Exception {
@@ -802,6 +809,7 @@ public class ActiveModeWardenTest extends WifiBaseTest {
assertTrue(currentCMMs.stream().anyMatch(cmm -> cmm.getRole() == ROLE_CLIENT_PRIMARY));
assertTrue(currentCMMs.stream().anyMatch(
cmm -> cmm.getRole() == ROLE_CLIENT_SECONDARY_TRANSIENT));
+ verify(mWifiConnectivityManager, never()).resetOnWifiDisable();
InOrder inOrder = inOrder(additionalClientModeManager, mClientModeManager);
// disable wifi and switch primary CMM to scan only mode
@@ -816,6 +824,7 @@ public class ActiveModeWardenTest extends WifiBaseTest {
// mode
inOrder.verify(additionalClientModeManager).stop();
inOrder.verify(mClientModeManager).setRole(ROLE_CLIENT_SCAN_ONLY, INTERNAL_REQUESTOR_WS);
+ verify(mWifiConnectivityManager).resetOnWifiDisable();
}
/**
@@ -1156,6 +1165,7 @@ public class ActiveModeWardenTest extends WifiBaseTest {
verify(mWifiNative).isStaApConcurrencySupported();
verify(mWifiNative).isStaStaConcurrencySupported();
verify(mWifiNative).isP2pStaConcurrencySupported();
+ verify(mWifiNative).isNanStaConcurrencySupported();
verifyZeroInteractions(mWifiNative);
}
@@ -1170,6 +1180,7 @@ public class ActiveModeWardenTest extends WifiBaseTest {
verify(mWifiDiagnostics).triggerBugReportDataCapture(
WifiDiagnostics.REPORT_REASON_WIFINATIVE_FAILURE);
verify(mSelfRecovery).trigger(eq(SelfRecovery.REASON_WIFINATIVE_FAILURE));
+ verify(mWifiConfigManager).writeDataToStorage();
}
/**
@@ -1183,6 +1194,7 @@ public class ActiveModeWardenTest extends WifiBaseTest {
verify(mWifiDiagnostics, never()).triggerBugReportDataCapture(
WifiDiagnostics.REPORT_REASON_WIFINATIVE_FAILURE);
verify(mSelfRecovery, never()).trigger(eq(SelfRecovery.REASON_WIFINATIVE_FAILURE));
+ verify(mWifiConfigManager, never()).writeDataToStorage();
}
/**
@@ -1195,6 +1207,7 @@ public class ActiveModeWardenTest extends WifiBaseTest {
verify(mWifiDiagnostics, never()).triggerBugReportDataCapture(
WifiDiagnostics.REPORT_REASON_WIFINATIVE_FAILURE);
verify(mSelfRecovery, never()).trigger(eq(SelfRecovery.REASON_WIFINATIVE_FAILURE));
+ verify(mWifiConfigManager, never()).writeDataToStorage();
}
/**
@@ -2687,7 +2700,6 @@ public class ActiveModeWardenTest extends WifiBaseTest {
verify(mClientModeManager, atLeastOnce()).getInterfaceName();
verify(mClientModeManager, atLeastOnce()).getPreviousRole();
- verifyNoMoreInteractions(mClientModeManager, mSoftApManager);
}
/**
@@ -3098,7 +3110,8 @@ public class ActiveModeWardenTest extends WifiBaseTest {
assertEquals(additionalClientModeManager, requestedClientModeManager.getValue());
// the additional CMM never became primary
verify(mPrimaryChangedCallback, never()).onChange(any(), eq(additionalClientModeManager));
- if (additionaClientModeManagerRole == ROLE_CLIENT_LOCAL_ONLY) {
+ if (additionaClientModeManagerRole == ROLE_CLIENT_LOCAL_ONLY
+ || additionaClientModeManagerRole == ROLE_CLIENT_SECONDARY_LONG_LIVED) {
assertEquals(Set.of(TEST_WORKSOURCE), mActiveModeWarden.getSecondaryRequestWs());
}
return additionalClientListener.value;
@@ -5060,10 +5073,29 @@ public class ActiveModeWardenTest extends WifiBaseTest {
mClientListener.onStopped(mClientModeManager);
mLooper.dispatchAll();
assertInDisabledState();
+ verify(mLastCallerInfoManager).put(eq(WifiManager.API_WIFI_ENABLED), anyInt(),
+ anyInt(), anyInt(), any(), eq(false));
}
@Test
- public void testSatelliteModeOffEnableWifi() throws Exception {
+ public void testSatelliteModeOffNoOp() throws Exception {
+ // Wifi is enabled
+ enterClientModeActiveState();
+ assertInEnabledState();
+
+ // Satellite mode is off
+ when(mSettingsStore.isSatelliteModeOn()).thenReturn(false);
+ mActiveModeWarden.handleSatelliteModeChange();
+
+ mLooper.dispatchAll();
+ assertInEnabledState();
+ // Should not enable wifi again since wifi is already on
+ verify(mLastCallerInfoManager, never()).put(eq(WifiManager.API_WIFI_ENABLED), anyInt(),
+ anyInt(), anyInt(), any(), eq(true));
+ }
+
+ @Test
+ public void testSatelliteModeOnAndThenOffEnableWifi() throws Exception {
// Wifi is enabled
enterClientModeActiveState();
assertInEnabledState();
@@ -5077,12 +5109,16 @@ public class ActiveModeWardenTest extends WifiBaseTest {
mClientListener.onStopped(mClientModeManager);
mLooper.dispatchAll();
assertInDisabledState();
+ verify(mLastCallerInfoManager).put(eq(WifiManager.API_WIFI_ENABLED), anyInt(),
+ anyInt(), anyInt(), any(), eq(false));
// Satellite mode is off, enable Wifi
when(mSettingsStore.isSatelliteModeOn()).thenReturn(false);
mActiveModeWarden.handleSatelliteModeChange();
mLooper.dispatchAll();
assertInEnabledState();
+ verify(mLastCallerInfoManager).put(eq(WifiManager.API_WIFI_ENABLED), anyInt(),
+ anyInt(), anyInt(), any(), eq(true));
}
@@ -5347,11 +5383,25 @@ public class ActiveModeWardenTest extends WifiBaseTest {
}
@Test
- public void testD2dSupportedWhenInfraStaDisabled() throws Exception {
+ public void testD2dSupportedWhenInfraStaDisabledWhenP2pStaConcurrencySupported()
+ throws Exception {
when(mWifiNative.isP2pStaConcurrencySupported()).thenReturn(true);
when(mWifiGlobals.isD2dSupportedWhenInfraStaDisabled()).thenReturn(true);
mActiveModeWarden = createActiveModeWarden();
mActiveModeWarden.start();
+ mLooper.dispatchAll();
+ verify(mWifiGlobals).setD2dStaConcurrencySupported(true);
+ verify(mWifiGlobals, atLeastOnce()).isD2dSupportedWhenInfraStaDisabled();
+ }
+
+ @Test
+ public void testD2dSupportedWhenInfraStaDisabledWhenNanStaConcurrencySupported()
+ throws Exception {
+ when(mWifiNative.isNanStaConcurrencySupported()).thenReturn(true);
+ when(mWifiGlobals.isD2dSupportedWhenInfraStaDisabled()).thenReturn(true);
+ mActiveModeWarden = createActiveModeWarden();
+ mActiveModeWarden.start();
+ mLooper.dispatchAll();
verify(mWifiGlobals).setD2dStaConcurrencySupported(true);
verify(mWifiGlobals, atLeastOnce()).isD2dSupportedWhenInfraStaDisabled();
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/ApplicationQosPolicyRequestHandlerTest.java b/service/tests/wifitests/src/com/android/server/wifi/ApplicationQosPolicyRequestHandlerTest.java
index c827837b83..5342efbafd 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/ApplicationQosPolicyRequestHandlerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/ApplicationQosPolicyRequestHandlerTest.java
@@ -652,7 +652,7 @@ public class ApplicationQosPolicyRequestHandlerTest {
/**
* Tests that uplink policies are only included in the queueAllPolicies request
- * if the includeUplink parameter is true.
+ * if the current AP supports QosCharacteristics.
*/
@Test
public void testQueueAllPoliciesRequest_mixedDirection() {
@@ -665,7 +665,8 @@ public class ApplicationQosPolicyRequestHandlerTest {
addPoliciesToTable(createUplinkPolicyList(numUplinkPolicies,
TEST_POLICY_ID_START + numDownlinkPolicies));
- // Only downlink policies.
+ // Expect that only the downlink policies are sent to the HAL
+ // if the current AP does not support QosCharacteristics.
mDut.queueAllPoliciesOnIface(TEST_IFACE_NAME_0, false);
verify(mWifiNative, atLeastOnce()).addQosPolicyRequestForScs(
eq(TEST_IFACE_NAME_0), mPolicyListCaptor.capture());
@@ -675,10 +676,19 @@ public class ApplicationQosPolicyRequestHandlerTest {
triggerAndVerifyApCallback(TEST_IFACE_NAME_0, mPolicyListCaptor.getValue(),
SupplicantStaIfaceHal.QOS_POLICY_SCS_RESPONSE_STATUS_SUCCESS);
- // Both uplink and downlink policies included in the request.
+ // If the current AP supports QosCharacteristics, expect that both uplink
+ // and downlink policies are sent (albeit in separate transactions).
+ // Downlink policies will be sent first.
mDut.queueAllPoliciesOnIface(TEST_IFACE_NAME_0, true);
verify(mWifiNative, atLeastOnce()).addQosPolicyRequestForScs(
eq(TEST_IFACE_NAME_0), mPolicyListCaptor.capture());
- assertEquals(numDownlinkPolicies + numUplinkPolicies, mPolicyListCaptor.getValue().size());
+ assertEquals(numDownlinkPolicies, mPolicyListCaptor.getValue().size());
+
+ // Trigger callback and check that the uplink policies are sent next.
+ triggerAndVerifyApCallback(TEST_IFACE_NAME_0, mPolicyListCaptor.getValue(),
+ SupplicantStaIfaceHal.QOS_POLICY_SCS_RESPONSE_STATUS_SUCCESS);
+ verify(mWifiNative, atLeastOnce()).addQosPolicyRequestForScs(
+ eq(TEST_IFACE_NAME_0), mPolicyListCaptor.capture());
+ assertEquals(numUplinkPolicies, mPolicyListCaptor.getValue().size());
}
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/ApplicationQosPolicyTrackingTableTest.java b/service/tests/wifitests/src/com/android/server/wifi/ApplicationQosPolicyTrackingTableTest.java
index 07596e465e..5a8b75a74a 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/ApplicationQosPolicyTrackingTableTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/ApplicationQosPolicyTrackingTableTest.java
@@ -281,53 +281,53 @@ public class ApplicationQosPolicyTrackingTableTest {
}
/**
- * Tests the {@link ApplicationQosPolicyTrackingTable#getAllPolicies(int)} method when
- * all policies have the same direction.
+ * Tests the {@link ApplicationQosPolicyTrackingTable#getAllPolicies(boolean)} method when
+ * no policies contain QosCharacteristics.
*/
@Test
- public void testGetAllPoliciesSameDirection() {
+ public void testGetAllPolicies_noQosChars() {
// Empty table should return an empty list.
- List<QosPolicyParams> retrievedPolicies =
- mDut.getAllPolicies(QosPolicyParams.DIRECTION_DOWNLINK);
+ List<QosPolicyParams> retrievedPolicies = mDut.getAllPolicies(false);
assertTrue(retrievedPolicies.isEmpty());
// Fill table with downlink policies from multiple requesters.
+ // No policies contain QosCharacteristics.
List<QosPolicyParams> policyList = generatePolicyList(
NUM_VIRTUAL_POLICY_IDS / 2, TEST_PHYSICAL_POLICY_ID_START);
mDut.addPolicies(policyList, TEST_UID);
mDut.addPolicies(policyList, TEST_UID + 1);
// getAllPolicies should return all policies across all requesters.
- retrievedPolicies = mDut.getAllPolicies(QosPolicyParams.DIRECTION_DOWNLINK);
+ retrievedPolicies = mDut.getAllPolicies(false);
assertEquals(NUM_VIRTUAL_POLICY_IDS, retrievedPolicies.size());
}
/**
- * Tests the {@link ApplicationQosPolicyTrackingTable#getAllPolicies(int)} method when
- * the policies in the table have different directions.
+ * Tests the {@link ApplicationQosPolicyTrackingTable#getAllPolicies(boolean)} method when
+ * some policies in the table contain QosCharacteristics and others do not.
*/
@Test
- public void testGetAllPoliciesDifferentDirection() {
+ public void testGetAllPolicies_filteredByQosChars() {
assumeTrue(SdkLevel.isAtLeastV());
- List<QosPolicyParams> downlinkPolicies = generatePolicyList(
+ List<QosPolicyParams> policiesWithoutQosChars = generatePolicyList(
NUM_VIRTUAL_POLICY_IDS / 2, TEST_PHYSICAL_POLICY_ID_START);
- mDut.addPolicies(downlinkPolicies, TEST_UID);
+ mDut.addPolicies(policiesWithoutQosChars, TEST_UID);
- // Table should contain several downlink and no uplink policies.
- List<QosPolicyParams> retrievedPolicies =
- mDut.getAllPolicies(QosPolicyParams.DIRECTION_DOWNLINK);
- assertEquals(downlinkPolicies.size(), retrievedPolicies.size());
- retrievedPolicies = mDut.getAllPolicies(QosPolicyParams.DIRECTION_UPLINK);
+ // Table should contain no policies with QosCharacteristics.
+ List<QosPolicyParams> retrievedPolicies = mDut.getAllPolicies(false);
+ assertEquals(policiesWithoutQosChars.size(), retrievedPolicies.size());
+ retrievedPolicies = mDut.getAllPolicies(true);
assertEquals(0, retrievedPolicies.size());
- List<QosPolicyParams> uplinkPolicies = generateUplinkPolicyList(
+ // Uplink policies are guaranteed to contain QosCharacteristics.
+ List<QosPolicyParams> policiesWithQosChars = generateUplinkPolicyList(
NUM_VIRTUAL_POLICY_IDS / 2, TEST_PHYSICAL_POLICY_ID_START);
- mDut.addPolicies(uplinkPolicies, TEST_UID + 1);
+ mDut.addPolicies(policiesWithQosChars, TEST_UID + 1);
- // Table should contain both uplink and downlink policies.
- retrievedPolicies = mDut.getAllPolicies(QosPolicyParams.DIRECTION_DOWNLINK);
- assertEquals(downlinkPolicies.size(), retrievedPolicies.size());
- retrievedPolicies = mDut.getAllPolicies(QosPolicyParams.DIRECTION_UPLINK);
- assertEquals(uplinkPolicies.size(), retrievedPolicies.size());
+ // Table should contain both policies with and without QosCharacteristics.
+ retrievedPolicies = mDut.getAllPolicies(false);
+ assertEquals(policiesWithoutQosChars.size(), retrievedPolicies.size());
+ retrievedPolicies = mDut.getAllPolicies(true);
+ assertEquals(policiesWithQosChars.size(), retrievedPolicies.size());
}
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/BackupRestoreControllerTest.java b/service/tests/wifitests/src/com/android/server/wifi/BackupRestoreControllerTest.java
index df26af361a..47c61d620d 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/BackupRestoreControllerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/BackupRestoreControllerTest.java
@@ -37,9 +37,9 @@ public class BackupRestoreControllerTest extends WifiBaseTest {
public static final String TEST_WIFI_UNION_BACKUP_DATA_WITH_SETTINGS_IN_V =
XML_GENERAL_BEGINNING
- + "<WifiBackupDataUnion>\n"
+ + "<WifiSettingsBackupData>\n"
+ WifiSettingsBackupRestoreTest.generateTestWifiSettingsTestingXml("")
- + "</WifiBackupDataUnion>\n";
+ + "</WifiSettingsBackupData>\n";
@Mock WifiSettingsBackupRestore mWifiSettingsBackupRestore;
@Mock Clock mClock;
diff --git a/service/tests/wifitests/src/com/android/server/wifi/ClientModeImplTest.java b/service/tests/wifitests/src/com/android/server/wifi/ClientModeImplTest.java
index 85e892c7f6..fddabc74b8 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/ClientModeImplTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/ClientModeImplTest.java
@@ -560,7 +560,6 @@ public class ClientModeImplTest extends WifiBaseTest {
@Mock RestrictedWifiNetworkFactory mRestrictedWifiNetworkFactory;
@Mock MultiInternetManager mMultiInternetManager;
@Mock WifiNetworkSuggestionsManager mWifiNetworkSuggestionsManager;
- @Mock LinkProbeManager mLinkProbeManager;
@Mock PackageManager mPackageManager;
@Mock WifiLockManager mWifiLockManager;
@Mock AsyncChannel mNullAsyncChannel;
@@ -743,7 +742,7 @@ public class ClientModeImplTest extends WifiBaseTest {
when(mWifiHandlerThread.getLooper()).thenReturn(mLooper.getLooper());
when(mWifiNative.getDeviceWiphyCapabilities(any())).thenReturn(mDeviceWiphyCapabilities);
if (Flags.getDeviceCrossAkmRoamingSupport() && SdkLevel.isAtLeastV()) {
- when(mDeviceWiphyCapabilities.getMaxNumberAkms()).thenReturn(2);
+ when(mDeviceWiphyCapabilities.getMaxNumberAkms()).thenReturn(3);
}
when(mWifiGlobals.isOweUpgradeEnabled()).thenReturn(true);
when(mWifiGlobals.getClientModeImplNumLogRecs()).thenReturn(100);
@@ -830,7 +829,7 @@ public class ClientModeImplTest extends WifiBaseTest {
mUntrustedWifiNetworkFactory, mOemWifiNetworkFactory, mRestrictedWifiNetworkFactory,
mMultiInternetManager, mWifiLastResortWatchdog, mWakeupController,
mWifiLockManager, mFrameworkFacade, mLooper.getLooper(),
- mWifiNative, mWrongPasswordNotifier, mWifiTrafficPoller, mLinkProbeManager,
+ mWifiNative, mWrongPasswordNotifier, mWifiTrafficPoller,
1, mBatteryStatsManager, mSupplicantStateTracker, mMboOceController,
mWifiCarrierInfoManager, mWifiPseudonymManager, mEapFailureNotifier,
mSimRequiredNotifier, mWifiScoreReport, mWifiP2pConnection, mWifiGlobals,
@@ -4036,6 +4035,12 @@ public class ClientModeImplTest extends WifiBaseTest {
mLooper.moveTimeForward(mWifiGlobals.getPollRssiIntervalMillis());
mLooper.dispatchAll();
assertRssiChangeBroadcastSent(3);
+
+ // Setup for invalid RSSI poll, should not send broadcast
+ signalPollResults.addEntry(0, -999, 65, 54, sFreq);
+ mLooper.moveTimeForward(mWifiGlobals.getPollRssiIntervalMillis());
+ mLooper.dispatchAll();
+ assertRssiChangeBroadcastSent(3);
}
/**
@@ -6159,29 +6164,6 @@ public class ClientModeImplTest extends WifiBaseTest {
}
/**
- * Verify that LinkProbeManager is updated during RSSI poll
- */
- @Test
- public void verifyRssiPollCallsLinkProbeManager() throws Exception {
- mCmi.enableRssiPolling(true);
-
- connect();
- // reset() should be called when RSSI polling is enabled and entering L2L3ConnectedState
- verify(mLinkProbeManager).resetOnNewConnection(); // called first time here
- verify(mLinkProbeManager, never()).resetOnScreenTurnedOn(); // not called
- verify(mLinkProbeManager).updateConnectionStats(any(), any());
-
- mCmi.enableRssiPolling(false);
- mLooper.dispatchAll();
- // reset() should be called when in L2L3ConnectedState (or child states) and RSSI polling
- // becomes enabled
- mCmi.enableRssiPolling(true);
- mLooper.dispatchAll();
- verify(mLinkProbeManager, times(1)).resetOnNewConnection(); // verify not called again
- verify(mLinkProbeManager).resetOnScreenTurnedOn(); // verify called here
- }
-
- /**
* Verify that when ordered to setLowLatencyMode(true),
* WifiNative is called with the right lowLatency mode.
*/
@@ -7884,6 +7866,39 @@ public class ClientModeImplTest extends WifiBaseTest {
verifyNoMoreInteractions(mWifiNetworkAgent);
}
+ /**
+ * Verify that roaming mode is enabled on disconnect for primary.
+ */
+ @Test
+ public void testRoamingModeOnDisconnectPrimary() throws Exception {
+ when(mClientModeManager.getRole()).thenReturn(ROLE_CLIENT_PRIMARY);
+ connect();
+ mCmi.disconnect();
+ mLooper.dispatchAll();
+ mCmi.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0,
+ new StateChangeResult(0, WifiSsid.fromUtf8Text(mConnectedNetwork.SSID),
+ TEST_BSSID_STR, sFreq, SupplicantState.DISCONNECTED));
+ mLooper.dispatchAll();
+ verify(mWifiNative).enableFirmwareRoaming(anyString(),
+ eq(WifiNative.ENABLE_FIRMWARE_ROAMING));
+ }
+
+ /**
+ * Verify that roaming mode doesn't change on disconnect for secondary.
+ */
+ @Test
+ public void testRoamingModeOnDisconnectSecondary() throws Exception {
+ when(mClientModeManager.getRole()).thenReturn(ROLE_CLIENT_SECONDARY_TRANSIENT);
+ connect();
+ mCmi.disconnect();
+ mLooper.dispatchAll();
+ mCmi.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0,
+ new StateChangeResult(0, WifiSsid.fromUtf8Text(mConnectedNetwork.SSID),
+ TEST_BSSID_STR, sFreq, SupplicantState.DISCONNECTED));
+ mLooper.dispatchAll();
+ verify(mWifiNative, never()).enableFirmwareRoaming(anyString(), anyInt());
+ }
+
@Test
public void testConnectionWhileDisconnecting() throws Exception {
connect();
@@ -9293,7 +9308,7 @@ public class ClientModeImplTest extends WifiBaseTest {
SecurityParams.createSecurityParamsBySecurityType(
WifiConfiguration.SECURITY_TYPE_PSK));
when(mWifiConfigManager.setNetworkDefaultGwMacAddress(anyInt(), any())).thenReturn(true);
- when(mWifiConfigManager.saveToStore(anyBoolean())).thenReturn(true);
+ when(mWifiConfigManager.saveToStore()).thenReturn(true);
WifiConfiguration linkedConfig = WifiConfigurationTestUtil.createPskNetwork("\"ssid2\"");
linkedConfig.networkId = connectedConfig.networkId + 1;
Map<String, WifiConfiguration> linkedNetworks = new HashMap<>();
@@ -9362,7 +9377,7 @@ public class ClientModeImplTest extends WifiBaseTest {
SecurityParams.createSecurityParamsBySecurityType(
WifiConfiguration.SECURITY_TYPE_SAE));
when(mWifiConfigManager.setNetworkDefaultGwMacAddress(anyInt(), any())).thenReturn(true);
- when(mWifiConfigManager.saveToStore(anyBoolean())).thenReturn(true);
+ when(mWifiConfigManager.saveToStore()).thenReturn(true);
mWifiNetworkAgentCallbackCaptor.getValue().onValidationStatus(
NetworkAgent.VALIDATION_STATUS_VALID, null /* captivePortalUrl */);
mLooper.dispatchAll();
@@ -9415,7 +9430,7 @@ public class ClientModeImplTest extends WifiBaseTest {
SecurityParams.createSecurityParamsBySecurityType(
WifiConfiguration.SECURITY_TYPE_PSK));
when(mWifiConfigManager.setNetworkDefaultGwMacAddress(anyInt(), any())).thenReturn(true);
- when(mWifiConfigManager.saveToStore(anyBoolean())).thenReturn(true);
+ when(mWifiConfigManager.saveToStore()).thenReturn(true);
// FT/PSK scan, do not update linked networks
ScanResult ftPskScan = new ScanResult();
@@ -9495,7 +9510,7 @@ public class ClientModeImplTest extends WifiBaseTest {
SecurityParams.createSecurityParamsBySecurityType(
WifiConfiguration.SECURITY_TYPE_PSK));
when(mWifiConfigManager.setNetworkDefaultGwMacAddress(anyInt(), any())).thenReturn(true);
- when(mWifiConfigManager.saveToStore(anyBoolean())).thenReturn(true);
+ when(mWifiConfigManager.saveToStore()).thenReturn(true);
WifiConfiguration linkedConfig = WifiConfigurationTestUtil.createPskNetwork("\"ssid2\"");
linkedConfig.networkId = connectedConfig.networkId + 1;
linkedConfig.allowAutojoin = false;
@@ -10086,6 +10101,33 @@ public class ClientModeImplTest extends WifiBaseTest {
assertFalse(mCmi.isAffiliatedLinkBssid(MacAddress.fromString(TEST_BSSID_STR2)));
}
+ @Test
+ public void testAffiliatedLinkBssidMatchWithNullLinkMacAddress() throws Exception {
+ setConnection();
+ List<MloLink> mloLinks = new ArrayList<>();
+ // Build MLO link with null link mac address
+ MloLink link1 = new MloLink();
+ link1.setBand(WifiScanner.WIFI_BAND_24_GHZ);
+ link1.setChannel(TEST_CHANNEL);
+ link1.setLinkId(TEST_MLO_LINK_ID);
+ link1.setRssi(TEST_RSSI);
+ mloLinks.add(link1);
+ when(mScanResult.getApMldMacAddress()).thenReturn(TEST_AP_MLD_MAC_ADDRESS);
+ when(mScanResult.getApMloLinkId()).thenReturn(TEST_MLO_LINK_ID);
+ when(mScanResult.getAffiliatedMloLinks()).thenReturn(mloLinks);
+ mScanResult.level = TEST_RSSI;
+ when(mWifiConfigManager.getScanDetailCacheForNetwork(FRAMEWORK_NETWORK_ID))
+ .thenReturn(mScanDetailCache);
+ when(mScanDetailCache.getScanResult(any())).thenReturn(mScanResult);
+ // Associate
+ mCmi.sendMessage(WifiMonitor.SUPPLICANT_STATE_CHANGE_EVENT, 0, 0,
+ new StateChangeResult(FRAMEWORK_NETWORK_ID, TEST_WIFI_SSID, TEST_BSSID_STR, sFreq,
+ SupplicantState.ASSOCIATED));
+ mLooper.dispatchAll();
+ // Test isAffiliatedLinkBssid match fails with no NPE
+ assertFalse(mCmi.isAffiliatedLinkBssid(MacAddress.fromString(TEST_BSSID_STR)));
+ }
+
/**
* Verify MLO parameters update from ScanResult at association
*/
@@ -11073,4 +11115,31 @@ public class ClientModeImplTest extends WifiBaseTest {
testDhcpHostnameSetting(true, WifiManager.FLAG_SEND_DHCP_HOSTNAME_RESTRICTION_SECURE,
SECURITY_TYPE_PSK, IIpClient.HOSTNAME_SETTING_DO_NOT_SEND);
}
+
+ /**
+ * Verify that the connection failure due to expired certificate status code is captured in the
+ * connection result metrics failure specific status code.
+ */
+ @Test
+ public void testConnectionFailureDueToExpiredCertificateStatusCode() throws Exception {
+ initializeAndAddNetworkAndVerifySuccess();
+
+ startConnectSuccess();
+
+ mCmi.sendMessage(WifiMonitor.AUXILIARY_SUPPLICANT_EVENT,
+ new SupplicantEventInfo(7, MacAddress.fromString(TEST_BSSID_STR),
+ "TLS: Certificate verification failed"
+ + ClientModeImpl.X509_CERTIFICATE_EXPIRED_ERROR_STRING));
+
+ mCmi.sendMessage(WifiMonitor.AUTHENTICATION_FAILURE_EVENT,
+ new AuthenticationFailureEventInfo(TEST_SSID, MacAddress.fromString(TEST_BSSID_STR),
+ WifiManager.ERROR_AUTH_FAILURE_EAP_FAILURE, -1));
+ mLooper.dispatchAll();
+
+ verify(mWifiMetrics).endConnectionEvent(
+ any(), eq(WifiMetrics.ConnectionEvent.FAILURE_AUTHENTICATION_FAILURE),
+ eq(WifiMetricsProto.ConnectionEvent.HLF_NONE),
+ eq(WifiMetricsProto.ConnectionEvent.AUTH_FAILURE_EAP_FAILURE),
+ anyInt(), eq(ClientModeImpl.EAP_FAILURE_CODE_CERTIFICATE_EXPIRED));
+ }
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/DeviceConfigFacadeTest.java b/service/tests/wifitests/src/com/android/server/wifi/DeviceConfigFacadeTest.java
index 9353e6a638..04536b8c55 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/DeviceConfigFacadeTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/DeviceConfigFacadeTest.java
@@ -19,6 +19,7 @@ package com.android.server.wifi;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import android.app.test.MockAnswerUtil.AnswerWithArguments;
@@ -234,6 +235,8 @@ public class DeviceConfigFacadeTest extends WifiBaseTest {
assertEquals(false, mDeviceConfigFacade.isAdjustPollRssiIntervalEnabled());
assertEquals(true, mDeviceConfigFacade.includePasspointSsidsInPnoScans());
assertEquals(true, mDeviceConfigFacade.isHandleRssiOrganicKernelFailuresEnabled());
+ assertEquals(Collections.EMPTY_SET,
+ mDeviceConfigFacade.getDisabledAutoBugreportTitleAndDetails());
}
/**
@@ -376,6 +379,9 @@ public class DeviceConfigFacadeTest extends WifiBaseTest {
anyBoolean())).thenReturn(true);
when(DeviceConfig.getBoolean(anyString(), eq("handle_rssi_organic_kernel_failures_enabled"),
anyBoolean())).thenReturn(true);
+ when(DeviceConfig.getString(anyString(),
+ eq("disabled_auto_bugreport_title_and_description"), any()))
+ .thenReturn("TITLE_1DETAIL_1,TITLE_2DETAIL_2");
mOnPropertiesChangedListenerCaptor.getValue().onPropertiesChanged(null);
// Verifying fields are updated to the new values
@@ -449,6 +455,11 @@ public class DeviceConfigFacadeTest extends WifiBaseTest {
assertEquals(true, mDeviceConfigFacade.isAdjustPollRssiIntervalEnabled());
assertEquals(true, mDeviceConfigFacade.includePasspointSsidsInPnoScans());
assertEquals(true, mDeviceConfigFacade.isHandleRssiOrganicKernelFailuresEnabled());
+ Set<String> disabledAutoBugreports =
+ mDeviceConfigFacade.getDisabledAutoBugreportTitleAndDetails();
+ assertEquals(2, disabledAutoBugreports.size());
+ assertTrue(disabledAutoBugreports.contains("TITLE_1DETAIL_1"));
+ assertTrue(disabledAutoBugreports.contains("TITLE_2DETAIL_2"));
when(DeviceConfig.getBoolean(anyString(), eq("oob_pseudonym_enabled"),
anyBoolean())).thenReturn(false);
diff --git a/service/tests/wifitests/src/com/android/server/wifi/HalDeviceManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/HalDeviceManagerTest.java
index 39b82d81bd..36e54b0680 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/HalDeviceManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/HalDeviceManagerTest.java
@@ -47,7 +47,6 @@ import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
@@ -66,7 +65,6 @@ import android.net.wifi.WifiManager;
import android.net.wifi.WifiScanner;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Handler;
-import android.os.HandlerThread;
import android.os.WorkSource;
import android.os.test.TestLooper;
import android.util.Log;
@@ -193,8 +191,6 @@ public class HalDeviceManagerTest extends WifiBaseTest {
when(mWorkSourceHelper2.getWorkSource()).thenReturn(TEST_WORKSOURCE_2);
when(mWifiInjector.getSettingsConfigStore()).thenReturn(mWifiSettingsConfigStore);
when(mWifiInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfigFacade);
- when(mDeviceConfigFacade.getFeatureFlags()).thenReturn(mFeatureFlags);
- when(mFeatureFlags.singleWifiThread()).thenReturn(true);
when(mConcreteClientModeManager.getRole()).thenReturn(
ClientModeManager.ROLE_CLIENT_PRIMARY);
@@ -1206,83 +1202,12 @@ public class HalDeviceManagerTest extends WifiBaseTest {
}
/**
- * Verify that when the thread that caused an iface to get destroyed is not the thread the
- * onDestroy callback is intended to be invoked on, then onDestroy is will get posted to the
- * correct thread.
- */
- @Test
- public void testOnDestroyedWithHandlerTriggeredOnDifferentThread() throws Exception {
- when(mFeatureFlags.singleWifiThread()).thenReturn(false);
- long currentThreadId = 983757; // arbitrary current thread ID
- when(mWifiInjector.getCurrentThreadId()).thenReturn(currentThreadId);
- // RETURNS_DEEP_STUBS allows mocking nested method calls
- Handler staIfaceOnDestroyedHandler = mock(Handler.class, Mockito.RETURNS_DEEP_STUBS);
- // Configure the handler to be on a different thread as the current thread.
- when(staIfaceOnDestroyedHandler.getLooper().getThread().getId())
- .thenReturn(currentThreadId + 1);
- InterfaceDestroyedListener staIdl = mock(InterfaceDestroyedListener.class);
- ArgumentCaptor<Runnable> lambdaCaptor = ArgumentCaptor.forClass(Runnable.class);
-
- // simulate adding a STA iface and then stopping wifi
- simulateStartAndStopWifi(staIdl, staIfaceOnDestroyedHandler);
-
- // Verify a runnable is posted because current thread is different than the intended thread
- // for running "onDestroyed"
- verify(staIfaceOnDestroyedHandler).postAtFrontOfQueue(lambdaCaptor.capture());
-
- // Verify onDestroyed is only run after the posted runnable is dispatched
- verify(staIdl, never()).onDestroyed("wlan0");
- lambdaCaptor.getValue().run();
- verify(staIdl).onDestroyed("wlan0");
- }
-
- /**
- * Verify that when the thread that caused an interface to get destroyed is not the thread the
- * onDestroy callback is intended to be invoked on, dispatchDestroyedListeners will block till
- * onDestroy callback is done, provided the overlay config_wifiWaitForDestroyedListeners is
- * True.
- */
- @Test
- public void testOnDestroyedWaitingWithHandlerTriggeredOnDifferentThread() throws Exception {
- when(mFeatureFlags.singleWifiThread()).thenReturn(false);
- // Enable waiting for destroy listeners
- mWaitForDestroyedListeners = true;
- // Setup a separate thread for destroy
- HandlerThread mHandlerThread = new HandlerThread("DestroyListener");
- mHandlerThread.start();
- Handler staIfaceOnDestroyedHandler = spy(mHandlerThread.getThreadHandler());
- InterfaceDestroyedListener staIdl = mock(InterfaceDestroyedListener.class);
- // Setup Wi-Fi
- TestChipV1 chipMock = new TestChipV1();
- chipMock.initialize();
- mInOrder = inOrder(mWifiMock, staIdl, chipMock.chip);
- // Start Wi-Fi
- assertTrue(mDut.start());
- // Create STA Iface.
- WifiStaIface staIface = mock(WifiStaIface.class);
- when(staIface.getName()).thenReturn("wlan0");
- doAnswer(new CreateStaIfaceAnswer(chipMock, true, staIface))
- .when(chipMock.chip).createStaIface();
- assertEquals(staIface, mDut.createStaIface(staIdl, staIfaceOnDestroyedHandler,
- TEST_WORKSOURCE_0, mConcreteClientModeManager));
- // Remove STA interface
- mDut.removeIface(staIface);
- // Dispatch
- mTestLooper.startAutoDispatch();
- mTestLooper.dispatchAll();
- // Validate OnDestroyed is called before removing interface.
- mInOrder.verify(staIdl).onDestroyed("wlan0");
- mInOrder.verify(chipMock.chip).removeStaIface("wlan0");
- }
-
- /**
* Verify that when the thread that caused an iface to get destroyed is already the thread the
* onDestroy callback is intended to be invoked on, then onDestroy is invoked directly.
*/
@Test
public void testOnDestroyedWithHandlerTriggeredOnSameThread() throws Exception {
long currentThreadId = 983757; // arbitrary current thread ID
- when(mWifiInjector.getCurrentThreadId()).thenReturn(currentThreadId);
// RETURNS_DEEP_STUBS allows mocking nested method calls
Handler staIfaceOnDestroyedHandler = mock(Handler.class, Mockito.RETURNS_DEEP_STUBS);
// Configure the handler thread ID so it's the same as the current thread.
@@ -1330,10 +1255,6 @@ public class HalDeviceManagerTest extends WifiBaseTest {
*/
@Test
public void testCreateApWithStaIfaceUpTestChipV1UsingHandlerListeners() throws Exception {
- // Make the creation and InterfaceDestroyListener running on the same thread to verify the
- // order in the real scenario.
- when(mWifiInjector.getCurrentThreadId())
- .thenReturn(mTestLooper.getLooper().getThread().getId());
TestChipV1 chipMock = new TestChipV1();
chipMock.initialize();
@@ -1403,11 +1324,6 @@ public class HalDeviceManagerTest extends WifiBaseTest {
@Test
public void testCreateLowerPriorityApWithStaIfaceUpTestChipV1UsingHandlerListeners()
throws Exception {
- // Make the creation and InterfaceDestroyListener running on the same thread to verify the
- // order in the real scenario.
- when(mWifiInjector.getCurrentThreadId())
- .thenReturn(mTestLooper.getLooper().getThread().getId());
-
TestChipV1 chipMock = new TestChipV1();
chipMock.initialize();
diff --git a/service/tests/wifitests/src/com/android/server/wifi/InsecureEapNetworkHandlerTest.java b/service/tests/wifitests/src/com/android/server/wifi/InsecureEapNetworkHandlerTest.java
index af60b424e6..3addabb430 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/InsecureEapNetworkHandlerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/InsecureEapNetworkHandlerTest.java
@@ -99,6 +99,7 @@ public class InsecureEapNetworkHandlerTest extends WifiBaseTest {
private static final int TEST_GEN_SERVER_CERT = 2;
private static final int TEST_GEN_SELF_SIGNED_CERT = 3;
private static final int TEST_GEN_FAKE_CA_CERT = 4;
+ private static final int TEST_GEN_SERVER_CERTIFICATE_WITHOUT_COMMON_NAME = 5;
private static final String TEST_SERVER_CERTIFICATE = "-----BEGIN CERTIFICATE-----\n"
+ "MIIGPjCCBCagAwIBAgIUN2Ss1JmvjveRe97iWoNh4V+Y5LYwDQYJKoZIhvcNAQEM\n"
@@ -279,6 +280,42 @@ public class InsecureEapNetworkHandlerTest extends WifiBaseTest {
+ "jUR49A==\n"
+ "-----END CERTIFICATE-----";
+ private static final String TEST_SERVER_CERTIFICATE_WITHOUT_COMMON_NAME =
+ "-----BEGIN CERTIFICATE-----\n"
+ + "MIIF+zCCA+OgAwIBAgIUCvmbTyLRy+5/Tt8iSpBB+xmZTfUwDQYJKoZIhvcNAQEM\n"
+ + "BQAwgZcxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRswGQYDVQQK\n"
+ + "DBJBbmRyb2lkIFdpLUZpIFRlc3QxGDAWBgNVBAsMD2FuZHJvaWR3aWZpLm9lbTE8\n"
+ + "MDoGA1UEAwwzQW5kcm9pZCBQYXJ0bmVyIFJvb3QgQ0EgZm9yIHRlc3RpbmcgYW5k\n"
+ + "IGRldmVsb3BtZW50MB4XDTI0MDMxMzE3NTIwMFoXDTI2MDMxMzE3NTIwMFowQTEL\n"
+ + "MAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExHTAbBgNVBAoMFEFuZHJv\n"
+ + "aWQgV2ktRmkgVGVzdGVyMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA\n"
+ + "uVNdRG1M/DVcfqi1Cl1FRXxZ2eeKe/IM6OA4KhkR0aymZtjmsoTO52JFVoTykCrj\n"
+ + "bnDp6wOTDaglwbClip/Be5Oj//6LS+A5J3PqUfQsOI+s8ZeAu6s4Kur4g0oPhfNz\n"
+ + "msRyQvhIUkwYCXEum+uQ3INLpy38JggEbTRR4nnn2UUh4+Shv9xYA/SiYrV/sd/f\n"
+ + "Vj++lAmOUQu/CLCWtpfBFTeiyg/DhypbHQVPnr+k1QBy7DKZlBXQb7POjE4M6Ed/\n"
+ + "/st11tB8qHZnM8Xe4CdM3xSJj9qs2BQyT228z7SCmA3r3P1CMvSRYqWu1mn4iMO1\n"
+ + "t0sShF/OfUkihE1ADA0q6GRHDLQ3T/TSnuYWyH4/iMMygHl+yfDeECaLOn/KEQM9\n"
+ + "hOBlXo5iKB/GMkFKeoGQQePwWllHK7HjNEAOOPyXS4nzRA1VUq0gVvhFpQX7ZK9X\n"
+ + "OWdNdcnof4wzOEJse96I7v3A1C0FYg57f1HKOnx195hb1wQfi0MOyE/mgqvtVWbP\n"
+ + "90Vd2nFMlNSVc38DUT7jyYTygUAl5eQDRZo/npNs32nf8YW4cWmN1r+LCHUkK22v\n"
+ + "y8bmSVTts7WHzx9K1kg5+XvaTxpgmmFneuh0XIFvTcGFwMPrHzwaa5pOCYjUvlSy\n"
+ + "GXOmRuSqFipufxxlRKM0cJhMUqI/vmYJ5byx5Wb1N+MCAwEAAaOBkzCBkDAdBgNV\n"
+ + "HQ4EFgQUz4BlPUEPOANhQ74NbClj0CrdiHswHwYDVR0jBBgwFoAUyWVsWmPxPCB6\n"
+ + "D7hRF7K2vyVzKOMwCQYDVR0TBAIwADALBgNVHQ8EBAMCBaAwEwYDVR0lBAwwCgYI\n"
+ + "KwYBBQUHAwEwIQYDVR0RBBowGIIWc2VydmVyLmFuZHJvaWR3aWZpLm9lbTANBgkq\n"
+ + "hkiG9w0BAQwFAAOCAgEAkf5CHaqzDsQKn8udsA9/fIKSOEqr0LUfwP20JzFe0HBA\n"
+ + "F3cWoMrEVoAJFfi5NFQJOjlEib7kvu2MI92lL6ch3D3iW5mnY5Ncnm2eyqi1kvii\n"
+ + "uueKnH4a9jsolWgcsGiw5vUhsodgxWzFr/yDURYZEWkzP4uiW3+0K6eoc11DPiDr\n"
+ + "16LS4xAINHVeEDhhkuZG2Bqo1ctbcQWR7Leb5JGpfkC7xNGyVNUwJYjI5vow5GzR\n"
+ + "Af2SvJuG3mMxBfM+8TMx4wf4Sgq80FmaJLNAOlfKlYIN0u/NV/pq6nWb0B4u3K0u\n"
+ + "ytH3BRJsuKg35fZEy4qRpBZL1Us9FzwPkRaUK+Sgtz9BLRPL5my3xUwnZaqw+ZRp\n"
+ + "Gw+vwErnSc3md9DhYMeGc0JdA141/pxc/P20hoLG7cDK/tO4PwBzNrF57XLEFC7v\n"
+ + "bww0rQoADGCIk48n2gZX/wh1XeHWJhk7C+lGGbA/qrs5zZbzDaMi/N3C74eiQJOH\n"
+ + "KdQk10pt2nU8xwC/RsfL7W+2K4c4/mZvaroxQvIxs8tRB3glbpwQe4HntpE0LdvH\n"
+ + "7hotzbIt0YtGtzIdOwpR277a73qT09pmYL97+rwPGWMviCkb9QNvFHBKc0MsgxXz\n"
+ + "15THXfttbGruZySMyj9kMox0NbhsVKiSEEiqMMHvJMbn4FDI1O9U5IDZdUplI0A=\n"
+ + "-----END CERTIFICATE-----";
+
@Mock WifiContext mContext;
@Mock WifiConfigManager mWifiConfigManager;
@Mock WifiNative mWifiNative;
@@ -660,6 +697,8 @@ public class InsecureEapNetworkHandlerTest extends WifiBaseTest {
certString = TEST_SELF_SIGNED_CERTIFICATE;
} else if (type == TEST_GEN_FAKE_CA_CERT) {
certString = TEST_FAKE_CA_CERTIFICATE;
+ } else if (type == TEST_GEN_SERVER_CERTIFICATE_WITHOUT_COMMON_NAME) {
+ certString = TEST_SERVER_CERTIFICATE_WITHOUT_COMMON_NAME;
} else {
throw (new Exception());
}
@@ -921,6 +960,31 @@ public class InsecureEapNetworkHandlerTest extends WifiBaseTest {
}
/**
+ * Verify that is reports errors if the server certificate doesn't contain the common name
+ */
+ @Test
+ public void verifyOnErrorWithServerCertificateWithoutCommonName() throws Exception {
+ assumeTrue(SdkLevel.isAtLeastT());
+ boolean isAtLeastT = true, isTrustOnFirstUseSupported = true, isUserSelected = true;
+
+ WifiConfiguration config = prepareWifiConfiguration(isAtLeastT);
+ setupTest(config, isAtLeastT, isTrustOnFirstUseSupported);
+
+ CertificateEventInfo mockCaCert = generateMockCertEventInfo(TEST_GEN_CA2_CERT);
+ // Server certificate without common name
+ CertificateEventInfo mockServerCert =
+ generateMockCertEventInfo(TEST_GEN_SERVER_CERTIFICATE_WITHOUT_COMMON_NAME);
+ mInsecureEapNetworkHandler.addPendingCertificate(config.networkId, 1, mockCaCert);
+ mInsecureEapNetworkHandler.addPendingCertificate(config.networkId, 0, mockServerCert);
+
+ mInsecureEapNetworkHandler.startUserApprovalIfNecessary(isUserSelected);
+ verify(mCallbacks).onError(eq(config.SSID));
+ verify(mWifiConfigManager, atLeastOnce()).updateNetworkSelectionStatus(eq(config.networkId),
+ eq(WifiConfiguration.NetworkSelectionStatus
+ .DISABLED_BY_WIFI_MANAGER));
+ }
+
+ /**
* Verify that setting pending certificate won't crash with no current configuration.
*/
@Test
diff --git a/service/tests/wifitests/src/com/android/server/wifi/LinkProbeManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/LinkProbeManagerTest.java
deleted file mode 100644
index 171e128141..0000000000
--- a/service/tests/wifitests/src/com/android/server/wifi/LinkProbeManagerTest.java
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * Copyright (C) 2019 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.wifi;
-
-import static junit.framework.Assert.assertEquals;
-
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyInt;
-import static org.mockito.Mockito.atLeastOnce;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-
-import android.content.Context;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.nl80211.WifiNl80211Manager;
-import android.os.Handler;
-import android.os.test.TestLooper;
-
-import androidx.test.filters.SmallTest;
-
-import com.android.wifi.resources.R;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.ArgumentCaptor;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-
-import java.util.HashSet;
-
-/**
- * Unit tests for LinkProbeManager
- */
-@SmallTest
-public class LinkProbeManagerTest extends WifiBaseTest {
-
- private static final String TEST_IFACE_NAME = "testIfaceName";
- private static final String TEST_BSSID = "6c:f3:7f:ae:8c:f3";
- private static final int TEST_ELAPSED_TIME_MS = 100;
-
- private LinkProbeManager mLinkProbeManager;
-
- private WifiInfo mWifiInfo;
- private long mTimeMs;
- @Mock private Clock mClock;
- @Mock private WifiNative mWifiNative;
- @Mock private WifiMetrics mWifiMetrics;
- @Mock private FrameworkFacade mFrameworkFacade;
- @Mock private Context mContext;
-
- private TestLooper mLooper = new TestLooper();
- private MockResources mResources;
-
- @Before
- public void setUp() throws Exception {
- MockitoAnnotations.initMocks(this);
-
- mResources = new MockResources();
- mResources.setBoolean(R.bool.config_wifi_link_probing_supported, true);
- when(mContext.getResources()).thenReturn(mResources);
-
- initLinkProbeManager();
-
- mWifiInfo = new WifiInfo();
- mWifiInfo.setBSSID(TEST_BSSID);
- mTimeMs = 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
-
- // Simulate new connection to trigger check for isSupported resource flag.
- mLinkProbeManager.resetOnNewConnection();
- mLinkProbeManager.resetOnScreenTurnedOn();
- }
-
- private void initLinkProbeManager() {
- mLinkProbeManager = new LinkProbeManager(mClock, mWifiNative, mWifiMetrics,
- mFrameworkFacade, new Handler(mLooper.getLooper()), mContext);
- mLinkProbeManager.enableVerboseLogging(true);
- }
-
- /**
- * Tests that link probing is correctly triggered when the required conditions are met, and an
- * ACK was received from the AP.
- */
- @Test
- public void testLinkProbeTriggeredAndAcked() throws Exception {
- // initialize tx success counter
- mWifiInfo.txSuccess = 50;
- mTimeMs += 3000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- // should not probe yet
- verify(mWifiNative, never()).probeLink(any(), any(), any(), anyInt());
- verify(mWifiMetrics, never()).incrementLinkProbeExperimentProbeCount(any());
-
- // tx success counter did not change since last update
- mWifiInfo.txSuccess = 50;
- // below RSSI threshold
- int rssi = LinkProbeManager.RSSI_THRESHOLD - 5;
- mWifiInfo.setRssi(rssi);
- // above link speed threshold
- int linkSpeed = LinkProbeManager.LINK_SPEED_THRESHOLD_MBPS + 10;
- mWifiInfo.setLinkSpeed(linkSpeed);
- // more than DELAY_AFTER_TX_SUCCESS_MS passed
- long timeDelta = LinkProbeManager.DELAY_AFTER_TX_SUCCESS_MS + 20000;
- mTimeMs += timeDelta;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- ArgumentCaptor<WifiNl80211Manager.SendMgmtFrameCallback> callbackCaptor =
- ArgumentCaptor.forClass(WifiNl80211Manager.SendMgmtFrameCallback.class);
- verify(mWifiNative).probeLink(eq(TEST_IFACE_NAME), any(), callbackCaptor.capture(),
- anyInt());
- ArgumentCaptor<String> experimentIdCaptor = ArgumentCaptor.forClass(String.class);
- verify(mWifiMetrics, atLeastOnce()).incrementLinkProbeExperimentProbeCount(
- experimentIdCaptor.capture());
- int numExperimentIds = LinkProbeManager.EXPERIMENT_DELAYS_MS.length
- * LinkProbeManager.EXPERIMENT_RSSIS.length
- * LinkProbeManager.EXPERIMENT_LINK_SPEEDS.length;
- assertEquals(numExperimentIds, new HashSet<>(experimentIdCaptor.getAllValues()).size());
-
- callbackCaptor.getValue().onAck(TEST_ELAPSED_TIME_MS);
- verify(mWifiMetrics).logLinkProbeSuccess(
- TEST_IFACE_NAME, timeDelta, rssi, linkSpeed, TEST_ELAPSED_TIME_MS);
- }
-
- /**
- * Tests that link probing is correctly triggered when the required conditions are met, but
- * no ACK was received from the AP.
- */
- @Test
- public void testLinkProbeTriggeredAndFailed() throws Exception {
- // initialize tx success counter
- mWifiInfo.txSuccess = 50;
- mTimeMs += 3000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- // should not probe yet
- verify(mWifiNative, never()).probeLink(any(), any(), any(), anyInt());
-
- // tx success counter did not change since last update
- mWifiInfo.txSuccess = 50;
- // above RSSI threshold
- int rssi = LinkProbeManager.RSSI_THRESHOLD + 5;
- mWifiInfo.setRssi(rssi);
- // below link speed threshold
- int linkSpeed = LinkProbeManager.LINK_SPEED_THRESHOLD_MBPS - 2;
- mWifiInfo.setLinkSpeed(linkSpeed);
- // more than DELAY_BETWEEN_PROBES_MS passed
- long timeDelta = LinkProbeManager.DELAY_BETWEEN_PROBES_MS + 1000;
- mTimeMs += timeDelta;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- ArgumentCaptor<WifiNl80211Manager.SendMgmtFrameCallback> callbackCaptor =
- ArgumentCaptor.forClass(WifiNl80211Manager.SendMgmtFrameCallback.class);
- verify(mWifiNative).probeLink(eq(TEST_IFACE_NAME), any(), callbackCaptor.capture(),
- anyInt());
-
- callbackCaptor.getValue().onFailure(WifiNl80211Manager.SEND_MGMT_FRAME_ERROR_NO_ACK);
- verify(mWifiMetrics).logLinkProbeFailure(TEST_IFACE_NAME, timeDelta, rssi, linkSpeed,
- WifiNl80211Manager.SEND_MGMT_FRAME_ERROR_NO_ACK);
- }
-
- /**
- * Tests that link probing is not triggered more than once every DELAY_BETWEEN_PROBES_MS
- */
- @Test
- public void testLinkProbeNotTriggeredTooFrequently() throws Exception {
- testLinkProbeTriggeredAndAcked();
-
- // tx success counter did not change since last update
- mWifiInfo.txSuccess = 50;
- // below RSSI threshold
- mWifiInfo.setRssi(LinkProbeManager.RSSI_THRESHOLD - 5);
- // above link speed threshold
- mWifiInfo.setLinkSpeed(LinkProbeManager.LINK_SPEED_THRESHOLD_MBPS + 10);
- // *** but less than DELAY_BETWEEN_PROBES_MS has passed since last probe ***
- mTimeMs += LinkProbeManager.DELAY_BETWEEN_PROBES_MS - 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- // should not probe
- verifyNoMoreInteractions(mWifiNative);
- }
-
- /**
- * Tests that link probing is not triggered when Tx has succeeded within the last
- * DELAY_AFTER_TX_SUCCESS_MS.
- */
- @Test
- public void testLinkProbeNotTriggeredWhenTxSucceeded() throws Exception {
- // initialize tx success counter
- mWifiInfo.txSuccess = 50;
- mTimeMs += 3000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- // should not probe yet
- verify(mWifiNative, never()).probeLink(any(), any(), any(), anyInt());
-
- // tx succeeded
- mWifiInfo.txSuccess = 55;
- mTimeMs += 3000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- // should not probe yet
- verify(mWifiNative, never()).probeLink(any(), any(), any(), anyInt());
-
- // tx success counter did not change since last update
- mWifiInfo.txSuccess = 55;
- // below RSSI threshold
- mWifiInfo.setRssi(LinkProbeManager.RSSI_THRESHOLD - 5);
- // above link speed threshold
- mWifiInfo.setLinkSpeed(LinkProbeManager.LINK_SPEED_THRESHOLD_MBPS + 10);
- // *** but less than DELAY_AFTER_TX_SUCCESS_MS has passed since last tx success ***
- mTimeMs += LinkProbeManager.DELAY_AFTER_TX_SUCCESS_MS - 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- verify(mWifiNative, never()).probeLink(any(), any(), any(), anyInt());
- }
-
- /**
- * Tests that link probing is not triggered when screen was turned on within the last
- * {@link LinkProbeManager#SCREEN_ON_DELAY_MS}.
- */
- @Test
- public void testLinkProbeNotTriggeredWhenScreenJustTurnedOn() throws Exception {
- mTimeMs += 30 * 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.resetOnScreenTurnedOn();
- // should not probe yet
- verify(mWifiNative, never()).probeLink(any(), any(), any(), anyInt());
-
- // tx success counter did not change since initialization
- mWifiInfo.txSuccess = 0;
- // below RSSI threshold
- mWifiInfo.setRssi(LinkProbeManager.RSSI_THRESHOLD - 5);
- // above link speed threshold
- mWifiInfo.setLinkSpeed(LinkProbeManager.LINK_SPEED_THRESHOLD_MBPS + 10);
- // *** but less than SCREEN_ON_DELAY_MS has passed since last screen on ***
- mTimeMs += LinkProbeManager.SCREEN_ON_DELAY_MS - 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- verify(mWifiNative, never()).probeLink(any(), any(), any(), anyInt());
- }
-
- /**
- * Tests that link probing is triggered when screen was turned on more than
- * {@link LinkProbeManager#SCREEN_ON_DELAY_MS} ago.
- */
- @Test
- public void testLinkProbeTriggeredAfterScreenTurnedOn() throws Exception {
- mTimeMs += 30 * 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.resetOnScreenTurnedOn();
- // should not probe yet
- verify(mWifiNative, never()).probeLink(any(), any(), any(), anyInt());
-
- // tx success counter did not change since initialization
- mWifiInfo.txSuccess = 0;
- // below RSSI threshold
- mWifiInfo.setRssi(LinkProbeManager.RSSI_THRESHOLD - 5);
- // above link speed threshold
- mWifiInfo.setLinkSpeed(LinkProbeManager.LINK_SPEED_THRESHOLD_MBPS + 10);
- // *** more than SCREEN_ON_DELAY_MS has passed since last screen on ***
- mTimeMs += LinkProbeManager.SCREEN_ON_DELAY_MS + 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- verify(mWifiNative).probeLink(eq(TEST_IFACE_NAME), any(), any(), anyInt());
- }
-
- /**
- * Tests when link probing feature is not supported by the device, no probes should run.
- */
- @Test
- public void testLinkProbeFeatureUnsupported() throws Exception {
- mResources.setBoolean(R.bool.config_wifi_link_probing_supported, false);
- initLinkProbeManager();
-
- // initialize tx success counter
- mWifiInfo.txSuccess = 50;
- mTimeMs += 3000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- // should not probe yet
- verify(mWifiNative, never()).probeLink(any(), any(), any(), anyInt());
-
- // tx success counter did not change since last update
- mWifiInfo.txSuccess = 50;
- // below RSSI threshold
- int rssi = LinkProbeManager.RSSI_THRESHOLD - 5;
- mWifiInfo.setRssi(rssi);
- // above link speed threshold
- int linkSpeed = LinkProbeManager.LINK_SPEED_THRESHOLD_MBPS + 10;
- mWifiInfo.setLinkSpeed(linkSpeed);
- // more than DELAY_AFTER_TX_SUCCESS_MS passed
- long timeDelta = LinkProbeManager.DELAY_AFTER_TX_SUCCESS_MS + 1000;
- mTimeMs += timeDelta;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- verify(mWifiNative, never()).probeLink(any() , any(), any(), anyInt());
- }
-
- /**
- * Tests exhausting the daily link probe quota and verify that no more link probes are made
- * after the limit is reached. Tests that the quota is reset upon entering a new day.
- */
- @Test
- public void testLinkProbeQuotaExceeded() {
- mTimeMs += 30 * 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- // should not probe yet
- verify(mWifiNative, never()).probeLink(any(), any(), any(), anyInt());
-
- // tx success counter did not change since initialization
- mWifiInfo.txSuccess = 0;
- // below RSSI threshold
- mWifiInfo.setRssi(LinkProbeManager.RSSI_THRESHOLD - 5);
- // above link speed threshold
- mWifiInfo.setLinkSpeed(LinkProbeManager.LINK_SPEED_THRESHOLD_MBPS + 10);
-
- // exhaust quota
- for (int i = 1; i <= LinkProbeManager.MAX_PROBE_COUNT_IN_PERIOD; i++) {
- mTimeMs += LinkProbeManager.DELAY_BETWEEN_PROBES_MS + 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- }
- verify(mWifiNative, times((int) LinkProbeManager.MAX_PROBE_COUNT_IN_PERIOD))
- .probeLink(eq(TEST_IFACE_NAME), any(), any(), anyInt());
- // verify no more quota
- for (int i = 0; i < 10; i++) {
- mTimeMs += LinkProbeManager.DELAY_BETWEEN_PROBES_MS + 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- }
- verify(mWifiNative, times((int) LinkProbeManager.MAX_PROBE_COUNT_IN_PERIOD))
- .probeLink(eq(TEST_IFACE_NAME), any(), any(), anyInt());
-
- // start new period
- mTimeMs += LinkProbeManager.PERIOD_MILLIS + 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
-
- // exhaust quota again
- for (int i = 1; i <= LinkProbeManager.MAX_PROBE_COUNT_IN_PERIOD; i++) {
- mTimeMs += LinkProbeManager.DELAY_BETWEEN_PROBES_MS + 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- }
- verify(mWifiNative, times((int) (2 * LinkProbeManager.MAX_PROBE_COUNT_IN_PERIOD)))
- .probeLink(eq(TEST_IFACE_NAME), any(), any(), anyInt());
- // verify no more quota again
- for (int i = 0; i < 10; i++) {
- mTimeMs += LinkProbeManager.DELAY_BETWEEN_PROBES_MS + 1000;
- when(mClock.getElapsedSinceBootMillis()).thenReturn(mTimeMs);
- mLinkProbeManager.updateConnectionStats(mWifiInfo, TEST_IFACE_NAME);
- }
- verify(mWifiNative, times((int) (2 * LinkProbeManager.MAX_PROBE_COUNT_IN_PERIOD)))
- .probeLink(eq(TEST_IFACE_NAME), any(), any(), anyInt());
- }
-}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java b/service/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java
index e061ea5e3f..2cfc54cc21 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/OpenNetworkNotifierTest.java
@@ -409,7 +409,7 @@ public class OpenNetworkNotifierTest extends WifiBaseTest {
mBroadcastReceiver.onReceive(mContext, createIntent(ACTION_USER_DISMISSED_NOTIFICATION));
- verify(mWifiConfigManager).saveToStore(false /* forceWrite */);
+ verify(mWifiConfigManager).saveToStore();
mNotificationController.clearPendingNotification(true);
List<ScanDetail> scanResults = mOpenNetworks;
@@ -435,7 +435,7 @@ public class OpenNetworkNotifierTest extends WifiBaseTest {
mBroadcastReceiver.onReceive(mContext, createIntent(ACTION_CONNECT_TO_NETWORK));
- verify(mWifiConfigManager).saveToStore(false /* forceWrite */);
+ verify(mWifiConfigManager).saveToStore();
verify(mWifiMetrics).setNetworkRecommenderBlocklistSize(OPEN_NET_NOTIFIER_TAG, 1);
List<ScanDetail> scanResults = mOpenNetworks;
@@ -855,7 +855,7 @@ public class OpenNetworkNotifierTest extends WifiBaseTest {
@Test
public void removeNetworkFromBlacklist_handlesNull() {
mNotificationController.handleWifiConnected(null);
- verify(mWifiConfigManager, never()).saveToStore(false /* forceWrite */);
+ verify(mWifiConfigManager, never()).saveToStore();
}
/**
@@ -864,7 +864,7 @@ public class OpenNetworkNotifierTest extends WifiBaseTest {
@Test
public void removeNetworkFromBlacklist_returnsEarlyIfNothingIsRemoved() {
mNotificationController.handleWifiConnected(TEST_SSID_1);
- verify(mWifiConfigManager, never()).saveToStore(false /* forceWrite */);
+ verify(mWifiConfigManager, never()).saveToStore();
}
/**
@@ -877,7 +877,7 @@ public class OpenNetworkNotifierTest extends WifiBaseTest {
// Simulate the user connecting to TEST_SSID_1 and verify it is removed from the blacklist
mNotificationController.handleWifiConnected(mTestNetwork.SSID);
- verify(mWifiConfigManager, times(2)).saveToStore(false /* forceWrite */);
+ verify(mWifiConfigManager, times(2)).saveToStore();
verify(mWifiMetrics).setNetworkRecommenderBlocklistSize(OPEN_NET_NOTIFIER_TAG, 0);
ScanResult actual = mNotificationController.recommendNetwork(mOpenNetworks);
ScanResult expected = mOpenNetworks.get(0).getScanResult();
diff --git a/service/tests/wifitests/src/com/android/server/wifi/OuiKeyedDataUtil.java b/service/tests/wifitests/src/com/android/server/wifi/OuiKeyedDataUtil.java
new file mode 100644
index 0000000000..3be43596a2
--- /dev/null
+++ b/service/tests/wifitests/src/com/android/server/wifi/OuiKeyedDataUtil.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi;
+
+import android.net.wifi.OuiKeyedData;
+import android.os.PersistableBundle;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Test utils for {@link OuiKeyedData}. Implementation is the same as
+ * {@link android.net.wifi.OuiKeyedDataUtil}
+ */
+public class OuiKeyedDataUtil {
+ private static final String STRING_FIELD_KEY = "stringField";
+ private static final String ARRAY_FIELD_KEY = "arrayField";
+
+ private static final String STRING_FIELD_VALUE = "someString";
+ private static final int[] ARRAY_FIELD_VALUE = new int[] {1, 2, 3};
+
+ /**
+ * Generate a single OuiKeyedData object containing several test fields.
+ */
+ public static OuiKeyedData createTestOuiKeyedData(int oui) {
+ PersistableBundle bundle = new PersistableBundle();
+ bundle.putString(STRING_FIELD_KEY, STRING_FIELD_VALUE);
+ bundle.putIntArray(ARRAY_FIELD_KEY, ARRAY_FIELD_VALUE);
+ return new OuiKeyedData.Builder(oui, bundle).build();
+ }
+
+ /**
+ * Generate a list of OuiKeyedData objects, each containing several test fields.
+ */
+ public static List<OuiKeyedData> createTestOuiKeyedDataList(int size) {
+ List<OuiKeyedData> ouiKeyedDataList = new ArrayList<>();
+ for (int i = 0; i < size; i++) {
+ ouiKeyedDataList.add(createTestOuiKeyedData(i + 1));
+ }
+ return ouiKeyedDataList;
+ }
+}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/RssiMonitorTest.java b/service/tests/wifitests/src/com/android/server/wifi/RssiMonitorTest.java
index f594da33a3..60eff99ff2 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/RssiMonitorTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/RssiMonitorTest.java
@@ -23,7 +23,7 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import android.content.Context;
+import android.net.wifi.WifiContext;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
@@ -61,7 +61,7 @@ public class RssiMonitorTest extends WifiBaseTest {
private RssiMonitor mRssiMonitor;
private WifiGlobals mWifiGlobals;
private TestLooper mLooper;
- @Mock Context mContext;
+ @Mock WifiContext mContext;
MockResources mMockResources = new MockResources();
private final WifiInfo mWifiInfo = new ExtendedWifiInfo(mWifiGlobals, TEST_INTERFACE_NAME);
@Mock WifiNative mWifiNative;
diff --git a/service/tests/wifitests/src/com/android/server/wifi/ScanRequestProxyTest.java b/service/tests/wifitests/src/com/android/server/wifi/ScanRequestProxyTest.java
index 9c87b0d718..8f52fa5204 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/ScanRequestProxyTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/ScanRequestProxyTest.java
@@ -151,10 +151,11 @@ public class ScanRequestProxyTest extends WifiBaseTest {
// Scan throttling is enabled by default.
when(mWifiSettingsConfigStore.get(eq(WIFI_SCAN_THROTTLE_ENABLED))).thenReturn(true);
+ WifiThreadRunner threadRunner = new WifiThreadRunner(new Handler(mLooper.getLooper()));
mScanRequestProxy =
new ScanRequestProxy(mContext, mAppOps, mActivityManager, mWifiInjector,
mWifiConfigManager, mWifiPermissionsUtil, mWifiMetrics, mClock,
- new Handler(mLooper.getLooper()), mWifiSettingsConfigStore);
+ threadRunner, mWifiSettingsConfigStore);
mScanRequestProxy.enableVerboseLogging(true);
when(mScanResultsCallback.asBinder()).thenReturn(mBinder);
when(mAnotherScanResultsCallback.asBinder()).thenReturn(mAnotherBinder);
diff --git a/service/tests/wifitests/src/com/android/server/wifi/SoftApManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/SoftApManagerTest.java
index b784680d3b..aeb84c21e5 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/SoftApManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/SoftApManagerTest.java
@@ -77,6 +77,7 @@ import android.net.wifi.WifiContext;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiScanner;
+import android.net.wifi.nl80211.DeviceWiphyCapabilities;
import android.net.wifi.nl80211.NativeWifiClient;
import android.os.BatteryManager;
import android.os.Message;
@@ -174,8 +175,10 @@ public class SoftApManagerTest extends WifiBaseTest {
private static final int[] TEST_SUPPORTED_24G_CHANNELS = new int[] {1, 2};
private static final int[] TEST_SUPPORTED_5G_CHANNELS = new int[] {36, 149};
- private boolean mApBridgeIfaceCobinationSupported = true;
- private boolean mApBridgeWithStaIfaceCobinationSupported = true;
+ private boolean mApBridgeIfaceCombinationSupported = true;
+ private boolean mApBridgeWithStaIfaceCombinationSupported = true;
+ private boolean mIsDriverSupportedRegChangedEvent = false;
+ private boolean mDeviceWiphyCapabilitiesSupports11Be = false;
private TestLooper mLooper;
private TestAlarmManager mAlarmManager;
@@ -216,6 +219,7 @@ public class SoftApManagerTest extends WifiBaseTest {
@Mock WifiInjector mWifiInjector;
@Mock WifiCountryCode mWifiCountryCode;
@Mock LocalLog mLocalLog;
+ @Mock DeviceWiphyCapabilities mDeviceWiphyCapabilities;
final ArgumentCaptor<WifiNative.InterfaceCallback> mWifiNativeInterfaceCallbackCaptor =
ArgumentCaptor.forClass(WifiNative.InterfaceCallback.class);
@@ -371,13 +375,13 @@ public class SoftApManagerTest extends WifiBaseTest {
if (combo.contentEquals(new SparseArray<Integer>() {{
put(HDM_CREATE_IFACE_AP_BRIDGE, 1);
}})) {
- return mApBridgeIfaceCobinationSupported;
+ return mApBridgeIfaceCombinationSupported;
}
if (combo.contentEquals(new SparseArray<Integer>() {{
put(HDM_CREATE_IFACE_AP_BRIDGE, 1);
put(HDM_CREATE_IFACE_STA, 1);
}})) {
- return mApBridgeWithStaIfaceCobinationSupported;
+ return mApBridgeWithStaIfaceCombinationSupported;
}
return false;
});
@@ -403,6 +407,10 @@ public class SoftApManagerTest extends WifiBaseTest {
when(mWifiNative.forceClientDisconnect(any(), any(), anyInt())).thenReturn(true);
when(mWifiInjector.getWifiHandlerLocalLog()).thenReturn(mLocalLog);
when(mWifiInjector.getWifiCountryCode()).thenReturn(mWifiCountryCode);
+ when(mWifiNative.getDeviceWiphyCapabilities(any(), anyBoolean())).thenReturn(
+ mDeviceWiphyCapabilities);
+ when(mDeviceWiphyCapabilities.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE))
+ .thenReturn(false);
// Init Test SoftAp infos
mTestSoftApInfo = new SoftApInfo();
@@ -747,18 +755,14 @@ public class SoftApManagerTest extends WifiBaseTest {
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
if (SdkLevel.isAtLeastSv2()) {
- verify(mContext, times(2)).sendBroadcastAsUser(intentCaptor.capture(),
+ verify(mContext, times(1)).sendBroadcastAsUser(intentCaptor.capture(),
eq(UserHandle.ALL), eq(android.Manifest.permission.ACCESS_WIFI_STATE));
} else {
- verify(mContext, times(2)).sendStickyBroadcastAsUser(intentCaptor.capture(),
+ verify(mContext, times(1)).sendStickyBroadcastAsUser(intentCaptor.capture(),
eq(UserHandle.ALL));
}
- List<Intent> capturedIntents = intentCaptor.getAllValues();
- checkApStateChangedBroadcast(capturedIntents.get(0), WIFI_AP_STATE_ENABLING,
- WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR, TEST_INTERFACE_NAME,
- softApConfig.getTargetMode());
- checkApStateChangedBroadcast(capturedIntents.get(1), WIFI_AP_STATE_FAILED,
- WIFI_AP_STATE_ENABLING, WifiManager.SAP_START_FAILURE_GENERAL, TEST_INTERFACE_NAME,
+ checkApStateChangedBroadcast(intentCaptor.getValue(), WIFI_AP_STATE_FAILED,
+ WIFI_AP_STATE_DISABLED, WifiManager.SAP_START_FAILURE_GENERAL, TEST_INTERFACE_NAME,
softApConfig.getTargetMode());
verify(mWifiMetrics).writeSoftApStartedEvent(
eq(SoftApManager.START_RESULT_FAILURE_SET_COUNTRY_CODE),
@@ -786,19 +790,14 @@ public class SoftApManagerTest extends WifiBaseTest {
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
if (SdkLevel.isAtLeastSv2()) {
- verify(mContext, times(2)).sendBroadcastAsUser(intentCaptor.capture(),
+ verify(mContext, times(1)).sendBroadcastAsUser(intentCaptor.capture(),
eq(UserHandle.ALL), eq(android.Manifest.permission.ACCESS_WIFI_STATE));
} else {
- verify(mContext, times(2)).sendStickyBroadcastAsUser(intentCaptor.capture(),
+ verify(mContext, times(1)).sendStickyBroadcastAsUser(intentCaptor.capture(),
eq(UserHandle.ALL));
}
-
- List<Intent> capturedIntents = intentCaptor.getAllValues();
- checkApStateChangedBroadcast(capturedIntents.get(0), WIFI_AP_STATE_ENABLING,
- WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR, TEST_INTERFACE_NAME,
- softApConfig.getTargetMode());
- checkApStateChangedBroadcast(capturedIntents.get(1), WIFI_AP_STATE_FAILED,
- WIFI_AP_STATE_ENABLING, WifiManager.SAP_START_FAILURE_GENERAL, TEST_INTERFACE_NAME,
+ checkApStateChangedBroadcast(intentCaptor.getValue(), WIFI_AP_STATE_FAILED,
+ WIFI_AP_STATE_DISABLED, WifiManager.SAP_START_FAILURE_GENERAL, TEST_INTERFACE_NAME,
softApConfig.getTargetMode());
}
@@ -826,19 +825,14 @@ public class SoftApManagerTest extends WifiBaseTest {
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
if (SdkLevel.isAtLeastSv2()) {
- verify(mContext, times(2)).sendBroadcastAsUser(intentCaptor.capture(),
+ verify(mContext, times(1)).sendBroadcastAsUser(intentCaptor.capture(),
eq(UserHandle.ALL), eq(android.Manifest.permission.ACCESS_WIFI_STATE));
} else {
- verify(mContext, times(2)).sendStickyBroadcastAsUser(intentCaptor.capture(),
+ verify(mContext, times(1)).sendStickyBroadcastAsUser(intentCaptor.capture(),
eq(UserHandle.ALL));
}
-
- List<Intent> capturedIntents = intentCaptor.getAllValues();
- checkApStateChangedBroadcast(capturedIntents.get(0), WIFI_AP_STATE_ENABLING,
- WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR, TEST_INTERFACE_NAME,
- softApConfig.getTargetMode());
- checkApStateChangedBroadcast(capturedIntents.get(1), WIFI_AP_STATE_FAILED,
- WIFI_AP_STATE_ENABLING, WifiManager.SAP_START_FAILURE_GENERAL, TEST_INTERFACE_NAME,
+ checkApStateChangedBroadcast(intentCaptor.getValue(), WIFI_AP_STATE_FAILED,
+ WIFI_AP_STATE_DISABLED, WifiManager.SAP_START_FAILURE_GENERAL, TEST_INTERFACE_NAME,
softApConfig.getTargetMode());
}
@@ -867,19 +861,14 @@ public class SoftApManagerTest extends WifiBaseTest {
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
if (SdkLevel.isAtLeastSv2()) {
- verify(mContext, times(2)).sendBroadcastAsUser(intentCaptor.capture(),
+ verify(mContext, times(1)).sendBroadcastAsUser(intentCaptor.capture(),
eq(UserHandle.ALL), eq(android.Manifest.permission.ACCESS_WIFI_STATE));
} else {
- verify(mContext, times(2)).sendStickyBroadcastAsUser(intentCaptor.capture(),
+ verify(mContext, times(1)).sendStickyBroadcastAsUser(intentCaptor.capture(),
eq(UserHandle.ALL));
}
-
- List<Intent> capturedIntents = intentCaptor.getAllValues();
- checkApStateChangedBroadcast(capturedIntents.get(0), WIFI_AP_STATE_ENABLING,
- WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR, TEST_INTERFACE_NAME,
- softApConfig.getTargetMode());
- checkApStateChangedBroadcast(capturedIntents.get(1), WIFI_AP_STATE_FAILED,
- WIFI_AP_STATE_ENABLING, WifiManager.SAP_START_FAILURE_GENERAL, TEST_INTERFACE_NAME,
+ checkApStateChangedBroadcast(intentCaptor.getValue(), WIFI_AP_STATE_FAILED,
+ WIFI_AP_STATE_DISABLED, WifiManager.SAP_START_FAILURE_GENERAL, TEST_INTERFACE_NAME,
softApConfig.getTargetMode());
}
@@ -2470,14 +2459,14 @@ public class SoftApManagerTest extends WifiBaseTest {
} else {
expectedConfig = config;
}
- if (SdkLevel.isAtLeastT()
- && expectedConfig.isIeee80211beEnabled()
- && !softApConfig.getCapability().areFeaturesSupported(
- SoftApCapability.SOFTAP_FEATURE_IEEE80211_BE)) {
- expectedConfig = new SoftApConfiguration.Builder(expectedConfig)
- .setIeee80211beEnabled(false)
- .build();
- }
+ }
+
+ if (SdkLevel.isAtLeastT()
+ && expectedConfig.isIeee80211beEnabled()
+ && !mDeviceWiphyCapabilitiesSupports11Be) {
+ expectedConfig = new SoftApConfiguration.Builder(expectedConfig)
+ .setIeee80211beEnabled(false)
+ .build();
}
SoftApConfiguration expectedConfigWithFrameworkACS = null;
@@ -2534,9 +2523,6 @@ public class SoftApManagerTest extends WifiBaseTest {
eq(mSoftApManager), anyList());
ArgumentCaptor<SoftApConfiguration> configCaptor =
ArgumentCaptor.forClass(SoftApConfiguration.class);
- order.verify(mCallback).onStateChanged(eq(new SoftApState(
- WifiManager.WIFI_AP_STATE_ENABLING, 0,
- softApConfig.getTetheringRequest(), TEST_INTERFACE_NAME)));
if (!TextUtils.isEmpty(softApConfig.getCountryCode())
&& !TextUtils.equals(
softApConfig.getCountryCode(),
@@ -2561,7 +2547,24 @@ public class SoftApManagerTest extends WifiBaseTest {
verify(mWifiCountryCode).unregisterListener(changeListenerCaptor.getValue());
assertThat(mSoftApManager.getSoftApModeConfiguration().getCapability().getCountryCode())
.isEqualTo(softApConfig.getCountryCode());
+ } else if (TextUtils.isEmpty(softApConfig.getCountryCode())
+ && mIsDriverSupportedRegChangedEvent && expectedConfig.getBands().length == 1) {
+ // Don't start SoftAP before driver country code change.
+ verify(mWifiNative, never()).startSoftAp(any(), any(), anyBoolean(), any());
+
+ ArgumentCaptor<WifiCountryCode.ChangeListener> changeListenerCaptor =
+ ArgumentCaptor.forClass(WifiCountryCode.ChangeListener.class);
+ verify(mWifiCountryCode).registerListener(changeListenerCaptor.capture());
+ // Now notify any country code.
+ changeListenerCaptor.getValue().onDriverCountryCodeChanged("some country");
+ mLooper.dispatchAll();
+ verify(mWifiCountryCode).unregisterListener(changeListenerCaptor.getValue());
+ assertThat(mSoftApManager.getSoftApModeConfiguration().getCapability().getCountryCode())
+ .isEqualTo("some country");
}
+ order.verify(mCallback).onStateChanged(eq(new SoftApState(
+ WifiManager.WIFI_AP_STATE_ENABLING, 0,
+ softApConfig.getTetheringRequest(), TEST_INTERFACE_NAME)));
order.verify(mWifiNative).startSoftAp(eq(TEST_INTERFACE_NAME),
configCaptor.capture(),
eq(softApConfig.getTargetMode() == WifiManager.IFACE_IP_MODE_TETHERED),
@@ -2799,6 +2802,9 @@ public class SoftApManagerTest extends WifiBaseTest {
Builder configBuilder = new SoftApConfiguration.Builder();
configBuilder.setBand(SoftApConfiguration.BAND_2GHZ);
configBuilder.setSsid(TEST_SSID);
+ if (SdkLevel.isAtLeastT()) {
+ configBuilder.setIeee80211beEnabled(false);
+ }
SoftApModeConfiguration apConfig = new SoftApModeConfiguration(
WifiManager.IFACE_IP_MODE_TETHERED, configBuilder.build(), mTestSoftApCapability,
@@ -3778,6 +3784,7 @@ public class SoftApManagerTest extends WifiBaseTest {
public void testWaitForDriverCountryCode() throws Exception {
when(mResources.getBoolean(
R.bool.config_wifiDriverSupportedNl80211RegChangedEvent)).thenReturn(true);
+ mIsDriverSupportedRegChangedEvent = true;
SoftApModeConfiguration apConfig =
new SoftApModeConfiguration(WifiManager.IFACE_IP_MODE_TETHERED, null,
mTestSoftApCapability, "Not " + TEST_COUNTRY_CODE, TEST_TETHERING_REQUEST);
@@ -3788,6 +3795,7 @@ public class SoftApManagerTest extends WifiBaseTest {
public void testWaitForDriverCountryCodeTimedOut() throws Exception {
when(mResources.getBoolean(
R.bool.config_wifiDriverSupportedNl80211RegChangedEvent)).thenReturn(true);
+ mIsDriverSupportedRegChangedEvent = true;
SoftApModeConfiguration apConfig =
new SoftApModeConfiguration(WifiManager.IFACE_IP_MODE_TETHERED, null,
mTestSoftApCapability, "Not" + TEST_COUNTRY_CODE, TEST_TETHERING_REQUEST);
@@ -3806,6 +3814,23 @@ public class SoftApManagerTest extends WifiBaseTest {
}
@Test
+ public void testWaitForDriverCountryCodeWhenNoInitialCountryCodeFor5GHz() throws Exception {
+ when(mResources.getBoolean(
+ R.bool.config_wifiDriverSupportedNl80211RegChangedEvent)).thenReturn(true);
+ mIsDriverSupportedRegChangedEvent = true;
+ Builder configBuilder = new SoftApConfiguration.Builder();
+ configBuilder.setBand(SoftApConfiguration.BAND_5GHZ);
+ configBuilder.setSsid(TEST_SSID);
+ SoftApModeConfiguration apConfig =
+ new SoftApModeConfiguration(WifiManager.IFACE_IP_MODE_TETHERED,
+ configBuilder.build(), mTestSoftApCapability, null,
+ TEST_TETHERING_REQUEST);
+ startSoftApAndVerifyEnabled(apConfig);
+ mLooper.dispatchAll();
+ verify(mWifiNative, never()).setApCountryCode(any(), any());
+ }
+
+ @Test
public void testUpdateCountryCodeWhenConfigDisabled() throws Exception {
when(mResources.getBoolean(R.bool.config_wifiSoftApDynamicCountryCodeUpdateSupported))
.thenReturn(false);
@@ -3871,7 +3896,7 @@ public class SoftApManagerTest extends WifiBaseTest {
assumeTrue(SdkLevel.isAtLeastS());
when(mResources.getBoolean(R.bool.config_wifiStaWithBridgedSoftApConcurrencySupported))
.thenReturn(true);
- mApBridgeWithStaIfaceCobinationSupported = false;
+ mApBridgeWithStaIfaceCombinationSupported = false;
Builder configBuilder = new SoftApConfiguration.Builder(
generateBridgedModeSoftApConfig(null));
@@ -4013,21 +4038,155 @@ public class SoftApManagerTest extends WifiBaseTest {
/**
* Tests that 11BE is set to disabled in the SoftApConfiguration if it isn't supported by
- * SoftApCapability.
+ * device Capabilities.
*/
@Test
- public void testStartSoftApRemoves11BEIfNotSupported() throws Exception {
+ public void testStartSoftApRemoves11BEIfNotSupportedByDeviceCapabilities() throws Exception {
assumeTrue(SdkLevel.isAtLeastT());
- mTestSoftApCapability.setSupportedFeatures(false,
- SoftApCapability.SOFTAP_FEATURE_IEEE80211_BE);
+ when(mResources.getBoolean(R.bool.config_wifiSoftapIeee80211beSupported))
+ .thenReturn(true);
+ when(mDeviceWiphyCapabilities.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE))
+ .thenReturn(false);
Builder configBuilder = new SoftApConfiguration.Builder();
- configBuilder.setBand(SoftApConfiguration.BAND_2GHZ);
+ configBuilder.setBand(SoftApConfiguration.BAND_5GHZ);
configBuilder.setSsid(TEST_SSID);
configBuilder.setIeee80211beEnabled(true);
+ configBuilder.setPassphrase("somepassword",
+ SoftApConfiguration.SECURITY_TYPE_WPA3_SAE);
SoftApModeConfiguration apConfig = new SoftApModeConfiguration(
WifiManager.IFACE_IP_MODE_TETHERED, configBuilder.build(),
mTestSoftApCapability, TEST_COUNTRY_CODE, TEST_TETHERING_REQUEST);
SoftApConfiguration expectedConfig = configBuilder.setIeee80211beEnabled(false).build();
startSoftApAndVerifyEnabled(apConfig, expectedConfig, false);
}
+
+ /**
+ * Tests that 11BE is set to disabled in the SoftApConfiguration if it isn't supported by
+ * overlay configuration.
+ */
+ @Test
+ public void testStartSoftApRemoves11BEIfNotSupportedByOverlay() throws Exception {
+ assumeTrue(SdkLevel.isAtLeastT());
+ when(mResources.getBoolean(R.bool.config_wifiSoftapIeee80211beSupported))
+ .thenReturn(false);
+ when(mDeviceWiphyCapabilities.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE))
+ .thenReturn(true);
+ mDeviceWiphyCapabilitiesSupports11Be = true;
+ Builder configBuilder = new SoftApConfiguration.Builder();
+ configBuilder.setBand(SoftApConfiguration.BAND_5GHZ);
+ configBuilder.setSsid(TEST_SSID);
+ configBuilder.setIeee80211beEnabled(true);
+ configBuilder.setPassphrase("somepassword",
+ SoftApConfiguration.SECURITY_TYPE_WPA3_SAE);
+ SoftApModeConfiguration apConfig = new SoftApModeConfiguration(
+ WifiManager.IFACE_IP_MODE_TETHERED, configBuilder.build(),
+ mTestSoftApCapability, TEST_COUNTRY_CODE, TEST_TETHERING_REQUEST);
+ SoftApConfiguration expectedConfig = configBuilder.setIeee80211beEnabled(false).build();
+ startSoftApAndVerifyEnabled(apConfig, expectedConfig, false);
+ }
+
+ /**
+ * Tests that 11BE configuration is disabled in WPA2-PSK security type
+ */
+ @Test
+ public void testStartSoftApRemoves11BEInWpa2()throws Exception {
+ assumeTrue(SdkLevel.isAtLeastT());
+ when(mResources.getBoolean(R.bool.config_wifiSoftapIeee80211beSupported))
+ .thenReturn(true);
+ when(mDeviceWiphyCapabilities.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE))
+ .thenReturn(true);
+ mDeviceWiphyCapabilitiesSupports11Be = true;
+ Builder configBuilder = new SoftApConfiguration.Builder();
+ configBuilder.setBand(SoftApConfiguration.BAND_5GHZ);
+ configBuilder.setSsid(TEST_SSID);
+ configBuilder.setIeee80211beEnabled(true);
+ configBuilder.setPassphrase("somepassword",
+ SoftApConfiguration.SECURITY_TYPE_WPA2_PSK);
+ SoftApModeConfiguration apConfig = new SoftApModeConfiguration(
+ WifiManager.IFACE_IP_MODE_TETHERED, configBuilder.build(),
+ mTestSoftApCapability, TEST_COUNTRY_CODE, TEST_TETHERING_REQUEST);
+ // 11be is expected to be disabled in WPA2-PSK
+ SoftApConfiguration expectedConfig = configBuilder.setIeee80211beEnabled(false).build();
+ startSoftApAndVerifyEnabled(apConfig, expectedConfig, false);
+ }
+
+ /**
+ * Tests that 11BE configuration is disabled if device overlay doesn't support Single link MLO
+ * in bridged mode
+ */
+ @Test
+ public void testStartSoftApRemoves11BEInBridgedModeIfNotSupportedByOverlay()throws Exception {
+ assumeTrue(SdkLevel.isAtLeastT());
+ when(mResources.getBoolean(R.bool.config_wifiSoftapIeee80211beSupported))
+ .thenReturn(true);
+ when(mResources.getBoolean(R.bool.config_wifiSoftApSingleLinkMloInBridgedModeSupported))
+ .thenReturn(false);
+ when(mDeviceWiphyCapabilities.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE))
+ .thenReturn(true);
+ mDeviceWiphyCapabilitiesSupports11Be = true;
+ int[] dual_bands = {SoftApConfiguration.BAND_2GHZ,
+ SoftApConfiguration.BAND_5GHZ};
+ Builder configBuilder = new SoftApConfiguration.Builder();
+ configBuilder.setBands(dual_bands);
+ configBuilder.setSsid(TEST_SSID);
+ configBuilder.setIeee80211beEnabled(true);
+ configBuilder.setPassphrase("somepassword",
+ SoftApConfiguration.SECURITY_TYPE_WPA3_SAE);
+ SoftApModeConfiguration apConfig = new SoftApModeConfiguration(
+ WifiManager.IFACE_IP_MODE_TETHERED, configBuilder.build(),
+ mTestSoftApCapability, TEST_COUNTRY_CODE, TEST_TETHERING_REQUEST);
+ SoftApConfiguration expectedConfig = configBuilder.setIeee80211beEnabled(false).build();
+ startSoftApAndVerifyEnabled(apConfig, expectedConfig, false);
+ }
+
+ /**
+ * Tests that 11BE configuration is not disabled if device overlay support Single link MLO
+ * in bridged mode
+ */
+ @Test
+ public void testStartSoftApInBridgedMode11BEConfiguration()throws Exception {
+ assumeTrue(SdkLevel.isAtLeastT());
+ when(mResources.getBoolean(R.bool.config_wifiSoftapIeee80211beSupported))
+ .thenReturn(true);
+ when(mResources.getBoolean(R.bool.config_wifiSoftApSingleLinkMloInBridgedModeSupported))
+ .thenReturn(true);
+ when(mDeviceWiphyCapabilities.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE))
+ .thenReturn(true);
+ mDeviceWiphyCapabilitiesSupports11Be = true;
+ int[] dual_bands = {SoftApConfiguration.BAND_2GHZ,
+ SoftApConfiguration.BAND_5GHZ};
+ Builder configBuilder = new SoftApConfiguration.Builder();
+ configBuilder.setBands(dual_bands);
+ configBuilder.setSsid(TEST_SSID);
+ configBuilder.setIeee80211beEnabled(true);
+ configBuilder.setPassphrase("somepassword",
+ SoftApConfiguration.SECURITY_TYPE_WPA3_SAE);
+ SoftApModeConfiguration apConfig = new SoftApModeConfiguration(
+ WifiManager.IFACE_IP_MODE_TETHERED, configBuilder.build(),
+ mTestSoftApCapability, TEST_COUNTRY_CODE, TEST_TETHERING_REQUEST);
+ startSoftApAndVerifyEnabled(apConfig, configBuilder.build(), false);
+ }
+
+ /**
+ * Tests that 11BE configuration is not disabled in Single AP mode
+ */
+ @Test
+ public void testStartSoftApInSingleAp11BEConfiguration()throws Exception {
+ assumeTrue(SdkLevel.isAtLeastT());
+ when(mResources.getBoolean(R.bool.config_wifiSoftapIeee80211beSupported))
+ .thenReturn(true);
+ when(mDeviceWiphyCapabilities.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE))
+ .thenReturn(true);
+ mDeviceWiphyCapabilitiesSupports11Be = true;
+ Builder configBuilder = new SoftApConfiguration.Builder();
+ configBuilder.setBand(SoftApConfiguration.BAND_5GHZ);
+ configBuilder.setSsid(TEST_SSID);
+ configBuilder.setIeee80211beEnabled(true);
+ configBuilder.setPassphrase("somepassword",
+ SoftApConfiguration.SECURITY_TYPE_WPA3_SAE);
+ SoftApModeConfiguration apConfig = new SoftApModeConfiguration(
+ WifiManager.IFACE_IP_MODE_TETHERED, configBuilder.build(),
+ mTestSoftApCapability, TEST_COUNTRY_CODE, TEST_TETHERING_REQUEST);
+ startSoftApAndVerifyEnabled(apConfig, configBuilder.build(), false);
+ }
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/SupplicantStaIfaceHalAidlImplTest.java b/service/tests/wifitests/src/com/android/server/wifi/SupplicantStaIfaceHalAidlImplTest.java
index 16c8767c54..8747683c77 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/SupplicantStaIfaceHalAidlImplTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/SupplicantStaIfaceHalAidlImplTest.java
@@ -2407,11 +2407,20 @@ public class SupplicantStaIfaceHalAidlImplTest extends WifiBaseTest {
eq(WLAN0_IFACE_NAME), eq(TRANSLATED_SUPPLICANT_SSID.toString()));
validateConnectSequence(false, 2, SUPPLICANT_SSID);
- // Fallback SSID was not found, broadcast the network not found event now.
+ // Fallback SSID was not found, finally broadcast NETWORK_NOT_FOUND and try the first SSID
+ // again.
mISupplicantStaIfaceCallback.onNetworkNotFound(NativeUtil.byteArrayFromArrayList(
NativeUtil.decodeSsid(SUPPLICANT_SSID)));
verify(mWifiMonitor).broadcastNetworkNotFoundEvent(
eq(WLAN0_IFACE_NAME), eq(TRANSLATED_SUPPLICANT_SSID.toString()));
+ validateConnectSequence(false, 3, TRANSLATED_SUPPLICANT_SSID.toString());
+
+ // First SSID not found, try the fallback without broadcasting NETWORK_NOT_FOUND.
+ mISupplicantStaIfaceCallback.onNetworkNotFound(NativeUtil.byteArrayFromArrayList(
+ NativeUtil.decodeSsid(TRANSLATED_SUPPLICANT_SSID.toString())));
+ verify(mWifiMonitor, times(1)).broadcastNetworkNotFoundEvent(
+ eq(WLAN0_IFACE_NAME), eq(TRANSLATED_SUPPLICANT_SSID.toString()));
+ validateConnectSequence(false, 4, SUPPLICANT_SSID);
}
/**
@@ -3353,4 +3362,38 @@ public class SupplicantStaIfaceHalAidlImplTest extends WifiBaseTest {
assertEquals(streamTimeoutUs, halParams.streamTimeoutUs);
assertEquals(halFrameClassifierMask, halParams.frameClassifierMask);
}
+
+ /**
+ * Test that MSCS params set through {@link SupplicantStaIfaceHalAidlImpl#enableMscs(
+ * MscsParams, String)} are cached for later resends.
+ */
+ @Test
+ public void testEnableAndResendMscs() throws Exception {
+ executeAndValidateInitializationSequence();
+ mDut.setupIface(WLAN0_IFACE_NAME);
+
+ doNothing().when(mISupplicantStaIfaceMock).configureMscs(any());
+ MscsParams defaultParams = new MscsParams.Builder().build();
+
+ ArgumentCaptor<android.hardware.wifi.supplicant.MscsParams> halParamsCaptor =
+ ArgumentCaptor.forClass(android.hardware.wifi.supplicant.MscsParams.class);
+ mDut.enableMscs(defaultParams, WLAN0_IFACE_NAME);
+ verify(mISupplicantStaIfaceMock).configureMscs(halParamsCaptor.capture());
+ android.hardware.wifi.supplicant.MscsParams initialParams = halParamsCaptor.getValue();
+
+ // Resend should use the params cached during the initial send.
+ mDut.resendMscs(WLAN0_IFACE_NAME);
+ verify(mISupplicantStaIfaceMock, times(2)).configureMscs(halParamsCaptor.capture());
+ android.hardware.wifi.supplicant.MscsParams resendParams = halParamsCaptor.getValue();
+
+ assertEquals(initialParams.upBitmap, resendParams.upBitmap);
+ assertEquals(initialParams.upLimit, resendParams.upLimit);
+ assertEquals(initialParams.streamTimeoutUs, resendParams.streamTimeoutUs);
+ assertEquals(initialParams.frameClassifierMask, resendParams.frameClassifierMask);
+
+ // Disabling MSCS should clear the cached params and prevent future resends.
+ mDut.disableMscs(WLAN0_IFACE_NAME);
+ mDut.resendMscs(WLAN0_IFACE_NAME);
+ verify(mISupplicantStaIfaceMock, times(2)).configureMscs(halParamsCaptor.capture());
+ }
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/SupplicantStaIfaceHalHidlImplTest.java b/service/tests/wifitests/src/com/android/server/wifi/SupplicantStaIfaceHalHidlImplTest.java
index be19bc53d1..5d4507c69d 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/SupplicantStaIfaceHalHidlImplTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/SupplicantStaIfaceHalHidlImplTest.java
@@ -3884,10 +3884,19 @@ public class SupplicantStaIfaceHalHidlImplTest extends WifiBaseTest {
eq(WLAN0_IFACE_NAME), eq(TRANSLATED_SUPPLICANT_SSID.toString()));
validateConnectSequence(false, 2, SUPPLICANT_SSID);
- // Fallback SSID was not found, broadcast the network not found event now.
+ // Fallback SSID was not found, finally broadcast NETWORK_NOT_FOUND and try the first SSID
+ // again.
mISupplicantStaIfaceCallbackV14.onNetworkNotFound(NativeUtil.decodeSsid(SUPPLICANT_SSID));
verify(mWifiMonitor).broadcastNetworkNotFoundEvent(
eq(WLAN0_IFACE_NAME), eq(TRANSLATED_SUPPLICANT_SSID.toString()));
+ validateConnectSequence(false, 3, TRANSLATED_SUPPLICANT_SSID.toString());
+
+ // First SSID not found, try the fallback without broadcasting NETWORK_NOT_FOUND.
+ mISupplicantStaIfaceCallbackV14.onNetworkNotFound(NativeUtil.decodeSsid(
+ TRANSLATED_SUPPLICANT_SSID.toString()));
+ verify(mWifiMonitor, times(1)).broadcastNetworkNotFoundEvent(
+ eq(WLAN0_IFACE_NAME), eq(TRANSLATED_SUPPLICANT_SSID.toString()));
+ validateConnectSequence(false, 4, SUPPLICANT_SSID);
}
/**
diff --git a/service/tests/wifitests/src/com/android/server/wifi/TwtManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/TwtManagerTest.java
index e6210e6c4a..79db9d4cfd 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/TwtManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/TwtManagerTest.java
@@ -30,9 +30,11 @@ import static org.mockito.MockitoAnnotations.initMocks;
import android.app.AlarmManager;
import android.app.test.TestAlarmManager;
+import android.content.res.Resources;
import android.net.wifi.ITwtCallback;
import android.net.wifi.ITwtCapabilitiesListener;
import android.net.wifi.ITwtStatsListener;
+import android.net.wifi.WifiContext;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiTwtSession;
import android.net.wifi.twt.TwtRequest;
@@ -47,6 +49,8 @@ import android.os.test.TestLooper;
import androidx.test.filters.SmallTest;
+import com.android.wifi.resources.R;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
@@ -65,6 +69,12 @@ public class TwtManagerTest extends WifiBaseTest {
private static final int TEST_TWT_SESSION_ID = 10;
private static final int TEST_TWT_CMD_ID = 1;
+ private static final String TEST_BSSID = "00:11:22:33:44:55";
+ private static final String TEST_BLOCKED_BSSID_1 = "AA:BB:CC:DD:EE:FF";
+ private static final int TEST_BLOCKED_OUI_1 = 0xAABBCC;
+ private static final int TEST_BLOCKED_OUI_2 = 0xAABBCD;
+ private static final int TEST_BLOCKED_OUI_3 = 0xAABBCE;
+ private static final int TEST_BLOCKED_OUI_4 = 0xAABBCF;
@Mock
Clock mClock;
@@ -87,6 +97,10 @@ public class TwtManagerTest extends WifiBaseTest {
ConcreteClientModeManager mClientModeManager;
@Captor
private ArgumentCaptor<TwtManager.WifiNativeTwtEvents> mWifiNativeTwtEventsArgumentCaptor;
+ @Mock
+ Resources mResources;
+ @Mock
+ WifiContext mContext;
/**
* Test setup.
@@ -98,11 +112,26 @@ public class TwtManagerTest extends WifiBaseTest {
mTestAlarmManager = new TestAlarmManager();
mAlarmManager = mTestAlarmManager.getAlarmManager();
when(mWifiInjector.getAlarmManager()).thenReturn(mAlarmManager);
+ when(mWifiInjector.getContext()).thenReturn(mContext);
+ when(mContext.getResources()).thenReturn(mResources);
+ int[] blockedOuiList =
+ {TEST_BLOCKED_OUI_4, TEST_BLOCKED_OUI_3, TEST_BLOCKED_OUI_2, TEST_BLOCKED_OUI_1};
+ when(mResources.getIntArray(R.array.config_wifiTwtBlockedOuiList)).thenReturn(
+ blockedOuiList);
+ when(mResources.getBoolean(R.bool.config_wifiTwtSupported)).thenReturn(true);
mTwtManager = new TwtManager(mWifiInjector, mCmiMonitor, mWifiNative, mHandler, mClock,
WifiTwtSession.MAX_TWT_SESSIONS, TWT_CALLBACKS_ID_START_OFFSET);
verify(mCmiMonitor).registerListener(mCmiListenerCaptor.capture());
mTwtManager.registerWifiNativeTwtEvents();
verify(mWifiNative).registerTwtCallbacks(mWifiNativeTwtEventsArgumentCaptor.capture());
+ when(mWifiNative.getTwtCapabilities(eq(WIFI_IFACE_NAME))).thenReturn(
+ getMockTwtCapabilities());
+ }
+
+ private void disableTwtSupport() {
+ when(mResources.getBoolean(R.bool.config_wifiTwtSupported)).thenReturn(false);
+ mTwtManager = new TwtManager(mWifiInjector, mCmiMonitor, mWifiNative, mHandler, mClock,
+ WifiTwtSession.MAX_TWT_SESSIONS, TWT_CALLBACKS_ID_START_OFFSET);
}
private Bundle getDefaultTwtCapabilities() {
@@ -179,6 +208,25 @@ public class TwtManagerTest extends WifiBaseTest {
mTwtManager.getTwtCapabilities(WIFI_IFACE_NAME, iTwtCapabilitiesListener);
inorder.verify(iTwtCapabilitiesListener).onResult(
argThat(argument -> isBundleContentEqual(mockTwtCapabilities, argument)));
+ // Disable overlay and test
+ disableTwtSupport();
+ mTwtManager.getTwtCapabilities(WIFI_IFACE_NAME, iTwtCapabilitiesListener);
+ inorder.verify(iTwtCapabilitiesListener).onResult(
+ argThat(argument -> isBundleContentEqual(defaultTwtCapabilities, argument)));
+ }
+
+ @Test
+ public void testOuiBlockListing() throws RemoteException {
+ ITwtCallback iTwtCallback = mock(ITwtCallback.class);
+ TwtRequest twtRequest = mock(TwtRequest.class);
+ InOrder inOrderCallback = inOrder(iTwtCallback);
+ when(iTwtCallback.asBinder()).thenReturn(mAppBinder);
+ when(mWifiNative.setupTwtSession(eq(1), eq(WIFI_IFACE_NAME), eq(twtRequest))).thenReturn(
+ true);
+ mTwtManager.setupTwtSession(WIFI_IFACE_NAME, twtRequest, iTwtCallback,
+ Binder.getCallingUid(), TEST_BLOCKED_BSSID_1);
+ inOrderCallback.verify(iTwtCallback).onFailure(
+ TwtSessionCallback.TWT_ERROR_CODE_AP_OUI_BLOCKLISTED);
}
@Test
@@ -190,14 +238,15 @@ public class TwtManagerTest extends WifiBaseTest {
InOrder inOrderBinder = inOrder(mAppBinder);
InOrder inOrderAlarm = inOrder(mAlarmManager);
// Test with null interface
- mTwtManager.setupTwtSession(null, twtRequest, iTwtCallback, Binder.getCallingUid());
+ mTwtManager.setupTwtSession(null, twtRequest, iTwtCallback, Binder.getCallingUid(),
+ TEST_BSSID);
inOrderCallback.verify(iTwtCallback).onFailure(
- TwtSessionCallback.TWT_ERROR_CODE_NOT_AVAILABLE);
+ TwtSessionCallback.TWT_ERROR_CODE_NOT_SUPPORTED);
// Test when wifiNative.setupTwtSession return false
when(mWifiNative.setupTwtSession(eq(1), eq(WIFI_IFACE_NAME), eq(twtRequest))).thenReturn(
false);
mTwtManager.setupTwtSession(WIFI_IFACE_NAME, twtRequest, iTwtCallback,
- Binder.getCallingUid());
+ Binder.getCallingUid(), TEST_BSSID);
inOrderBinder.verify(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt());
inOrderAlarm.verify(mAlarmManager).set(eq(AlarmManager.ELAPSED_REALTIME), anyLong(),
anyString(), any(AlarmManager.OnAlarmListener.class), eq(mHandler));
@@ -209,10 +258,32 @@ public class TwtManagerTest extends WifiBaseTest {
when(mWifiNative.setupTwtSession(eq(1), eq(WIFI_IFACE_NAME), eq(twtRequest))).thenReturn(
true);
mTwtManager.setupTwtSession(WIFI_IFACE_NAME, twtRequest, iTwtCallback,
- Binder.getCallingUid());
+ Binder.getCallingUid(), TEST_BSSID);
inOrderBinder.verify(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt());
inOrderAlarm.verify(mAlarmManager).set(eq(AlarmManager.ELAPSED_REALTIME), anyLong(),
anyString(), any(AlarmManager.OnAlarmListener.class), eq(mHandler));
+ // Enable overlay, disable TWT capability, and test
+ when(mWifiNative.getTwtCapabilities(eq(WIFI_IFACE_NAME))).thenReturn(
+ getDefaultTwtCapabilities());
+ mTwtManager.setupTwtSession(WIFI_IFACE_NAME, twtRequest, iTwtCallback,
+ Binder.getCallingUid(), TEST_BSSID);
+ inOrderCallback.verify(iTwtCallback).onFailure(
+ TwtSessionCallback.TWT_ERROR_CODE_NOT_SUPPORTED);
+ // Disable overlay, enable TWT capability, and test
+ when(mWifiNative.getTwtCapabilities(eq(WIFI_IFACE_NAME))).thenReturn(
+ getMockTwtCapabilities());
+ disableTwtSupport();
+ mTwtManager.setupTwtSession(WIFI_IFACE_NAME, twtRequest, iTwtCallback,
+ Binder.getCallingUid(), TEST_BSSID);
+ inOrderCallback.verify(iTwtCallback).onFailure(
+ TwtSessionCallback.TWT_ERROR_CODE_NOT_SUPPORTED);
+ // Disable overlay, disable TWT capability, and test
+ when(mWifiNative.getTwtCapabilities(eq(WIFI_IFACE_NAME))).thenReturn(
+ getDefaultTwtCapabilities());
+ mTwtManager.setupTwtSession(WIFI_IFACE_NAME, twtRequest, iTwtCallback,
+ Binder.getCallingUid(), TEST_BSSID);
+ inOrderCallback.verify(iTwtCallback).onFailure(
+ TwtSessionCallback.TWT_ERROR_CODE_NOT_SUPPORTED);
}
@Test
@@ -234,7 +305,7 @@ public class TwtManagerTest extends WifiBaseTest {
inOrderAlarm.verifyNoMoreInteractions();
// Make a session
mTwtManager.setupTwtSession(WIFI_IFACE_NAME, twtRequest, iTwtCallback,
- Binder.getCallingUid());
+ Binder.getCallingUid(), TEST_BSSID);
inOrderBinder.verify(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt());
inOrderAlarm.verify(mAlarmManager).set(eq(AlarmManager.ELAPSED_REALTIME), anyLong(),
anyString(), any(AlarmManager.OnAlarmListener.class), eq(mHandler));
@@ -282,7 +353,7 @@ public class TwtManagerTest extends WifiBaseTest {
argThat(argument -> isBundleContentEqual(defaultTwtStats, argument)));
// Make a session
mTwtManager.setupTwtSession(WIFI_IFACE_NAME, twtRequest, iTwtCallback,
- Binder.getCallingUid());
+ Binder.getCallingUid(), TEST_BSSID);
inOrderBinder.verify(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt());
inOrderAlarm.verify(mAlarmManager).set(eq(AlarmManager.ELAPSED_REALTIME), anyLong(),
anyString(), any(AlarmManager.OnAlarmListener.class), eq(mHandler));
@@ -313,7 +384,7 @@ public class TwtManagerTest extends WifiBaseTest {
when(mWifiNative.setupTwtSession(eq(1), eq(WIFI_IFACE_NAME), eq(twtRequest))).thenReturn(
true);
mTwtManager.setupTwtSession(WIFI_IFACE_NAME, twtRequest, iTwtCallback,
- Binder.getCallingUid());
+ Binder.getCallingUid(), TEST_BSSID);
inOrderBinder.verify(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt());
inOrderAlarm.verify(mAlarmManager).set(eq(AlarmManager.ELAPSED_REALTIME), anyLong(),
anyString(), any(AlarmManager.OnAlarmListener.class), eq(mHandler));
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WakeupControllerTest.java b/service/tests/wifitests/src/com/android/server/wifi/WakeupControllerTest.java
index e3643944ff..10ae4d9fbb 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WakeupControllerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WakeupControllerTest.java
@@ -265,6 +265,26 @@ public class WakeupControllerTest extends WifiBaseTest {
}
/**
+ * Verify WakeupController is disabled when the location mode is disabled.
+ */
+ @Test
+ public void verifyDisabledWhenLocationOff() {
+ initializeWakeupController(true /* enabled */);
+ when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(false);
+ assertFalse(mWakeupController.isEnabledAndReady());
+ }
+
+ /**
+ * Verify WakeupController is disabled when scan is disabled.
+ */
+ @Test
+ public void verifyDisabledWhenScanOff() {
+ initializeWakeupController(true /* enabled */);
+ when(mWifiSettingsStore.isScanAlwaysAvailableToggleEnabled()).thenReturn(false);
+ assertFalse(mWakeupController.isEnabledAndReady());
+ }
+
+ /**
* Verify WakeupController registers its store data with the WifiConfigStore on construction.
*/
@Test
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WakeupLockTest.java b/service/tests/wifitests/src/com/android/server/wifi/WakeupLockTest.java
index 52f9783742..a25a17d537 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WakeupLockTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WakeupLockTest.java
@@ -18,8 +18,9 @@ package com.android.server.wifi;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import android.net.wifi.SecurityParams;
import android.net.wifi.WifiConfiguration;
@@ -148,7 +149,7 @@ public class WakeupLockTest extends WifiBaseTest {
mWakeupLock.update(networks);
// want 2 invocations, once for setLock(), once for addToLock
- verify(mWifiConfigManager, times(2)).saveToStore(false);
+ verify(mWifiConfigManager, times(2)).saveToStore();
}
/**
@@ -251,7 +252,7 @@ public class WakeupLockTest extends WifiBaseTest {
@Test
public void initializeShouldSaveSsidsToStore() {
setLockAndInitializeByTimeout(Collections.singletonList(mNetwork1));
- verify(mWifiConfigManager).saveToStore(eq(false));
+ verify(mWifiConfigManager).saveToStore();
}
/**
@@ -263,7 +264,7 @@ public class WakeupLockTest extends WifiBaseTest {
updateEnoughTimesToEvictWithoutAsserts(Collections.emptyList());
// need exactly 2 invocations: 1 for initialize, 1 for successful update
- verify(mWifiConfigManager, times(2)).saveToStore(eq(false));
+ verify(mWifiConfigManager, times(2)).saveToStore();
}
/**
@@ -273,7 +274,7 @@ public class WakeupLockTest extends WifiBaseTest {
public void updateShouldNotSaveIfLockDoesNotChange() {
List<ScanResultMatchInfo> networks = Collections.singletonList(mNetwork1);
setLockAndInitializeByTimeout(networks);
- verify(mWifiConfigManager, times(1)).saveToStore(anyBoolean());
+ verify(mWifiConfigManager, times(1)).saveToStore();
mWakeupLock.update(networks);
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WakeupOnboardingTest.java b/service/tests/wifitests/src/com/android/server/wifi/WakeupOnboardingTest.java
index d045b04d46..8bafe1d4b2 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WakeupOnboardingTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WakeupOnboardingTest.java
@@ -204,7 +204,7 @@ public class WakeupOnboardingTest extends WifiBaseTest {
public void setOnboardedSavesToStore() {
setOnboardedStatus(false);
mWakeupOnboarding.setOnboarded();
- verify(mWifiConfigManager).saveToStore(false /* forceWrite */);
+ verify(mWifiConfigManager).saveToStore();
assertTrue(mWakeupOnboarding.isOnboarded());
}
@@ -216,7 +216,7 @@ public class WakeupOnboardingTest extends WifiBaseTest {
setOnboardedStatus(false);
setNotificationsShown(0);
mWakeupOnboarding.maybeShowNotification();
- verify(mWifiConfigManager).saveToStore(false /* forceWrite */);
+ verify(mWifiConfigManager).saveToStore();
}
/**
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiApConfigStoreTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiApConfigStoreTest.java
index 644d022cdd..d1642fa328 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiApConfigStoreTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiApConfigStoreTest.java
@@ -13,7 +13,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
package com.android.server.wifi;
import static android.net.wifi.SoftApConfiguration.RANDOMIZATION_NON_PERSISTENT;
@@ -23,6 +22,7 @@ import static android.net.wifi.SoftApConfiguration.SECURITY_TYPE_WPA3_SAE;
import static android.net.wifi.SoftApConfiguration.SECURITY_TYPE_WPA3_SAE_TRANSITION;
import static com.android.server.wifi.HalDeviceManager.HDM_CREATE_IFACE_AP_BRIDGE;
+import static com.android.server.wifi.WifiSettingsConfigStore.WIFI_STATIC_CHIP_INFO;
import static com.google.common.truth.Truth.assertThat;
@@ -33,9 +33,11 @@ import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -110,6 +112,8 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
@Mock private ActiveModeWarden mActiveModeWarden;
@Mock private PackageManager mPackageManager;
@Mock private SoftApCapability mSoftApCapability;
+ @Mock private HalDeviceManager mHalDeviceManager;
+ @Mock private WifiSettingsConfigStore mWifiSettingsConfigStore;
private Random mRandom;
private MockResources mResources;
@@ -118,6 +122,10 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
private SoftApStoreData.DataSource mDataStoreSource;
private ArrayList<Integer> mKnownGood2GChannelList;
+ final ArgumentCaptor<WifiSettingsConfigStore.OnSettingsChangedListener>
+ mStaticChipInfoListenerCaptor =
+ ArgumentCaptor.forClass(WifiSettingsConfigStore.OnSettingsChangedListener.class);
+
@Before
public void setUp() throws Exception {
mLooper = new TestLooper();
@@ -125,7 +133,10 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
MockitoAnnotations.initMocks(this);
mMockApplInfo.targetSdkVersion = Build.VERSION_CODES.P;
when(mContext.getApplicationInfo()).thenReturn(mMockApplInfo);
-
+ when(mWifiInjector.getSettingsConfigStore()).thenReturn(mWifiSettingsConfigStore);
+ when(mWifiInjector.getHalDeviceManager()).thenReturn(mHalDeviceManager);
+ // Default assume true for all old test cases.
+ when(mHalDeviceManager.isConcurrencyComboLoadedFromDriver()).thenReturn(true);
/* Setup expectations for Resources to return some default settings. */
mResources = new MockResources();
mResources.setString(R.string.config_wifiSoftap2gChannelList,
@@ -187,7 +198,10 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
ArgumentCaptor.forClass(SoftApStoreData.DataSource.class);
verify(mWifiInjector).makeSoftApStoreData(dataStoreSourceArgumentCaptor.capture());
mDataStoreSource = dataStoreSourceArgumentCaptor.getValue();
-
+ verify(mWifiSettingsConfigStore).registerChangeListener(
+ eq(WIFI_STATIC_CHIP_INFO),
+ mStaticChipInfoListenerCaptor.capture(),
+ any(Handler.class));
return store;
}
@@ -223,7 +237,6 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
verifyDefaultApConfig(config, expectedSsid, isSaeSupport, true, false);
}
-
private void verifyDefaultApConfig(SoftApConfiguration config, String expectedSsid,
boolean isSaeSupport, boolean isMacRandomizationSupport, boolean isBridgedApSupport) {
String[] splitSsid = config.getWifiSsid().getUtf8Text().toString().split("_");
@@ -315,7 +328,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
WifiApConfigStore store = createWifiApConfigStore();
verifyDefaultApConfig(store.getApConfiguration(), TEST_DEFAULT_AP_SSID);
mLooper.dispatchAll();
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
}
@@ -344,7 +357,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
verifyDefaultApConfig(store.getApConfiguration(), TEST_DEFAULT_AP_SSID);
verifyDefaultApConfig(mDataStoreSource.toSerialize(), TEST_DEFAULT_AP_SSID);
mLooper.dispatchAll();
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
verify(mBackupManagerProxy).notifyDataChanged();
assertFalse(store.getApConfiguration().isUserConfigurationInternal());
assertNotEquals(lassPassphrase, store.getLastConfiguredTetheredApPassphraseSinceBoot());
@@ -363,7 +376,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
verifyDefaultApConfig(store.getApConfiguration(), TEST_DEFAULT_AP_SSID);
assertFalse(store.getApConfiguration().isUserConfigurationInternal());
mLooper.dispatchAll();
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
/* Update with a valid configuration. */
SoftApConfiguration expectedConfig = setupApConfig(
@@ -380,7 +393,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
.getPersistentRandomizedMacAddress());
verifyApConfig(expectedConfig, mDataStoreSource.toSerialize());
mLooper.dispatchAll();
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
verify(mBackupManagerProxy, times(2)).notifyDataChanged();
assertTrue(store.getApConfiguration().isUserConfigurationInternal());
}
@@ -396,7 +409,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
WifiApConfigStore store = createWifiApConfigStore();
verifyDefaultApConfig(store.getApConfiguration(), TEST_DEFAULT_AP_SSID);
mLooper.dispatchAll();
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
/* Update with a valid configuration. */
SoftApConfiguration providedConfig = setupApConfig(
@@ -419,7 +432,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
verifyApConfig(expectedConfig, store.getApConfiguration());
verifyApConfig(expectedConfig, mDataStoreSource.toSerialize());
mLooper.dispatchAll();
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
verify(mBackupManagerProxy, times(2)).notifyDataChanged();
}
@@ -434,7 +447,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
WifiApConfigStore store = createWifiApConfigStore();
verifyDefaultApConfig(store.getApConfiguration(), TEST_DEFAULT_AP_SSID);
mLooper.dispatchAll();
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
/* Update with a valid configuration. */
SoftApConfiguration expectedConfig = setupApConfig(
@@ -448,7 +461,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
verifyApConfig(expectedConfig, store.getApConfiguration());
verifyApConfig(expectedConfig, mDataStoreSource.toSerialize());
mLooper.dispatchAll();
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
verify(mBackupManagerProxy, times(2)).notifyDataChanged();
}
@@ -462,7 +475,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
WifiApConfigStore store = createWifiApConfigStore();
verifyDefaultApConfig(store.getApConfiguration(), TEST_DEFAULT_AP_SSID);
mLooper.dispatchAll();
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
/* Update with a valid configuration. */
SoftApConfiguration expectedConfig = setupApConfig(
@@ -476,7 +489,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
verifyApConfig(expectedConfig, store.getApConfiguration());
verifyApConfig(expectedConfig, mDataStoreSource.toSerialize());
mLooper.dispatchAll();
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
verify(mBackupManagerProxy, times(2)).notifyDataChanged();
}
@@ -507,7 +520,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
verifyApConfig(expectedConfig, store.getApConfiguration());
verifyApConfig(expectedConfig, mDataStoreSource.toSerialize());
mLooper.dispatchAll();
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
verify(mBackupManagerProxy).notifyDataChanged();
}
@@ -531,7 +544,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
mDataStoreSource.fromDeserialized(persistedConfig);
verifyApConfig(persistedConfig, store.getApConfiguration());
mLooper.dispatchAll();
- verify(mWifiConfigManager, never()).saveToStore(true);
+ verify(mWifiConfigManager, never()).saveToStore();
verify(mBackupManagerProxy, never()).notifyDataChanged();
}
@@ -1361,7 +1374,7 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
WifiApConfigStore store = createWifiApConfigStore();
verifyDefaultApConfig(store.getApConfiguration(), TEST_DEFAULT_AP_SSID);
mLooper.dispatchAll();
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
// Test to enable forced AP band
store.enableForceSoftApBandOrChannel(testBand, 0, SoftApInfo.CHANNEL_WIDTH_AUTO);
@@ -1472,4 +1485,50 @@ public class WifiApConfigStoreTest extends WifiBaseTest {
.setSsid(TEST_DEFAULT_HOTSPOT_SSID).build());
assertEquals(lastPassphrase, store.getLastConfiguredTetheredApPassphraseSinceBoot());
}
+
+ @Test
+ public void testChipSupportBridgedButStaticChipUpdatedAfterGeneratingDefaultConfig()
+ throws Exception {
+ assumeTrue(SdkLevel.isAtLeastS());
+ when(mHalDeviceManager.isConcurrencyComboLoadedFromDriver()).thenReturn(false);
+ mResources.setBoolean(R.bool.config_wifiBridgedSoftApSupported, true);
+ WifiApConfigStore store = createWifiApConfigStore();
+ verifyDefaultApConfig(store.getApConfiguration(),
+ TEST_DEFAULT_AP_SSID, false, true, true);
+ mLooper.dispatchAll();
+ mStaticChipInfoListenerCaptor.getValue()
+ .onSettingsChanged(WIFI_STATIC_CHIP_INFO, "new static chip info");
+ mLooper.dispatchAll();
+ // Chip supports bridged mode, so no extra saveToStore when chip info is updated.
+ verify(mWifiConfigManager).saveToStore();
+ }
+
+ @Test
+ public void testChipNotSupportButStaticChipUpdatedAfterGeneratingDefaultConfig()
+ throws Exception {
+ assumeTrue(SdkLevel.isAtLeastS());
+ reset(mWifiNative);
+ when(mWifiNative.canDeviceSupportCreateTypeCombo(any())).thenReturn(false);
+ when(mHalDeviceManager.isConcurrencyComboLoadedFromDriver()).thenReturn(false);
+ mResources.setBoolean(R.bool.config_wifiBridgedSoftApSupported, true);
+ WifiApConfigStore store = createWifiApConfigStore();
+ // Verify default band is bridged mode
+ verifyDefaultApConfig(store.getApConfiguration(),
+ TEST_DEFAULT_AP_SSID, false, true, true);
+ mLooper.dispatchAll();
+ reset(mWifiConfigManager);
+ mStaticChipInfoListenerCaptor.getValue()
+ .onSettingsChanged(WIFI_STATIC_CHIP_INFO, "new static chip info");
+ mLooper.dispatchAll();
+ // No update since isConcurrencyComboLoadedFromDriver returns false
+ verify(mWifiConfigManager, never()).saveToStore();
+ when(mHalDeviceManager.isConcurrencyComboLoadedFromDriver()).thenReturn(true);
+ mStaticChipInfoListenerCaptor.getValue()
+ .onSettingsChanged(WIFI_STATIC_CHIP_INFO, "new static chip info");
+ mLooper.dispatchAll();
+ // Chip didn't support bridged mode, so extra saveToStore for update to default band.
+ verify(mWifiConfigManager).saveToStore();
+ // Verify it changes to default band.
+ verifyDefaultApConfig(store.getApConfiguration(), TEST_DEFAULT_AP_SSID, false, true, false);
+ }
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiBlocklistMonitorTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiBlocklistMonitorTest.java
index c44bcad857..ce5a929101 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiBlocklistMonitorTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiBlocklistMonitorTest.java
@@ -34,6 +34,7 @@ import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.NetworkSelectionStatus;
import android.net.wifi.WifiConfiguration.NetworkSelectionStatus.DisableReasonInfo;
import android.net.wifi.WifiSsid;
+import android.util.ArraySet;
import android.util.LocalLog;
import androidx.test.filters.SmallTest;
@@ -80,6 +81,8 @@ public class WifiBlocklistMonitorTest extends WifiBaseTest {
private static final int TEST_DHCP_FAILURE = WifiBlocklistMonitor.REASON_DHCP_FAILURE;
private static final long TEST_MAX_DISABLE_DURATION_MILLIS =
TimeUnit.HOURS.toMillis(18); // 18 hours
+ private static final long TEST_SHORT_MAX_DISABLE_DURATION_MILLIS =
+ TimeUnit.SECONDS.toMillis(10); // 10 seconds
private static final long BASE_BLOCKLIST_DURATION = TimeUnit.MINUTES.toMillis(5); // 5 minutes
private static final long BASE_CONNECTED_SCORE_BLOCKLIST_DURATION =
TimeUnit.SECONDS.toMillis(30);
@@ -88,6 +91,7 @@ public class WifiBlocklistMonitorTest extends WifiBaseTest {
private static final long ABNORMAL_DISCONNECT_TIME_WINDOW_MS = TimeUnit.SECONDS.toMillis(30);
private static final long ABNORMAL_DISCONNECT_RESET_TIME_MS = TimeUnit.HOURS.toMillis(3);
private static final int FAILURE_STREAK_CAP = 7;
+ private static final int FAILURE_STREAK_CAP_LONG = 20;
private static final Map<Integer, Integer> BLOCK_REASON_TO_DISABLE_THRESHOLD_MAP =
Map.ofEntries(
Map.entry(WifiBlocklistMonitor.REASON_AP_UNABLE_TO_HANDLE_NEW_STA, 1),
@@ -263,6 +267,11 @@ public class WifiBlocklistMonitorTest extends WifiBaseTest {
TEST_BSSID_1, config,
WifiBlocklistMonitor.REASON_AP_UNABLE_TO_HANDLE_NEW_STA, TEST_GOOD_RSSI);
assertTrue(mWifiBlocklistMonitor.updateAndGetBssidBlocklist().contains(TEST_BSSID_1));
+ assertTrue(mWifiBlocklistMonitor.getBssidBlocklistForSsids(
+ new ArraySet<>(Arrays.asList(new String[]{TEST_SSID_1}))).contains(TEST_BSSID_1));
+ assertTrue(mWifiBlocklistMonitor.getBssidBlocklistForSsids(null).contains(TEST_BSSID_1));
+ assertFalse(mWifiBlocklistMonitor.getBssidBlocklistForSsids(
+ Collections.EMPTY_SET).contains(TEST_BSSID_1));
}
// Verify adding 2 BSSID for SSID_1 and 1 BSSID for SSID_2 to the blocklist.
@@ -440,7 +449,7 @@ public class WifiBlocklistMonitorTest extends WifiBaseTest {
* streak), we are setting the blocklist duration using an exponential backoff technique.
*/
@Test
- public void testBssidIsRemoveFromBlocklistAfterTimoutExponentialBackoff() {
+ public void testBssidIsRemoveFromBlocklistAfterTimeoutExponentialBackoff() {
verifyAddTestBssidToBlocklist();
int multiplier = 2;
long duration = 0;
@@ -461,7 +470,7 @@ public class WifiBlocklistMonitorTest extends WifiBaseTest {
multiplier *= 2;
}
- // finally verify that the timout is capped by the FAILURE_STREAK_CAP
+ // finally verify that the timeout is capped by the FAILURE_STREAK_CAP
when(mWifiScoreCard.getBssidBlocklistStreak(anyString(), anyString(), anyInt()))
.thenReturn(FAILURE_STREAK_CAP + 1);
when(mClock.getWallClockMillis()).thenReturn(0L);
@@ -473,6 +482,26 @@ public class WifiBlocklistMonitorTest extends WifiBaseTest {
}
/**
+ * Verify that when adding a AP that had already been failing (therefore has a blocklist
+ * streak), we are setting the blocklist duration using an exponential backoff technique,
+ * and the disable duration for a network is capped at WifiConfigMaxDisableDurationMs.
+ */
+ @Test
+ public void testBssidIsRemoveFromBlocklistAfterTimeoutExponentialBackoffCapped() {
+ mResources.setInteger(R.integer.config_wifiBssidBlocklistMonitorFailureStreakCap,
+ FAILURE_STREAK_CAP_LONG);
+ when(mWifiScoreCard.getBssidBlocklistStreak(anyString(), anyString(), anyInt()))
+ .thenReturn(FAILURE_STREAK_CAP_LONG);
+ // verify that the timeout is capped at WifiConfigMaxDisableDurationMs
+ when(mClock.getWallClockMillis()).thenReturn(0L);
+ verifyAddTestBssidToBlocklist();
+ when(mClock.getWallClockMillis()).thenReturn(TEST_MAX_DISABLE_DURATION_MILLIS);
+ assertTrue(mWifiBlocklistMonitor.updateAndGetBssidBlocklist().contains(TEST_BSSID_1));
+ when(mClock.getWallClockMillis()).thenReturn(TEST_MAX_DISABLE_DURATION_MILLIS + 1);
+ assertEquals(0, mWifiBlocklistMonitor.updateAndGetBssidBlocklist().size());
+ }
+
+ /**
* Verify that consecutive failures will add a BSSID to blocklist.
*/
@Test
@@ -1622,6 +1651,24 @@ public class WifiBlocklistMonitorTest extends WifiBaseTest {
}
/**
+ * Verify the disable duration for a network is capped at
+ * a short WifiConfigMaxDisableDurationMs.
+ */
+ @Test
+ public void testTryEnableNetworkCappedByShortMaxDisableDuration() {
+ WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
+ int disableReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION;
+ when(mWifiGlobals.getWifiConfigMaxDisableDurationMs())
+ .thenReturn(TEST_SHORT_MAX_DISABLE_DURATION_MILLIS);
+ verifyDisableNetwork(openNetwork, disableReason);
+
+ // verify the exponential backoff is capped at WifiConfigMaxDisableDurationMs
+ verifyNetworkIsEnabledAfter(openNetwork,
+ TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS
+ + TEST_SHORT_MAX_DISABLE_DURATION_MILLIS);
+ }
+
+ /**
* Verifies that a network is disabled for the base duration even when there are no BSSIDs
* blocked.
*/
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiCarrierInfoManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiCarrierInfoManagerTest.java
index 3fd252d03e..71a7a82dd2 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiCarrierInfoManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiCarrierInfoManagerTest.java
@@ -446,7 +446,7 @@ public class WifiCarrierInfoManagerTest extends WifiBaseTest {
verify(mListener).onImsiProtectedOrUserApprovalChanged(NON_DATA_CARRIER_ID, true);
verify(mListener, never())
.onImsiProtectedOrUserApprovalChanged(eq(DATA_CARRIER_ID), anyBoolean());
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
assertFalse(mWifiCarrierInfoManager.shouldFlipOnAutoJoinForOobPseudonym());
ArgumentCaptor<BroadcastReceiver> receiver =
@@ -484,7 +484,7 @@ public class WifiCarrierInfoManagerTest extends WifiBaseTest {
verify(mListener).onImsiProtectedOrUserApprovalChanged(NON_DATA_CARRIER_ID, false);
verify(mListener, never())
.onImsiProtectedOrUserApprovalChanged(eq(DATA_CARRIER_ID), anyBoolean());
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
// do nothing for ACTION_CARRIER_CONFIG_CHANGED
ArgumentCaptor<BroadcastReceiver> receiver =
@@ -1858,11 +1858,11 @@ public class WifiCarrierInfoManagerTest extends WifiBaseTest {
mWifiCarrierInfoManager.setHasUserApprovedImsiPrivacyExemptionForCarrier(true,
DATA_CARRIER_ID);
verify(mListener).onImsiProtectedOrUserApprovalChanged(DATA_CARRIER_ID, true);
- inOrder.verify(mWifiConfigManager).saveToStore(true);
+ inOrder.verify(mWifiConfigManager).saveToStore();
assertTrue(mWifiCarrierInfoManager
.hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
mWifiCarrierInfoManager.clearImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID);
- inOrder.verify(mWifiConfigManager).saveToStore(true);
+ inOrder.verify(mWifiConfigManager).saveToStore();
assertFalse(mWifiCarrierInfoManager
.hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
}
@@ -1888,7 +1888,7 @@ public class WifiCarrierInfoManagerTest extends WifiBaseTest {
verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE);
verify(mWifiMetrics).addUserApprovalCarrierUiReaction(
WifiCarrierInfoManager.ACTION_USER_ALLOWED_CARRIER, false);
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
assertTrue(mCarrierInfoDataSource.hasNewDataToSerialize());
assertTrue(mWifiCarrierInfoManager
.hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
@@ -1918,7 +1918,7 @@ public class WifiCarrierInfoManagerTest extends WifiBaseTest {
verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_CARRIER_SUGGESTION_AVAILABLE);
verify(mDialogHandle, never()).launchDialog();
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
assertTrue(mCarrierInfoDataSource.hasNewDataToSerialize());
assertFalse(mWifiCarrierInfoManager
.hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
@@ -1962,7 +1962,7 @@ public class WifiCarrierInfoManagerTest extends WifiBaseTest {
sendBroadcastForUserActionOnImsi(NOTIFICATION_USER_DISMISSED_INTENT_ACTION,
CARRIER_NAME, DATA_CARRIER_ID);
verifyNoMoreInteractions(mWifiNotificationManager);
- verify(mWifiConfigManager, never()).saveToStore(true);
+ verify(mWifiConfigManager, never()).saveToStore();
assertFalse(mCarrierInfoDataSource.hasNewDataToSerialize());
assertFalse(mWifiCarrierInfoManager
.hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
@@ -2000,7 +2000,7 @@ public class WifiCarrierInfoManagerTest extends WifiBaseTest {
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
verify(mContext).sendBroadcast(intentCaptor.capture(), any(), any());
assertEquals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS, intentCaptor.getValue().getAction());
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
assertTrue(mCarrierInfoDataSource.hasNewDataToSerialize());
assertFalse(mWifiCarrierInfoManager
.hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
@@ -2049,7 +2049,7 @@ public class WifiCarrierInfoManagerTest extends WifiBaseTest {
when(mClock.getElapsedSinceBootMillis()).thenReturn(mCurrentTimeMills + 6 * 60 * 1000);
validateImsiProtectionNotification(CARRIER_NAME);
- verify(mWifiConfigManager, never()).saveToStore(true);
+ verify(mWifiConfigManager, never()).saveToStore();
assertFalse(mCarrierInfoDataSource.hasNewDataToSerialize());
assertFalse(mWifiCarrierInfoManager
.hasUserApprovedImsiPrivacyExemptionForCarrier(DATA_CARRIER_ID));
@@ -2089,7 +2089,7 @@ public class WifiCarrierInfoManagerTest extends WifiBaseTest {
ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
verify(mContext).sendBroadcast(intentCaptor.capture(), any(), any());
assertEquals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS, intentCaptor.getValue().getAction());
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
assertTrue(mCarrierInfoDataSource.hasNewDataToSerialize());
verify(mListener).onImsiProtectedOrUserApprovalChanged(DATA_CARRIER_ID, true);
verify(mWifiMetrics).addUserApprovalCarrierUiReaction(
@@ -2190,7 +2190,7 @@ public class WifiCarrierInfoManagerTest extends WifiBaseTest {
assertTrue(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, false));
mWifiCarrierInfoManager.setCarrierNetworkOffloadEnabled(DATA_SUBID, false, false);
mLooper.dispatchAll();
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
assertFalse(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, false));
}
@@ -2212,7 +2212,7 @@ public class WifiCarrierInfoManagerTest extends WifiBaseTest {
listenerCaptor.getValue().onDataEnabledChanged(true, DATA_ENABLED_REASON_USER);
mWifiCarrierInfoManager.setCarrierNetworkOffloadEnabled(DATA_SUBID, true, false);
mLooper.dispatchAll();
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
assertFalse(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(DATA_SUBID, true));
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java
index 3d01187bc4..d5709575ed 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiConfigManagerTest.java
@@ -334,8 +334,6 @@ public class WifiConfigManagerTest extends WifiBaseTest {
when(mPackageManager.getPackagesHoldingPermissions(any(String[].class), anyInt()))
.thenReturn(Collections.emptyList());
when(mWifiInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfigFacade);
- when(mDeviceConfigFacade.getFeatureFlags()).thenReturn(mFeatureFlags);
- when(mFeatureFlags.delaySaveToStore()).thenReturn(true);
mWifiCarrierInfoManager = spy(new WifiCarrierInfoManager(mTelephonyManager,
mSubscriptionManager, mWifiInjector, mock(FrameworkFacade.class),
wifiContext, mock(WifiConfigStore.class), mock(Handler.class),
@@ -444,23 +442,23 @@ public class WifiConfigManagerTest extends WifiBaseTest {
}
/**
- * Verifies the {@link WifiConfigManager#saveToStore(boolean)} is rejected until the store has
+ * Verifies the {@link WifiConfigManager#saveToStore()} is rejected until the store has
* been read first using {@link WifiConfigManager#loadFromStore()}.
*/
@Test
public void testSaveToStoreIsRejectedBeforeLoadFromStore() throws Exception {
- assertFalse(mWifiConfigManager.saveToStore(true));
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
+ assertFalse(mWifiConfigManager.saveToStore());
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
verify(mWifiMetrics, never()).wifiConfigStored(anyInt());
assertTrue(mWifiConfigManager.loadFromStore());
mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
- assertTrue(mWifiConfigManager.saveToStore(true));
+ assertTrue(mWifiConfigManager.saveToStore());
assertTrue(mAlarmManager.isPending(BUFFERED_WRITE_ALARM_TAG));
mAlarmManager.dispatch(BUFFERED_WRITE_ALARM_TAG);
mLooper.dispatchAll();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore).write();
verify(mWifiMetrics).wifiConfigStored(anyInt());
}
@@ -621,7 +619,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
verifyNetworkUpdateBroadcast();
// Ensure that the write was not invoked for ephemeral network addition.
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
verify(mWifiMetrics, never()).wifiConfigStored(anyInt());
List<WifiConfiguration> retrievedNetworks =
@@ -1525,7 +1523,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
verify(mWifiKeyStore, never()).removeKeys(any(WifiEnterpriseConfig.class), eq(false));
verifyNetworkRemoveBroadcast();
// Ensure that the write was not invoked for Passpoint network remove.
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
verify(mWifiMetrics, never()).wifiConfigStored(anyInt());
}
@@ -1724,7 +1722,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
assertTrue(mAlarmManager.isPending(BUFFERED_WRITE_ALARM_TAG));
mAlarmManager.dispatch(BUFFERED_WRITE_ALARM_TAG);
mLooper.dispatchAll();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore).write();
verify(mWifiBlocklistMonitor, times(2)).clearBssidBlocklistForSsid(openNetwork.SSID);
// Now set it disabled.
@@ -1737,7 +1735,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
assertTrue(mAlarmManager.isPending(BUFFERED_WRITE_ALARM_TAG));
mAlarmManager.dispatch(BUFFERED_WRITE_ALARM_TAG);
mLooper.dispatchAll();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore).write();
verify(mWifiMetrics, atLeast(2)).wifiConfigStored(anyInt());
}
@@ -1819,7 +1817,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
assertTrue(mAlarmManager.isPending(BUFFERED_WRITE_ALARM_TAG));
mAlarmManager.dispatch(BUFFERED_WRITE_ALARM_TAG);
mLooper.dispatchAll();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore).write();
// Now set it disallow auto-join.
assertTrue(mWifiConfigManager.allowAutojoin(
@@ -1829,7 +1827,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
assertTrue(mAlarmManager.isPending(BUFFERED_WRITE_ALARM_TAG));
mAlarmManager.dispatch(BUFFERED_WRITE_ALARM_TAG);
mLooper.dispatchAll();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore).write();
verify(mWifiMetrics, atLeast(2)).wifiConfigStored(anyInt());
}
@@ -3925,7 +3923,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
mWifiConfigManager.handleUserStop(user1);
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
.switchUserStoresAndRead(any(List.class));
- mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore).write();
verify(mWifiMetrics).wifiConfigStored(anyInt());
}
@@ -3993,7 +3991,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
// Set up the internal data first.
assertTrue(mWifiConfigManager.loadFromStore());
mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
.switchUserStoresAndRead(any(List.class));
@@ -4003,11 +4001,11 @@ public class WifiConfigManagerTest extends WifiBaseTest {
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
mContextConfigStoreMockOrder.verify(mWifiConfigStore)
.switchUserStoresAndRead(any(List.class));
- mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore).write();
verify(mWifiMetrics).wifiConfigStored(anyInt());
// Verify shut down handling
- mWifiConfigManager.handleShutDown();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(true);
+ mWifiConfigManager.writeDataToStorage();
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore).write();
}
/**
@@ -4023,7 +4021,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
// data.
mWifiConfigManager.handleUserUnlock(user1);
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
.switchUserStoresAndRead(any(List.class));
@@ -4051,7 +4049,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
// (need to wait for loadFromStore invocation).
mWifiConfigManager.handleUserSwitch(user2);
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
.switchUserStoresAndRead(any(List.class));
verify(mWifiMetrics, never()).wifiConfigStored(anyInt());
@@ -4083,7 +4081,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
// (need to wait for loadFromStore invocation).
mWifiConfigManager.handleUserUnlock(user1);
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
.switchUserStoresAndRead(any(List.class));
@@ -4091,7 +4089,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
// (need to wait for loadFromStore invocation).
mWifiConfigManager.handleUserSwitch(user2);
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
.switchUserStoresAndRead(any(List.class));
verify(mWifiMetrics, never()).wifiConfigStored(anyInt());
@@ -4123,14 +4121,14 @@ public class WifiConfigManagerTest extends WifiBaseTest {
// (need to wait for loadFromStore invocation).
mWifiConfigManager.handleUserSwitch(user2);
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
.switchUserStoresAndRead(any(List.class));
// Unlock the user1 for the first time and ensure that we don't read the data
mWifiConfigManager.handleUserUnlock(user1);
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(anyBoolean());
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
mContextConfigStoreMockOrder.verify(mWifiConfigStore, never())
.switchUserStoresAndRead(any(List.class));
verify(mWifiMetrics, never()).wifiConfigStored(anyInt());
@@ -4408,7 +4406,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
// This should have triggered 2 buffered writes. 1 for setting the connect choice, 1 for
// clearing it after network removal.
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, times(2)).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, times(2)).write();
verify(mListener, times(2)).onConnectChoiceRemoved(anyString());
verify(mWifiMetrics, atLeast(2)).wifiConfigStored(anyInt());
}
@@ -5816,7 +5814,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
.setConfigurations(sharedConfigsCaptor.capture());
mNetworkListStoreDataMockOrder.verify(mNetworkListUserStoreData)
.setConfigurations(userConfigsCaptor.capture());
- mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore).write();
return Pair.create(sharedConfigsCaptor.getValue(), userConfigsCaptor.getValue());
} catch (Exception e) {
fail("Exception encountered during write " + e);
@@ -6072,7 +6070,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
verifyNetworkAddBroadcast();
// Ensure that the write was not invoked for ephemeral network addition.
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
return result;
}
@@ -6090,7 +6088,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
verifyNetworkAddBroadcast();
// Ensure that the write was not invoked for ephemeral network addition.
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
return result;
}
@@ -6110,7 +6108,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
any(WifiConfiguration.class));
verifyNetworkAddBroadcast();
// Ensure that the write was not invoked for Passpoint network addition.
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
return result;
}
@@ -6199,7 +6197,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
verifyNetworkRemoveBroadcast();
// Ensure that the write was not invoked for ephemeral network remove.
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
}
/**
@@ -6214,7 +6212,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
verify(mWifiKeyStore, never()).removeKeys(any(WifiEnterpriseConfig.class), eq(false));
verifyNetworkRemoveBroadcast();
// Ensure that the write was not invoked for Passpoint network remove.
- mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write(true);
+ mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).write();
}
/**
@@ -8153,7 +8151,7 @@ public class WifiConfigManagerTest extends WifiBaseTest {
WifiConfiguration config = mWifiConfigManager.getConfiguredNetwork(eapPeapNetId);
assertFalse(config.enterpriseConfig.isTrustOnFirstUseEnabled());
assertFalse(config.enterpriseConfig.isUserApproveNoCaCert());
- assertEquals("mockServerCert", config.enterpriseConfig.getDomainSuffixMatch());
+ assertEquals("", config.enterpriseConfig.getDomainSuffixMatch());
assertEquals("DNS:wifi.android;EMAIL:test@wifi.com;DNS:network.android;"
+ "URI:http://test.android.com",
config.enterpriseConfig.getAltSubjectMatch());
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiConfigStoreTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiConfigStoreTest.java
index dd930430fd..2c4080a8db 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiConfigStoreTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiConfigStoreTest.java
@@ -27,7 +27,6 @@ import android.net.MacAddress;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiMigration;
import android.net.wifi.util.HexEncoding;
-import android.os.Handler;
import android.os.UserHandle;
import android.os.test.TestLooper;
@@ -280,7 +279,7 @@ public class WifiConfigStoreTest extends WifiBaseTest {
public void setUp() throws Exception {
setupMocks();
- mWifiConfigStore = new WifiConfigStore(mContext, new Handler(mLooper.getLooper()), mClock,
+ mWifiConfigStore = new WifiConfigStore(mClock,
mWifiMetrics, Arrays.asList(mSharedStore, mSharedSoftApStore));
// Enable verbose logging before tests.
mWifiConfigStore.enableVerboseLogging(true);
@@ -307,7 +306,7 @@ public class WifiConfigStoreTest extends WifiBaseTest {
public void testWriteWithNoStoreData() throws Exception {
// Perform force write to both share and user store file.
mWifiConfigStore.setUserStores(mUserStores);
- mWifiConfigStore.write(true);
+ mWifiConfigStore.write();
assertFalse(mSharedStore.isStoreWritten());
assertFalse(mUserStore.isStoreWritten());
@@ -328,7 +327,7 @@ public class WifiConfigStoreTest extends WifiBaseTest {
mWifiConfigStore.registerStoreData(mUserStoreData);
mWifiConfigStore.switchUserStoresAndRead(mUserStores);
- mWifiConfigStore.write(true);
+ mWifiConfigStore.write();
assertFalse(mAlarmManager.isPending(WifiConfigStore.BUFFERED_WRITE_ALARM_TAG));
assertTrue(mSharedStore.isStoreWritten());
@@ -339,110 +338,6 @@ public class WifiConfigStoreTest extends WifiBaseTest {
}
/**
- * Tests the write API with the force flag set to false.
- * Expected behavior: This should set an alarm to write to the store files.
- */
- @Test
- public void testBufferedWrite() throws Exception {
- // Register data container.
- mWifiConfigStore.registerStoreData(mSharedStoreData);
- mWifiConfigStore.registerStoreData(mUserStoreData);
-
- mWifiConfigStore.switchUserStoresAndRead(mUserStores);
- mWifiConfigStore.write(false);
-
- assertTrue(mAlarmManager.isPending(WifiConfigStore.BUFFERED_WRITE_ALARM_TAG));
- assertFalse(mSharedStore.isStoreWritten());
- assertFalse(mUserStore.isStoreWritten());
- assertFalse(mUserNetworkSuggestionsStore.isStoreWritten());
-
- // Now send the alarm and ensure that the writes happen.
- mAlarmManager.dispatch(WifiConfigStore.BUFFERED_WRITE_ALARM_TAG);
- mLooper.dispatchAll();
- assertTrue(mSharedStore.isStoreWritten());
- assertTrue(mUserStore.isStoreWritten());
- assertFalse(mUserNetworkSuggestionsStore.isStoreWritten());
-
- verify(mWifiMetrics).noteWifiConfigStoreWriteDuration(anyInt());
- }
-
- /**
- * Tests the force write after a buffered write.
- * Expected behaviour: The force write should override the previous buffered write and stop the
- * buffer write alarms.
- */
- @Test
- public void testForceWriteAfterBufferedWrite() throws Exception {
- // Register a test data container with bogus data.
- mWifiConfigStore.registerStoreData(mSharedStoreData);
- mWifiConfigStore.registerStoreData(mUserStoreData);
-
- mSharedStoreData.setData("abcds");
- mUserStoreData.setData("asdfa");
-
- // Perform buffered write for both user and share store file.
- mWifiConfigStore.switchUserStoresAndRead(mUserStores);
- mWifiConfigStore.write(false);
-
- assertTrue(mAlarmManager.isPending(WifiConfigStore.BUFFERED_WRITE_ALARM_TAG));
- assertFalse(mSharedStore.isStoreWritten());
- assertFalse(mUserStore.isStoreWritten());
-
- // Update the container with new set of data. The send a force write and ensure that the
- // writes have been performed and alarms have been stopped and updated data are written.
- mUserStoreData.setData(TEST_USER_DATA);
- mSharedStoreData.setData(TEST_SHARE_DATA);
- mWifiConfigStore.write(true);
-
- assertFalse(mAlarmManager.isPending(WifiConfigStore.BUFFERED_WRITE_ALARM_TAG));
- assertTrue(mSharedStore.isStoreWritten());
- assertTrue(mUserStore.isStoreWritten());
-
- // Verify correct data are loaded to the data container after a read.
- mWifiConfigStore.read();
- assertEquals(TEST_USER_DATA, mUserStoreData.getData());
- assertEquals(TEST_SHARE_DATA, mSharedStoreData.getData());
- }
-
- /**
- * Tests the force write with no new data after a buffered write.
- * Expected behaviour: The force write should flush the previous buffered write and stop the
- * buffer write alarms.
- */
- @Test
- public void testForceWriteWithNoNewDataAfterBufferedWrite() throws Exception {
- // Register a test data container with bogus data.
- mWifiConfigStore.registerStoreData(mSharedStoreData);
- mWifiConfigStore.registerStoreData(mUserStoreData);
-
- mSharedStoreData.setData("abcds");
- mUserStoreData.setData("asdfa");
-
- // Perform buffered write for both user and share store file.
- mWifiConfigStore.switchUserStoresAndRead(mUserStores);
- mWifiConfigStore.write(false);
-
- assertTrue(mAlarmManager.isPending(WifiConfigStore.BUFFERED_WRITE_ALARM_TAG));
- assertFalse(mSharedStore.isStoreWritten());
- assertFalse(mUserStore.isStoreWritten());
-
- // Containers have no new data.
- mUserStoreData.setHasAnyNewData(false);
- mSharedStoreData.setHasAnyNewData(false);
- mWifiConfigStore.write(true);
-
- assertFalse(mAlarmManager.isPending(WifiConfigStore.BUFFERED_WRITE_ALARM_TAG));
- assertTrue(mSharedStore.isStoreWritten());
- assertTrue(mUserStore.isStoreWritten());
-
- // Verify correct data are loaded to the data container after a read.
- mWifiConfigStore.read();
- assertEquals("abcds", mSharedStoreData.getData());
- assertEquals("asdfa", mUserStoreData.getData());
- }
-
-
- /**
* Tests the read API behaviour after a write to the store files.
* Expected behaviour: The read should return the same data that was last written.
*/
@@ -462,7 +357,7 @@ public class WifiConfigStoreTest extends WifiBaseTest {
// Write share and user data.
mUserStoreData.setData(TEST_USER_DATA);
mSharedStoreData.setData(TEST_SHARE_DATA);
- mWifiConfigStore.write(true);
+ mWifiConfigStore.write();
// Read and verify the data content in the data container.
mWifiConfigStore.read();
@@ -542,7 +437,7 @@ public class WifiConfigStoreTest extends WifiBaseTest {
mSharedStoreData.setData(TEST_SHARE_DATA);
// Perform write for the share store file.
- mWifiConfigStore.write(true);
+ mWifiConfigStore.write();
mWifiConfigStore.read();
// Verify data content for both user and share data.
assertEquals(TEST_SHARE_DATA, mSharedStoreData.getData());
@@ -562,7 +457,7 @@ public class WifiConfigStoreTest extends WifiBaseTest {
// Perform force write with empty data content to both user and share store file.
mWifiConfigStore.switchUserStoresAndRead(mUserStores);
- mWifiConfigStore.write(true);
+ mWifiConfigStore.write();
// Setup data container with some value.
mUserStoreData.setData(TEST_USER_DATA);
@@ -641,7 +536,7 @@ public class WifiConfigStoreTest extends WifiBaseTest {
openNetwork.shared, openNetwork.creatorUid, openNetwork.creatorName,
openNetwork.getRandomizedMacAddress(), openNetwork.subscriptionId);
- mWifiConfigStore.write(true);
+ mWifiConfigStore.write();
// Verify the user store content.
assertEquals(xmlString, new String(mUserStore.getStoreBytes()));
}
@@ -801,7 +696,7 @@ public class WifiConfigStoreTest extends WifiBaseTest {
mWifiConfigStore.setUserStores(mUserStores);
// Now trigger a write.
- mWifiConfigStore.write(true);
+ mWifiConfigStore.write();
verify(sharedStoreData).hasNewDataToSerialize();
verify(userStoreData).hasNewDataToSerialize();
@@ -966,7 +861,7 @@ public class WifiConfigStoreTest extends WifiBaseTest {
StoreFile userStoreFile2 = mock(StoreFile.class);
when(userStoreFile2.getFileId())
.thenReturn(WifiConfigStore.STORE_FILE_USER_NETWORK_SUGGESTIONS);
- mWifiConfigStore = new WifiConfigStore(mContext, new Handler(mLooper.getLooper()), mClock,
+ mWifiConfigStore = new WifiConfigStore(mClock,
mWifiMetrics, Arrays.asList(sharedStoreFile1, sharedStoreFile2));
mWifiConfigStore.setUserStores(Arrays.asList(userStoreFile1, userStoreFile2));
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiConfigurationTestUtil.java b/service/tests/wifitests/src/com/android/server/wifi/WifiConfigurationTestUtil.java
index 0abc488459..8d29edb679 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiConfigurationTestUtil.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiConfigurationTestUtil.java
@@ -800,6 +800,9 @@ public class WifiConfigurationTestUtil {
expected.getNetworkSelectionStatus(), actual.getNetworkSelectionStatus());
assertWifiEnterpriseConfigEqualForConfigStore(
expected.enterpriseConfig, actual.enterpriseConfig);
+ if (SdkLevel.isAtLeastV()) {
+ assertEquals(expected.getVendorData(), actual.getVendorData());
+ }
}
/**
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiConfigurationUtilTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiConfigurationUtilTest.java
index f8e6396c84..8dbe628f5c 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiConfigurationUtilTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiConfigurationUtilTest.java
@@ -314,7 +314,7 @@ public class WifiConfigurationUtilTest extends WifiBaseTest {
* string.
*/
@Test
- public void testValidateNegativeCases_MalformedAsciiSsidString() {
+ public void testValidateNegativeCases_MalformedPlaintextSsidString() {
WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
assertTrue(WifiConfigurationUtil.validate(config, SUPPORTED_FEATURES_ALL,
WifiConfigurationUtil.VALIDATE_FOR_ADD));
@@ -325,6 +325,21 @@ public class WifiConfigurationUtilTest extends WifiBaseTest {
}
/**
+ * Verify that the validate method fails to validate WifiConfiguration with a too-long ssid
+ * string.
+ */
+ @Test
+ public void testValidateNegativeCases_TooLongPlaintextSsidString() {
+ WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
+ assertTrue(WifiConfigurationUtil.validate(config, SUPPORTED_FEATURES_ALL,
+ WifiConfigurationUtil.VALIDATE_FOR_ADD));
+
+ config.SSID = "\"012345678901234567890123456789012\"";
+ assertFalse(WifiConfigurationUtil.validate(config, SUPPORTED_FEATURES_ALL,
+ WifiConfigurationUtil.VALIDATE_FOR_ADD));
+ }
+
+ /**
* Verify that the validate method fails to validate WifiConfiguration with bad ssid length.
*/
@Test
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiConnectivityManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiConnectivityManagerTest.java
index e4988f2705..e5ddabb0e1 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiConnectivityManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiConnectivityManagerTest.java
@@ -284,6 +284,7 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
private TestAlarmManager mAlarmManager;
private TestLooper mLooper;
private TestHandler mTestHandler;
+ private WifiThreadRunner mWifiThreadRunner;
private WifiConnectivityManager mWifiConnectivityManager;
private WifiNetworkSelector mWifiNS;
private WifiConnectivityHelper mWifiConnectivityHelper;
@@ -4092,7 +4093,7 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
public void listenToAllSingleScanResults() {
ScanSettings settings = new ScanSettings();
WifiScannerInternal.ScanListener scanListener = new WifiScannerInternal.ScanListener(mock(
- WifiScanner.ScanListener.class), mTestHandler);
+ WifiScanner.ScanListener.class), mWifiThreadRunner);
// Request a single scan outside of WifiConnectivityManager.
mWifiScanner.startScan(settings, scanListener);
@@ -4123,7 +4124,7 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
// Request a single scan to trigger network selection.
ScanSettings settings = new ScanSettings();
WifiScannerInternal.ScanListener scanListener = new WifiScannerInternal.ScanListener(mock(
- WifiScanner.ScanListener.class), mTestHandler);
+ WifiScanner.ScanListener.class), mWifiThreadRunner);
mWifiScanner.startScan(settings, scanListener);
mLooper.dispatchAll();
@@ -4154,7 +4155,7 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
// Request a single scan to trigger network selection.
ScanSettings settings = new ScanSettings();
WifiScannerInternal.ScanListener scanListener = new WifiScannerInternal.ScanListener(mock(
- WifiScanner.ScanListener.class), mTestHandler);
+ WifiScanner.ScanListener.class), mWifiThreadRunner);
mWifiScanner.startScan(settings, scanListener);
mLooper.dispatchAll();
@@ -4192,7 +4193,7 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
// Request a single scan to trigger network selection.
ScanSettings settings = new ScanSettings();
WifiScannerInternal.ScanListener scanListener = new WifiScannerInternal.ScanListener(mock(
- WifiScanner.ScanListener.class), mTestHandler);
+ WifiScanner.ScanListener.class), mWifiThreadRunner);
mWifiScanner.startScan(settings, scanListener);
mLooper.dispatchAll();
@@ -4253,7 +4254,7 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
// Request a single scan to trigger network selection.
ScanSettings settings = new ScanSettings();
WifiScannerInternal.ScanListener scanListener = new WifiScannerInternal.ScanListener(mock(
- WifiScanner.ScanListener.class), mTestHandler);
+ WifiScanner.ScanListener.class), mWifiThreadRunner);
mWifiScanner.startScan(settings, scanListener);
mLooper.dispatchAll();
@@ -4309,7 +4310,7 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
// Request a single scan to trigger network selection.
ScanSettings settings = new ScanSettings();
WifiScannerInternal.ScanListener scanListener = new WifiScannerInternal.ScanListener(mock(
- WifiScanner.ScanListener.class), mTestHandler);
+ WifiScanner.ScanListener.class), mWifiThreadRunner);
mWifiScanner.startScan(settings, scanListener);
mLooper.dispatchAll();
@@ -4365,7 +4366,7 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
// Request a single scan to trigger network selection.
ScanSettings settings = new ScanSettings();
WifiScannerInternal.ScanListener scanListener = new WifiScannerInternal.ScanListener(mock(
- WifiScanner.ScanListener.class), mTestHandler);
+ WifiScanner.ScanListener.class), mWifiThreadRunner);
mWifiScanner.startScan(settings, scanListener);
mLooper.dispatchAll();
@@ -4403,7 +4404,7 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
// Request a single scan to trigger network selection.
ScanSettings settings = new ScanSettings();
WifiScannerInternal.ScanListener scanListener = new WifiScannerInternal.ScanListener(mock(
- WifiScanner.ScanListener.class), mTestHandler);
+ WifiScanner.ScanListener.class), mWifiThreadRunner);
mWifiScanner.startScan(settings, scanListener);
mLooper.dispatchAll();
@@ -4465,7 +4466,7 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
// Request a single scan to trigger network selection.
ScanSettings settings = new ScanSettings();
WifiScannerInternal.ScanListener scanListener = new WifiScannerInternal.ScanListener(mock(
- WifiScanner.ScanListener.class), mTestHandler);
+ WifiScanner.ScanListener.class), mWifiThreadRunner);
mWifiScanner.startScan(settings, scanListener);
mLooper.dispatchAll();
@@ -6102,12 +6103,13 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
mLooper.dispatchAll();
List<WifiNetworkSelector.ClientModeManagerState> expectedCmmStates =
Arrays.asList(new WifiNetworkSelector.ClientModeManagerState(
- "wlan0", false, true, wifiInfo1, false),
+ "wlan0", false, true, wifiInfo1, false, ROLE_CLIENT_PRIMARY),
new WifiNetworkSelector.ClientModeManagerState(
- "wlan1", false, true, wifiInfo2, false));
+ "wlan1", false, true, wifiInfo2, false,
+ ROLE_CLIENT_SECONDARY_LONG_LIVED));
verify(mWifiNS).getCandidatesFromScan(any(), any(),
eq(expectedCmmStates), anyBoolean(), anyBoolean(), anyBoolean(), any(),
- anyBoolean());
+ eq(false));
}
@Test
@@ -6137,14 +6139,42 @@ public class WifiConnectivityManagerTest extends WifiBaseTest {
primaryCmm,
WifiConnectivityManager.WIFI_STATE_DISCONNECTED);
mLooper.dispatchAll();
- List<WifiNetworkSelector.ClientModeManagerState> expectedCmmStates =
- Arrays.asList(new WifiNetworkSelector.ClientModeManagerState(
- "wlan0", false, true, wifiInfo1, false),
- new WifiNetworkSelector.ClientModeManagerState(
- "unknown", false, true, new WifiInfo(), false));
verify(mWifiNS).getCandidatesFromScan(any(), any(),
- eq(expectedCmmStates), anyBoolean(), anyBoolean(), anyBoolean(), any(),
- anyBoolean());
+ any(), anyBoolean(), anyBoolean(), anyBoolean(), any(),
+ eq(true));
+ }
+
+ @Test
+ public void testMbbAvailableWillSkipSufficiencyCheck() {
+ // Set screen to on
+ setScreenState(true);
+ // set OEM paid connection allowed.
+ WorkSource oemPaidWs = new WorkSource();
+ mWifiConnectivityManager.setOemPaidConnectionAllowed(true, oemPaidWs);
+
+ ConcreteClientModeManager primaryCmm = mock(ConcreteClientModeManager.class);
+ WifiInfo wifiInfo1 = mock(WifiInfo.class);
+ when(primaryCmm.getInterfaceName()).thenReturn("wlan0");
+ when(primaryCmm.getRole()).thenReturn(ROLE_CLIENT_PRIMARY);
+ when(primaryCmm.isConnected()).thenReturn(false);
+ when(primaryCmm.isDisconnected()).thenReturn(true);
+ when(primaryCmm.getConnectionInfo()).thenReturn(wifiInfo1);
+
+ when(mActiveModeWarden.getInternetConnectivityClientModeManagers())
+ .thenReturn(Arrays.asList(primaryCmm));
+ // Second STA creation is allowed.
+ when(mActiveModeWarden.canRequestMoreClientModeManagersInRole(
+ eq(ActiveModeWarden.INTERNAL_REQUESTOR_WS), eq(ROLE_CLIENT_SECONDARY_TRANSIENT),
+ eq(false))).thenReturn(true);
+
+ // Set WiFi to disconnected state to trigger scan
+ mWifiConnectivityManager.handleConnectionStateChanged(
+ primaryCmm,
+ WifiConnectivityManager.WIFI_STATE_DISCONNECTED);
+ mLooper.dispatchAll();
+ verify(mWifiNS).getCandidatesFromScan(any(), any(),
+ any(), anyBoolean(), anyBoolean(), anyBoolean(), any(),
+ eq(true));
}
/**
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiCountryCodeTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiCountryCodeTest.java
index e9ba8d3b68..dacf2cc178 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiCountryCodeTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiCountryCodeTest.java
@@ -16,7 +16,6 @@
package com.android.server.wifi;
-import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_PRIMARY;
import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_SECONDARY_LONG_LIVED;
import static com.android.server.wifi.WifiSettingsConfigStore.WIFI_DEFAULT_COUNTRY_CODE;
@@ -25,14 +24,12 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyInt;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -45,10 +42,7 @@ import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
-import android.telephony.SubscriptionInfo;
-import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
-import android.telephony.ims.ImsMmTelManager;
import androidx.test.filters.SmallTest;
@@ -58,7 +52,6 @@ import com.android.server.wifi.p2p.WifiP2pMetrics;
import com.android.server.wifi.util.WifiPermissionsUtil;
import com.android.wifi.resources.R;
-import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
@@ -110,15 +103,12 @@ public class WifiCountryCodeTest extends WifiBaseTest {
@Mock WifiInfo mWifiInfo;
@Mock WifiCountryCode.ChangeListener mExternalChangeListener;
@Mock SoftApModeConfiguration mSoftApModeConfiguration;
- @Mock SubscriptionManager mSubscriptionManager;
- @Mock SubscriptionInfo mActiveSubscriptionInfo;
- @Mock ImsMmTelManager mImsMmTelManager;
@Mock Clock mClock;
@Mock WifiPermissionsUtil mWifiPermissionsUtil;
@Mock WifiP2pMetrics mWifiP2pMetrics;
+ @Mock WifiCarrierInfoManager mWifiCarrierInfoManager;
private WifiCountryCode mWifiCountryCode;
private List<ClientModeManager> mClientManagerList;
- private List<SubscriptionInfo> mSubscriptionInfoList = new ArrayList<>();
private MockitoSession mStaticMockSession = null;
@Captor
@@ -171,19 +161,6 @@ public class WifiCountryCodeTest extends WifiBaseTest {
}).when(mSettingsConfigStore).put(eq(WIFI_DEFAULT_COUNTRY_CODE), any(String.class));
when(mSettingsConfigStore.get(WIFI_DEFAULT_COUNTRY_CODE)).thenReturn(mDefaultCountryCode);
- when(mContext.getSystemService(SubscriptionManager.class)).thenReturn(mSubscriptionManager);
- mSubscriptionInfoList.add(mActiveSubscriptionInfo);
-
- when(mSubscriptionManager.getCompleteActiveSubscriptionInfoList())
- .thenReturn(mSubscriptionInfoList);
- when(mActiveSubscriptionInfo.getSubscriptionId()).thenReturn(TEST_ACTIVE_SUBSCRIPTION_ID);
- mStaticMockSession = mockitoSession()
- .mockStatic(ImsMmTelManager.class)
- .startMocking();
-
- lenient().when(ImsMmTelManager.createForSubscriptionId(eq(TEST_ACTIVE_SUBSCRIPTION_ID)))
- .thenReturn(mImsMmTelManager);
- when(mImsMmTelManager.isAvailable(anyInt(), anyInt())).thenReturn(false);
createWifiCountryCode();
mScanDetails = setupScanDetails(TEST_COUNTRY_CODE);
@@ -194,11 +171,6 @@ public class WifiCountryCodeTest extends WifiBaseTest {
when(mPackageManager.hasSystemFeature(FEATURE_TELEPHONY_CALLING)).thenReturn(supported);
}
- @After
- public void cleanUp() throws Exception {
- mStaticMockSession.finishMocking();
- }
-
private void createWifiCountryCode() {
mResources.setBoolean(R.bool.config_wifi_revert_country_code_on_cellular_loss,
mRevertCountryCodeOnCellularLoss);
@@ -231,7 +203,8 @@ public class WifiCountryCodeTest extends WifiBaseTest {
mWifiNative,
mSettingsConfigStore,
mClock,
- mWifiPermissionsUtil);
+ mWifiPermissionsUtil,
+ mWifiCarrierInfoManager);
mWifiCountryCode.enableVerboseLogging(true);
verify(mActiveModeWarden, atLeastOnce()).registerModeChangeCallback(
mModeChangeCallbackCaptor.capture());
@@ -361,7 +334,7 @@ public class WifiCountryCodeTest extends WifiBaseTest {
mClientModeImplListenerCaptor.getValue().onConnectionStart(mClientModeManager);
// Wifi Calling is available
- when(mImsMmTelManager.isAvailable(anyInt(), anyInt())).thenReturn(true);
+ when(mWifiCarrierInfoManager.isWifiCallingAvailable()).thenReturn(true);
// Telephony country code arrives.
mWifiCountryCode.setTelephonyCountryCodeAndUpdate(mTelephonyCountryCode);
// Telephony country code won't be applied at this time.
@@ -371,7 +344,7 @@ public class WifiCountryCodeTest extends WifiBaseTest {
verify(mClientModeManager, times(0)).disconnect();
// Wifi Calling is not available
- when(mImsMmTelManager.isAvailable(anyInt(), anyInt())).thenReturn(false);
+ when(mWifiCarrierInfoManager.isWifiCallingAvailable()).thenReturn(false);
// Wifi traffic is high
when(mWifiInfo.getSuccessfulTxPacketsPerSecond()).thenReturn(20.0);
// Telephony country code arrives.
@@ -466,21 +439,6 @@ public class WifiCountryCodeTest extends WifiBaseTest {
}
/**
- * Test that we don't crash when we try to set the country code if the TelephonyService
- * cannot be found. This is really only the case when instrumentation tests that run on the
- * phone process are cleaned up.
- */
- @Test
- public void setCountryCodeDoesNotCrashWhenTelephonyServiceNotFound() throws Exception {
- when(mImsMmTelManager.isAvailable(anyInt(), anyInt())).thenThrow(new RuntimeException());
- try {
- mWifiCountryCode.setTelephonyCountryCodeAndUpdate(mTelephonyCountryCode);
- } catch (RuntimeException e) {
- fail("Didn't catch RuntimeException from Telephony Service not being found!");
- }
- }
-
- /**
* Test if we can keep using the last known country code when phone is out of service, when
* |config_wifi_revert_country_code_on_cellular_loss| is set to false;
* Telephony service calls |setCountryCode| with an empty string when phone is out of service.
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiDeviceStateChangeManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiDeviceStateChangeManagerTest.java
index ed4910aef8..95eac5fa53 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiDeviceStateChangeManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiDeviceStateChangeManagerTest.java
@@ -74,7 +74,7 @@ public class WifiDeviceStateChangeManagerTest extends WifiBaseTest {
verify(mStateChangeCallback, never()).onScreenStateChanged(anyBoolean());
mWifiDeviceStateChangeManager.handleBootCompleted();
verify(mContext, atLeastOnce())
- .registerReceiver(mBroadcastReceiverCaptor.capture(), any(), any(), any());
+ .registerReceiver(mBroadcastReceiverCaptor.capture(), any());
verify(mStateChangeCallback).onScreenStateChanged(true);
reset(mStateChangeCallback);
setScreenState(true);
@@ -91,7 +91,7 @@ public class WifiDeviceStateChangeManagerTest extends WifiBaseTest {
public void testRegisterAfterBootCompleted() {
mWifiDeviceStateChangeManager.handleBootCompleted();
verify(mContext, atLeastOnce())
- .registerReceiver(mBroadcastReceiverCaptor.capture(), any(), any(), any());
+ .registerReceiver(mBroadcastReceiverCaptor.capture(), any());
mWifiDeviceStateChangeManager.registerStateChangeCallback(mStateChangeCallback);
// Register after boot completed should immediately get a callback
verify(mStateChangeCallback).onScreenStateChanged(true);
@@ -102,5 +102,6 @@ public class WifiDeviceStateChangeManagerTest extends WifiBaseTest {
assertNotNull(broadcastReceiver);
Intent intent = new Intent(screenOn ? ACTION_SCREEN_ON : ACTION_SCREEN_OFF);
broadcastReceiver.onReceive(mContext, intent);
+ mLooper.dispatchAll();
}
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiDiagnosticsTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiDiagnosticsTest.java
index f2a2f445a3..4457977b37 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiDiagnosticsTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiDiagnosticsTest.java
@@ -59,6 +59,8 @@ import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
@@ -159,6 +161,8 @@ public class WifiDiagnosticsTest extends WifiBaseTest {
when(mActiveModeWarden.getPrimaryClientModeManager()).thenReturn(mClientModeManager);
when(mActiveModeWarden.getClientModeManagers()).thenReturn(clientModeManagerList);
when(mDeviceConfigFacade.getBugReportMinWindowMs()).thenReturn(BUG_REPORT_MIN_WINDOW_MS);
+ when(mDeviceConfigFacade.getDisabledAutoBugreportTitleAndDetails()).thenReturn(
+ Collections.EMPTY_SET);
when(mContext.getPackageManager()).thenReturn(mPackageManager);
when(mPackageManager.queryIntentActivities(any(), anyInt())).thenReturn(mResolveInfoList);
// needed to for the loop in WifiDiagnostics.readLogcatStreamLinesWithTimeout().
@@ -924,6 +928,17 @@ public class WifiDiagnosticsTest extends WifiBaseTest {
}
@Test
+ public void takeBugreportIgnoredWhenTitleAndDetailDisabled() {
+ // Verify bugreport is disabled for a specific title and detail.
+ // Use set of empty String here to match empty title and detail.
+ when(mDeviceConfigFacade.getDisabledAutoBugreportTitleAndDetails()).thenReturn(
+ new HashSet<>(Arrays.asList("TITLEDETAIL")));
+ when(mBuildProperties.isUserBuild()).thenReturn(false);
+ mWifiDiagnostics.takeBugReport("TITLE", "DETAIL");
+ verify(mPackageManager, never()).queryIntentActivities(any(), anyInt());
+ }
+
+ @Test
public void takeBugReportSwallowsExceptions() {
when(mBuildProperties.isUserBuild()).thenReturn(false);
doThrow(new RuntimeException()).when(mBugreportManager).requestBugreport(
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiDialogManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiDialogManagerTest.java
index 257e7b9e70..58ff485f74 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiDialogManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiDialogManagerTest.java
@@ -21,6 +21,7 @@ import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doThrow;
@@ -107,7 +108,7 @@ public class WifiDialogManagerTest extends WifiBaseTest {
private void dispatchMockWifiThreadRunner(WifiThreadRunner wifiThreadRunner) {
ArgumentCaptor<Runnable> runnableArgumentCaptor = ArgumentCaptor.forClass(Runnable.class);
- verify(wifiThreadRunner, atLeastOnce()).post(runnableArgumentCaptor.capture());
+ verify(wifiThreadRunner, atLeastOnce()).post(runnableArgumentCaptor.capture(), anyString());
runnableArgumentCaptor.getValue().run();
}
@@ -124,7 +125,8 @@ public class WifiDialogManagerTest extends WifiBaseTest {
dialogHandle.launchDialog(timeoutMs);
ArgumentCaptor<Runnable> launchRunnableArgumentCaptor =
ArgumentCaptor.forClass(Runnable.class);
- verify(wifiThreadRunner, atLeastOnce()).post(launchRunnableArgumentCaptor.capture());
+ verify(wifiThreadRunner, atLeastOnce()).post(launchRunnableArgumentCaptor.capture(),
+ anyString());
launchRunnableArgumentCaptor.getValue().run();
}
@@ -139,7 +141,8 @@ public class WifiDialogManagerTest extends WifiBaseTest {
dialogHandle.dismissDialog();
ArgumentCaptor<Runnable> dismissRunnableArgumentCaptor =
ArgumentCaptor.forClass(Runnable.class);
- verify(wifiThreadRunner, atLeastOnce()).post(dismissRunnableArgumentCaptor.capture());
+ verify(wifiThreadRunner, atLeastOnce()).post(dismissRunnableArgumentCaptor.capture(),
+ anyString());
dismissRunnableArgumentCaptor.getValue().run();
}
@@ -338,7 +341,7 @@ public class WifiDialogManagerTest extends WifiBaseTest {
// A reply to the same dialog id should not trigger callback
mDialogManager.replyToSimpleDialog(dialogId, WifiManager.DIALOG_REPLY_POSITIVE);
- verify(callbackThreadRunner, never()).post(any());
+ verify(callbackThreadRunner, never()).post(any(), anyString());
verify(callback, times(0)).onPositiveButtonClicked();
// Another call to dismiss should not send another dismiss intent.
@@ -452,7 +455,7 @@ public class WifiDialogManagerTest extends WifiBaseTest {
verify(builder).setNeutralButton(eq(TEST_NEUTRAL_BUTTON_TEXT),
neutralButtonListenerCaptor.capture());
verify(builder).setOnCancelListener(cancelListenerCaptor.capture());
- verify(mWifiThreadRunner, never()).postDelayed(any(Runnable.class), anyInt());
+ verify(mWifiThreadRunner, never()).postDelayed(any(Runnable.class), anyInt(), anyString());
// Positive
positiveButtonListenerCaptor.getValue().onClick(dialog, DialogInterface.BUTTON_POSITIVE);
@@ -505,7 +508,8 @@ public class WifiDialogManagerTest extends WifiBaseTest {
// Verify the timeout runnable was posted and run it.
ArgumentCaptor<Runnable> runnableArgumentCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(mWifiThreadRunner, times(1))
- .postDelayed(runnableArgumentCaptor.capture(), eq((long) TIMEOUT_MILLIS));
+ .postDelayed(runnableArgumentCaptor.capture(), eq((long) TIMEOUT_MILLIS),
+ anyString());
runnableArgumentCaptor.getValue().run();
// Verify that the dialog was cancelled.
@@ -543,7 +547,8 @@ public class WifiDialogManagerTest extends WifiBaseTest {
// Verify the timeout runnable was posted.
ArgumentCaptor<Runnable> runnableArgumentCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(mWifiThreadRunner, times(1))
- .postDelayed(runnableArgumentCaptor.capture(), eq((long) TIMEOUT_MILLIS));
+ .postDelayed(runnableArgumentCaptor.capture(), eq((long) TIMEOUT_MILLIS),
+ anyString());
runnableArgumentCaptor.getValue().run();
// Dismiss the dialog before the timeout runnable executes.
@@ -623,7 +628,7 @@ public class WifiDialogManagerTest extends WifiBaseTest {
verify(builder).setNeutralButton(eq(TEST_NEUTRAL_BUTTON_TEXT),
neutralButtonListenerCaptor.capture());
verify(builder).setOnCancelListener(cancelListenerCaptor.capture());
- verify(mWifiThreadRunner, never()).postDelayed(any(Runnable.class), anyInt());
+ verify(mWifiThreadRunner, never()).postDelayed(any(Runnable.class), anyInt(), anyString());
// Positive
positiveButtonListenerCaptor.getValue().onClick(dialog, DialogInterface.BUTTON_POSITIVE);
@@ -676,7 +681,8 @@ public class WifiDialogManagerTest extends WifiBaseTest {
// Verify the timeout runnable was posted and run it.
ArgumentCaptor<Runnable> runnableArgumentCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(mWifiThreadRunner, times(1))
- .postDelayed(runnableArgumentCaptor.capture(), eq((long) TIMEOUT_MILLIS));
+ .postDelayed(runnableArgumentCaptor.capture(), eq((long) TIMEOUT_MILLIS),
+ anyString());
runnableArgumentCaptor.getValue().run();
// Verify that the dialog was cancelled.
@@ -714,7 +720,8 @@ public class WifiDialogManagerTest extends WifiBaseTest {
// Verify the timeout runnable was posted.
ArgumentCaptor<Runnable> runnableArgumentCaptor = ArgumentCaptor.forClass(Runnable.class);
verify(mWifiThreadRunner, times(1))
- .postDelayed(runnableArgumentCaptor.capture(), eq((long) TIMEOUT_MILLIS));
+ .postDelayed(runnableArgumentCaptor.capture(), eq((long) TIMEOUT_MILLIS),
+ anyString());
runnableArgumentCaptor.getValue().run();
// Dismiss the dialog before the timeout runnable executes.
@@ -991,7 +998,7 @@ public class WifiDialogManagerTest extends WifiBaseTest {
// A reply to the same dialog id should not trigger callback
mDialogManager.replyToP2pInvitationReceivedDialog(dialogId, true, null);
- verify(callbackThreadRunner, never()).post(any());
+ verify(callbackThreadRunner, never()).post(any(), anyString());
verify(callback, times(0)).onAccepted(null);
// Another call to dismiss should not send another dismiss intent.
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiGlobalsTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiGlobalsTest.java
index 3a29bbf1bc..dab681fca6 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiGlobalsTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiGlobalsTest.java
@@ -25,8 +25,9 @@ import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
-import android.content.Context;
import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiContext;
+import android.net.wifi.util.WifiResourceCache;
import androidx.test.filters.SmallTest;
@@ -47,7 +48,7 @@ public class WifiGlobalsTest extends WifiBaseTest {
private WifiGlobals mWifiGlobals;
private MockResources mResources;
- @Mock private Context mContext;
+ @Mock private WifiContext mContext;
private static final int TEST_NETWORK_ID = 54;
private static final String TEST_SSID = "\"GoogleGuest\"";
@@ -64,6 +65,7 @@ public class WifiGlobalsTest extends WifiBaseTest {
new String[] {TEST_SSID});
mResources.setStringArray(R.array.config_wifiAfcServerUrlsForCountry, new String[] {});
when(mContext.getResources()).thenReturn(mResources);
+ when(mContext.getResourceCache()).thenReturn(new WifiResourceCache(mContext));
mWifiGlobals = new WifiGlobals(mContext);
}
@@ -146,6 +148,7 @@ public class WifiGlobalsTest extends WifiBaseTest {
mWifiGlobals = new WifiGlobals(mContext);
assertFalse(mWifiGlobals.isBackgroundScanSupported());
+ when(mContext.getResourceCache()).thenReturn(new WifiResourceCache(mContext));
mResources.setBoolean(R.bool.config_wifi_background_scan_support, true);
mWifiGlobals = new WifiGlobals(mContext);
assertTrue(mWifiGlobals.isBackgroundScanSupported());
@@ -277,6 +280,8 @@ public class WifiGlobalsTest extends WifiBaseTest {
@Test
public void testSetWepAllowedWhenWepIsNotDeprecated() {
+ mResources.setBoolean(R.bool.config_wifiWepAllowedControlSupported, true);
+ mWifiGlobals = new WifiGlobals(mContext);
assertTrue(mWifiGlobals.isWepSupported());
// Default is not allow
assertFalse(mWifiGlobals.isWepAllowed());
@@ -288,6 +293,15 @@ public class WifiGlobalsTest extends WifiBaseTest {
mWifiGlobals.setWepAllowed(false);
assertTrue(mWifiGlobals.isWepDeprecated());
assertFalse(mWifiGlobals.isWepAllowed());
+
+ // Test WEP allowed control is NOT supported.
+ mResources.setBoolean(R.bool.config_wifiWepAllowedControlSupported, false);
+ mWifiGlobals = new WifiGlobals(mContext);
+ // Default is not allow, but don't care it since control is not supported.
+ assertFalse(mWifiGlobals.isWepAllowed());
+ // But we won't consider WEP is allowed since control is NOT supported.
+ // So WEP should be NOT deprecated since config_wifiWepDeprecated is false.
+ assertFalse(mWifiGlobals.isWepDeprecated());
}
@@ -301,57 +315,6 @@ public class WifiGlobalsTest extends WifiBaseTest {
assertFalse(mWifiGlobals.isSwPnoEnabled());
}
- /**
- * Verify Force Overlay Config Value
- */
- @Test
- public void testForceOverlayConfigValue() throws Exception {
- mResources.setBoolean(R.bool.config_wifi_background_scan_support, true);
- mWifiGlobals = new WifiGlobals(mContext);
- assertFalse(mWifiGlobals.forceOverlayConfigValue(null, null, false));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
- assertFalse(mWifiGlobals.forceOverlayConfigValue("", "", false));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
- assertFalse(mWifiGlobals.forceOverlayConfigValue("abc", "", false));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
- assertFalse(mWifiGlobals.forceOverlayConfigValue(null, null, true));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
- assertFalse(mWifiGlobals.forceOverlayConfigValue("", "", true));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
- assertFalse(mWifiGlobals.forceOverlayConfigValue("abc", "", true));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
- assertFalse(mWifiGlobals.forceOverlayConfigValue("abc", "false", true));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
- assertFalse(mWifiGlobals.forceOverlayConfigValue("abc", "reset", true));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
- assertFalse(mWifiGlobals.forceOverlayConfigValue("abc", "true", true));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
- assertFalse(mWifiGlobals.forceOverlayConfigValue("config_wifi_background_scan_support",
- "abc", true));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
-
- //Disable case
- assertTrue(mWifiGlobals.forceOverlayConfigValue("config_wifi_background_scan_support",
- "false", false));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
- assertTrue(mWifiGlobals.forceOverlayConfigValue("config_wifi_background_scan_support",
- "true", false));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
-
- // Testing for false case
- assertTrue(mWifiGlobals.forceOverlayConfigValue("config_wifi_background_scan_support",
- "false", true));
- assertFalse(mWifiGlobals.isBackgroundScanSupported());
- mResources.setBoolean(R.bool.config_wifi_background_scan_support, false);
- mWifiGlobals = new WifiGlobals(mContext);
- assertFalse(mWifiGlobals.isBackgroundScanSupported());
-
- //Resetting to True
- assertTrue(mWifiGlobals.forceOverlayConfigValue("config_wifi_background_scan_support",
- "true", true));
- assertTrue(mWifiGlobals.isBackgroundScanSupported());
- }
-
@Test
public void testIsD2dSupportedWhenInfraStaDisabled() {
mResources.setBoolean(R.bool.config_wifiD2dAllowedControlSupportedWhenInfraStaDisabled,
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiMetricsTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiMetricsTest.java
index 41f10cfe41..3c4f6c4db1 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiMetricsTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiMetricsTest.java
@@ -2235,6 +2235,7 @@ public class WifiMetricsTest extends WifiBaseTest {
mWifiMetrics.setConnectionScanDetail("nonexistentIface", mock(ScanDetail.class));
mWifiMetrics.setConnectionPmkCache("nonexistentIface", false);
mWifiMetrics.setConnectionMaxSupportedLinkSpeedMbps("nonexistentIface", 100, 50);
+ mWifiMetrics.setConnectionChannelWidth("nonexistentIface", ScanResult.CHANNEL_WIDTH_160MHZ);
mWifiMetrics.endConnectionEvent("nonexistentIface",
WifiMetrics.ConnectionEvent.FAILURE_ASSOCIATION_REJECTION,
WifiMetricsProto.ConnectionEvent.HLF_DHCP,
@@ -6611,7 +6612,7 @@ public class WifiMetricsTest extends WifiBaseTest {
eq((int) wifiDisconnectTimeMs / 1000),
eq((int) (wifiDisconnectTimeMs - connectionEndTimeMs) / 1000),
eq(WifiStatsLog.WIFI_CONNECTION_RESULT_REPORTED__ROLE__ROLE_CLIENT_PRIMARY),
- anyInt(), anyInt(), anyInt(), anyInt()));
+ anyInt(), anyInt(), anyInt(), anyInt(), anyInt()));
}
@Test
@@ -6639,7 +6640,7 @@ public class WifiMetricsTest extends WifiBaseTest {
ExtendedMockito.verify(() -> WifiStatsLog.write(
eq(WifiStatsLog.WIFI_DISCONNECT_REPORTED),
anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(),
- anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt()),
+ anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt()),
times(0));
}
@@ -6650,7 +6651,7 @@ public class WifiMetricsTest extends WifiBaseTest {
ExtendedMockito.verify(() -> WifiStatsLog.write(
eq(WifiStatsLog.WIFI_DISCONNECT_REPORTED),
anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(),
- anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt()),
+ anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt(), anyInt()),
times(0));
}
@@ -7256,7 +7257,8 @@ public class WifiMetricsTest extends WifiBaseTest {
when(networkDetail.isIndividualTwtSupported()).thenReturn(true);
when(networkDetail.isTwtRequired()).thenReturn(true);
when(networkDetail.isFilsCapable()).thenReturn(true);
- when(networkDetail.is11azSupported()).thenReturn(true);
+ when(networkDetail.is80211azNtbResponder()).thenReturn(true);
+ when(networkDetail.is80211azTbResponder()).thenReturn(false);
when(networkDetail.is80211McResponderSupport()).thenReturn(true);
when(networkDetail.isEpcsPriorityAccessSupported()).thenReturn(true);
when(networkDetail.getHSRelease()).thenReturn(NetworkDetail.HSRelease.Unknown);
@@ -7277,6 +7279,7 @@ public class WifiMetricsTest extends WifiBaseTest {
mWifiMetrics.logBugReport();
mWifiMetrics.logStaEvent(TEST_IFACE_NAME, StaEvent.TYPE_CMD_START_ROAM,
StaEvent.DISCONNECT_UNKNOWN, null);
+ mWifiMetrics.setConnectionChannelWidth(TEST_IFACE_NAME, ScanResult.CHANNEL_WIDTH_160MHZ);
mWifiMetrics.endConnectionEvent(TEST_IFACE_NAME,
WifiMetrics.ConnectionEvent.FAILURE_NONE,
WifiMetricsProto.ConnectionEvent.HLF_NONE,
@@ -7310,6 +7313,7 @@ public class WifiMetricsTest extends WifiBaseTest {
eq(WifiStatsLog.WIFI_AP_CAPABILITIES_REPORTED__PASSPOINT_RELEASE__PASSPOINT_RELEASE_UNKNOWN),
eq(false), // isPasspointHomeProvider
eq(WifiStatsLog.WIFI_AP_CAPABILITIES_REPORTED__AP_TYPE_6GHZ__AP_TYPE_6GHZ_STANDARD_POWER),
- eq(true))); // mIsEcpsPriorityAccessSupported
+ eq(true), // mIsEcpsPriorityAccessSupported
+ eq(WifiStatsLog.WIFI_AP_CAPABILITIES_REPORTED__CHANNEL_WIDTH_MHZ__CHANNEL_WIDTH_160MHZ))); // mChannelWidth
}
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiNativeInterfaceManagementTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiNativeInterfaceManagementTest.java
index 2481f066e6..0fcc471052 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiNativeInterfaceManagementTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiNativeInterfaceManagementTest.java
@@ -57,6 +57,7 @@ import com.android.modules.utils.build.SdkLevel;
import com.android.server.wifi.HalDeviceManager.InterfaceDestroyedListener;
import com.android.server.wifi.WifiNative.SupplicantDeathEventHandler;
import com.android.server.wifi.WifiNative.VendorHalDeathEventHandler;
+import com.android.server.wifi.hal.WifiNanIface;
import com.android.server.wifi.p2p.WifiP2pNative;
import com.android.server.wifi.util.NetdWrapper;
import com.android.server.wifi.util.NetdWrapper.NetdEventObserver;
@@ -116,17 +117,19 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
@Mock private WifiNative.InterfaceCallback mIfaceCallback0;
@Mock private WifiNative.InterfaceCallback mIfaceCallback1;
@Mock private WifiNative.InterfaceEventCallback mIfaceEventCallback0;
- @Mock private HalDeviceManager.InterfaceDestroyedListener mP2pInterfaceDestroyedListener;
- @Mock private Handler mP2pEventHandler;
+ @Mock private HalDeviceManager.InterfaceDestroyedListener mTestInterfaceDestroyedListener;
+ @Mock private Handler mCreateIfaceEventHandler;
@Mock private WifiSettingsConfigStore mWifiSettingsConfigStore;
@Mock private WifiGlobals mWifiGlobals;
@Mock private ConcreteClientModeManager mConcreteClientModeManager;
@Mock private SoftApManager mSoftApManager;
+ @Mock private WifiNanIface mActiveWifiNanIface;
@Mock DeviceConfigFacade mDeviceConfigFacade;
private TestLooper mLooper;
private WifiNative.Iface mActiveP2pIface;
+ private WifiNative.Iface mActiveNanIface;
private ArgumentCaptor<VendorHalDeathEventHandler> mWifiVendorHalDeathHandlerCaptor =
ArgumentCaptor.forClass(VendorHalDeathEventHandler.class);
@@ -251,6 +254,7 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
mInOrder.verify(mWificondControl).tearDownInterfaces();
mInOrder.verify(mWifiVendorHal).registerRadioModeChangeHandler(any());
mActiveP2pIface = null;
+ mActiveNanIface = null;
}
@After
@@ -899,12 +903,13 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
* Verifies the setup of a client interface and wificond death handling.
*/
@Test
- public void testSetupClientInterfaceAndWicondDied() throws Exception {
+ public void testSetupClientInterfaceAndWificondDied() throws Exception {
executeAndValidateSetupClientInterface(
false, false, IFACE_NAME_0, mIfaceCallback0, mIfaceDestroyedListenerCaptor0,
mNetworkObserverCaptor0);
// Trigger wificond death
mWificondDeathHandlerCaptor.getValue().run();
+ mLooper.dispatchAll();
mInOrder.verify(mWifiMetrics).incrementNumWificondCrashes();
@@ -924,6 +929,7 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
// Trigger vendor HAL death
mWifiVendorHalDeathHandlerCaptor.getValue().onDeath();
+ mLooper.dispatchAll();
mInOrder.verify(mWifiMetrics).incrementNumHalCrashes();
@@ -971,6 +977,7 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
// Trigger vendor HAL death
mHostapdDeathHandlerCaptor.getValue().onDeath();
+ mLooper.dispatchAll();
mInOrder.verify(mWifiMetrics).incrementNumHostapdCrashes();
@@ -1000,6 +1007,7 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
// Trigger vendor HAL death
mHostapdDeathHandlerCaptor.getValue().onDeath();
+ mLooper.dispatchAll();
mInOrder.verify(mWifiMetrics).incrementNumHostapdCrashes();
@@ -1486,19 +1494,80 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
return P2P_IFACE_NAME;
}
}).when(mHalDeviceManager).createP2pIface(any(), any(), any());
- mActiveP2pIface = mWifiNative.createP2pIface(mP2pInterfaceDestroyedListener,
- mP2pEventHandler, TEST_WORKSOURCE);
+ mActiveP2pIface = mWifiNative.createP2pIface(mTestInterfaceDestroyedListener,
+ mCreateIfaceEventHandler, TEST_WORKSOURCE);
assertEquals(P2P_IFACE_NAME, mActiveP2pIface.name);
// Creation of P2P interface should trigger the STA interface destroy
verify(mWifiVendorHal, atLeastOnce()).isVendorHalSupported();
verify(mWifiVendorHal, atLeastOnce()).isVendorHalReady();
validateOnDestroyedClientInterface(false, false, true,
IFACE_NAME_0, mIfaceCallback0, mNetworkObserverCaptor0.getValue());
- validateCreateP2pInterface(true, false, false, P2P_IFACE_NAME, true, 0);
+ validateCreateP2pInterface(true, false, false, true, 0);
executeAndValidateTeardownP2pInterface(false, false, false, false, false,
mActiveP2pIface, true);
}
+ @Test
+ public void testSetupNanInterfaceAndTeardownNan() throws Exception {
+ executeAndValidateCreateNanInterface(false, false, false, false, true);
+ executeAndValidateTeardownNanInterface(false, false, false, false, mActiveNanIface);
+ }
+
+
+ /**
+ * Verifies the setup of a single client interface and teardown by Nan on.
+ */
+ @Test
+ public void testSetupClientInterfaceAndTeardownNan() throws Exception {
+ executeAndValidateCreateNanInterface(false, false, false, false, true);
+ // Trigger the Nan interface teardown when STA interface is created.
+ doAnswer(new MockAnswerUtil.AnswerWithArguments() {
+ public String answer(InterfaceDestroyedListener destroyedListener, WorkSource ws,
+ ConcreteClientModeManager concreteClientModeManager) {
+ mWifiNative.teardownNanIface(mActiveNanIface.id);
+ return IFACE_NAME_0;
+ }
+ }).when(mWifiVendorHal).createStaIface(any(), any(), eq(mConcreteClientModeManager));
+
+ assertEquals(IFACE_NAME_0,
+ mWifiNative.setupInterfaceForClientInScanMode(mIfaceCallback0, TEST_WORKSOURCE,
+ mConcreteClientModeManager));
+ assertEquals(Set.of(IFACE_NAME_0), mWifiNative.getClientInterfaceNames());
+ validateSetupClientInterfaceForScan(
+ true, false, false, false, IFACE_NAME_0, mIfaceDestroyedListenerCaptor0,
+ mNetworkObserverCaptor0, true, 0);
+ validateStartHal(true, true);
+ validateOnDestroyedNanInterface(true, false, false, false);
+ }
+
+ /**
+ * Verifies the setup of a single client interface (for scan) and teardown by Nan on.
+ */
+ @Test
+ public void testCreateNanIfaceAndTeardownClientIface() throws Exception {
+ executeAndValidateSetupClientInterface(
+ false, false, false, false, IFACE_NAME_0, mIfaceCallback0,
+ mIfaceDestroyedListenerCaptor0, mNetworkObserverCaptor0, true, 0);
+ assertEquals(Set.of(IFACE_NAME_0), mWifiNative.getClientInterfaceNames());
+ // Trigger the STA interface teardown when P2p interface is created.
+ // The iface name will remain the same.
+ doAnswer(new MockAnswerUtil.AnswerWithArguments() {
+ public WifiNanIface answer(
+ HalDeviceManager.InterfaceDestroyedListener interfaceDestroyedListener,
+ Handler handler, WorkSource requestorWs) {
+ mIfaceDestroyedListenerCaptor0.getValue().onDestroyed(IFACE_NAME_0);
+ return mActiveWifiNanIface;
+ }
+ }).when(mHalDeviceManager).createNanIface(any(), any(), any());
+ executeAndValidateCreateNanInterface(true, false, false, false, false);
+ // Creation of Nan interface should trigger the STA interface destroy
+ verify(mWifiVendorHal, atLeastOnce()).isVendorHalSupported();
+ verify(mWifiVendorHal, atLeastOnce()).isVendorHalReady();
+ validateOnDestroyedClientInterface(false, false, false, true,
+ IFACE_NAME_0, mIfaceCallback0, mNetworkObserverCaptor0.getValue());
+ executeAndValidateTeardownNanInterface(false, false, false, false, mActiveNanIface);
+ }
+
private void executeAndValidateSetupClientInterface(
boolean hasStaIface, boolean hasApIface,
String ifaceName, @Mock WifiNative.InterfaceCallback callback,
@@ -1526,12 +1595,24 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
ArgumentCaptor<InterfaceDestroyedListener> destroyedListenerCaptor,
ArgumentCaptor<NetdEventObserver> networkObserverCaptor, boolean vendorHalSupported,
int failureCode) throws Exception {
+ executeAndValidateSetupClientInterface(hasStaIface, hasApIface, hasP2pIface, false,
+ ifaceName, callback, destroyedListenerCaptor,
+ networkObserverCaptor, vendorHalSupported, failureCode);
+ }
+
+ private void executeAndValidateSetupClientInterface(
+ boolean hasStaIface, boolean hasApIface, boolean hasP2pIface, boolean hasNanIface,
+ String ifaceName, @Mock WifiNative.InterfaceCallback callback,
+ ArgumentCaptor<InterfaceDestroyedListener> destroyedListenerCaptor,
+ ArgumentCaptor<NetdEventObserver> networkObserverCaptor, boolean vendorHalSupported,
+ int failureCode) throws Exception {
when(mWifiVendorHal.createStaIface(any(), any(), eq(mConcreteClientModeManager)))
.thenReturn(ifaceName);
executeAndValidateSetupClientInterfaceForScan(
- hasStaIface, hasApIface, hasP2pIface, ifaceName, callback, destroyedListenerCaptor,
- networkObserverCaptor, vendorHalSupported, failureCode);
- executeAndValidateSwitchClientInterfaceToConnectivityMode(hasStaIface, hasApIface,
+ hasStaIface, hasApIface, hasP2pIface, hasNanIface, ifaceName, callback,
+ destroyedListenerCaptor, networkObserverCaptor, vendorHalSupported, failureCode);
+ executeAndValidateSwitchClientInterfaceToConnectivityMode(
+ hasStaIface, hasApIface,
ifaceName, TEST_WORKSOURCE, vendorHalSupported, failureCode);
}
@@ -1550,6 +1631,16 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
String ifaceName, @Mock WifiNative.InterfaceCallback callback,
InterfaceDestroyedListener destroyedListener,
NetdEventObserver networkObserver) throws Exception {
+ executeAndValidateTeardownClientInterface(anyOtherStaIface, anyOtherApIface,
+ anyOtherP2pIface, false /* anyOtherNanIface */, ifaceName, callback,
+ destroyedListener, networkObserver);
+ }
+
+ private void executeAndValidateTeardownClientInterface(
+ boolean anyOtherStaIface, boolean anyOtherApIface, boolean anyOtherP2pIface,
+ boolean anyOtherNanIface, String ifaceName, @Mock WifiNative.InterfaceCallback callback,
+ InterfaceDestroyedListener destroyedListener,
+ NetdEventObserver networkObserver) throws Exception {
mWifiNative.teardownInterface(ifaceName);
mInOrder.verify(mWifiVendorHal).isVendorHalSupported();
@@ -1559,7 +1650,7 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
destroyedListener.onDestroyed(ifaceName);
validateOnDestroyedClientInterface(
- anyOtherStaIface, anyOtherApIface, anyOtherP2pIface,
+ anyOtherStaIface, anyOtherApIface, anyOtherP2pIface, anyOtherNanIface,
ifaceName, callback, networkObserver);
}
@@ -1576,6 +1667,15 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
boolean anyOtherStaIface, boolean anyOtherApIface, boolean anyOtherP2pIface,
String ifaceName, @Mock WifiNative.InterfaceCallback callback,
NetdEventObserver networkObserver) throws Exception {
+ validateOnDestroyedClientInterface(
+ anyOtherStaIface, anyOtherApIface, anyOtherP2pIface, false /* anyOtherNanIface */,
+ ifaceName, callback, networkObserver);
+ }
+
+ private void validateOnDestroyedClientInterface(
+ boolean anyOtherStaIface, boolean anyOtherApIface, boolean anyOtherP2pIface,
+ boolean anyOtherNanIface, String ifaceName, @Mock WifiNative.InterfaceCallback callback,
+ NetdEventObserver networkObserver) throws Exception {
mInOrder.verify(mWifiMonitor).stopMonitoring(ifaceName);
if (networkObserver != null) {
mInOrder.verify(mNetdWrapper).unregisterObserver(networkObserver);
@@ -1592,7 +1692,7 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
}
when(mSupplicantStaIfaceHal.isInitializationStarted()).thenReturn(false);
}
- if (!anyOtherStaIface && !anyOtherApIface && !anyOtherP2pIface) {
+ if (!anyOtherStaIface && !anyOtherApIface && !anyOtherP2pIface && !anyOtherNanIface) {
mInOrder.verify(mWificondControl).tearDownInterfaces();
mInOrder.verify(mWifiVendorHal).isVendorHalSupported();
mInOrder.verify(mWifiVendorHal).stopVendorHal();
@@ -1627,6 +1727,17 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
ArgumentCaptor<InterfaceDestroyedListener> destroyedListenerCaptor,
ArgumentCaptor<NetdEventObserver> networkObserverCaptor,
boolean vendorHalSupported, int failureCode) throws Exception {
+ executeAndValidateSetupClientInterfaceForScan(hasStaIface, hasApIface,
+ hasP2pIface, false /* hasNanIface */, ifaceName, callback,
+ destroyedListenerCaptor, networkObserverCaptor, vendorHalSupported, failureCode);
+ }
+
+ private void executeAndValidateSetupClientInterfaceForScan(
+ boolean hasStaIface, boolean hasApIface, boolean hasP2pIface, boolean hasNanIface,
+ String ifaceName, @Mock WifiNative.InterfaceCallback callback,
+ ArgumentCaptor<InterfaceDestroyedListener> destroyedListenerCaptor,
+ ArgumentCaptor<NetdEventObserver> networkObserverCaptor,
+ boolean vendorHalSupported, int failureCode) throws Exception {
if (failureCode != STA_FAILURE_CODE_CREAT_IFACE) {
when(mWifiVendorHal.createStaIface(any(), any(), eq(mConcreteClientModeManager)))
.thenReturn(ifaceName);
@@ -1636,8 +1747,8 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
mConcreteClientModeManager));
validateSetupClientInterfaceForScan(
- hasStaIface, hasApIface, hasP2pIface, ifaceName, destroyedListenerCaptor,
- networkObserverCaptor, vendorHalSupported, failureCode);
+ hasStaIface, hasApIface, hasP2pIface, hasNanIface, ifaceName,
+ destroyedListenerCaptor, networkObserverCaptor, vendorHalSupported, failureCode);
}
private void validateStartHal(boolean hasAnyIface, boolean vendorHalSupported) {
@@ -1671,7 +1782,18 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
String ifaceName, ArgumentCaptor<InterfaceDestroyedListener> destroyedListenerCaptor,
ArgumentCaptor<NetdEventObserver> networkObserverCaptor, boolean vendorHalSupported,
int failureCode) throws Exception {
- validateStartHal(hasStaIface || hasApIface || hasP2pIface, vendorHalSupported);
+ validateSetupClientInterfaceForScan(hasStaIface, hasApIface, hasP2pIface,
+ false /* hasNanIfacd */, ifaceName, destroyedListenerCaptor, networkObserverCaptor,
+ vendorHalSupported, failureCode);
+ }
+
+ private void validateSetupClientInterfaceForScan(
+ boolean hasStaIface, boolean hasApIface, boolean hasP2pIface, boolean hasNanIface,
+ String ifaceName, ArgumentCaptor<InterfaceDestroyedListener> destroyedListenerCaptor,
+ ArgumentCaptor<NetdEventObserver> networkObserverCaptor, boolean vendorHalSupported,
+ int failureCode) throws Exception {
+ validateStartHal(hasStaIface || hasApIface || hasP2pIface || hasNanIface,
+ vendorHalSupported);
if (vendorHalSupported) {
mInOrder.verify(mWifiVendorHal).createStaIface(
destroyedListenerCaptor.capture(), eq(TEST_WORKSOURCE),
@@ -1729,6 +1851,16 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
String ifaceName, @Mock WifiNative.InterfaceCallback callback,
InterfaceDestroyedListener destroyedListener,
NetdEventObserver networkObserver) throws Exception {
+ executeAndValidateTeardownClientInterfaceForScan(anyOtherStaIface, anyOtherApIface,
+ anyOtherP2pIface, false /* anyOtherNanIface */, ifaceName, callback,
+ destroyedListener, networkObserver);
+ }
+
+ private void executeAndValidateTeardownClientInterfaceForScan(
+ boolean anyOtherStaIface, boolean anyOtherApIface, boolean anyOtherP2pIface,
+ boolean anyOtherNanIface, String ifaceName, @Mock WifiNative.InterfaceCallback callback,
+ InterfaceDestroyedListener destroyedListener,
+ NetdEventObserver networkObserver) throws Exception {
mWifiNative.teardownInterface(ifaceName);
mInOrder.verify(mWifiVendorHal).isVendorHalSupported();
@@ -1738,7 +1870,7 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
destroyedListener.onDestroyed(ifaceName);
validateOnDestroyedClientInterfaceForScan(
- anyOtherStaIface, anyOtherApIface, anyOtherP2pIface,
+ anyOtherStaIface, anyOtherApIface, anyOtherP2pIface, anyOtherNanIface,
ifaceName, callback, networkObserver);
}
@@ -1755,13 +1887,21 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
boolean anyOtherStaIface, boolean anyOtherApIface, boolean anyOtherP2pIface,
String ifaceName, @Mock WifiNative.InterfaceCallback callback,
NetdEventObserver networkObserver) throws Exception {
+ validateOnDestroyedClientInterfaceForScan(
+ anyOtherStaIface, anyOtherApIface, anyOtherP2pIface,
+ false /* anyOtherNanIface */, ifaceName, callback, networkObserver);
+ }
+ private void validateOnDestroyedClientInterfaceForScan(
+ boolean anyOtherStaIface, boolean anyOtherApIface, boolean anyOtherP2pIface,
+ boolean anyOtherNanIface, String ifaceName, @Mock WifiNative.InterfaceCallback callback,
+ NetdEventObserver networkObserver) throws Exception {
mInOrder.verify(mWifiMonitor).stopMonitoring(ifaceName);
if (networkObserver != null) {
mInOrder.verify(mNetdWrapper).unregisterObserver(networkObserver);
}
mInOrder.verify(mWificondControl).tearDownClientInterface(ifaceName);
- if (!anyOtherStaIface && !anyOtherApIface && !anyOtherP2pIface) {
+ if (!anyOtherStaIface && !anyOtherApIface && !anyOtherP2pIface && !anyOtherNanIface) {
mInOrder.verify(mWificondControl).tearDownInterfaces();
mInOrder.verify(mWifiVendorHal).isVendorHalSupported();
mInOrder.verify(mWifiVendorHal).stopVendorHal();
@@ -1796,6 +1936,17 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
ArgumentCaptor<InterfaceDestroyedListener> destroyedListenerCaptor,
ArgumentCaptor<NetdEventObserver> networkObserverCaptor, boolean isBridged,
boolean vendorHalSupported, int failureCode) throws Exception {
+ executeAndValidateSetupSoftApInterface(hasStaIface, hasApIface, hasP2pIface,
+ false /* hasNanIface */, ifaceName, callback, destroyedListenerCaptor,
+ networkObserverCaptor, isBridged, vendorHalSupported, failureCode);
+ }
+
+ private void executeAndValidateSetupSoftApInterface(
+ boolean hasStaIface, boolean hasApIface, boolean hasP2pIface, boolean hasNanIface,
+ String ifaceName, @Mock WifiNative.InterfaceCallback callback,
+ ArgumentCaptor<InterfaceDestroyedListener> destroyedListenerCaptor,
+ ArgumentCaptor<NetdEventObserver> networkObserverCaptor, boolean isBridged,
+ boolean vendorHalSupported, int failureCode) throws Exception {
when(mWifiVendorHal.createApIface(any(), any(), anyInt(), eq(isBridged), any(), anyList()))
.thenReturn(ifaceName);
assertEquals(failureCode == 0 ? ifaceName : null, mWifiNative.setupInterfaceForSoftApMode(
@@ -1803,8 +1954,9 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
mSoftApManager, new ArrayList<>()));
validateSetupSoftApInterface(
- hasStaIface, hasApIface, ifaceName, destroyedListenerCaptor,
- networkObserverCaptor, isBridged, vendorHalSupported, failureCode);
+ hasStaIface, hasApIface, hasP2pIface, hasNanIface, ifaceName,
+ destroyedListenerCaptor, networkObserverCaptor, isBridged,
+ vendorHalSupported, failureCode);
}
private void validateSetupSoftApInterface(
@@ -1822,7 +1974,18 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
String ifaceName, ArgumentCaptor<InterfaceDestroyedListener> destroyedListenerCaptor,
ArgumentCaptor<NetdEventObserver> networkObserverCaptor, boolean isBridged,
boolean vendorHalSupported, int failureCode) throws Exception {
- validateStartHal(hasStaIface || hasApIface || hasP2pIface, vendorHalSupported);
+ validateSetupSoftApInterface(hasStaIface, hasApIface, hasP2pIface, false /* hasNanIface */,
+ ifaceName, destroyedListenerCaptor,
+ networkObserverCaptor, isBridged, vendorHalSupported, failureCode);
+ }
+
+ private void validateSetupSoftApInterface(
+ boolean hasStaIface, boolean hasApIface, boolean hasP2pIface, boolean hasNanIface,
+ String ifaceName, ArgumentCaptor<InterfaceDestroyedListener> destroyedListenerCaptor,
+ ArgumentCaptor<NetdEventObserver> networkObserverCaptor, boolean isBridged,
+ boolean vendorHalSupported, int failureCode) throws Exception {
+ validateStartHal(hasStaIface || hasApIface || hasP2pIface || hasNanIface,
+ vendorHalSupported);
if (!hasApIface) {
mInOrder.verify(mHostapdHal).isInitializationStarted();
mInOrder.verify(mHostapdHal).initialize();
@@ -1919,6 +2082,15 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
boolean anyOtherStaIface, boolean anyOtherApIface, boolean anyOtherP2pIface,
String ifaceName, @Mock WifiNative.InterfaceCallback callback,
NetdEventObserver networkObserver) throws Exception {
+ validateOnDestroyedSoftApInterface(
+ anyOtherStaIface, anyOtherApIface, anyOtherP2pIface,
+ false /* anyOtherNanIface */, ifaceName, callback, networkObserver);
+ }
+
+ private void validateOnDestroyedSoftApInterface(
+ boolean anyOtherStaIface, boolean anyOtherApIface, boolean anyOtherP2pIface,
+ boolean anyOtherNanIface, String ifaceName, @Mock WifiNative.InterfaceCallback callback,
+ NetdEventObserver networkObserver) throws Exception {
if (networkObserver != null) {
mInOrder.verify(mNetdWrapper).unregisterObserver(networkObserver);
}
@@ -1929,7 +2101,7 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
mInOrder.verify(mHostapdHal).deregisterDeathHandler();
mInOrder.verify(mHostapdHal).terminate();
}
- if (!anyOtherStaIface && !anyOtherApIface && !anyOtherP2pIface) {
+ if (!anyOtherStaIface && !anyOtherApIface && !anyOtherP2pIface && !anyOtherNanIface) {
mInOrder.verify(mWificondControl).tearDownInterfaces();
mInOrder.verify(mWifiVendorHal).isVendorHalSupported();
mInOrder.verify(mWifiVendorHal).stopVendorHal();
@@ -1956,6 +2128,13 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
private void executeAndValidateCreateP2pInterface(
boolean hasStaIface, boolean hasApIface, boolean hasP2pIface,
String ifaceName, boolean vendorHalSupported, int failureCode) throws Exception {
+ executeAndValidateCreateP2pInterface(hasStaIface, hasApIface, hasP2pIface, false,
+ ifaceName, vendorHalSupported, failureCode);
+ }
+
+ private void executeAndValidateCreateP2pInterface(
+ boolean hasStaIface, boolean hasApIface, boolean hasP2pIface, boolean hasNanIface,
+ String ifaceName, boolean vendorHalSupported, int failureCode) throws Exception {
if (failureCode != P2P_FAILURE_CODE_CREATE_INTERFACE) {
if (vendorHalSupported) {
when(mHalDeviceManager.createP2pIface(any(), any(), any()))
@@ -1965,25 +2144,33 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
.thenReturn(ifaceName);
}
}
- mActiveP2pIface = mWifiNative.createP2pIface(mP2pInterfaceDestroyedListener,
- mP2pEventHandler, TEST_WORKSOURCE);
+ mActiveP2pIface = mWifiNative.createP2pIface(mTestInterfaceDestroyedListener,
+ mCreateIfaceEventHandler, TEST_WORKSOURCE);
if (failureCode == 0) {
assertNotNull(mActiveP2pIface);
assertEquals(mActiveP2pIface.name, ifaceName);
} else {
assertNull(mActiveP2pIface);
}
- validateCreateP2pInterface(hasStaIface, hasApIface, hasP2pIface,
- ifaceName, vendorHalSupported, failureCode);
+ validateCreateP2pInterface(hasStaIface, hasApIface, hasP2pIface, hasNanIface,
+ vendorHalSupported, failureCode);
}
private void validateCreateP2pInterface(
boolean hasStaIface, boolean hasApIface, boolean hasP2pIface,
- String ifaceName, boolean vendorHalSupported, int failureCode) throws Exception {
- validateStartHal(hasStaIface || hasApIface || hasP2pIface, vendorHalSupported);
+ boolean vendorHalSupported, int failureCode) throws Exception {
+ validateCreateP2pInterface(hasStaIface, hasApIface, hasP2pIface, false,
+ vendorHalSupported, failureCode);
+ }
+
+ private void validateCreateP2pInterface(
+ boolean hasStaIface, boolean hasApIface, boolean hasP2pIface, boolean hasNanIface,
+ boolean vendorHalSupported, int failureCode) throws Exception {
+ validateStartHal(hasStaIface || hasApIface || hasP2pIface || hasNanIface,
+ vendorHalSupported);
if (vendorHalSupported) {
- verify(mHalDeviceManager).createP2pIface(eq(mP2pInterfaceDestroyedListener),
- eq(mP2pEventHandler), eq(TEST_WORKSOURCE));
+ verify(mHalDeviceManager).createP2pIface(eq(mTestInterfaceDestroyedListener),
+ eq(mCreateIfaceEventHandler), eq(TEST_WORKSOURCE));
if (failureCode == P2P_FAILURE_CODE_CREATE_INTERFACE) {
verify(mWifiMetrics).incrementNumSetupP2pInterfaceFailureDueToHal();
}
@@ -1997,18 +2184,31 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
boolean isSupplicantStartedBefore, boolean anyOtherApIface,
boolean anyOtherP2pIface, WifiNative.Iface iface, boolean vendorHalSupported)
throws Exception {
+ executeAndValidateTeardownP2pInterface(anyOtherStaIface, anyOtherConnectivityStaIface,
+ isSupplicantStartedBefore, anyOtherApIface, anyOtherP2pIface, false,
+ iface, vendorHalSupported);
+ }
+
+ private void executeAndValidateTeardownP2pInterface(
+ boolean anyOtherStaIface, boolean anyOtherConnectivityStaIface,
+ boolean isSupplicantStartedBefore, boolean anyOtherApIface,
+ boolean anyOtherP2pIface, boolean anyOtherNanIface,
+ WifiNative.Iface iface, boolean vendorHalSupported)
+ throws Exception {
mWifiNative.teardownP2pIface(iface.id);
validateOnDestroyedP2pInterface(anyOtherStaIface, anyOtherConnectivityStaIface,
isSupplicantStartedBefore, anyOtherApIface,
- anyOtherP2pIface, vendorHalSupported);
+ anyOtherP2pIface, anyOtherNanIface, vendorHalSupported);
}
private void validateOnDestroyedP2pInterface(
boolean anyOtherStaIface, boolean anyOtherConnectivityStaIface,
boolean isSupplicantStartedBefore, boolean anyOtherApIface,
- boolean anyOtherP2pIface, boolean vendorHalSupported) throws Exception {
- if (vendorHalSupported && !anyOtherStaIface && !anyOtherApIface && !anyOtherP2pIface) {
+ boolean anyOtherP2pIface, boolean anyOtherNanIface,
+ boolean vendorHalSupported) throws Exception {
+ if (vendorHalSupported && !anyOtherStaIface && !anyOtherApIface
+ && !anyOtherP2pIface && !anyOtherNanIface) {
mInOrder.verify(mWificondControl).tearDownInterfaces();
mInOrder.verify(mWifiVendorHal).isVendorHalSupported();
mInOrder.verify(mWifiVendorHal).stopVendorHal();
@@ -2025,4 +2225,37 @@ public class WifiNativeInterfaceManagementTest extends WifiBaseTest {
}
}
}
+
+ // Nan
+ private void executeAndValidateCreateNanInterface(
+ boolean hasStaIface, boolean hasApIface, boolean hasP2pIface, boolean hasNanIface,
+ boolean isNeedToMockCreateNan) throws Exception {
+ if (isNeedToMockCreateNan) {
+ when(mHalDeviceManager.createNanIface(any(), any(), any()))
+ .thenReturn(mActiveWifiNanIface);
+ }
+ mActiveNanIface = mWifiNative.createNanIface(mTestInterfaceDestroyedListener,
+ mCreateIfaceEventHandler, TEST_WORKSOURCE);
+ validateStartHal(hasStaIface || hasApIface || hasP2pIface || hasNanIface, true);
+ assertNotNull(mActiveNanIface);
+ assertEquals(mActiveNanIface.iface, mActiveWifiNanIface);
+ }
+
+ private void executeAndValidateTeardownNanInterface(
+ boolean anyOtherStaIface, boolean anyOtherApIface, boolean anyOtherP2pIface,
+ boolean anyOtherNanIface, WifiNative.Iface iface) throws Exception {
+ mWifiNative.teardownNanIface(iface.id);
+ validateOnDestroyedNanInterface(anyOtherStaIface, anyOtherApIface,
+ anyOtherP2pIface, anyOtherNanIface);
+ }
+
+ private void validateOnDestroyedNanInterface(
+ boolean anyOtherStaIface, boolean anyOtherApIface, boolean anyOtherP2pIface,
+ boolean anyOtherNanIface) throws Exception {
+ if (!anyOtherStaIface && !anyOtherApIface && !anyOtherP2pIface && !anyOtherNanIface) {
+ mInOrder.verify(mWificondControl).tearDownInterfaces();
+ mInOrder.verify(mWifiVendorHal).isVendorHalSupported();
+ mInOrder.verify(mWifiVendorHal).stopVendorHal();
+ }
+ }
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiNativeTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiNativeTest.java
index 492770024d..cff25254dd 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiNativeTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiNativeTest.java
@@ -1601,8 +1601,10 @@ public class WifiNativeTest extends WifiBaseTest {
@Test
public void testGetSupportedBandsFromHal() throws Exception {
List<WifiAvailableChannel> usableChannelList = new ArrayList<>();
- usableChannelList.add(new WifiAvailableChannel(2412, WifiAvailableChannel.OP_MODE_STA));
- usableChannelList.add(new WifiAvailableChannel(5160, WifiAvailableChannel.OP_MODE_STA));
+ usableChannelList.add(new WifiAvailableChannel(2412, WifiAvailableChannel.OP_MODE_STA,
+ ScanResult.CHANNEL_WIDTH_20MHZ));
+ usableChannelList.add(new WifiAvailableChannel(5160, WifiAvailableChannel.OP_MODE_STA,
+ ScanResult.CHANNEL_WIDTH_40MHZ));
when(mWifiVendorHal.getUsableChannels(WifiScanner.WIFI_BAND_24_5_WITH_DFS_6_60_GHZ,
WifiAvailableChannel.OP_MODE_STA,
WifiAvailableChannel.FILTER_REGULATORY)).thenReturn(usableChannelList);
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkFactoryTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkFactoryTest.java
index d2e20cdfc7..87dce767a5 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkFactoryTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkFactoryTest.java
@@ -843,7 +843,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
attachDefaultWifiNetworkSpecifierAndAppInfo(TEST_UID_1, false, new int[0], false);
mWifiNetworkFactory.needNetworkFor(mNetworkRequest);
- verifyPeriodicScans(0,
+ verifyPeriodicScans(false, 0,
PERIODIC_SCAN_INTERVAL_MS, // 10s
PERIODIC_SCAN_INTERVAL_MS, // 10s
PERIODIC_SCAN_INTERVAL_MS, // 10s
@@ -859,7 +859,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
attachDefaultWifiNetworkSpecifierAndAppInfo(TEST_UID_1, false, new int[0], false);
mWifiNetworkFactory.needNetworkFor(mNetworkRequest);
- verifyPeriodicScans(0,
+ verifyPeriodicScans(false, 0,
PERIODIC_SCAN_INTERVAL_MS, // 10s
PERIODIC_SCAN_INTERVAL_MS); // 10s
@@ -881,7 +881,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
verify(mNetworkRequestMatchCallback).onUserSelectionCallbackRegistration(
mNetworkRequestUserSelectionCallback.capture());
- verifyPeriodicScans(0,
+ verifyPeriodicScans(false, 0,
PERIODIC_SCAN_INTERVAL_MS, // 10s
PERIODIC_SCAN_INTERVAL_MS); // 10s
@@ -962,7 +962,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
@@ -1003,7 +1003,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
@@ -1044,7 +1044,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
@@ -1086,7 +1086,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
@@ -1128,7 +1128,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
@@ -1171,7 +1171,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
@@ -1216,7 +1216,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
// We expect no network match in this case.
verify(mNetworkRequestMatchCallback, never()).onMatch(any());
@@ -1254,7 +1254,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
// We expect no network match in this case.
verify(mNetworkRequestMatchCallback, never()).onMatch(any());
@@ -1374,7 +1374,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
verify(mNetworkRequestMatchCallback).onUserSelectionCallbackRegistration(
mNetworkRequestUserSelectionCallback.capture());
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
INetworkRequestUserSelectionCallback networkRequestUserSelectionCallback =
mNetworkRequestUserSelectionCallback.getValue();
@@ -1476,7 +1476,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
verify(mNetworkRequestMatchCallback).onUserSelectionCallbackRegistration(
mNetworkRequestUserSelectionCallback.capture());
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
// Now trigger user selection to the network.
mSelectedNetwork = ScanResultUtil.createNetworkFromScanResult(matchingScanResult);
@@ -1524,7 +1524,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
verify(mNetworkRequestMatchCallback).onUserSelectionCallbackRegistration(
mNetworkRequestUserSelectionCallback.capture());
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
// Scan result 2 has the highest RSSI, so that should be picked.
ScanResult matchingScanResult = mTestScanDatas[0].getResults()[2];
@@ -1587,7 +1587,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mNetworkRequestUserSelectionCallback.capture());
verifyPeriodicScans(
0L,
- new PeriodicScanParams(0, scanDatas1),
+ false, new PeriodicScanParams(0, scanDatas1),
new PeriodicScanParams(PERIODIC_SCAN_INTERVAL_MS, scanDatas2));
// Now trigger user selection to the network.
@@ -1654,7 +1654,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
scanDatas2[0].getResults()[3].timestamp = nowMs;
verifyPeriodicScans(
nowMs,
- new PeriodicScanParams(0, scanDatas1),
+ false, new PeriodicScanParams(0, scanDatas1),
new PeriodicScanParams(PERIODIC_SCAN_INTERVAL_MS, scanDatas2));
// Now trigger user selection to the network.
@@ -2949,7 +2949,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.needNetworkFor(mNetworkRequest);
when(mNetworkRequestMatchCallback.asBinder()).thenReturn(mAppBinder);
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
// Verify we triggered the match callback.
@@ -2992,7 +2992,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.needNetworkFor(mNetworkRequest);
when(mNetworkRequestMatchCallback.asBinder()).thenReturn(mAppBinder);
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
// Verify we triggered the match callback.
@@ -3033,7 +3033,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.needNetworkFor(mNetworkRequest);
when(mNetworkRequestMatchCallback.asBinder()).thenReturn(mAppBinder);
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
// Verify we triggered the match callback.
@@ -3086,7 +3086,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
// simulate scan results coming in and verify we auto connect to the network
when(mNetworkRequestMatchCallback.asBinder()).thenReturn(mAppBinder);
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
// Verify the match callback is not triggered since the UI is not started.
@@ -3152,7 +3152,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.needNetworkFor(mNetworkRequest);
when(mNetworkRequestMatchCallback.asBinder()).thenReturn(mAppBinder);
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
// Verify we triggered the match callback.
@@ -3196,7 +3196,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
mWifiNetworkFactory.needNetworkFor(mNetworkRequest);
when(mNetworkRequestMatchCallback.asBinder()).thenReturn(mAppBinder);
mWifiNetworkFactory.addCallback(mNetworkRequestMatchCallback);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
ArgumentCaptor<List<ScanResult>> matchedScanResultsCaptor =
ArgumentCaptor.forClass(List.class);
// Verify we triggered the match callback.
@@ -3218,7 +3218,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
sendNetworkRequestAndSetupForConnectionStatus(TEST_SSID_1);
// Verify config store interactions.
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
assertTrue(mDataSource.hasNewDataToSerialize());
Map<String, Set<AccessPoint>> approvedAccessPointsMapToWrite = mDataSource.toSerialize();
@@ -3371,27 +3371,27 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
* approved previously via CDM and the scan result is present in the cached scan results.
*/
private void
- testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchApprovedViaCDM()
+ testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchApprovedViaCDM(
+ boolean hasMatchResult)
throws Exception {
// Setup scan data for WPA-PSK networks.
- setupScanData(SCAN_RESULT_TYPE_WPA_PSK,
- TEST_SSID_1, TEST_SSID_2, TEST_SSID_3, TEST_SSID_4);
-
- // Choose the matching scan result.
- ScanResult matchingScanResult = mTestScanDatas[0].getResults()[0];
- when(mWifiScanner.getSingleScanResults())
- .thenReturn(Arrays.asList(mTestScanDatas[0].getResults()));
+ if (hasMatchResult) {
+ setupScanData(SCAN_RESULT_TYPE_WPA_PSK,
+ TEST_SSID_1, TEST_SSID_2, TEST_SSID_3, TEST_SSID_4);
+ when(mWifiScanner.getSingleScanResults())
+ .thenReturn(Arrays.asList(mTestScanDatas[0].getResults()));
+ }
// Setup CDM approval for the scan result.
when(mCompanionDeviceManager.isDeviceAssociatedForWifiConnection(
TEST_PACKAGE_NAME_1,
- MacAddress.fromString(matchingScanResult.BSSID),
+ MacAddress.fromString(TEST_BSSID_1),
UserHandle.getUserHandleForUid(TEST_UID_1))).thenReturn(true);
PatternMatcher ssidPatternMatch =
new PatternMatcher(TEST_SSID_1, PatternMatcher.PATTERN_LITERAL);
Pair<MacAddress, MacAddress> bssidPatternMatch =
- Pair.create(MacAddress.fromString(matchingScanResult.BSSID),
+ Pair.create(MacAddress.fromString(TEST_BSSID_1),
MacAddress.BROADCAST_ADDRESS);
attachWifiNetworkSpecifierAndAppInfo(
ssidPatternMatch, bssidPatternMatch,
@@ -3401,22 +3401,42 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
// Verify we did not trigger the UI for the second request.
verify(mContext, never()).startActivityAsUser(any(), any());
- // Verify we did not trigger a scan.
- verify(mWifiScanner, never()).startScan(any(), any(), any(), any());
- // Verify we did not trigger the match callback.
- verify(mNetworkRequestMatchCallback, never()).onMatch(anyList());
- // Verify that we sent a connection attempt to ClientModeManager
- verify(mConnectHelper).connectToNetwork(eq(mClientModeManager), any(),
- mConnectListenerArgumentCaptor.capture(), anyInt(), any(), any());
+ if (hasMatchResult) {
+ // Verify we did not trigger a scan.
+ verify(mWifiScanner, never()).startScan(any(), any(), any(), any());
+ // Verify we did not trigger the match callback.
+ verify(mNetworkRequestMatchCallback, never()).onMatch(anyList());
+ // Verify that we sent a connection attempt to ClientModeManager
+ verify(mConnectHelper).connectToNetwork(eq(mClientModeManager), any(),
+ mConnectListenerArgumentCaptor.capture(), anyInt(), any(), any());
- verify(mWifiMetrics).incrementNetworkRequestApiNumUserApprovalBypass();
+ verify(mWifiMetrics).incrementNetworkRequestApiNumUserApprovalBypass();
+ } else {
+ verifyPeriodicScans(true, 0,
+ PERIODIC_SCAN_INTERVAL_MS,
+ PERIODIC_SCAN_INTERVAL_MS,
+ PERIODIC_SCAN_INTERVAL_MS);
+ verify(mConnectHelper, never()).connectToNetwork(any(), any(),
+ mConnectListenerArgumentCaptor.capture(), anyInt(), any(), any());
+
+ verify(mWifiMetrics, never()).incrementNetworkRequestApiNumUserApprovalBypass();
+ mLooper.dispatchAll();
+ verify(mConnectivityManager).declareNetworkRequestUnfulfillable(eq(mNetworkRequest));
+ }
}
@Test
public void
testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchApprovedViaCDMNoStaSta()
throws Exception {
- testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchApprovedViaCDM();
+ testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchApprovedViaCDM(true);
+ }
+
+ @Test
+ public void
+ testNetworkSpecifierNoMatchUsingLiteralSsidAndBssidMatchApprovedViaCDMNoStaSta()
+ throws Exception {
+ testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchApprovedViaCDM(false);
}
@Test
@@ -3426,7 +3446,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
when(mResources.getBoolean(
eq(R.bool.config_wifiMultiStaLocalOnlyConcurrencyEnabled)))
.thenReturn(true);
- testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchApprovedViaCDM();
+ testNetworkSpecifierMatchSuccessUsingLiteralSsidAndBssidMatchApprovedViaCDM(true);
}
/**
@@ -3500,7 +3520,7 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
validateUiStartParams(true);
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
// Ensure we did not send any match callbacks, until the callback is registered
verify(mNetworkRequestMatchCallback, never()).onMatch(any());
@@ -3816,19 +3836,20 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
verify(mNetworkRequestMatchCallback).onUserSelectionCallbackRegistration(
mNetworkRequestUserSelectionCallback.capture());
- verifyPeriodicScans(0, PERIODIC_SCAN_INTERVAL_MS);
+ verifyPeriodicScans(false, 0, PERIODIC_SCAN_INTERVAL_MS);
verify(mNetworkRequestMatchCallback, atLeastOnce()).onMatch(anyList());
}
- private void verifyPeriodicScans(long...expectedIntervalsInSeconds) {
+ private void verifyPeriodicScans(boolean stopAtLastSchedule,
+ long...expectedIntervalsInSeconds) {
PeriodicScanParams[] periodicScanParams =
new PeriodicScanParams[expectedIntervalsInSeconds.length];
for (int i = 0; i < expectedIntervalsInSeconds.length; i++) {
periodicScanParams[i] =
new PeriodicScanParams(expectedIntervalsInSeconds[i], mTestScanDatas);
}
- verifyPeriodicScans(0L, periodicScanParams);
+ verifyPeriodicScans(0L, stopAtLastSchedule, periodicScanParams);
}
private static class PeriodicScanParams {
@@ -3846,7 +3867,8 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
// b) Scan results received.
// c) Set alarm for next scan at the expected interval.
// d) Alarm fires, go to step a) again and repeat.
- private void verifyPeriodicScans(long nowMs, PeriodicScanParams... scanParams) {
+ private void verifyPeriodicScans(long nowMs, boolean stopAtLastSchedule,
+ PeriodicScanParams... scanParams) {
when(mClock.getElapsedSinceBootMillis()).thenReturn(nowMs);
OnAlarmListener alarmListener = null;
@@ -3874,6 +3896,9 @@ public class WifiNetworkFactoryTest extends WifiBaseTest {
// Now trigger the scan results callback and verify the alarm set for the next scan.
scanListener.onResults(scanParams[i].scanDatas);
+ if (stopAtLastSchedule && i == scanParams.length - 2) {
+ break;
+ }
mInOrder.verify(mAlarmManager).set(eq(AlarmManager.ELAPSED_REALTIME_WAKEUP),
eq(expectedNextIntervalInMs + nowMs), any(),
mPeriodicScanListenerArgumentCaptor.capture(), any());
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkSelectorTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkSelectorTest.java
index c28c6ba4b9..d5e102383b 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkSelectorTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkSelectorTest.java
@@ -19,6 +19,8 @@ package com.android.server.wifi;
import static android.net.wifi.WifiManager.WIFI_FEATURE_OWE;
import static android.net.wifi.WifiManager.WIFI_FEATURE_WPA3_SAE;
+import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_PRIMARY;
+import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_SECONDARY_LONG_LIVED;
import static com.android.server.wifi.WifiConfigurationTestUtil.SECURITY_EAP;
import static com.android.server.wifi.WifiConfigurationTestUtil.SECURITY_NONE;
import static com.android.server.wifi.WifiConfigurationTestUtil.SECURITY_OWE;
@@ -552,7 +554,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals("Expect null configuration", null, candidate);
@@ -586,12 +588,12 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals("Expect null configuration", null, candidate);
assertTrue(mWifiNetworkSelector.getConnectableScanDetails().isEmpty());
- verify(mPasspointNetworkNominateHelper).updatePasspointConfig(any());
+ verify(mPasspointNetworkNominateHelper, never()).updatePasspointConfig(any());
verify(mPasspointNetworkNominateHelper, never()).getPasspointNetworkCandidates(any());
}
@@ -623,9 +625,10 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
+ assertNotNull(candidate);
when(mClock.getElapsedSinceBootMillis()).thenReturn(SystemClock.elapsedRealtime()
+ WifiNetworkSelector.MINIMUM_NETWORK_SELECTION_INTERVAL_MS - 2000);
@@ -634,16 +637,16 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, true, false, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
candidate = mWifiNetworkSelector.selectNetwork(candidates);
- assertEquals("Expect null configuration", null, candidate);
+ assertNull("Expect null configuration", candidate);
assertTrue(mWifiNetworkSelector.getConnectableScanDetails().isEmpty());
verify(mWifiConfigManager, atLeast(2))
.updateScanDetailCacheFromScanDetailForSavedNetwork(any());
- verify(mPasspointNetworkNominateHelper, times(2)).updatePasspointConfig(any());
+ verify(mPasspointNetworkNominateHelper).updatePasspointConfig(any());
verify(mPasspointNetworkNominateHelper).getPasspointNetworkCandidates(any());
}
@@ -676,7 +679,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
WifiConfigurationTestUtil.assertConfigurationEqual(savedConfigs[0], candidate);
@@ -688,7 +691,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -728,7 +731,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
when(mWifiInfo.getSupplicantState()).thenReturn(SupplicantState.COMPLETED);
@@ -746,7 +749,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, true, false, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -788,7 +791,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
when(mWifiInfo.getSupplicantState()).thenReturn(SupplicantState.COMPLETED);
@@ -814,7 +817,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, true, false, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -850,7 +853,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
verify(mWifiMetrics).incrementNetworkSelectionFilteredBssidCount(0);
@@ -891,7 +894,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
verify(mWifiMetrics).incrementNetworkSelectionFilteredBssidCount(1);
@@ -931,7 +934,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals("Expect null configuration", null, candidate);
@@ -969,7 +972,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals("Expect null configuration", null, candidate);
@@ -1009,7 +1012,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals("Expect null configuration", null, candidate);
@@ -1052,7 +1055,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals("Expect null configuration", null, candidate);
@@ -1101,7 +1104,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
}
@@ -1135,7 +1138,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals("Expect null configuration", null, candidate);
@@ -1170,7 +1173,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals("Expect null configuration", null, candidate);
@@ -1205,7 +1208,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals(ssids[0], candidate.SSID);
@@ -1239,7 +1242,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -1265,7 +1268,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, true, false, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -1304,7 +1307,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -1335,7 +1338,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, true, false, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
assertEquals(2, candidates.size());
assertEquals(100, candidates.get(0).getPredictedThroughputMbps());
@@ -1375,7 +1378,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -1401,7 +1404,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -1454,7 +1457,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
WifiConfigurationTestUtil.assertConfigurationEqual(userChoice, candidate);
@@ -1469,7 +1472,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
candidate = mWifiNetworkSelector.selectNetwork(candidates);
WifiConfigurationTestUtil.assertConfigurationEqual(networkSelectorChoice, candidate);
@@ -1510,7 +1513,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
WifiConfigurationTestUtil.assertConfigurationEqual(userChoice, candidate);
@@ -1523,7 +1526,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -1565,7 +1568,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
WifiConfigurationTestUtil.assertConfigurationEqual(userChoice, candidate);
@@ -1576,7 +1579,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
candidate = mWifiNetworkSelector.selectNetwork(candidates);
WifiConfigurationTestUtil.assertConfigurationEqual(networkSelectorChoice, candidate);
@@ -1611,7 +1614,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
assertFalse(candidates.isEmpty());
@@ -1628,7 +1631,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
assertFalse(candidates.isEmpty());
@@ -1678,7 +1681,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -1894,7 +1897,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
//WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals(1, candidates.size());
@@ -1906,7 +1909,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
//WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals(1, candidates.size());
@@ -2022,7 +2025,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
true, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertNotNull("Result should be not null", candidate);
@@ -2064,7 +2067,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, true, false, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
true, true, true, Collections.emptySet(), false);
candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -2102,7 +2105,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
List<ScanDetail> expectedOpenUnsavedNetworks = new ArrayList<>();
@@ -2137,7 +2140,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
unSavedScanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertEquals("Expect open unsaved networks",
@@ -2152,7 +2155,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
candidates = mWifiNetworkSelector.getCandidatesFromScan(
savedScanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
candidate = mWifiNetworkSelector.selectNetwork(candidates);
// Saved networks are filtered out.
@@ -2182,7 +2185,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
List<ScanDetail> expectedOpenUnsavedNetworks = new ArrayList<>();
@@ -2214,7 +2217,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
assertTrue(mWifiNetworkSelector.getFilteredScanDetailsForOpenUnsavedNetworks().isEmpty());
@@ -2256,7 +2259,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
List<ScanDetail> expectedOpenUnsavedNetworks = new ArrayList<>();
@@ -2292,7 +2295,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
List<ScanDetail> expectedOpenUnsavedNetworks = new ArrayList<>();
@@ -2323,7 +2326,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
setUpTwoNetworks(-35, -40),
EMPTY_BLOCKLIST,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
true, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -2461,7 +2464,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
true, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
// Check if the wifiConfig is updated with the latest
@@ -2492,7 +2495,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
// Expect one privileged and one regular candidate.
assertEquals(2, candidates.size());
@@ -2542,7 +2545,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
verify(mWifiMetrics, times(1))
@@ -2666,10 +2669,10 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(
- TEST_IFACE_NAME, true, false, mWifiInfo, false),
+ TEST_IFACE_NAME, true, false, mWifiInfo, false, ROLE_CLIENT_PRIMARY),
new ClientModeManagerState(
TEST_IFACE_NAME_SECONDARY, true, false, mSecondaryWifiInfo,
- false)),
+ false, ROLE_CLIENT_SECONDARY_LONG_LIVED)),
false, true, true, Collections.emptySet(), false);
WifiConfiguration candidate = mWifiNetworkSelector.selectNetwork(candidates);
@@ -2730,16 +2733,40 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
when(mClock.getElapsedSinceBootMillis()).thenReturn(SystemClock.elapsedRealtime()
+ WifiNetworkSelector.MINIMUM_NETWORK_SELECTION_INTERVAL_MS + 2000);
- // Do network selection.
- List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
- scanDetails, blocklist,
+ List<ClientModeManagerState> cmmStates =
Arrays.asList(new ClientModeManagerState(
- TEST_IFACE_NAME, true, false, mWifiInfo, false),
+ TEST_IFACE_NAME, true, false, mWifiInfo, false, ROLE_CLIENT_PRIMARY),
new ClientModeManagerState(
- TEST_IFACE_NAME_SECONDARY, true, false, mSecondaryWifiInfo,
- false)),
- false, true, true, Collections.emptySet(), false);
- assertNull(mWifiNetworkSelector.selectNetwork(candidates));
+ TEST_IFACE_NAME_SECONDARY, true, false, mSecondaryWifiInfo, false,
+ ROLE_CLIENT_SECONDARY_LONG_LIVED));
+
+ // Do network selection.
+ List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
+ scanDetails, blocklist, cmmStates, false, true, true, Collections.emptySet(),
+ false);
+ assertNull(candidates);
+
+ // Mock that the primary connection has a user connect choice pointing something
+ // Verify candidate return is not null in this case
+ WifiConfiguration primaryConfig = mock(WifiConfiguration.class);
+ WifiConfiguration.NetworkSelectionStatus networkSelectionStatus = mock(
+ WifiConfiguration.NetworkSelectionStatus.class);
+ when(networkSelectionStatus.getConnectChoice()).thenReturn("\"ConnectChoiceTest\"NONE");
+ when(primaryConfig.getNetworkSelectionStatus()).thenReturn(networkSelectionStatus);
+ when(mWifiConfigManager.getConfiguredNetwork(mWifiInfo.getNetworkId())).thenReturn(
+ primaryConfig);
+ candidates = mWifiNetworkSelector.getCandidatesFromScan(
+ scanDetails, blocklist, cmmStates, false, true, true, Collections.emptySet(),
+ false);
+ // Candidate should not be null
+ assertNotNull(candidates);
+
+ // disable associated network selection and verify no candidate is returned now
+ doReturn(false).when(mResource).getBoolean(
+ R.bool.config_wifi_framework_enable_associated_network_selection);
+ assertNull(mWifiNetworkSelector.getCandidatesFromScan(
+ scanDetails, blocklist, cmmStates, false, true, true, Collections.emptySet(),
+ false));
}
private void runNetworkSelectionWith(ScanDetailsAndWifiConfigs scanDetailsAndConfigs) {
@@ -2747,7 +2774,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
scanDetailsAndConfigs.getScanDetails(),
new HashSet<>(), // blocklist
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
true, // untrustedNetworkAllowed
true, // oemPaid
true, // oemPrivate
@@ -2806,7 +2833,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, new HashSet<>(),
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
assertEquals(2, candidates.size());
@@ -2862,7 +2889,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, new HashSet<>(),
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
// PSK type is disabled, PSK network is not matched.
assertEquals(1, candidates.size());
@@ -2896,7 +2923,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, new HashSet<>(),
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
assertEquals(2, candidates.size());
@@ -2929,7 +2956,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, new HashSet<>(),
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
// The SAE-only network should be filtered.
assertEquals(1, candidates.size());
@@ -2964,7 +2991,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, new HashSet<>(),
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
assertEquals(2, candidates.size());
@@ -3008,7 +3035,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, new HashSet<>(),
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
// OPEN type is disabled, OPEN network is not matched.
assertEquals(1, candidates.size());
@@ -3041,7 +3068,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, new HashSet<>(),
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
assertEquals(2, candidates.size());
@@ -3074,7 +3101,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, new HashSet<>(),
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
// The OWE-only network should be filtered.
assertEquals(1, candidates.size());
@@ -3107,7 +3134,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, new HashSet<>(),
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
assertEquals(2, candidates.size());
@@ -3151,7 +3178,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, new HashSet<>(),
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
// WPA2 Enterprise type is disabled, WPA2 Enterprise network is not matched.
assertEquals(1, candidates.size());
@@ -3223,7 +3250,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
assertNotNull(candidates);
if (expectedSecurityParamType == -1) {
@@ -3262,7 +3289,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, new HashSet<>(),
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
assertEquals(2, candidates.size());
@@ -3370,7 +3397,7 @@ public class WifiNetworkSelectorTest extends WifiBaseTest {
List<WifiCandidates.Candidate> candidates = mWifiNetworkSelector.getCandidatesFromScan(
scanDetails, blocklist,
Arrays.asList(new ClientModeManagerState(TEST_IFACE_NAME, false, true, mWifiInfo,
- false)),
+ false, ROLE_CLIENT_PRIMARY)),
false, true, true, Collections.emptySet(), false);
return candidates;
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkSuggestionsManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkSuggestionsManagerTest.java
index 6a9d78c44e..131f7de508 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkSuggestionsManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiNetworkSuggestionsManagerTest.java
@@ -21,6 +21,7 @@ import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREG
import static android.app.AppOpsManager.MODE_ALLOWED;
import static android.app.AppOpsManager.MODE_IGNORED;
import static android.app.AppOpsManager.OPSTR_CHANGE_WIFI_STATE;
+import static android.net.wifi.WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT;
import static android.net.wifi.WifiManager.ACTION_REMOVE_SUGGESTION_LINGER;
import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn;
@@ -34,6 +35,7 @@ import static com.android.server.wifi.WifiNetworkSuggestionsManager.NOTIFICATION
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeFalse;
import static org.junit.Assume.assumeTrue;
@@ -420,10 +422,10 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// Now remove all of them.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList1, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList2, TEST_UID_2,
- TEST_PACKAGE_2, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_2, ACTION_REMOVE_SUGGESTION_DISCONNECT));
verify(mPasspointManager).removeProvider(eq(TEST_UID_2), eq(false),
eq(passpointConfiguration.getUniqueId()), isNull());
verify(mWifiScoreCard).removeNetwork(anyString());
@@ -459,7 +461,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
TEST_PACKAGE_1, TEST_FEATURE));
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
}
@Test
@@ -493,7 +495,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
mWifiNetworkSuggestionsManager.remove(
List.of(removingSuggestion),
TEST_UID_1, TEST_PACKAGE_1,
- WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ ACTION_REMOVE_SUGGESTION_DISCONNECT));
// Make sure remove the keyStore with the internal config
verify(mWifiKeyStore).removeKeys(eq(networkSuggestion1.wifiConfiguration.enterpriseConfig),
eq(false));
@@ -658,11 +660,11 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// Now remove all of them by sending an empty list.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(new ArrayList<>(), TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
verify(mLruConnectionTracker).removeNetwork(any());
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(new ArrayList<>(), TEST_UID_2,
- TEST_PACKAGE_2, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_2, ACTION_REMOVE_SUGGESTION_DISCONNECT));
verify(mPasspointManager).removeProvider(eq(TEST_UID_2), eq(false),
eq(passpointConfiguration.getUniqueId()), isNull());
@@ -686,7 +688,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
TEST_PACKAGE_1, TEST_FEATURE));
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList1, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.add(networkSuggestionList1, TEST_UID_1,
TEST_PACKAGE_1, TEST_FEATURE));
@@ -884,7 +886,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// The remove should succeed.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
// Now add 2 more.
networkSuggestionList = new ArrayList<>();
@@ -938,7 +940,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// Remove should fail because the network list is different.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList2, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
}
/**
@@ -986,7 +988,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
TEST_UID_1, TEST_PACKAGE_1, TEST_FEATURE));
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID,
mWifiNetworkSuggestionsManager.remove(Collections.singletonList(null), TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
}
/**
@@ -1296,7 +1298,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// remove the suggestion & ensure lookup fails.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(List.of(), TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
assertTrue(mWifiNetworkSuggestionsManager
.getNetworkSuggestionsForScanDetail(scanDetail).isEmpty());
}
@@ -1404,7 +1406,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
verify(mWifiConfigManager).removeSuggestionConfiguredNetwork(
argThat(new WifiConfigMatcher(networkSuggestion.wifiConfiguration)));
mInorder.verify(mWifiPermissionsUtil)
@@ -1865,7 +1867,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
TEST_PACKAGE_1, TEST_FEATURE));
// Verify config store interactions.
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
assertTrue(mDataSource.hasNewDataToSerialize());
Map<String, PerAppInfo> networkSuggestionsMapToWrite = mDataSource.toSerialize();
@@ -1893,7 +1895,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
*/
@Test
public void testAddNetworkSuggestionsConfigStoreWriteFailedByOOM() {
- when(mWifiConfigManager.saveToStore(anyBoolean())).thenThrow(new OutOfMemoryError())
+ when(mWifiConfigManager.saveToStore()).thenThrow(new OutOfMemoryError())
.thenReturn(true);
WifiNetworkSuggestion networkSuggestion = createWifiNetworkSuggestion(
WifiConfigurationTestUtil.createOpenNetwork(), null, false, false, true, true,
@@ -1906,7 +1908,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
TEST_PACKAGE_1, TEST_FEATURE));
// Verify config store interactions.
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
assertTrue(mDataSource.hasNewDataToSerialize());
Map<String, PerAppInfo> networkSuggestionsMapToWrite = mDataSource.toSerialize();
@@ -1934,10 +1936,10 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
TEST_PACKAGE_1, TEST_FEATURE));
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
// Verify config store interactions.
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
assertTrue(mDataSource.hasNewDataToSerialize());
// Expect a single app entry with no active suggestions.
@@ -2126,7 +2128,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// Now remove the network suggestion and ensure we did trigger a disconnect.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
verify(mWifiConfigManager).removeSuggestionConfiguredNetwork(
argThat(new WifiConfigMatcher(connectNetwork)));
}
@@ -2161,7 +2163,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// Now remove all network suggestion and ensure we did trigger a disconnect.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(new ArrayList<>(), TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
verify(mWifiConfigManager).removeSuggestionConfiguredNetwork(
argThat(new WifiConfigMatcher(connectNetwork)));
}
@@ -2250,11 +2252,11 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// Now remove first add, nothing happens.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList1, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
// Stop watching app-ops changes on last remove.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList2, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
assertTrue(mWifiNetworkSuggestionsManager.getAllNetworkSuggestions().isEmpty());
verify(mAppOpsManager, never()).stopWatchingMode(mAppOpChangedListenerCaptor.getValue());
@@ -2413,10 +2415,10 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// Remove all suggestions from TEST_PACKAGE_1 & TEST_PACKAGE_2, we should continue to track.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList1, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList2, TEST_UID_2,
- TEST_PACKAGE_2, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_2, ACTION_REMOVE_SUGGESTION_DISCONNECT));
assertTrue(mDataSource.hasNewDataToSerialize());
Map<String, PerAppInfo> networkSuggestionsMapToWrite = mDataSource.toSerialize();
@@ -2475,10 +2477,10 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// Remove all suggestions from TEST_PACKAGE_1 & TEST_PACKAGE_2, we should continue to track.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList1, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList2, TEST_UID_2,
- TEST_PACKAGE_2, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_2, ACTION_REMOVE_SUGGESTION_DISCONNECT));
assertTrue(mDataSource.hasNewDataToSerialize());
Map<String, PerAppInfo> networkSuggestionsMapToWrite = mDataSource.toSerialize();
@@ -2582,7 +2584,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_NETWORK_SUGGESTION_AVAILABLE);
// Verify config store interactions.
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
assertTrue(mDataSource.hasNewDataToSerialize());
verify(mWifiMetrics).addUserApprovalSuggestionAppUiReaction(
WifiNetworkSuggestionsManager.ACTION_USER_ALLOWED_APP, false);
@@ -2642,7 +2644,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_NETWORK_SUGGESTION_AVAILABLE);
// Verify config store interactions.
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
assertTrue(mDataSource.hasNewDataToSerialize());
verify(mWifiMetrics).addUserApprovalSuggestionAppUiReaction(
WifiNetworkSuggestionsManager.ACTION_USER_DISALLOWED_APP, false);
@@ -2745,7 +2747,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// App remove all network suggestions, expect empty list.
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(new ArrayList<>(), TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
storedNetworkSuggestionListPerApp =
mWifiNetworkSuggestionsManager.get(TEST_PACKAGE_1, TEST_UID_1);
assertEquals(storedNetworkSuggestionListPerApp.size(), 0);
@@ -2823,7 +2825,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
dialogCallbackCaptor.getValue().onPositiveButtonClicked();
// Verify config store interactions.
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
assertTrue(mDataSource.hasNewDataToSerialize());
verify(mWifiMetrics).addUserApprovalSuggestionAppUiReaction(
WifiNetworkSuggestionsManager.ACTION_USER_ALLOWED_APP, true);
@@ -2866,7 +2868,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
OPSTR_CHANGE_WIFI_STATE, TEST_UID_1, TEST_PACKAGE_1, MODE_IGNORED);
// Verify config store interactions.
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
assertTrue(mDataSource.hasNewDataToSerialize());
verify(mWifiMetrics).addUserApprovalSuggestionAppUiReaction(
WifiNetworkSuggestionsManager.ACTION_USER_DISALLOWED_APP, true);
@@ -2923,7 +2925,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
mLooper.dispatchAll();
// Verify no new config store or app-op interactions.
- verify(mWifiConfigManager).saveToStore(true); // 1 already done for add
+ verify(mWifiConfigManager).saveToStore(); // 1 already done for add
verify(mAppOpsManager, never()).setMode(any(), anyInt(), any(), anyInt());
verify(mWifiMetrics).addUserApprovalSuggestionAppUiReaction(
WifiNetworkSuggestionsManager.ACTION_USER_DISMISS, true);
@@ -2957,7 +2959,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_NETWORK_SUGGESTION_AVAILABLE);
// Verify config store interactions.
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
assertTrue(mDataSource.hasNewDataToSerialize());
reset(mWifiNotificationManager);
@@ -2995,7 +2997,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
verify(mWifiNotificationManager).cancel(SystemMessage.NOTE_NETWORK_SUGGESTION_AVAILABLE);
// Verify config store interactions.
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
assertTrue(mDataSource.hasNewDataToSerialize());
reset(mWifiNotificationManager);
@@ -3534,7 +3536,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
DEFAULT_PRIORITY_GROUP);
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(List.of(suggestionToRemove), TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
}
/**
@@ -3624,7 +3626,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
.thenReturn(TelephonyManager.UNKNOWN_CARRIER_ID);
mWifiNetworkSuggestionsManager.updateCarrierPrivilegedApps();
assertEquals(0, mWifiNetworkSuggestionsManager.get(TEST_PACKAGE_1, TEST_UID_1).size());
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
status = mWifiNetworkSuggestionsManager
.add(networkSuggestionList, TEST_UID_1, TEST_PACKAGE_1, TEST_FEATURE);
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_NOT_ALLOWED, status);
@@ -3666,7 +3668,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
.thenReturn(TelephonyManager.UNKNOWN_CARRIER_ID);
mWifiNetworkSuggestionsManager.updateCarrierPrivilegedApps(Collections.emptySet());
assertEquals(0, mWifiNetworkSuggestionsManager.get(TEST_PACKAGE_1, TEST_UID_1).size());
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
status = mWifiNetworkSuggestionsManager
.add(networkSuggestionList, TEST_UID_1, TEST_PACKAGE_1, TEST_FEATURE);
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_NOT_ALLOWED, status);
@@ -3700,17 +3702,17 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// No matching will return false.
assertFalse(mWifiNetworkSuggestionsManager
.allowNetworkSuggestionAutojoin(configuration, false));
- verify(mWifiConfigManager, never()).saveToStore(true);
+ verify(mWifiConfigManager, never()).saveToStore();
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.add(networkSuggestionList, TEST_UID_1,
TEST_PACKAGE_1, TEST_FEATURE));
mWifiNetworkSuggestionsManager.setHasUserApprovedForApp(true, TEST_UID_1, TEST_PACKAGE_1);
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
reset(mWifiConfigManager);
assertTrue(mWifiNetworkSuggestionsManager
.allowNetworkSuggestionAutojoin(configuration, false));
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
Set<ExtendedWifiNetworkSuggestion> matchedSuggestions = mWifiNetworkSuggestionsManager
.getNetworkSuggestionsForWifiConfiguration(configuration,
TEST_BSSID);
@@ -3739,7 +3741,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
mWifiNetworkSuggestionsManager.add(networkSuggestionList, TEST_UID_1,
TEST_PACKAGE_1, TEST_FEATURE));
mWifiNetworkSuggestionsManager.setHasUserApprovedForApp(true, TEST_UID_1, TEST_PACKAGE_1);
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
reset(mWifiConfigManager);
// Create WifiConfiguration for Passpoint network.
WifiConfiguration config = WifiConfigurationTestUtil.createPasspointNetwork();
@@ -3756,14 +3758,14 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
.thenReturn(false);
assertFalse(mWifiNetworkSuggestionsManager
.allowNetworkSuggestionAutojoin(config, false));
- verify(mWifiConfigManager, never()).saveToStore(true);
+ verify(mWifiConfigManager, never()).saveToStore();
// When update PasspointManager is success, will return true and persist suggestion.
when(mPasspointManager.enableAutojoin(anyString(), isNull(), anyBoolean()))
.thenReturn(true);
assertTrue(mWifiNetworkSuggestionsManager
.allowNetworkSuggestionAutojoin(config, false));
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
Set<ExtendedWifiNetworkSuggestion> matchedSuggestions = mWifiNetworkSuggestionsManager
.getNetworkSuggestionsForWifiConfiguration(config, TEST_BSSID);
for (ExtendedWifiNetworkSuggestion ewns : matchedSuggestions) {
@@ -3998,7 +4000,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
for (ExtendedWifiNetworkSuggestion ewns : matchedSuggestions) {
assertTrue(ewns.isAutojoinEnabled);
}
- verify(mWifiConfigManager, atLeastOnce()).saveToStore(true);
+ verify(mWifiConfigManager, atLeastOnce()).saveToStore();
}
@Test
@@ -4237,7 +4239,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(networkSuggestionList1, TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
verify(listener).onSuggestionsRemoved(networkSuggestionList1);
}
@@ -4638,7 +4640,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
TEST_PACKAGE_1, TEST_FEATURE));
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL,
mWifiNetworkSuggestionsManager.remove(Arrays.asList(networkSuggestion), TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
assertTrue(mWifiNetworkSuggestionsManager.get(TEST_PACKAGE_1, TEST_UID_1).isEmpty());
assertFalse(mWifiNetworkSuggestionsManager.registerSuggestionConnectionStatusListener(
mConnectionStatusListener, TEST_PACKAGE_1, TEST_UID_1));
@@ -4652,7 +4654,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
assertFalse(mWifiNetworkSuggestionsManager.get(TEST_PACKAGE_1, TEST_UID_1).isEmpty());
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(Arrays.asList(networkSuggestion), TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
assertTrue(mWifiNetworkSuggestionsManager.registerSuggestionConnectionStatusListener(
mConnectionStatusListener, TEST_PACKAGE_1, TEST_UID_1));
}
@@ -4693,7 +4695,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
mWifiNetworkSuggestionsManager.remove(Arrays.asList(networkSuggestion), TEST_UID_1,
- TEST_PACKAGE_1, WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
verify(mWifiConfigManager).removeSuggestionConfiguredNetwork(
argThat(new WifiConfigMatcher(connectNetwork)));
mInorder.verify(mWifiPermissionsUtil).doesUidBelongToCurrentUserOrDeviceOwner(anyInt());
@@ -4720,6 +4722,7 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
.thenReturn(true);
WifiConfiguration eapSimConfig = WifiConfigurationTestUtil.createWpa2Wpa3EnterpriseNetwork(
WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
+ eapSimConfig.enterpriseConfig.setAnonymousIdentity(TEST_ANONYMOUS_IDENTITY);
WifiNetworkSuggestion networkSuggestion = createWifiNetworkSuggestion(
new WifiConfiguration(eapSimConfig), null, false, false, true, true,
DEFAULT_PRIORITY_GROUP);
@@ -4737,14 +4740,25 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
configuration.creatorUid = TEST_UID_1;
configuration.enterpriseConfig.setAnonymousIdentity(TEST_ANONYMOUS_IDENTITY);
+ Set<ExtendedWifiNetworkSuggestion> matchedSuggestions = mWifiNetworkSuggestionsManager
+ .getNetworkSuggestionsForWifiConfiguration(configuration,
+ TEST_BSSID);
+ for (ExtendedWifiNetworkSuggestion ewns : matchedSuggestions) {
+ assertNull(ewns.anonymousIdentity);
+ assertEquals(TEST_ANONYMOUS_IDENTITY,
+ ewns.createInternalWifiConfiguration(mWifiCarrierInfoManager)
+ .enterpriseConfig.getAnonymousIdentity());
+ }
+
mWifiNetworkSuggestionsManager.setAnonymousIdentity(configuration);
- Set<ExtendedWifiNetworkSuggestion> matchedSuggestions = mWifiNetworkSuggestionsManager
+ matchedSuggestions = mWifiNetworkSuggestionsManager
.getNetworkSuggestionsForWifiConfiguration(configuration,
TEST_BSSID);
for (ExtendedWifiNetworkSuggestion ewns : matchedSuggestions) {
assertEquals(TEST_ANONYMOUS_IDENTITY, ewns.anonymousIdentity);
}
+
// Reset SIM network suggestion, Anonymous Identity should gone.
mWifiNetworkSuggestionsManager.resetSimNetworkSuggestions();
matchedSuggestions = mWifiNetworkSuggestionsManager
@@ -4752,8 +4766,11 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
TEST_BSSID);
for (ExtendedWifiNetworkSuggestion ewns : matchedSuggestions) {
assertEquals(null, ewns.anonymousIdentity);
+ assertEquals(TEST_ANONYMOUS_IDENTITY,
+ ewns.createInternalWifiConfiguration(mWifiCarrierInfoManager)
+ .enterpriseConfig.getAnonymousIdentity());
}
- verify(mWifiConfigManager, times(3)).saveToStore(true);
+ verify(mWifiConfigManager, times(3)).saveToStore();
}
@Test
@@ -4797,12 +4814,12 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
}
// Add suggestion and change user approval have 2, set and remove user choice have 2.
- verify(mWifiConfigManager, times(4)).saveToStore(true);
+ verify(mWifiConfigManager, times(4)).saveToStore();
reset(mWifiConfigManager);
listener.onConnectChoiceRemoved(USER_CONNECT_CHOICE);
listener.onConnectChoiceRemoved(null);
- verify(mWifiConfigManager, never()).saveToStore(anyBoolean());
+ verify(mWifiConfigManager, never()).saveToStore();
}
/**
@@ -5198,4 +5215,15 @@ public class WifiNetworkSuggestionsManagerTest extends WifiBaseTest {
// Verify no more broadcast were sent out.
mInorder.verifyNoMoreInteractions();
}
+
+ @Test
+ public void testHandleShutDown() {
+ mWifiNetworkSuggestionsManager.handleShutDown();
+ assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL,
+ mWifiNetworkSuggestionsManager.add(Collections.emptyList(), TEST_UID_1,
+ TEST_PACKAGE_1, TEST_FEATURE));
+ assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL,
+ mWifiNetworkSuggestionsManager.remove(Collections.emptyList(), TEST_UID_1,
+ TEST_PACKAGE_1, ACTION_REMOVE_SUGGESTION_DISCONNECT));
+ }
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiRoamingConfigStoreTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiRoamingConfigStoreTest.java
index e59bd4c37a..bba85549bc 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiRoamingConfigStoreTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiRoamingConfigStoreTest.java
@@ -90,7 +90,7 @@ public class WifiRoamingConfigStoreTest extends WifiBaseTest {
assertTrue(mWifiRoamingConfigStore.getRoamingMode(TEST_SSID) == TEST_DEFAULT_ROAMING_MODE);
assertTrue(mWifiRoamingConfigStore.getPerSsidRoamingModes(true).isEmpty());
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
}
@Test
@@ -107,7 +107,7 @@ public class WifiRoamingConfigStoreTest extends WifiBaseTest {
assertTrue(mWifiRoamingConfigStore.getRoamingMode(TEST_SSID) == TEST_DEFAULT_ROAMING_MODE);
assertTrue(mWifiRoamingConfigStore.getPerSsidRoamingModes(false).isEmpty());
- verify(mWifiConfigManager, times(2)).saveToStore(true);
+ verify(mWifiConfigManager, times(2)).saveToStore();
}
@Test
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiScoreReportTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiScoreReportTest.java
index c974d69de5..4f5aaf7e21 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiScoreReportTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiScoreReportTest.java
@@ -1198,6 +1198,11 @@ public class WifiScoreReportTest extends WifiBaseTest {
verify(mExternalScoreUpdateObserverProxy).registerCallback(
mExternalScoreUpdateObserverCbCaptor.capture());
when(mNetwork.getNetId()).thenReturn(TEST_NETWORK_ID);
+
+ WifiSignalPollResults signalPollResults = new WifiSignalPollResults();
+ signalPollResults.addEntry(0, -42, 65, 54, 2437);
+ when(mWifiNative.signalPoll(TEST_IFACE_NAME)).thenReturn(signalPollResults);
+
mWifiScoreReport.startConnectedNetworkScorer(TEST_NETWORK_ID, TEST_USER_SELECTED);
mExternalScoreUpdateObserverCbCaptor.getValue().triggerUpdateOfWifiUsabilityStats(
@@ -1205,6 +1210,21 @@ public class WifiScoreReportTest extends WifiBaseTest {
mLooper.dispatchAll();
verify(mWifiNative).getWifiLinkLayerStats(TEST_IFACE_NAME);
verify(mWifiNative).signalPoll(TEST_IFACE_NAME);
+ assertEquals(-42, mWifiInfo.getRssi());
+
+ // Verify valid RSSI poll is updated to WifiInfo
+ signalPollResults.addEntry(0, -55, 65, 54, 2437);
+ mExternalScoreUpdateObserverCbCaptor.getValue().triggerUpdateOfWifiUsabilityStats(
+ scorerImpl.mSessionId);
+ mLooper.dispatchAll();
+ assertEquals(-55, mWifiInfo.getRssi());
+
+ // Verify invalid RSSI poll is ignored
+ signalPollResults.addEntry(0, -999, 65, 54, 2437);
+ mExternalScoreUpdateObserverCbCaptor.getValue().triggerUpdateOfWifiUsabilityStats(
+ scorerImpl.mSessionId);
+ mLooper.dispatchAll();
+ assertEquals(-55, mWifiInfo.getRssi());
}
/**
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiServiceImplTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiServiceImplTest.java
index ef5d255dc2..1e25a458c0 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiServiceImplTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiServiceImplTest.java
@@ -103,8 +103,8 @@ import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.ignoreStubs;
import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.ignoreStubs;
import static org.mockito.Mockito.isNull;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
@@ -160,6 +160,7 @@ import android.net.wifi.ILastCallerListener;
import android.net.wifi.IListListener;
import android.net.wifi.ILocalOnlyConnectionStatusListener;
import android.net.wifi.ILocalOnlyHotspotCallback;
+import android.net.wifi.IMacAddressListListener;
import android.net.wifi.IMapListener;
import android.net.wifi.INetworkRequestMatchCallback;
import android.net.wifi.IOnWifiActivityEnergyInfoListener;
@@ -212,6 +213,7 @@ import android.net.wifi.hotspot2.pps.Credential;
import android.net.wifi.hotspot2.pps.HomeSp;
import android.net.wifi.twt.TwtRequest;
import android.net.wifi.twt.TwtSessionCallback;
+import android.net.wifi.util.WifiResourceCache;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
@@ -235,6 +237,7 @@ import android.telephony.PhoneStateListener;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.util.ArrayMap;
+import android.util.ArraySet;
import android.util.Pair;
import androidx.test.filters.SmallTest;
@@ -386,6 +389,10 @@ public class WifiServiceImplTest extends WifiBaseTest {
final ArgumentCaptor<SoftApModeConfiguration> mSoftApModeConfigCaptor =
ArgumentCaptor.forClass(SoftApModeConfiguration.class);
+ final ArgumentCaptor<WifiSettingsConfigStore.OnSettingsChangedListener>
+ mWepAllowedSettingChangedListenerCaptor =
+ ArgumentCaptor.forClass(WifiSettingsConfigStore.OnSettingsChangedListener.class);
+
@Mock Bundle mBundle;
@Mock WifiContext mContext;
@Mock Context mContextAsUser;
@@ -476,7 +483,6 @@ public class WifiServiceImplTest extends WifiBaseTest {
@Mock SelfRecovery mSelfRecovery;
@Mock LastCallerInfoManager mLastCallerInfoManager;
@Mock BuildProperties mBuildProperties;
- @Mock LinkProbeManager mLinkProbeManager;
@Mock IOnWifiDriverCountryCodeChangedListener mIOnWifiDriverCountryCodeChangedListener;
@Mock WifiShellCommand mWifiShellCommand;
@Mock AfcManager mAfcManager;
@@ -499,6 +505,8 @@ public class WifiServiceImplTest extends WifiBaseTest {
@Captor ArgumentCaptor<Intent> mIntentCaptor;
@Captor ArgumentCaptor<List> mListCaptor;
@Mock TwtManager mTwtManager;
+ @Mock WifiResourceCache mWifiResourceCache;
+
@Rule
// For frameworks
public TestRule compatChangeRule = new PlatformCompatChangeRule();
@@ -544,7 +552,6 @@ public class WifiServiceImplTest extends WifiBaseTest {
when(mWifiInjector.getMakeBeforeBreakManager()).thenReturn(mMakeBeforeBreakManager);
when(mWifiInjector.getWifiNotificationManager()).thenReturn(mWifiNotificationManager);
when(mWifiInjector.getBuildProperties()).thenReturn(mBuildProperties);
- when(mWifiInjector.getLinkProbeManager()).thenReturn(mLinkProbeManager);
when(mWifiInjector.makeWifiShellCommand(any())).thenReturn(mWifiShellCommand);
when(mWifiInjector.getAfcManager()).thenReturn(mAfcManager);
when(mWifiInjector.getPasspointNetworkNominateHelper())
@@ -559,6 +566,7 @@ public class WifiServiceImplTest extends WifiBaseTest {
when(mHandlerThread.getThreadHandler()).thenReturn(new Handler(mLooper.getLooper()));
when(mHandlerThread.getLooper()).thenReturn(mLooper.getLooper());
when(mContext.getResources()).thenReturn(mResources);
+ when(mContext.getResourceCache()).thenReturn(mWifiResourceCache);
when(mContext.getContentResolver()).thenReturn(mContentResolver);
when(mContext.getPackageManager()).thenReturn(mPackageManager);
when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenReturn(mPackageInfo);
@@ -788,10 +796,10 @@ public class WifiServiceImplTest extends WifiBaseTest {
private WifiServiceImpl makeWifiServiceImplWithMockRunnerWhichTimesOut() {
WifiThreadRunner mockRunner = mock(WifiThreadRunner.class);
- when(mockRunner.call(any(), any())).then(returnsSecondArg());
- when(mockRunner.call(any(), any(int.class))).then(returnsSecondArg());
- when(mockRunner.call(any(), any(boolean.class))).then(returnsSecondArg());
- when(mockRunner.post(any())).thenReturn(false);
+ when(mockRunner.call(any(), any(), anyString())).then(returnsSecondArg());
+ when(mockRunner.call(any(), any(int.class), anyString())).then(returnsSecondArg());
+ when(mockRunner.call(any(), any(boolean.class), anyString())).then(returnsSecondArg());
+ when(mockRunner.post(any(), anyString())).thenReturn(false);
when(mWifiInjector.getWifiThreadRunner()).thenReturn(mockRunner);
// Reset mWifiCountryCode to avoid verify failure in makeWifiServiceImpl.
@@ -853,6 +861,7 @@ public class WifiServiceImplTest extends WifiBaseTest {
WifiDiagnostics.REPORT_REASON_USER_ACTION);
verify(mWifiDiagnostics).dump(any(), any(), any());
verify(mPasspointNetworkNominateHelper).dump(any());
+ verify(mWifiResourceCache).dump(any());
}
@Test
@@ -1694,6 +1703,67 @@ public class WifiServiceImplTest extends WifiBaseTest {
verify(mActiveModeWarden).addWifiNetworkStateChangedListener(testListener);
}
+ private class GetBssidBlocklistMatcher implements
+ ArgumentMatcher<ParceledListSlice<MacAddress>> {
+ private boolean mDoMatching;
+ GetBssidBlocklistMatcher(boolean doMatching) {
+ // false to match empty
+ // true to match some BSSID
+ mDoMatching = doMatching;
+ }
+ @Override
+ public boolean matches(ParceledListSlice<MacAddress> macAddresses) {
+ if (mDoMatching) {
+ return macAddresses.getList().size() == 1
+ && macAddresses.getList().get(0).toString().equals(TEST_BSSID);
+ }
+ return macAddresses.getList().isEmpty();
+ }
+ }
+
+ @Test
+ public void testGetBssidBlocklist() throws Exception {
+ IMacAddressListListener listener = mock(IMacAddressListListener.class);
+ // verify null arguments throw exception
+ assertThrows(IllegalArgumentException.class,
+ () -> mWifiServiceImpl.getBssidBlocklist(null, listener));
+ assertThrows(IllegalArgumentException.class,
+ () -> mWifiServiceImpl.getBssidBlocklist(
+ new ParceledListSlice(Collections.EMPTY_LIST), null));
+
+ when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
+ when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(false);
+ assertThrows(SecurityException.class,
+ () -> mWifiServiceImpl.getBssidBlocklist(
+ new ParceledListSlice(Collections.EMPTY_LIST), listener));
+
+ // Verify calling with empty SSIDs with network settings permission
+ when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
+ mWifiServiceImpl.getBssidBlocklist(new ParceledListSlice(Collections.EMPTY_LIST), listener);
+ mLooper.dispatchAll();
+ verify(mWifiBlocklistMonitor).getBssidBlocklistForSsids(null);
+ verify(listener).onResult(argThat(new GetBssidBlocklistMatcher(false)));
+
+ // Verify calling with non-null SSIDs with SUW permission, and verify dup SSID gets removed
+ when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
+ when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(true);
+ when(mWifiBlocklistMonitor.getBssidBlocklistForSsids(any())).thenReturn(
+ Arrays.asList(new String[] {TEST_BSSID}));
+ ParceledListSlice<MacAddress> expectedResult = new ParceledListSlice<>(Arrays.asList(
+ new MacAddress[] {MacAddress.fromString(TEST_BSSID)}));
+ WifiSsid ssid = WifiSsid.fromString(TEST_SSID_WITH_QUOTES);
+ List<WifiSsid> ssidListWithDup = new ArrayList<>();
+ ssidListWithDup.add(ssid);
+ ssidListWithDup.add(ssid);
+ ParceledListSlice<WifiSsid> ssidsParceledListWithDup =
+ new ParceledListSlice<>(ssidListWithDup);
+ Set<String> ssidSet = new ArraySet<>(Arrays.asList(new String[]{TEST_SSID_WITH_QUOTES}));
+ mWifiServiceImpl.getBssidBlocklist(ssidsParceledListWithDup, listener);
+ mLooper.dispatchAll();
+ verify(mWifiBlocklistMonitor).getBssidBlocklistForSsids(ssidSet);
+ verify(listener).onResult(argThat(new GetBssidBlocklistMatcher(true)));
+ }
+
/**
* Verify that the restartWifiSubsystem succeeds and passes correct parameters.
*/
@@ -2244,7 +2314,7 @@ public class WifiServiceImplTest extends WifiBaseTest {
/**
* Verify a SecurityException is thrown when a caller without the correct permission attempts to
- * call startTetheredHotspotRequest().
+ * call startTetheredHotspot().
*/
@Test(expected = SecurityException.class)
public void testStartTetheredHotspotRequestWithoutPermissionThrowsException() throws Exception {
@@ -3340,7 +3410,7 @@ public class WifiServiceImplTest extends WifiBaseTest {
String featureId = "test.com.featureId";
mLooper.startAutoDispatch();
List<ScanResult> retrievedScanResultList = mWifiServiceImpl.getScanResults(packageName,
- featureId);
+ featureId).getList();
mLooper.stopAutoDispatchAndIgnoreExceptions();
verify(mScanRequestProxy).getScanResults();
@@ -3366,7 +3436,7 @@ public class WifiServiceImplTest extends WifiBaseTest {
String featureId = "test.com.featureId";
mLooper.startAutoDispatch();
List<ScanResult> retrievedScanResultList = mWifiServiceImpl.getScanResults(packageName,
- featureId);
+ featureId).getList();
mLooper.stopAutoDispatchAndIgnoreExceptions();
verify(mScanRequestProxy, never()).getScanResults();
@@ -5389,6 +5459,34 @@ public class WifiServiceImplTest extends WifiBaseTest {
}
/**
+ * Verify that the CONNECT_NETWORK message received from NF is forwarded to
+ * ClientModeManager.
+ */
+ @Test
+ public void testConnectNetworkWithNfcUid() throws Exception {
+ final int origCallingUid = Binder.getCallingUid();
+ BinderUtil.setUid(Process.NFC_UID);
+ try {
+ when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt()))
+ .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID));
+ WifiConfiguration config = new WifiConfiguration();
+ config.SSID = TEST_SSID;
+ when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID))
+ .thenReturn(config);
+ mWifiServiceImpl.connect(config, TEST_NETWORK_ID, mock(IActionListener.class),
+ TEST_PACKAGE_NAME, mExtras);
+ mLooper.dispatchAll();
+ verify(mWifiConfigManager).addOrUpdateNetwork(eq(config), anyInt());
+ verify(mConnectHelper).connectToNetwork(any(NetworkUpdateResult.class),
+ any(ActionListenerWrapper.class), anyInt(), any(), any());
+ verify(mLastCallerInfoManager).put(eq(WifiManager.API_CONNECT_CONFIG), anyInt(),
+ anyInt(), anyInt(), anyString(), eq(true));
+ } finally {
+ BinderUtil.setUid(origCallingUid);
+ }
+ }
+
+ /**
* Verify the secondary internet CMM is stopped when explicit connection is initiated on the
* primary.
*/
@@ -6882,38 +6980,6 @@ public class WifiServiceImplTest extends WifiBaseTest {
}
/**
- * Verify that add or update networks is allowed for apps holding system alert permission.
- */
- @Test
- public void testAddOrUpdateNetworkIsAllowedForAppsWithSystemAlertPermission() throws Exception {
- doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
- .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
- when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), any(), eq(false))).thenReturn(
- new NetworkUpdateResult(0));
-
- // Verify caller fails to add network as Guest user.
- when(mWifiPermissionsUtil.checkSystemAlertWindowPermission(
- Process.myUid(), TEST_PACKAGE_NAME)).thenReturn(true);
- when(mWifiPermissionsUtil.isGuestUser()).thenReturn(true);
- WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
- mLooper.startAutoDispatch();
- assertEquals(-1,
- mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
-
- // Verify caller successfully add network when not a Guest user.
- when(mWifiPermissionsUtil.isGuestUser()).thenReturn(false);
- assertEquals(0,
- mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
- mLooper.stopAutoDispatchAndIgnoreExceptions();
-
- verifyCheckChangePermission(TEST_PACKAGE_NAME);
- verify(mWifiPermissionsUtil, times(2))
- .checkSystemAlertWindowPermission(anyInt(), anyString());
- verify(mWifiConfigManager).addOrUpdateNetwork(any(), anyInt(), any(), eq(false));
- verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls();
- }
-
- /**
* Verify that add or update networks is allowed for DeviceOwner app.
*/
@Test
@@ -9371,6 +9437,7 @@ public class WifiServiceImplTest extends WifiBaseTest {
mLooper.stopAutoDispatchAndIgnoreExceptions();
verify(mWakeupController).dump(any(), any(), any());
verify(mPasspointNetworkNominateHelper).dump(any());
+ verify(mWifiResourceCache).dump(any());
}
/**
@@ -10011,10 +10078,14 @@ public class WifiServiceImplTest extends WifiBaseTest {
mLooper.startAutoDispatch();
assertThat(mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_5_WITH_DFS_6_60_GHZ, OP_MODE_SAP,
FILTER_REGULATORY, TEST_PACKAGE_NAME, mExtras)).containsExactly(
- new WifiAvailableChannel(2452, WifiAvailableChannel.OP_MODE_SAP),
- new WifiAvailableChannel(5180, WifiAvailableChannel.OP_MODE_SAP),
- new WifiAvailableChannel(5955, WifiAvailableChannel.OP_MODE_SAP),
- new WifiAvailableChannel(58320, WifiAvailableChannel.OP_MODE_SAP));
+ new WifiAvailableChannel(2452, WifiAvailableChannel.OP_MODE_SAP,
+ ScanResult.CHANNEL_WIDTH_20MHZ),
+ new WifiAvailableChannel(5180, WifiAvailableChannel.OP_MODE_SAP,
+ ScanResult.CHANNEL_WIDTH_20MHZ),
+ new WifiAvailableChannel(5955, WifiAvailableChannel.OP_MODE_SAP,
+ ScanResult.CHANNEL_WIDTH_20MHZ),
+ new WifiAvailableChannel(58320, WifiAvailableChannel.OP_MODE_SAP,
+ ScanResult.CHANNEL_WIDTH_20MHZ));
mLooper.stopAutoDispatchAndIgnoreExceptions();
}
@@ -10036,13 +10107,16 @@ public class WifiServiceImplTest extends WifiBaseTest {
when(mWifiNative.isHalStarted()).thenReturn(true);
when(mWifiNative.getUsableChannels(eq(WIFI_BAND_24_GHZ), anyInt(), anyInt()))
.thenReturn(Arrays.asList(
- new WifiAvailableChannel(2452, WifiAvailableChannel.OP_MODE_SAP)));
+ new WifiAvailableChannel(2452, WifiAvailableChannel.OP_MODE_SAP,
+ ScanResult.CHANNEL_WIDTH_20MHZ)));
when(mWifiNative.getUsableChannels(eq(WIFI_BAND_5_GHZ), anyInt(), anyInt()))
.thenReturn(Arrays.asList(
- new WifiAvailableChannel(5180, WifiAvailableChannel.OP_MODE_SAP)));
+ new WifiAvailableChannel(5180, WifiAvailableChannel.OP_MODE_SAP,
+ ScanResult.CHANNEL_WIDTH_20MHZ)));
when(mWifiNative.getUsableChannels(eq(WIFI_BAND_6_GHZ), anyInt(), anyInt()))
.thenReturn(Arrays.asList(
- new WifiAvailableChannel(5955, WifiAvailableChannel.OP_MODE_SAP)));
+ new WifiAvailableChannel(5955, WifiAvailableChannel.OP_MODE_SAP,
+ ScanResult.CHANNEL_WIDTH_20MHZ)));
when(mWifiNative.getUsableChannels(eq(WIFI_BAND_60_GHZ), anyInt(), anyInt()))
.thenReturn(null);
@@ -11457,7 +11531,7 @@ public class WifiServiceImplTest extends WifiBaseTest {
when(mWifiNative.isHalStarted()).thenReturn(true);
// Channel 9 - 2452Mhz
WifiAvailableChannel channels2g = new WifiAvailableChannel(2452,
- WifiAvailableChannel.OP_MODE_SAP);
+ WifiAvailableChannel.OP_MODE_SAP, ScanResult.CHANNEL_WIDTH_20MHZ);
when(mWifiNative.isHalSupported()).thenReturn(true);
when(mWifiNative.isHalStarted()).thenReturn(true);
when(mWifiNative.getUsableChannels(eq(WifiScanner.WIFI_BAND_24_GHZ), anyInt(), anyInt()))
@@ -12191,7 +12265,8 @@ public class WifiServiceImplTest extends WifiBaseTest {
mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
verify(mActiveModeWarden).notifyShuttingDown();
verify(mWifiScoreCard).resetAllConnectionStates();
- verify(mWifiConfigManager).handleShutDown();
+ verify(mWifiConfigManager).writeDataToStorage();
+ verify(mWifiNetworkSuggestionsManager).handleShutDown();
}
@Test(expected = SecurityException.class)
@@ -12629,10 +12704,11 @@ public class WifiServiceImplTest extends WifiBaseTest {
verify(iTwtCallback).onFailure(eq(TwtSessionCallback.TWT_ERROR_CODE_NOT_AVAILABLE));
// Test setupTwtSession with station connected
when(mClientModeManager.isConnected()).thenReturn(true);
+ when(mClientModeManager.getConnectedBssid()).thenReturn(TEST_BSSID);
mWifiServiceImpl.setupTwtSession(twtRequest, iTwtCallback, mExtras);
mLooper.dispatchAll();
verify(mTwtManager).setupTwtSession(eq(WIFI_IFACE_NAME), eq(twtRequest), eq(iTwtCallback),
- eq(Binder.getCallingUid()));
+ eq(Binder.getCallingUid()), eq(TEST_BSSID));
}
@Test
@@ -12725,4 +12801,32 @@ public class WifiServiceImplTest extends WifiBaseTest {
mLooper.dispatchAll();
verify(mBackupRestoreController).parserBackupDataAndDispatch(mockTestRestoredData);
}
+
+ @Test
+ public void testWepAllowedChangedFromCloudRestoration() {
+ when(mWifiSettingsConfigStore.get(eq(WIFI_WEP_ALLOWED))).thenReturn(true);
+ when(mWifiGlobals.isWepAllowed()).thenReturn(true);
+ mWifiServiceImpl.checkAndStartWifi();
+ mLooper.dispatchAll();
+ verify(mWifiSettingsConfigStore).registerChangeListener(
+ eq(WIFI_WEP_ALLOWED),
+ mWepAllowedSettingChangedListenerCaptor.capture(),
+ any(Handler.class));
+ verify(mWifiGlobals).setWepAllowed(true);
+ // Mock wep connection to make sure it will disconnect
+ ConcreteClientModeManager cmmWep = mock(ConcreteClientModeManager.class);
+ WifiInfo mockWifiInfoWep = mock(WifiInfo.class);
+ List<ClientModeManager> cmms = Arrays.asList(cmmWep);
+ when(mActiveModeWarden.getClientModeManagers()).thenReturn(cmms);
+ when(mockWifiInfoWep.getCurrentSecurityType()).thenReturn(WifiInfo.SECURITY_TYPE_WEP);
+ when(cmmWep.getConnectionInfo()).thenReturn(mockWifiInfoWep);
+
+ // Test wep is changed from cloud restoration.
+ mWepAllowedSettingChangedListenerCaptor.getValue()
+ .onSettingsChanged(WIFI_WEP_ALLOWED, false);
+ mLooper.dispatchAll();
+ verify(mWifiGlobals).setWepAllowed(false);
+ // Only WEP disconnect
+ verify(cmmWep).disconnect();
+ }
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiSettingsBackupRestoreTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiSettingsBackupRestoreTest.java
index c8aecd50a0..38b4d9e0a4 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiSettingsBackupRestoreTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiSettingsBackupRestoreTest.java
@@ -55,17 +55,17 @@ public class WifiSettingsBackupRestoreTest extends WifiBaseTest {
add(WifiSettingsConfigStore.WIFI_WEP_ALLOWED); }};
/**
- * The data we backup in this module is <WifiSettingsBackData></WifiSettingsBackData>
+ * The data we backup in this module is <WifiSettingsSection></WifiSettingsSection>
* and the depth is 1.
*/
public static String generateTestWifiSettingsTestingXml(String backupKeys) {
- return "<WifiSettingsBackData>\n"
+ return "<WifiSettingsSection>\n"
+ "<Settings>\n"
+ "<map name=\"Values\">\n"
+ backupKeys
+ "</map>\n"
+ "</Settings>\n"
- + "</WifiSettingsBackData>\n";
+ + "</WifiSettingsSection>\n";
}
private WifiSettingsBackupRestore mWifiSettingsBackupRestore;
@@ -115,7 +115,7 @@ public class WifiSettingsBackupRestoreTest extends WifiBaseTest {
mWifiSettingsBackupRestore.restoreSettingsFromBackupData(
generateTestXmlPullParser(
generateTestWifiSettingsTestingXml(testBackupMap).getBytes()),
- 0 /* The depth of Tag: WifiSettingsBackData */);
+ 0 /* The depth of Tag: WifiSettingsSection */);
verify(mWifiSettingsConfigStore).put(eq(WifiSettingsConfigStore.WIFI_WEP_ALLOWED),
eq(Boolean.TRUE));
}
@@ -126,7 +126,7 @@ public class WifiSettingsBackupRestoreTest extends WifiBaseTest {
mWifiSettingsBackupRestore.restoreSettingsFromBackupData(
generateTestXmlPullParser(
generateTestWifiSettingsTestingXml(testBackupMap).getBytes()),
- 0 /* The depth of Tag: WifiSettingsBackData */);
+ 0 /* The depth of Tag: WifiSettingsSection */);
verify(mWifiSettingsConfigStore, never()).put(any(), any());
}
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiSettingsConfigStoreTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiSettingsConfigStoreTest.java
index e2e2575d87..d60cf9e3e4 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiSettingsConfigStoreTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiSettingsConfigStoreTest.java
@@ -97,7 +97,7 @@ public class WifiSettingsConfigStoreTest extends WifiBaseTest {
mWifiSettingsConfigStore.put(WIFI_VERBOSE_LOGGING_ENABLED, true);
mLooper.dispatchAll();
assertTrue(mWifiSettingsConfigStore.get(WIFI_VERBOSE_LOGGING_ENABLED));
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
}
@Test
@@ -152,7 +152,7 @@ public class WifiSettingsConfigStoreTest extends WifiBaseTest {
assertTrue(mWifiSettingsConfigStore.get(WIFI_VERBOSE_LOGGING_ENABLED));
// Trigger store file write after migration.
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
}
private XmlPullParser createSettingsTestXmlForParsing(Key key, Object value)
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiShellCommandTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiShellCommandTest.java
index 4783d049cf..9252aa8f41 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiShellCommandTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiShellCommandTest.java
@@ -58,8 +58,10 @@ import android.net.wifi.WifiNetworkSpecifier;
import android.net.wifi.WifiNetworkSuggestion;
import android.net.wifi.WifiScanner;
import android.os.Binder;
+import android.os.Handler;
import android.os.PatternMatcher;
import android.os.Process;
+import android.os.test.TestLooper;
import androidx.test.filters.SmallTest;
@@ -74,6 +76,7 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.io.FileDescriptor;
+import java.util.ArrayList;
import java.util.Arrays;
/**
@@ -100,16 +103,17 @@ public class WifiShellCommandTest extends WifiBaseTest {
@Mock WifiCarrierInfoManager mWifiCarrierInfoManager;
@Mock WifiNetworkFactory mWifiNetworkFactory;
@Mock WifiGlobals mWifiGlobals;
- @Mock WifiThreadRunner mWifiThreadRunner;
@Mock ScanRequestProxy mScanRequestProxy;
@Mock WifiDiagnostics mWifiDiagnostics;
@Mock DeviceConfigFacade mDeviceConfig;
@Mock WifiScanner mWifiScanner;
WifiShellCommand mWifiShellCommand;
+ TestLooper mLooper;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
+ mLooper = new TestLooper();
when(mWifiInjector.getActiveModeWarden()).thenReturn(mActiveModeWarden);
when(mActiveModeWarden.getPrimaryClientModeManager()).thenReturn(mPrimaryClientModeManager);
@@ -131,9 +135,10 @@ public class WifiShellCommandTest extends WifiBaseTest {
when(mWifiInjector.getWifiDiagnostics()).thenReturn(mWifiDiagnostics);
when(mWifiInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfig);
when(mContext.getSystemService(WifiScanner.class)).thenReturn(mWifiScanner);
+ when(mScanRequestProxy.getScanResults()).thenReturn(new ArrayList<>());
mWifiShellCommand = new WifiShellCommand(mWifiInjector, mWifiService, mContext,
- mWifiGlobals, mWifiThreadRunner);
+ mWifiGlobals, new WifiThreadRunner(new Handler(mLooper.getLooper())));
// by default emulate shell uid.
BinderUtil.setUid(Process.SHELL_UID);
@@ -310,6 +315,7 @@ public class WifiShellCommandTest extends WifiBaseTest {
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"network-suggestions-set-user-approved", TEST_PACKAGE, "yes"});
+ mLooper.dispatchAll();
verify(mWifiNetworkSuggestionsManager, never()).setHasUserApprovedForApp(
anyBoolean(), anyInt(), anyString());
assertFalse(mWifiShellCommand.getErrPrintWriter().toString().isEmpty());
@@ -319,12 +325,14 @@ public class WifiShellCommandTest extends WifiBaseTest {
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"network-suggestions-set-user-approved", TEST_PACKAGE, "yes"});
+ mLooper.dispatchAll();
verify(mWifiNetworkSuggestionsManager).setHasUserApprovedForApp(
eq(true), anyInt(), eq(TEST_PACKAGE));
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"network-suggestions-set-user-approved", TEST_PACKAGE, "no"});
+ mLooper.dispatchAll();
verify(mWifiNetworkSuggestionsManager).setHasUserApprovedForApp(
eq(false), anyInt(), eq(TEST_PACKAGE));
}
@@ -525,6 +533,7 @@ public class WifiShellCommandTest extends WifiBaseTest {
@Test
public void testStartSoftAp() {
+ BinderUtil.setUid(Process.ROOT_UID);
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"start-softap", "ap1", "wpa2", "xyzabc321", "-b", "5"});
@@ -542,6 +551,7 @@ public class WifiShellCommandTest extends WifiBaseTest {
@Test
public void testStopSoftAp() {
+ BinderUtil.setUid(Process.ROOT_UID);
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"stop-softap"});
@@ -858,13 +868,6 @@ public class WifiShellCommandTest extends WifiBaseTest {
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"connect-network", "012345", "open", "-x"});
- verify(mWifiService, never()).connect(argThat(wifiConfiguration ->
- (wifiConfiguration.SSID.equals("012345"))), eq(-1), any(), any(), any());
-
- BinderUtil.setUid(Process.ROOT_UID);
- mWifiShellCommand.exec(
- new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
- new String[]{"connect-network", "012345", "open", "-x"});
verify(mWifiService).connect(argThat(wifiConfiguration ->
(wifiConfiguration.SSID.equals("012345"))), eq(-1), any(), any(), any());
}
@@ -874,13 +877,6 @@ public class WifiShellCommandTest extends WifiBaseTest {
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"add-network", "012345", "open", "-x"});
- verify(mWifiService, never()).save(argThat(wifiConfiguration ->
- (wifiConfiguration.SSID.equals("012345"))), any());
-
- BinderUtil.setUid(Process.ROOT_UID);
- mWifiShellCommand.exec(
- new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
- new String[]{"add-network", "012345", "open", "-x"});
verify(mWifiService).save(argThat(wifiConfiguration ->
(wifiConfiguration.SSID.equals("012345"))), any(), any());
}
@@ -914,6 +910,7 @@ public class WifiShellCommandTest extends WifiBaseTest {
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"add-request", testSsid, "open"});
+ mLooper.dispatchAll();
verify(mConnectivityManager).requestNetwork(eq(
new NetworkRequest.Builder()
.addTransportType(TRANSPORT_WIFI)
@@ -922,12 +919,13 @@ public class WifiShellCommandTest extends WifiBaseTest {
.setSsid(testSsid)
.build())
.build()),
- (ConnectivityManager.NetworkCallback) any());
+ any(ConnectivityManager.NetworkCallback.class));
// OWE
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
- new String[]{"add-request", testSsid, "owe", testPassphrase});
+ new String[]{"add-request", testSsid, "owe"});
+ mLooper.dispatchAll();
verify(mConnectivityManager).requestNetwork(eq(
new NetworkRequest.Builder()
.addTransportType(TRANSPORT_WIFI)
@@ -937,12 +935,13 @@ public class WifiShellCommandTest extends WifiBaseTest {
.setIsEnhancedOpen(true)
.build())
.build()),
- (ConnectivityManager.NetworkCallback) any());
+ any(ConnectivityManager.NetworkCallback.class));
// WPA2
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"add-request", testSsid, "wpa2", testPassphrase});
+ mLooper.dispatchAll();
verify(mConnectivityManager).requestNetwork(eq(
new NetworkRequest.Builder()
.addTransportType(TRANSPORT_WIFI)
@@ -952,12 +951,13 @@ public class WifiShellCommandTest extends WifiBaseTest {
.setWpa2Passphrase(testPassphrase)
.build())
.build()),
- (ConnectivityManager.NetworkCallback) any());
+ any(ConnectivityManager.NetworkCallback.class));
// WPA3
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"add-request", testSsid, "wpa3", testPassphrase});
+ mLooper.dispatchAll();
verify(mConnectivityManager).requestNetwork(eq(
new NetworkRequest.Builder()
.addTransportType(TRANSPORT_WIFI)
@@ -967,12 +967,13 @@ public class WifiShellCommandTest extends WifiBaseTest {
.setWpa3Passphrase(testPassphrase)
.build())
.build()),
- (ConnectivityManager.NetworkCallback) any());
+ any(ConnectivityManager.NetworkCallback.class));
// Test bssid flag
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"add-request", testSsid, "open", "-b", testBssid});
+ mLooper.dispatchAll();
verify(mConnectivityManager).requestNetwork(eq(
new NetworkRequest.Builder()
.addTransportType(TRANSPORT_WIFI)
@@ -982,12 +983,13 @@ public class WifiShellCommandTest extends WifiBaseTest {
.setBssid(MacAddress.fromString(testBssid))
.build())
.build()),
- (ConnectivityManager.NetworkCallback) any());
+ any(ConnectivityManager.NetworkCallback.class));
// Test glob flag
mWifiShellCommand.exec(
new Binder(), new FileDescriptor(), new FileDescriptor(), new FileDescriptor(),
new String[]{"add-request", "-g", testSsid, "open"});
+ mLooper.dispatchAll();
verify(mConnectivityManager).requestNetwork(eq(
new NetworkRequest.Builder()
.addTransportType(TRANSPORT_WIFI)
@@ -997,7 +999,7 @@ public class WifiShellCommandTest extends WifiBaseTest {
testSsid, PatternMatcher.PATTERN_ADVANCED_GLOB))
.build())
.build()),
- (ConnectivityManager.NetworkCallback) any());
+ any(ConnectivityManager.NetworkCallback.class));
}
@Test
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiThreadRunnerTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiThreadRunnerTest.java
index 4a041bcefd..cd5bf58dc0 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiThreadRunnerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiThreadRunnerTest.java
@@ -18,6 +18,7 @@ package com.android.server.wifi;
import static com.google.common.truth.Truth.assertThat;
+import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.doAnswer;
@@ -28,11 +29,14 @@ import static org.mockito.Mockito.verify;
import android.os.Handler;
import android.os.HandlerThread;
+import android.os.Message;
import androidx.test.filters.SmallTest;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
@@ -48,6 +52,7 @@ public class WifiThreadRunnerTest extends WifiBaseTest {
private WifiThreadRunner mWifiThreadRunner;
@Mock private Runnable mRunnable;
+ @Captor private ArgumentCaptor<Message> mCaptor;
private Handler mHandler;
@@ -77,7 +82,7 @@ public class WifiThreadRunnerTest extends WifiBaseTest {
return true;
}).when(mHandler).runWithScissors(any(), anyLong());
- Integer result = mWifiThreadRunner.call(mSupplier, VALUE_ON_TIMEOUT);
+ Integer result = mWifiThreadRunner.call(mSupplier, VALUE_ON_TIMEOUT, "taskName");
assertThat(result).isEqualTo(RESULT);
verify(mSupplier).get();
@@ -85,9 +90,9 @@ public class WifiThreadRunnerTest extends WifiBaseTest {
@Test
public void callFailure_returnValueOnTimeout() {
- doReturn(false).when(mHandler).post(any());
+ doReturn(false).when(mHandler).sendMessage(any());
- Integer result = mWifiThreadRunner.call(mSupplier, VALUE_ON_TIMEOUT);
+ Integer result = mWifiThreadRunner.call(mSupplier, VALUE_ON_TIMEOUT, "taskName");
assertThat(result).isEqualTo(VALUE_ON_TIMEOUT);
verify(mSupplier, never()).get();
@@ -102,7 +107,7 @@ public class WifiThreadRunnerTest extends WifiBaseTest {
return true;
}).when(mHandler).runWithScissors(any(), anyLong());
- boolean result = mWifiThreadRunner.run(mRunnable);
+ boolean result = mWifiThreadRunner.run(mRunnable, "taskName");
assertThat(result).isTrue();
verify(mRunnable).run();
@@ -110,9 +115,9 @@ public class WifiThreadRunnerTest extends WifiBaseTest {
@Test
public void runFailure() {
- doReturn(false).when(mHandler).post(any());
+ doReturn(false).when(mHandler).sendMessage(any());
- boolean runSuccess = mWifiThreadRunner.run(mRunnable);
+ boolean runSuccess = mWifiThreadRunner.run(mRunnable, "taskName");
assertThat(runSuccess).isFalse();
verify(mRunnable, never()).run();
@@ -120,24 +125,26 @@ public class WifiThreadRunnerTest extends WifiBaseTest {
@Test
public void postSuccess() {
- doReturn(true).when(mHandler).post(any());
+ doReturn(true).when(mHandler).sendMessage(any());
- boolean postSuccess = mWifiThreadRunner.post(mRunnable);
+ boolean postSuccess = mWifiThreadRunner.post(mRunnable, "");
assertThat(postSuccess).isTrue();
- verify(mHandler).post(mRunnable);
+ verify(mHandler).sendMessage(mCaptor.capture());
+ assertEquals(mRunnable, mCaptor.getValue().getCallback());
// assert that the runnable is not run on the calling thread
verify(mRunnable, never()).run();
}
@Test
public void postFailure() {
- doReturn(false).when(mHandler).post(any());
+ doReturn(false).when(mHandler).sendMessage(any());
- boolean postSuccess = mWifiThreadRunner.post(mRunnable);
+ boolean postSuccess = mWifiThreadRunner.post(mRunnable, "");
assertThat(postSuccess).isFalse();
- verify(mHandler).post(mRunnable);
+ verify(mHandler).sendMessage(mCaptor.capture());
+ assertEquals(mRunnable, mCaptor.getValue().getCallback());
verify(mRunnable, never()).run();
}
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiVendorHalTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiVendorHalTest.java
index c6e4d5e600..c958fc1a3a 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WifiVendorHalTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiVendorHalTest.java
@@ -1828,4 +1828,18 @@ public class WifiVendorHalTest extends WifiBaseTest {
assertTrue(mWifiVendorHal.setRoamingMode(TEST_IFACE_NAME, WifiManager.ROAMING_MODE_NORMAL)
== WifiStatusCode.SUCCESS);
}
+
+ /**
+ * Test that setVoipMode() results in calling into WifiChip
+ */
+ @Test
+ public void testVoipMode() throws Exception {
+ when(mWifiChip.setVoipMode(anyInt())).thenReturn(true);
+ // should fail - not started
+ assertFalse(mWifiVendorHal.setVoipMode(WifiChip.WIFI_VOIP_MODE_VOICE));
+ // Start the vendor hal
+ assertTrue(mWifiVendorHal.startVendorHalSta(mConcreteClientModeManager));
+ assertTrue(mWifiVendorHal.setVoipMode(WifiChip.WIFI_VOIP_MODE_VOICE));
+ verify(mWifiChip).setVoipMode(WifiChip.WIFI_VOIP_MODE_VOICE);
+ }
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WifiVoipDetectorTest.java b/service/tests/wifitests/src/com/android/server/wifi/WifiVoipDetectorTest.java
new file mode 100644
index 0000000000..9741a2c8c2
--- /dev/null
+++ b/service/tests/wifitests/src/com/android/server/wifi/WifiVoipDetectorTest.java
@@ -0,0 +1,194 @@
+/*
+ * Copyright (C) 2024 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wifi;
+
+import static org.junit.Assume.assumeTrue;
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.media.AudioManager;
+import android.os.Handler;
+import android.os.test.TestLooper;
+import android.telephony.CallAttributes;
+import android.telephony.CallQuality;
+import android.telephony.PreciseCallState;
+import android.telephony.TelephonyManager;
+
+import androidx.test.filters.SmallTest;
+
+import com.android.modules.utils.build.SdkLevel;
+import com.android.server.wifi.hal.WifiChip;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+/**
+ * Unit tests for {@link com.android.server.wifi.WifiVoipDetectorTest}.
+ */
+@SmallTest
+public class WifiVoipDetectorTest extends WifiBaseTest {
+
+ private static final CallAttributes TEST_VOWIFI_CALL_ATT =
+ new CallAttributes(new PreciseCallState(),
+ TelephonyManager.NETWORK_TYPE_IWLAN, new CallQuality());
+ private static final CallAttributes TEST_LTE_CALL_ATT =
+ new CallAttributes(new PreciseCallState(),
+ TelephonyManager.NETWORK_TYPE_LTE, new CallQuality());
+
+ private static final String TEST_PRIMARY_INTERFACE_NAME = "wlan0";
+ private static final String TEST_SECONDARY_INTERFACE_NAME = "wlan1";
+
+ @Mock private Context mContext;
+ @Mock private WifiInjector mWifiInjector;
+ @Mock private AudioManager mAudioManager;
+ @Mock private TelephonyManager mTelephonyManager;
+ @Mock private WifiNative mWifiNative;
+ @Mock private WifiCarrierInfoManager mWifiCarrierInfoManager;
+
+ private WifiVoipDetector mWifiVoipDetector;
+ private TestLooper mLooper;
+ private ArgumentCaptor<WifiVoipDetector.WifiCallingStateListener> mTelephonyCallbackCaptor;
+ private ArgumentCaptor<AudioManager.OnModeChangedListener> mAudioModeChangedListeneCaptor;
+
+ @Before
+ public void setUp() throws Exception {
+ assumeTrue(SdkLevel.isAtLeastV());
+ MockitoAnnotations.initMocks(this);
+ mTelephonyCallbackCaptor =
+ ArgumentCaptor.forClass(WifiVoipDetector.WifiCallingStateListener.class);
+ mAudioModeChangedListeneCaptor =
+ ArgumentCaptor.forClass(AudioManager.OnModeChangedListener.class);
+ mLooper = new TestLooper();
+ when(mWifiInjector.makeTelephonyManager()).thenReturn(mTelephonyManager);
+ when(mContext.getSystemService(AudioManager.class)).thenReturn(mAudioManager);
+ when(mWifiInjector.getWifiNative()).thenReturn(mWifiNative);
+ when(mWifiNative.setVoipMode(anyInt())).thenReturn(true);
+ mWifiVoipDetector = new WifiVoipDetector(mContext,
+ new Handler(mLooper.getLooper()), mWifiInjector, mWifiCarrierInfoManager);
+ }
+
+ private void resetWifiNativeAndReSetupforMock() {
+ reset(mWifiNative);
+ when(mWifiNative.setVoipMode(anyInt())).thenReturn(true);
+ }
+
+ @Test
+ public void testNotifyWifiConnectedDisconnectedInPrimaryClientMode() {
+ assumeTrue(SdkLevel.isAtLeastV());
+ mWifiVoipDetector.notifyWifiConnected(true, true, TEST_PRIMARY_INTERFACE_NAME);
+ verify(mTelephonyManager).registerTelephonyCallback(any(),
+ mTelephonyCallbackCaptor.capture());
+ verify(mAudioManager).addOnModeChangedListener(any(),
+ mAudioModeChangedListeneCaptor.capture());
+ // Init should do nothing
+ verify(mWifiNative, never()).setVoipMode(anyInt());
+ // deinit should do nothing
+ mWifiVoipDetector.notifyWifiConnected(false, true, TEST_PRIMARY_INTERFACE_NAME);
+ verify(mWifiNative, never()).setVoipMode(anyInt());
+ // Init again when VoIP call is on
+ when(mWifiCarrierInfoManager.isWifiCallingAvailable()).thenReturn(true);
+ mWifiVoipDetector.notifyWifiConnected(true, true, TEST_PRIMARY_INTERFACE_NAME);
+ verify(mWifiNative).setVoipMode(WifiChip.WIFI_VOIP_MODE_VOICE);
+ // Test VoWifi call off -> switch to VoLte
+ mTelephonyCallbackCaptor.getValue().onCallAttributesChanged(TEST_LTE_CALL_ATT);
+ verify(mWifiNative).setVoipMode(WifiChip.WIFI_VOIP_MODE_OFF);
+ resetWifiNativeAndReSetupforMock();
+ // Test VoWifi Call
+ mTelephonyCallbackCaptor.getValue().onCallAttributesChanged(TEST_VOWIFI_CALL_ATT);
+ verify(mWifiNative).setVoipMode(WifiChip.WIFI_VOIP_MODE_VOICE);
+ resetWifiNativeAndReSetupforMock();
+ // Test VoWifi call off -> switch to VoLte
+ mTelephonyCallbackCaptor.getValue().onCallAttributesChanged(TEST_LTE_CALL_ATT);
+ verify(mWifiNative).setVoipMode(WifiChip.WIFI_VOIP_MODE_OFF);
+ resetWifiNativeAndReSetupforMock();
+ // Test MODE_IN_COMMUNICATION to trigger voice mode
+ mAudioModeChangedListeneCaptor.getValue().onModeChanged(AudioManager.MODE_IN_COMMUNICATION);
+ verify(mWifiNative).setVoipMode(WifiChip.WIFI_VOIP_MODE_VOICE);
+ resetWifiNativeAndReSetupforMock();
+ // Test MODE_NORMAL off WifiChip.WIFI_VOIP_MODE_OFF
+ mAudioModeChangedListeneCaptor.getValue().onModeChanged(AudioManager.MODE_NORMAL);
+ verify(mWifiNative).setVoipMode(WifiChip.WIFI_VOIP_MODE_OFF);
+ resetWifiNativeAndReSetupforMock();
+ // Test MODE_COMMUNICATION_REDIRECT to trigger voice mode
+ mAudioModeChangedListeneCaptor.getValue().onModeChanged(
+ AudioManager.MODE_COMMUNICATION_REDIRECT);
+ verify(mWifiNative).setVoipMode(WifiChip.WIFI_VOIP_MODE_VOICE);
+ resetWifiNativeAndReSetupforMock();
+ // Do nothing when mode change between two OTT modes.
+ mAudioModeChangedListeneCaptor.getValue().onModeChanged(AudioManager.MODE_IN_COMMUNICATION);
+ verify(mWifiNative, never()).setVoipMode(anyInt());
+ mWifiVoipDetector.notifyWifiConnected(false, true, TEST_PRIMARY_INTERFACE_NAME);
+ verify(mWifiNative).setVoipMode(WifiChip.WIFI_VOIP_MODE_OFF);
+ // Test OTT on when wifi is disconnected, should do nothing since it doesn't relate to wifi.
+ resetWifiNativeAndReSetupforMock();
+ mAudioModeChangedListeneCaptor.getValue().onModeChanged(
+ AudioManager.MODE_COMMUNICATION_REDIRECT);
+ verify(mWifiNative, never()).setVoipMode(anyInt());
+ // Wifi is connected and trigger Voice mode.
+ when(mAudioManager.getMode()).thenReturn(AudioManager.MODE_COMMUNICATION_REDIRECT);
+ mWifiVoipDetector.notifyWifiConnected(true, true, TEST_PRIMARY_INTERFACE_NAME);
+ verify(mWifiNative).setVoipMode(WifiChip.WIFI_VOIP_MODE_VOICE);
+ }
+
+ @Test
+ public void testNotifyWifiConnectedDisconnectedInSecondaryClientMode() {
+ assumeTrue(SdkLevel.isAtLeastV());
+ mWifiVoipDetector.notifyWifiConnected(true, false, TEST_SECONDARY_INTERFACE_NAME);
+ verify(mTelephonyManager, never()).registerTelephonyCallback(any(),
+ mTelephonyCallbackCaptor.capture());
+ verify(mAudioManager, never()).addOnModeChangedListener(any(),
+ mAudioModeChangedListeneCaptor.capture());
+ verify(mWifiNative, never()).setVoipMode(anyInt());
+ }
+
+ @Test
+ public void testNotifyWifiConnectedDisconnectedInPrimarySecondaryClientModeSwitch() {
+ assumeTrue(SdkLevel.isAtLeastV());
+ assumeTrue(SdkLevel.isAtLeastV());
+ mWifiVoipDetector.notifyWifiConnected(true, true, TEST_PRIMARY_INTERFACE_NAME);
+ verify(mTelephonyManager).registerTelephonyCallback(any(),
+ mTelephonyCallbackCaptor.capture());
+ verify(mAudioManager).addOnModeChangedListener(any(),
+ mAudioModeChangedListeneCaptor.capture());
+ verify(mWifiNative, never()).setVoipMode(anyInt());
+
+ mWifiVoipDetector.notifyWifiConnected(true, false, TEST_SECONDARY_INTERFACE_NAME);
+ mWifiVoipDetector.notifyWifiConnected(false, false, TEST_SECONDARY_INTERFACE_NAME);
+ verify(mTelephonyManager, never()).unregisterTelephonyCallback(any());
+ verify(mAudioManager, never()).removeOnModeChangedListener(any());
+ // MBB use case
+ // Secondary network is connected.
+ mWifiVoipDetector.notifyWifiConnected(true, false, TEST_SECONDARY_INTERFACE_NAME);
+ // Primary switch role to secondary and disconnected
+ mWifiVoipDetector.notifyWifiConnected(false, false, TEST_PRIMARY_INTERFACE_NAME);
+ verify(mTelephonyManager, never()).unregisterTelephonyCallback(any());
+ verify(mAudioManager, never()).removeOnModeChangedListener(any());
+ // Secondary switch role to primary and disconnected
+ mWifiVoipDetector.notifyWifiConnected(false, true, TEST_SECONDARY_INTERFACE_NAME);
+ // Verify unregister
+ verify(mTelephonyManager).unregisterTelephonyCallback(any());
+ verify(mAudioManager).removeOnModeChangedListener(any());
+ }
+}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/WrongPasswordNotifierTest.java b/service/tests/wifitests/src/com/android/server/wifi/WrongPasswordNotifierTest.java
index 76b4f4cb84..e9807f1fc9 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/WrongPasswordNotifierTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/WrongPasswordNotifierTest.java
@@ -115,6 +115,7 @@ public class WrongPasswordNotifierTest extends WifiBaseTest {
assertEquals(TEST_SETTINGS_PACKAGE, intent.getValue().getPackage());
assertEquals(TEST_SSID.getUtf8Text(),
intent.getValue().getStringExtra("wifi_start_connect_ssid"));
+ assertEquals(Intent.FLAG_ACTIVITY_CLEAR_TOP, intent.getValue().getFlags());
}
/**
diff --git a/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareDataPathStateManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareDataPathStateManagerTest.java
index 2adab51238..809fa1a915 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareDataPathStateManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareDataPathStateManagerTest.java
@@ -90,17 +90,21 @@ import androidx.test.filters.SmallTest;
import com.android.modules.utils.build.SdkLevel;
import com.android.server.wifi.Clock;
+import com.android.server.wifi.DeviceConfigFacade;
import com.android.server.wifi.HalDeviceManager;
import com.android.server.wifi.InterfaceConflictManager;
import com.android.server.wifi.MockResources;
import com.android.server.wifi.WifiBaseTest;
+import com.android.server.wifi.WifiGlobals;
import com.android.server.wifi.WifiInjector;
+import com.android.server.wifi.WifiSettingsConfigStore;
import com.android.server.wifi.aware.WifiAwareDataPathStateManager.WifiAwareNetworkAgent;
import com.android.server.wifi.hal.WifiNanIface.NanDataPathChannelCfg;
import com.android.server.wifi.hal.WifiNanIface.NanStatusCode;
import com.android.server.wifi.util.NetdWrapper;
import com.android.server.wifi.util.WifiPermissionsUtil;
import com.android.server.wifi.util.WifiPermissionsWrapper;
+import com.android.wifi.flags.FeatureFlags;
import com.android.wifi.resources.R;
import org.junit.After;
@@ -159,6 +163,10 @@ public class WifiAwareDataPathStateManagerTest extends WifiBaseTest {
@Mock private WifiInjector mWifiInjector;
@Mock private PairingConfigManager mPairingConfigManager;
@Mock private StatsManager mStatsManager;
+ @Mock private DeviceConfigFacade mDeviceConfigFacade;
+ @Mock private FeatureFlags mFeatureFlags;
+ @Mock private WifiSettingsConfigStore mWifiSettingsConfigStore;
+ @Mock private WifiGlobals mWifiGlobals;
@Rule
public ErrorCollector collector = new ErrorCollector();
@@ -207,7 +215,10 @@ public class WifiAwareDataPathStateManagerTest extends WifiBaseTest {
if (SdkLevel.isAtLeastS()) {
when(mWifiPermissionsUtil.getWifiCallerType(any())).thenReturn(6);
}
-
+ when(mWifiInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfigFacade);
+ when(mDeviceConfigFacade.getFeatureFlags()).thenReturn(mFeatureFlags);
+ when(mWifiInjector.getSettingsConfigStore()).thenReturn(mWifiSettingsConfigStore);
+ when(mWifiInjector.getWifiGlobals()).thenReturn(mWifiGlobals);
mDut = new WifiAwareStateManager(mWifiInjector, mPairingConfigManager);
mDut.setNative(mMockNativeManager, mMockNative);
mDut.start(mMockContext, mMockLooper.getLooper(), mAwareMetricsMock,
diff --git a/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareNativeManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareNativeManagerTest.java
index b9b3a1fea9..c2c97a34e0 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareNativeManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareNativeManagerTest.java
@@ -20,6 +20,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
@@ -35,7 +36,9 @@ import androidx.test.filters.SmallTest;
import com.android.server.wifi.HalDeviceManager;
import com.android.server.wifi.WifiBaseTest;
+import com.android.server.wifi.WifiNative;
import com.android.server.wifi.hal.WifiNanIface;
+import com.android.wifi.flags.FeatureFlags;
import org.junit.Before;
import org.junit.Rule;
@@ -58,6 +61,9 @@ public class WifiAwareNativeManagerTest extends WifiBaseTest {
@Mock private HalDeviceManager mHalDeviceManager;
@Mock private WifiAwareNativeCallback mWifiAwareNativeCallback;
@Mock private WifiNanIface mWifiNanIfaceMock;
+ @Mock private WifiNative.Iface mWifiNativeNanIfaceMock;
+ @Mock private WifiNative mWifiNative;
+ @Mock private FeatureFlags mFeatureFlags;
@Mock private Handler mHandlerMock;
private ArgumentCaptor<HalDeviceManager.ManagerStatusListener> mManagerStatusListenerCaptor =
ArgumentCaptor.forClass(HalDeviceManager.ManagerStatusListener.class);
@@ -79,16 +85,18 @@ public class WifiAwareNativeManagerTest extends WifiBaseTest {
when(mWifiNanIfaceMock.registerFrameworkCallback(any())).thenReturn(true);
mDut = new WifiAwareNativeManager(mWifiAwareStateManagerMock,
- mHalDeviceManager, mWifiAwareNativeCallback);
+ mHalDeviceManager, mWifiAwareNativeCallback, mWifiNative, mFeatureFlags);
mDut.enableVerboseLogging(true, true);
mDut.start(mHandlerMock);
- mInOrder = inOrder(mWifiAwareStateManagerMock, mHalDeviceManager, mWifiNanIfaceMock);
+ mInOrder = inOrder(mWifiAwareStateManagerMock, mHalDeviceManager,
+ mWifiNanIfaceMock, mWifiNative);
// validate (and capture) that register manage status callback
mInOrder.verify(mHalDeviceManager).initialize();
mInOrder.verify(mHalDeviceManager).registerStatusListener(
mManagerStatusListenerCaptor.capture(), any());
+ mWifiNativeNanIfaceMock.iface = mWifiNanIfaceMock;
}
/**
@@ -104,11 +112,10 @@ public class WifiAwareNativeManagerTest extends WifiBaseTest {
*/
@Test
public void testControlFlowWithoutInterface() {
+ when(mWifiAwareStateManagerMock.isD2dAllowedWhenStaDisabled()).thenReturn(true);
// configure HalDeviceManager as ready/wifi started (and to return an interface if
// requested)
when(mHalDeviceManager.isStarted()).thenReturn(true);
- when(mHalDeviceManager.createNanIface(any(), any(), any()))
- .thenReturn(mWifiNanIfaceMock);
// 1. onStatusChange (ready/started)
mManagerStatusListenerCaptor.getValue().onStatusChanged();
@@ -117,15 +124,15 @@ public class WifiAwareNativeManagerTest extends WifiBaseTest {
// 2. onStatusChange (not ready) -> disableUsage
when(mHalDeviceManager.isStarted()).thenReturn(false);
mManagerStatusListenerCaptor.getValue().onStatusChanged();
+ mInOrder.verify(mWifiAwareStateManagerMock).isD2dAllowedWhenStaDisabled();
- mInOrder.verify(mWifiAwareStateManagerMock).disableUsage(false);
+ mInOrder.verify(mWifiAwareStateManagerMock).disableUsage(true);
// 3. onStatusChange (ready/started) + available -> enableUsage
when(mHalDeviceManager.isStarted()).thenReturn(true);
mManagerStatusListenerCaptor.getValue().onStatusChanged();
mInOrder.verify(mWifiAwareStateManagerMock).tryToGetAwareCapability();
-
- mInOrder.verify(mHalDeviceManager, never()).createNanIface(any(), any(), any());
+ mInOrder.verify(mWifiNative, never()).createNanIface(any(), any(), any());
verifyNoMoreInteractions(mWifiAwareStateManagerMock, mWifiNanIfaceMock);
assertNull("Interface non-null!", mDut.getWifiNanIface());
}
@@ -139,8 +146,8 @@ public class WifiAwareNativeManagerTest extends WifiBaseTest {
// configure HalDeviceManager as ready/wifi started (and to return an interface if
// requested)
when(mHalDeviceManager.isStarted()).thenReturn(true);
- when(mHalDeviceManager.createNanIface(any(), any(), any()))
- .thenReturn(mWifiNanIfaceMock);
+ when(mWifiNative.createNanIface(any(), any(), any()))
+ .thenReturn(mWifiNativeNanIfaceMock);
// 1. onStatusChange (ready/started)
mManagerStatusListenerCaptor.getValue().onStatusChanged();
@@ -149,7 +156,7 @@ public class WifiAwareNativeManagerTest extends WifiBaseTest {
// 2. request (interface obtained)
mDut.tryToGetAware(TEST_WS);
- mInOrder.verify(mHalDeviceManager).createNanIface(mDestroyedListenerCaptor.capture(),
+ mInOrder.verify(mWifiNative).createNanIface(mDestroyedListenerCaptor.capture(),
any(), eq(TEST_WS));
mInOrder.verify(mWifiNanIfaceMock).registerFrameworkCallback(any());
mInOrder.verify(mWifiNanIfaceMock).enableVerboseLogging(anyBoolean());
@@ -158,13 +165,14 @@ public class WifiAwareNativeManagerTest extends WifiBaseTest {
// 3. release (interface released)
mDut.releaseAware();
mInOrder.verify(mHalDeviceManager).removeIface(mWifiNanIfaceMock);
+ mInOrder.verify(mWifiNative).teardownNanIface(anyInt());
assertNull("Interface non-null!", mDut.getWifiNanIface());
mDestroyedListenerCaptor.getValue().onDestroyed("nan0");
// 4. request (interface obtained)
mDut.tryToGetAware(TEST_WS);
- mInOrder.verify(mHalDeviceManager).createNanIface(mDestroyedListenerCaptor.capture(),
+ mInOrder.verify(mWifiNative).createNanIface(mDestroyedListenerCaptor.capture(),
any(), eq(TEST_WS));
mInOrder.verify(mWifiNanIfaceMock).registerFrameworkCallback(any());
mInOrder.verify(mWifiNanIfaceMock).enableVerboseLogging(anyBoolean());
@@ -181,12 +189,13 @@ public class WifiAwareNativeManagerTest extends WifiBaseTest {
// 7. release (interface released)
mDut.releaseAware();
mInOrder.verify(mHalDeviceManager).removeIface(mWifiNanIfaceMock);
+ mInOrder.verify(mWifiNative).teardownNanIface(anyInt());
assertNull("Interface non-null!", mDut.getWifiNanIface());
mDestroyedListenerCaptor.getValue().onDestroyed("nan0");
-
- mInOrder.verify(mHalDeviceManager, never()).createNanIface(any(), any(), any());
+ mInOrder.verify(mWifiNative, never()).createNanIface(any(), any(), any());
mInOrder.verify(mHalDeviceManager, never()).removeIface(any());
+ mInOrder.verify(mWifiNative, never()).teardownNanIface(anyInt());
verifyNoMoreInteractions(mWifiAwareStateManagerMock, mWifiNanIfaceMock);
}
@@ -198,8 +207,8 @@ public class WifiAwareNativeManagerTest extends WifiBaseTest {
// configure HalDeviceManager as ready/wifi started (and to return an interface if
// requested)
when(mHalDeviceManager.isStarted()).thenReturn(true);
- when(mHalDeviceManager.createNanIface(any(), any(), any()))
- .thenReturn(mWifiNanIfaceMock);
+ when(mWifiNative.createNanIface(any(), any(), any()))
+ .thenReturn(mWifiNativeNanIfaceMock);
// 1. onStatusChange (ready/started)
mManagerStatusListenerCaptor.getValue().onStatusChanged();
@@ -208,7 +217,7 @@ public class WifiAwareNativeManagerTest extends WifiBaseTest {
// 2. request (interface obtained)
mDut.tryToGetAware(TEST_WS);
- mInOrder.verify(mHalDeviceManager).createNanIface(mDestroyedListenerCaptor.capture(),
+ mInOrder.verify(mWifiNative).createNanIface(mDestroyedListenerCaptor.capture(),
any(), eq(TEST_WS));
mInOrder.verify(mWifiNanIfaceMock).registerFrameworkCallback(any());
mInOrder.verify(mWifiNanIfaceMock).enableVerboseLogging(anyBoolean());
@@ -223,8 +232,9 @@ public class WifiAwareNativeManagerTest extends WifiBaseTest {
// 4. a release doesn't do much
mDut.releaseAware();
- mInOrder.verify(mHalDeviceManager, never()).createNanIface(any(), any(), any());
+ mInOrder.verify(mWifiNative, never()).createNanIface(any(), any(), any());
mInOrder.verify(mHalDeviceManager, never()).removeIface(any());
+ mInOrder.verify(mWifiNative, never()).teardownNanIface(anyInt());
verifyNoMoreInteractions(mWifiAwareStateManagerMock, mWifiNanIfaceMock);
}
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareStateManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareStateManagerTest.java
index f1578311f0..51537dccda 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareStateManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/aware/WifiAwareStateManagerTest.java
@@ -16,10 +16,12 @@
package com.android.server.wifi.aware;
+import static android.hardware.wifi.NanStatusCode.FOLLOWUP_TX_QUEUE_FULL;
import static android.hardware.wifi.V1_0.NanRangingIndication.EGRESS_MET_MASK;
import static android.net.wifi.WifiAvailableChannel.OP_MODE_WIFI_AWARE;
import static android.net.wifi.aware.Characteristics.WIFI_AWARE_CIPHER_SUITE_NCS_PK_PASN_128;
+import static com.android.server.wifi.WifiSettingsConfigStore.D2D_ALLOWED_WHEN_INFRA_STA_DISABLED;
import static com.android.server.wifi.proto.WifiStatsLog.WIFI_AWARE_CAPABILITIES;
import static org.hamcrest.core.IsEqual.equalTo;
@@ -66,6 +68,7 @@ import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.wifi.IBooleanListener;
import android.net.wifi.OuiKeyedData;
+import android.net.wifi.ScanResult;
import android.net.wifi.WifiAvailableChannel;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiScanner;
@@ -105,12 +108,15 @@ import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
import com.android.modules.utils.build.SdkLevel;
import com.android.server.wifi.Clock;
+import com.android.server.wifi.DeviceConfigFacade;
import com.android.server.wifi.HalDeviceManager;
import com.android.server.wifi.InterfaceConflictManager;
import com.android.server.wifi.MockResources;
import com.android.server.wifi.WifiBaseTest;
+import com.android.server.wifi.WifiGlobals;
import com.android.server.wifi.WifiInjector;
import com.android.server.wifi.WifiNative;
+import com.android.server.wifi.WifiSettingsConfigStore;
import com.android.server.wifi.WifiThreadRunner;
import com.android.server.wifi.hal.WifiNanIface.NanRangingIndication;
import com.android.server.wifi.hal.WifiNanIface.NanStatusCode;
@@ -119,6 +125,7 @@ import com.android.server.wifi.util.NetdWrapper;
import com.android.server.wifi.util.WaitingState;
import com.android.server.wifi.util.WifiPermissionsUtil;
import com.android.server.wifi.util.WifiPermissionsWrapper;
+import com.android.wifi.flags.FeatureFlags;
import com.android.wifi.resources.R;
import org.junit.After;
@@ -176,6 +183,13 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
@Mock private WifiInjector mWifiInjector;
@Mock private PairingConfigManager mPairingConfigManager;
@Mock private StatsManager mStatsManager;
+ @Mock private DeviceConfigFacade mDeviceConfigFacade;
+ @Mock private FeatureFlags mFeatureFlags;
+ @Mock private WifiSettingsConfigStore mWifiSettingsConfigStore;
+ @Mock private WifiGlobals mWifiGlobals;
+ final ArgumentCaptor<WifiSettingsConfigStore.OnSettingsChangedListener>
+ mD2dAllowedSettingChangedListenerCaptor =
+ ArgumentCaptor.forClass(WifiSettingsConfigStore.OnSettingsChangedListener.class);
@Rule
public ErrorCollector collector = new ErrorCollector();
@@ -252,11 +266,18 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
WifiThreadRunner wifiThreadRunner = new WifiThreadRunner(wifiHandler);
when(mWifiInjector.getWifiNative()).thenReturn(mWifiNative);
when(mWifiInjector.getWifiThreadRunner()).thenReturn(wifiThreadRunner);
+ when(mWifiInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfigFacade);
+ when(mWifiInjector.getSettingsConfigStore()).thenReturn(mWifiSettingsConfigStore);
+ when(mWifiInjector.getWifiGlobals()).thenReturn(mWifiGlobals);
+ when(mDeviceConfigFacade.getFeatureFlags()).thenReturn(mFeatureFlags);
+ when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(true);
mDut = new WifiAwareStateManager(mWifiInjector, mPairingConfigManager);
mDut.setNative(mMockNativeManager, mMockNative);
mDut.start(mMockContext, mMockLooper.getLooper(), mAwareMetricsMock,
mWifiPermissionsUtil, mPermissionsWrapperMock, new Clock(),
mock(NetdWrapper.class), mInterfaceConflictManager);
+ verify(mMockContext, never()).registerReceiver(any(), any(IntentFilter.class), isNull(),
+ any(Handler.class));
mDut.startLate();
mDut.enableVerboseLogging(true, true, true);
mMockLooper.dispatchAll();
@@ -276,6 +297,10 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
mPowerBcastReceiver = bcastRxCaptor.getAllValues().get(0);
mLocationModeReceiver = bcastRxCaptor.getAllValues().get(1);
mWifiStateChangedReceiver = bcastRxCaptor.getAllValues().get(2);
+ verify(mWifiSettingsConfigStore).registerChangeListener(
+ eq(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED),
+ mD2dAllowedSettingChangedListenerCaptor.capture(),
+ any(Handler.class));
installMocksInStateManager(mDut, mMockAwareDataPathStatemanager);
ArgumentCaptor<Short> transactionId = ArgumentCaptor.forClass(Short.class);
@@ -1109,8 +1134,10 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
when(mWifiNative.getUsableChannels(WifiScanner.WIFI_BAND_5_GHZ, OP_MODE_WIFI_AWARE,
WifiAvailableChannel.FILTER_NAN_INSTANT_MODE))
.thenReturn(List.of(new WifiAvailableChannel(5220,
- WifiAvailableChannel.OP_MODE_WIFI_AWARE),
- new WifiAvailableChannel(5745, WifiAvailableChannel.OP_MODE_WIFI_AWARE)));
+ WifiAvailableChannel.OP_MODE_WIFI_AWARE,
+ ScanResult.CHANNEL_WIDTH_80MHZ),
+ new WifiAvailableChannel(5745, WifiAvailableChannel.OP_MODE_WIFI_AWARE,
+ ScanResult.CHANNEL_WIDTH_80MHZ)));
mActiveCountryCodeChangedCallback.onActiveCountryCodeChanged("US");
mMockLooper.dispatchAll();
inOrder.verify(mMockNative).enableAndConfigure(transactionId.capture(),
@@ -1196,7 +1223,7 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
when(mWifiNative.getUsableChannels(WifiScanner.WIFI_BAND_5_GHZ, OP_MODE_WIFI_AWARE,
WifiAvailableChannel.FILTER_NAN_INSTANT_MODE))
.thenReturn(List.of(new WifiAvailableChannel(5220,
- WifiAvailableChannel.OP_MODE_WIFI_AWARE)));
+ WifiAvailableChannel.OP_MODE_WIFI_AWARE, ScanResult.CHANNEL_WIDTH_80MHZ)));
mActiveCountryCodeChangedCallback.onActiveCountryCodeChanged("US");
mMockLooper.dispatchAll();
inOrder.verify(mMockNative).enableAndConfigure(transactionId.capture(),
@@ -1772,6 +1799,7 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
final String peerMsg = "some message from peer";
final int messageId = 6948;
final int messageId2 = 6949;
+ final int messageId3 = 6950;
final int rangeMin = 0;
final int rangeMax = 55;
final int rangedDistance = 30;
@@ -1888,6 +1916,22 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
validateInternalSendMessageQueuesCleanedUp(messageId2);
verify(mAwareMetricsMock, atLeastOnce()).reportAwareInstantModeEnabled(anyBoolean());
verifyNoMoreInteractions(mockCallback, mockSessionCallback, mMockNative, mAwareMetricsMock);
+
+ // (6) Send message but FW queue is full
+ mDut.sendMessage(uid, clientId, sessionId.getValue(), peerIdCaptor.getValue(),
+ ssi.getBytes(), messageId3, 0);
+ mMockLooper.dispatchAll();
+ inOrder.verify(mMockNative).sendMessage(transactionId.capture(), eq(subscribeId),
+ eq(requestorId), eq(peerMac), eq(ssi.getBytes()), eq(messageId3));
+ short tid3 = transactionId.getValue();
+ mDut.onMessageSendQueuedFailResponse(tid3, FOLLOWUP_TX_QUEUE_FULL);
+ mMockLooper.dispatchAll();
+ validateInternalSendMessageQueueBlocking(messageId3);
+
+ // (7) App disconnect
+ mDut.disconnect(clientId);
+ mMockLooper.dispatchAll();
+ validateInternalSendMessageQueuesCleanedUp(messageId3);
}
/**
@@ -3851,6 +3895,12 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
mMockLooper.dispatchAll();
// and same for other gating changes -> no changes
+ simulateD2dAllowedChange(false);
+ mMockLooper.dispatchAll();
+ simulateD2dAllowedChange(true);
+ mMockLooper.dispatchAll();
+
+ // and same for other gating changes -> no changes
simulateLocationModeChange(true);
simulateWifiStateChange(true);
mMockLooper.dispatchAll();
@@ -3920,6 +3970,12 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
simulateWifiStateChange(false);
mMockLooper.dispatchAll();
+ // and same for other gating changes -> no changes
+ simulateD2dAllowedChange(false);
+ mMockLooper.dispatchAll();
+ simulateD2dAllowedChange(true);
+ mMockLooper.dispatchAll();
+
// enable other gating feature -> no change
simulatePowerStateChangeDoze(false);
simulateWifiStateChange(true);
@@ -4037,7 +4093,8 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
assertTrue(mDut.isDeviceAttached());
inOrder.verify(mockCallback).onConnectSuccess(clientId);
- // (3) wifi state change: disable
+ // (3) wifi state change: disable & D2d disallowed
+ simulateD2dAllowedChange(false);
simulateWifiStateChange(false);
mMockLooper.dispatchAll();
inOrder.verify(mockCallback).onAttachTerminate();
@@ -4059,7 +4116,24 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
simulateLocationModeChange(true);
mMockLooper.dispatchAll();
- // (4) wifi state change: enable
+ // (4) wifi state change: disable & D2d allowed
+ simulateD2dAllowedChange(true);
+ mMockLooper.dispatchAll();
+ collector.checkThat("usage enabled", mDut.isUsageEnabled(), equalTo(true));
+ validateCorrectAwareStatusChangeBroadcast(inOrder);
+
+ // (5) wifi state change: disable & D2d disallowed
+ simulateD2dAllowedChange(false);
+ mMockLooper.dispatchAll();
+ validateCorrectAwareStatusChangeBroadcast(inOrder);
+ inOrder.verify(mMockNative).disable(transactionId.capture());
+ mDut.onDisableResponse(transactionId.getValue(), NanStatusCode.SUCCESS);
+ mMockLooper.dispatchAll();
+ inOrder.verify(mMockNativeManager).releaseAware();
+ assertFalse(mDut.isDeviceAttached());
+ collector.checkThat("usage disabled", mDut.isUsageEnabled(), equalTo(false));
+
+ // (6) wifi state change: enable
simulateWifiStateChange(true);
mMockLooper.dispatchAll();
collector.checkThat("usage enabled", mDut.isUsageEnabled(), equalTo(true));
@@ -5628,6 +5702,11 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
"mFwQueuedSendMessages");
field.setAccessible(true);
Map<Short, Message> fwQueuedSendMessages = (Map<Short, Message>) field.get(sm);
+ field = WifiAwareStateManager.WifiAwareStateMachine.class.getDeclaredField(
+ "mSendQueueBlocked");
+ field.setAccessible(true);
+ boolean sendQueueBlocked = field.getBoolean(sm);
+ assertFalse(sendQueueBlocked);
for (int i = 0; i < hostQueuedSendMessages.size(); ++i) {
Message msg = hostQueuedSendMessages.valueAt(i);
@@ -5647,6 +5726,45 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
}
}
+ private void validateInternalSendMessageQueueBlocking(int messageId) throws Exception {
+ Field field = WifiAwareStateManager.class.getDeclaredField("mSm");
+ field.setAccessible(true);
+ WifiAwareStateManager.WifiAwareStateMachine sm =
+ (WifiAwareStateManager.WifiAwareStateMachine) field.get(mDut);
+
+ field = WifiAwareStateManager.WifiAwareStateMachine.class.getDeclaredField(
+ "mHostQueuedSendMessages");
+ field.setAccessible(true);
+ SparseArray<Message> hostQueuedSendMessages = (SparseArray<Message>) field.get(sm);
+
+ field = WifiAwareStateManager.WifiAwareStateMachine.class.getDeclaredField(
+ "mFwQueuedSendMessages");
+ field.setAccessible(true);
+ Map<Short, Message> fwQueuedSendMessages = (Map<Short, Message>) field.get(sm);
+ field = WifiAwareStateManager.WifiAwareStateMachine.class.getDeclaredField(
+ "mSendQueueBlocked");
+ field.setAccessible(true);
+ boolean sendQueueBlocked = field.getBoolean(sm);
+ assertTrue(sendQueueBlocked);
+
+ for (int i = 0; i < hostQueuedSendMessages.size(); ++i) {
+ Message msg = hostQueuedSendMessages.valueAt(i);
+ if (msg.getData().getInt("message_id") == messageId) {
+ collector.checkThat(
+ "Message cleared-up from host queue. Message ID=" + messageId, msg,
+ notNullValue());
+ }
+ }
+
+ for (Message msg: fwQueuedSendMessages.values()) {
+ if (msg.getData().getInt("message_id") == messageId) {
+ collector.checkThat(
+ "Message not cleared-up from firmware queue. Message ID=" + messageId, msg,
+ nullValue());
+ }
+ }
+ }
+
/**
* Simulate power state change due to doze. Changes the power manager return values and
* dispatches a broadcast.
@@ -5694,6 +5812,14 @@ public class WifiAwareStateManagerTest extends WifiBaseTest {
mWifiStateChangedReceiver.onReceive(mMockContext, intent);
}
+ private void simulateD2dAllowedChange(boolean isD2dAllowed) {
+ when(mWifiGlobals.isD2dSupportedWhenInfraStaDisabled()).thenReturn(true);
+ when(mWifiSettingsConfigStore.get(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED))
+ .thenReturn(isD2dAllowed);
+ mD2dAllowedSettingChangedListenerCaptor.getValue()
+ .onSettingsChanged(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED, isD2dAllowed);
+ }
+
private static Capabilities getCapabilities() {
Capabilities cap = new Capabilities();
cap.maxConcurrentAwareClusters = 1;
diff --git a/service/tests/wifitests/src/com/android/server/wifi/b2b/WifiRoamingModeManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/b2b/WifiRoamingModeManagerTest.java
index e813423309..f4b7bfc212 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/b2b/WifiRoamingModeManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/b2b/WifiRoamingModeManagerTest.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-package com.android.server.wifi;
+package com.android.server.wifi.b2b;
import static org.junit.Assume.assumeTrue;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -30,7 +30,11 @@ import android.net.wifi.WifiSsid;
import androidx.test.filters.SmallTest;
import com.android.modules.utils.build.SdkLevel;
-import com.android.server.wifi.b2b.WifiRoamingModeManager;
+import com.android.server.wifi.ActiveModeWarden;
+import com.android.server.wifi.ClientModeManager;
+import com.android.server.wifi.WifiBaseTest;
+import com.android.server.wifi.WifiNative;
+import com.android.server.wifi.WifiRoamingConfigStore;
import org.junit.Before;
import org.junit.Test;
diff --git a/service/tests/wifitests/src/com/android/server/wifi/hal/WifiChipAidlImplTest.java b/service/tests/wifitests/src/com/android/server/wifi/hal/WifiChipAidlImplTest.java
index ff62b05bd7..8e65ef6ef9 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/hal/WifiChipAidlImplTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/hal/WifiChipAidlImplTest.java
@@ -16,6 +16,8 @@
package com.android.server.wifi.hal;
+import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
+
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -24,13 +26,17 @@ import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;
import android.content.Context;
import android.hardware.wifi.AfcChannelAllowance;
import android.hardware.wifi.IWifiChip;
+import android.hardware.wifi.IWifiChip.FeatureSetMask;
+import android.hardware.wifi.IWifiChip.VoipMode;
import android.hardware.wifi.WifiDebugHostWakeReasonRxIcmpPacketDetails;
import android.hardware.wifi.WifiDebugHostWakeReasonRxMulticastPacketDetails;
import android.hardware.wifi.WifiDebugHostWakeReasonRxPacketDetails;
@@ -49,12 +55,14 @@ import com.android.server.wifi.WifiBaseTest;
import com.android.server.wifi.WifiNative;
import com.android.server.wifi.WlanWakeReasonAndCounts;
+import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import org.mockito.MockitoSession;
import java.util.ArrayList;
import java.util.List;
@@ -62,6 +70,8 @@ import java.util.Random;
public class WifiChipAidlImplTest extends WifiBaseTest {
private WifiChipAidlImpl mDut;
+ private MockitoSession mSession;
+
@Mock private IWifiChip mIWifiChipMock;
@Mock private Context mContextMock;
@Mock private SsidTranslator mSsidTranslatorMock;
@@ -70,6 +80,14 @@ public class WifiChipAidlImplTest extends WifiBaseTest {
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mDut = new WifiChipAidlImpl(mIWifiChipMock, mContextMock, mSsidTranslatorMock);
+ mSession = mockitoSession()
+ .mockStatic(WifiHalAidlImpl.class)
+ .startMocking();
+ }
+
+ @After
+ public void tearDown() {
+ mSession.finishMocking();
}
@Test
@@ -436,4 +454,34 @@ public class WifiChipAidlImplTest extends WifiBaseTest {
return afcChannelAllowance;
}
+
+ /**
+ * Test that setVoipMode() results in calling into WifiChip
+ */
+ @Test
+ public void testVoipMode() throws Exception {
+ // Old Hal should not execute the call.
+ when(mIWifiChipMock.getFeatureSet()).thenReturn(FeatureSetMask.SET_VOIP_MODE);
+ lenient().when(WifiHalAidlImpl.isServiceVersionAtLeast(2))
+ .thenReturn(false);
+ // Update feature set to support VOIP.
+ mDut.getCapabilitiesAfterIfacesExist();
+ // Old Hal should not execute the call.
+ assertFalse(mDut.setVoipMode(VoipMode.VOICE));
+ assertFalse(mDut.setVoipMode(VoipMode.OFF));
+ verify(mIWifiChipMock, never()).setVoipMode(anyInt());
+ // Call HAL when hal is V2 or above.
+ lenient().when(WifiHalAidlImpl.isServiceVersionAtLeast(2))
+ .thenReturn(true);
+ assertTrue(mDut.setVoipMode(WifiChip.WIFI_VOIP_MODE_VOICE));
+ verify(mIWifiChipMock).setVoipMode(VoipMode.VOICE);
+ assertTrue(mDut.setVoipMode(VoipMode.OFF));
+ // Don't call HAL when feature is not supported
+ reset(mIWifiChipMock);
+ // Update feature set
+ mDut.getCapabilitiesAfterIfacesExist();
+ assertFalse(mDut.setVoipMode(VoipMode.VOICE));
+ assertFalse(mDut.setVoipMode(VoipMode.OFF));
+ verify(mIWifiChipMock, never()).setVoipMode(anyInt());
+ }
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/hal/WifiStaIfaceAidlImplTest.java b/service/tests/wifitests/src/com/android/server/wifi/hal/WifiStaIfaceAidlImplTest.java
index 95b978eb01..668e105e53 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/hal/WifiStaIfaceAidlImplTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/hal/WifiStaIfaceAidlImplTest.java
@@ -83,8 +83,8 @@ public class WifiStaIfaceAidlImplTest extends WifiBaseTest {
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
- mDut = new WifiStaIfaceAidlImpl(mIWifiStaIfaceMock, mContextMock, mSsidTranslatorMock);
when(mContextMock.getResources()).thenReturn(mResourcesMock);
+ mDut = new WifiStaIfaceAidlImpl(mIWifiStaIfaceMock, mContextMock, mSsidTranslatorMock);
}
/**
@@ -137,6 +137,7 @@ public class WifiStaIfaceAidlImplTest extends WifiBaseTest {
public void testTwoRadioStatsAggregation() throws Exception {
when(mResourcesMock.getBoolean(R.bool.config_wifiLinkLayerAllRadiosStatsAggregationEnabled))
.thenReturn(true);
+ mDut = new WifiStaIfaceAidlImpl(mIWifiStaIfaceMock, mContextMock, mSsidTranslatorMock);
Random r = new Random(245786856);
StaLinkLayerStats stats = new StaLinkLayerStats();
// Fill stats in two radios
diff --git a/service/tests/wifitests/src/com/android/server/wifi/hal/WifiStaIfaceHidlImplTest.java b/service/tests/wifitests/src/com/android/server/wifi/hal/WifiStaIfaceHidlImplTest.java
index b72bcde42d..d41ba3af2e 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/hal/WifiStaIfaceHidlImplTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/hal/WifiStaIfaceHidlImplTest.java
@@ -121,6 +121,7 @@ public class WifiStaIfaceHidlImplTest extends WifiBaseTest {
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
+ when(mContextMock.getResources()).thenReturn(mResourcesMock);
mDut = new WifiStaIfaceHidlImplSpy(0);
mWifiStatusSuccess = new WifiStatus();
@@ -131,8 +132,6 @@ public class WifiStaIfaceHidlImplTest extends WifiBaseTest {
mWifiStatusBusy = new WifiStatus();
mWifiStatusBusy.code = WifiStatusCode.ERROR_BUSY;
mWifiStatusBusy.description = "Don't bother me, kid";
-
- when(mContextMock.getResources()).thenReturn(mResourcesMock);
}
/**
@@ -616,6 +615,7 @@ public class WifiStaIfaceHidlImplTest extends WifiBaseTest {
public void testTwoRadioStatsAggregation_1_3() throws Exception {
when(mResourcesMock.getBoolean(R.bool.config_wifiLinkLayerAllRadiosStatsAggregationEnabled))
.thenReturn(true);
+ mDut = new WifiStaIfaceHidlImplSpy(0);
Random r = new Random(245786856);
android.hardware.wifi.V1_3.StaLinkLayerStats stats =
new android.hardware.wifi.V1_3.StaLinkLayerStats();
@@ -661,6 +661,7 @@ public class WifiStaIfaceHidlImplTest extends WifiBaseTest {
public void testTwoRadioStatsAggregation_1_5() throws Exception {
when(mResourcesMock.getBoolean(R.bool.config_wifiLinkLayerAllRadiosStatsAggregationEnabled))
.thenReturn(true);
+ mDut = new WifiStaIfaceHidlImplSpy(0);
Random r = new Random(245786856);
android.hardware.wifi.V1_5.StaLinkLayerStats stats =
new android.hardware.wifi.V1_5.StaLinkLayerStats();
diff --git a/service/tests/wifitests/src/com/android/server/wifi/hotspot2/ANQPRequestManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/hotspot2/ANQPRequestManagerTest.java
index 731df4d8a6..748cae1dd5 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/hotspot2/ANQPRequestManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/hotspot2/ANQPRequestManagerTest.java
@@ -19,7 +19,6 @@ package com.android.server.wifi.hotspot2;
import static com.android.server.wifi.hotspot2.ANQPRequestManager.ANQP_REQUEST_ALARM_TAG;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.anyLong;
@@ -128,8 +127,6 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
mAlarmManager = new TestAlarmManager();
when(mWifiInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfigFacade);
when(mWifiInjector.getAlarmManager()).thenReturn(mAlarmManager.getAlarmManager());
- when(mDeviceConfigFacade.getFeatureFlags()).thenReturn(mFeatureFlags);
- when(mFeatureFlags.anqpRequestWaitForResponse()).thenReturn(false);
mManager = new ANQPRequestManager(mHandler, mClock, mWifiInjector,
new Handler(mLooper.getLooper()));
}
@@ -144,8 +141,9 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
@Test
public void requestR1ANQPElementsWithoutRC() throws Exception {
when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(true);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
+ verify(mHandler).requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC);
}
/**
@@ -160,6 +158,7 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITH_RC)).thenReturn(true);
mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, true,
NetworkDetail.HSRelease.R1);
+ verify(mHandler).requestANQP(TEST_BSSID, R1_ANQP_WITH_RC);
}
/**
@@ -172,8 +171,9 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
@Test
public void requestR1R2ANQPElementsWithoutRC() throws Exception {
when(mHandler.requestANQP(TEST_BSSID, R1R2_ANQP_WITHOUT_RC)).thenReturn(true);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R2));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R2);
+ verify(mHandler).requestANQP(TEST_BSSID, R1R2_ANQP_WITHOUT_RC);
}
/**
@@ -186,40 +186,9 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
@Test
public void requestR1R2ANQPElementsWithRC() throws Exception {
when(mHandler.requestANQP(TEST_BSSID, R1R2_ANQP_WITH_RC)).thenReturn(true);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, true,
- NetworkDetail.HSRelease.R2));
- }
-
- /**
- * Verify that attempt to request ANQP elements from an AP will fail when there is a request
- * already pending. The request will succeed when the hold off time is up.
- *
- * @throws Exception
- */
- @Test
- public void requestANQPElementsWithPendingRequest() throws Exception {
- // Send the initial request.
- long startTime = 0;
- when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(true);
- when(mClock.getElapsedSinceBootMillis()).thenReturn(startTime);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
- reset(mHandler);
-
- // Attempt another request will fail while one is still pending and hold off time is not up
- // yet.
- when(mClock.getElapsedSinceBootMillis()).thenReturn(startTime + 1);
- assertFalse(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
- verify(mHandler, never()).requestANQP(anyLong(), anyObject());
- reset(mHandler);
-
- // Attempt other request will succeed after the hold off time is up.
- when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(true);
- when(mClock.getElapsedSinceBootMillis())
- .thenReturn(startTime + ANQPRequestManager.BASE_HOLDOFF_TIME_MILLISECONDS);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, true,
+ NetworkDetail.HSRelease.R2);
+ verify(mHandler).requestANQP(TEST_BSSID, R1R2_ANQP_WITH_RC);
}
/**
@@ -234,15 +203,17 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
long startTime = 0;
when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(false);
when(mClock.getElapsedSinceBootMillis()).thenReturn(startTime);
- assertFalse(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
+ verify(mHandler).requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC);
reset(mHandler);
// Verify that new request is not being held off after previous send failure.
when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(true);
when(mClock.getElapsedSinceBootMillis()).thenReturn(startTime);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
+ verify(mHandler).requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC);
}
/**
@@ -257,8 +228,9 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
long startTime = 0;
when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(true);
when(mClock.getElapsedSinceBootMillis()).thenReturn(startTime);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
+ verify(mHandler).requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC);
reset(mHandler);
// Request completed with success. Verify that the key associated with the request
@@ -267,8 +239,9 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(true);
when(mClock.getElapsedSinceBootMillis()).thenReturn(startTime + 1);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
+ verify(mHandler).requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC);
}
/**
@@ -284,8 +257,9 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
long startTime = 0;
when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(true);
when(mClock.getElapsedSinceBootMillis()).thenReturn(startTime);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
+ verify(mHandler).requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC);
reset(mHandler);
// Request completed with failure. Verify that the key associated with the request
@@ -294,16 +268,17 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
// Attempt another request will fail since the hold off time is not up yet.
when(mClock.getElapsedSinceBootMillis()).thenReturn(startTime + 1);
- assertFalse(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
verify(mHandler, never()).requestANQP(anyLong(), anyObject());
// Attempt another request will succeed after the hold off time is up.
when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(true);
when(mClock.getElapsedSinceBootMillis())
.thenReturn(startTime + ANQPRequestManager.BASE_HOLDOFF_TIME_MILLISECONDS);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
+ verify(mHandler).requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC);
}
/**
@@ -319,9 +294,11 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
// Initial request.
when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(true);
when(mClock.getElapsedSinceBootMillis()).thenReturn(currentTime);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
+ verify(mHandler).requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC);
reset(mHandler);
+ mManager.onRequestCompleted(TEST_BSSID, false);
// Sending the request with the hold off time based on the current hold off count.
for (int i = 0; i <= ANQPRequestManager.MAX_HOLDOFF_COUNT; i++) {
@@ -330,17 +307,19 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
// Request will fail before the hold off time is up.
when(mClock.getElapsedSinceBootMillis()).thenReturn(currentTime);
- assertFalse(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
verify(mHandler, never()).requestANQP(anyLong(), anyObject());
// Request will succeed when the hold off time is up.
currentTime += 1;
when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(true);
when(mClock.getElapsedSinceBootMillis()).thenReturn(currentTime);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
+ verify(mHandler).requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC);
reset(mHandler);
+ mManager.onRequestCompleted(TEST_BSSID, false);
}
// Verify that the hold off time is max out at the maximum hold off count.
@@ -348,15 +327,16 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
* (1 << ANQPRequestManager.MAX_HOLDOFF_COUNT) - 1);
when(mClock.getElapsedSinceBootMillis()).thenReturn(currentTime);
- assertFalse(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
verify(mHandler, never()).requestANQP(anyLong(), anyObject());
currentTime += 1;
when(mHandler.requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC)).thenReturn(true);
when(mClock.getElapsedSinceBootMillis()).thenReturn(currentTime);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R1));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R1);
+ verify(mHandler).requestANQP(TEST_BSSID, R1_ANQP_WITHOUT_RC);
reset(mHandler);
}
@@ -370,8 +350,9 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
@Test
public void requestR1R2ANQPElementsWithoutRCForR3() throws Exception {
when(mHandler.requestANQP(TEST_BSSID, R1R2_ANQP_WITHOUT_RC)).thenReturn(true);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
- NetworkDetail.HSRelease.R3));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, false,
+ NetworkDetail.HSRelease.R3);
+ verify(mHandler).requestANQP(TEST_BSSID, R1R2_ANQP_WITHOUT_RC);
}
/**
@@ -384,8 +365,9 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
@Test
public void requestR1R2ANQPElementsWithRCForR3() throws Exception {
when(mHandler.requestANQP(TEST_BSSID, R1R2_ANQP_WITH_RC)).thenReturn(true);
- assertTrue(mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, true,
- NetworkDetail.HSRelease.R3));
+ mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, true,
+ NetworkDetail.HSRelease.R3);
+ verify(mHandler).requestANQP(TEST_BSSID, R1R2_ANQP_WITH_RC);
}
/**
@@ -401,7 +383,6 @@ public class ANQPRequestManagerTest extends WifiBaseTest {
@Test
public void testWaitResponseEnabled() {
- when(mFeatureFlags.anqpRequestWaitForResponse()).thenReturn(true);
when(mHandler.requestANQP(anyLong(), any())).thenReturn(true);
mManager.requestANQPElements(TEST_BSSID, TEST_ANQP_KEY, true,
NetworkDetail.HSRelease.R3);
diff --git a/service/tests/wifitests/src/com/android/server/wifi/hotspot2/PasspointManagerTest.java b/service/tests/wifitests/src/com/android/server/wifi/hotspot2/PasspointManagerTest.java
index 1aa5c1c659..24e18e2697 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/hotspot2/PasspointManagerTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/hotspot2/PasspointManagerTest.java
@@ -680,7 +680,7 @@ public class PasspointManagerTest extends WifiBaseTest {
* 1 from |removeProvider| + 2 from |setAutojoinEnabled| + 2 from
* |enableMacRandomization| + 2 from |setMeteredOverride| = 7 calls to |saveToStore|
*/
- verify(mWifiConfigManager, times(7)).saveToStore(true);
+ verify(mWifiConfigManager, times(7)).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderUninstallation();
verify(mWifiMetrics).incrementNumPasspointProviderUninstallSuccess();
verify(mAppOpsManager).stopWatchingMode(any(AppOpsManager.OnOpChangedListener.class));
@@ -802,7 +802,7 @@ public class PasspointManagerTest extends WifiBaseTest {
assertTrue(mManager.addOrUpdateProvider(config, TEST_CREATOR_UID, TEST_PACKAGE,
false, true, false));
verifyInstalledConfig(config);
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderInstallation();
verify(mWifiMetrics).incrementNumPasspointProviderInstallSuccess();
reset(mWifiMetrics);
@@ -820,7 +820,7 @@ public class PasspointManagerTest extends WifiBaseTest {
verify(provider).uninstallCertsAndKeys();
verify(mWifiConfigManager).removePasspointConfiguredNetwork(
provider.getWifiConfig().getProfileKey());
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderUninstallation();
verify(mWifiMetrics).incrementNumPasspointProviderUninstallSuccess();
assertTrue(mManager.getProviderConfigs(TEST_UID, true).isEmpty());
@@ -887,7 +887,7 @@ public class PasspointManagerTest extends WifiBaseTest {
assertTrue(mManager.addOrUpdateProvider(origConfig, TEST_CREATOR_UID, TEST_PACKAGE,
false, true, false));
verifyInstalledConfig(origConfig);
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderInstallation();
verify(mWifiMetrics).incrementNumPasspointProviderInstallSuccess();
verify(origProvider, never()).setUserConnectChoice(any(), anyInt());
@@ -921,7 +921,7 @@ public class PasspointManagerTest extends WifiBaseTest {
argThat((c) -> c.FQDN.equals(TEST_FQDN)), eq(TEST_CREATOR_UID), eq(TEST_PACKAGE),
eq(false));
verify(mWifiConfigManager).allowAutojoin(TEST_NETWORK_ID, origWifiConfig.allowAutojoin);
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderInstallation();
verify(mWifiMetrics).incrementNumPasspointProviderInstallSuccess();
assertEquals(2, mSharedDataSource.getProviderIndex());
@@ -950,7 +950,7 @@ public class PasspointManagerTest extends WifiBaseTest {
assertTrue(installedConfigs.contains(origConfig));
assertTrue(installedConfigs.contains(newConfig));
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderInstallation();
verify(mWifiMetrics).incrementNumPasspointProviderInstallSuccess();
@@ -1207,7 +1207,7 @@ public class PasspointManagerTest extends WifiBaseTest {
List<Pair<PasspointProvider, PasspointMatch>> matchedProviders =
mManager.getAllMatchedProviders(createTestScanResult());
- verify(mWifiConfigManager).saveToStore(eq(true));
+ verify(mWifiConfigManager).saveToStore();
} finally {
session.finishMocking();
@@ -2029,7 +2029,7 @@ public class PasspointManagerTest extends WifiBaseTest {
assertTrue(mManager.addOrUpdateProvider(config, TEST_CREATOR_UID, TEST_PACKAGE,
false, true, false));
verifyInstalledConfig(config);
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderInstallation();
verify(mWifiMetrics).incrementNumPasspointProviderInstallSuccess();
reset(mWifiMetrics);
@@ -2043,7 +2043,7 @@ public class PasspointManagerTest extends WifiBaseTest {
// Remove the provider as a non-privileged non-creator app.
assertFalse(mManager.removeProvider(TEST_UID, false, null, TEST_FQDN));
verify(provider, never()).uninstallCertsAndKeys();
- verify(mWifiConfigManager, never()).saveToStore(true);
+ verify(mWifiConfigManager, never()).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderUninstallation();
verify(mWifiMetrics, never()).incrementNumPasspointProviderUninstallSuccess();
@@ -2115,7 +2115,7 @@ public class PasspointManagerTest extends WifiBaseTest {
verify(provider, never()).uninstallCertsAndKeys();
verify(mWifiConfigManager, never()).removePasspointConfiguredNetwork(
provider.getWifiConfig().getProfileKey());
- verify(mWifiConfigManager, never()).saveToStore(true);
+ verify(mWifiConfigManager, never()).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderUninstallation();
verify(mWifiMetrics, never()).incrementNumPasspointProviderUninstallSuccess();
verify(mAppOpsManager, never()).stopWatchingMode(
@@ -2134,7 +2134,7 @@ public class PasspointManagerTest extends WifiBaseTest {
verify(provider).uninstallCertsAndKeys();
verify(mWifiConfigManager, never()).removePasspointConfiguredNetwork(
provider.getWifiConfig().getProfileKey());
- verify(mWifiConfigManager, never()).saveToStore(true);
+ verify(mWifiConfigManager, never()).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderUninstallation();
verify(mWifiMetrics).incrementNumPasspointProviderUninstallSuccess();
verify(mAppOpsManager, never()).stopWatchingMode(
@@ -2196,7 +2196,7 @@ public class PasspointManagerTest extends WifiBaseTest {
argThat((c) -> c.FQDN.equals(TEST_FQDN)), eq(TEST_CREATOR_UID), eq(TEST_PACKAGE),
eq(false));
verify(mWifiConfigManager).allowAutojoin(TEST_NETWORK_ID, origWifiConfig.allowAutojoin);
- verify(mWifiConfigManager, never()).saveToStore(true);
+ verify(mWifiConfigManager, never()).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderInstallation();
verify(mWifiMetrics).incrementNumPasspointProviderInstallSuccess();
assertEquals(2, mSharedDataSource.getProviderIndex());
@@ -2215,7 +2215,7 @@ public class PasspointManagerTest extends WifiBaseTest {
eq(true), eq(mClock))).thenReturn(newProvider);
assertTrue(mManager.addOrUpdateProvider(newConfig, TEST_CREATOR_UID, TEST_PACKAGE,
true, true, false));
- verify(mWifiConfigManager, never()).saveToStore(true);
+ verify(mWifiConfigManager, never()).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderInstallation();
verify(mWifiMetrics).incrementNumPasspointProviderInstallSuccess();
@@ -2269,7 +2269,7 @@ public class PasspointManagerTest extends WifiBaseTest {
eq(false), eq(mClock))).thenReturn(newProvider);
assertTrue(mManager.addOrUpdateProvider(newConfig, TEST_CREATOR_UID, TEST_PACKAGE,
false, true, false));
- verify(mWifiConfigManager).saveToStore(true);
+ verify(mWifiConfigManager).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderInstallation();
verify(mWifiMetrics).incrementNumPasspointProviderInstallSuccess();
@@ -2326,7 +2326,7 @@ public class PasspointManagerTest extends WifiBaseTest {
eq(true), eq(mClock))).thenReturn(newProvider);
assertTrue(mManager.addOrUpdateProvider(newConfig, TEST_CREATOR_UID, TEST_PACKAGE1, true,
true, false));
- verify(mWifiConfigManager, never()).saveToStore(true);
+ verify(mWifiConfigManager, never()).saveToStore();
verify(mWifiMetrics).incrementNumPasspointProviderInstallation();
verify(mWifiMetrics).incrementNumPasspointProviderInstallSuccess();
@@ -2820,7 +2820,7 @@ public class PasspointManagerTest extends WifiBaseTest {
mManager.resetSimPasspointNetwork();
verify(provider).setAnonymousIdentity(null);
- verify(mWifiConfigManager, times(3)).saveToStore(true);
+ verify(mWifiConfigManager, times(3)).saveToStore();
}
/**
@@ -2863,13 +2863,13 @@ public class PasspointManagerTest extends WifiBaseTest {
verify(provider, times(2)).setUserConnectChoice(null, 0);
verify(provider2, never()).setUserConnectChoice(any(), anyInt());
- verify(mWifiConfigManager, times(3)).saveToStore(true);
+ verify(mWifiConfigManager, times(3)).saveToStore();
reset(mWifiConfigManager);
when(provider.getConnectChoice()).thenReturn(null);
listener.onConnectChoiceRemoved(USER_CONNECT_CHOICE);
listener.onConnectChoiceRemoved(null);
- verify(mWifiConfigManager, never()).saveToStore(anyBoolean());
+ verify(mWifiConfigManager, never()).saveToStore();
}
/*
diff --git a/service/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackAidlImplTest.java b/service/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackAidlImplTest.java
index 208a01b912..df9120d06b 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackAidlImplTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackAidlImplTest.java
@@ -934,6 +934,8 @@ public class SupplicantP2pIfaceCallbackAidlImplTest extends WifiBaseTest {
ArgumentCaptor.forClass(WifiP2pDevice.class);
mDut.onStaAuthorized(mDeviceAddress1Bytes, mDeviceAddress2Bytes);
verify(mMonitor).broadcastP2pApStaConnected(any(String.class), p2pDeviceCaptor.capture());
+ assertEquals(MacAddress.fromBytes(mDeviceAddress1Bytes),
+ p2pDeviceCaptor.getValue().getInterfaceMacAddress());
assertEquals(mDeviceAddress2String, p2pDeviceCaptor.getValue().deviceAddress);
}
@@ -948,6 +950,8 @@ public class SupplicantP2pIfaceCallbackAidlImplTest extends WifiBaseTest {
ArgumentCaptor.forClass(WifiP2pDevice.class);
mDut.onStaAuthorized(mDeviceAddress1Bytes, NativeUtil.ANY_MAC_BYTES);
verify(mMonitor).broadcastP2pApStaConnected(any(String.class), p2pDeviceCaptor.capture());
+ assertEquals(MacAddress.fromBytes(mDeviceAddress1Bytes),
+ p2pDeviceCaptor.getValue().getInterfaceMacAddress());
assertEquals(mDeviceAddress1String, p2pDeviceCaptor.getValue().deviceAddress);
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackHidlImplTest.java b/service/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackHidlImplTest.java
index dca52eb615..916fc5afaf 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackHidlImplTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/p2p/SupplicantP2pIfaceCallbackHidlImplTest.java
@@ -31,6 +31,7 @@ import android.app.test.MockAnswerUtil.AnswerWithArguments;
import android.hardware.wifi.supplicant.V1_0.ISupplicantP2pIfaceCallback;
import android.hardware.wifi.supplicant.V1_0.ISupplicantP2pIfaceCallback.P2pStatusCode;
import android.hardware.wifi.supplicant.V1_0.WpsConfigMethods;
+import android.net.MacAddress;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
@@ -542,6 +543,8 @@ public class SupplicantP2pIfaceCallbackHidlImplTest extends WifiBaseTest {
ArgumentCaptor.forClass(WifiP2pDevice.class);
mDut.onStaAuthorized(mDeviceAddress1Bytes, mDeviceAddress2Bytes);
verify(mMonitor).broadcastP2pApStaConnected(any(String.class), p2pDeviceCaptor.capture());
+ assertEquals(MacAddress.fromBytes(mDeviceAddress1Bytes),
+ p2pDeviceCaptor.getValue().getInterfaceMacAddress());
assertEquals(mDeviceAddress2String, p2pDeviceCaptor.getValue().deviceAddress);
}
@@ -556,6 +559,8 @@ public class SupplicantP2pIfaceCallbackHidlImplTest extends WifiBaseTest {
ArgumentCaptor.forClass(WifiP2pDevice.class);
mDut.onStaAuthorized(mDeviceAddress1Bytes, NativeUtil.ANY_MAC_BYTES);
verify(mMonitor).broadcastP2pApStaConnected(any(String.class), p2pDeviceCaptor.capture());
+ assertEquals(MacAddress.fromBytes(mDeviceAddress1Bytes),
+ p2pDeviceCaptor.getValue().getInterfaceMacAddress());
assertEquals(mDeviceAddress1String, p2pDeviceCaptor.getValue().deviceAddress);
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pMetricsTest.java b/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pMetricsTest.java
index 454576c67e..b386fc4add 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pMetricsTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pMetricsTest.java
@@ -90,7 +90,7 @@ public class WifiP2pMetricsTest extends WifiBaseTest {
// Start and end Connection event.
mWifiP2pMetrics.startConnectionEvent(P2pConnectionEvent.CONNECTION_FRESH, null,
- GroupEvent.GROUP_OWNER, 2000);
+ GroupEvent.GROUP_OWNER, 2000, "nc");
assertTrue(mWifiP2pMetrics.hasOngoingConnection());
when(mClock.getElapsedSinceBootMillis()).thenReturn(1000L);
mWifiP2pMetrics.endConnectionEvent(P2pConnectionEvent.CLF_NONE);
@@ -104,13 +104,13 @@ public class WifiP2pMetricsTest extends WifiBaseTest {
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__FAILURE_CODE__NONE,
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__GROUP_ROLE__GROUP_OWNER,
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__BAND__BAND_UNKNOWN,
- 0, 0, 2000, true, false, 1));
+ 0, 0, 2000, true, false, 1, "nc"));
// Start and end Connection event.
config.groupOwnerBand = 5210;
when(mWifiInfo.getFrequency()).thenReturn(2412);
mWifiP2pMetrics.startConnectionEvent(P2pConnectionEvent.CONNECTION_FRESH, config,
- GroupEvent.GROUP_OWNER, 2014);
+ GroupEvent.GROUP_OWNER, 2014, "nc");
mWifiP2pMetrics.setFallbackToNegotiationOnInviteStatusInfoUnavailable();
when(mClock.getElapsedSinceBootMillis()).thenReturn(3000L);
mWifiP2pMetrics.setIsCountryCodeWorldMode(false);
@@ -124,7 +124,7 @@ public class WifiP2pMetricsTest extends WifiBaseTest {
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__FAILURE_CODE__NONE,
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__GROUP_ROLE__GROUP_OWNER,
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__BAND__BAND_FREQUENCY,
- 5210, 2412, 2014, false, true, 1));
+ 5210, 2412, 2014, false, true, 1, "nc"));
// End Connection event without starting one.
// this would create a new connection event immediately.
@@ -135,14 +135,14 @@ public class WifiP2pMetricsTest extends WifiBaseTest {
// Start two ConnectionEvents in a row.
// The current active un-ended connection event is excluded.
mWifiP2pMetrics.startConnectionEvent(P2pConnectionEvent.CONNECTION_REINVOKE, config,
- GroupEvent.GROUP_OWNER, Process.SYSTEM_UID);
+ GroupEvent.GROUP_OWNER, Process.SYSTEM_UID, null);
stats = mWifiP2pMetrics.consolidateProto();
assertEquals(3, stats.connectionEvent.length);
// The last un-ended connection is ended.
// The current active un-ended connection event is excluded.
mWifiP2pMetrics.startConnectionEvent(P2pConnectionEvent.CONNECTION_REINVOKE, config,
- GroupEvent.GROUP_OWNER, Process.SYSTEM_UID);
+ GroupEvent.GROUP_OWNER, Process.SYSTEM_UID, null);
stats = mWifiP2pMetrics.consolidateProto();
assertEquals(4, stats.connectionEvent.length);
}
@@ -369,7 +369,7 @@ public class WifiP2pMetricsTest extends WifiBaseTest {
config.groupOwnerBand = WifiP2pConfig.GROUP_OWNER_BAND_5GHZ;
when(mClock.getElapsedSinceBootMillis()).thenReturn(0L);
mWifiP2pMetrics.startConnectionEvent(P2pConnectionEvent.CONNECTION_FAST, config,
- GroupEvent.GROUP_CLIENT, 2000);
+ GroupEvent.GROUP_CLIENT, 2000, "nc");
when(mClock.getElapsedSinceBootMillis()).thenReturn(1000L);
mWifiP2pMetrics.endConnectionEvent(P2pConnectionEvent.CLF_TIMEOUT);
mWifiP2pMetrics.consolidateProto();
@@ -380,11 +380,11 @@ public class WifiP2pMetricsTest extends WifiBaseTest {
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__FAILURE_CODE__TIMEOUT,
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__GROUP_ROLE__GROUP_CLIENT,
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__BAND__BAND_5G,
- 0, 0, 2000, true, false, 1));
+ 0, 0, 2000, true, false, 1, "nc"));
when(mClock.getElapsedSinceBootMillis()).thenReturn(29000L);
mWifiP2pMetrics.startConnectionEvent(P2pConnectionEvent.CONNECTION_FAST, config,
- GroupEvent.GROUP_CLIENT, 2000);
+ GroupEvent.GROUP_CLIENT, 2000, "nb");
when(mClock.getElapsedSinceBootMillis()).thenReturn(31000L);
mWifiP2pMetrics.endConnectionEvent(P2pConnectionEvent.CLF_TIMEOUT);
mWifiP2pMetrics.consolidateProto();
@@ -395,11 +395,11 @@ public class WifiP2pMetricsTest extends WifiBaseTest {
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__FAILURE_CODE__TIMEOUT,
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__GROUP_ROLE__GROUP_CLIENT,
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__BAND__BAND_5G,
- 0, 0, 2000, true, false, 2));
+ 0, 0, 2000, true, false, 2, "nb"));
when(mClock.getElapsedSinceBootMillis()).thenReturn(60000L);
mWifiP2pMetrics.startConnectionEvent(P2pConnectionEvent.CONNECTION_FAST, config,
- GroupEvent.GROUP_CLIENT, 2000);
+ GroupEvent.GROUP_CLIENT, 2000, "nc");
when(mClock.getElapsedSinceBootMillis()).thenReturn(63000L);
mWifiP2pMetrics.endConnectionEvent(P2pConnectionEvent.CLF_NONE);
mWifiP2pMetrics.consolidateProto();
@@ -410,6 +410,6 @@ public class WifiP2pMetricsTest extends WifiBaseTest {
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__FAILURE_CODE__NONE,
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__GROUP_ROLE__GROUP_CLIENT,
WifiStatsLog.WIFI_P2P_CONNECTION_REPORTED__BAND__BAND_5G,
- 0, 0, 2000, true, false, 1));
+ 0, 0, 2000, true, false, 1, "nc"));
}
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pNativeInterfaceManagementTest.java b/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pNativeInterfaceManagementTest.java
index 694c6901fa..7080a1d6a5 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pNativeInterfaceManagementTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pNativeInterfaceManagementTest.java
@@ -108,7 +108,6 @@ public class WifiP2pNativeInterfaceManagementTest extends WifiBaseTest {
.thenReturn(TEST_P2P_IFACE_NAME);
when(mWifiInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfigFacade);
when(mDeviceConfigFacade.getFeatureFlags()).thenReturn(mFeatureFlags);
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(true);
mWifiP2pNative = new WifiP2pNative(mWifiNl80211Manager, mWifiNative, mWifiMetrics,
mWifiVendorHal, mSupplicantP2pIfaceHal, mHalDeviceManager, mPropertyService,
mWifiInjector);
@@ -118,15 +117,6 @@ public class WifiP2pNativeInterfaceManagementTest extends WifiBaseTest {
* Verifies the setup of a p2p interface.
*/
@Test
- public void testSetUpInterfaceByHDM() throws Exception {
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(false);
- testSetUpInterface(false);
- }
-
- /**
- * Verifies the setup of a p2p interface.
- */
- @Test
public void testSetUpInterfaceByWifiNative() throws Exception {
testSetUpInterface(true);
}
@@ -169,15 +159,6 @@ public class WifiP2pNativeInterfaceManagementTest extends WifiBaseTest {
* Verifies the teardown of a p2p interface.
*/
@Test
- public void testTeardownInterfaceWhenD2dWithoutSTADisabled() throws Exception {
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(false);
- testTeardownInterface(false);
- }
-
- /**
- * Verifies the teardown of a p2p interface.
- */
- @Test
public void testTeardownInterface() throws Exception {
testTeardownInterface(true);
}
@@ -202,14 +183,6 @@ public class WifiP2pNativeInterfaceManagementTest extends WifiBaseTest {
public void testTeardownInterfaceWithNoVendorHalWhenD2dAloneFeatureEnabled() throws Exception {
testTeardownInterfaceWithNoVendorHal(true);
}
- /**
- * Verifies the teardown of a p2p interface with no HAL (HIDL) support.
- */
- @Test
- public void testTeardownInterfaceWithNoVendorHalD2dAloneFeatureDisabled() throws Exception {
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(false);
- testTeardownInterfaceWithNoVendorHal(false);
- }
private void testTeardownInterfaceWithNoVendorHal(boolean isD2dAloneFeatureEnabled)
throws Exception {
diff --git a/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pNativeTest.java b/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pNativeTest.java
index e70588f5bd..d27157087e 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pNativeTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pNativeTest.java
@@ -140,7 +140,6 @@ public class WifiP2pNativeTest extends WifiBaseTest {
mWifiClientInterfaceNames.add("wlan1");
when(mWifiInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfigFacade);
when(mDeviceConfigFacade.getFeatureFlags()).thenReturn(mFeatureFlags);
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(true);
mWifiP2pNative = new WifiP2pNative(mWifiCondManager, mWifiNative, mWifiMetrics,
mWifiVendorHalMock, mSupplicantP2pIfaceHalMock, mHalDeviceManagerMock,
mPropertyServiceMock, mWifiInjector);
@@ -189,30 +188,11 @@ public class WifiP2pNativeTest extends WifiBaseTest {
}
/**
- * Verifies that setupInterface by calling HalDeviceManager returns correct values
- * when successfully creating P2P Iface. (Old design, feature is disabled)
- */
- @Test
- public void testSetupInterfaceByHDMSuccessInCreatingP2pIface() {
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(false);
- testSetupInterfaceSuccessInCreatingP2pIface(false);
- }
-
- /**
* Verifies that setupInterface by WifiNative returns correct values
* when successfully creating P2P Iface. (The default behavior)
*/
@Test
public void testSetupInterfaceByWifiNativeSuccessInCreatingP2pIface() {
- testSetupInterfaceSuccessInCreatingP2pIface(true);
- }
-
- private void testSetupInterfaceSuccessInCreatingP2pIface(boolean isD2dAloneFeatureEnabled) {
- if (!isD2dAloneFeatureEnabled) {
- when(mHalDeviceManagerMock.createP2pIface(
- any(HalDeviceManager.InterfaceDestroyedListener.class),
- eq(mHandlerMock), eq(mWorkSourceMock))).thenReturn(TEST_IFACE);
- }
when(mSupplicantP2pIfaceHalMock.initialize()).thenReturn(true);
when(mSupplicantP2pIfaceHalMock.isInitializationComplete()).thenReturn(true);
when(mSupplicantP2pIfaceHalMock.setupIface(eq(TEST_IFACE))).thenReturn(true);
@@ -244,33 +224,13 @@ public class WifiP2pNativeTest extends WifiBaseTest {
/**
* Verifies that setupInterface returns correct values when failing in creating P2P Iface
- * by HDM.
- */
- @Test
- public void testSetupInterfaceFailureInCreatingP2pIfaceByHDM() {
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(false);
- testSetupInterfaceFailureInCreatingP2pIface(false);
- }
-
- /**
- * Verifies that setupInterface returns correct values when failing in creating P2P Iface
* by WifiNative.
*/
@Test
public void testSetupInterfaceFailureInCreatingP2pIfaceByWifiNative() {
- testSetupInterfaceFailureInCreatingP2pIface(true);
- }
-
- private void testSetupInterfaceFailureInCreatingP2pIface(boolean isD2dAloneFeatureEnabled) {
- if (isD2dAloneFeatureEnabled) {
- when(mWifiNative.createP2pIface(
- any(HalDeviceManager.InterfaceDestroyedListener.class),
- eq(mHandlerMock), eq(mWorkSourceMock))).thenReturn(null);
- } else {
- when(mHalDeviceManagerMock.createP2pIface(
- any(HalDeviceManager.InterfaceDestroyedListener.class),
- eq(mHandlerMock), eq(mWorkSourceMock))).thenReturn(null);
- }
+ when(mWifiNative.createP2pIface(
+ any(HalDeviceManager.InterfaceDestroyedListener.class),
+ eq(mHandlerMock), eq(mWorkSourceMock))).thenReturn(null);
when(mHalDeviceManagerMock.isItPossibleToCreateIface(
eq(HalDeviceManager.HDM_CREATE_IFACE_P2P), eq(mWorkSourceMock))).thenReturn(true);
@@ -287,31 +247,10 @@ public class WifiP2pNativeTest extends WifiBaseTest {
* HalDevMgr not possibly creating it.
*/
@Test
- public void testSetupInterfaceFailureInHDMCreatingP2pIfaceWhenHalDevMgrNotPossiblyCreate() {
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(false);
- testSetupInterfaceFailureInCreatingP2pIfaceAndHalDevMgrNotPossiblyCreate(false);
- }
-
- /**
- * Verifies that Wi-Fi metrics do correct action when setting up p2p interface failed and
- * HalDevMgr not possibly creating it.
- */
- @Test
public void testSetupInterfaceFailureInCreatingP2pByWifiNativeAndHalDevMgrNotPossiblyCreate() {
- testSetupInterfaceFailureInCreatingP2pIfaceAndHalDevMgrNotPossiblyCreate(true);
- }
-
- private void testSetupInterfaceFailureInCreatingP2pIfaceAndHalDevMgrNotPossiblyCreate(
- boolean isD2dAloneFeatureEnabled) {
- if (isD2dAloneFeatureEnabled) {
- when(mWifiNative.createP2pIface(
- any(HalDeviceManager.InterfaceDestroyedListener.class),
- eq(mHandlerMock), eq(mWorkSourceMock))).thenReturn(null);
- } else {
- when(mHalDeviceManagerMock.createP2pIface(
- any(HalDeviceManager.InterfaceDestroyedListener.class),
- eq(mHandlerMock), eq(mWorkSourceMock))).thenReturn(null);
- }
+ when(mWifiNative.createP2pIface(
+ any(HalDeviceManager.InterfaceDestroyedListener.class),
+ eq(mHandlerMock), eq(mWorkSourceMock))).thenReturn(null);
when(mHalDeviceManagerMock.isItPossibleToCreateIface(
eq(HalDeviceManager.HDM_CREATE_IFACE_P2P), eq(mWorkSourceMock))).thenReturn(false);
@@ -324,27 +263,7 @@ public class WifiP2pNativeTest extends WifiBaseTest {
* initialization fails.
*/
@Test
- public void testSetupInterfaceByHDMAndFailureInSupplicantConnectionInitialization() {
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(false);
- testSetupInterfaceFailureInSupplicantConnectionInitialization(false);
- }
-
- /**
- * Verifies that setupInterface returns correct values when supplicant connection
- * initialization fails.
- */
- @Test
public void testSetupInterfaceByWifiNativeAndFailureInSupplicantConnectionInitialization() {
- testSetupInterfaceFailureInSupplicantConnectionInitialization(true);
- }
-
- private void testSetupInterfaceFailureInSupplicantConnectionInitialization(
- boolean isD2dAloneFeatureEnabled) {
- if (!isD2dAloneFeatureEnabled) {
- when(mHalDeviceManagerMock.createP2pIface(
- any(HalDeviceManager.InterfaceDestroyedListener.class),
- eq(mHandlerMock), eq(mWorkSourceMock))).thenReturn(TEST_IFACE);
- }
when(mSupplicantP2pIfaceHalMock.isInitializationStarted()).thenReturn(false);
when(mSupplicantP2pIfaceHalMock.initialize()).thenReturn(false);
assertEquals(
@@ -359,27 +278,7 @@ public class WifiP2pNativeTest extends WifiBaseTest {
* initialization never completes.
*/
@Test
- public void testSetupInterfaceByHDMAndFailureInSupplicantConnectionInitNotCompleted() {
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(false);
- testSetupInterfaceFailureInSupplicantConnectionInitNotCompleted(false);
- }
-
- /**
- * Verifies that setupInterface returns correct values when supplicant connection
- * initialization never completes.
- */
- @Test
public void testSetupInterfaceByWifiNativeAndFailureInSupplicantConnectionInitNotCompleted() {
- testSetupInterfaceFailureInSupplicantConnectionInitNotCompleted(true);
- }
-
- private void testSetupInterfaceFailureInSupplicantConnectionInitNotCompleted(
- boolean isD2dAloneFeatureEnabled) {
- if (!isD2dAloneFeatureEnabled) {
- when(mHalDeviceManagerMock.createP2pIface(
- any(HalDeviceManager.InterfaceDestroyedListener.class),
- eq(mHandlerMock), eq(mWorkSourceMock))).thenReturn(TEST_IFACE);
- }
when(mSupplicantP2pIfaceHalMock.setupIface(eq(TEST_IFACE))).thenReturn(true);
when(mSupplicantP2pIfaceHalMock.initialize()).thenReturn(true);
when(mSupplicantP2pIfaceHalMock.isInitializationComplete()).thenReturn(false);
@@ -396,26 +295,7 @@ public class WifiP2pNativeTest extends WifiBaseTest {
* for supplicant.
*/
@Test
- public void testSetupInterfaceByHDMAndFailureInSettingUpP2pIfaceInSupplicant() {
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(false);
- testSetupInterfaceFailureInSettingUpP2pIfaceInSupplicant(false);
- }
-
- /**
- * Verifies that setupInterface returns correct values when failing in setting up P2P Iface
- * for supplicant.
- */
- @Test
public void testSetupInterfaceByWifiNativeAndFailureInSettingUpP2pIfaceInSupplicant() {
- testSetupInterfaceFailureInSettingUpP2pIfaceInSupplicant(true);
- }
- private void testSetupInterfaceFailureInSettingUpP2pIfaceInSupplicant(
- boolean isD2dAloneFeatureEnabled) {
- if (!isD2dAloneFeatureEnabled) {
- when(mHalDeviceManagerMock.createP2pIface(
- any(HalDeviceManager.InterfaceDestroyedListener.class),
- eq(mHandlerMock), eq(mWorkSourceMock))).thenReturn(TEST_IFACE);
- }
when(mSupplicantP2pIfaceHalMock.initialize()).thenReturn(true);
when(mSupplicantP2pIfaceHalMock.isInitializationComplete()).thenReturn(true);
when(mSupplicantP2pIfaceHalMock.setupIface(eq(TEST_IFACE))).thenReturn(false);
diff --git a/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pServiceImplTest.java b/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pServiceImplTest.java
index 78b7fa1df9..dba7220a05 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pServiceImplTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/p2p/WifiP2pServiceImplTest.java
@@ -1436,7 +1436,7 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
when(mWifiInjector.getWifiP2pMetrics()).thenReturn(mWifiP2pMetrics);
when(mWifiInjector.getWifiP2pMonitor()).thenReturn(mWifiMonitor);
when(mWifiInjector.getWifiP2pNative()).thenReturn(mWifiNative);
- when(mWifiInjector.getWifiP2pServiceHandlerThread()).thenReturn(mHandlerThread);
+ when(mWifiInjector.getWifiHandlerThread()).thenReturn(mHandlerThread);
when(mWifiInjector.getWifiPermissionsUtil()).thenReturn(mWifiPermissionsUtil);
when(mWifiInjector.getSettingsConfigStore()).thenReturn(mWifiSettingsConfigStore);
when(mWifiInjector.getCoexManager()).thenReturn(mCoexManager);
@@ -1787,7 +1787,7 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
new WifiP2pServiceImplTest.P2pStateChangedIntentMatcher(
WifiP2pManager.WIFI_P2P_STATE_ENABLED)), any());
if (SdkLevel.isAtLeastT()) {
- verify(mP2pListener).onStateChanged(eq(true));
+ verify(mP2pListener).onP2pStateChanged(eq(WifiP2pManager.WIFI_P2P_STATE_ENABLED));
}
// disabled broadcast sent when user restriction is set
@@ -1797,7 +1797,7 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
new WifiP2pServiceImplTest.P2pStateChangedIntentMatcher(
WifiP2pManager.WIFI_P2P_STATE_DISABLED)), any());
if (SdkLevel.isAtLeastT()) {
- verify(mP2pListener).onStateChanged(eq(false));
+ verify(mP2pListener).onP2pStateChanged(eq(WifiP2pManager.WIFI_P2P_STATE_DISABLED));
}
// no disabled broadcast sent when Wi-Fi is disabled since broadcast already sent
@@ -2268,7 +2268,8 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
verify(mLastCallerInfoManager).put(eq(WifiManager.API_P2P_DISCOVER_PEERS), anyInt(),
anyInt(), anyInt(), anyString(), eq(true));
if (SdkLevel.isAtLeastT()) {
- verify(mP2pListener).onDiscoveryStateChanged(eq(true));
+ verify(mP2pListener).onDiscoveryStateChanged(
+ eq(WifiP2pManager.WIFI_P2P_DISCOVERY_STARTED));
}
}
@@ -2717,9 +2718,9 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
@Test
public void testRequestGroupInfoSuccess() throws Exception {
setTargetSdkGreaterThanT();
- mTestWifiP2pGroup.setOwner(mTestThisDevice);
+ mTestWifiP2pNewPersistentGoGroup.setOwner(mTestThisDevice);
forceP2pEnabled(mClient1);
- sendGroupStartedMsg(mTestWifiP2pGroup);
+ sendGroupStartedMsg(mTestWifiP2pNewPersistentGoGroup);
simulateTetherReady();
when(mWifiPermissionsUtil.checkLocalMacAddressPermission(anyInt())).thenReturn(false);
sendRequestGroupInfoMsg(mClientMessenger);
@@ -2735,7 +2736,7 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
}
assertEquals(WifiP2pManager.RESPONSE_GROUP_INFO, mMessageCaptor.getValue().what);
WifiP2pGroup wifiP2pGroup = (WifiP2pGroup) mMessageCaptor.getValue().obj;
- assertEquals(mTestWifiP2pGroup.getNetworkName(), wifiP2pGroup.getNetworkName());
+ assertEquals(TEST_NETWORK_NAME, wifiP2pGroup.getNetworkName());
// Ensure that our own MAC address is anonymized if we're the group owner.
assertEquals(ANONYMIZED_DEVICE_ADDRESS, wifiP2pGroup.getOwner().deviceAddress);
}
@@ -2747,9 +2748,9 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
@Test
public void testRequestGroupInfoIncludesMacForNetworkSettingsApp() throws Exception {
setTargetSdkGreaterThanT();
- mTestWifiP2pGroup.setOwner(mTestThisDevice);
+ mTestWifiP2pNewPersistentGoGroup.setOwner(mTestThisDevice);
forceP2pEnabled(mClient1);
- sendGroupStartedMsg(mTestWifiP2pGroup);
+ sendGroupStartedMsg(mTestWifiP2pNewPersistentGoGroup);
simulateTetherReady();
when(mWifiPermissionsUtil.checkLocalMacAddressPermission(anyInt())).thenReturn(true);
sendRequestGroupInfoMsg(mClientMessenger);
@@ -2836,7 +2837,7 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
eq("testFeature"), anyInt(), eq(true));
}
if (SdkLevel.isAtLeastT()) {
- verify(mP2pListener).onListenStateChanged(eq(true));
+ verify(mP2pListener).onListenStateChanged(eq(WifiP2pManager.WIFI_P2P_LISTEN_STARTED));
}
}
@@ -3197,7 +3198,8 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
eq(P2pConnectionEvent.CONNECTION_FRESH),
configCaptor.capture(),
eq(WifiMetricsProto.GroupEvent.GROUP_UNKNOWN),
- eq(mClient1.getCallingUid()));
+ eq(mClient1.getCallingUid()),
+ eq("testFeature"));
assertEquals(mTestWifiP2pPeerConfig.toString(), configCaptor.getValue().toString());
verify(mLastCallerInfoManager).put(eq(WifiManager.API_P2P_CONNECT), anyInt(),
anyInt(), anyInt(), anyString(), eq(true));
@@ -3234,7 +3236,8 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
eq(P2pConnectionEvent.CONNECTION_REINVOKE),
configCaptor.capture(),
eq(WifiMetricsProto.GroupEvent.GROUP_UNKNOWN),
- eq(mClient1.getCallingUid()));
+ eq(mClient1.getCallingUid()),
+ eq("testFeature"));
assertEquals(mTestWifiP2pPeerConfig.toString(), configCaptor.getValue().toString());
}
@@ -3266,7 +3269,8 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
eq(P2pConnectionEvent.CONNECTION_REINVOKE),
eq(null),
eq(WifiMetricsProto.GroupEvent.GROUP_OWNER),
- eq(mClient1.getCallingUid()));
+ eq(mClient1.getCallingUid()),
+ eq("testFeature"));
verify(mLastCallerInfoManager).put(eq(WifiManager.API_P2P_CREATE_GROUP), anyInt(),
anyInt(), anyInt(), anyString(), eq(true));
}
@@ -3296,7 +3300,8 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
eq(P2pConnectionEvent.CONNECTION_LOCAL),
eq(null),
eq(WifiMetricsProto.GroupEvent.GROUP_OWNER),
- eq(mClient1.getCallingUid()));
+ eq(mClient1.getCallingUid()),
+ eq("testFeature"));
}
/**
@@ -3323,7 +3328,8 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
eq(P2pConnectionEvent.CONNECTION_LOCAL),
eq(null),
eq(WifiMetricsProto.GroupEvent.GROUP_OWNER),
- eq(mClient1.getCallingUid()));
+ eq(mClient1.getCallingUid()),
+ eq("testFeature"));
}
/**
@@ -3354,7 +3360,8 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
eq(P2pConnectionEvent.CONNECTION_FAST),
configCaptor.capture(),
eq(WifiMetricsProto.GroupEvent.GROUP_CLIENT),
- eq(mClient1.getCallingUid()));
+ eq(mClient1.getCallingUid()),
+ eq("testFeature"));
assertEquals(mTestWifiP2pFastConnectionConfig.toString(),
configCaptor.getValue().toString());
}
@@ -3383,7 +3390,8 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
eq(P2pConnectionEvent.CONNECTION_FAST),
configCaptor.capture(),
eq(WifiMetricsProto.GroupEvent.GROUP_CLIENT),
- eq(mClient1.getCallingUid()));
+ eq(mClient1.getCallingUid()),
+ eq("testFeature"));
assertEquals(mTestWifiP2pFastConnectionConfig.toString(),
configCaptor.getValue().toString());
@@ -3419,7 +3427,8 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
eq(P2pConnectionEvent.CONNECTION_FAST),
configCaptor.capture(),
eq(WifiMetricsProto.GroupEvent.GROUP_OWNER),
- eq(mClient1.getCallingUid()));
+ eq(mClient1.getCallingUid()),
+ eq("testFeature"));
assertEquals(mTestWifiP2pFastConnectionConfig.toString(),
configCaptor.getValue().toString());
verify(mLastCallerInfoManager).put(eq(WifiManager.API_P2P_CREATE_GROUP_P2P_CONFIG),
@@ -6549,7 +6558,8 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
eq(P2pConnectionEvent.CONNECTION_FRESH),
configCaptor.capture(),
eq(WifiMetricsProto.GroupEvent.GROUP_UNKNOWN),
- eq(mClient1.getCallingUid()));
+ eq(mClient1.getCallingUid()),
+ eq("testFeature"));
assertEquals(mTestWifiP2pPeerConfig.toString(), configCaptor.getValue().toString());
// Verify timer is cannelled
// Includes re-schedule 3 times:
@@ -7466,7 +7476,8 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
pdEvent);
verify(mWifiNative).p2pCancelConnect();
if (SdkLevel.isAtLeastT()) {
- verify(mP2pListener).onGroupCreationFailed();
+ verify(mP2pListener).onGroupCreationFailed(
+ eq(WifiP2pManager.GROUP_CREATION_FAILURE_REASON_PROVISION_DISCOVERY_FAILED));
}
}
@@ -8064,7 +8075,6 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
when(mWifiSettingsConfigStore.get(eq(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED)))
.thenReturn(true);
when(mWifiGlobals.isD2dSupportedWhenInfraStaDisabled()).thenReturn(true);
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(true);
simulateWifiStateChange(false);
checkIsP2pInitWhenClientConnected(true, mClient1,
new WorkSource(mClient1.getCallingUid(), TEST_PACKAGE_NAME));
@@ -8137,7 +8147,6 @@ public class WifiP2pServiceImplTest extends WifiBaseTest {
when(mWifiSettingsConfigStore.get(eq(D2D_ALLOWED_WHEN_INFRA_STA_DISABLED)))
.thenReturn(true);
when(mWifiGlobals.isD2dSupportedWhenInfraStaDisabled()).thenReturn(true);
- when(mFeatureFlags.d2dWhenInfraStaOff()).thenReturn(true);
simulateWifiStateChange(false);
checkIsP2pInitWhenClientConnected(true, mClient1,
new WorkSource(mClient1.getCallingUid(), TEST_PACKAGE_NAME));
diff --git a/service/tests/wifitests/src/com/android/server/wifi/util/ApConfigUtilTest.java b/service/tests/wifitests/src/com/android/server/wifi/util/ApConfigUtilTest.java
index e0d780ee14..5774278cc1 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/util/ApConfigUtilTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/util/ApConfigUtilTest.java
@@ -17,6 +17,12 @@
package com.android.server.wifi.util;
import static android.net.wifi.SoftApCapability.SOFTAP_FEATURE_IEEE80211_BE;
+import static android.net.wifi.SoftApConfiguration.SECURITY_TYPE_OPEN;
+import static android.net.wifi.SoftApConfiguration.SECURITY_TYPE_WPA2_PSK;
+import static android.net.wifi.SoftApConfiguration.SECURITY_TYPE_WPA3_OWE;
+import static android.net.wifi.SoftApConfiguration.SECURITY_TYPE_WPA3_OWE_TRANSITION;
+import static android.net.wifi.SoftApConfiguration.SECURITY_TYPE_WPA3_SAE;
+import static android.net.wifi.SoftApConfiguration.SECURITY_TYPE_WPA3_SAE_TRANSITION;
import static com.android.server.wifi.HalDeviceManager.HDM_CREATE_IFACE_AP_BRIDGE;
import static com.android.server.wifi.HalDeviceManager.HDM_CREATE_IFACE_STA;
@@ -47,6 +53,7 @@ import android.net.wifi.SoftApConfiguration.Builder;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiScanner;
+import android.net.wifi.nl80211.DeviceWiphyCapabilities;
import android.util.SparseArray;
import android.util.SparseIntArray;
@@ -164,6 +171,8 @@ public class ApConfigUtilTest extends WifiBaseTest {
@Mock WifiNative mWifiNative;
@Mock CoexManager mCoexManager;
@Mock WifiSettingsConfigStore mConfigStore;
+ @Mock
+ DeviceWiphyCapabilities mDeviceWiphyCapabilities;
private SoftApCapability mCapability;
private boolean mApBridgeIfaceCobinationSupported = false;
private boolean mApBridgeWithStaIfaceCobinationSupported = false;
@@ -191,6 +200,8 @@ public class ApConfigUtilTest extends WifiBaseTest {
when(mWifiNative.getUsableChannels(anyInt(), anyInt(), anyInt())).thenReturn(null);
when(mConfigStore.get(
WifiSettingsConfigStore.WIFI_WIPHY_11BE_SUPPORTED)).thenReturn(false);
+ when(mDeviceWiphyCapabilities.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE))
+ .thenReturn(false);
when(mWifiNative.canDeviceSupportCreateTypeCombo(any()))
.thenAnswer(answer -> {
SparseArray<Integer> combo = answer.getArgument(0);
@@ -615,7 +626,7 @@ public class ApConfigUtilTest extends WifiBaseTest {
config = new SoftApConfiguration.Builder()
.setBand(SoftApConfiguration.BAND_5GHZ | SoftApConfiguration.BAND_6GHZ)
- .setPassphrase("somepassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
+ .setPassphrase("somepassword", SECURITY_TYPE_WPA2_PSK)
.build();
assertEquals(SoftApConfiguration.BAND_5GHZ,
ApConfigUtil.remove6gBandForUnsupportedSecurity(mResources, config, false)
@@ -649,7 +660,7 @@ public class ApConfigUtilTest extends WifiBaseTest {
}
config = new SoftApConfiguration.Builder()
.setBand(SoftApConfiguration.BAND_6GHZ)
- .setPassphrase("somepassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
+ .setPassphrase("somepassword", SECURITY_TYPE_WPA2_PSK)
.build();
assertNull(ApConfigUtil.remove6gBandForUnsupportedSecurity(mResources, config, false));
}
@@ -677,7 +688,7 @@ public class ApConfigUtilTest extends WifiBaseTest {
config = new SoftApConfiguration.Builder()
.setBands(bands)
- .setPassphrase("somepassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
+ .setPassphrase("somepassword", SECURITY_TYPE_WPA2_PSK)
.build();
assertArrayEquals(bands_no6g,
ApConfigUtil.remove6gBandForUnsupportedSecurity(mResources, config, true)
@@ -945,7 +956,7 @@ public class ApConfigUtilTest extends WifiBaseTest {
MacAddress testBssid = MacAddress.fromString("aa:22:33:44:55:66");
SoftApConfiguration currentConfig = new SoftApConfiguration.Builder()
.setSsid("TestSSid")
- .setPassphrase("testpassphrase", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
+ .setPassphrase("testpassphrase", SECURITY_TYPE_WPA2_PSK)
.setBand(SoftApConfiguration.BAND_2GHZ)
.setChannel(11, SoftApConfiguration.BAND_2GHZ)
.setHiddenSsid(true)
@@ -955,7 +966,7 @@ public class ApConfigUtilTest extends WifiBaseTest {
// DO NOT use copy constructor to copy to test since it's instance is the same.
SoftApConfiguration newConfig_noChange = new SoftApConfiguration.Builder()
.setSsid("TestSSid")
- .setPassphrase("testpassphrase", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
+ .setPassphrase("testpassphrase", SECURITY_TYPE_WPA2_PSK)
.setBand(SoftApConfiguration.BAND_2GHZ)
.setChannel(11, SoftApConfiguration.BAND_2GHZ)
.setHiddenSsid(true)
@@ -985,7 +996,7 @@ public class ApConfigUtilTest extends WifiBaseTest {
SoftApConfiguration newConfig_passphraseChanged = new SoftApConfiguration
.Builder(newConfig_noChange)
.setPassphrase("newtestpassphrase",
- SoftApConfiguration.SECURITY_TYPE_WPA2_PSK).build();
+ SECURITY_TYPE_WPA2_PSK).build();
assertTrue(ApConfigUtil.checkConfigurationChangeNeedToRestart(currentConfig,
newConfig_passphraseChanged));
// Test Security Type Changed
@@ -1150,7 +1161,7 @@ public class ApConfigUtilTest extends WifiBaseTest {
testSoftApCapability.setSupportedChannelList(SoftApConfiguration.BAND_6GHZ, new int[0]);
config = new SoftApConfiguration.Builder()
.setBand(SoftApConfiguration.BAND_2GHZ | SoftApConfiguration.BAND_5GHZ)
- .setPassphrase("somepassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
+ .setPassphrase("somepassword", SECURITY_TYPE_WPA2_PSK)
.build();
assertEquals(SoftApConfiguration.BAND_2GHZ,
ApConfigUtil.removeUnavailableBandsFromConfig(config, testSoftApCapability,
@@ -1164,7 +1175,7 @@ public class ApConfigUtilTest extends WifiBaseTest {
testSoftApCapability.setSupportedChannelList(SoftApConfiguration.BAND_6GHZ, new int[0]);
config = new SoftApConfiguration.Builder()
.setBand(SoftApConfiguration.BAND_2GHZ | SoftApConfiguration.BAND_6GHZ)
- .setPassphrase("somepassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
+ .setPassphrase("somepassword", SECURITY_TYPE_WPA2_PSK)
.build();
assertNull(ApConfigUtil.removeUnavailableBandsFromConfig(config, testSoftApCapability,
mCoexManager, mContext));
@@ -1429,4 +1440,46 @@ public class ApConfigUtilTest extends WifiBaseTest {
assertTrue(Arrays.stream(ALLOWED_5G_FREQS).anyMatch(n -> n == freq));
}
}
+
+ @Test
+ public void testIs11beAllowedInBridgedModeConfiguration() throws Exception {
+ assumeTrue(SdkLevel.isAtLeastT());
+ SoftApConfiguration config;
+ int[] dualBands = {SoftApConfiguration.BAND_2GHZ, SoftApConfiguration.BAND_5GHZ};
+
+ config = new SoftApConfiguration.Builder()
+ .setBands(dualBands)
+ .setPassphrase("somepassword", SoftApConfiguration.SECURITY_TYPE_WPA3_SAE)
+ .build();
+ when(mDeviceWiphyCapabilities.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE))
+ .thenReturn(false);
+ /* 11be is disallowed when IEEE80211_BE feature is not supported */
+ assertFalse(ApConfigUtil.is11beAllowedForThisConfiguration(mDeviceWiphyCapabilities,
+ mContext, config, true));
+
+ when(mResources.getBoolean(R.bool.config_wifiSoftapIeee80211beSupported))
+ .thenReturn(true);
+ when(mResources.getBoolean(R.bool.config_wifiSoftApSingleLinkMloInBridgedModeSupported))
+ .thenReturn(true);
+ when(mDeviceWiphyCapabilities.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE))
+ .thenReturn(true);
+ /* 11be is allowed if chip supports single link MLO in bridged mode */
+ assertTrue(ApConfigUtil.is11beAllowedForThisConfiguration(mDeviceWiphyCapabilities,
+ mContext, config, true));
+
+ /* 11be is not allowed if chip doesn't support single link MLO in bridged mode */
+ when(mResources.getBoolean(R.bool.config_wifiSoftApSingleLinkMloInBridgedModeSupported))
+ .thenReturn(false);
+ assertFalse(ApConfigUtil.is11beAllowedForThisConfiguration(mDeviceWiphyCapabilities,
+ mContext, config, true));
+ }
+ @Test
+ public void testIs11beDisabledForSecurityType() throws Exception {
+ assertTrue(ApConfigUtil.is11beDisabledForSecurityType(SECURITY_TYPE_OPEN));
+ assertTrue(ApConfigUtil.is11beDisabledForSecurityType(SECURITY_TYPE_WPA2_PSK));
+ assertFalse(ApConfigUtil.is11beDisabledForSecurityType(SECURITY_TYPE_WPA3_SAE));
+ assertFalse(ApConfigUtil.is11beDisabledForSecurityType(SECURITY_TYPE_WPA3_SAE_TRANSITION));
+ assertFalse(ApConfigUtil.is11beDisabledForSecurityType(SECURITY_TYPE_WPA3_OWE));
+ assertTrue(ApConfigUtil.is11beDisabledForSecurityType(SECURITY_TYPE_WPA3_OWE_TRANSITION));
+ }
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/util/InformationElementUtilTest.java b/service/tests/wifitests/src/com/android/server/wifi/util/InformationElementUtilTest.java
index b931d38eec..0d5e495193 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/util/InformationElementUtilTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/util/InformationElementUtilTest.java
@@ -1309,8 +1309,8 @@ public class InformationElementUtilTest extends WifiBaseTest {
extendedCap.from(ie);
assertFalse(extendedCap.isStrictUtf8());
assertFalse(extendedCap.is80211McRTTResponder());
- assertFalse(extendedCap.isTriggerBasedRangingRespSupported());
- assertFalse(extendedCap.isNonTriggerBasedRangingRespSupported());
+ assertFalse(extendedCap.is80211azTbResponder());
+ assertFalse(extendedCap.is80211azNtbResponder());
assertFalse(extendedCap.isTwtRequesterSupported());
assertFalse(extendedCap.isTwtResponderSupported());
assertFalse(extendedCap.isFilsCapable());
@@ -1368,8 +1368,8 @@ public class InformationElementUtilTest extends WifiBaseTest {
InformationElementUtil.ExtendedCapabilities extendedCap =
new InformationElementUtil.ExtendedCapabilities();
extendedCap.from(ie);
- assertTrue(extendedCap.isTriggerBasedRangingRespSupported());
- assertTrue(extendedCap.isNonTriggerBasedRangingRespSupported());
+ assertTrue(extendedCap.is80211azTbResponder());
+ assertTrue(extendedCap.is80211azNtbResponder());
assertTrue(extendedCap.isTwtRequesterSupported());
assertTrue(extendedCap.isTwtResponderSupported());
assertTrue(extendedCap.isFilsCapable());
diff --git a/service/tests/wifitests/src/com/android/server/wifi/util/RssiUtilTest.java b/service/tests/wifitests/src/com/android/server/wifi/util/RssiUtilTest.java
index d87d94c56f..3e924173c0 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/util/RssiUtilTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/util/RssiUtilTest.java
@@ -27,6 +27,7 @@ import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
import android.net.wifi.IWifiManager;
+import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Looper;
@@ -121,4 +122,14 @@ public class RssiUtilTest extends WifiBaseTest {
int level = wifiManager.getMaxSignalLevel();
assertThat(level).isEqualTo(4);
}
+
+ @Test
+ public void testCalculateAdjustedRssi() {
+ assertThat(RssiUtil.calculateAdjustedRssi(WifiInfo.INVALID_RSSI - 1))
+ .isEqualTo(WifiInfo.INVALID_RSSI);
+ assertThat(RssiUtil.calculateAdjustedRssi(WifiInfo.INVALID_RSSI + 1))
+ .isEqualTo(WifiInfo.INVALID_RSSI + 1);
+ assertThat(RssiUtil.calculateAdjustedRssi(150))
+ .isEqualTo(150 - 256);
+ }
}
diff --git a/service/tests/wifitests/src/com/android/server/wifi/util/WifiPermissionsUtilTest.java b/service/tests/wifitests/src/com/android/server/wifi/util/WifiPermissionsUtilTest.java
index 67dbdaba85..a53ace0010 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/util/WifiPermissionsUtilTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/util/WifiPermissionsUtilTest.java
@@ -870,52 +870,6 @@ public class WifiPermissionsUtilTest extends WifiBaseTest {
}
/**
- * Verifies the helper method exposed for checking SYSTERM_ALERT_WINDOW permission.
- */
- @Test
- public void testCheckSystemAlertWindowPermissionWithModeDefaultAppOps() throws Exception {
- setupMocks();
- WifiPermissionsUtil wifiPermissionsUtil = new WifiPermissionsUtil(mMockPermissionsWrapper,
- mMockContext, mMockUserManager, mWifiInjector);
- wifiPermissionsUtil.enableVerboseLogging(true);
-
- when(mMockAppOps.noteOpNoThrow(AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW, MANAGED_PROFILE_UID,
- TEST_PACKAGE_NAME, null, null))
- .thenReturn(AppOpsManager.MODE_DEFAULT);
- when(mMockPermissionsWrapper.getUidPermission(
- Manifest.permission.SYSTEM_ALERT_WINDOW, MANAGED_PROFILE_UID))
- .thenReturn(PackageManager.PERMISSION_DENIED);
- assertFalse(wifiPermissionsUtil.checkSystemAlertWindowPermission(
- MANAGED_PROFILE_UID, TEST_PACKAGE_NAME));
-
- when(mMockAppOps.noteOpNoThrow(AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW, MANAGED_PROFILE_UID,
- TEST_PACKAGE_NAME, null, null))
- .thenReturn(AppOpsManager.MODE_DEFAULT);
- when(mMockPermissionsWrapper.getUidPermission(
- Manifest.permission.SYSTEM_ALERT_WINDOW, MANAGED_PROFILE_UID))
- .thenReturn(PackageManager.PERMISSION_GRANTED);
- assertTrue(wifiPermissionsUtil.checkSystemAlertWindowPermission(
- MANAGED_PROFILE_UID, TEST_PACKAGE_NAME));
- }
-
- /**
- * Verifies the helper method exposed for checking SYSTERM_ALERT_WINDOW permission.
- */
- @Test
- public void testCheckSystemAlertWindowPermissionWithModeAllowedAppOps() throws Exception {
- setupMocks();
- WifiPermissionsUtil wifiPermissionsUtil = new WifiPermissionsUtil(mMockPermissionsWrapper,
- mMockContext, mMockUserManager, mWifiInjector);
- wifiPermissionsUtil.enableVerboseLogging(true);
-
- when(mMockAppOps.noteOpNoThrow(
- AppOpsManager.OP_SYSTEM_ALERT_WINDOW, MANAGED_PROFILE_UID, TEST_PACKAGE_NAME))
- .thenReturn(AppOpsManager.MODE_ALLOWED);
- assertTrue(wifiPermissionsUtil.checkSystemAlertWindowPermission(
- MANAGED_PROFILE_UID, TEST_PACKAGE_NAME));
- }
-
- /**
* Verifies the helper method exposed for checking if the app is a DeviceOwner.
*/
@Test
diff --git a/service/tests/wifitests/src/com/android/server/wifi/util/XmlUtilTest.java b/service/tests/wifitests/src/com/android/server/wifi/util/XmlUtilTest.java
index f782eb8fcb..389686ee77 100644
--- a/service/tests/wifitests/src/com/android/server/wifi/util/XmlUtilTest.java
+++ b/service/tests/wifitests/src/com/android/server/wifi/util/XmlUtilTest.java
@@ -20,6 +20,7 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -38,6 +39,7 @@ import androidx.test.filters.SmallTest;
import com.android.internal.util.FastXmlSerializer;
import com.android.modules.utils.build.SdkLevel;
import com.android.net.module.util.MacAddressUtils;
+import com.android.server.wifi.OuiKeyedDataUtil;
import com.android.server.wifi.WifiBaseTest;
import com.android.server.wifi.WifiConfigurationTestUtil;
import com.android.server.wifi.util.XmlUtil.IpConfigurationXmlUtil;
@@ -969,4 +971,16 @@ public class XmlUtilTest extends WifiBaseTest {
throws IOException, XmlPullParserException {
testConfigStoreWithEncryptedPreSharedKey(true, true);
}
+
+ /**
+ * Verify that the vendor data field is serialized and deserialized correctly
+ * when provided.
+ */
+ @Test
+ public void testWifiConfigurationWithVendorData() throws Exception {
+ assumeTrue(SdkLevel.isAtLeastV());
+ WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
+ config.setVendorData(OuiKeyedDataUtil.createTestOuiKeyedDataList(10));
+ serializeDeserializeWifiConfiguration(config);
+ }
}
diff --git a/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/Android.bp b/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/Android.bp
index 74f44e96c0..f6b5eb8a54 100644
--- a/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/Android.bp
+++ b/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/Android.bp
@@ -32,6 +32,7 @@ android_test {
"mobly-snippet-lib",
],
min_sdk_version: "30",
+ target_sdk_version: "35",
}
android_test {
diff --git a/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/WifiAwareSnippet.java b/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/WifiAwareSnippet.java
index f26b72f8fb..e89a56f6b3 100644
--- a/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/WifiAwareSnippet.java
+++ b/tests/hostsidetests/multidevices/com.google.snippet.wifi/aware/WifiAwareSnippet.java
@@ -54,7 +54,7 @@ import java.util.function.Consumer;
/** An example snippet class with a simple Rpc. */
public class WifiAwareSnippet implements Snippet {
- private Object mLock;
+ private final Object mLock = new Object();
private static class WifiAwareSnippetException extends Exception {
private static final long SERIAL_VERSION_UID = 1;
diff --git a/tests/hostsidetests/multidevices/com.google.snippet.wifi/direct/Android.bp b/tests/hostsidetests/multidevices/com.google.snippet.wifi/direct/Android.bp
index 1c09fbeb2e..e5125978bf 100644
--- a/tests/hostsidetests/multidevices/com.google.snippet.wifi/direct/Android.bp
+++ b/tests/hostsidetests/multidevices/com.google.snippet.wifi/direct/Android.bp
@@ -30,4 +30,5 @@ android_test {
"mobly-snippet-lib",
],
min_sdk_version: "30",
+ target_sdk_version: "35",
}