summaryrefslogtreecommitdiff
path: root/wifi/java/android/net
diff options
context:
space:
mode:
Diffstat (limited to 'wifi/java/android/net')
-rw-r--r--wifi/java/android/net/wifi/AnqpInformationElement.java80
-rw-r--r--wifi/java/android/net/wifi/BatchedScanResult.java97
-rw-r--r--wifi/java/android/net/wifi/CoexUnsafeChannel.java176
-rw-r--r--wifi/java/android/net/wifi/EAPConstants.java57
-rw-r--r--wifi/java/android/net/wifi/EasyConnectStatusCallback.java286
-rw-r--r--wifi/java/android/net/wifi/IActionListener.aidl27
-rw-r--r--wifi/java/android/net/wifi/ICoexCallback.aidl26
-rw-r--r--wifi/java/android/net/wifi/IDppCallback.aidl54
-rw-r--r--wifi/java/android/net/wifi/ILocalOnlyHotspotCallback.aidl30
-rw-r--r--wifi/java/android/net/wifi/INetworkRequestMatchCallback.aidl39
-rw-r--r--wifi/java/android/net/wifi/INetworkRequestUserSelectionCallback.aidl31
-rw-r--r--wifi/java/android/net/wifi/IOnWifiActivityEnergyInfoListener.aidl33
-rw-r--r--wifi/java/android/net/wifi/IOnWifiUsabilityStatsListener.aidl41
-rw-r--r--wifi/java/android/net/wifi/IScanResultsCallback.aidl27
-rw-r--r--wifi/java/android/net/wifi/IScanResultsListener.aidl24
-rw-r--r--wifi/java/android/net/wifi/IScoreUpdateObserver.aidl29
-rw-r--r--wifi/java/android/net/wifi/ISoftApCallback.aidl71
-rw-r--r--wifi/java/android/net/wifi/ISuggestionConnectionStatusListener.aidl29
-rw-r--r--wifi/java/android/net/wifi/ITrafficStateCallback.aidl34
-rw-r--r--wifi/java/android/net/wifi/IWifiConnectedNetworkScorer.aidl33
-rw-r--r--wifi/java/android/net/wifi/IWifiManager.aidl338
-rw-r--r--wifi/java/android/net/wifi/IWifiScanner.aidl30
-rw-r--r--wifi/java/android/net/wifi/ParcelUtil.java165
-rw-r--r--wifi/java/android/net/wifi/RttManager.aidl21
-rw-r--r--wifi/java/android/net/wifi/RttManager.java1233
-rw-r--r--wifi/java/android/net/wifi/ScanResult.java1214
-rw-r--r--wifi/java/android/net/wifi/SoftApCapability.java307
-rwxr-xr-xwifi/java/android/net/wifi/SoftApConfToXmlMigrationUtil.java284
-rw-r--r--wifi/java/android/net/wifi/SoftApConfiguration.java1334
-rw-r--r--wifi/java/android/net/wifi/SoftApInfo.java276
-rw-r--r--wifi/java/android/net/wifi/SupplicantState.java265
-rw-r--r--wifi/java/android/net/wifi/SynchronousExecutor.java29
-rw-r--r--wifi/java/android/net/wifi/WifiAnnotations.java124
-rw-r--r--wifi/java/android/net/wifi/WifiClient.java95
-rw-r--r--wifi/java/android/net/wifi/WifiConfiguration.java3373
-rw-r--r--wifi/java/android/net/wifi/WifiDppConfig.aidl20
-rw-r--r--wifi/java/android/net/wifi/WifiDppConfig.java216
-rw-r--r--wifi/java/android/net/wifi/WifiEnterpriseConfig.java1526
-rw-r--r--wifi/java/android/net/wifi/WifiFrameworkInitializer.java121
-rw-r--r--wifi/java/android/net/wifi/WifiInfo.java1209
-rw-r--r--wifi/java/android/net/wifi/WifiManager.java7185
-rwxr-xr-xwifi/java/android/net/wifi/WifiMigration.java558
-rw-r--r--wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java163
-rw-r--r--wifi/java/android/net/wifi/WifiNetworkConnectionStatistics.java85
-rwxr-xr-xwifi/java/android/net/wifi/WifiNetworkScoreCache.java316
-rw-r--r--wifi/java/android/net/wifi/WifiNetworkSpecifier.java655
-rw-r--r--wifi/java/android/net/wifi/WifiNetworkSuggestion.java1406
-rw-r--r--wifi/java/android/net/wifi/WifiScanner.java1704
-rw-r--r--wifi/java/android/net/wifi/WifiSsid.java288
-rw-r--r--wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java351
-rw-r--r--wifi/java/android/net/wifi/WpsInfo.java102
-rw-r--r--wifi/java/android/net/wifi/aware/AttachCallback.java45
-rw-r--r--wifi/java/android/net/wifi/aware/AwareResources.java146
-rw-r--r--wifi/java/android/net/wifi/aware/Characteristics.java154
-rw-r--r--wifi/java/android/net/wifi/aware/ConfigRequest.aidl19
-rw-r--r--wifi/java/android/net/wifi/aware/ConfigRequest.java385
-rw-r--r--wifi/java/android/net/wifi/aware/DiscoverySession.java431
-rw-r--r--wifi/java/android/net/wifi/aware/DiscoverySessionCallback.java208
-rw-r--r--wifi/java/android/net/wifi/aware/IWifiAwareDiscoverySessionCallback.aidl39
-rw-r--r--wifi/java/android/net/wifi/aware/IWifiAwareEventCallback.aidl31
-rw-r--r--wifi/java/android/net/wifi/aware/IWifiAwareMacAddressProvider.aidl27
-rw-r--r--wifi/java/android/net/wifi/aware/IWifiAwareManager.aidl65
-rw-r--r--wifi/java/android/net/wifi/aware/IdentityChangedListener.java39
-rw-r--r--wifi/java/android/net/wifi/aware/ParcelablePeerHandle.java60
-rw-r--r--wifi/java/android/net/wifi/aware/PeerHandle.java63
-rw-r--r--wifi/java/android/net/wifi/aware/PublishConfig.java393
-rw-r--r--wifi/java/android/net/wifi/aware/PublishDiscoverySession.java68
-rw-r--r--wifi/java/android/net/wifi/aware/SubscribeConfig.java497
-rw-r--r--wifi/java/android/net/wifi/aware/SubscribeDiscoverySession.java73
-rw-r--r--wifi/java/android/net/wifi/aware/TlvBufferUtils.java714
-rw-r--r--wifi/java/android/net/wifi/aware/WifiAwareAgentNetworkSpecifier.java224
-rw-r--r--wifi/java/android/net/wifi/aware/WifiAwareManager.java938
-rw-r--r--wifi/java/android/net/wifi/aware/WifiAwareNetworkInfo.java182
-rw-r--r--wifi/java/android/net/wifi/aware/WifiAwareNetworkSpecifier.java446
-rw-r--r--wifi/java/android/net/wifi/aware/WifiAwareSession.java343
-rw-r--r--wifi/java/android/net/wifi/aware/WifiAwareUtils.java106
-rw-r--r--wifi/java/android/net/wifi/aware/package.html43
-rw-r--r--wifi/java/android/net/wifi/hotspot2/ConfigParser.java486
-rw-r--r--wifi/java/android/net/wifi/hotspot2/IProvisioningCallback.aidl41
-rw-r--r--wifi/java/android/net/wifi/hotspot2/OsuProvider.java270
-rw-r--r--wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java1075
-rw-r--r--wifi/java/android/net/wifi/hotspot2/ProvisioningCallback.java235
-rw-r--r--wifi/java/android/net/wifi/hotspot2/omadm/PpsMoParser.java1787
-rw-r--r--wifi/java/android/net/wifi/hotspot2/omadm/XMLNode.java109
-rw-r--r--wifi/java/android/net/wifi/hotspot2/omadm/XMLParser.java108
-rw-r--r--wifi/java/android/net/wifi/hotspot2/pps/Credential.java1313
-rw-r--r--wifi/java/android/net/wifi/hotspot2/pps/HomeSp.java491
-rw-r--r--wifi/java/android/net/wifi/hotspot2/pps/Policy.java576
-rw-r--r--wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java403
-rw-r--r--wifi/java/android/net/wifi/migration_samples/README.txt35
-rw-r--r--wifi/java/android/net/wifi/migration_samples/Shared_WifiConfigStore.xml200
-rw-r--r--wifi/java/android/net/wifi/migration_samples/Shared_WifiConfigStoreSoftAp.xml22
-rw-r--r--wifi/java/android/net/wifi/migration_samples/User_WifiConfigStore.xml81
-rw-r--r--wifi/java/android/net/wifi/migration_samples/User_WifiConfigStoreNetworkSuggestions.xml155
-rw-r--r--wifi/java/android/net/wifi/nl80211/ChannelSettings.java95
-rw-r--r--wifi/java/android/net/wifi/nl80211/DeviceWiphyCapabilities.java283
-rw-r--r--wifi/java/android/net/wifi/nl80211/HiddenNetwork.java87
-rw-r--r--wifi/java/android/net/wifi/nl80211/NativeScanResult.java321
-rw-r--r--wifi/java/android/net/wifi/nl80211/NativeWifiClient.java103
-rw-r--r--wifi/java/android/net/wifi/nl80211/PnoNetwork.java171
-rw-r--r--wifi/java/android/net/wifi/nl80211/PnoSettings.java209
-rw-r--r--wifi/java/android/net/wifi/nl80211/RadioChainInfo.java125
-rw-r--r--wifi/java/android/net/wifi/nl80211/SingleScanSettings.java118
-rw-r--r--wifi/java/android/net/wifi/nl80211/WifiNl80211Manager.java1325
-rw-r--r--wifi/java/android/net/wifi/p2p/IWifiP2pManager.aidl34
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pConfig.java506
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pDevice.java440
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pDeviceList.java219
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pGroup.java371
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pGroupList.java257
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pInfo.java98
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pManager.java2059
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pProvDiscEvent.java92
-rw-r--r--wifi/java/android/net/wifi/p2p/WifiP2pWfdInfo.java278
-rw-r--r--wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceInfo.java237
-rw-r--r--wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceRequest.java107
-rw-r--r--wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceResponse.java309
-rw-r--r--wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceInfo.java187
-rw-r--r--wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceRequest.java283
-rw-r--r--wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceResponse.java381
-rw-r--r--wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceInfo.java111
-rw-r--r--wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceRequest.java82
-rw-r--r--wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceResponse.java159
-rw-r--r--wifi/java/android/net/wifi/p2p/package.html68
-rw-r--r--wifi/java/android/net/wifi/package.html29
-rw-r--r--wifi/java/android/net/wifi/rtt/CivicLocation.java333
-rw-r--r--wifi/java/android/net/wifi/rtt/CivicLocationKeys.java115
-rw-r--r--wifi/java/android/net/wifi/rtt/IRttCallback.aidl37
-rw-r--r--wifi/java/android/net/wifi/rtt/IWifiRttManager.aidl33
-rw-r--r--wifi/java/android/net/wifi/rtt/RangingRequest.java267
-rw-r--r--wifi/java/android/net/wifi/rtt/RangingResult.java438
-rw-r--r--wifi/java/android/net/wifi/rtt/RangingResultCallback.java70
-rw-r--r--wifi/java/android/net/wifi/rtt/ResponderConfig.java514
-rw-r--r--wifi/java/android/net/wifi/rtt/ResponderLocation.java1427
-rw-r--r--wifi/java/android/net/wifi/rtt/WifiRttManager.java190
-rw-r--r--wifi/java/android/net/wifi/rtt/package.html45
-rw-r--r--wifi/java/android/net/wifi/util/HexEncoding.java183
137 files changed, 0 insertions, 52139 deletions
diff --git a/wifi/java/android/net/wifi/AnqpInformationElement.java b/wifi/java/android/net/wifi/AnqpInformationElement.java
deleted file mode 100644
index 47b712991c49..000000000000
--- a/wifi/java/android/net/wifi/AnqpInformationElement.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2016 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;
-
-/**
- * This object contains the payload of an ANQP element.
- * Vendor id is the vendor ID for the element, or 0 if it is an 802.11(u) element.
- * Hotspot 2.0 uses the WFA Vendor ID which is 0x506f9a
- * The payload contains the bytes of the payload, starting after the length octet(s).
- * @hide
- */
-public class AnqpInformationElement {
- public static final int HOTSPOT20_VENDOR_ID = 0x506f9a;
-
- public static final int ANQP_QUERY_LIST = 256;
- public static final int ANQP_CAPABILITY_LIST = 257;
- public static final int ANQP_VENUE_NAME = 258;
- public static final int ANQP_EMERGENCY_NUMBER = 259;
- public static final int ANQP_NWK_AUTH_TYPE = 260;
- public static final int ANQP_ROAMING_CONSORTIUM = 261;
- public static final int ANQP_IP_ADDR_AVAILABILITY = 262;
- public static final int ANQP_NAI_REALM = 263;
- public static final int ANQP_3GPP_NETWORK = 264;
- public static final int ANQP_GEO_LOC = 265;
- public static final int ANQP_CIVIC_LOC = 266;
- public static final int ANQP_LOC_URI = 267;
- public static final int ANQP_DOM_NAME = 268;
- public static final int ANQP_EMERGENCY_ALERT = 269;
- public static final int ANQP_TDLS_CAP = 270;
- public static final int ANQP_EMERGENCY_NAI = 271;
- public static final int ANQP_NEIGHBOR_REPORT = 272;
- public static final int ANQP_VENDOR_SPEC = 56797;
-
- public static final int HS_QUERY_LIST = 1;
- public static final int HS_CAPABILITY_LIST = 2;
- public static final int HS_FRIENDLY_NAME = 3;
- public static final int HS_WAN_METRICS = 4;
- public static final int HS_CONN_CAPABILITY = 5;
- public static final int HS_NAI_HOME_REALM_QUERY = 6;
- public static final int HS_OPERATING_CLASS = 7;
- public static final int HS_OSU_PROVIDERS = 8;
- public static final int HS_ICON_REQUEST = 10;
- public static final int HS_ICON_FILE = 11;
-
- private final int mVendorId;
- private final int mElementId;
- private final byte[] mPayload;
-
- public AnqpInformationElement(int vendorId, int elementId, byte[] payload) {
- mVendorId = vendorId;
- mElementId = elementId;
- mPayload = payload;
- }
-
- public int getVendorId() {
- return mVendorId;
- }
-
- public int getElementId() {
- return mElementId;
- }
-
- public byte[] getPayload() {
- return mPayload;
- }
-}
diff --git a/wifi/java/android/net/wifi/BatchedScanResult.java b/wifi/java/android/net/wifi/BatchedScanResult.java
deleted file mode 100644
index ed8845dd2ae3..000000000000
--- a/wifi/java/android/net/wifi/BatchedScanResult.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2008 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.os.Parcelable;
-import android.annotation.SystemApi;
-import android.os.Parcel;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Describes the Results of a batched set of wifi scans where the firmware performs many
- * scans and stores the timestamped results without waking the main processor each time.
- * @hide
- * @removed
- */
-@Deprecated
-@SystemApi
-public class BatchedScanResult implements Parcelable {
- private static final String TAG = "BatchedScanResult";
-
- /** Inidcates this scan was interrupted and may only have partial results. */
- public boolean truncated;
-
- /** The result of this particular scan. */
- public final List<ScanResult> scanResults = new ArrayList<ScanResult>();
-
-
- public BatchedScanResult() {
- }
-
- public BatchedScanResult(BatchedScanResult source) {
- truncated = source.truncated;
- for (ScanResult s : source.scanResults) scanResults.add(new ScanResult(s));
- }
-
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
-
- sb.append("BatchedScanResult: ").
- append("truncated: ").append(String.valueOf(truncated)).
- append("scanResults: [");
- for (ScanResult s : scanResults) {
- sb.append(" <").append(s.toString()).append("> ");
- }
- sb.append(" ]");
- return sb.toString();
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(truncated ? 1 : 0);
- dest.writeInt(scanResults.size());
- for (ScanResult s : scanResults) {
- s.writeToParcel(dest, flags);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @android.annotation.NonNull Creator<BatchedScanResult> CREATOR =
- new Creator<BatchedScanResult>() {
- public BatchedScanResult createFromParcel(Parcel in) {
- BatchedScanResult result = new BatchedScanResult();
- result.truncated = (in.readInt() == 1);
- int count = in.readInt();
- while (count-- > 0) {
- result.scanResults.add(ScanResult.CREATOR.createFromParcel(in));
- }
- return result;
- }
-
- public BatchedScanResult[] newArray(int size) {
- return new BatchedScanResult[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/CoexUnsafeChannel.java b/wifi/java/android/net/wifi/CoexUnsafeChannel.java
deleted file mode 100644
index 3f9efa020d05..000000000000
--- a/wifi/java/android/net/wifi/CoexUnsafeChannel.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (C) 2020 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 static android.net.wifi.WifiScanner.WIFI_BAND_24_GHZ;
-import static android.net.wifi.WifiScanner.WIFI_BAND_5_GHZ;
-import static android.net.wifi.WifiScanner.WIFI_BAND_6_GHZ;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.Objects;
-
-/**
- * Data structure class representing a Wi-Fi channel that would cause interference to/receive
- * interference from the active cellular channels and should be avoided.
- *
- * If {@link #isPowerCapAvailable()} is {@code true}, then a valid power cap value is available
- * through {@link #getPowerCapDbm()} to be used if this channel cannot be avoided. If {@code false},
- * then {@link #getPowerCapDbm()} throws an IllegalStateException and the channel will not need to
- * cap its power.
- *
- * @hide
- */
-@SystemApi
-public final class CoexUnsafeChannel implements Parcelable {
- private @WifiAnnotations.WifiBandBasic int mBand;
- private int mChannel;
- private boolean mIsPowerCapAvailable = false;
- private int mPowerCapDbm;
-
- /**
- * Constructor for a CoexUnsafeChannel with no power cap specified.
- * @param band One of {@link WifiAnnotations.WifiBandBasic}
- * @param channel Channel number
- */
- public CoexUnsafeChannel(@WifiAnnotations.WifiBandBasic int band, int channel) {
- mBand = band;
- mChannel = channel;
- }
-
- /**
- * Constructor for a CoexUnsafeChannel with power cap specified.
- * @param band One of {@link WifiAnnotations.WifiBandBasic}
- * @param channel Channel number
- * @param powerCapDbm Power cap in dBm
- */
- public CoexUnsafeChannel(@WifiAnnotations.WifiBandBasic int band, int channel,
- int powerCapDbm) {
- mBand = band;
- mChannel = channel;
- setPowerCapDbm(powerCapDbm);
- }
-
- /** Returns the Wi-Fi band of this channel as one of {@link WifiAnnotations.WifiBandBasic} */
- public @WifiAnnotations.WifiBandBasic int getBand() {
- return mBand;
- }
-
- /** Returns the channel number of this channel. */
- public int getChannel() {
- return mChannel;
- }
-
- /** Returns {@code true} if {@link #getPowerCapDbm()} is a valid value, else {@code false} */
- public boolean isPowerCapAvailable() {
- return mIsPowerCapAvailable;
- }
-
- /**
- * Returns the power cap of this channel in dBm. Throws IllegalStateException if
- * {@link #isPowerCapAvailable()} is {@code false}.
- */
- public int getPowerCapDbm() {
- if (!mIsPowerCapAvailable) {
- throw new IllegalStateException("getPowerCapDbm called but power cap is unavailable");
- }
- return mPowerCapDbm;
- }
-
- /** Set the power cap of this channel. */
- public void setPowerCapDbm(int powerCapDbm) {
- mIsPowerCapAvailable = true;
- mPowerCapDbm = powerCapDbm;
- }
-
- @Override
- public boolean equals(@Nullable Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- CoexUnsafeChannel that = (CoexUnsafeChannel) o;
- return mBand == that.mBand
- && mChannel == that.mChannel
- && mIsPowerCapAvailable == that.mIsPowerCapAvailable
- && mPowerCapDbm == that.mPowerCapDbm;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mBand, mChannel, mIsPowerCapAvailable, mPowerCapDbm);
- }
-
- @Override
- public String toString() {
- StringBuilder sj = new StringBuilder("CoexUnsafeChannel{");
- sj.append(mChannel);
- sj.append(", ");
- if (mBand == WIFI_BAND_24_GHZ) {
- sj.append("2.4GHz");
- } else if (mBand == WIFI_BAND_5_GHZ) {
- sj.append("5GHz");
- } else if (mBand == WIFI_BAND_6_GHZ) {
- sj.append("6GHz");
- } else {
- sj.append("UNKNOWN BAND");
- }
- if (mIsPowerCapAvailable) {
- sj.append(", ").append(mPowerCapDbm).append("dBm");
- }
- sj.append('}');
- return sj.toString();
- }
-
- /** Implement the Parcelable interface {@hide} */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mBand);
- dest.writeInt(mChannel);
- dest.writeBoolean(mIsPowerCapAvailable);
- if (mIsPowerCapAvailable) {
- dest.writeInt(mPowerCapDbm);
- }
- }
-
- /** Implement the Parcelable interface */
- public static final @NonNull Creator<CoexUnsafeChannel> CREATOR =
- new Creator<CoexUnsafeChannel>() {
- public CoexUnsafeChannel createFromParcel(Parcel in) {
- final int band = in.readInt();
- final int channel = in.readInt();
- final boolean isPowerCapAvailable = in.readBoolean();
- if (isPowerCapAvailable) {
- final int powerCapDbm = in.readInt();
- return new CoexUnsafeChannel(band, channel, powerCapDbm);
- }
- return new CoexUnsafeChannel(band, channel);
- }
-
- public CoexUnsafeChannel[] newArray(int size) {
- return new CoexUnsafeChannel[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/EAPConstants.java b/wifi/java/android/net/wifi/EAPConstants.java
deleted file mode 100644
index b5f7c946ff05..000000000000
--- a/wifi/java/android/net/wifi/EAPConstants.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Copyright (c) 2016, 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;
-
-/**
- * Utility class containing EAP (Extensible Authentication Protocol) Related constants.
- *
- * @hide
- */
-public final class EAPConstants {
- // Constant definition for EAP types. Refer to
- // http://www.iana.org/assignments/eap-numbers/eap-numbers.xhtml for more info.
- public static final int EAP_MD5 = 4;
- public static final int EAP_OTP = 5;
- public static final int EAP_RSA = 9;
- public static final int EAP_KEA = 11;
- public static final int EAP_KEA_VALIDATE = 12;
- public static final int EAP_TLS = 13;
- public static final int EAP_LEAP = 17;
- public static final int EAP_SIM = 18;
- public static final int EAP_TTLS = 21;
- public static final int EAP_AKA = 23;
- public static final int EAP_3Com = 24;
- public static final int EAP_MSCHAPv2 = 26;
- public static final int EAP_PEAP = 29;
- public static final int EAP_POTP = 32;
- public static final int EAP_ActiontecWireless = 35;
- public static final int EAP_HTTPDigest = 38;
- public static final int EAP_SPEKE = 41;
- public static final int EAP_MOBAC = 42;
- public static final int EAP_FAST = 43;
- public static final int EAP_ZLXEAP = 44;
- public static final int EAP_Link = 45;
- public static final int EAP_PAX = 46;
- public static final int EAP_PSK = 47;
- public static final int EAP_SAKE = 48;
- public static final int EAP_IKEv2 = 49;
- public static final int EAP_AKA_PRIME = 50;
- public static final int EAP_GPSK = 51;
- public static final int EAP_PWD = 52;
- public static final int EAP_EKE = 53;
- public static final int EAP_TEAP = 55;
-}
diff --git a/wifi/java/android/net/wifi/EasyConnectStatusCallback.java b/wifi/java/android/net/wifi/EasyConnectStatusCallback.java
deleted file mode 100644
index ee7025594bc6..000000000000
--- a/wifi/java/android/net/wifi/EasyConnectStatusCallback.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Copyright (C) 2018 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.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.util.SparseArray;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.concurrent.Executor;
-
-/**
- * Easy Connect (DPP) Status Callback. Use this callback to get status updates (success, failure,
- * progress) from the Easy Connect operations.
- */
-public abstract class EasyConnectStatusCallback {
- /**
- * Easy Connect R1 Success event: Configuration sent (Configurator mode). This is the last
- * and final Easy Connect event when either the local device or remote device implement R1.
- * If both devices implement R2, this event will never be received, and the
- * {@link #EASY_CONNECT_EVENT_SUCCESS_CONFIGURATION_APPLIED} will be received.
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_EVENT_SUCCESS_CONFIGURATION_SENT = 0;
-
- /**
- * Easy Connect R2 Success event: Configuration applied by Enrollee (Configurator mode).
- * This is the last and final Easy Connect event when both the local device and remote device
- * implement R2. If either the local device or remote device implement R1, this event will never
- * be received, and the {@link #EASY_CONNECT_EVENT_SUCCESS_CONFIGURATION_SENT} will be received.
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_EVENT_SUCCESS_CONFIGURATION_APPLIED = 1;
-
- /** @hide */
- @IntDef(prefix = {"EASY_CONNECT_EVENT_SUCCESS_"}, value = {
- EASY_CONNECT_EVENT_SUCCESS_CONFIGURATION_SENT,
- EASY_CONNECT_EVENT_SUCCESS_CONFIGURATION_APPLIED,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface EasyConnectSuccessStatusCode {
- }
-
- /**
- * Easy Connect Progress event: Initial authentication with peer succeeded.
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_EVENT_PROGRESS_AUTHENTICATION_SUCCESS = 0;
-
- /**
- * Easy Connect Progress event: Peer requires more time to process bootstrapping.
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_EVENT_PROGRESS_RESPONSE_PENDING = 1;
-
- /**
- * Easy Connect R2 Progress event: Configuration sent to Enrollee, waiting for response
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_EVENT_PROGRESS_CONFIGURATION_SENT_WAITING_RESPONSE = 2;
-
- /**
- * Easy Connect R2 Progress event: Configuration accepted by Enrollee, waiting for response
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_EVENT_PROGRESS_CONFIGURATION_ACCEPTED = 3;
-
- /** @hide */
- @IntDef(prefix = {"EASY_CONNECT_EVENT_PROGRESS_"}, value = {
- EASY_CONNECT_EVENT_PROGRESS_AUTHENTICATION_SUCCESS,
- EASY_CONNECT_EVENT_PROGRESS_RESPONSE_PENDING,
- EASY_CONNECT_EVENT_PROGRESS_CONFIGURATION_SENT_WAITING_RESPONSE,
- EASY_CONNECT_EVENT_PROGRESS_CONFIGURATION_ACCEPTED,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface EasyConnectProgressStatusCode {
- }
-
- /**
- * Easy Connect Failure event: Scanned QR code is either not a Easy Connect URI, or the Easy
- * Connect URI has errors.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_INVALID_URI = -1;
-
- /**
- * Easy Connect Failure event: Bootstrapping/Authentication initialization process failure.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_AUTHENTICATION = -2;
-
- /**
- * Easy Connect Failure event: Both devices are implementing the same role and are incompatible.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_NOT_COMPATIBLE = -3;
-
- /**
- * Easy Connect Failure event: Configuration process has failed due to malformed message.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_CONFIGURATION = -4;
-
- /**
- * Easy Connect Failure event: Easy Connect request while in another Easy Connect exchange.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_BUSY = -5;
-
- /**
- * Easy Connect Failure event: No response from the peer.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_TIMEOUT = -6;
-
- /**
- * Easy Connect Failure event: General protocol failure.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_GENERIC = -7;
-
- /**
- * Easy Connect Failure event: Feature or option is not supported.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_NOT_SUPPORTED = -8;
-
- /**
- * Easy Connect Failure event: Invalid network provided to Easy Connect configurator.
- * Network must either be WPA3-Personal (SAE) or WPA2-Personal (PSK).
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_INVALID_NETWORK = -9;
-
- /**
- * Easy Connect R2 Failure event: Enrollee cannot find the network.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_CANNOT_FIND_NETWORK = -10;
-
- /**
- * Easy Connect R2 Failure event: Enrollee failed to authenticate with the network.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_ENROLLEE_AUTHENTICATION = -11;
-
- /**
- * Easy Connect R2 Failure event: Enrollee rejected the configuration.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_ENROLLEE_REJECTED_CONFIGURATION = -12;
-
- /**
- * Easy Connect Failure event: System failed to generate DPP URI.
- */
- public static final int EASY_CONNECT_EVENT_FAILURE_URI_GENERATION = -13;
-
- /** @hide */
- @IntDef(prefix = {"EASY_CONNECT_EVENT_FAILURE_"}, value = {
- EASY_CONNECT_EVENT_FAILURE_INVALID_URI,
- EASY_CONNECT_EVENT_FAILURE_AUTHENTICATION,
- EASY_CONNECT_EVENT_FAILURE_NOT_COMPATIBLE,
- EASY_CONNECT_EVENT_FAILURE_CONFIGURATION,
- EASY_CONNECT_EVENT_FAILURE_BUSY,
- EASY_CONNECT_EVENT_FAILURE_TIMEOUT,
- EASY_CONNECT_EVENT_FAILURE_GENERIC,
- EASY_CONNECT_EVENT_FAILURE_NOT_SUPPORTED,
- EASY_CONNECT_EVENT_FAILURE_INVALID_NETWORK,
- EASY_CONNECT_EVENT_FAILURE_CANNOT_FIND_NETWORK,
- EASY_CONNECT_EVENT_FAILURE_ENROLLEE_AUTHENTICATION,
- EASY_CONNECT_EVENT_FAILURE_ENROLLEE_REJECTED_CONFIGURATION,
- EASY_CONNECT_EVENT_FAILURE_URI_GENERATION,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface EasyConnectFailureStatusCode {
- }
-
- /** @hide */
- @SystemApi
- public EasyConnectStatusCallback() {
- // Fully-static utility classes must not have constructor
- }
-
- /**
- * Called when local Easy Connect Enrollee successfully receives a new Wi-Fi configuration from
- * the
- * peer Easy Connect configurator. This callback marks the successful end of the Easy Connect
- * current Easy Connect
- * session, and no further callbacks will be called. This callback is the successful outcome
- * of a Easy Connect flow starting with
- * {@link WifiManager#startEasyConnectAsEnrolleeInitiator(String, Executor,
- * EasyConnectStatusCallback)} .
- *
- * @param newNetworkId New Wi-Fi configuration with a network ID received from the configurator
- * @hide
- */
- @SystemApi
- public abstract void onEnrolleeSuccess(int newNetworkId);
-
- /**
- * Called when a Easy Connect success event takes place, except for when configuration is
- * received from an external Configurator. The callback onSuccessConfigReceived will be used in
- * this case. This callback marks the successful end of the current Easy Connect session, and no
- * further callbacks will be called. This callback is the successful outcome of a Easy Connect
- * flow starting with {@link WifiManager#startEasyConnectAsConfiguratorInitiator(String, int,
- * int, Executor,EasyConnectStatusCallback)}.
- *
- * @param code Easy Connect success status code.
- * @hide
- */
- @SystemApi
- public abstract void onConfiguratorSuccess(@EasyConnectSuccessStatusCode int code);
-
- /**
- * Called when a Easy Connect Failure event takes place. This callback marks the unsuccessful
- * end of the current Easy Connect session, and no further callbacks will be called.
- *
- * @param code Easy Connect failure status code.
- * @hide
- */
- @SystemApi
- public void onFailure(@EasyConnectFailureStatusCode int code) {}
-
- /**
- * Called when a Easy Connect Failure event takes place. This callback marks the unsuccessful
- * end of the current Easy Connect session, and no further callbacks will be called.
- *
- * Note: Easy Connect (DPP) R2, provides additional details for the Configurator when the
- * remote Enrollee is unable to connect to a network. The ssid, channelList and bandList
- * inputs are initialized only for the EASY_CONNECT_EVENT_FAILURE_CANNOT_FIND_NETWORK failure
- * code, and the ssid and bandList are initialized for the
- * EASY_CONNECT_EVENT_FAILURE_ENROLLEE_AUTHENTICATION failure code.
- *
- * @param code Easy Connect failure status code.
- * @param ssid SSID of the network the Enrollee tried to connect to.
- * @param channelListArray List of Global Operating classes and channel sets the Enrollee used
- * to scan to find the network, see the "DPP Connection Status Object"
- * section in the specification for the format, and Table E-4 in
- * IEEE Std 802.11-2016 - Global operating classes for more details.
- * The sparse array key is the Global Operating class, and the value
- * is an integer array of Wi-Fi channels.
- * @param operatingClassArray Array of bands the Enrollee supports as expressed as the Global
- * Operating Class, see Table E-4 in IEEE Std 802.11-2016 - Global
- * operating classes.
- * @hide
- */
- @SystemApi
- public void onFailure(@EasyConnectFailureStatusCode int code, @Nullable String ssid,
- @NonNull SparseArray<int[]> channelListArray, @NonNull int[] operatingClassArray) {
- onFailure(code);
- }
-
- /**
- * Called when Easy Connect events that indicate progress take place. Can be used by UI elements
- * to show progress.
- *
- * @param code Easy Connect progress status code.
- * @hide
- */
- @SystemApi
- public abstract void onProgress(@EasyConnectProgressStatusCode int code);
-
- /**
- * Called when local Easy Connect Responder successfully generates a DPP URI from
- * the supplicant. This callback is the first successful outcome
- * of a Easy Connect Responder flow starting with
- * {@link WifiManager#startEasyConnectAsEnrolleeResponder(String, int, Executor,
- * EasyConnectStatusCallback)} .
- *
- * @param uri DPP URI from the supplicant.
- * @hide
- */
- @SystemApi
- public void onBootstrapUriGenerated(@NonNull String uri) {};
-}
diff --git a/wifi/java/android/net/wifi/IActionListener.aidl b/wifi/java/android/net/wifi/IActionListener.aidl
deleted file mode 100644
index faa0901cb087..000000000000
--- a/wifi/java/android/net/wifi/IActionListener.aidl
+++ /dev/null
@@ -1,27 +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 android.net.wifi;
-
-/**
- * Interface for generic wifi callbacks.
- * @hide
- */
-oneway interface IActionListener
-{
- void onSuccess();
- void onFailure(int reason);
-}
diff --git a/wifi/java/android/net/wifi/ICoexCallback.aidl b/wifi/java/android/net/wifi/ICoexCallback.aidl
deleted file mode 100644
index 89e4c4b93013..000000000000
--- a/wifi/java/android/net/wifi/ICoexCallback.aidl
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2020 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;
-
-/**
- * Interface for Wi-Fi/cellular coex callback.
- * @hide
- */
-oneway interface ICoexCallback
-{
- void onCoexUnsafeChannelsChanged();
-}
diff --git a/wifi/java/android/net/wifi/IDppCallback.aidl b/wifi/java/android/net/wifi/IDppCallback.aidl
deleted file mode 100644
index dcbe8468de9e..000000000000
--- a/wifi/java/android/net/wifi/IDppCallback.aidl
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2018 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;
-
-/**
- * Interface for DPP callback.
- *
- * @hide
- */
-oneway interface IDppCallback
-{
- /**
- * Called when local DPP Enrollee successfully receives a new Wi-Fi configuratrion from the
- * peer DPP configurator.
- */
- void onSuccessConfigReceived(int newNetworkId);
-
- /**
- * Called when DPP success events take place, except for when configuration is received from
- * an external Configurator. The callback onSuccessConfigReceived will be used in this case.
- */
- void onSuccess(int status);
-
- /**
- * Called when DPP Failure events take place.
- */
- void onFailure(int status, String ssid, String channelList, in int[] bandArray);
-
- /**
- * Called when DPP events that indicate progress take place. Can be used by UI elements
- * to show progress.
- */
- void onProgress(int status);
-
- /**
- * Called when local DPP Responder successfully generates a URI.
- */
- void onBootstrapUriGenerated(String uri);
-
-}
diff --git a/wifi/java/android/net/wifi/ILocalOnlyHotspotCallback.aidl b/wifi/java/android/net/wifi/ILocalOnlyHotspotCallback.aidl
deleted file mode 100644
index b567f29660a7..000000000000
--- a/wifi/java/android/net/wifi/ILocalOnlyHotspotCallback.aidl
+++ /dev/null
@@ -1,30 +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 android.net.wifi;
-
-import android.net.wifi.SoftApConfiguration;
-
-/**
- * Communicates LOHS status back to the application process.
- *
- * @hide
- */
-oneway interface ILocalOnlyHotspotCallback {
- void onHotspotStarted(in SoftApConfiguration config);
- void onHotspotStopped();
- void onHotspotFailed(int reason);
-}
diff --git a/wifi/java/android/net/wifi/INetworkRequestMatchCallback.aidl b/wifi/java/android/net/wifi/INetworkRequestMatchCallback.aidl
deleted file mode 100644
index d14ec57ea07a..000000000000
--- a/wifi/java/android/net/wifi/INetworkRequestMatchCallback.aidl
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2018 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.wifi.INetworkRequestUserSelectionCallback;
-import android.net.wifi.ScanResult;
-import android.net.wifi.WifiConfiguration;
-
-/**
- * Interface for network request match callback.
- *
- * @hide
- */
-oneway interface INetworkRequestMatchCallback
-{
- void onUserSelectionCallbackRegistration(in INetworkRequestUserSelectionCallback userSelectionCallback);
-
- void onAbort();
-
- void onMatch(in List<ScanResult> scanResults);
-
- void onUserSelectionConnectSuccess(in WifiConfiguration wificonfiguration);
-
- void onUserSelectionConnectFailure(in WifiConfiguration wificonfiguration);
-}
diff --git a/wifi/java/android/net/wifi/INetworkRequestUserSelectionCallback.aidl b/wifi/java/android/net/wifi/INetworkRequestUserSelectionCallback.aidl
deleted file mode 100644
index 524cefbb295f..000000000000
--- a/wifi/java/android/net/wifi/INetworkRequestUserSelectionCallback.aidl
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2018 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.wifi.WifiConfiguration;
-
-/**
- * Interface for providing user selection in response to
- * network request match callback.
- * @hide
- */
-oneway interface INetworkRequestUserSelectionCallback
-{
- void select(in WifiConfiguration wificonfiguration);
-
- void reject();
-}
diff --git a/wifi/java/android/net/wifi/IOnWifiActivityEnergyInfoListener.aidl b/wifi/java/android/net/wifi/IOnWifiActivityEnergyInfoListener.aidl
deleted file mode 100644
index 7e25fd8a3be2..000000000000
--- a/wifi/java/android/net/wifi/IOnWifiActivityEnergyInfoListener.aidl
+++ /dev/null
@@ -1,33 +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 android.net.wifi;
-
-import android.os.connectivity.WifiActivityEnergyInfo;
-
-/**
- * Interface for Wi-Fi activity energy info listener.
- *
- * @hide
- */
-oneway interface IOnWifiActivityEnergyInfoListener
-{
- /**
- * Service to manager callback providing current Wi-Fi activity energy info.
- * @param info the Wi-Fi activity energy info
- */
- void onWifiActivityEnergyInfo(in WifiActivityEnergyInfo info);
-}
diff --git a/wifi/java/android/net/wifi/IOnWifiUsabilityStatsListener.aidl b/wifi/java/android/net/wifi/IOnWifiUsabilityStatsListener.aidl
deleted file mode 100644
index 4687f3088eef..000000000000
--- a/wifi/java/android/net/wifi/IOnWifiUsabilityStatsListener.aidl
+++ /dev/null
@@ -1,41 +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 android.net.wifi;
-
-import android.net.wifi.WifiUsabilityStatsEntry;
-
-/**
- * Interface for Wi-Fi usability stats listener.
- *
- * @hide
- */
-oneway interface IOnWifiUsabilityStatsListener
-{
- /**
- * Service to manager callback providing current Wi-Fi usability stats.
- *
- * @param seqNum The sequence number of stats, used to derive the timing of updated Wi-Fi
- * usability statistics, set by framework and shall be incremented by one
- * after each update.
- * @param isSameBssidAndFreq The flag to indicate whether the BSSID and the frequency of
- * network stays the same or not relative to the last update of
- * Wi-Fi usability stats.
- * @param stats The updated Wi-Fi usability statistics.
- */
- void onWifiUsabilityStats(int seqNum, boolean isSameBssidAndFreq,
- in WifiUsabilityStatsEntry stats);
-}
diff --git a/wifi/java/android/net/wifi/IScanResultsCallback.aidl b/wifi/java/android/net/wifi/IScanResultsCallback.aidl
deleted file mode 100644
index 56f602510fd9..000000000000
--- a/wifi/java/android/net/wifi/IScanResultsCallback.aidl
+++ /dev/null
@@ -1,27 +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 android.net.wifi;
-
-/**
- * Interface for Wi-Fi scan result available callback.
- *
- * @hide
- */
-oneway interface IScanResultsCallback
-{
- void onScanResultsAvailable();
-}
diff --git a/wifi/java/android/net/wifi/IScanResultsListener.aidl b/wifi/java/android/net/wifi/IScanResultsListener.aidl
deleted file mode 100644
index e7eaddd712c9..000000000000
--- a/wifi/java/android/net/wifi/IScanResultsListener.aidl
+++ /dev/null
@@ -1,24 +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 android.net.wifi;
-
-/** @hide */
-
-oneway interface IScanResultsListener
-{
- void onScanResultsAvailable();
-}
diff --git a/wifi/java/android/net/wifi/IScoreUpdateObserver.aidl b/wifi/java/android/net/wifi/IScoreUpdateObserver.aidl
deleted file mode 100644
index 775fed7d47ef..000000000000
--- a/wifi/java/android/net/wifi/IScoreUpdateObserver.aidl
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2020 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;
-
-/**
- * Interface for Wi-Fi score callback.
- *
- * @hide
- */
-oneway interface IScoreUpdateObserver
-{
- void notifyScoreUpdate(int sessionId, int score);
-
- void triggerUpdateOfWifiUsabilityStats(int sessionId);
-}
diff --git a/wifi/java/android/net/wifi/ISoftApCallback.aidl b/wifi/java/android/net/wifi/ISoftApCallback.aidl
deleted file mode 100644
index f81bcb9e06d7..000000000000
--- a/wifi/java/android/net/wifi/ISoftApCallback.aidl
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2018 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.wifi.SoftApCapability;
-import android.net.wifi.SoftApInfo;
-
-import android.net.wifi.WifiClient;
-
-/**
- * Interface for Soft AP callback.
- *
- * @hide
- */
-oneway interface ISoftApCallback
-{
- /**
- * Service to manager callback providing current soft AP state. The possible
- * parameter values listed are defined in WifiManager.java
- *
- * @param state new AP state. One of WIFI_AP_STATE_DISABLED,
- * WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_ENABLED,
- * WIFI_AP_STATE_ENABLING, WIFI_AP_STATE_FAILED
- * @param failureReason reason when in failed state. One of
- * SAP_START_FAILURE_GENERAL, SAP_START_FAILURE_NO_CHANNEL
- */
- void onStateChanged(int state, int failureReason);
-
- /**
- * Service to manager callback providing connected client's information.
- *
- * @param clients the currently connected clients
- */
- void onConnectedClientsChanged(in List<WifiClient> clients);
-
- /**
- * Service to manager callback providing information of softap.
- *
- * @param softApInfo is the softap information. {@link SoftApInfo}
- */
- void onInfoChanged(in SoftApInfo softApInfo);
-
-
- /**
- * Service to manager callback providing capability of softap.
- *
- * @param capability is the softap capability. {@link SoftApCapability}
- */
- void onCapabilityChanged(in SoftApCapability capability);
-
- /**
- * Service to manager callback providing blocked client of softap with specific reason code.
- *
- * @param client the currently blocked client.
- * @param blockedReason one of blocked reason from {@link WifiManager.SapClientBlockedReason}
- */
- void onBlockedClientConnecting(in WifiClient client, int blockedReason);
-}
diff --git a/wifi/java/android/net/wifi/ISuggestionConnectionStatusListener.aidl b/wifi/java/android/net/wifi/ISuggestionConnectionStatusListener.aidl
deleted file mode 100644
index b49e49ba0cd5..000000000000
--- a/wifi/java/android/net/wifi/ISuggestionConnectionStatusListener.aidl
+++ /dev/null
@@ -1,29 +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 android.net.wifi;
-
-import android.net.wifi.WifiNetworkSuggestion;
-
-/**
- * Interface for suggestion network connection listener.
- *
- * @hide
- */
-oneway interface ISuggestionConnectionStatusListener
-{
- void onConnectionStatus(in WifiNetworkSuggestion wifiNetworkSuggestion, int failureReason);
-}
diff --git a/wifi/java/android/net/wifi/ITrafficStateCallback.aidl b/wifi/java/android/net/wifi/ITrafficStateCallback.aidl
deleted file mode 100644
index 0c8e777f67ba..000000000000
--- a/wifi/java/android/net/wifi/ITrafficStateCallback.aidl
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2018 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;
-
-/**
- * Interface for Traffic state callback.
- *
- * @hide
- */
-oneway interface ITrafficStateCallback
-{
- /**
- * Callback invoked to inform clients about the current traffic state.
- *
- * @param state One of the values: {@link #DATA_ACTIVITY_NONE}, {@link #DATA_ACTIVITY_IN},
- * {@link #DATA_ACTIVITY_OUT} & {@link #DATA_ACTIVITY_INOUT}.
- * @hide
- */
- void onStateChanged(int state);
-}
diff --git a/wifi/java/android/net/wifi/IWifiConnectedNetworkScorer.aidl b/wifi/java/android/net/wifi/IWifiConnectedNetworkScorer.aidl
deleted file mode 100644
index f96d037cbfea..000000000000
--- a/wifi/java/android/net/wifi/IWifiConnectedNetworkScorer.aidl
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2020 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.wifi.IScoreUpdateObserver;
-
-/**
- * Interface for Wi-Fi connected network scorer.
- *
- * @hide
- */
-oneway interface IWifiConnectedNetworkScorer
-{
- void onStart(int sessionId);
-
- void onStop(int sessionId);
-
- void onSetScoreUpdateObserver(IScoreUpdateObserver observerImpl);
-}
diff --git a/wifi/java/android/net/wifi/IWifiManager.aidl b/wifi/java/android/net/wifi/IWifiManager.aidl
deleted file mode 100644
index 429f4927d0c5..000000000000
--- a/wifi/java/android/net/wifi/IWifiManager.aidl
+++ /dev/null
@@ -1,338 +0,0 @@
-/**
- * Copyright (c) 2008, 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.content.pm.ParceledListSlice;
-
-import android.net.wifi.hotspot2.OsuProvider;
-import android.net.wifi.hotspot2.PasspointConfiguration;
-import android.net.wifi.hotspot2.IProvisioningCallback;
-
-import android.net.DhcpInfo;
-import android.net.Network;
-import android.net.wifi.CoexUnsafeChannel;
-import android.net.wifi.IActionListener;
-import android.net.wifi.ICoexCallback;
-import android.net.wifi.IDppCallback;
-import android.net.wifi.ILocalOnlyHotspotCallback;
-import android.net.wifi.INetworkRequestMatchCallback;
-import android.net.wifi.IOnWifiActivityEnergyInfoListener;
-import android.net.wifi.IOnWifiUsabilityStatsListener;
-import android.net.wifi.IScanResultsCallback;
-import android.net.wifi.ISoftApCallback;
-import android.net.wifi.ISuggestionConnectionStatusListener;
-import android.net.wifi.ITrafficStateCallback;
-import android.net.wifi.IWifiConnectedNetworkScorer;
-import android.net.wifi.ScanResult;
-import android.net.wifi.SoftApConfiguration;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiInfo;
-import android.net.wifi.WifiDppConfig;
-import android.net.wifi.WifiNetworkSuggestion;
-
-import android.os.Messenger;
-import android.os.ResultReceiver;
-import android.os.WorkSource;
-
-/**
- * Interface that allows controlling and querying Wi-Fi connectivity.
- *
- * {@hide}
- */
-interface IWifiManager
-{
- long getSupportedFeatures();
-
- oneway void getWifiActivityEnergyInfoAsync(in IOnWifiActivityEnergyInfoListener listener);
-
- ParceledListSlice getConfiguredNetworks(String packageName, String featureId);
-
- ParceledListSlice getPrivilegedConfiguredNetworks(String packageName, String featureId);
-
- Map getAllMatchingFqdnsForScanResults(in List<ScanResult> scanResult);
-
- Map getMatchingOsuProviders(in List<ScanResult> scanResult);
-
- Map getMatchingPasspointConfigsForOsuProviders(in List<OsuProvider> osuProviders);
-
- int addOrUpdateNetwork(in WifiConfiguration config, String packageName);
-
- boolean addOrUpdatePasspointConfiguration(in PasspointConfiguration config, String packageName);
-
- boolean removePasspointConfiguration(in String fqdn, String packageName);
-
- List<PasspointConfiguration> getPasspointConfigurations(in String packageName);
-
- List<WifiConfiguration> getWifiConfigsForPasspointProfiles(in List<String> fqdnList);
-
- void queryPasspointIcon(long bssid, String fileName);
-
- int matchProviderWithCurrentNetwork(String fqdn);
-
- boolean removeNetwork(int netId, String packageName);
-
- boolean enableNetwork(int netId, boolean disableOthers, String packageName);
-
- boolean disableNetwork(int netId, String packageName);
-
- void allowAutojoinGlobal(boolean choice);
-
- void allowAutojoin(int netId, boolean choice);
-
- void allowAutojoinPasspoint(String fqdn, boolean enableAutoJoin);
-
- void setMacRandomizationSettingPasspointEnabled(String fqdn, boolean enable);
-
- void setPasspointMeteredOverride(String fqdn, int meteredOverride);
-
- boolean startScan(String packageName, String featureId);
-
- List<ScanResult> getScanResults(String callingPackage, String callingFeatureId);
-
- boolean disconnect(String packageName);
-
- boolean reconnect(String packageName);
-
- boolean reassociate(String packageName);
-
- WifiInfo getConnectionInfo(String callingPackage, String callingFeatureId);
-
- boolean setWifiEnabled(String packageName, boolean enable);
-
- int getWifiEnabledState();
-
- String getCountryCode();
-
- boolean is5GHzBandSupported();
-
- boolean is6GHzBandSupported();
-
- boolean is60GHzBandSupported();
-
- boolean isWifiStandardSupported(int standard);
-
- DhcpInfo getDhcpInfo();
-
- void setScanAlwaysAvailable(boolean isAvailable, String packageName);
-
- boolean isScanAlwaysAvailable();
-
- boolean acquireWifiLock(IBinder lock, int lockType, String tag, in WorkSource ws);
-
- void updateWifiLockWorkSource(IBinder lock, in WorkSource ws);
-
- boolean releaseWifiLock(IBinder lock);
-
- void initializeMulticastFiltering();
-
- boolean isMulticastEnabled();
-
- void acquireMulticastLock(IBinder binder, String tag);
-
- void releaseMulticastLock(String tag);
-
- void updateInterfaceIpState(String ifaceName, int mode);
-
- void setCoexUnsafeChannels(in List<CoexUnsafeChannel> unsafeChannels, int mandatoryRestrictions);
-
- List<CoexUnsafeChannel> getCoexUnsafeChannels();
-
- int getCoexRestrictions();
-
- void registerCoexCallback(in ICoexCallback callback);
-
- void unregisterCoexCallback(in ICoexCallback callback);
-
- boolean startSoftAp(in WifiConfiguration wifiConfig, String packageName);
-
- boolean startTetheredHotspot(in SoftApConfiguration softApConfig, String packageName);
-
- boolean stopSoftAp();
-
- int startLocalOnlyHotspot(in ILocalOnlyHotspotCallback callback, String packageName,
- String featureId, in SoftApConfiguration customConfig);
-
- void stopLocalOnlyHotspot();
-
- void startWatchLocalOnlyHotspot(in ILocalOnlyHotspotCallback callback);
-
- void stopWatchLocalOnlyHotspot();
-
- @UnsupportedAppUsage
- int getWifiApEnabledState();
-
- @UnsupportedAppUsage
- WifiConfiguration getWifiApConfiguration();
-
- SoftApConfiguration getSoftApConfiguration();
-
- boolean setWifiApConfiguration(in WifiConfiguration wifiConfig, String packageName);
-
- boolean setSoftApConfiguration(in SoftApConfiguration softApConfig, String packageName);
-
- void notifyUserOfApBandConversion(String packageName);
-
- void enableTdls(String remoteIPAddress, boolean enable);
-
- void enableTdlsWithMacAddress(String remoteMacAddress, boolean enable);
-
- String getCurrentNetworkWpsNfcConfigurationToken();
-
- void enableVerboseLogging(int verbose);
-
- int getVerboseLoggingLevel();
-
- void disableEphemeralNetwork(String SSID, String packageName);
-
- void factoryReset(String packageName);
-
- @UnsupportedAppUsage(maxTargetSdk = 30, trackingBug = 170729553)
- Network getCurrentNetwork();
-
- byte[] retrieveBackupData();
-
- void restoreBackupData(in byte[] data);
-
- byte[] retrieveSoftApBackupData();
-
- SoftApConfiguration restoreSoftApBackupData(in byte[] data);
-
- void restoreSupplicantBackupData(in byte[] supplicantData, in byte[] ipConfigData);
-
- void startSubscriptionProvisioning(in OsuProvider provider, in IProvisioningCallback callback);
-
- void registerSoftApCallback(in IBinder binder, in ISoftApCallback callback, int callbackIdentifier);
-
- void unregisterSoftApCallback(int callbackIdentifier);
-
- void addOnWifiUsabilityStatsListener(in IBinder binder, in IOnWifiUsabilityStatsListener listener, int listenerIdentifier);
-
- void removeOnWifiUsabilityStatsListener(int listenerIdentifier);
-
- void registerTrafficStateCallback(in IBinder binder, in ITrafficStateCallback callback, int callbackIdentifier);
-
- void unregisterTrafficStateCallback(int callbackIdentifier);
-
- String getCapabilities(String capaType);
-
- int dppAddBootstrapQrCode(String uri);
-
- int dppBootstrapGenerate(in WifiDppConfig config);
-
- String dppGetUri(int bootstrap_id);
-
- int dppBootstrapRemove(int bootstrap_id);
-
- int dppListen(String frequency, int dpp_role, boolean qr_mutual, boolean netrole_ap);
-
- void dppStopListen();
-
- int dppConfiguratorAdd(String curve, String key, int expiry);
-
- int dppConfiguratorRemove(int config_id);
-
- int dppStartAuth(in WifiDppConfig config);
-
- String dppConfiguratorGetKey(int id);
-
- boolean isExtendingWifi();
-
- boolean isWifiCoverageExtendFeatureEnabled();
-
- void enableWifiCoverageExtendFeature(boolean enable);
-
- void registerNetworkRequestMatchCallback(in IBinder binder, in INetworkRequestMatchCallback callback, int callbackIdentifier);
-
- void unregisterNetworkRequestMatchCallback(int callbackIdentifier);
-
- int addNetworkSuggestions(in List<WifiNetworkSuggestion> networkSuggestions, in String packageName,
- in String featureId);
-
- int removeNetworkSuggestions(in List<WifiNetworkSuggestion> networkSuggestions, in String packageName);
-
- List<WifiNetworkSuggestion> getNetworkSuggestions(in String packageName);
-
- String[] getFactoryMacAddresses();
-
- void setDeviceMobilityState(int state);
-
- void startDppAsConfiguratorInitiator(in IBinder binder, in String enrolleeUri,
- int selectedNetworkId, int netRole, in IDppCallback callback);
-
- void startDppAsEnrolleeInitiator(in IBinder binder, in String configuratorUri,
- in IDppCallback callback);
-
- void startDppAsEnrolleeResponder(in IBinder binder, in String deviceInfo, int curve,
- in IDppCallback callback);
-
- void stopDppSession();
-
- void updateWifiUsabilityScore(int seqNum, int score, int predictionHorizonSec);
-
- oneway void connect(in WifiConfiguration config, int netId, in IActionListener listener);
-
- oneway void save(in WifiConfiguration config, in IActionListener listener);
-
- oneway void forget(int netId, in IActionListener listener);
-
- void registerScanResultsCallback(in IScanResultsCallback callback);
-
- void unregisterScanResultsCallback(in IScanResultsCallback callback);
-
- void registerSuggestionConnectionStatusListener(in IBinder binder, in ISuggestionConnectionStatusListener listener, int listenerIdentifier, String packageName, String featureId);
-
- void unregisterSuggestionConnectionStatusListener(int listenerIdentifier, String packageName);
-
- int calculateSignalLevel(int rssi);
-
- List<WifiConfiguration> getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(in List<ScanResult> scanResults);
-
- boolean setWifiConnectedNetworkScorer(in IBinder binder, in IWifiConnectedNetworkScorer scorer);
-
- void clearWifiConnectedNetworkScorer();
-
- /**
- * Return the Map of {@link WifiNetworkSuggestion} and the list of <ScanResult>
- */
- Map getMatchingScanResults(in List<WifiNetworkSuggestion> networkSuggestions, in List<ScanResult> scanResults, String callingPackage, String callingFeatureId);
-
- void setScanThrottleEnabled(boolean enable);
-
- boolean isScanThrottleEnabled();
-
- Map getAllMatchingPasspointProfilesForScanResults(in List<ScanResult> scanResult);
-
- void setAutoWakeupEnabled(boolean enable);
-
- boolean isAutoWakeupEnabled();
-
- int getNetworkSuggestionUserApprovalStatus(String packageName);
-
- void startTemporarilyDisablingAllNonCarrierMergedWifi(int subId);
-
- void stopTemporarilyDisablingAllNonCarrierMergedWifi();
-
- void setCarrierNetworkOffloadEnabled(int subscriptionId, boolean merged, boolean enabled);
-
- boolean isCarrierNetworkOffloadEnabled(int subscriptionId, boolean merged);
-
- int getSoftApWifiStandard();
-
- boolean isVht8ssCapableDevice();
-
- String doDriverCmd(String command);
-}
diff --git a/wifi/java/android/net/wifi/IWifiScanner.aidl b/wifi/java/android/net/wifi/IWifiScanner.aidl
deleted file mode 100644
index 485f5ce5415e..000000000000
--- a/wifi/java/android/net/wifi/IWifiScanner.aidl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2008 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.os.Messenger;
-import android.os.Bundle;
-
-/**
- * {@hide}
- */
-interface IWifiScanner
-{
- Messenger getMessenger();
-
- Bundle getAvailableChannels(int band, String packageName, String featureId);
-}
diff --git a/wifi/java/android/net/wifi/ParcelUtil.java b/wifi/java/android/net/wifi/ParcelUtil.java
deleted file mode 100644
index a26877d9b095..000000000000
--- a/wifi/java/android/net/wifi/ParcelUtil.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/**
- * Copyright (c) 2016, 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.os.Parcel;
-
-import java.io.ByteArrayInputStream;
-import java.security.KeyFactory;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.PKCS8EncodedKeySpec;
-
-/**
- * Provides utilities for writing/reading a non-Parcelable objects to/from
- * a Parcel object.
- *
- * @hide
- */
-public class ParcelUtil {
- /**
- * Write a PrivateKey object |key| to the specified Parcel |dest|.
- *
- * Below is the data format:
- * |algorithm| -> String of algorithm name
- * |endcodedKey| -> byte[] of key data
- *
- * For a null PrivateKey object, a null string will be written to |algorithm| and
- * |encodedKey| will be skipped. Since a PrivateKey can only be constructed with
- * a valid algorithm String.
- *
- * @param dest Parcel object to write to
- * @param key PrivateKey object to read from.
- */
- public static void writePrivateKey(Parcel dest, PrivateKey key) {
- if (key == null) {
- dest.writeString(null);
- return;
- }
-
- dest.writeString(key.getAlgorithm());
- dest.writeByteArray(key.getEncoded());
- }
-
- /**
- * Read/create a PrivateKey object from a specified Parcel object |in|.
- *
- * Refer to the function above for the expected data format.
- *
- * @param in Parcel object to read from
- * @return a PrivateKey object or null
- */
- public static PrivateKey readPrivateKey(Parcel in) {
- String algorithm = in.readString();
- if (algorithm == null) {
- return null;
- }
-
- byte[] userKeyBytes = in.createByteArray();
- try {
- KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
- return keyFactory.generatePrivate(new PKCS8EncodedKeySpec(userKeyBytes));
- } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
- return null;
- }
- }
-
- /**
- * Write a X509Certificate object |cert| to a Parcel object |dest|.
- * The data being written to the Parcel is just a byte[] of the encoded certificate data.
- *
- * @param dest Parcel object to write to
- * @param cert X509Certificate object to read from
- */
- public static void writeCertificate(Parcel dest, X509Certificate cert) {
- byte[] certBytes = null;
- if (cert != null) {
- try {
- certBytes = cert.getEncoded();
- } catch (CertificateEncodingException e) {
- /* empty, write null. */
- }
- }
- dest.writeByteArray(certBytes);
- }
-
- /**
- * Read/create a X509Certificate object from a specified Parcel object |in|.
- *
- * @param in Parcel object to read from
- * @return a X509Certficate object or null
- */
- public static X509Certificate readCertificate(Parcel in) {
- byte[] certBytes = in.createByteArray();
- if (certBytes == null) {
- return null;
- }
-
- try {
- CertificateFactory cFactory = CertificateFactory.getInstance("X.509");
- return (X509Certificate) cFactory
- .generateCertificate(new ByteArrayInputStream(certBytes));
- } catch (CertificateException e) {
- return null;
- }
- }
-
- /**
- * Write an array of X509Certificate objects |certs| to a Parcel object |dest|.
- * The data being written to the Parcel are consist of an integer indicating
- * the size of the array and the certificates data. Certificates data will be
- * skipped for a null array or size of 0 array.
- *
- * @param dest Parcel object to write to
- * @param certs array of X509Certificate objects to read from
- */
- public static void writeCertificates(Parcel dest, X509Certificate[] certs) {
- if (certs == null || certs.length == 0) {
- dest.writeInt(0);
- return;
- }
-
- dest.writeInt(certs.length);
- for (int i = 0; i < certs.length; i++) {
- writeCertificate(dest, certs[i]);
- }
- }
-
- /**
- * Read/create an array of X509Certificate objects from a specified Parcel object |in|.
- *
- * @param in Parcel object to read from
- * @return X509Certficate[] or null
- */
- public static X509Certificate[] readCertificates(Parcel in) {
- int length = in.readInt();
- if (length == 0) {
- return null;
- }
-
- X509Certificate[] certs = new X509Certificate[length];
- for (int i = 0; i < length; i++) {
- certs[i] = readCertificate(in);
- }
- return certs;
- }
-}
diff --git a/wifi/java/android/net/wifi/RttManager.aidl b/wifi/java/android/net/wifi/RttManager.aidl
deleted file mode 100644
index 9479cf0b936e..000000000000
--- a/wifi/java/android/net/wifi/RttManager.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-/**
- * Copyright (c) 2015, 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;
-
-parcelable RttManager.RttCapabilities;
-parcelable RttManager.ParcelableRttResults;
-parcelable RttManager.ParcelableRttParams;
diff --git a/wifi/java/android/net/wifi/RttManager.java b/wifi/java/android/net/wifi/RttManager.java
deleted file mode 100644
index 034defb083de..000000000000
--- a/wifi/java/android/net/wifi/RttManager.java
+++ /dev/null
@@ -1,1233 +0,0 @@
-package android.net.wifi;
-
-import android.Manifest;
-import android.annotation.NonNull;
-import android.annotation.RequiresPermission;
-import android.annotation.SuppressLint;
-import android.annotation.SystemApi;
-import android.annotation.SystemService;
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.net.wifi.rtt.RangingRequest;
-import android.net.wifi.rtt.RangingResult;
-import android.net.wifi.rtt.RangingResultCallback;
-import android.net.wifi.rtt.WifiRttManager;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.os.SystemClock;
-import android.util.Log;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.Protocol;
-
-import java.util.List;
-
-/** @hide */
-@SystemApi
-@Deprecated
-@SystemService(Context.WIFI_RTT_SERVICE)
-public class RttManager {
-
- private static final boolean DBG = false;
- private static final String TAG = "RttManager";
-
- /** @deprecated It is Not supported anymore. */
- @Deprecated
- public static final int RTT_TYPE_UNSPECIFIED = 0;
-
- public static final int RTT_TYPE_ONE_SIDED = 1;
- public static final int RTT_TYPE_TWO_SIDED = 2;
-
- /** @deprecated It is not supported anymore. */
- @Deprecated
- public static final int RTT_TYPE_11_V = 2;
-
- /** @deprecated It is not supported anymore. */
- @Deprecated
- public static final int RTT_TYPE_11_MC = 4;
-
- /** @deprecated It is not supported anymore. */
- @Deprecated
- public static final int RTT_PEER_TYPE_UNSPECIFIED = 0;
-
- public static final int RTT_PEER_TYPE_AP = 1;
- public static final int RTT_PEER_TYPE_STA = 2; /* requires NAN */
- public static final int RTT_PEER_P2P_GO = 3;
- public static final int RTT_PEER_P2P_CLIENT = 4;
- public static final int RTT_PEER_NAN = 5;
-
- /**
- * @deprecated It is not supported anymore.
- * Use {@link android.net.wifi.RttManager#RTT_BW_20_SUPPORT} API.
- */
- @Deprecated
- public static final int RTT_CHANNEL_WIDTH_20 = 0;
-
- /**
- * @deprecated It is not supported anymore.
- * Use {@link android.net.wifi.RttManager#RTT_BW_40_SUPPORT} API.
- */
- @Deprecated
- public static final int RTT_CHANNEL_WIDTH_40 = 1;
-
- /**
- * @deprecated It is not supported anymore.
- * Use {@link android.net.wifi.RttManager#RTT_BW_80_SUPPORT} API.
- */
- @Deprecated
- public static final int RTT_CHANNEL_WIDTH_80 = 2;
-
- /**@deprecated It is not supported anymore.
- * Use {@link android.net.wifi.RttManager#RTT_BW_160_SUPPORT} API.
- */
- @Deprecated
- public static final int RTT_CHANNEL_WIDTH_160 = 3;
-
- /**@deprecated not supported anymore*/
- @Deprecated
- public static final int RTT_CHANNEL_WIDTH_80P80 = 4;
-
- /**@deprecated It is not supported anymore.
- * Use {@link android.net.wifi.RttManager#RTT_BW_5_SUPPORT} API.
- */
- @Deprecated
- public static final int RTT_CHANNEL_WIDTH_5 = 5;
-
- /**@deprecated It is not supported anymore.
- * Use {@link android.net.wifi.RttManager#RTT_BW_10_SUPPORT} API.
- */
- @Deprecated
- public static final int RTT_CHANNEL_WIDTH_10 = 6;
-
- /** @deprecated channel info must be specified. */
- @Deprecated
- public static final int RTT_CHANNEL_WIDTH_UNSPECIFIED = -1;
-
- public static final int RTT_STATUS_SUCCESS = 0;
- /** General failure*/
- public static final int RTT_STATUS_FAILURE = 1;
- /** Destination does not respond to RTT request*/
- public static final int RTT_STATUS_FAIL_NO_RSP = 2;
- /** RTT request is rejected by the destination. Double side RTT only*/
- public static final int RTT_STATUS_FAIL_REJECTED = 3;
- /** */
- public static final int RTT_STATUS_FAIL_NOT_SCHEDULED_YET = 4;
- /** Timing measurement timeout*/
- public static final int RTT_STATUS_FAIL_TM_TIMEOUT = 5;
- /** Destination is on a different channel from the RTT Request*/
- public static final int RTT_STATUS_FAIL_AP_ON_DIFF_CHANNEL = 6;
- /** This type of Ranging is not support by Hardware*/
- public static final int RTT_STATUS_FAIL_NO_CAPABILITY = 7;
- /** Request abort fro uncertain reason*/
- public static final int RTT_STATUS_ABORTED = 8;
- /** The T1-T4 or TOD/TOA Timestamp is illegal*/
- public static final int RTT_STATUS_FAIL_INVALID_TS = 9;
- /** 11mc protocol level failed, eg, unrecognized FTMR/FTM frame*/
- public static final int RTT_STATUS_FAIL_PROTOCOL = 10;
- /** Request can not be scheduled by hardware*/
- public static final int RTT_STATUS_FAIL_SCHEDULE = 11;
- /** destination is busy now, you can try after a specified time from destination*/
- public static final int RTT_STATUS_FAIL_BUSY_TRY_LATER = 12;
- /** Bad Request argument*/
- public static final int RTT_STATUS_INVALID_REQ = 13;
- /** Wifi is not enabled*/
- public static final int RTT_STATUS_NO_WIFI = 14;
- /** Responder overrides param info, cannot range with new params 2-side RTT only*/
- public static final int RTT_STATUS_FAIL_FTM_PARAM_OVERRIDE = 15;
-
- public static final int REASON_UNSPECIFIED = -1;
- public static final int REASON_NOT_AVAILABLE = -2;
- public static final int REASON_INVALID_LISTENER = -3;
- public static final int REASON_INVALID_REQUEST = -4;
- /** Do not have required permission */
- public static final int REASON_PERMISSION_DENIED = -5;
- /** Ranging failed because responder role is enabled in STA mode.*/
- public static final int
- REASON_INITIATOR_NOT_ALLOWED_WHEN_RESPONDER_ON = -6;
-
- public static final String DESCRIPTION_KEY = "android.net.wifi.RttManager.Description";
-
- /**
- * RTT BW supported bit mask, used as RTT param bandWidth too
- */
- public static final int RTT_BW_5_SUPPORT = 0x01;
- public static final int RTT_BW_10_SUPPORT = 0x02;
- public static final int RTT_BW_20_SUPPORT = 0x04;
- public static final int RTT_BW_40_SUPPORT = 0x08;
- public static final int RTT_BW_80_SUPPORT = 0x10;
- public static final int RTT_BW_160_SUPPORT = 0x20;
-
- /**
- * RTT Preamble Support bit mask
- */
- public static final int PREAMBLE_LEGACY = 0x01;
- public static final int PREAMBLE_HT = 0x02;
- public static final int PREAMBLE_VHT = 0x04;
-
- /** @deprecated Use the new {@link android.net.wifi.RttManager.RttCapabilities} API */
- @Deprecated
- public class Capabilities {
- public int supportedType;
- public int supportedPeerType;
- }
-
- /** @deprecated Use the new {@link android.net.wifi.RttManager#getRttCapabilities()} API.*/
- @Deprecated
- @SuppressLint("RequiresPermission")
- public Capabilities getCapabilities() {
- throw new UnsupportedOperationException(
- "getCapabilities is not supported in the adaptation layer");
- }
-
- /**
- * This class describe the RTT capability of the Hardware
- */
- @Deprecated
- public static class RttCapabilities implements Parcelable {
- /** @deprecated It is not supported*/
- @Deprecated
- public boolean supportedType;
- /** @deprecated It is not supported*/
- @Deprecated
- public boolean supportedPeerType;
- //1-sided rtt measurement is supported
- public boolean oneSidedRttSupported;
- //11mc 2-sided rtt measurement is supported
- public boolean twoSided11McRttSupported;
- //location configuration information supported
- public boolean lciSupported;
- //location civic records supported
- public boolean lcrSupported;
- //preamble supported, see bit mask definition above
- public int preambleSupported;
- //RTT bandwidth supported
- public int bwSupported;
- // Whether STA responder role is supported.
- public boolean responderSupported;
-
- /** Whether the secure RTT protocol is supported. */
- public boolean secureRttSupported;
-
- /** Draft 11mc version supported, including major and minor version. e.g, draft 4.3 is 43 */
- public int mcVersion;
-
- @NonNull
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append("oneSidedRtt ").
- append(oneSidedRttSupported ? "is Supported. " : "is not supported. ").
- append("twoSided11McRtt ").
- append(twoSided11McRttSupported ? "is Supported. " : "is not supported. ").
- append("lci ").
- append(lciSupported ? "is Supported. " : "is not supported. ").
- append("lcr ").
- append(lcrSupported ? "is Supported. " : "is not supported. ");
-
- if ((preambleSupported & PREAMBLE_LEGACY) != 0) {
- sb.append("Legacy ");
- }
-
- if ((preambleSupported & PREAMBLE_HT) != 0) {
- sb.append("HT ");
- }
-
- if ((preambleSupported & PREAMBLE_VHT) != 0) {
- sb.append("VHT ");
- }
-
- sb.append("is supported. ");
-
- if ((bwSupported & RTT_BW_5_SUPPORT) != 0) {
- sb.append("5 MHz ");
- }
-
- if ((bwSupported & RTT_BW_10_SUPPORT) != 0) {
- sb.append("10 MHz ");
- }
-
- if ((bwSupported & RTT_BW_20_SUPPORT) != 0) {
- sb.append("20 MHz ");
- }
-
- if ((bwSupported & RTT_BW_40_SUPPORT) != 0) {
- sb.append("40 MHz ");
- }
-
- if ((bwSupported & RTT_BW_80_SUPPORT) != 0) {
- sb.append("80 MHz ");
- }
-
- if ((bwSupported & RTT_BW_160_SUPPORT) != 0) {
- sb.append("160 MHz ");
- }
-
- sb.append("is supported.");
-
- sb.append(" STA responder role is ")
- .append(responderSupported ? "supported" : "not supported");
- sb.append(" Secure RTT protocol is ")
- .append(secureRttSupported ? "supported" : "not supported");
- sb.append(" 11mc version is " + mcVersion);
-
- return sb.toString();
- }
- /** Implement the Parcelable interface {@hide} */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(oneSidedRttSupported ? 1 : 0);
- dest.writeInt(twoSided11McRttSupported ? 1 : 0);
- dest.writeInt(lciSupported ? 1 : 0);
- dest.writeInt(lcrSupported ? 1 : 0);
- dest.writeInt(preambleSupported);
- dest.writeInt(bwSupported);
- dest.writeInt(responderSupported ? 1 : 0);
- dest.writeInt(secureRttSupported ? 1 : 0);
- dest.writeInt(mcVersion);
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @android.annotation.NonNull Creator<RttCapabilities> CREATOR =
- new Creator<RttCapabilities>() {
- @Override
- public RttCapabilities createFromParcel(Parcel in) {
- RttCapabilities capabilities = new RttCapabilities();
- capabilities.oneSidedRttSupported = (in.readInt() == 1);
- capabilities.twoSided11McRttSupported = (in.readInt() == 1);
- capabilities.lciSupported = (in.readInt() == 1);
- capabilities.lcrSupported = (in.readInt() == 1);
- capabilities.preambleSupported = in.readInt();
- capabilities.bwSupported = in.readInt();
- capabilities.responderSupported = (in.readInt() == 1);
- capabilities.secureRttSupported = (in.readInt() == 1);
- capabilities.mcVersion = in.readInt();
- return capabilities;
- }
- /** Implement the Parcelable interface {@hide} */
- @Override
- public RttCapabilities[] newArray(int size) {
- return new RttCapabilities[size];
- }
- };
- }
-
- /**
- * This method is deprecated. Please use the {@link WifiRttManager} API.
- */
- @RequiresPermission(Manifest.permission.LOCATION_HARDWARE)
- public RttCapabilities getRttCapabilities() {
- return mRttCapabilities;
- }
-
- /** specifies parameters for RTT request */
- @Deprecated
- public static class RttParams {
- /**
- * type of destination device being ranged
- * currently only support RTT_PEER_TYPE_AP
- * Range:RTT_PEER_TYPE_xxxx Default value:RTT_PEER_TYPE_AP
- */
- public int deviceType;
-
- /**
- * type of RTT measurement method. Need check scan result and RttCapabilities first
- * Range: RTT_TYPE_ONE_SIDED or RTT_TYPE_TWO_SIDED
- * Default value: RTT_TYPE_ONE_SIDED
- */
- public int requestType;
-
- /**
- * Whether the secure RTT protocol needs to be used for ranging this peer device.
- */
- public boolean secure;
-
- /**
- * mac address of the device being ranged
- * Default value: null
- */
- public String bssid;
-
- /**
- * The primary control channel over which the client is
- * communicating with the AP.Same as ScanResult.frequency
- * Default value: 0
- */
- public int frequency;
-
- /**
- * channel width of the destination AP. Same as ScanResult.channelWidth
- * Default value: 0
- */
- public int channelWidth;
-
- /**
- * Not used if the AP bandwidth is 20 MHz
- * If the AP use 40, 80 or 160 MHz, this is the center frequency
- * if the AP use 80 + 80 MHz, this is the center frequency of the first segment
- * same as ScanResult.centerFreq0
- * Default value: 0
- */
- public int centerFreq0;
-
- /**
- * Only used if the AP bandwidth is 80 + 80 MHz
- * if the AP use 80 + 80 MHz, this is the center frequency of the second segment
- * same as ScanResult.centerFreq1
- * Default value: 0
- */
- public int centerFreq1;
-
- /**
- * number of samples to be taken
- * @deprecated Use the new {@link android.net.wifi.RttManager.RttParams#numSamplesPerBurst}
- */
- @Deprecated
- public int num_samples;
-
- /**
- * number of retries if a sample fails
- * @deprecated
- * Use {@link android.net.wifi.RttManager.RttParams#numRetriesPerMeasurementFrame} API.
- */
- @Deprecated
- public int num_retries;
-
- /** Number of burst in exp , 2^x. 0 means single shot measurement, range 0-15
- * Currently only single shot is supported
- * Default value: 0
- */
- public int numberBurst;
-
- /**
- * valid only if numberBurst > 1, interval between burst(100ms).
- * Range : 0-31, 0--means no specific
- * Default value: 0
- */
- public int interval;
-
- /**
- * number of samples to be taken in one burst
- * Range: 1-31
- * Default value: 8
- */
- public int numSamplesPerBurst;
-
- /** number of retries for each measurement frame if a sample fails
- * Only used by single side RTT,
- * Range 0 - 3 Default value: 0
- */
- public int numRetriesPerMeasurementFrame;
-
- /**
- * number of retries for FTMR frame (control frame) if it fails.
- * Only used by 80211MC double side RTT
- * Range: 0-3 Default Value : 0
- */
- public int numRetriesPerFTMR;
-
- /**
- * Request LCI information, only available when choose double side RTT measurement
- * need check RttCapabilties first.
- * Default value: false
- * */
- public boolean LCIRequest;
-
- /**
- * Request LCR information, only available when choose double side RTT measurement
- * need check RttCapabilties first.
- * Default value: false
- * */
- public boolean LCRRequest;
-
- /**
- * Timeout for each burst, (250 * 2^x) us,
- * Range 1-11 and 15. 15 means no control Default value: 15
- * */
- public int burstTimeout;
-
- /** preamble used for RTT measurement
- * Range: PREAMBLE_LEGACY, PREAMBLE_HT, PREAMBLE_VHT
- * Default value: PREAMBLE_HT
- */
- public int preamble;
-
- /** bandWidth used for RTT measurement.User need verify the highest BW the destination
- * support (from scan result etc) before set this value. Wider channels result usually give
- * better accuracy. However, the frame loss can increase too.
- * should be one of RTT_BW_5_SUPPORT to RTT_BW_160_SUPPORT. However, need check
- * RttCapabilities firstto verify HW support this bandwidth.
- * Default value:RTT_BW_20_SUPPORT
- */
- public int bandwidth;
-
- public RttParams() {
- //provide initial value for RttParams
- deviceType = RTT_PEER_TYPE_AP;
- requestType = RTT_TYPE_ONE_SIDED;
- numberBurst = 0;
- numSamplesPerBurst = 8;
- numRetriesPerMeasurementFrame = 0;
- numRetriesPerFTMR = 0;
- burstTimeout = 15;
- preamble = PREAMBLE_HT;
- bandwidth = RTT_BW_20_SUPPORT;
- }
-
- /**
- * {@hide}
- */
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("deviceType=" + deviceType);
- sb.append(", requestType=" + requestType);
- sb.append(", secure=" + secure);
- sb.append(", bssid=" + bssid);
- sb.append(", frequency=" + frequency);
- sb.append(", channelWidth=" + channelWidth);
- sb.append(", centerFreq0=" + centerFreq0);
- sb.append(", centerFreq1=" + centerFreq1);
- sb.append(", num_samples=" + num_samples);
- sb.append(", num_retries=" + num_retries);
- sb.append(", numberBurst=" + numberBurst);
- sb.append(", interval=" + interval);
- sb.append(", numSamplesPerBurst=" + numSamplesPerBurst);
- sb.append(", numRetriesPerMeasurementFrame=" + numRetriesPerMeasurementFrame);
- sb.append(", numRetriesPerFTMR=" + numRetriesPerFTMR);
- sb.append(", LCIRequest=" + LCIRequest);
- sb.append(", LCRRequest=" + LCRRequest);
- sb.append(", burstTimeout=" + burstTimeout);
- sb.append(", preamble=" + preamble);
- sb.append(", bandwidth=" + bandwidth);
- return sb.toString();
- }
- }
-
- /** pseudo-private class used to parcel arguments */
- @Deprecated
- public static class ParcelableRttParams implements Parcelable {
-
- @NonNull
- public RttParams mParams[];
-
- /**
- * @hide
- */
- @VisibleForTesting
- public ParcelableRttParams(RttParams[] params) {
- mParams = (params == null ? new RttParams[0] : params);
- }
-
- /** Implement the Parcelable interface {@hide} */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mParams.length);
-
- for (RttParams params : mParams) {
- dest.writeInt(params.deviceType);
- dest.writeInt(params.requestType);
- dest.writeByte(params.secure ? (byte) 1 : 0);
- dest.writeString(params.bssid);
- dest.writeInt(params.channelWidth);
- dest.writeInt(params.frequency);
- dest.writeInt(params.centerFreq0);
- dest.writeInt(params.centerFreq1);
- dest.writeInt(params.numberBurst);
- dest.writeInt(params.interval);
- dest.writeInt(params.numSamplesPerBurst);
- dest.writeInt(params.numRetriesPerMeasurementFrame);
- dest.writeInt(params.numRetriesPerFTMR);
- dest.writeInt(params.LCIRequest ? 1 : 0);
- dest.writeInt(params.LCRRequest ? 1 : 0);
- dest.writeInt(params.burstTimeout);
- dest.writeInt(params.preamble);
- dest.writeInt(params.bandwidth);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @android.annotation.NonNull Creator<ParcelableRttParams> CREATOR =
- new Creator<ParcelableRttParams>() {
- @Override
- public ParcelableRttParams createFromParcel(Parcel in) {
-
- int num = in.readInt();
- RttParams params[] = new RttParams[num];
- for (int i = 0; i < num; i++) {
- params[i] = new RttParams();
- params[i].deviceType = in.readInt();
- params[i].requestType = in.readInt();
- params[i].secure = (in.readByte() != 0);
- params[i].bssid = in.readString();
- params[i].channelWidth = in.readInt();
- params[i].frequency = in.readInt();
- params[i].centerFreq0 = in.readInt();
- params[i].centerFreq1 = in.readInt();
- params[i].numberBurst = in.readInt();
- params[i].interval = in.readInt();
- params[i].numSamplesPerBurst = in.readInt();
- params[i].numRetriesPerMeasurementFrame = in.readInt();
- params[i].numRetriesPerFTMR = in.readInt();
- params[i].LCIRequest = (in.readInt() == 1);
- params[i].LCRRequest = (in.readInt() == 1);
- params[i].burstTimeout = in.readInt();
- params[i].preamble = in.readInt();
- params[i].bandwidth = in.readInt();
- }
-
- ParcelableRttParams parcelableParams = new ParcelableRttParams(params);
- return parcelableParams;
- }
-
- @Override
- public ParcelableRttParams[] newArray(int size) {
- return new ParcelableRttParams[size];
- }
- };
- }
-
- @Deprecated
- public static class WifiInformationElement {
- /** Information Element ID 0xFF means element is invalid. */
- public byte id;
- public byte[] data;
- }
- /** specifies RTT results */
- @Deprecated
- public static class RttResult {
- /** mac address of the device being ranged. */
- public String bssid;
-
- /** # of burst for this measurement. */
- public int burstNumber;
-
- /** total number of measurement frames attempted in this measurement. */
- public int measurementFrameNumber;
-
- /** total successful number of measurement frames in this measurement. */
- public int successMeasurementFrameNumber;
-
- /**
- * Maximum number of frames per burst supported by peer. Two side RTT only
- * Valid only if less than request
- */
- public int frameNumberPerBurstPeer;
-
- /** status of the request */
- public int status;
-
- /**
- * type of the request used
- * @deprecated Use {@link android.net.wifi.RttManager.RttResult#measurementType}
- */
- @Deprecated
- public int requestType;
-
- /** RTT measurement method type used, should be one of RTT_TYPE_ONE_SIDED or
- * RTT_TYPE_TWO_SIDED.
- */
- public int measurementType;
-
- /**
- * only valid when status == RTT_STATUS_FAIL_BUSY_TRY_LATER
- * please retry RTT measurement after this duration since peer indicate busy at ths moment
- * Unit S Range:1-31
- */
- public int retryAfterDuration;
-
- /** timestamp of completion, in microsecond since boot. */
- public long ts;
-
- /** average RSSI observed, unit of 0.5 dB. */
- public int rssi;
-
- /**
- * RSSI spread (i.e. max - min)
- * @deprecated Use {@link android.net.wifi.RttManager.RttResult#rssiSpread} API.
- */
- @Deprecated
- public int rssi_spread;
-
- /**RSSI spread (i.e. max - min), unit of 0.5 dB. */
- public int rssiSpread;
-
- /**
- * average transmit rate
- * @deprecated Use {@link android.net.wifi.RttManager.RttResult#txRate} API.
- */
- @Deprecated
- public int tx_rate;
-
- /** average transmit rate. Unit (kbps). */
- public int txRate;
-
- /** average receiving rate Unit (kbps). */
- public int rxRate;
-
- /**
- * average round trip time in nano second
- * @deprecated Use {@link android.net.wifi.RttManager.RttResult#rtt} API.
- */
- @Deprecated
- public long rtt_ns;
-
- /** average round trip time in picoseconds. */
- public long rtt;
-
- /**
- * standard deviation observed in round trip time
- * @deprecated Use {@link android.net.wifi.RttManager.RttResult#rttStandardDeviation} API.
- */
- @Deprecated
- public long rtt_sd_ns;
-
- /** standard deviation of RTT in picoseconds. */
- public long rttStandardDeviation;
-
- /**
- * spread (i.e. max - min) round trip time
- * @deprecated Use {@link android.net.wifi.RttManager.RttResult#rttSpread} API.
- */
- @Deprecated
- public long rtt_spread_ns;
-
- /** spread (i.e. max - min) RTT in picoseconds. */
- public long rttSpread;
-
- /**
- * average distance in centimeter, computed based on rtt_ns
- * @deprecated use {@link android.net.wifi.RttManager.RttResult#distance} API.
- */
- @Deprecated
- public int distance_cm;
-
- /** average distance in cm, computed based on rtt. */
- public int distance;
-
- /**
- * standard deviation observed in distance
- * @deprecated
- * Use {@link .android.net.wifi.RttManager.RttResult#distanceStandardDeviation} API.
- */
- @Deprecated
- public int distance_sd_cm;
-
- /** standard deviation observed in distance in cm. */
- public int distanceStandardDeviation;
-
- /**
- * spread (i.e. max - min) distance
- * @deprecated Use {@link android.net.wifi.RttManager.RttResult#distanceSpread} API.
- */
- @Deprecated
- public int distance_spread_cm;
-
- /** spread (i.e. max - min) distance in cm. */
- public int distanceSpread;
-
- /** the duration of this measurement burst, unit ms. */
- public int burstDuration;
-
- /** Burst number supported by peer after negotiation, 2side RTT only*/
- public int negotiatedBurstNum;
-
- /** LCI information Element, only available for double side RTT. */
- public WifiInformationElement LCI;
-
- /** LCR information Element, only available to double side RTT. */
- public WifiInformationElement LCR;
-
- /**
- * Whether the secure RTT protocol was used for ranging.
- */
- public boolean secure;
- }
-
-
- /** pseudo-private class used to parcel results. */
- @Deprecated
- public static class ParcelableRttResults implements Parcelable {
-
- public RttResult mResults[];
-
- public ParcelableRttResults(RttResult[] results) {
- mResults = results;
- }
-
- /**
- * {@hide}
- */
- public String toString() {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < mResults.length; ++i) {
- sb.append("[" + i + "]: ");
- sb.append("bssid=" + mResults[i].bssid);
- sb.append(", burstNumber=" + mResults[i].burstNumber);
- sb.append(", measurementFrameNumber=" + mResults[i].measurementFrameNumber);
- sb.append(", successMeasurementFrameNumber="
- + mResults[i].successMeasurementFrameNumber);
- sb.append(", frameNumberPerBurstPeer=" + mResults[i].frameNumberPerBurstPeer);
- sb.append(", status=" + mResults[i].status);
- sb.append(", requestType=" + mResults[i].requestType);
- sb.append(", measurementType=" + mResults[i].measurementType);
- sb.append(", retryAfterDuration=" + mResults[i].retryAfterDuration);
- sb.append(", ts=" + mResults[i].ts);
- sb.append(", rssi=" + mResults[i].rssi);
- sb.append(", rssi_spread=" + mResults[i].rssi_spread);
- sb.append(", rssiSpread=" + mResults[i].rssiSpread);
- sb.append(", tx_rate=" + mResults[i].tx_rate);
- sb.append(", txRate=" + mResults[i].txRate);
- sb.append(", rxRate=" + mResults[i].rxRate);
- sb.append(", rtt_ns=" + mResults[i].rtt_ns);
- sb.append(", rtt=" + mResults[i].rtt);
- sb.append(", rtt_sd_ns=" + mResults[i].rtt_sd_ns);
- sb.append(", rttStandardDeviation=" + mResults[i].rttStandardDeviation);
- sb.append(", rtt_spread_ns=" + mResults[i].rtt_spread_ns);
- sb.append(", rttSpread=" + mResults[i].rttSpread);
- sb.append(", distance_cm=" + mResults[i].distance_cm);
- sb.append(", distance=" + mResults[i].distance);
- sb.append(", distance_sd_cm=" + mResults[i].distance_sd_cm);
- sb.append(", distanceStandardDeviation=" + mResults[i].distanceStandardDeviation);
- sb.append(", distance_spread_cm=" + mResults[i].distance_spread_cm);
- sb.append(", distanceSpread=" + mResults[i].distanceSpread);
- sb.append(", burstDuration=" + mResults[i].burstDuration);
- sb.append(", negotiatedBurstNum=" + mResults[i].negotiatedBurstNum);
- sb.append(", LCI=" + mResults[i].LCI);
- sb.append(", LCR=" + mResults[i].LCR);
- sb.append(", secure=" + mResults[i].secure);
- }
- return sb.toString();
- }
-
- /** Implement the Parcelable interface {@hide} */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- if (mResults != null) {
- dest.writeInt(mResults.length);
- for (RttResult result : mResults) {
- dest.writeString(result.bssid);
- dest.writeInt(result.burstNumber);
- dest.writeInt(result.measurementFrameNumber);
- dest.writeInt(result.successMeasurementFrameNumber);
- dest.writeInt(result.frameNumberPerBurstPeer);
- dest.writeInt(result.status);
- dest.writeInt(result.measurementType);
- dest.writeInt(result.retryAfterDuration);
- dest.writeLong(result.ts);
- dest.writeInt(result.rssi);
- dest.writeInt(result.rssiSpread);
- dest.writeInt(result.txRate);
- dest.writeLong(result.rtt);
- dest.writeLong(result.rttStandardDeviation);
- dest.writeLong(result.rttSpread);
- dest.writeInt(result.distance);
- dest.writeInt(result.distanceStandardDeviation);
- dest.writeInt(result.distanceSpread);
- dest.writeInt(result.burstDuration);
- dest.writeInt(result.negotiatedBurstNum);
- dest.writeByte(result.LCI.id);
- if (result.LCI.id != (byte) 0xFF) {
- dest.writeByte((byte)result.LCI.data.length);
- dest.writeByteArray(result.LCI.data);
- }
- dest.writeByte(result.LCR.id);
- if (result.LCR.id != (byte) 0xFF) {
- dest.writeByte((byte) result.LCR.data.length);
- dest.writeByteArray(result.LCR.data);
- }
- dest.writeByte(result.secure ? (byte) 1 : 0);
- }
- } else {
- dest.writeInt(0);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @android.annotation.NonNull Creator<ParcelableRttResults> CREATOR =
- new Creator<ParcelableRttResults>() {
- @Override
- public ParcelableRttResults createFromParcel(Parcel in) {
-
- int num = in.readInt();
-
- if (num == 0) {
- return new ParcelableRttResults(null);
- }
-
- RttResult results[] = new RttResult[num];
- for (int i = 0; i < num; i++) {
- results[i] = new RttResult();
- results[i].bssid = in.readString();
- results[i].burstNumber = in.readInt();
- results[i].measurementFrameNumber = in.readInt();
- results[i].successMeasurementFrameNumber = in.readInt();
- results[i].frameNumberPerBurstPeer = in.readInt();
- results[i].status = in.readInt();
- results[i].measurementType = in.readInt();
- results[i].retryAfterDuration = in.readInt();
- results[i].ts = in.readLong();
- results[i].rssi = in.readInt();
- results[i].rssiSpread = in.readInt();
- results[i].txRate = in.readInt();
- results[i].rtt = in.readLong();
- results[i].rttStandardDeviation = in.readLong();
- results[i].rttSpread = in.readLong();
- results[i].distance = in.readInt();
- results[i].distanceStandardDeviation = in.readInt();
- results[i].distanceSpread = in.readInt();
- results[i].burstDuration = in.readInt();
- results[i].negotiatedBurstNum = in.readInt();
- results[i].LCI = new WifiInformationElement();
- results[i].LCI.id = in.readByte();
- if (results[i].LCI.id != (byte) 0xFF) {
- byte length = in.readByte();
- results[i].LCI.data = new byte[length];
- in.readByteArray(results[i].LCI.data);
- }
- results[i].LCR = new WifiInformationElement();
- results[i].LCR.id = in.readByte();
- if (results[i].LCR.id != (byte) 0xFF) {
- byte length = in.readByte();
- results[i].LCR.data = new byte[length];
- in.readByteArray(results[i].LCR.data);
- }
- results[i].secure = (in.readByte() != 0);
- }
-
- ParcelableRttResults parcelableResults = new ParcelableRttResults(results);
- return parcelableResults;
- }
-
- @Override
- public ParcelableRttResults[] newArray(int size) {
- return new ParcelableRttResults[size];
- }
- };
- }
-
- @Deprecated
- public static interface RttListener {
- public void onSuccess(RttResult[] results);
- public void onFailure(int reason, String description);
- public void onAborted();
- }
-
- /**
- * Request to start an RTT ranging
- * <p>
- * This method is deprecated. Please use the
- * {@link WifiRttManager#startRanging(RangingRequest, java.util.concurrent.Executor, RangingResultCallback)}
- * API.
- *
- * @param params -- RTT request Parameters
- * @param listener -- Call back to inform RTT result
- * @exception throw IllegalArgumentException when params are illegal
- * throw IllegalStateException when RttCapabilities do not exist
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void startRanging(RttParams[] params, RttListener listener) {
- Log.i(TAG, "Send RTT request to RTT Service");
-
- if (!mNewService.isAvailable()) {
- listener.onFailure(REASON_NOT_AVAILABLE, "");
- return;
- }
-
- RangingRequest.Builder builder = new RangingRequest.Builder();
- for (RttParams rttParams : params) {
- if (rttParams.deviceType != RTT_PEER_TYPE_AP) {
- listener.onFailure(REASON_INVALID_REQUEST, "Only AP peers are supported");
- return;
- }
-
- ScanResult reconstructed = new ScanResult();
- reconstructed.BSSID = rttParams.bssid;
- if (rttParams.requestType == RTT_TYPE_TWO_SIDED) {
- reconstructed.setFlag(ScanResult.FLAG_80211mc_RESPONDER);
- }
- reconstructed.channelWidth = rttParams.channelWidth;
- reconstructed.frequency = rttParams.frequency;
- reconstructed.centerFreq0 = rttParams.centerFreq0;
- reconstructed.centerFreq1 = rttParams.centerFreq1;
- builder.addResponder(
- android.net.wifi.rtt.ResponderConfig.fromScanResult(reconstructed));
- }
- try {
- mNewService.startRanging(builder.build(),
- mContext.getMainExecutor(),
- new RangingResultCallback() {
- @Override
- public void onRangingFailure(int code) {
- int localCode = REASON_UNSPECIFIED;
- if (code == STATUS_CODE_FAIL_RTT_NOT_AVAILABLE) {
- localCode = REASON_NOT_AVAILABLE;
- }
- listener.onFailure(localCode, "");
- }
-
- @Override
- public void onRangingResults(List<RangingResult> results) {
- RttResult[] legacyResults = new RttResult[results.size()];
- int i = 0;
- for (RangingResult result : results) {
- legacyResults[i] = new RttResult();
- legacyResults[i].status = result.getStatus();
- legacyResults[i].bssid = result.getMacAddress().toString();
- if (result.getStatus() == RangingResult.STATUS_SUCCESS) {
- legacyResults[i].distance = result.getDistanceMm() / 10;
- legacyResults[i].distanceStandardDeviation =
- result.getDistanceStdDevMm() / 10;
- legacyResults[i].rssi = result.getRssi() * -2;
- legacyResults[i].ts = result.getRangingTimestampMillis() * 1000;
- legacyResults[i].measurementFrameNumber =
- result.getNumAttemptedMeasurements();
- legacyResults[i].successMeasurementFrameNumber =
- result.getNumSuccessfulMeasurements();
- } else {
- // just in case legacy API needed some relatively real timestamp
- legacyResults[i].ts = SystemClock.elapsedRealtime() * 1000;
- }
- i++;
- }
- listener.onSuccess(legacyResults);
- }
- });
- } catch (IllegalArgumentException e) {
- Log.e(TAG, "startRanging: invalid arguments - " + e);
- listener.onFailure(REASON_INVALID_REQUEST, e.getMessage());
- } catch (SecurityException e) {
- Log.e(TAG, "startRanging: security exception - " + e);
- listener.onFailure(REASON_PERMISSION_DENIED, e.getMessage());
- }
- }
-
- /**
- * This method is deprecated and performs no function. Please use the {@link WifiRttManager}
- * API.
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void stopRanging(RttListener listener) {
- Log.e(TAG, "stopRanging: unsupported operation - nop");
- }
-
- /**
- * Callbacks for responder operations.
- * <p>
- * A {@link ResponderCallback} is the handle to the calling client. {@link RttManager} will keep
- * a reference to the callback for the entire period when responder is enabled. The same
- * callback as used in enabling responder needs to be passed for disabling responder.
- * The client can freely destroy or reuse the callback after {@link RttManager#disableResponder}
- * is called.
- */
- @Deprecated
- public abstract static class ResponderCallback {
- /** Callback when responder is enabled. */
- public abstract void onResponderEnabled(ResponderConfig config);
- /** Callback when enabling responder failed. */
- public abstract void onResponderEnableFailure(int reason);
- // TODO: consider adding onResponderAborted once it's supported.
- }
-
- /**
- * Enable Wi-Fi RTT responder mode on the device. The enabling result will be delivered via
- * {@code callback}.
- * <p>
- * Note calling this method with the same callback when the responder is already enabled won't
- * change the responder state, a cached {@link ResponderConfig} from the last enabling will be
- * returned through the callback.
- * <p>
- * This method is deprecated and will throw an {@link UnsupportedOperationException}
- * exception. Please use the {@link WifiRttManager} API to perform a Wi-Fi Aware peer-to-peer
- * ranging.
- *
- * @param callback Callback for responder enabling/disabling result.
- * @throws IllegalArgumentException If {@code callback} is null.
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void enableResponder(ResponderCallback callback) {
- throw new UnsupportedOperationException(
- "enableResponder is not supported in the adaptation layer");
- }
-
- /**
- * Disable Wi-Fi RTT responder mode on the device. The {@code callback} needs to be the
- * same one used in {@link #enableResponder(ResponderCallback)}.
- * <p>
- * Calling this method when responder isn't enabled won't have any effect. The callback can be
- * reused for enabling responder after this method is called.
- * <p>
- * This method is deprecated and will throw an {@link UnsupportedOperationException}
- * exception. Please use the {@link WifiRttManager} API to perform a Wi-Fi Aware peer-to-peer
- * ranging.
- *
- * @param callback The same callback used for enabling responder.
- * @throws IllegalArgumentException If {@code callback} is null.
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void disableResponder(ResponderCallback callback) {
- throw new UnsupportedOperationException(
- "disableResponder is not supported in the adaptation layer");
- }
-
- /**
- * Configuration used for RTT responder mode. The configuration information can be used by a
- * peer device to range the responder.
- *
- * @see ScanResult
- */
- @Deprecated
- public static class ResponderConfig implements Parcelable {
-
- // TODO: make all fields final once we can get mac address from responder HAL APIs.
- /**
- * Wi-Fi mac address used for responder mode.
- */
- public String macAddress = "";
-
- /**
- * The primary 20 MHz frequency (in MHz) of the channel where responder is enabled.
- * @see ScanResult#frequency
- */
- public int frequency;
-
- /**
- * Center frequency of the channel where responder is enabled on. Only in use when channel
- * width is at least 40MHz.
- * @see ScanResult#centerFreq0
- */
- public int centerFreq0;
-
- /**
- * Center frequency of the second segment when channel width is 80 + 80 MHz.
- * @see ScanResult#centerFreq1
- */
- public int centerFreq1;
-
- /**
- * Width of the channel where responder is enabled on.
- * @see ScanResult#channelWidth
- */
- public int channelWidth;
-
- /**
- * Preamble supported by responder.
- */
- public int preamble;
-
- @NonNull
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("macAddress = ").append(macAddress)
- .append(" frequency = ").append(frequency)
- .append(" centerFreq0 = ").append(centerFreq0)
- .append(" centerFreq1 = ").append(centerFreq1)
- .append(" channelWidth = ").append(channelWidth)
- .append(" preamble = ").append(preamble);
- return builder.toString();
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(macAddress);
- dest.writeInt(frequency);
- dest.writeInt(centerFreq0);
- dest.writeInt(centerFreq1);
- dest.writeInt(channelWidth);
- dest.writeInt(preamble);
- }
-
- /** Implement {@link Parcelable} interface */
- public static final @android.annotation.NonNull Parcelable.Creator<ResponderConfig> CREATOR =
- new Parcelable.Creator<ResponderConfig>() {
- @Override
- public ResponderConfig createFromParcel(Parcel in) {
- ResponderConfig config = new ResponderConfig();
- config.macAddress = in.readString();
- config.frequency = in.readInt();
- config.centerFreq0 = in.readInt();
- config.centerFreq1 = in.readInt();
- config.channelWidth = in.readInt();
- config.preamble = in.readInt();
- return config;
- }
-
- @Override
- public ResponderConfig[] newArray(int size) {
- return new ResponderConfig[size];
- }
- };
-
- }
-
- /* private methods */
- public static final int BASE = Protocol.BASE_WIFI_RTT_MANAGER;
-
- public static final int CMD_OP_START_RANGING = BASE + 0;
- public static final int CMD_OP_STOP_RANGING = BASE + 1;
- public static final int CMD_OP_FAILED = BASE + 2;
- public static final int CMD_OP_SUCCEEDED = BASE + 3;
- public static final int CMD_OP_ABORTED = BASE + 4;
- public static final int CMD_OP_ENABLE_RESPONDER = BASE + 5;
- public static final int CMD_OP_DISABLE_RESPONDER = BASE + 6;
- public static final int
- CMD_OP_ENALBE_RESPONDER_SUCCEEDED = BASE + 7;
- public static final int
- CMD_OP_ENALBE_RESPONDER_FAILED = BASE + 8;
- /** @hide */
- public static final int CMD_OP_REG_BINDER = BASE + 9;
-
- private final WifiRttManager mNewService;
- private final Context mContext;
- private RttCapabilities mRttCapabilities;
-
- /**
- * Create a new WifiScanner instance.
- * Applications will almost always want to use
- * {@link android.content.Context#getSystemService Context.getSystemService()} to retrieve
- * the standard {@link android.content.Context#WIFI_RTT_SERVICE Context.WIFI_RTT_SERVICE}.
- * @param service the new WifiRttManager service
- *
- * @hide
- */
- public RttManager(@NonNull Context context, @NonNull WifiRttManager service) {
- mNewService = service;
- mContext = context;
-
- boolean rttSupported = context.getPackageManager().hasSystemFeature(
- PackageManager.FEATURE_WIFI_RTT);
-
- mRttCapabilities = new RttCapabilities();
- mRttCapabilities.oneSidedRttSupported = rttSupported;
- mRttCapabilities.twoSided11McRttSupported = rttSupported;
- mRttCapabilities.lciSupported = false;
- mRttCapabilities.lcrSupported = false;
- mRttCapabilities.preambleSupported = PREAMBLE_HT | PREAMBLE_VHT;
- mRttCapabilities.bwSupported = RTT_BW_40_SUPPORT | RTT_BW_80_SUPPORT;
- mRttCapabilities.responderSupported = false;
- mRttCapabilities.secureRttSupported = false;
- }
-}
-
diff --git a/wifi/java/android/net/wifi/ScanResult.java b/wifi/java/android/net/wifi/ScanResult.java
deleted file mode 100644
index 78afb579674f..000000000000
--- a/wifi/java/android/net/wifi/ScanResult.java
+++ /dev/null
@@ -1,1214 +0,0 @@
-/*
- * Copyright (C) 2008 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.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.net.wifi.WifiAnnotations.ChannelWidth;
-import android.net.wifi.WifiAnnotations.WifiStandard;
-import android.os.Build;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * Describes information about a detected access point. In addition
- * to the attributes described here, the supplicant keeps track of
- * {@code quality}, {@code noise}, and {@code maxbitrate} attributes,
- * but does not currently report them to external clients.
- */
-public final class ScanResult implements Parcelable {
- /**
- * The network name.
- */
- public String SSID;
-
- /**
- * Ascii encoded SSID. This will replace SSID when we deprecate it. @hide
- */
- @UnsupportedAppUsage
- public WifiSsid wifiSsid;
-
- /**
- * The address of the access point.
- */
- public String BSSID;
-
- /**
- * The HESSID from the beacon.
- * @hide
- */
- @UnsupportedAppUsage
- public long hessid;
-
- /**
- * The ANQP Domain ID from the Hotspot 2.0 Indication element, if present.
- * @hide
- */
- @UnsupportedAppUsage
- public int anqpDomainId;
-
- /*
- * This field is equivalent to the |flags|, rather than the |capabilities| field
- * of the per-BSS scan results returned by WPA supplicant. See the definition of
- * |struct wpa_bss| in wpa_supplicant/bss.h for more details.
- */
- /**
- * Describes the authentication, key management, and encryption schemes
- * supported by the access point.
- */
- public String capabilities;
-
- /**
- * The interface name on which the scan result was received.
- * @hide
- */
- public String ifaceName;
-
- /**
- * @hide
- * No security protocol.
- */
- @SystemApi
- public static final int PROTOCOL_NONE = 0;
- /**
- * @hide
- * Security protocol type: WPA version 1.
- */
- @SystemApi
- public static final int PROTOCOL_WPA = 1;
- /**
- * @hide
- * Security protocol type: RSN, for WPA version 2, and version 3.
- */
- @SystemApi
- public static final int PROTOCOL_RSN = 2;
- /**
- * @hide
- * Security protocol type:
- * OSU Server-only authenticated layer 2 Encryption Network.
- * Used for Hotspot 2.0.
- */
- @SystemApi
- public static final int PROTOCOL_OSEN = 3;
-
- /**
- * @hide
- * Security protocol type: WAPI.
- */
- @SystemApi
- public static final int PROTOCOL_WAPI = 4;
-
- /**
- * @hide
- * No security key management scheme.
- */
- @SystemApi
- public static final int KEY_MGMT_NONE = 0;
- /**
- * @hide
- * Security key management scheme: PSK.
- */
- @SystemApi
- public static final int KEY_MGMT_PSK = 1;
- /**
- * @hide
- * Security key management scheme: EAP.
- */
- @SystemApi
- public static final int KEY_MGMT_EAP = 2;
- /**
- * @hide
- * Security key management scheme: FT_PSK.
- */
- @SystemApi
- public static final int KEY_MGMT_FT_PSK = 3;
- /**
- * @hide
- * Security key management scheme: FT_EAP.
- */
- @SystemApi
- public static final int KEY_MGMT_FT_EAP = 4;
- /**
- * @hide
- * Security key management scheme: PSK_SHA256
- */
- @SystemApi
- public static final int KEY_MGMT_PSK_SHA256 = 5;
- /**
- * @hide
- * Security key management scheme: EAP_SHA256.
- */
- @SystemApi
- public static final int KEY_MGMT_EAP_SHA256 = 6;
- /**
- * @hide
- * Security key management scheme: OSEN.
- * Used for Hotspot 2.0.
- */
- @SystemApi
- public static final int KEY_MGMT_OSEN = 7;
- /**
- * @hide
- * Security key management scheme: SAE.
- */
- @SystemApi
- public static final int KEY_MGMT_SAE = 8;
- /**
- * @hide
- * Security key management scheme: OWE.
- */
- @SystemApi
- public static final int KEY_MGMT_OWE = 9;
- /**
- * @hide
- * Security key management scheme: SUITE_B_192.
- */
- @SystemApi
- public static final int KEY_MGMT_EAP_SUITE_B_192 = 10;
- /**
- * @hide
- * Security key management scheme: FT_SAE.
- */
- @SystemApi
- public static final int KEY_MGMT_FT_SAE = 11;
- /**
- * @hide
- * Security key management scheme: OWE in transition mode.
- */
- @SystemApi
- public static final int KEY_MGMT_OWE_TRANSITION = 12;
- /**
- * @hide
- * Security key management scheme: WAPI_PSK.
- */
- @SystemApi
- public static final int KEY_MGMT_WAPI_PSK = 13;
- /**
- * @hide
- * Security key management scheme: WAPI_CERT.
- */
- @SystemApi
- public static final int KEY_MGMT_WAPI_CERT = 14;
-
- /**
- * @hide
- * Security key management scheme: FILS_SHA256.
- */
- public static final int KEY_MGMT_FILS_SHA256 = 15;
- /**
- * @hide
- * Security key management scheme: FILS_SHA384.
- */
- public static final int KEY_MGMT_FILS_SHA384 = 16;
- /**
- * @hide
- * Security key management scheme: DPP.
- */
- public static final int KEY_MGMT_DPP = 17;
- /**
- * @hide
- * No cipher suite.
- */
- @SystemApi
- public static final int CIPHER_NONE = 0;
- /**
- * @hide
- * No group addressed, only used for group data cipher.
- */
- @SystemApi
- public static final int CIPHER_NO_GROUP_ADDRESSED = 1;
- /**
- * @hide
- * Cipher suite: TKIP
- */
- @SystemApi
- public static final int CIPHER_TKIP = 2;
- /**
- * @hide
- * Cipher suite: CCMP
- */
- @SystemApi
- public static final int CIPHER_CCMP = 3;
- /**
- * @hide
- * Cipher suite: GCMP
- */
- @SystemApi
- public static final int CIPHER_GCMP_256 = 4;
- /**
- * @hide
- * Cipher suite: SMS4
- */
- @SystemApi
- public static final int CIPHER_SMS4 = 5;
-
- /**
- * The detected signal level in dBm, also known as the RSSI.
- *
- * <p>Use {@link android.net.wifi.WifiManager#calculateSignalLevel} to convert this number into
- * an absolute signal level which can be displayed to a user.
- */
- public int level;
- /**
- * The primary 20 MHz frequency (in MHz) of the channel over which the client is communicating
- * with the access point.
- */
- public int frequency;
-
- /**
- * AP Channel bandwidth is 20 MHZ
- */
- public static final int CHANNEL_WIDTH_20MHZ = 0;
- /**
- * AP Channel bandwidth is 40 MHZ
- */
- public static final int CHANNEL_WIDTH_40MHZ = 1;
- /**
- * AP Channel bandwidth is 80 MHZ
- */
- public static final int CHANNEL_WIDTH_80MHZ = 2;
- /**
- * AP Channel bandwidth is 160 MHZ
- */
- public static final int CHANNEL_WIDTH_160MHZ = 3;
- /**
- * AP Channel bandwidth is 160 MHZ, but 80MHZ + 80MHZ
- */
- public static final int CHANNEL_WIDTH_80MHZ_PLUS_MHZ = 4;
-
- /**
- * Wi-Fi unknown standard
- */
- public static final int WIFI_STANDARD_UNKNOWN = 0;
-
- /**
- * Wi-Fi 802.11a/b/g
- */
- public static final int WIFI_STANDARD_LEGACY = 1;
-
- /**
- * Wi-Fi 802.11n
- */
- public static final int WIFI_STANDARD_11N = 4;
-
- /**
- * Wi-Fi 802.11ac
- */
- public static final int WIFI_STANDARD_11AC = 5;
-
- /**
- * Wi-Fi 802.11ax
- */
- public static final int WIFI_STANDARD_11AX = 6;
-
- /**
- * AP wifi standard.
- */
- private @WifiStandard int mWifiStandard;
-
- /**
- * return the AP wifi standard.
- */
- public @WifiStandard int getWifiStandard() {
- return mWifiStandard;
- }
-
- /**
- * sets the AP wifi standard.
- * @hide
- */
- public void setWifiStandard(@WifiStandard int standard) {
- mWifiStandard = standard;
- }
-
- /**
- * Convert Wi-Fi standard to string
- */
- private static @Nullable String wifiStandardToString(@WifiStandard int standard) {
- switch(standard) {
- case WIFI_STANDARD_LEGACY:
- return "legacy";
- case WIFI_STANDARD_11N:
- return "11n";
- case WIFI_STANDARD_11AC:
- return "11ac";
- case WIFI_STANDARD_11AX:
- return "11ax";
- case WIFI_STANDARD_UNKNOWN:
- return "unknown";
- }
- return null;
- }
-
- /**
- * AP Channel bandwidth; one of {@link #CHANNEL_WIDTH_20MHZ}, {@link #CHANNEL_WIDTH_40MHZ},
- * {@link #CHANNEL_WIDTH_80MHZ}, {@link #CHANNEL_WIDTH_160MHZ}
- * or {@link #CHANNEL_WIDTH_80MHZ_PLUS_MHZ}.
- */
- public @ChannelWidth int channelWidth;
-
- /**
- * Not used if the AP bandwidth is 20 MHz
- * If the AP use 40, 80 or 160 MHz, this is the center frequency (in MHz)
- * if the AP use 80 + 80 MHz, this is the center frequency of the first segment (in MHz)
- */
- public int centerFreq0;
-
- /**
- * Only used if the AP bandwidth is 80 + 80 MHz
- * if the AP use 80 + 80 MHz, this is the center frequency of the second segment (in MHz)
- */
- public int centerFreq1;
-
- /**
- * @deprecated use is80211mcResponder() instead
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public boolean is80211McRTTResponder;
-
- /**
- * timestamp in microseconds (since boot) when
- * this result was last seen.
- */
- public long timestamp;
-
- /**
- * Timestamp representing date when this result was last seen, in milliseconds from 1970
- * {@hide}
- */
- @UnsupportedAppUsage
- public long seen;
-
- /**
- * On devices with multiple hardware radio chains, this class provides metadata about
- * each radio chain that was used to receive this scan result (probe response or beacon).
- * {@hide}
- */
- public static class RadioChainInfo {
- /** Vendor defined id for a radio chain. */
- public int id;
- /** Detected signal level in dBm (also known as the RSSI) on this radio chain. */
- public int level;
-
- @Override
- public String toString() {
- return "RadioChainInfo: id=" + id + ", level=" + level;
- }
-
- @Override
- public boolean equals(Object otherObj) {
- if (this == otherObj) {
- return true;
- }
- if (!(otherObj instanceof RadioChainInfo)) {
- return false;
- }
- RadioChainInfo other = (RadioChainInfo) otherObj;
- return id == other.id && level == other.level;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(id, level);
- }
- };
-
- /**
- * Information about the list of the radio chains used to receive this scan result
- * (probe response or beacon).
- *
- * For Example: On devices with 2 hardware radio chains, this list could hold 1 or 2
- * entries based on whether this scan result was received using one or both the chains.
- * {@hide}
- */
- public RadioChainInfo[] radioChainInfos;
-
- /**
- * Status indicating the scan result does not correspond to a user's saved configuration
- * @hide
- * @removed
- */
- @SystemApi
- public boolean untrusted;
-
- /**
- * Number of time autojoin used it
- * @hide
- */
- @UnsupportedAppUsage
- public int numUsage;
-
- /**
- * The approximate distance to the AP in centimeter, if available. Else
- * {@link UNSPECIFIED}.
- * {@hide}
- */
- @UnsupportedAppUsage
- public int distanceCm;
-
- /**
- * The standard deviation of the distance to the access point, if available.
- * Else {@link UNSPECIFIED}.
- * {@hide}
- */
- @UnsupportedAppUsage
- public int distanceSdCm;
-
- /** {@hide} */
- public static final long FLAG_PASSPOINT_NETWORK = 0x0000000000000001;
-
- /** {@hide} */
- public static final long FLAG_80211mc_RESPONDER = 0x0000000000000002;
-
- /*
- * These flags are specific to the ScanResult class, and are not related to the |flags|
- * field of the per-BSS scan results from WPA supplicant.
- */
- /**
- * Defines flags; such as {@link #FLAG_PASSPOINT_NETWORK}.
- * {@hide}
- */
- @UnsupportedAppUsage
- public long flags;
-
- /**
- * sets a flag in {@link #flags} field
- * @param flag flag to set
- * @hide
- */
- public void setFlag(long flag) {
- flags |= flag;
- }
-
- /**
- * clears a flag in {@link #flags} field
- * @param flag flag to set
- * @hide
- */
- public void clearFlag(long flag) {
- flags &= ~flag;
- }
-
- public boolean is80211mcResponder() {
- return (flags & FLAG_80211mc_RESPONDER) != 0;
- }
-
- public boolean isPasspointNetwork() {
- return (flags & FLAG_PASSPOINT_NETWORK) != 0;
- }
-
- /**
- * Indicates venue name (such as 'San Francisco Airport') published by access point; only
- * available on Passpoint network and if published by access point.
- */
- public CharSequence venueName;
-
- /**
- * Indicates Passpoint operator name published by access point.
- */
- public CharSequence operatorFriendlyName;
-
- /**
- * {@hide}
- */
- public final static int UNSPECIFIED = -1;
-
- /**
- * 2.4 GHz band first channel number
- * @hide
- */
- public static final int BAND_24_GHZ_FIRST_CH_NUM = 1;
- /**
- * 2.4 GHz band last channel number
- * @hide
- */
- public static final int BAND_24_GHZ_LAST_CH_NUM = 14;
- /**
- * 2.4 GHz band frequency of first channel in MHz
- * @hide
- */
- public static final int BAND_24_GHZ_START_FREQ_MHZ = 2412;
- /**
- * 2.4 GHz band frequency of last channel in MHz
- * @hide
- */
- public static final int BAND_24_GHZ_END_FREQ_MHZ = 2484;
-
- /**
- * 5 GHz band first channel number
- * @hide
- */
- public static final int BAND_5_GHZ_FIRST_CH_NUM = 32;
- /**
- * 5 GHz band last channel number
- * @hide
- */
- public static final int BAND_5_GHZ_LAST_CH_NUM = 173;
- /**
- * 5 GHz band frequency of first channel in MHz
- * @hide
- */
- public static final int BAND_5_GHZ_START_FREQ_MHZ = 5160;
- /**
- * 5 GHz band frequency of last channel in MHz
- * @hide
- */
- public static final int BAND_5_GHZ_END_FREQ_MHZ = 5865;
-
- /**
- * 6 GHz band first channel number
- * @hide
- */
- public static final int BAND_6_GHZ_FIRST_CH_NUM = 1;
- /**
- * 6 GHz band last channel number
- * @hide
- */
- public static final int BAND_6_GHZ_LAST_CH_NUM = 233;
- /**
- * 6 GHz band frequency of first channel in MHz
- * @hide
- */
- public static final int BAND_6_GHZ_START_FREQ_MHZ = 5955;
- /**
- * 6 GHz band frequency of last channel in MHz
- * @hide
- */
- public static final int BAND_6_GHZ_END_FREQ_MHZ = 7115;
-
- /**
- * 6 GHz band operating class 136 channel 2 center frequency in MHz
- * @hide
- */
- public static final int BAND_6_GHZ_OP_CLASS_136_CH_2_FREQ_MHZ = 5935;
-
- /**
- * 60 GHz band first channel number
- * @hide
- */
- public static final int BAND_60_GHZ_FIRST_CH_NUM = 1;
- /**
- * 60 GHz band last channel number
- * @hide
- */
- public static final int BAND_60_GHZ_LAST_CH_NUM = 6;
- /**
- * 60 GHz band frequency of first channel in MHz
- * @hide
- */
- public static final int BAND_60_GHZ_START_FREQ_MHZ = 58320;
- /**
- * 60 GHz band frequency of last channel in MHz
- * @hide
- */
- public static final int BAND_60_GHZ_END_FREQ_MHZ = 70200;
-
- /**
- * Utility function to check if a frequency within 2.4 GHz band
- * @param freqMhz frequency in MHz
- * @return true if within 2.4GHz, false otherwise
- *
- * @hide
- */
- public static boolean is24GHz(int freqMhz) {
- return freqMhz >= BAND_24_GHZ_START_FREQ_MHZ && freqMhz <= BAND_24_GHZ_END_FREQ_MHZ;
- }
-
- /**
- * Utility function to check if a frequency within 5 GHz band
- * @param freqMhz frequency in MHz
- * @return true if within 5GHz, false otherwise
- *
- * @hide
- */
- public static boolean is5GHz(int freqMhz) {
- return freqMhz >= BAND_5_GHZ_START_FREQ_MHZ && freqMhz <= BAND_5_GHZ_END_FREQ_MHZ;
- }
-
- /**
- * Utility function to check if a frequency within 6 GHz band
- * @param freqMhz
- * @return true if within 6GHz, false otherwise
- *
- * @hide
- */
- public static boolean is6GHz(int freqMhz) {
- if (freqMhz == BAND_6_GHZ_OP_CLASS_136_CH_2_FREQ_MHZ) {
- return true;
- }
- return (freqMhz >= BAND_6_GHZ_START_FREQ_MHZ && freqMhz <= BAND_6_GHZ_END_FREQ_MHZ);
- }
-
- /**
- * Utility function to check if a frequency within 60 GHz band
- * @param freqMhz
- * @return true if within 60GHz, false otherwise
- *
- * @hide
- */
- public static boolean is60GHz(int freqMhz) {
- return freqMhz >= BAND_60_GHZ_START_FREQ_MHZ && freqMhz <= BAND_60_GHZ_END_FREQ_MHZ;
- }
-
- /**
- * Utility function to convert channel number/band to frequency in MHz
- * @param channel number to convert
- * @param band of channel to convert
- * @return center frequency in Mhz of the channel, {@link UNSPECIFIED} if no match
- *
- * @hide
- */
- public static int convertChannelToFrequencyMhz(int channel, @WifiScanner.WifiBand int band) {
- if (band == WifiScanner.WIFI_BAND_24_GHZ) {
- // Special case
- if (channel == 14) {
- return 2484;
- } else if (channel >= BAND_24_GHZ_FIRST_CH_NUM && channel <= BAND_24_GHZ_LAST_CH_NUM) {
- return ((channel - BAND_24_GHZ_FIRST_CH_NUM) * 5) + BAND_24_GHZ_START_FREQ_MHZ;
- } else {
- return UNSPECIFIED;
- }
- }
- if (band == WifiScanner.WIFI_BAND_5_GHZ) {
- if (channel >= BAND_5_GHZ_FIRST_CH_NUM && channel <= BAND_5_GHZ_LAST_CH_NUM) {
- return ((channel - BAND_5_GHZ_FIRST_CH_NUM) * 5) + BAND_5_GHZ_START_FREQ_MHZ;
- } else {
- return UNSPECIFIED;
- }
- }
- if (band == WifiScanner.WIFI_BAND_6_GHZ) {
- if (channel >= BAND_6_GHZ_FIRST_CH_NUM && channel <= BAND_6_GHZ_LAST_CH_NUM) {
- if (channel == 2) {
- return BAND_6_GHZ_OP_CLASS_136_CH_2_FREQ_MHZ;
- }
- return ((channel - BAND_6_GHZ_FIRST_CH_NUM) * 5) + BAND_6_GHZ_START_FREQ_MHZ;
- } else {
- return UNSPECIFIED;
- }
- }
- return UNSPECIFIED;
- }
-
- /**
- * Utility function to convert frequency in MHz to channel number
- * @param freqMhz frequency in MHz
- * @return channel number associated with given frequency, {@link UNSPECIFIED} if no match
- *
- * @hide
- */
- public static int convertFrequencyMhzToChannel(int freqMhz) {
- // Special case
- if (freqMhz == 2484) {
- return 14;
- } else if (is24GHz(freqMhz)) {
- return (freqMhz - BAND_24_GHZ_START_FREQ_MHZ) / 5 + BAND_24_GHZ_FIRST_CH_NUM;
- } else if (is5GHz(freqMhz)) {
- return ((freqMhz - BAND_5_GHZ_START_FREQ_MHZ) / 5) + BAND_5_GHZ_FIRST_CH_NUM;
- } else if (is6GHz(freqMhz)) {
- if (freqMhz == BAND_6_GHZ_OP_CLASS_136_CH_2_FREQ_MHZ) {
- return 2;
- }
- return ((freqMhz - BAND_6_GHZ_START_FREQ_MHZ) / 5) + BAND_6_GHZ_FIRST_CH_NUM;
- }
-
- return UNSPECIFIED;
- }
-
- /**
- * @hide
- */
- public boolean is24GHz() {
- return ScanResult.is24GHz(frequency);
- }
-
- /**
- * @hide
- */
- public boolean is5GHz() {
- return ScanResult.is5GHz(frequency);
- }
-
- /**
- * @hide
- */
- public boolean is6GHz() {
- return ScanResult.is6GHz(frequency);
- }
-
- /**
- * @hide
- */
- public boolean is60GHz() {
- return ScanResult.is60GHz(frequency);
- }
-
- /**
- * @hide
- * anqp lines from supplicant BSS response
- */
- @UnsupportedAppUsage
- public List<String> anqpLines;
-
- /**
- * information elements from beacon.
- */
- public static class InformationElement {
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_SSID = 0;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_SUPPORTED_RATES = 1;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_TIM = 5;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_BSS_LOAD = 11;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_ERP = 42;
- /** @hide */
- public static final int EID_HT_CAPABILITIES = 45;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_RSN = 48;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_EXTENDED_SUPPORTED_RATES = 50;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_HT_OPERATION = 61;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_INTERWORKING = 107;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_ROAMING_CONSORTIUM = 111;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_EXTENDED_CAPS = 127;
- /** @hide */
- public static final int EID_VHT_CAPABILITIES = 191;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_VHT_OPERATION = 192;
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int EID_VSA = 221;
- /** @hide */
- public static final int EID_EXTENSION_PRESENT = 255;
-
- // Extension IDs
- /** @hide */
- public static final int EID_EXT_HE_CAPABILITIES = 35;
- /** @hide */
- public static final int EID_EXT_HE_OPERATION = 36;
-
- /** @hide */
- @UnsupportedAppUsage
- public int id;
- /** @hide */
- public int idExt;
-
- /** @hide */
- @UnsupportedAppUsage
- public byte[] bytes;
-
- /** @hide */
- public InformationElement() {
- }
-
- public InformationElement(@NonNull InformationElement rhs) {
- this.id = rhs.id;
- this.idExt = rhs.idExt;
- this.bytes = rhs.bytes.clone();
- }
-
- /**
- * The element ID of the information element. Defined in the IEEE 802.11-2016 spec
- * Table 9-77.
- */
- public int getId() {
- return id;
- }
-
- /**
- * The element ID Extension of the information element. Defined in the IEEE 802.11-2016 spec
- * Table 9-77.
- */
- public int getIdExt() {
- return idExt;
- }
-
- /**
- * Get the specific content of the information element.
- */
- @NonNull
- public ByteBuffer getBytes() {
- return ByteBuffer.wrap(bytes).asReadOnlyBuffer();
- }
- }
-
- /**
- * information elements found in the beacon.
- * @hide
- */
- @UnsupportedAppUsage
- public InformationElement[] informationElements;
- /**
- * Get all information elements found in the beacon.
- */
- @NonNull
- public List<InformationElement> getInformationElements() {
- return Collections.unmodifiableList(Arrays.asList(informationElements));
- }
-
- /** ANQP response elements.
- * @hide
- */
- public AnqpInformationElement[] anqpElements;
-
- /** {@hide} */
- public ScanResult(WifiSsid wifiSsid, String BSSID, long hessid, int anqpDomainId,
- byte[] osuProviders, String caps, int level, int frequency, long tsf) {
- this.wifiSsid = wifiSsid;
- this.SSID = (wifiSsid != null) ? wifiSsid.toString() : WifiManager.UNKNOWN_SSID;
- this.BSSID = BSSID;
- this.hessid = hessid;
- this.anqpDomainId = anqpDomainId;
- if (osuProviders != null) {
- this.anqpElements = new AnqpInformationElement[1];
- this.anqpElements[0] =
- new AnqpInformationElement(AnqpInformationElement.HOTSPOT20_VENDOR_ID,
- AnqpInformationElement.HS_OSU_PROVIDERS, osuProviders);
- }
- this.capabilities = caps;
- this.level = level;
- this.frequency = frequency;
- this.timestamp = tsf;
- this.distanceCm = UNSPECIFIED;
- this.distanceSdCm = UNSPECIFIED;
- this.channelWidth = UNSPECIFIED;
- this.centerFreq0 = UNSPECIFIED;
- this.centerFreq1 = UNSPECIFIED;
- this.flags = 0;
- this.radioChainInfos = null;
- this.mWifiStandard = WIFI_STANDARD_UNKNOWN;
- }
-
- /** {@hide} */
- public ScanResult(WifiSsid wifiSsid, String BSSID, String caps, int level, int frequency,
- long tsf, int distCm, int distSdCm) {
- this.wifiSsid = wifiSsid;
- this.SSID = (wifiSsid != null) ? wifiSsid.toString() : WifiManager.UNKNOWN_SSID;
- this.BSSID = BSSID;
- this.capabilities = caps;
- this.level = level;
- this.frequency = frequency;
- this.timestamp = tsf;
- this.distanceCm = distCm;
- this.distanceSdCm = distSdCm;
- this.channelWidth = UNSPECIFIED;
- this.centerFreq0 = UNSPECIFIED;
- this.centerFreq1 = UNSPECIFIED;
- this.flags = 0;
- this.radioChainInfos = null;
- this.mWifiStandard = WIFI_STANDARD_UNKNOWN;
- }
-
- /** {@hide} */
- public ScanResult(String Ssid, String BSSID, long hessid, int anqpDomainId, String caps,
- int level, int frequency,
- long tsf, int distCm, int distSdCm, int channelWidth, int centerFreq0, int centerFreq1,
- boolean is80211McRTTResponder) {
- this.SSID = Ssid;
- this.BSSID = BSSID;
- this.hessid = hessid;
- this.anqpDomainId = anqpDomainId;
- this.capabilities = caps;
- this.level = level;
- this.frequency = frequency;
- this.timestamp = tsf;
- this.distanceCm = distCm;
- this.distanceSdCm = distSdCm;
- this.channelWidth = channelWidth;
- this.centerFreq0 = centerFreq0;
- this.centerFreq1 = centerFreq1;
- if (is80211McRTTResponder) {
- this.flags = FLAG_80211mc_RESPONDER;
- } else {
- this.flags = 0;
- }
- this.radioChainInfos = null;
- this.mWifiStandard = WIFI_STANDARD_UNKNOWN;
- }
-
- /** {@hide} */
- public ScanResult(WifiSsid wifiSsid, String Ssid, String BSSID, long hessid, int anqpDomainId,
- String caps, int level,
- int frequency, long tsf, int distCm, int distSdCm, int channelWidth,
- int centerFreq0, int centerFreq1, boolean is80211McRTTResponder) {
- this(Ssid, BSSID, hessid, anqpDomainId, caps, level, frequency, tsf, distCm,
- distSdCm, channelWidth, centerFreq0, centerFreq1, is80211McRTTResponder);
- this.wifiSsid = wifiSsid;
- }
-
- /** copy constructor */
- public ScanResult(@NonNull ScanResult source) {
- if (source != null) {
- wifiSsid = source.wifiSsid;
- SSID = source.SSID;
- BSSID = source.BSSID;
- hessid = source.hessid;
- anqpDomainId = source.anqpDomainId;
- informationElements = source.informationElements;
- anqpElements = source.anqpElements;
- capabilities = source.capabilities;
- level = source.level;
- frequency = source.frequency;
- channelWidth = source.channelWidth;
- centerFreq0 = source.centerFreq0;
- centerFreq1 = source.centerFreq1;
- timestamp = source.timestamp;
- distanceCm = source.distanceCm;
- distanceSdCm = source.distanceSdCm;
- seen = source.seen;
- untrusted = source.untrusted;
- numUsage = source.numUsage;
- venueName = source.venueName;
- operatorFriendlyName = source.operatorFriendlyName;
- flags = source.flags;
- radioChainInfos = source.radioChainInfos;
- this.mWifiStandard = source.mWifiStandard;
- this.ifaceName = source.ifaceName;
- }
- }
-
- /** Construct an empty scan result. */
- public ScanResult() {
- }
-
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- String none = "<none>";
-
- sb.append("SSID: ")
- .append(wifiSsid == null ? WifiManager.UNKNOWN_SSID : wifiSsid)
- .append(", BSSID: ")
- .append(BSSID == null ? none : BSSID)
- .append(", capabilities: ")
- .append(capabilities == null ? none : capabilities)
- .append(", level: ")
- .append(level)
- .append(", frequency: ")
- .append(frequency)
- .append(", timestamp: ")
- .append(timestamp);
- sb.append(", distance: ").append((distanceCm != UNSPECIFIED ? distanceCm : "?")).
- append("(cm)");
- sb.append(", distanceSd: ").append((distanceSdCm != UNSPECIFIED ? distanceSdCm : "?")).
- append("(cm)");
-
- sb.append(", passpoint: ");
- sb.append(((flags & FLAG_PASSPOINT_NETWORK) != 0) ? "yes" : "no");
- sb.append(", ChannelBandwidth: ").append(channelWidth);
- sb.append(", centerFreq0: ").append(centerFreq0);
- sb.append(", centerFreq1: ").append(centerFreq1);
- sb.append(", standard: ").append(wifiStandardToString(mWifiStandard));
- sb.append(", 80211mcResponder: ");
- sb.append(((flags & FLAG_80211mc_RESPONDER) != 0) ? "is supported" : "is not supported");
- sb.append(", Radio Chain Infos: ").append(Arrays.toString(radioChainInfos));
- sb.append(", interface name: ").append(ifaceName);
- return sb.toString();
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- if (wifiSsid != null) {
- dest.writeInt(1);
- wifiSsid.writeToParcel(dest, flags);
- } else {
- dest.writeInt(0);
- }
- dest.writeString(SSID);
- dest.writeString(BSSID);
- dest.writeLong(hessid);
- dest.writeInt(anqpDomainId);
- dest.writeString(capabilities);
- dest.writeInt(level);
- dest.writeInt(frequency);
- dest.writeLong(timestamp);
- dest.writeInt(distanceCm);
- dest.writeInt(distanceSdCm);
- dest.writeInt(channelWidth);
- dest.writeInt(centerFreq0);
- dest.writeInt(centerFreq1);
- dest.writeInt(mWifiStandard);
- dest.writeLong(seen);
- dest.writeInt(untrusted ? 1 : 0);
- dest.writeInt(numUsage);
- dest.writeString((venueName != null) ? venueName.toString() : "");
- dest.writeString((operatorFriendlyName != null) ? operatorFriendlyName.toString() : "");
- dest.writeLong(this.flags);
-
- if (informationElements != null) {
- dest.writeInt(informationElements.length);
- for (int i = 0; i < informationElements.length; i++) {
- dest.writeInt(informationElements[i].id);
- dest.writeInt(informationElements[i].idExt);
- dest.writeInt(informationElements[i].bytes.length);
- dest.writeByteArray(informationElements[i].bytes);
- }
- } else {
- dest.writeInt(0);
- }
-
- if (anqpLines != null) {
- dest.writeInt(anqpLines.size());
- for (int i = 0; i < anqpLines.size(); i++) {
- dest.writeString(anqpLines.get(i));
- }
- }
- else {
- dest.writeInt(0);
- }
- if (anqpElements != null) {
- dest.writeInt(anqpElements.length);
- for (AnqpInformationElement element : anqpElements) {
- dest.writeInt(element.getVendorId());
- dest.writeInt(element.getElementId());
- dest.writeInt(element.getPayload().length);
- dest.writeByteArray(element.getPayload());
- }
- } else {
- dest.writeInt(0);
- }
-
- if (radioChainInfos != null) {
- dest.writeInt(radioChainInfos.length);
- for (int i = 0; i < radioChainInfos.length; i++) {
- dest.writeInt(radioChainInfos[i].id);
- dest.writeInt(radioChainInfos[i].level);
- }
- } else {
- dest.writeInt(0);
- }
- dest.writeString((ifaceName != null) ? ifaceName.toString() : "");
- }
-
- /** Implement the Parcelable interface */
- public static final @NonNull Creator<ScanResult> CREATOR =
- new Creator<ScanResult>() {
- public ScanResult createFromParcel(Parcel in) {
- WifiSsid wifiSsid = null;
- if (in.readInt() == 1) {
- wifiSsid = WifiSsid.CREATOR.createFromParcel(in);
- }
- ScanResult sr = new ScanResult(
- wifiSsid,
- in.readString(), /* SSID */
- in.readString(), /* BSSID */
- in.readLong(), /* HESSID */
- in.readInt(), /* ANQP Domain ID */
- in.readString(), /* capabilities */
- in.readInt(), /* level */
- in.readInt(), /* frequency */
- in.readLong(), /* timestamp */
- in.readInt(), /* distanceCm */
- in.readInt(), /* distanceSdCm */
- in.readInt(), /* channelWidth */
- in.readInt(), /* centerFreq0 */
- in.readInt(), /* centerFreq1 */
- false /* rtt responder,
- fixed with flags below */
- );
-
- sr.mWifiStandard = in.readInt();
- sr.seen = in.readLong();
- sr.untrusted = in.readInt() != 0;
- sr.numUsage = in.readInt();
- sr.venueName = in.readString();
- sr.operatorFriendlyName = in.readString();
- sr.flags = in.readLong();
- int n = in.readInt();
- if (n != 0) {
- sr.informationElements = new InformationElement[n];
- for (int i = 0; i < n; i++) {
- sr.informationElements[i] = new InformationElement();
- sr.informationElements[i].id = in.readInt();
- sr.informationElements[i].idExt = in.readInt();
- int len = in.readInt();
- sr.informationElements[i].bytes = new byte[len];
- in.readByteArray(sr.informationElements[i].bytes);
- }
- }
-
- n = in.readInt();
- if (n != 0) {
- sr.anqpLines = new ArrayList<String>();
- for (int i = 0; i < n; i++) {
- sr.anqpLines.add(in.readString());
- }
- }
- n = in.readInt();
- if (n != 0) {
- sr.anqpElements = new AnqpInformationElement[n];
- for (int i = 0; i < n; i++) {
- int vendorId = in.readInt();
- int elementId = in.readInt();
- int len = in.readInt();
- byte[] payload = new byte[len];
- in.readByteArray(payload);
- sr.anqpElements[i] =
- new AnqpInformationElement(vendorId, elementId, payload);
- }
- }
- n = in.readInt();
- if (n != 0) {
- sr.radioChainInfos = new RadioChainInfo[n];
- for (int i = 0; i < n; i++) {
- sr.radioChainInfos[i] = new RadioChainInfo();
- sr.radioChainInfos[i].id = in.readInt();
- sr.radioChainInfos[i].level = in.readInt();
- }
- }
- sr.ifaceName = in.readString();
- return sr;
- }
-
- public ScanResult[] newArray(int size) {
- return new ScanResult[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/SoftApCapability.java b/wifi/java/android/net/wifi/SoftApCapability.java
deleted file mode 100644
index 6e1c64235763..000000000000
--- a/wifi/java/android/net/wifi/SoftApCapability.java
+++ /dev/null
@@ -1,307 +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 android.net.wifi;
-
-import android.annotation.LongDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.wifi.SoftApConfiguration.BandType;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import com.android.modules.utils.build.SdkLevel;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Arrays;
-import java.util.Objects;
-
-/**
- * A class representing capability of the SoftAp.
- * {@see WifiManager}
- *
- * @hide
- */
-@SystemApi
-public final class SoftApCapability implements Parcelable {
-
- private static final String TAG = "SoftApCapability";
- private static final int[] EMPTY_INT_ARRAY = new int[0];
- /**
- * Support for automatic channel selection in driver (ACS).
- * Driver will auto select best channel based on interference to optimize performance.
- *
- * flag when {@link R.bool.config_wifi_softap_acs_supported} is true.
- *
- * <p>
- * Use {@link WifiManager.SoftApCallback#onInfoChanged(SoftApInfo)} and
- * {@link SoftApInfo#getFrequency} and {@link SoftApInfo#getBandwidth} to get
- * driver channel selection result.
- */
- public static final long SOFTAP_FEATURE_ACS_OFFLOAD = 1 << 0;
-
- /**
- * Support for client force disconnect.
- * flag when {@link R.bool.config_wifiSofapClientForceDisconnectSupported} is true
- *
- * <p>
- * Several Soft AP client control features, e.g. specifying the maximum number of
- * Soft AP clients, only work when this feature support is present.
- * Check feature support before invoking
- * {@link SoftApConfiguration.Builder#setMaxNumberOfClients(int)}
- */
- public static final long SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT = 1 << 1;
-
- /**
- * Support for WPA3 Simultaneous Authentication of Equals (WPA3-SAE).
- *
- * flag when {@link config_wifi_softap_sae_supported} is true.
- */
- public static final long SOFTAP_FEATURE_WPA3_SAE = 1 << 2;
-
- /**
- * Support for MAC address customization.
- * flag when {@link R.bool.config_wifiSoftapMacAddressCustomizationSupported} is true
- *
- * <p>
- * Check feature support before invoking
- * {@link SoftApConfiguration.Builder#setBssid(MadAddress)} or
- * {@link SoftApConfiguration.Builder#setMacRandomizationSetting(int)} with
- * {@link SoftApConfiguration.RANDOMIZATION_PERSISTENT}
- */
- public static final long SOFTAP_FEATURE_MAC_ADDRESS_CUSTOMIZATION = 1 << 3;
-
- /**
- * Support for WPA3 Opportunistic Wireless Encryption (WPA3-OWE).
- *
- * flag when {@link config_wifi_softap_owe_supported)} is true.
- * @hide
- */
- public static final long SOFTAP_FEATURE_WPA3_OWE = 1 << 4;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @LongDef(flag = true, prefix = { "SOFTAP_FEATURE_" }, value = {
- SOFTAP_FEATURE_ACS_OFFLOAD,
- SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT,
- SOFTAP_FEATURE_WPA3_SAE,
- SOFTAP_FEATURE_MAC_ADDRESS_CUSTOMIZATION,
- SOFTAP_FEATURE_WPA3_OWE,
- })
- public @interface HotspotFeatures {}
-
- private @HotspotFeatures long mSupportedFeatures = 0;
-
- private int mMaximumSupportedClientNumber;
-
- /**
- * A list storing supported 2.4G channels.
- */
- private int[] mSupportedChannelListIn24g = EMPTY_INT_ARRAY;
-
- /**
- * A list storing supported 5G channels.
- */
- private int[] mSupportedChannelListIn5g = EMPTY_INT_ARRAY;
-
- /**
- * A list storing supported 6G channels.
- */
- private int[] mSupportedChannelListIn6g = EMPTY_INT_ARRAY;
-
- /**
- * Get the maximum supported client numbers which AP resides on.
- */
- public int getMaxSupportedClients() {
- return mMaximumSupportedClientNumber;
- }
-
- /**
- * Set the maximum supported client numbers which AP resides on.
- *
- * @param maxClient maximum supported client numbers for the softap.
- * @hide
- */
- public void setMaxSupportedClients(int maxClient) {
- mMaximumSupportedClientNumber = maxClient;
- }
-
- /**
- * Returns true when all of the queried features are supported, otherwise false.
- *
- * @param features One or combination of the following features:
- * {@link #SOFTAP_FEATURE_ACS_OFFLOAD}, {@link #SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT} or
- * {@link #SOFTAP_FEATURE_WPA3_SAE}.
- */
- public boolean areFeaturesSupported(@HotspotFeatures long features) {
- return (mSupportedFeatures & features) == features;
- }
-
- /**
- * Set supported channel list in target band type.
- *
- * @param band One of the following band types:
- * {@link SoftApConfiguation#BAND_2GHZ}, {@link SoftApConfiguation#BAND_5GHZ} or
- * {@link SoftApConfiguation#BAND_6GHZ}.
- * @param supportedChannelList supported channel list in target band
- * @return true if band and supportedChannelList are valid, otherwise false.
- *
- * @throws IllegalArgumentException when band type is invalid.
- * @hide
- */
- public boolean setSupportedChannelList(@BandType int band,
- @Nullable int[] supportedChannelList) {
- if (supportedChannelList == null) return false;
- switch (band) {
- case SoftApConfiguration.BAND_2GHZ:
- mSupportedChannelListIn24g = supportedChannelList;
- break;
- case SoftApConfiguration.BAND_5GHZ:
- mSupportedChannelListIn5g = supportedChannelList;
- break;
- case SoftApConfiguration.BAND_6GHZ:
- mSupportedChannelListIn6g = supportedChannelList;
- break;
- default:
- throw new IllegalArgumentException("Invalid band: " + band);
- }
- return true;
- }
-
- /**
- * Returns a list of the supported channels in the given band.
- * The result depends on the on the country code that has been set.
- * Can be used to set the channel of the AP with the
- * {@link SoftapConfiguration.Builder#setChannel(int, int)} API.
- *
- * @param band One of the following band types:
- * {@link SoftApConfiguation#BAND_2GHZ}, {@link SoftApConfiguation#BAND_5GHZ} or
- * {@link SoftApConfiguation#BAND_6GHZ}.
- * @return List of supported channels for the band.
- *
- * @throws IllegalArgumentException when band type is invalid.
- */
- @NonNull
- public int[] getSupportedChannelList(@BandType int band) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- switch (band) {
- case SoftApConfiguration.BAND_2GHZ:
- return mSupportedChannelListIn24g;
- case SoftApConfiguration.BAND_5GHZ:
- return mSupportedChannelListIn5g;
- case SoftApConfiguration.BAND_6GHZ:
- return mSupportedChannelListIn6g;
- default:
- throw new IllegalArgumentException("Invalid band: " + band);
- }
- }
-
- /**
- * @hide
- */
- public SoftApCapability(@Nullable SoftApCapability source) {
- if (source != null) {
- mSupportedFeatures = source.mSupportedFeatures;
- mMaximumSupportedClientNumber = source.mMaximumSupportedClientNumber;
- mSupportedChannelListIn24g = source.mSupportedChannelListIn24g;
- mSupportedChannelListIn5g = source.mSupportedChannelListIn5g;
- mSupportedChannelListIn6g = source.mSupportedChannelListIn6g;
- }
- }
-
- /**
- * Constructor with combination of the feature.
- * Zero to no supported feature.
- *
- * @param features One or combination of the following features:
- * {@link #SOFTAP_FEATURE_ACS_OFFLOAD}, {@link #SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT} or
- * {@link #SOFTAP_FEATURE_WPA3_SAE}.
- * @hide
- */
- public SoftApCapability(@HotspotFeatures long features) {
- mSupportedFeatures = features;
- }
-
- @Override
- /** Implement the Parcelable interface. */
- public int describeContents() {
- return 0;
- }
-
- @Override
- /** Implement the Parcelable interface */
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeLong(mSupportedFeatures);
- dest.writeInt(mMaximumSupportedClientNumber);
- dest.writeIntArray(mSupportedChannelListIn24g);
- dest.writeIntArray(mSupportedChannelListIn5g);
- dest.writeIntArray(mSupportedChannelListIn6g);
- }
-
- @NonNull
- /** Implement the Parcelable interface */
- public static final Creator<SoftApCapability> CREATOR = new Creator<SoftApCapability>() {
- public SoftApCapability createFromParcel(Parcel in) {
- SoftApCapability capability = new SoftApCapability(in.readLong());
- capability.mMaximumSupportedClientNumber = in.readInt();
- capability.setSupportedChannelList(SoftApConfiguration.BAND_2GHZ, in.createIntArray());
- capability.setSupportedChannelList(SoftApConfiguration.BAND_5GHZ, in.createIntArray());
- capability.setSupportedChannelList(SoftApConfiguration.BAND_6GHZ, in.createIntArray());
- return capability;
- }
-
- public SoftApCapability[] newArray(int size) {
- return new SoftApCapability[size];
- }
- };
-
- @NonNull
- @Override
- public String toString() {
- StringBuilder sbuf = new StringBuilder();
- sbuf.append("SupportedFeatures=").append(mSupportedFeatures);
- sbuf.append("MaximumSupportedClientNumber=").append(mMaximumSupportedClientNumber);
- sbuf.append("SupportedChannelListIn24g")
- .append(Arrays.toString(mSupportedChannelListIn24g));
- sbuf.append("SupportedChannelListIn5g").append(Arrays.toString(mSupportedChannelListIn5g));
- sbuf.append("SupportedChannelListIn6g").append(Arrays.toString(mSupportedChannelListIn6g));
- return sbuf.toString();
- }
-
- @Override
- public boolean equals(@NonNull Object o) {
- if (this == o) return true;
- if (!(o instanceof SoftApCapability)) return false;
- SoftApCapability capability = (SoftApCapability) o;
- return mSupportedFeatures == capability.mSupportedFeatures
- && mMaximumSupportedClientNumber == capability.mMaximumSupportedClientNumber
- && Arrays.equals(mSupportedChannelListIn24g, capability.mSupportedChannelListIn24g)
- && Arrays.equals(mSupportedChannelListIn5g, capability.mSupportedChannelListIn5g)
- && Arrays.equals(mSupportedChannelListIn6g, capability.mSupportedChannelListIn6g);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mSupportedFeatures, mMaximumSupportedClientNumber,
- Arrays.hashCode(mSupportedChannelListIn24g),
- Arrays.hashCode(mSupportedChannelListIn5g),
- Arrays.hashCode(mSupportedChannelListIn6g));
- }
-}
diff --git a/wifi/java/android/net/wifi/SoftApConfToXmlMigrationUtil.java b/wifi/java/android/net/wifi/SoftApConfToXmlMigrationUtil.java
deleted file mode 100755
index c5472ce34478..000000000000
--- a/wifi/java/android/net/wifi/SoftApConfToXmlMigrationUtil.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (C) 2020 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 static android.os.Environment.getDataMiscDirectory;
-
-import android.annotation.Nullable;
-import android.net.MacAddress;
-import android.util.Log;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.FastXmlSerializer;
-import com.android.internal.util.XmlUtils;
-
-import org.xmlpull.v1.XmlPullParserException;
-import org.xmlpull.v1.XmlSerializer;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
-
-/**
- * Utility class to convert the legacy softap.conf file format to the new XML format.
- * Note:
- * <li>This should be modified by the OEM if they want to migrate configuration for existing
- * devices for new softap features supported by AOSP in Android 11.
- * For ex: client allowlist/blocklist feature was already supported by some OEM's before Android 10
- * while AOSP only supported it in Android 11. </li>
- * <li>Most of this class was copied over from WifiApConfigStore class in Android 10 and
- * SoftApStoreData class in Android 11</li>
- * @hide
- */
-public final class SoftApConfToXmlMigrationUtil {
- private static final String TAG = "SoftApConfToXmlMigrationUtil";
-
- /**
- * Directory to read the wifi config store files from under.
- */
- private static final String LEGACY_WIFI_STORE_DIRECTORY_NAME = "wifi";
- /**
- * The legacy Softap config file which contained key/value pairs.
- */
- private static final String LEGACY_AP_CONFIG_FILE = "softap.conf";
-
- /**
- * Pre-apex wifi shared folder.
- */
- private static File getLegacyWifiSharedDirectory() {
- return new File(getDataMiscDirectory(), LEGACY_WIFI_STORE_DIRECTORY_NAME);
- }
-
- /* @hide constants copied from WifiConfiguration */
- /**
- * 2GHz band.
- */
- private static final int WIFICONFIG_AP_BAND_2GHZ = 0;
- /**
- * 5GHz band.
- */
- private static final int WIFICONFIG_AP_BAND_5GHZ = 1;
- /**
- * Device is allowed to choose the optimal band (2Ghz or 5Ghz) based on device capability,
- * operating country code and current radio conditions.
- */
- private static final int WIFICONFIG_AP_BAND_ANY = -1;
- /**
- * Convert band from WifiConfiguration into SoftApConfiguration
- *
- * @param wifiConfigBand band encoded as WIFICONFIG_AP_BAND_xxxx
- * @return band as encoded as SoftApConfiguration.BAND_xxx
- */
- @VisibleForTesting
- public static int convertWifiConfigBandToSoftApConfigBand(int wifiConfigBand) {
- switch (wifiConfigBand) {
- case WIFICONFIG_AP_BAND_2GHZ:
- return SoftApConfiguration.BAND_2GHZ;
- case WIFICONFIG_AP_BAND_5GHZ:
- return SoftApConfiguration.BAND_5GHZ;
- case WIFICONFIG_AP_BAND_ANY:
- return SoftApConfiguration.BAND_2GHZ | SoftApConfiguration.BAND_5GHZ;
- default:
- return SoftApConfiguration.BAND_2GHZ;
- }
- }
-
- /**
- * Load AP configuration from legacy persistent storage.
- * Note: This is deprecated and only used for migrating data once on reboot.
- */
- private static SoftApConfiguration loadFromLegacyFile(InputStream fis) {
- SoftApConfiguration config = null;
- DataInputStream in = null;
- try {
- SoftApConfiguration.Builder configBuilder = new SoftApConfiguration.Builder();
- in = new DataInputStream(new BufferedInputStream(fis));
-
- int version = in.readInt();
- if (version < 1 || version > 3) {
- Log.e(TAG, "Bad version on hotspot configuration file");
- return null;
- }
- configBuilder.setSsid(in.readUTF());
-
- if (version >= 2) {
- int band = in.readInt();
- int channel = in.readInt();
- if (channel == 0) {
- configBuilder.setBand(
- convertWifiConfigBandToSoftApConfigBand(band));
- } else {
- configBuilder.setChannel(channel,
- convertWifiConfigBandToSoftApConfigBand(band));
- }
- }
- if (version >= 3) {
- configBuilder.setHiddenSsid(in.readBoolean());
- }
- int authType = in.readInt();
- if (authType == WifiConfiguration.KeyMgmt.WPA2_PSK) {
- configBuilder.setPassphrase(in.readUTF(),
- SoftApConfiguration.SECURITY_TYPE_WPA2_PSK);
- }
- config = configBuilder.build();
- } catch (IOException e) {
- Log.e(TAG, "Error reading hotspot configuration ", e);
- config = null;
- } catch (IllegalArgumentException ie) {
- Log.e(TAG, "Invalid hotspot configuration ", ie);
- config = null;
- } finally {
- if (in != null) {
- try {
- in.close();
- } catch (IOException e) {
- Log.e(TAG, "Error closing hotspot configuration during read", e);
- }
- }
- }
- // NOTE: OEM's should add their customized parsing code here.
- return config;
- }
-
- // This is the version that Android 11 released with.
- private static final int CONFIG_STORE_DATA_VERSION = 3;
-
- private static final String XML_TAG_DOCUMENT_HEADER = "WifiConfigStoreData";
- private static final String XML_TAG_VERSION = "Version";
- private static final String XML_TAG_SECTION_HEADER_SOFTAP = "SoftAp";
- private static final String XML_TAG_SSID = "SSID";
- private static final String XML_TAG_BSSID = "Bssid";
- private static final String XML_TAG_CHANNEL = "Channel";
- private static final String XML_TAG_HIDDEN_SSID = "HiddenSSID";
- private static final String XML_TAG_SECURITY_TYPE = "SecurityType";
- private static final String XML_TAG_AP_BAND = "ApBand";
- private static final String XML_TAG_PASSPHRASE = "Passphrase";
- private static final String XML_TAG_MAX_NUMBER_OF_CLIENTS = "MaxNumberOfClients";
- private static final String XML_TAG_AUTO_SHUTDOWN_ENABLED = "AutoShutdownEnabled";
- private static final String XML_TAG_SHUTDOWN_TIMEOUT_MILLIS = "ShutdownTimeoutMillis";
- private static final String XML_TAG_CLIENT_CONTROL_BY_USER = "ClientControlByUser";
- private static final String XML_TAG_BLOCKED_CLIENT_LIST = "BlockedClientList";
- private static final String XML_TAG_ALLOWED_CLIENT_LIST = "AllowedClientList";
- public static final String XML_TAG_CLIENT_MACADDRESS = "ClientMacAddress";
-
- private static byte[] convertConfToXml(SoftApConfiguration softApConf) {
- try {
- final XmlSerializer out = new FastXmlSerializer();
- final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- out.setOutput(outputStream, StandardCharsets.UTF_8.name());
-
- // Header for the XML file.
- out.startDocument(null, true);
- out.startTag(null, XML_TAG_DOCUMENT_HEADER);
- XmlUtils.writeValueXml(CONFIG_STORE_DATA_VERSION, XML_TAG_VERSION, out);
- out.startTag(null, XML_TAG_SECTION_HEADER_SOFTAP);
-
- // SoftAp conf
- XmlUtils.writeValueXml(softApConf.getSsid(), XML_TAG_SSID, out);
- if (softApConf.getBssid() != null) {
- XmlUtils.writeValueXml(softApConf.getBssid().toString(), XML_TAG_BSSID, out);
- }
- XmlUtils.writeValueXml(softApConf.getBand(), XML_TAG_AP_BAND, out);
- XmlUtils.writeValueXml(softApConf.getChannel(), XML_TAG_CHANNEL, out);
- XmlUtils.writeValueXml(softApConf.isHiddenSsid(), XML_TAG_HIDDEN_SSID, out);
- XmlUtils.writeValueXml(softApConf.getSecurityType(), XML_TAG_SECURITY_TYPE, out);
- if (softApConf.getSecurityType() != SoftApConfiguration.SECURITY_TYPE_OPEN) {
- XmlUtils.writeValueXml(softApConf.getPassphrase(), XML_TAG_PASSPHRASE, out);
- }
- XmlUtils.writeValueXml(softApConf.getMaxNumberOfClients(),
- XML_TAG_MAX_NUMBER_OF_CLIENTS, out);
- XmlUtils.writeValueXml(softApConf.isClientControlByUserEnabled(),
- XML_TAG_CLIENT_CONTROL_BY_USER, out);
- XmlUtils.writeValueXml(softApConf.isAutoShutdownEnabled(),
- XML_TAG_AUTO_SHUTDOWN_ENABLED, out);
- XmlUtils.writeValueXml(softApConf.getShutdownTimeoutMillis(),
- XML_TAG_SHUTDOWN_TIMEOUT_MILLIS, out);
- out.startTag(null, XML_TAG_BLOCKED_CLIENT_LIST);
- for (MacAddress mac: softApConf.getBlockedClientList()) {
- XmlUtils.writeValueXml(mac.toString(), XML_TAG_CLIENT_MACADDRESS, out);
- }
- out.endTag(null, XML_TAG_BLOCKED_CLIENT_LIST);
- out.startTag(null, XML_TAG_ALLOWED_CLIENT_LIST);
- for (MacAddress mac: softApConf.getAllowedClientList()) {
- XmlUtils.writeValueXml(mac.toString(), XML_TAG_CLIENT_MACADDRESS, out);
- }
- out.endTag(null, XML_TAG_ALLOWED_CLIENT_LIST);
-
- // Footer for the XML file.
- out.endTag(null, XML_TAG_SECTION_HEADER_SOFTAP);
- out.endTag(null, XML_TAG_DOCUMENT_HEADER);
- out.endDocument();
-
- return outputStream.toByteArray();
- } catch (IOException | XmlPullParserException e) {
- Log.e(TAG, "Failed to convert softap conf to XML", e);
- return null;
- }
- }
-
- private SoftApConfToXmlMigrationUtil() { }
-
- /**
- * Read the legacy /data/misc/wifi/softap.conf file format and convert to the new XML
- * format understood by WifiConfigStore.
- * Note: Used for unit testing.
- */
- @VisibleForTesting
- @Nullable
- public static InputStream convert(InputStream fis) {
- SoftApConfiguration softApConf = loadFromLegacyFile(fis);
- if (softApConf == null) return null;
-
- byte[] xmlBytes = convertConfToXml(softApConf);
- if (xmlBytes == null) return null;
-
- return new ByteArrayInputStream(xmlBytes);
- }
-
- /**
- * Read the legacy /data/misc/wifi/softap.conf file format and convert to the new XML
- * format understood by WifiConfigStore.
- */
- @Nullable
- public static InputStream convert() {
- File file = new File(getLegacyWifiSharedDirectory(), LEGACY_AP_CONFIG_FILE);
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(file);
- } catch (FileNotFoundException e) {
- return null;
- }
- if (fis == null) return null;
- return convert(fis);
- }
-
- /**
- * Remove the legacy /data/misc/wifi/softap.conf file.
- */
- @Nullable
- public static void remove() {
- File file = new File(getLegacyWifiSharedDirectory(), LEGACY_AP_CONFIG_FILE);
- file.delete();
- }
-}
diff --git a/wifi/java/android/net/wifi/SoftApConfiguration.java b/wifi/java/android/net/wifi/SoftApConfiguration.java
deleted file mode 100644
index 7ecd615c6937..000000000000
--- a/wifi/java/android/net/wifi/SoftApConfiguration.java
+++ /dev/null
@@ -1,1334 +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 android.net.wifi;
-
-import android.annotation.IntDef;
-import android.annotation.IntRange;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.SparseIntArray;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.Preconditions;
-import com.android.modules.utils.build.SdkLevel;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * Configuration for a soft access point (a.k.a. Soft AP, SAP, Hotspot).
- *
- * This is input for the framework provided by a client app, i.e. it exposes knobs to instruct the
- * framework how it should configure a hotspot.
- *
- * System apps can use this to configure a tethered hotspot using
- * {@code WifiManager#startTetheredHotspot(SoftApConfiguration)} and
- * {@code WifiManager#setSoftApConfiguration(SoftApConfiguration)}
- * or local-only hotspot using
- * {@code WifiManager#startLocalOnlyHotspot(SoftApConfiguration, Executor,
- * WifiManager.LocalOnlyHotspotCallback)}.
- *
- * Instances of this class are immutable; use {@link SoftApConfiguration.Builder} and its methods to
- * create a new instance.
- *
- */
-public final class SoftApConfiguration implements Parcelable {
-
- private static final String TAG = "SoftApConfiguration";
-
- @VisibleForTesting
- static final int PSK_MIN_LEN = 8;
-
- @VisibleForTesting
- static final int PSK_MAX_LEN = 63;
-
- /**
- * 2GHz band.
- * @hide
- */
- @SystemApi
- public static final int BAND_2GHZ = 1 << 0;
-
- /**
- * 5GHz band.
- * @hide
- */
- @SystemApi
- public static final int BAND_5GHZ = 1 << 1;
-
- /**
- * 6GHz band.
- * @hide
- */
- @SystemApi
- public static final int BAND_6GHZ = 1 << 2;
-
- /**
- * 2GHz + 5GHz or 2GHz + 6GHz concurrent Dual band.
- * @hide
- */
- public static final int BAND_DUAL = 1 << 3;
-
- /**
- * Device is allowed to choose the optimal band (2Ghz, 5Ghz, 6Ghz) based on device capability,
- * operating country code and current radio conditions.
- * @hide
- *
- * @deprecated The bands are a bit mask - use any combination of {@code BAND_},
- * for instance {@code BAND_2GHZ | BAND_5GHZ | BAND_6GHZ}.
- */
- @SystemApi
- public static final int BAND_ANY = BAND_2GHZ | BAND_5GHZ | BAND_6GHZ;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(flag = true, prefix = { "BAND_TYPE_" }, value = {
- BAND_2GHZ,
- BAND_5GHZ,
- BAND_6GHZ,
- BAND_DUAL,
- })
- public @interface BandType {}
-
- private static boolean isBandValid(@BandType int band) {
- return ((band != 0) && (((band & ~BAND_ANY) == 0) || (band == BAND_DUAL)));
- }
-
- private static final int MAX_CH_ACS = 0;
- private static final int MIN_CH_2G_BAND = 1;
- private static final int MAX_CH_2G_BAND = 14;
- private static final int MIN_CH_5G_BAND = 34;
- private static final int MAX_CH_5G_BAND = 196;
- private static final int MIN_CH_6G_BAND = 1;
- private static final int MAX_CH_6G_BAND = 253;
-
-
-
- private static boolean isChannelBandPairValid(int channel, @BandType int band) {
- switch (band) {
- case BAND_2GHZ:
- if (channel < MIN_CH_2G_BAND || channel > MAX_CH_2G_BAND) {
- return false;
- }
- break;
-
- case BAND_5GHZ:
- if (channel < MIN_CH_5G_BAND || channel > MAX_CH_5G_BAND) {
- return false;
- }
- break;
-
- case BAND_6GHZ:
- if (channel < MIN_CH_6G_BAND || channel > MAX_CH_6G_BAND) {
- return false;
- }
- break;
- case BAND_DUAL:
- if (channel != MAX_CH_ACS) {
- return false;
- }
- break;
- default:
- return false;
- }
- return true;
- }
-
- /**
- * SSID for the AP, or null for a framework-determined SSID.
- */
- private final @Nullable String mSsid;
-
- /**
- * BSSID for the AP, or null to use a framework-determined BSSID.
- */
- private final @Nullable MacAddress mBssid;
-
- /**
- * Pre-shared key for WPA2-PSK or WPA3-SAE-Transition or WPA3-SAE encryption which depends on
- * the security type.
- */
- private final @Nullable String mPassphrase;
-
- /**
- * This is a network that does not broadcast its SSID, so an
- * SSID-specific probe request must be used for scans.
- */
- private final boolean mHiddenSsid;
-
- /**
- * The operating channels of the dual APs.
- *
- * The SparseIntArray that consists the band and the channel of matching the band.
- */
- @NonNull
- private final SparseIntArray mChannels;
-
- /**
- * The maximim allowed number of clients that can associate to the AP.
- */
- private final int mMaxNumberOfClients;
-
- /**
- * The operating security type of the AP.
- * One of the following security types:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WPA2_PSK},
- * {@link #SECURITY_TYPE_WPA3_SAE_TRANSITION},
- * {@link #SECURITY_TYPE_WPA3_SAE}
- */
- private final @SecurityType int mSecurityType;
-
- /**
- * The flag to indicate client need to authorize by user
- * when client is connecting to AP.
- */
- private final boolean mClientControlByUser;
-
- /**
- * The list of blocked client that can't associate to the AP.
- */
- private final List<MacAddress> mBlockedClientList;
-
- /**
- * The list of allowed client that can associate to the AP.
- */
- private final List<MacAddress> mAllowedClientList;
-
- /**
- * Whether auto shutdown of soft AP is enabled or not.
- */
- private final boolean mAutoShutdownEnabled;
-
- /**
- * Delay in milliseconds before shutting down soft AP when
- * there are no connected devices.
- */
- private final long mShutdownTimeoutMillis;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"RANDOMIZATION_"}, value = {
- RANDOMIZATION_NONE,
- RANDOMIZATION_PERSISTENT})
- public @interface MacRandomizationSetting {}
-
- /**
- * Use factory MAC as BSSID for the AP
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_NONE = 0;
- /**
- * Generate a randomized MAC as BSSID for the AP
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_PERSISTENT = 1;
-
- /**
- * Level of MAC randomization for the AP BSSID.
- * @hide
- */
- @MacRandomizationSetting
- private int mMacRandomizationSetting;
-
-
- /**
- * THe definition of security type OPEN.
- */
- public static final int SECURITY_TYPE_OPEN = 0;
-
- /**
- * The definition of security type WPA2-PSK.
- */
- public static final int SECURITY_TYPE_WPA2_PSK = 1;
-
- /**
- * The definition of security type WPA3-SAE Transition mode.
- */
- public static final int SECURITY_TYPE_WPA3_SAE_TRANSITION = 2;
-
- /**
- * The definition of security type WPA3-SAE.
- */
- public static final int SECURITY_TYPE_WPA3_SAE = 3;
-
- /** @hide */
- public static final int SECURITY_TYPE_OWE = 4;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = { "SECURITY_TYPE_" }, value = {
- SECURITY_TYPE_OPEN,
- SECURITY_TYPE_WPA2_PSK,
- SECURITY_TYPE_WPA3_SAE_TRANSITION,
- SECURITY_TYPE_WPA3_SAE,
- SECURITY_TYPE_OWE,
- })
- public @interface SecurityType {}
-
- /**
- * Iface name for OWE transition mode.
- */
- private final @Nullable String mOweTransIfaceName;
-
- /** Private constructor for Builder and Parcelable implementation. */
- private SoftApConfiguration(@Nullable String ssid, @Nullable MacAddress bssid,
- @Nullable String passphrase, boolean hiddenSsid, @NonNull SparseIntArray channels,
- @SecurityType int securityType, int maxNumberOfClients, boolean shutdownTimeoutEnabled,
- long shutdownTimeoutMillis, boolean clientControlByUser,
- @NonNull List<MacAddress> blockedList, @NonNull List<MacAddress> allowedList,
- int macRandomizationSetting, @Nullable String oweTransIfaceName) {
- mSsid = ssid;
- mBssid = bssid;
- mPassphrase = passphrase;
- mHiddenSsid = hiddenSsid;
- if (channels.size() != 0) {
- mChannels = channels.clone();
- } else {
- mChannels = new SparseIntArray(1);
- mChannels.put(BAND_2GHZ, 0);
- }
- mSecurityType = securityType;
- mMaxNumberOfClients = maxNumberOfClients;
- mAutoShutdownEnabled = shutdownTimeoutEnabled;
- mShutdownTimeoutMillis = shutdownTimeoutMillis;
- mClientControlByUser = clientControlByUser;
- mBlockedClientList = new ArrayList<>(blockedList);
- mAllowedClientList = new ArrayList<>(allowedList);
- mMacRandomizationSetting = macRandomizationSetting;
- mOweTransIfaceName = oweTransIfaceName;
- }
-
- @Override
- public boolean equals(Object otherObj) {
- if (this == otherObj) {
- return true;
- }
- if (!(otherObj instanceof SoftApConfiguration)) {
- return false;
- }
- SoftApConfiguration other = (SoftApConfiguration) otherObj;
- return Objects.equals(mSsid, other.mSsid)
- && Objects.equals(mBssid, other.mBssid)
- && Objects.equals(mPassphrase, other.mPassphrase)
- && mHiddenSsid == other.mHiddenSsid
- && mChannels.toString().equals(other.mChannels.toString())
- && mSecurityType == other.mSecurityType
- && mMaxNumberOfClients == other.mMaxNumberOfClients
- && mAutoShutdownEnabled == other.mAutoShutdownEnabled
- && mShutdownTimeoutMillis == other.mShutdownTimeoutMillis
- && mClientControlByUser == other.mClientControlByUser
- && Objects.equals(mBlockedClientList, other.mBlockedClientList)
- && Objects.equals(mAllowedClientList, other.mAllowedClientList)
- && mMacRandomizationSetting == other.mMacRandomizationSetting
- && mOweTransIfaceName == other.mOweTransIfaceName;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mSsid, mBssid, mPassphrase, mHiddenSsid,
- mChannels.toString(), mSecurityType, mMaxNumberOfClients, mAutoShutdownEnabled,
- mShutdownTimeoutMillis, mClientControlByUser, mBlockedClientList,
- mAllowedClientList, mMacRandomizationSetting, mOweTransIfaceName);
- }
-
- @Override
- public String toString() {
- StringBuilder sbuf = new StringBuilder();
- sbuf.append("ssid = ").append(mSsid);
- if (mBssid != null) sbuf.append(" \n bssid = ").append(mBssid.toString());
- sbuf.append(" \n Passphrase = ").append(
- TextUtils.isEmpty(mPassphrase) ? "<empty>" : "<non-empty>");
- sbuf.append(" \n HiddenSsid =").append(mHiddenSsid);
- sbuf.append(" \n Channels =").append(mChannels);
- sbuf.append(" \n SecurityType=").append(getSecurityType());
- sbuf.append(" \n MaxClient=").append(mMaxNumberOfClients);
- sbuf.append(" \n AutoShutdownEnabled=").append(mAutoShutdownEnabled);
- sbuf.append(" \n ShutdownTimeoutMillis=").append(mShutdownTimeoutMillis);
- sbuf.append(" \n ClientControlByUser=").append(mClientControlByUser);
- sbuf.append(" \n BlockedClientList=").append(mBlockedClientList);
- sbuf.append(" \n AllowedClientList=").append(mAllowedClientList);
- sbuf.append(" \n MacRandomizationSetting=").append(mMacRandomizationSetting);
- sbuf.append(" \n OWE Transition mode Iface =").append(mOweTransIfaceName);
- return sbuf.toString();
- }
-
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeString(mSsid);
- dest.writeParcelable(mBssid, flags);
- dest.writeString(mPassphrase);
- dest.writeBoolean(mHiddenSsid);
- writeSparseIntArray(dest, mChannels);
- dest.writeInt(mSecurityType);
- dest.writeInt(mMaxNumberOfClients);
- dest.writeBoolean(mAutoShutdownEnabled);
- dest.writeLong(mShutdownTimeoutMillis);
- dest.writeBoolean(mClientControlByUser);
- dest.writeTypedList(mBlockedClientList);
- dest.writeTypedList(mAllowedClientList);
- dest.writeInt(mMacRandomizationSetting);
- dest.writeString(mOweTransIfaceName);
- }
-
- /* Reference from frameworks/base/core/java/android/os/Parcel.java */
- private static void writeSparseIntArray(@NonNull Parcel dest,
- @Nullable SparseIntArray val) {
- if (val == null) {
- dest.writeInt(-1);
- return;
- }
- int n = val.size();
- dest.writeInt(n);
- int i = 0;
- while (i < n) {
- dest.writeInt(val.keyAt(i));
- dest.writeInt(val.valueAt(i));
- i++;
- }
- }
-
-
- /* Reference from frameworks/base/core/java/android/os/Parcel.java */
- @NonNull
- private static SparseIntArray readSparseIntArray(@NonNull Parcel in) {
- int n = in.readInt();
- if (n < 0) {
- return new SparseIntArray();
- }
- SparseIntArray sa = new SparseIntArray(n);
- while (n > 0) {
- int key = in.readInt();
- int value = in.readInt();
- sa.append(key, value);
- n--;
- }
- return sa;
- }
-
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @NonNull
- public static final Creator<SoftApConfiguration> CREATOR = new Creator<SoftApConfiguration>() {
- @Override
- public SoftApConfiguration createFromParcel(Parcel in) {
- return new SoftApConfiguration(
- in.readString(),
- in.readParcelable(MacAddress.class.getClassLoader()),
- in.readString(), in.readBoolean(), readSparseIntArray(in), in.readInt(),
- in.readInt(), in.readBoolean(), in.readLong(), in.readBoolean(),
- in.createTypedArrayList(MacAddress.CREATOR),
- in.createTypedArrayList(MacAddress.CREATOR), in.readInt(), in.readString());
- }
-
- @Override
- public SoftApConfiguration[] newArray(int size) {
- return new SoftApConfiguration[size];
- }
- };
-
- /**
- * Return String set to be the SSID for the AP.
- * See also {@link Builder#setSsid(String)}.
- */
- @Nullable
- public String getSsid() {
- return mSsid;
- }
-
- /**
- * Returns MAC address set to be BSSID for the AP.
- * See also {@link Builder#setBssid(MacAddress)}.
- */
- @Nullable
- public MacAddress getBssid() {
- return mBssid;
- }
-
- /**
- * Returns String set to be passphrase for current AP.
- * See also {@link Builder#setPassphrase(String, int)}.
- */
- @Nullable
- public String getPassphrase() {
- return mPassphrase;
- }
-
- /**
- * Returns Boolean set to be indicate hidden (true: doesn't broadcast its SSID) or
- * not (false: broadcasts its SSID) for the AP.
- * See also {@link Builder#setHiddenSsid(boolean)}.
- */
- public boolean isHiddenSsid() {
- return mHiddenSsid;
- }
-
- /**
- * Returns band type set to be the band for the AP.
- *
- * One or combination of {@code BAND_}, for instance
- * {@link #BAND_2GHZ}, {@link #BAND_5GHZ}, or {@code BAND_2GHZ | BAND_5GHZ}.
- *
- * Note: Returns the lowest band when more than one band is set.
- * Use {@link #getBands()} to get dual bands setting.
- *
- * See also {@link Builder#setBand(int)}.
- *
- * @hide
- */
- @SystemApi
- public @BandType int getBand() {
- return mChannels.keyAt(0);
- }
-
- /**
- * Returns a sorted array in ascending order that consists of the configured band types
- * for the APs.
- *
- * The band type is one or combination of {@code BAND_}, for instance
- * {@link #BAND_2GHZ}, {@link #BAND_5GHZ}, or {@code BAND_2GHZ | BAND_5GHZ}.
- *
- * Note: return array may only include one band when current setting is single AP mode.
- * See also {@link Builder#setBands(int[])}.
- *
- * @hide
- */
- @SystemApi
- public @NonNull int[] getBands() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- int[] bands = new int[mChannels.size()];
- for (int i = 0; i < bands.length; i++) {
- bands[i] = mChannels.keyAt(i);
- }
- return bands;
- }
-
- /**
- * Returns Integer set to be the channel for the AP.
- *
- * Note: Returns the channel which associated to the lowest band if more than one channel
- * is set. Use {@link Builder#getChannels()} to get dual channel setting.
- * See also {@link Builder#setChannel(int, int)}.
- *
- * @hide
- */
- @SystemApi
- public int getChannel() {
- return mChannels.valueAt(0);
- }
-
-
- /**
- * Returns SparseIntArray (key: {@code BandType} , value: channel) that consists of
- * the configured bands and channels for the AP(s).
- *
- * Note: return array may only include one channel when current setting is single AP mode.
- * See also {@link Builder#setChannels(SparseIntArray)}.
- *
- * @hide
- */
- @SystemApi
- public @NonNull SparseIntArray getChannels() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return getChannelsInternal();
- }
-
- /**
- * Internal version bypassing SdkLevel checks
- * TODO(b/173791707): find a better way to allow Wifi to call its own new S APIs.
- * @hide
- */
- public @NonNull SparseIntArray getChannelsInternal() {
- return mChannels.clone();
- }
-
- /**
- * Get security type params which depends on which security passphrase to set.
- *
- * @return One of:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WPA2_PSK},
- * {@link #SECURITY_TYPE_WPA3_SAE_TRANSITION},
- * {@link #SECURITY_TYPE_WPA3_SAE}
- * {@link #SECURITY_TYPE_OWE},
- */
- public @SecurityType int getSecurityType() {
- return mSecurityType;
- }
-
- /**
- * Returns the maximum number of clients that can associate to the AP.
- * See also {@link Builder#setMaxNumberOfClients(int)}.
- *
- * @hide
- */
- @SystemApi
- public int getMaxNumberOfClients() {
- return mMaxNumberOfClients;
- }
-
- /**
- * Returns whether auto shutdown is enabled or not.
- * The Soft AP will shutdown when there are no devices associated to it for
- * the timeout duration. See also {@link Builder#setAutoShutdownEnabled(boolean)}.
- *
- * @hide
- */
- @SystemApi
- public boolean isAutoShutdownEnabled() {
- return mAutoShutdownEnabled;
- }
-
- /**
- * Returns the shutdown timeout in milliseconds.
- * The Soft AP will shutdown when there are no devices associated to it for
- * the timeout duration. See also {@link Builder#setShutdownTimeoutMillis(long)}.
- *
- * @hide
- */
- @SystemApi
- public long getShutdownTimeoutMillis() {
- return mShutdownTimeoutMillis;
- }
-
- /**
- * Returns a flag indicating whether clients need to be pre-approved by the user.
- * (true: authorization required) or not (false: not required).
- * See also {@link Builder#setClientControlByUserEnabled(Boolean)}.
- *
- * @hide
- */
- @SystemApi
- public boolean isClientControlByUserEnabled() {
- return mClientControlByUser;
- }
-
- /**
- * Returns List of clients which aren't allowed to associate to the AP.
- *
- * Clients are configured using {@link Builder#setBlockedClientList(List)}
- *
- * @hide
- */
- @NonNull
- @SystemApi
- public List<MacAddress> getBlockedClientList() {
- return mBlockedClientList;
- }
-
- /**
- * List of clients which are allowed to associate to the AP.
- * Clients are configured using {@link Builder#setAllowedClientList(List)}
- *
- * @hide
- */
- @NonNull
- @SystemApi
- public List<MacAddress> getAllowedClientList() {
- return mAllowedClientList;
- }
-
- /**
- * Returns the level of MAC randomization for the AP BSSID.
- * See also {@link Builder#setMacRandomizationSetting(int)}.
- *
- * @hide
- */
- @SystemApi
- @MacRandomizationSetting
- public int getMacRandomizationSetting() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mMacRandomizationSetting;
- }
-
- /**
- * Returns a {@link WifiConfiguration} representation of this {@link SoftApConfiguration}.
- * Note that SoftApConfiguration may contain configuration which is cannot be represented
- * by the legacy WifiConfiguration, in such cases a null will be returned.
- *
- * <li> SoftAp band in {@link WifiConfiguration.apBand} only supports
- * 2GHz, 5GHz, 2GHz+5GHz bands, so conversion is limited to these bands. </li>
- *
- * <li> SoftAp security type in {@link WifiConfiguration.KeyMgmt} only supports
- * NONE, WPA2_PSK, so conversion is limited to these security type.</li>
- * @hide
- */
- @Nullable
- @SystemApi
- public WifiConfiguration toWifiConfiguration() {
- WifiConfiguration wifiConfig = new WifiConfiguration();
- wifiConfig.SSID = mSsid;
- wifiConfig.preSharedKey = mPassphrase;
- wifiConfig.hiddenSSID = mHiddenSsid;
- wifiConfig.apChannel = getChannel();
- switch (mSecurityType) {
- case SECURITY_TYPE_OPEN:
- wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
- break;
- case SECURITY_TYPE_WPA2_PSK:
- case SECURITY_TYPE_WPA3_SAE_TRANSITION:
- wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA2_PSK);
- break;
- case SECURITY_TYPE_OWE:
- wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.OWE);
- break;
- default:
- Log.e(TAG, "Convert fail, unsupported security type :" + mSecurityType);
- return null;
- }
-
- switch (getBand()) {
- case BAND_2GHZ:
- wifiConfig.apBand = WifiConfiguration.AP_BAND_2GHZ;
- break;
- case BAND_5GHZ:
- wifiConfig.apBand = WifiConfiguration.AP_BAND_5GHZ;
- break;
- case BAND_2GHZ | BAND_5GHZ:
- wifiConfig.apBand = WifiConfiguration.AP_BAND_ANY;
- break;
- case BAND_2GHZ | BAND_6GHZ:
- wifiConfig.apBand = WifiConfiguration.AP_BAND_ANY;
- break;
- case BAND_ANY:
- wifiConfig.apBand = WifiConfiguration.AP_BAND_ANY;
- break;
- case BAND_DUAL:
- wifiConfig.apBand = WifiConfiguration.AP_BAND_DUAL;
- break;
- default:
- Log.e(TAG, "Convert fail, unsupported band setting :" + getBand());
- return null;
- }
- return wifiConfig;
- }
-
- /**
- * Return the iface name for OWE transition mode for the AP.
- * {@link #setOweTransIfaceName(String)}.
- *
- * @hide
- */
- @Nullable
- public String getOweTransIfaceName() {
- return mOweTransIfaceName;
- }
-
- /**
- * Builds a {@link SoftApConfiguration}, which allows an app to configure various aspects of a
- * Soft AP.
- *
- * All fields are optional. By default, SSID and BSSID are automatically chosen by the
- * framework, and an open network is created.
- *
- * @hide
- */
- @SystemApi
- public static final class Builder {
- private String mSsid;
- private MacAddress mBssid;
- private String mPassphrase;
- private boolean mHiddenSsid;
- private SparseIntArray mChannels;
- private int mMaxNumberOfClients;
- private int mSecurityType;
- private boolean mAutoShutdownEnabled;
- private long mShutdownTimeoutMillis;
- private boolean mClientControlByUser;
- private List<MacAddress> mBlockedClientList;
- private List<MacAddress> mAllowedClientList;
- private int mMacRandomizationSetting;
- private String mOweTransIfaceName;
-
- /**
- * Constructs a Builder with default values (see {@link Builder}).
- */
- public Builder() {
- mSsid = null;
- mBssid = null;
- mPassphrase = null;
- mHiddenSsid = false;
- mChannels = new SparseIntArray(1);
- mChannels.put(BAND_2GHZ, 0);
- mMaxNumberOfClients = 0;
- mSecurityType = SECURITY_TYPE_OPEN;
- mAutoShutdownEnabled = true; // enabled by default.
- mShutdownTimeoutMillis = 0;
- mClientControlByUser = false;
- mBlockedClientList = new ArrayList<>();
- mAllowedClientList = new ArrayList<>();
- mMacRandomizationSetting = RANDOMIZATION_PERSISTENT;
- mOweTransIfaceName = null;
- }
-
- /**
- * Constructs a Builder initialized from an existing {@link SoftApConfiguration} instance.
- */
- public Builder(@NonNull SoftApConfiguration other) {
- Objects.requireNonNull(other);
-
- mSsid = other.mSsid;
- mBssid = other.mBssid;
- mPassphrase = other.mPassphrase;
- mHiddenSsid = other.mHiddenSsid;
- mChannels = other.mChannels.clone();
- mMaxNumberOfClients = other.mMaxNumberOfClients;
- mSecurityType = other.mSecurityType;
- mAutoShutdownEnabled = other.mAutoShutdownEnabled;
- mShutdownTimeoutMillis = other.mShutdownTimeoutMillis;
- mClientControlByUser = other.mClientControlByUser;
- mBlockedClientList = new ArrayList<>(other.mBlockedClientList);
- mAllowedClientList = new ArrayList<>(other.mAllowedClientList);
- mMacRandomizationSetting = other.mMacRandomizationSetting;
- mOweTransIfaceName = other.mOweTransIfaceName;
- }
-
- /**
- * Builds the {@link SoftApConfiguration}.
- *
- * @return A new {@link SoftApConfiguration}, as configured by previous method calls.
- */
- @NonNull
- public SoftApConfiguration build() {
- for (MacAddress client : mAllowedClientList) {
- if (mBlockedClientList.contains(client)) {
- throw new IllegalArgumentException("A MacAddress exist in both client list");
- }
- }
- return new SoftApConfiguration(mSsid, mBssid, mPassphrase,
- mHiddenSsid, mChannels, mSecurityType, mMaxNumberOfClients,
- mAutoShutdownEnabled, mShutdownTimeoutMillis, mClientControlByUser,
- mBlockedClientList, mAllowedClientList, mMacRandomizationSetting,
- mOweTransIfaceName);
- }
-
- /**
- * Specifies an SSID for the AP.
- * <p>
- * Null SSID only support when configure a local-only hotspot.
- * <p>
- * <li>If not set, defaults to null.</li>
- *
- * @param ssid SSID of valid Unicode characters, or null to have the SSID automatically
- * chosen by the framework.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when the SSID is empty or not valid Unicode.
- */
- @NonNull
- public Builder setSsid(@Nullable String ssid) {
- if (ssid != null) {
- Preconditions.checkStringNotEmpty(ssid);
- Preconditions.checkArgument(StandardCharsets.UTF_8.newEncoder().canEncode(ssid));
- }
- mSsid = ssid;
- return this;
- }
-
- /**
- * Specifies a BSSID for the AP.
- * <p>
- * <li>If not set, defaults to null.</li>
- *
- * If multiple bands are requested via {@link #setBands(int[])} or
- * {@link #setChannels(SparseIntArray)}, HAL will derive 2 MAC addresses since framework
- * only sends down 1 MAC address.
- *
- * An example (but different implementation may perform a different mapping):
- * <li>MAC address 1: copy value of MAC address,
- * and set byte 1 = (0xFF - BSSID[1])</li>
- * <li>MAC address 2: copy value of MAC address,
- * and set byte 2 = (0xFF - BSSID[2])</li>
- *
- * Example BSSID argument: e2:38:60:c4:0e:b7
- * Derived MAC address 1: e2:c7:60:c4:0e:b7
- * Derived MAC address 2: e2:38:9f:c4:0e:b7
- *
- * <p>
- * Use {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_MAC_ADDRESS_CUSTOMIZATION} to determine
- * whether or not this feature is supported.
- *
- * @param bssid BSSID, or null to have the BSSID chosen by the framework. The caller is
- * responsible for avoiding collisions.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when the given BSSID is the all-zero
- * , multicast or broadcast MAC address.
- */
- @NonNull
- public Builder setBssid(@Nullable MacAddress bssid) {
- if (bssid != null) {
- Preconditions.checkArgument(!bssid.equals(WifiManager.ALL_ZEROS_MAC_ADDRESS));
- if (bssid.getAddressType() != MacAddress.TYPE_UNICAST) {
- throw new IllegalArgumentException("bssid doesn't support "
- + "multicast or broadcast mac address");
- }
- }
- mBssid = bssid;
- return this;
- }
-
- /**
- * Specifies that this AP should use specific security type with the given ASCII passphrase.
- *
- * @param securityType One of the following security types:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WPA2_PSK},
- * {@link #SECURITY_TYPE_WPA3_SAE_TRANSITION},
- * {@link #SECURITY_TYPE_WPA3_SAE}.
- * @param passphrase The passphrase to use for sepcific {@code securityType} configuration
- * or null with {@link #SECURITY_TYPE_OPEN}.
- *
- * @return Builder for chaining.
- * @throws IllegalArgumentException when the passphrase length is invalid and
- * {@code securityType} is not {@link #SECURITY_TYPE_OPEN}
- * or non-null passphrase and {@code securityType} is
- * {@link #SECURITY_TYPE_OPEN}.
- */
- @NonNull
- public Builder setPassphrase(@Nullable String passphrase, @SecurityType int securityType) {
- if (securityType == SECURITY_TYPE_OPEN
- || securityType == SECURITY_TYPE_OWE) {
- if (!TextUtils.isEmpty(passphrase)) {
- throw new IllegalArgumentException(
- "passphrase should be null when security type is open");
- } else {
- passphrase = null;
- }
- } else {
- Preconditions.checkStringNotEmpty(passphrase);
- if (securityType == SECURITY_TYPE_WPA2_PSK
- || securityType == SECURITY_TYPE_WPA3_SAE_TRANSITION) {
- if (passphrase.length() < PSK_MIN_LEN || passphrase.length() > PSK_MAX_LEN) {
- throw new IllegalArgumentException(
- "Password size must be at least " + PSK_MIN_LEN
- + " and no more than " + PSK_MAX_LEN
- + " for WPA2_PSK and WPA3_SAE_TRANSITION Mode");
- }
- }
- }
- mSecurityType = securityType;
- mPassphrase = passphrase;
- return this;
- }
-
- /**
- * Specifies whether the AP is hidden (doesn't broadcast its SSID) or
- * not (broadcasts its SSID).
- * <p>
- * <li>If not set, defaults to false (i.e not a hidden network).</li>
- *
- * @param hiddenSsid true for a hidden SSID, false otherwise.
- * @return Builder for chaining.
- */
- @NonNull
- public Builder setHiddenSsid(boolean hiddenSsid) {
- mHiddenSsid = hiddenSsid;
- return this;
- }
-
- /**
- * Specifies the band for the AP.
- * <p>
- * <li>If not set, defaults to {@link #BAND_2GHZ}.</li>
- *
- * @param band One or combination of the following band type:
- * {@link #BAND_2GHZ}, {@link #BAND_5GHZ}, {@link #BAND_6GHZ}.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when an invalid band type is provided.
- */
- @NonNull
- public Builder setBand(@BandType int band) {
- if (!isBandValid(band)) {
- throw new IllegalArgumentException("Invalid band type: " + band);
- }
- mChannels = new SparseIntArray(1);
- mChannels.put(band, 0);
- return this;
- }
-
- /**
- * Specifies the bands for the APs.
- * If more than 1 band is set, this will bring up concurrent APs.
- * on the requested bands (if possible).
- * <p>
- *
- * Use {@link WifiManager#isBridgedApConcurrencySupported()} to determine
- * whether or not concurrent APs are supported.
- *
- * @param bands Array of the {@link #BandType}.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when more than 2 bands are set or an invalid band type
- * is provided.
- */
- @NonNull
- public Builder setBands(@NonNull int[] bands) {
- if (bands.length == 0 || bands.length > 2) {
- throw new IllegalArgumentException("Unsupported number of bands("
- + bands.length + ") configured");
- }
- SparseIntArray channels = new SparseIntArray(bands.length);
- for (int val : bands) {
- if (!isBandValid(val)) {
- throw new IllegalArgumentException("Invalid band type: " + val);
- }
- channels.put(val, 0);
- }
- mChannels = channels;
- return this;
- }
-
-
- /**
- * Specifies the channel and associated band for the AP.
- *
- * The channel which AP resides on. Valid channels are country dependent.
- * The {@link SoftApCapability#getSupportedChannelList(int)} can be used to obtain
- * valid channels.
- *
- * <p>
- * If not set, the default for the channel is the special value 0 which has the
- * framework auto-select a valid channel from the band configured with
- * {@link #setBand(int)}.
- *
- * The channel auto selection will be offloaded to driver when
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_ACS_OFFLOAD}
- * return true. The driver will auto select the best channel (e.g. best performance)
- * based on environment interference. Check {@link SoftApCapability} for more detail.
- *
- * The API contains (band, channel) input since the 6GHz band uses the same channel
- * numbering scheme as is used in the 2.4GHz and 5GHz band. Therefore, both are needed to
- * uniquely identify individual channels.
- *
- * <p>
- * @param channel operating channel of the AP.
- * @param band containing this channel.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when the invalid channel or band type is configured.
- */
- @NonNull
- public Builder setChannel(int channel, @BandType int band) {
- if (!isChannelBandPairValid(channel, band)) {
- throw new IllegalArgumentException("Invalid channel(" + channel
- + ") & band (" + band + ") configured");
- }
- mChannels = new SparseIntArray(1);
- mChannels.put(band, channel);
- return this;
- }
-
- /**
- * Specifies the channels and associated bands for the APs.
- *
- * When more than 1 channel is set, this will bring up concurrent APs on the requested
- * channels and bands (if possible).
- *
- * Valid channels are country dependent.
- * The {@link SoftApCapability#getSupportedChannelList(int)} can be used to obtain
- * valid channels in each band.
- *
- * Use {@link WifiManager#isBridgedApConcurrencySupported()} to determine
- * whether or not concurrent APs are supported.
- *
- * <p>
- * If not set, the default for the channel is the special value 0 which has the framework
- * auto-select a valid channel from the band configured with {@link #setBands(int[])}.
- *
- * The channel auto selection will be offloaded to driver when
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_ACS_OFFLOAD}
- * returns true. The driver will auto select the best channel (e.g. best performance)
- * based on environment interference. Check {@link SoftApCapability} for more detail.
- *
- * The API contains (band, channel) input since the 6GHz band uses the same channel
- * numbering scheme as is used in the 2.4GHz and 5GHz band. Therefore, both are needed to
- * uniquely identify individual channels.
- *
- * <p>
- * @param channels SparseIntArray (key: {@code #BandType} , value: channel) consists of
- * {@code BAND_} and corresponding channel.
- * @return Builder for chaining.
- * @throws IllegalArgumentException when more than 2 channels are set or the invalid
- * channel or band type is configured.
- */
- @NonNull
- public Builder setChannels(@NonNull SparseIntArray channels) {
- if (channels.size() == 0 || channels.size() > 2) {
- throw new IllegalArgumentException("Unsupported number of channels("
- + channels.size() + ") configured");
- }
- for (int i = 0; i < channels.size(); i++) {
- int channel = channels.valueAt(i);
- int band = channels.keyAt(i);
- if (channel == 0) {
- if (!isBandValid(band)) {
- throw new IllegalArgumentException("Invalid band type: " + band);
- }
- } else {
- if (!isChannelBandPairValid(channel, band)) {
- throw new IllegalArgumentException("Invalid channel(" + channel
- + ") & band (" + band + ") configured");
- }
- }
- }
- mChannels = channels.clone();
- return this;
- }
-
-
- /**
- * Specifies the maximum number of clients that can associate to the AP.
- *
- * The maximum number of clients (STAs) which can associate to the AP.
- * The AP will reject association from any clients above this number.
- * Specify a value of 0 to have the framework automatically use the maximum number
- * which the device can support (based on hardware and carrier constraints).
- * <p>
- * Use {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#getMaxSupportedClients} to get the maximum number of clients
- * which the device supports (based on hardware and carrier constraints).
- *
- * <p>
- * <li>If not set, defaults to 0.</li>
- *
- * This method requires HAL support. If the method is used to set a
- * non-zero {@code maxNumberOfClients} value then
- * {@link WifiManager#startTetheredHotspot} will report error code
- * {@link WifiManager#SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}.
- *
- * <p>
- * Use {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT} to determine whether
- * or not this feature is supported.
- *
- * @param maxNumberOfClients maximum client number of the AP.
- * @return Builder for chaining.
- */
- @NonNull
- public Builder setMaxNumberOfClients(@IntRange(from = 0) int maxNumberOfClients) {
- if (maxNumberOfClients < 0) {
- throw new IllegalArgumentException("maxNumberOfClients should be not negative");
- }
- mMaxNumberOfClients = maxNumberOfClients;
- return this;
- }
-
- /**
- * Specifies whether auto shutdown is enabled or not.
- * The Soft AP will shut down when there are no devices connected to it for
- * the timeout duration.
- *
- * <p>
- * <li>If not set, defaults to true</li>
- *
- * @param enable true to enable, false to disable.
- * @return Builder for chaining.
- *
- * @see #setShutdownTimeoutMillis(long)
- */
- @NonNull
- public Builder setAutoShutdownEnabled(boolean enable) {
- mAutoShutdownEnabled = enable;
- return this;
- }
-
- /**
- * Specifies the shutdown timeout in milliseconds.
- * The Soft AP will shut down when there are no devices connected to it for
- * the timeout duration.
- *
- * Specify a value of 0 to have the framework automatically use default timeout
- * setting which defined in {@link R.integer.config_wifi_framework_soft_ap_timeout_delay}
- *
- * <p>
- * <li>If not set, defaults to 0</li>
- * <li>The shut down timeout will apply when {@link #setAutoShutdownEnabled(boolean)} is
- * set to true</li>
- *
- * @param timeoutMillis milliseconds of the timeout delay.
- * @return Builder for chaining.
- *
- * @see #setAutoShutdownEnabled(boolean)
- */
- @NonNull
- public Builder setShutdownTimeoutMillis(@IntRange(from = 0) long timeoutMillis) {
- if (timeoutMillis < 0) {
- throw new IllegalArgumentException("Invalid timeout value");
- }
- mShutdownTimeoutMillis = timeoutMillis;
- return this;
- }
-
- /**
- * Configure the Soft AP to require manual user control of client association.
- * If disabled (the default) then any client which isn't in the blocked list
- * {@link #getBlockedClientList()} can associate to this Soft AP using the
- * correct credentials until the Soft AP capacity is reached (capacity is hardware, carrier,
- * or user limited - using {@link #setMaxNumberOfClients(int)}).
- *
- * If manual user control is enabled then clients will be accepted, rejected, or require
- * a user approval based on the configuration provided by
- * {@link #setBlockedClientList(List)} and {@link #setAllowedClientList(List)}.
- *
- * <p>
- * This method requires HAL support. HAL support can be determined using
- * {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT}
- *
- * <p>
- * If the method is called on a device without HAL support then starting the soft AP
- * using {@link WifiManager#startTetheredHotspot(SoftApConfiguration)} will fail with
- * {@link WifiManager#SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}.
- *
- * <p>
- * <li>If not set, defaults to false (i.e The authoriztion is not required).</li>
- *
- * @param enabled true for enabling the control by user, false otherwise.
- * @return Builder for chaining.
- */
- @NonNull
- public Builder setClientControlByUserEnabled(boolean enabled) {
- mClientControlByUser = enabled;
- return this;
- }
-
-
- /**
- * This method together with {@link setClientControlByUserEnabled(boolean)} control client
- * connections to the AP. If client control by user is disabled using the above method then
- * this API has no effect and clients are allowed to associate to the AP (within limit of
- * max number of clients).
- *
- * If client control by user is enabled then this API configures the list of clients
- * which are explicitly allowed. These are auto-accepted.
- *
- * All other clients which attempt to associate, whose MAC addresses are on neither list,
- * are:
- * <ul>
- * <li>Rejected</li>
- * <li>A callback {@link WifiManager.SoftApCallback#onBlockedClientConnecting(WifiClient)}
- * is issued (which allows the user to add them to the allowed client list if desired).<li>
- * </ul>
- *
- * @param allowedClientList list of clients which are allowed to associate to the AP
- * without user pre-approval.
- * @return Builder for chaining.
- */
- @NonNull
- public Builder setAllowedClientList(@NonNull List<MacAddress> allowedClientList) {
- mAllowedClientList = new ArrayList<>(allowedClientList);
- return this;
- }
-
- /**
- * This API configures the list of clients which are blocked and cannot associate
- * to the Soft AP.
- *
- * <p>
- * This method requires HAL support. HAL support can be determined using
- * {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT}
- *
- * <p>
- * If the method is called on a device without HAL support then starting the soft AP
- * using {@link WifiManager#startTetheredHotspot(SoftApConfiguration)} will fail with
- * {@link WifiManager#SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}.
- *
- * @param blockedClientList list of clients which are not allowed to associate to the AP.
- * @return Builder for chaining.
- */
- @NonNull
- public Builder setBlockedClientList(@NonNull List<MacAddress> blockedClientList) {
- mBlockedClientList = new ArrayList<>(blockedClientList);
- return this;
- }
-
- /**
- * Specifies the level of MAC randomization for the AP BSSID.
- * The Soft AP BSSID will be randomized only if the BSSID isn't set
- * {@link #setBssid(MacAddress)} and this method is either uncalled
- * or called with {@link #RANDOMIZATION_PERSISTENT}.
- *
- * <p>
- * <li>If not set, defaults to {@link #RANDOMIZATION_PERSISTENT}</li>
- *
- * <p>
- * Requires HAL support when set to {@link #RANDOMIZATION_PERSISTENT}.
- * Use {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)} and
- * {@link SoftApCapability#areFeaturesSupported(long)}
- * with {@link SoftApCapability.SOFTAP_FEATURE_MAC_ADDRESS_CUSTOMIZATION} to determine
- * whether or not this feature is supported.
- *
- * @param macRandomizationSetting One of the following setting:
- * {@link #RANDOMIZATION_NONE} or {@link #RANDOMIZATION_PERSISTENT}.
- * @return Builder for chaining.
- *
- * @see #setBssid(MacAddress)
- */
- @NonNull
- public Builder setMacRandomizationSetting(
- @MacRandomizationSetting int macRandomizationSetting) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mMacRandomizationSetting = macRandomizationSetting;
- return this;
- }
-
- /**
- * Specifies an iface name for OWE transition mode for the AP.
- * <p>
- * <li>If not set, defaults to null.</li>
- *
- * @param oweTransIfaceName iface name for OWE transition mode.
- * @return Builder for chaining.
- *
- * @hide
- */
- @NonNull
- public Builder setOweTransIfaceName(@Nullable String oweTransIfaceName) {
- mOweTransIfaceName = oweTransIfaceName;
- return this;
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/SoftApInfo.java b/wifi/java/android/net/wifi/SoftApInfo.java
deleted file mode 100644
index 55c2f1759952..000000000000
--- a/wifi/java/android/net/wifi/SoftApInfo.java
+++ /dev/null
@@ -1,276 +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 android.net.wifi;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import com.android.internal.util.Preconditions;
-import com.android.modules.utils.build.SdkLevel;
-
-import java.util.Objects;
-
-/**
- * A class representing information about SoftAp.
- * {@see WifiManager}
- *
- * @hide
- */
-@SystemApi
-public final class SoftApInfo implements Parcelable {
-
- /**
- * AP Channel bandwidth is invalid.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_INVALID = 0;
-
- /**
- * AP Channel bandwidth is 20 MHZ but no HT.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_20MHZ_NOHT = 1;
-
- /**
- * AP Channel bandwidth is 20 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_20MHZ = 2;
-
- /**
- * AP Channel bandwidth is 40 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_40MHZ = 3;
-
- /**
- * AP Channel bandwidth is 80 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_80MHZ = 4;
-
- /**
- * AP Channel bandwidth is 160 MHZ, but 80MHZ + 80MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_80MHZ_PLUS_MHZ = 5;
-
- /**
- * AP Channel bandwidth is 160 MHZ.
- *
- * @see #getBandwidth()
- */
- public static final int CHANNEL_WIDTH_160MHZ = 6;
-
- /** The frequency which AP resides on. */
- private int mFrequency = 0;
-
- @WifiAnnotations.Bandwidth
- private int mBandwidth = CHANNEL_WIDTH_INVALID;
-
- /** The MAC Address which AP resides on. */
- @Nullable
- private MacAddress mBssid;
-
- /**
- * The operational mode of the AP.
- */
- private @WifiAnnotations.WifiStandard int mWifiStandard = ScanResult.WIFI_STANDARD_UNKNOWN;
-
- /**
- * Get the frequency which AP resides on.
- */
- public int getFrequency() {
- return mFrequency;
- }
-
- /**
- * Set the frequency which AP resides on.
- * @hide
- */
- public void setFrequency(int freq) {
- mFrequency = freq;
- }
-
- /**
- * Get AP Channel bandwidth.
- *
- * @return One of {@link #CHANNEL_WIDTH_20MHZ}, {@link #CHANNEL_WIDTH_40MHZ},
- * {@link #CHANNEL_WIDTH_80MHZ}, {@link #CHANNEL_WIDTH_160MHZ},
- * {@link #CHANNEL_WIDTH_80MHZ_PLUS_MHZ} or {@link #CHANNEL_WIDTH_INVALID}.
- */
- @WifiAnnotations.Bandwidth
- public int getBandwidth() {
- return mBandwidth;
- }
-
- /**
- * Set AP Channel bandwidth.
- * @hide
- */
- public void setBandwidth(@WifiAnnotations.Bandwidth int bandwidth) {
- mBandwidth = bandwidth;
- }
-
- /**
- * Get the MAC address (BSSID) of the AP. Null when AP disabled.
- */
- @Nullable
- public MacAddress getBssid() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mBssid;
- }
-
- /**
- * Set the MAC address which AP resides on.
- * <p>
- * <li>If not set, defaults to null.</li>
- * @param bssid BSSID, The caller is responsible for avoiding collisions.
- * @throws IllegalArgumentException when the given BSSID is the all-zero or broadcast MAC
- * address.
- *
- * @hide
- */
- public void setBssid(@Nullable MacAddress bssid) {
- if (bssid != null) {
- Preconditions.checkArgument(!bssid.equals(WifiManager.ALL_ZEROS_MAC_ADDRESS));
- Preconditions.checkArgument(!bssid.equals(MacAddress.BROADCAST_ADDRESS));
- }
- mBssid = bssid;
- }
-
- /**
- * Set the operational mode of the AP.
- *
- * @param wifiStandard values from {@link ScanResult}'s {@code WIFI_STANDARD_}
- * @hide
- */
- public void setWifiStandard(@WifiAnnotations.WifiStandard int wifiStandard) {
- mWifiStandard = wifiStandard;
- }
-
- /**
- * Get the operational mode of the AP.
- * @return valid values from {@link ScanResult}'s {@code WIFI_STANDARD_}
- */
- public @WifiAnnotations.WifiStandard int getWifiStandard() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return getWifiStandardInternal();
- }
-
- /**
- * Internal version bypassing SdkLevel checks
- * TODO(b/173791707): find a better way to allow Wifi to call its own new S APIs.
- * @hide
- */
- public @WifiAnnotations.WifiStandard int getWifiStandardInternal() {
- return mWifiStandard;
- }
-
- /**
- * @hide
- */
- public SoftApInfo(@Nullable SoftApInfo source) {
- if (source != null) {
- mFrequency = source.mFrequency;
- mBandwidth = source.mBandwidth;
- mBssid = source.mBssid;
- mWifiStandard = source.mWifiStandard;
- }
- }
-
- /**
- * @hide
- */
- public SoftApInfo() {
- }
-
- @Override
- /** Implement the Parcelable interface. */
- public int describeContents() {
- return 0;
- }
-
- @Override
- /** Implement the Parcelable interface */
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeInt(mFrequency);
- dest.writeInt(mBandwidth);
- dest.writeParcelable(mBssid, flags);
- dest.writeInt(mWifiStandard);
- }
-
- @NonNull
- /** Implement the Parcelable interface */
- public static final Creator<SoftApInfo> CREATOR = new Creator<SoftApInfo>() {
- public SoftApInfo createFromParcel(Parcel in) {
- SoftApInfo info = new SoftApInfo();
- info.mFrequency = in.readInt();
- info.mBandwidth = in.readInt();
- info.mBssid = in.readParcelable(MacAddress.class.getClassLoader());
- info.mWifiStandard = in.readInt();
- return info;
- }
-
- public SoftApInfo[] newArray(int size) {
- return new SoftApInfo[size];
- }
- };
-
- @NonNull
- @Override
- public String toString() {
- StringBuilder sbuf = new StringBuilder();
- sbuf.append("SoftApInfo{");
- sbuf.append("bandwidth= ").append(mBandwidth);
- sbuf.append(", frequency= ").append(mFrequency);
- if (mBssid != null) sbuf.append(",bssid=").append(mBssid.toString());
- sbuf.append(", wifiStandard= ").append(mWifiStandard);
- sbuf.append("}");
- return sbuf.toString();
- }
-
- @Override
- public boolean equals(@NonNull Object o) {
- if (this == o) return true;
- if (!(o instanceof SoftApInfo)) return false;
- SoftApInfo softApInfo = (SoftApInfo) o;
- return mFrequency == softApInfo.mFrequency
- && mBandwidth == softApInfo.mBandwidth
- && Objects.equals(mBssid, softApInfo.mBssid)
- && mWifiStandard == softApInfo.mWifiStandard;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mFrequency, mBandwidth, mBssid, mWifiStandard);
- }
-}
diff --git a/wifi/java/android/net/wifi/SupplicantState.java b/wifi/java/android/net/wifi/SupplicantState.java
deleted file mode 100644
index de7e2b556be3..000000000000
--- a/wifi/java/android/net/wifi/SupplicantState.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- * Copyright (C) 2008 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.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * From <code>defs.h</code> in <code>wpa_supplicant</code>.
- * <p/>
- * These enumeration values are used to indicate the current wpa_supplicant
- * state. This is more fine-grained than most users will be interested in.
- * In general, it is better to use
- * {@link android.net.NetworkInfo.State NetworkInfo.State}.
- * <p/>
- * Note, the order of these enum constants must match the numerical values of the
- * state constants in <code>defs.h</code> in <code>wpa_supplicant</code>.
- */
-public enum SupplicantState implements Parcelable {
- /**
- * This state indicates that client is not associated, but is likely to
- * start looking for an access point. This state is entered when a
- * connection is lost.
- */
- DISCONNECTED,
-
- /**
- * Interface is disabled
- * <p/>
- * This state is entered if the network interface is disabled.
- * wpa_supplicant refuses any new operations that would
- * use the radio until the interface has been enabled.
- */
- INTERFACE_DISABLED,
-
- /**
- * Inactive state (wpa_supplicant disabled).
- * <p/>
- * This state is entered if there are no enabled networks in the
- * configuration. wpa_supplicant is not trying to associate with a new
- * network and external interaction (e.g., ctrl_iface call to add or
- * enable a network) is needed to start association.
- */
- INACTIVE,
-
- /**
- * Scanning for a network.
- * <p/>
- * This state is entered when wpa_supplicant starts scanning for a
- * network.
- */
- SCANNING,
-
- /**
- * Trying to authenticate with a BSS/SSID
- * <p/>
- * This state is entered when wpa_supplicant has found a suitable BSS
- * to authenticate with and the driver is configured to try to
- * authenticate with this BSS.
- */
- AUTHENTICATING,
-
- /**
- * Trying to associate with a BSS/SSID.
- * <p/>
- * This state is entered when wpa_supplicant has found a suitable BSS
- * to associate with and the driver is configured to try to associate
- * with this BSS in ap_scan=1 mode. When using ap_scan=2 mode, this
- * state is entered when the driver is configured to try to associate
- * with a network using the configured SSID and security policy.
- */
- ASSOCIATING,
-
- /**
- * Association completed.
- * <p/>
- * This state is entered when the driver reports that association has
- * been successfully completed with an AP. If IEEE 802.1X is used
- * (with or without WPA/WPA2), wpa_supplicant remains in this state
- * until the IEEE 802.1X/EAPOL authentication has been completed.
- */
- ASSOCIATED,
-
- /**
- * WPA 4-Way Key Handshake in progress.
- * <p/>
- * This state is entered when WPA/WPA2 4-Way Handshake is started. In
- * case of WPA-PSK, this happens when receiving the first EAPOL-Key
- * frame after association. In case of WPA-EAP, this state is entered
- * when the IEEE 802.1X/EAPOL authentication has been completed.
- */
- FOUR_WAY_HANDSHAKE,
-
- /**
- * WPA Group Key Handshake in progress.
- * <p/>
- * This state is entered when 4-Way Key Handshake has been completed
- * (i.e., when the supplicant sends out message 4/4) and when Group
- * Key rekeying is started by the AP (i.e., when supplicant receives
- * message 1/2).
- */
- GROUP_HANDSHAKE,
-
- /**
- * All authentication completed.
- * <p/>
- * This state is entered when the full authentication process is
- * completed. In case of WPA2, this happens when the 4-Way Handshake is
- * successfully completed. With WPA, this state is entered after the
- * Group Key Handshake; with IEEE 802.1X (non-WPA) connection is
- * completed after dynamic keys are received (or if not used, after
- * the EAP authentication has been completed). With static WEP keys and
- * plaintext connections, this state is entered when an association
- * has been completed.
- * <p/>
- * This state indicates that the supplicant has completed its
- * processing for the association phase and that data connection is
- * fully configured. Note, however, that there may not be any IP
- * address associated with the connection yet. Typically, a DHCP
- * request needs to be sent at this point to obtain an address.
- */
- COMPLETED,
-
- /**
- * An Android-added state that is reported when a client issues an
- * explicit DISCONNECT command. In such a case, the supplicant is
- * not only dissociated from the current access point (as for the
- * DISCONNECTED state above), but it also does not attempt to connect
- * to any access point until a RECONNECT or REASSOCIATE command
- * is issued by the client.
- */
- DORMANT,
-
- /**
- * No connection to wpa_supplicant.
- * <p/>
- * This is an additional pseudo-state to handle the case where
- * wpa_supplicant is not running and/or we have not been able
- * to establish a connection to it.
- */
- UNINITIALIZED,
-
- /**
- * A pseudo-state that should normally never be seen.
- */
- INVALID;
-
- /**
- * Returns {@code true} if the supplicant state is valid and {@code false}
- * otherwise.
- * @param state The supplicant state
- * @return {@code true} if the supplicant state is valid and {@code false}
- * otherwise.
- */
- public static boolean isValidState(SupplicantState state) {
- return state != UNINITIALIZED && state != INVALID;
- }
-
-
- /** Supplicant associating or authenticating is considered a handshake state {@hide} */
- public static boolean isHandshakeState(SupplicantState state) {
- switch(state) {
- case AUTHENTICATING:
- case ASSOCIATING:
- case ASSOCIATED:
- case FOUR_WAY_HANDSHAKE:
- case GROUP_HANDSHAKE:
- return true;
- case COMPLETED:
- case DISCONNECTED:
- case INTERFACE_DISABLED:
- case INACTIVE:
- case SCANNING:
- case DORMANT:
- case UNINITIALIZED:
- case INVALID:
- return false;
- default:
- throw new IllegalArgumentException("Unknown supplicant state");
- }
- }
-
- /** @hide */
- public static boolean isConnecting(SupplicantState state) {
- switch(state) {
- case AUTHENTICATING:
- case ASSOCIATING:
- case ASSOCIATED:
- case FOUR_WAY_HANDSHAKE:
- case GROUP_HANDSHAKE:
- case COMPLETED:
- return true;
- case DISCONNECTED:
- case INTERFACE_DISABLED:
- case INACTIVE:
- case SCANNING:
- case DORMANT:
- case UNINITIALIZED:
- case INVALID:
- return false;
- default:
- throw new IllegalArgumentException("Unknown supplicant state");
- }
- }
-
- /** @hide */
- public static boolean isDriverActive(SupplicantState state) {
- switch(state) {
- case DISCONNECTED:
- case DORMANT:
- case INACTIVE:
- case AUTHENTICATING:
- case ASSOCIATING:
- case ASSOCIATED:
- case SCANNING:
- case FOUR_WAY_HANDSHAKE:
- case GROUP_HANDSHAKE:
- case COMPLETED:
- return true;
- case INTERFACE_DISABLED:
- case UNINITIALIZED:
- case INVALID:
- return false;
- default:
- throw new IllegalArgumentException("Unknown supplicant state");
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(name());
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @android.annotation.NonNull Creator<SupplicantState> CREATOR =
- new Creator<SupplicantState>() {
- public SupplicantState createFromParcel(Parcel in) {
- return SupplicantState.valueOf(in.readString());
- }
-
- public SupplicantState[] newArray(int size) {
- return new SupplicantState[size];
- }
- };
-
-}
diff --git a/wifi/java/android/net/wifi/SynchronousExecutor.java b/wifi/java/android/net/wifi/SynchronousExecutor.java
deleted file mode 100644
index 9926b1b5f7dc..000000000000
--- a/wifi/java/android/net/wifi/SynchronousExecutor.java
+++ /dev/null
@@ -1,29 +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 android.net.wifi;
-
-import java.util.concurrent.Executor;
-
-/**
- * An executor implementation that runs synchronously on the current thread.
- * @hide
- */
-public class SynchronousExecutor implements Executor {
- @Override
- public void execute(Runnable r) {
- r.run();
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiAnnotations.java b/wifi/java/android/net/wifi/WifiAnnotations.java
deleted file mode 100644
index acda7e06c95d..000000000000
--- a/wifi/java/android/net/wifi/WifiAnnotations.java
+++ /dev/null
@@ -1,124 +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 android.net.wifi;
-
-import android.annotation.IntDef;
-import android.annotation.StringDef;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-/**
- * Wifi annotations meant to be statically linked into client modules, since they cannot be
- * exposed as @SystemApi.
- *
- * e.g. {@link IntDef}, {@link StringDef}
- *
- * @hide
- */
-public final class WifiAnnotations {
- private WifiAnnotations() {}
-
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"SCAN_TYPE_"}, value = {
- WifiScanner.SCAN_TYPE_LOW_LATENCY,
- WifiScanner.SCAN_TYPE_LOW_POWER,
- WifiScanner.SCAN_TYPE_HIGH_ACCURACY})
- public @interface ScanType {}
-
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"WIFI_BAND_"}, value = {
- WifiScanner.WIFI_BAND_UNSPECIFIED,
- WifiScanner.WIFI_BAND_24_GHZ,
- WifiScanner.WIFI_BAND_5_GHZ,
- WifiScanner.WIFI_BAND_5_GHZ_DFS_ONLY,
- WifiScanner.WIFI_BAND_6_GHZ})
- public @interface WifiBandBasic {}
-
- @IntDef(prefix = { "CHANNEL_WIDTH_" }, value = {
- SoftApInfo.CHANNEL_WIDTH_INVALID,
- SoftApInfo.CHANNEL_WIDTH_20MHZ_NOHT,
- SoftApInfo.CHANNEL_WIDTH_20MHZ,
- SoftApInfo.CHANNEL_WIDTH_40MHZ,
- SoftApInfo.CHANNEL_WIDTH_80MHZ,
- SoftApInfo.CHANNEL_WIDTH_80MHZ_PLUS_MHZ,
- SoftApInfo.CHANNEL_WIDTH_160MHZ,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface Bandwidth {}
-
- @IntDef(prefix = { "CHANNEL_WIDTH_" }, value = {
- ScanResult.CHANNEL_WIDTH_20MHZ,
- ScanResult.CHANNEL_WIDTH_40MHZ,
- ScanResult.CHANNEL_WIDTH_80MHZ,
- ScanResult.CHANNEL_WIDTH_160MHZ,
- ScanResult.CHANNEL_WIDTH_80MHZ_PLUS_MHZ,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface ChannelWidth{}
-
- @IntDef(prefix = { "WIFI_STANDARD_" }, value = {
- ScanResult.WIFI_STANDARD_UNKNOWN,
- ScanResult.WIFI_STANDARD_LEGACY,
- ScanResult.WIFI_STANDARD_11N,
- ScanResult.WIFI_STANDARD_11AC,
- ScanResult.WIFI_STANDARD_11AX,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface WifiStandard{}
-
- @IntDef(prefix = { "PROTOCOL_" }, value = {
- ScanResult.PROTOCOL_NONE,
- ScanResult.PROTOCOL_WPA,
- ScanResult.PROTOCOL_RSN,
- ScanResult.PROTOCOL_OSEN,
- ScanResult.PROTOCOL_WAPI
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface Protocol {}
-
- @IntDef(prefix = { "KEY_MGMT_" }, value = {
- ScanResult.KEY_MGMT_NONE,
- ScanResult.KEY_MGMT_PSK,
- ScanResult.KEY_MGMT_EAP,
- ScanResult.KEY_MGMT_FT_PSK,
- ScanResult.KEY_MGMT_FT_EAP,
- ScanResult.KEY_MGMT_PSK_SHA256,
- ScanResult.KEY_MGMT_EAP_SHA256,
- ScanResult.KEY_MGMT_OSEN,
- ScanResult.KEY_MGMT_SAE,
- ScanResult.KEY_MGMT_OWE,
- ScanResult.KEY_MGMT_EAP_SUITE_B_192,
- ScanResult.KEY_MGMT_FT_SAE,
- ScanResult.KEY_MGMT_OWE_TRANSITION,
- ScanResult.KEY_MGMT_WAPI_PSK,
- ScanResult.KEY_MGMT_WAPI_CERT
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface KeyMgmt {}
-
- @IntDef(prefix = { "CIPHER_" }, value = {
- ScanResult.CIPHER_NONE,
- ScanResult.CIPHER_NO_GROUP_ADDRESSED,
- ScanResult.CIPHER_TKIP,
- ScanResult.CIPHER_CCMP,
- ScanResult.CIPHER_GCMP_256,
- ScanResult.CIPHER_SMS4
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface Cipher {}
-}
diff --git a/wifi/java/android/net/wifi/WifiClient.java b/wifi/java/android/net/wifi/WifiClient.java
deleted file mode 100644
index 3794566f3d8f..000000000000
--- a/wifi/java/android/net/wifi/WifiClient.java
+++ /dev/null
@@ -1,95 +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 android.net.wifi;
-
-import android.annotation.NonNull;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.Objects;
-
-/** @hide */
-@SystemApi
-public final class WifiClient implements Parcelable {
-
- private final MacAddress mMacAddress;
-
- /**
- * The mac address of this client.
- */
- @NonNull
- public MacAddress getMacAddress() {
- return mMacAddress;
- }
-
- private WifiClient(Parcel in) {
- mMacAddress = in.readParcelable(null);
- }
-
- /** @hide */
- public WifiClient(@NonNull MacAddress macAddress) {
- Objects.requireNonNull(macAddress, "mMacAddress must not be null.");
-
- this.mMacAddress = macAddress;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeParcelable(mMacAddress, flags);
- }
-
- @NonNull
- public static final Creator<WifiClient> CREATOR = new Creator<WifiClient>() {
- public WifiClient createFromParcel(Parcel in) {
- return new WifiClient(in);
- }
-
- public WifiClient[] newArray(int size) {
- return new WifiClient[size];
- }
- };
-
- @NonNull
- @Override
- public String toString() {
- return "WifiClient{"
- + "mMacAddress=" + mMacAddress
- + '}';
- }
-
- @Override
- public boolean equals(@NonNull Object o) {
- if (this == o) return true;
- if (!(o instanceof WifiClient)) return false;
- WifiClient client = (WifiClient) o;
- return mMacAddress.equals(client.mMacAddress);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mMacAddress);
- }
-}
-
-
diff --git a/wifi/java/android/net/wifi/WifiConfiguration.java b/wifi/java/android/net/wifi/WifiConfiguration.java
deleted file mode 100644
index 10e4afbeaf48..000000000000
--- a/wifi/java/android/net/wifi/WifiConfiguration.java
+++ /dev/null
@@ -1,3373 +0,0 @@
-/*
- * Copyright (C) 2008 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.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.content.pm.PackageManager;
-import android.net.IpConfiguration;
-import android.net.IpConfiguration.ProxySettings;
-import android.net.MacAddress;
-import android.net.NetworkSpecifier;
-import android.net.ProxyInfo;
-import android.net.StaticIpConfiguration;
-import android.net.Uri;
-import android.os.Build;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.os.SystemClock;
-import android.os.UserHandle;
-import android.telephony.SubscriptionInfo;
-import android.telephony.SubscriptionManager;
-import android.telephony.TelephonyManager;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.SparseArray;
-
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.net.module.util.MacAddressUtils;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Arrays;
-import java.util.BitSet;
-import java.util.Calendar;
-import java.util.HashMap;
-
-/**
- * A class representing a configured Wi-Fi network, including the
- * security configuration.
- *
- * @deprecated Use {@link WifiNetworkSpecifier.Builder} to create {@link NetworkSpecifier} and
- * {@link WifiNetworkSuggestion.Builder} to create {@link WifiNetworkSuggestion}. This will become a
- * system use only object in the future.
- */
-@Deprecated
-public class WifiConfiguration implements Parcelable {
- private static final String TAG = "WifiConfiguration";
- /**
- * Current Version of the Backup Serializer.
- */
- private static final int BACKUP_VERSION = 3;
- /** {@hide} */
- public static final String ssidVarName = "ssid";
- /** {@hide} */
- public static final String bssidVarName = "bssid";
- /** {@hide} */
- public static final String pskVarName = "psk";
- /** {@hide} */
- @Deprecated
- @UnsupportedAppUsage
- public static final String[] wepKeyVarNames = { "wep_key0", "wep_key1", "wep_key2", "wep_key3" };
- /** {@hide} */
- @Deprecated
- public static final String wepTxKeyIdxVarName = "wep_tx_keyidx";
- /** {@hide} */
- public static final String priorityVarName = "priority";
- /** {@hide} */
- public static final String hiddenSSIDVarName = "scan_ssid";
- /** {@hide} */
- public static final String pmfVarName = "ieee80211w";
- /** {@hide} */
- public static final String updateIdentiferVarName = "update_identifier";
- /**
- * The network ID for an invalid network.
- *
- * @hide
- */
- @SystemApi
- public static final int INVALID_NETWORK_ID = -1;
- /** {@hide} */
- public static final int LOCAL_ONLY_NETWORK_ID = -2;
-
- /** {@hide} */
- private String mPasspointManagementObjectTree;
- /** {@hide} */
- private static final int MAXIMUM_RANDOM_MAC_GENERATION_RETRY = 3;
-
- /** {@hide} */
- public static final String shareThisApVarName = "share_this_ap";
-
- /**
- * Recognized key management schemes.
- */
- public static class KeyMgmt {
- private KeyMgmt() { }
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(value = {
- NONE,
- WPA_PSK,
- WPA_EAP,
- IEEE8021X,
- WPA2_PSK,
- OSEN,
- FT_PSK,
- FT_EAP,
- SAE,
- OWE,
- SUITE_B_192,
- WPA_PSK_SHA256,
- WPA_EAP_SHA256,
- WAPI_PSK,
- WAPI_CERT,
- FILS_SHA256,
- FILS_SHA384,
- DPP})
- public @interface KeyMgmtScheme {}
-
- /** WPA is not used; plaintext or static WEP could be used. */
- public static final int NONE = 0;
- /** WPA pre-shared key (requires {@code preSharedKey} to be specified). */
- public static final int WPA_PSK = 1;
- /** WPA using EAP authentication. Generally used with an external authentication server. */
- public static final int WPA_EAP = 2;
- /**
- * IEEE 802.1X using EAP authentication and (optionally) dynamically
- * generated WEP keys.
- */
- public static final int IEEE8021X = 3;
-
- /**
- * WPA2 pre-shared key for use with soft access point
- * (requires {@code preSharedKey} to be specified).
- * @hide
- */
- @SystemApi
- public static final int WPA2_PSK = 4;
- /**
- * Hotspot 2.0 r2 OSEN:
- * @hide
- */
- public static final int OSEN = 5;
-
- /**
- * IEEE 802.11r Fast BSS Transition with PSK authentication.
- * @hide
- */
- public static final int FT_PSK = 6;
-
- /**
- * IEEE 802.11r Fast BSS Transition with EAP authentication.
- * @hide
- */
- public static final int FT_EAP = 7;
-
- /**
- * Simultaneous Authentication of Equals
- */
- public static final int SAE = 8;
-
- /**
- * Opportunististic Wireless Encryption
- */
- public static final int OWE = 9;
-
- /**
- * SUITE_B_192 192 bit level
- */
- public static final int SUITE_B_192 = 10;
-
- /**
- * WPA pre-shared key with stronger SHA256-based algorithms.
- * @hide
- */
- public static final int WPA_PSK_SHA256 = 11;
-
- /**
- * WPA using EAP authentication with stronger SHA256-based algorithms.
- * @hide
- */
- public static final int WPA_EAP_SHA256 = 12;
-
- /**
- * WAPI pre-shared key (requires {@code preSharedKey} to be specified).
- * @hide
- */
- @SystemApi
- public static final int WAPI_PSK = 13;
-
- /**
- * WAPI certificate to be specified.
- * @hide
- */
- @SystemApi
- public static final int WAPI_CERT = 14;
-
- /**
- * IEEE 802.11ai FILS SK with SHA256
- * @hide
- */
- public static final int FILS_SHA256 = 15;
- /**
- * IEEE 802.11ai FILS SK with SHA384:
- * @hide
- */
- public static final int FILS_SHA384 = 16;
- /**
- * Device Provisioning Protocol
- * @hide
- */
- public static final int DPP = 17;
-
- public static final String varName = "key_mgmt";
-
- public static final String[] strings = { "NONE", "WPA_PSK", "WPA_EAP",
- "IEEE8021X", "WPA2_PSK", "OSEN", "FT_PSK", "FT_EAP",
- "SAE", "OWE", "SUITE_B_192", "WPA_PSK_SHA256", "WPA_EAP_SHA256",
- "WAPI_PSK", "WAPI_CERT", "FILS_SHA256", "FILS_SHA384", "DPP", };
- }
-
- /**
- * Recognized security protocols.
- */
- public static class Protocol {
- private Protocol() { }
-
- /** WPA/IEEE 802.11i/D3.0
- * @deprecated Due to security and performance limitations, use of WPA-1 networks
- * is discouraged. WPA-2 (RSN) should be used instead. */
- @Deprecated
- public static final int WPA = 0;
- /** RSN WPA2/WPA3/IEEE 802.11i */
- public static final int RSN = 1;
- /** HS2.0 r2 OSEN
- * @hide
- */
- public static final int OSEN = 2;
-
- /**
- * WAPI Protocol
- */
- public static final int WAPI = 3;
-
- public static final String varName = "proto";
-
- public static final String[] strings = { "WPA", "RSN", "OSEN", "WAPI" };
- }
-
- /**
- * Recognized IEEE 802.11 authentication algorithms.
- */
- public static class AuthAlgorithm {
- private AuthAlgorithm() { }
-
- /** Open System authentication (required for WPA/WPA2) */
- public static final int OPEN = 0;
- /** Shared Key authentication (requires static WEP keys)
- * @deprecated Due to security and performance limitations, use of WEP networks
- * is discouraged. */
- @Deprecated
- public static final int SHARED = 1;
- /** LEAP/Network EAP (only used with LEAP) */
- public static final int LEAP = 2;
-
- /** SAE (Used only for WPA3-Personal) */
- public static final int SAE = 3;
-
- public static final String varName = "auth_alg";
-
- public static final String[] strings = { "OPEN", "SHARED", "LEAP", "SAE" };
- }
-
- /**
- * Recognized pairwise ciphers for WPA.
- */
- public static class PairwiseCipher {
- private PairwiseCipher() { }
-
- /** Use only Group keys (deprecated) */
- public static final int NONE = 0;
- /** Temporal Key Integrity Protocol [IEEE 802.11i/D7.0]
- * @deprecated Due to security and performance limitations, use of WPA-1 networks
- * is discouraged. WPA-2 (RSN) should be used instead. */
- @Deprecated
- public static final int TKIP = 1;
- /** AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0] */
- public static final int CCMP = 2;
- /**
- * AES in Galois/Counter Mode
- */
- public static final int GCMP_256 = 3;
- /**
- * SMS4 cipher for WAPI
- */
- public static final int SMS4 = 4;
-
- /**
- * AES in Galois/Counter Mode with a 128-bit integrity key
- */
- public static final int GCMP_128 = 5;
-
-
- public static final String varName = "pairwise";
-
- public static final String[] strings = { "NONE", "TKIP", "CCMP", "GCMP_256", "SMS4",
- "GCMP_128" };
- }
-
- /**
- * Recognized group ciphers.
- * <pre>
- * CCMP = AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0]
- * TKIP = Temporal Key Integrity Protocol [IEEE 802.11i/D7.0]
- * WEP104 = WEP (Wired Equivalent Privacy) with 104-bit key
- * WEP40 = WEP (Wired Equivalent Privacy) with 40-bit key (original 802.11)
- * GCMP_256 = AES in Galois/Counter Mode
- * </pre>
- */
- public static class GroupCipher {
- private GroupCipher() { }
-
- /** WEP40 = WEP (Wired Equivalent Privacy) with 40-bit key (original 802.11)
- * @deprecated Due to security and performance limitations, use of WEP networks
- * is discouraged. */
- @Deprecated
- public static final int WEP40 = 0;
- /** WEP104 = WEP (Wired Equivalent Privacy) with 104-bit key
- * @deprecated Due to security and performance limitations, use of WEP networks
- * is discouraged. */
- @Deprecated
- public static final int WEP104 = 1;
- /** Temporal Key Integrity Protocol [IEEE 802.11i/D7.0] */
- public static final int TKIP = 2;
- /** AES in Counter mode with CBC-MAC [RFC 3610, IEEE 802.11i/D7.0] */
- public static final int CCMP = 3;
- /** Hotspot 2.0 r2 OSEN
- * @hide
- */
- public static final int GTK_NOT_USED = 4;
- /**
- * AES in Galois/Counter Mode
- */
- public static final int GCMP_256 = 5;
- /**
- * SMS4 cipher for WAPI
- */
- public static final int SMS4 = 6;
- /**
- * AES in Galois/Counter Mode with a 128-bit integrity key
- */
- public static final int GCMP_128 = 7;
-
- public static final String varName = "group";
-
- public static final String[] strings =
- { /* deprecated */ "WEP40", /* deprecated */ "WEP104",
- "TKIP", "CCMP", "GTK_NOT_USED", "GCMP_256",
- "SMS4", "GCMP_128" };
- }
-
- /**
- * Recognized group management ciphers.
- * <pre>
- * BIP_CMAC_256 = Cipher-based Message Authentication Code 256 bits
- * BIP_GMAC_128 = Galois Message Authentication Code 128 bits
- * BIP_GMAC_256 = Galois Message Authentication Code 256 bits
- * </pre>
- */
- public static class GroupMgmtCipher {
- private GroupMgmtCipher() { }
-
- /** CMAC-256 = Cipher-based Message Authentication Code */
- public static final int BIP_CMAC_256 = 0;
-
- /** GMAC-128 = Galois Message Authentication Code */
- public static final int BIP_GMAC_128 = 1;
-
- /** GMAC-256 = Galois Message Authentication Code */
- public static final int BIP_GMAC_256 = 2;
-
- private static final String varName = "groupMgmt";
-
- private static final String[] strings = { "BIP_CMAC_256",
- "BIP_GMAC_128", "BIP_GMAC_256"};
- }
-
- /**
- * Recognized suiteB ciphers.
- * <pre>
- * ECDHE_ECDSA
- * ECDHE_RSA
- * </pre>
- * @hide
- */
- public static class SuiteBCipher {
- private SuiteBCipher() { }
-
- /** Diffie-Hellman with Elliptic Curve_ECDSA signature */
- public static final int ECDHE_ECDSA = 0;
-
- /** Diffie-Hellman with_RSA signature */
- public static final int ECDHE_RSA = 1;
-
- private static final String varName = "SuiteB";
-
- private static final String[] strings = { "ECDHE_ECDSA", "ECDHE_RSA" };
- }
-
- /** Possible status of a network configuration. */
- public static class Status {
- private Status() { }
-
- /** this is the network we are currently connected to */
- public static final int CURRENT = 0;
- /** supplicant will not attempt to use this network */
- public static final int DISABLED = 1;
- /** supplicant will consider this network available for association */
- public static final int ENABLED = 2;
-
- public static final String[] strings = { "current", "disabled", "enabled" };
- }
-
- /** Security type for an open network. */
- public static final int SECURITY_TYPE_OPEN = 0;
- /** Security type for a WEP network. */
- public static final int SECURITY_TYPE_WEP = 1;
- /** Security type for a PSK network. */
- public static final int SECURITY_TYPE_PSK = 2;
- /** Security type for an EAP network. */
- public static final int SECURITY_TYPE_EAP = 3;
- /** Security type for an SAE network. */
- public static final int SECURITY_TYPE_SAE = 4;
- /**
- * Security type for a WPA3-Enterprise in 192-bit security network.
- * This is the same as {@link #SECURITY_TYPE_EAP_SUITE_B} and uses the same value.
- */
- public static final int SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT = 5;
- /**
- * Security type for a WPA3-Enterprise in 192-bit security network.
- * @deprecated Use the {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT} constant
- * (which is the same value).
- */
- @Deprecated
- public static final int SECURITY_TYPE_EAP_SUITE_B =
- SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT;
- /** Security type for an OWE network. */
- public static final int SECURITY_TYPE_OWE = 6;
- /** Security type for a WAPI PSK network. */
- public static final int SECURITY_TYPE_WAPI_PSK = 7;
- /** Security type for a WAPI Certificate network. */
- public static final int SECURITY_TYPE_WAPI_CERT = 8;
- /** Security type for a WPA3-Enterprise network. */
- public static final int SECURITY_TYPE_EAP_WPA3_ENTERPRISE = 9;
-
- /**
- * Security types we support.
- * @hide
- */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = { "SECURITY_TYPE_" }, value = {
- SECURITY_TYPE_OPEN,
- SECURITY_TYPE_WEP,
- SECURITY_TYPE_PSK,
- SECURITY_TYPE_EAP,
- SECURITY_TYPE_SAE,
- SECURITY_TYPE_EAP_SUITE_B,
- SECURITY_TYPE_OWE,
- SECURITY_TYPE_WAPI_PSK,
- SECURITY_TYPE_WAPI_CERT,
- SECURITY_TYPE_EAP_WPA3_ENTERPRISE,
- SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT,
- })
- public @interface SecurityType {}
-
- /**
- * Set the various security params to correspond to the provided security type.
- * This is accomplished by setting the various BitSets exposed in WifiConfiguration.
- *
- * @param securityType One of the following security types:
- * {@link #SECURITY_TYPE_OPEN},
- * {@link #SECURITY_TYPE_WEP},
- * {@link #SECURITY_TYPE_PSK},
- * {@link #SECURITY_TYPE_EAP},
- * {@link #SECURITY_TYPE_SAE},
- * {@link #SECURITY_TYPE_EAP_SUITE_B},
- * {@link #SECURITY_TYPE_OWE},
- * {@link #SECURITY_TYPE_WAPI_PSK},
- * {@link #SECURITY_TYPE_WAPI_CERT},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE},
- * {@link #SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT}
- */
- public void setSecurityParams(@SecurityType int securityType) {
- // Clear all the bitsets.
- allowedKeyManagement.clear();
- allowedProtocols.clear();
- allowedAuthAlgorithms.clear();
- allowedPairwiseCiphers.clear();
- allowedGroupCiphers.clear();
- allowedGroupManagementCiphers.clear();
- allowedSuiteBCiphers.clear();
-
- switch (securityType) {
- case SECURITY_TYPE_OPEN:
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
- break;
- case SECURITY_TYPE_WEP:
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
- allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
- allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
- break;
- case SECURITY_TYPE_PSK:
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
- break;
- case SECURITY_TYPE_EAP:
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
- break;
- case SECURITY_TYPE_SAE:
- allowedProtocols.set(WifiConfiguration.Protocol.RSN);
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SAE);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.GCMP_128);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.GCMP_256);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_128);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
- requirePmf = true;
- break;
- // The value of {@link SECURITY_TYPE_EAP_SUITE_B} is the same as
- // {@link SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT}, remove it to avoid
- // duplicate case label errors.
- case SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT:
- allowedProtocols.set(WifiConfiguration.Protocol.RSN);
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.SUITE_B_192);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.GCMP_128);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.GCMP_256);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_128);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
- allowedGroupManagementCiphers.set(WifiConfiguration.GroupMgmtCipher.BIP_GMAC_256);
- // Note: allowedSuiteBCiphers bitset will be set by the service once the
- // certificates are attached to this profile
- requirePmf = true;
- break;
- case SECURITY_TYPE_OWE:
- allowedProtocols.set(WifiConfiguration.Protocol.RSN);
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.OWE);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.GCMP_128);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.GCMP_256);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_128);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
- requirePmf = true;
- break;
- case SECURITY_TYPE_WAPI_PSK:
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WAPI_PSK);
- allowedProtocols.set(WifiConfiguration.Protocol.WAPI);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.SMS4);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.SMS4);
- break;
- case SECURITY_TYPE_WAPI_CERT:
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WAPI_CERT);
- allowedProtocols.set(WifiConfiguration.Protocol.WAPI);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.SMS4);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.SMS4);
- break;
- case SECURITY_TYPE_EAP_WPA3_ENTERPRISE:
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
- allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
- allowedProtocols.set(WifiConfiguration.Protocol.RSN);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
- allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.GCMP_256);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
- allowedGroupCiphers.set(WifiConfiguration.GroupCipher.GCMP_256);
- requirePmf = true;
- break;
- default:
- throw new IllegalArgumentException("unknown security type " + securityType);
- }
- }
-
- /** @hide */
- public static final int UNKNOWN_UID = -1;
-
- /**
- * The ID number that the supplicant uses to identify this
- * network configuration entry. This must be passed as an argument
- * to most calls into the supplicant.
- */
- public int networkId;
-
- // Fixme We need remove this field to use only Quality network selection status only
- /**
- * The current status of this network configuration entry.
- * @see Status
- */
- public int status;
-
- /**
- * The network's SSID. Can either be a UTF-8 string,
- * which must be enclosed in double quotation marks
- * (e.g., {@code "MyNetwork"}), or a string of
- * hex digits, which are not enclosed in quotes
- * (e.g., {@code 01a243f405}).
- */
- public String SSID;
-
- /**
- * When set, this network configuration entry should only be used when
- * associating with the AP having the specified BSSID. The value is
- * a string in the format of an Ethernet MAC address, e.g.,
- * <code>XX:XX:XX:XX:XX:XX</code> where each <code>X</code> is a hex digit.
- */
- public String BSSID;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"AP_BAND_"}, value = {
- AP_BAND_2GHZ,
- AP_BAND_5GHZ,
- AP_BAND_ANY})
- public @interface ApBand {}
-
- /**
- * 2GHz band.
- * @hide
- */
- public static final int AP_BAND_2GHZ = 0;
-
- /**
- * 5GHz band.
- * @hide
- */
- public static final int AP_BAND_5GHZ = 1;
-
- /**
- * 2GHz + 5GHz Dual band.
- * @hide
- */
- public static final int AP_BAND_DUAL = 2;
-
- /**
- * 60GHz band
- * @hide
- */
- public static final int AP_BAND_60GHZ = 3;
-
- /**
- * Device is allowed to choose the optimal band (2Ghz or 5Ghz) based on device capability,
- * operating country code and current radio conditions.
- * @hide
- */
- public static final int AP_BAND_ANY = -1;
-
- /**
- * The band which the AP resides on.
- * One of {@link #AP_BAND_2GHZ}, {@link #AP_BAND_5GHZ}, or {@link #AP_BAND_ANY}.
- * By default, {@link #AP_BAND_2GHZ} is chosen.
- *
- * @hide
- */
- @UnsupportedAppUsage
- @ApBand
- public int apBand = AP_BAND_2GHZ;
-
- /**
- * The channel which AP resides on,currently, US only
- * 2G 1-11
- * 5G 36,40,44,48,149,153,157,161,165
- * 0 - find a random available channel according to the apBand
- * @hide
- */
- @UnsupportedAppUsage
- public int apChannel = 0;
-
- /**
- * Pre-shared key for use with WPA-PSK. Either an ASCII string enclosed in
- * double quotation marks (e.g., {@code "abcdefghij"} for PSK passphrase or
- * a string of 64 hex digits for raw PSK.
- * <p/>
- * When the value of this key is read, the actual key is
- * not returned, just a "*" if the key has a value, or the null
- * string otherwise.
- */
- public String preSharedKey;
-
- /**
- * Four WEP keys. For each of the four values, provide either an ASCII
- * string enclosed in double quotation marks (e.g., {@code "abcdef"}),
- * a string of hex digits (e.g., {@code 0102030405}), or an empty string
- * (e.g., {@code ""}).
- * <p/>
- * When the value of one of these keys is read, the actual key is
- * not returned, just a "*" if the key has a value, or the null
- * string otherwise.
- * @deprecated Due to security and performance limitations, use of WEP networks
- * is discouraged.
- */
- @Deprecated
- public String[] wepKeys;
-
- /** Default WEP key index, ranging from 0 to 3.
- * @deprecated Due to security and performance limitations, use of WEP networks
- * is discouraged. */
- @Deprecated
- public int wepTxKeyIndex;
-
- /**
- * Priority determines the preference given to a network by {@code wpa_supplicant}
- * when choosing an access point with which to associate.
- * @deprecated This field does not exist anymore.
- */
- @Deprecated
- public int priority;
-
- /**
- * This is a network that does not broadcast its SSID, so an
- * SSID-specific probe request must be used for scans.
- */
- public boolean hiddenSSID;
-
- /**
- * True if the network requires Protected Management Frames (PMF), false otherwise.
- * @hide
- */
- @SystemApi
- public boolean requirePmf;
-
- /**
- * @hide
- * This configuration is used in AP to extend the coverage.
- */
- public boolean shareThisAp;
-
- /**
- * Update identifier, for Passpoint network.
- * @hide
- */
- public String updateIdentifier;
-
- /**
- * The set of key management protocols supported by this configuration.
- * See {@link KeyMgmt} for descriptions of the values.
- * Defaults to WPA-PSK WPA-EAP.
- */
- @NonNull
- public BitSet allowedKeyManagement;
- /**
- * The set of security protocols supported by this configuration.
- * See {@link Protocol} for descriptions of the values.
- * Defaults to WPA RSN.
- */
- @NonNull
- public BitSet allowedProtocols;
- /**
- * The set of authentication protocols supported by this configuration.
- * See {@link AuthAlgorithm} for descriptions of the values.
- * Defaults to automatic selection.
- */
- @NonNull
- public BitSet allowedAuthAlgorithms;
- /**
- * The set of pairwise ciphers for WPA supported by this configuration.
- * See {@link PairwiseCipher} for descriptions of the values.
- * Defaults to CCMP TKIP.
- */
- @NonNull
- public BitSet allowedPairwiseCiphers;
- /**
- * The set of group ciphers supported by this configuration.
- * See {@link GroupCipher} for descriptions of the values.
- * Defaults to CCMP TKIP WEP104 WEP40.
- */
- @NonNull
- public BitSet allowedGroupCiphers;
- /**
- * The set of group management ciphers supported by this configuration.
- * See {@link GroupMgmtCipher} for descriptions of the values.
- */
- @NonNull
- public BitSet allowedGroupManagementCiphers;
- /**
- * The set of SuiteB ciphers supported by this configuration.
- * To be used for WPA3-Enterprise mode. Set automatically by the framework based on the
- * certificate type that is used in this configuration.
- */
- @NonNull
- public BitSet allowedSuiteBCiphers;
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the EAP.
- */
- public WifiEnterpriseConfig enterpriseConfig;
-
- /**
- * Fully qualified domain name of a Passpoint configuration
- */
- public String FQDN;
-
- /**
- * Name of Passpoint credential provider
- */
- public String providerFriendlyName;
-
- /**
- * Flag indicating if this network is provided by a home Passpoint provider or a roaming
- * Passpoint provider. This flag will be {@code true} if this network is provided by
- * a home Passpoint provider and {@code false} if is provided by a roaming Passpoint provider
- * or is a non-Passpoint network.
- */
- public boolean isHomeProviderNetwork;
-
- /**
- * Roaming Consortium Id list for Passpoint credential; identifies a set of networks where
- * Passpoint credential will be considered valid
- */
- public long[] roamingConsortiumIds;
-
- /**
- * True if this network configuration is visible to and usable by other users on the
- * same device, false otherwise.
- *
- * @hide
- */
- @SystemApi
- public boolean shared;
-
- /**
- * @hide
- */
- @NonNull
- @UnsupportedAppUsage
- private IpConfiguration mIpConfiguration;
-
- /**
- * @hide
- * dhcp server MAC address if known
- */
- public String dhcpServer;
-
- /**
- * @hide
- * default Gateway MAC address if known
- */
- @UnsupportedAppUsage
- public String defaultGwMacAddress;
-
- /**
- * @hide
- * last time we connected, this configuration had validated internet access
- */
- @UnsupportedAppUsage
- public boolean validatedInternetAccess;
-
- /**
- * @hide
- * The number of beacon intervals between Delivery Traffic Indication Maps (DTIM)
- * This value is populated from scan results that contain Beacon Frames, which are infrequent.
- * The value is not guaranteed to be set or current (Although it SHOULDNT change once set)
- * Valid values are from 1 - 255. Initialized here as 0, use this to check if set.
- */
- public int dtimInterval = 0;
-
- /**
- * Flag indicating if this configuration represents a legacy Passpoint configuration
- * (Release N or older). This is used for migrating Passpoint configuration from N to O.
- * This will no longer be needed after O.
- * @hide
- */
- public boolean isLegacyPasspointConfig = false;
- /**
- * @hide
- * Uid of app creating the configuration
- */
- @SystemApi
- public int creatorUid;
-
- /**
- * @hide
- * Uid of last app issuing a connection related command
- */
- @UnsupportedAppUsage
- public int lastConnectUid;
-
- /**
- * @hide
- * Uid of last app modifying the configuration
- */
- @SystemApi
- public int lastUpdateUid;
-
- /**
- * @hide
- * Universal name for app creating the configuration
- * see {@link PackageManager#getNameForUid(int)}
- */
- @SystemApi
- public String creatorName;
-
- /**
- * @hide
- * Universal name for app updating the configuration
- * see {@link PackageManager#getNameForUid(int)}
- */
- @SystemApi
- public String lastUpdateName;
-
- /**
- * The carrier ID identifies the operator who provides this network configuration.
- * see {@link TelephonyManager#getSimCarrierId()}
- * @hide
- */
- @SystemApi
- public int carrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
-
- /**
- * The subscription ID identifies the SIM card for which this network configuration is valid.
- * See {@link SubscriptionInfo#getSubscriptionId()}
- * @hide
- */
- @SystemApi
- public int subscriptionId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
-
- /**
- * @hide
- * Auto-join is allowed by user for this network.
- * Default true.
- */
- @SystemApi
- public boolean allowAutojoin = true;
-
- /** @hide **/
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- public static int INVALID_RSSI = -127;
-
- /**
- * @hide
- * Number of reports indicating no Internet Access
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public int numNoInternetAccessReports;
-
- /**
- * @hide
- * The WiFi configuration is considered to have no internet access for purpose of autojoining
- * if there has been a report of it having no internet access, and, it never have had
- * internet access in the past.
- */
- @SystemApi
- public boolean hasNoInternetAccess() {
- return numNoInternetAccessReports > 0 && !validatedInternetAccess;
- }
-
- /**
- * The WiFi configuration is expected not to have Internet access (e.g., a wireless printer, a
- * Chromecast hotspot, etc.). This will be set if the user explicitly confirms a connection to
- * this configuration and selects "don't ask again".
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public boolean noInternetAccessExpected;
-
- /**
- * The WiFi configuration is expected not to have Internet access (e.g., a wireless printer, a
- * Chromecast hotspot, etc.). This will be set if the user explicitly confirms a connection to
- * this configuration and selects "don't ask again".
- * @hide
- */
- @SystemApi
- public boolean isNoInternetAccessExpected() {
- return noInternetAccessExpected;
- }
-
- /**
- * This Wifi configuration is expected for OSU(Online Sign Up) of Passpoint Release 2.
- * @hide
- */
- public boolean osu;
-
- /**
- * @hide
- * Last time the system was connected to this configuration.
- */
- public long lastConnected;
-
- /**
- * @hide
- * Last time the system was disconnected to this configuration.
- */
- public long lastDisconnected;
-
- /**
- * Set if the configuration was self added by the framework
- * This boolean is cleared if we get a connect/save/ update or
- * any wifiManager command that indicate the user interacted with the configuration
- * since we will now consider that the configuration belong to him.
- * @deprecated only kept for @UnsupportedAppUsage
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public boolean selfAdded;
-
- /**
- * Peer WifiConfiguration this WifiConfiguration was added for
- * @hide
- */
- public String peerWifiConfiguration;
-
- /**
- * @hide
- * Indicate that a WifiConfiguration is temporary and should not be saved
- * nor considered by AutoJoin.
- */
- public boolean ephemeral;
-
- /**
- * @hide
- * Indicate that a WifiConfiguration is temporary and should not be saved
- * nor considered by AutoJoin.
- */
- @SystemApi
- public boolean isEphemeral() {
- return ephemeral;
- }
-
- /**
- * Indicate whether the network is trusted or not. Networks are considered trusted
- * if the user explicitly allowed this network connection.
- * This bit can be used by suggestion network, see
- * {@link WifiNetworkSuggestion.Builder#setUntrusted(boolean)}
- * @hide
- */
- public boolean trusted;
-
- /**
- * Indicate whether the network is oem paid or not. Networks are considered oem paid
- * if the corresponding connection is only available to system apps.
- *
- * This bit can only be used by suggestion network, see
- * {@link WifiNetworkSuggestion.Builder#setOemPaid(boolean)}
- * @hide
- */
- public boolean oemPaid;
-
-
- /**
- * Indicate whether the network is oem private or not. Networks are considered oem private
- * if the corresponding connection is only available to system apps.
- *
- * This bit can only be used by suggestion network, see
- * {@link WifiNetworkSuggestion.Builder#setOemPrivate(boolean)}
- * @hide
- */
- public boolean oemPrivate;
-
- /**
- * Indicate whether or not the network is a carrier merged network.
- * This bit can only be used by suggestion network, see
- * {@link WifiNetworkSuggestion.Builder#setCarrierMerged(boolean)}
- * @hide
- */
- @SystemApi
- public boolean carrierMerged;
-
- /**
- * True if this Wifi configuration is created from a {@link WifiNetworkSuggestion},
- * false otherwise.
- *
- * @hide
- */
- @SystemApi
- public boolean fromWifiNetworkSuggestion;
-
- /**
- * True if this Wifi configuration is created from a {@link WifiNetworkSpecifier},
- * false otherwise.
- *
- * @hide
- */
- @SystemApi
- public boolean fromWifiNetworkSpecifier;
-
- /**
- * True if the creator of this configuration has expressed that it
- * should be considered metered, false otherwise.
- *
- * @see #isMetered(WifiConfiguration, WifiInfo)
- *
- * @hide
- */
- @SystemApi
- public boolean meteredHint;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"METERED_OVERRIDE_"}, value = {
- METERED_OVERRIDE_NONE,
- METERED_OVERRIDE_METERED,
- METERED_OVERRIDE_NOT_METERED})
- public @interface MeteredOverride {}
-
- /**
- * No metered override.
- * @hide
- */
- @SystemApi
- public static final int METERED_OVERRIDE_NONE = 0;
- /**
- * Override network to be metered.
- * @hide
- */
- @SystemApi
- public static final int METERED_OVERRIDE_METERED = 1;
- /**
- * Override network to be unmetered.
- * @hide
- */
- @SystemApi
- public static final int METERED_OVERRIDE_NOT_METERED = 2;
-
- /**
- * Indicates if the end user has expressed an explicit opinion about the
- * meteredness of this network, such as through the Settings app.
- * This value is one of {@link #METERED_OVERRIDE_NONE}, {@link #METERED_OVERRIDE_METERED},
- * or {@link #METERED_OVERRIDE_NOT_METERED}.
- * <p>
- * This should always override any values from {@link #meteredHint} or
- * {@link WifiInfo#getMeteredHint()}.
- *
- * By default this field is set to {@link #METERED_OVERRIDE_NONE}.
- *
- * @see #isMetered(WifiConfiguration, WifiInfo)
- * @hide
- */
- @SystemApi
- @MeteredOverride
- public int meteredOverride = METERED_OVERRIDE_NONE;
-
- /**
- * Blend together all the various opinions to decide if the given network
- * should be considered metered or not.
- *
- * @hide
- */
- @SystemApi
- public static boolean isMetered(@Nullable WifiConfiguration config, @Nullable WifiInfo info) {
- boolean metered = false;
- if (info != null && info.getMeteredHint()) {
- metered = true;
- }
- if (config != null && config.meteredHint) {
- metered = true;
- }
- if (config != null
- && config.meteredOverride == WifiConfiguration.METERED_OVERRIDE_METERED) {
- metered = true;
- }
- if (config != null
- && config.meteredOverride == WifiConfiguration.METERED_OVERRIDE_NOT_METERED) {
- metered = false;
- }
- return metered;
- }
-
- /**
- * @hide
- * Returns true if this WiFi config is for an open network.
- */
- public boolean isOpenNetwork() {
- final int cardinality = allowedKeyManagement.cardinality();
- final boolean hasNoKeyMgmt = cardinality == 0
- || (cardinality == 1 && (allowedKeyManagement.get(KeyMgmt.NONE)
- || allowedKeyManagement.get(KeyMgmt.OWE)));
-
- boolean hasNoWepKeys = true;
- if (wepKeys != null) {
- for (int i = 0; i < wepKeys.length; i++) {
- if (wepKeys[i] != null) {
- hasNoWepKeys = false;
- break;
- }
- }
- }
-
- return hasNoKeyMgmt && hasNoWepKeys;
- }
-
- /**
- * @hide
- * Setting this value will force scan results associated with this configuration to
- * be included in the bucket of networks that are externally scored.
- * If not set, associated scan results will be treated as legacy saved networks and
- * will take precedence over networks in the scored category.
- */
- @SystemApi
- public boolean useExternalScores;
-
- /**
- * @hide
- * Number of time the scorer overrode a the priority based choice, when comparing two
- * WifiConfigurations, note that since comparing WifiConfiguration happens very often
- * potentially at every scan, this number might become very large, even on an idle
- * system.
- */
- @SystemApi
- public int numScorerOverride;
-
- /**
- * @hide
- * Number of time the scorer overrode a the priority based choice, and the comparison
- * triggered a network switch
- */
- @SystemApi
- public int numScorerOverrideAndSwitchedNetwork;
-
- /**
- * @hide
- * Number of time we associated to this configuration.
- */
- @SystemApi
- public int numAssociation;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"RANDOMIZATION_"}, value = {
- RANDOMIZATION_NONE,
- RANDOMIZATION_PERSISTENT,
- RANDOMIZATION_ENHANCED,
- RANDOMIZATION_AUTO})
- public @interface MacRandomizationSetting {}
-
- /**
- * Use factory MAC when connecting to this network
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_NONE = 0;
- /**
- * Generate a randomized MAC once and reuse it for all connections to this network
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_PERSISTENT = 1;
-
- /**
- * Use a randomly generated MAC address for connections to this network.
- * This option does not persist the randomized MAC address.
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_ENHANCED = 2;
-
- /**
- * Let the wifi framework automatically decide the MAC randomization strategy.
- * @hide
- */
- @SystemApi
- public static final int RANDOMIZATION_AUTO = 3;
-
- /**
- * Level of MAC randomization for this network.
- * One of {@link #RANDOMIZATION_NONE}, {@link #RANDOMIZATION_AUTO},
- * {@link #RANDOMIZATION_PERSISTENT} or {@link #RANDOMIZATION_ENHANCED}.
- * By default this field is set to {@link #RANDOMIZATION_AUTO}.
- * @hide
- */
- @SystemApi
- @MacRandomizationSetting
- public int macRandomizationSetting = RANDOMIZATION_AUTO;
-
- /**
- * @hide
- * Randomized MAC address to use with this particular network
- */
- @NonNull
- private MacAddress mRandomizedMacAddress;
-
- /**
- * @hide
- * The wall clock time of when |mRandomizedMacAddress| should be re-randomized in enhanced
- * MAC randomization mode.
- */
- public long randomizedMacExpirationTimeMs = 0;
-
- /**
- * The wall clock time of when |mRandomizedMacAddress| is last modified.
- * @hide
- */
- public long randomizedMacLastModifiedTimeMs = 0;
-
- /**
- * @hide
- * Checks if the given MAC address can be used for Connected Mac Randomization
- * by verifying that it is non-null, unicast, locally assigned, and not default mac.
- * @param mac MacAddress to check
- * @return true if mac is good to use
- */
- public static boolean isValidMacAddressForRandomization(MacAddress mac) {
- return mac != null && !MacAddressUtils.isMulticastAddress(mac) && mac.isLocallyAssigned()
- && !MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS).equals(mac);
- }
-
- /**
- * Returns MAC address set to be the local randomized MAC address.
- * Depending on user preference, the device may or may not use the returned MAC address for
- * connections to this network.
- * <p>
- * Information is restricted to Device Owner, Profile Owner, and Carrier apps
- * (which will only obtain addresses for configurations which they create). Other callers
- * will receive a default "02:00:00:00:00:00" MAC address.
- */
- public @NonNull MacAddress getRandomizedMacAddress() {
- return mRandomizedMacAddress;
- }
-
- /**
- * @hide
- * @param mac MacAddress to change into
- */
- public void setRandomizedMacAddress(@NonNull MacAddress mac) {
- if (mac == null) {
- Log.e(TAG, "setRandomizedMacAddress received null MacAddress.");
- return;
- }
- mRandomizedMacAddress = mac;
- }
- /**
- * @hide
- * DPP Connector (signedConnector as string).
- */
- public String dppConnector;
-
- /**
- * @hide
- * DPP net Access Key (own private key).
- */
- public String dppNetAccessKey;
-
- /**
- * @hide
- * DPP net Access Key expiry in UNIX time stamp. 0 indicates no expiration.
- */
- public int dppNetAccessKeyExpiry;
-
- /**
- * @hide
- * DPP C-Sign key (Configurator public key).
- */
- public String dppCsign;
-
- /** @hide
- * Boost given to RSSI on a home network for the purpose of calculating the score
- * This adds stickiness to home networks, as defined by:
- * - less than 4 known BSSIDs
- * - PSK only
- * - TODO: add a test to verify that all BSSIDs are behind same gateway
- ***/
- public static final int HOME_NETWORK_RSSI_BOOST = 5;
-
- /**
- * This class is used to contain all the information and API used for quality network selection.
- * @hide
- */
- @SystemApi
- public static class NetworkSelectionStatus {
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = "NETWORK_SELECTION_",
- value = {
- NETWORK_SELECTION_ENABLED,
- NETWORK_SELECTION_TEMPORARY_DISABLED,
- NETWORK_SELECTION_PERMANENTLY_DISABLED})
- public @interface NetworkEnabledStatus {}
- /**
- * This network will be considered as a potential candidate to connect to during network
- * selection.
- */
- public static final int NETWORK_SELECTION_ENABLED = 0;
- /**
- * This network was temporary disabled. May be re-enabled after a time out.
- */
- public static final int NETWORK_SELECTION_TEMPORARY_DISABLED = 1;
- /**
- * This network was permanently disabled.
- */
- public static final int NETWORK_SELECTION_PERMANENTLY_DISABLED = 2;
- /**
- * Maximum Network selection status
- * @hide
- */
- public static final int NETWORK_SELECTION_STATUS_MAX = 3;
-
- /**
- * Quality network selection status String (for debug purpose). Use Quality network
- * selection status value as index to extec the corresponding debug string
- * @hide
- */
- public static final String[] QUALITY_NETWORK_SELECTION_STATUS = {
- "NETWORK_SELECTION_ENABLED",
- "NETWORK_SELECTION_TEMPORARY_DISABLED",
- "NETWORK_SELECTION_PERMANENTLY_DISABLED"};
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = "DISABLED_", value = {
- DISABLED_NONE,
- DISABLED_ASSOCIATION_REJECTION,
- DISABLED_AUTHENTICATION_FAILURE,
- DISABLED_DHCP_FAILURE,
- DISABLED_NO_INTERNET_TEMPORARY,
- DISABLED_AUTHENTICATION_NO_CREDENTIALS,
- DISABLED_NO_INTERNET_PERMANENT,
- DISABLED_BY_WIFI_MANAGER,
- DISABLED_BY_WRONG_PASSWORD,
- DISABLED_AUTHENTICATION_NO_SUBSCRIPTION})
- public @interface NetworkSelectionDisableReason {}
-
- // Quality Network disabled reasons
- /** Default value. Means not disabled. */
- public static final int DISABLED_NONE = 0;
- /**
- * The starting index for network selection disabled reasons.
- * @hide
- */
- public static final int NETWORK_SELECTION_DISABLED_STARTING_INDEX = 1;
- /** This network is temporarily disabled because of multiple association rejections. */
- public static final int DISABLED_ASSOCIATION_REJECTION = 1;
- /** This network is temporarily disabled because of multiple authentication failure. */
- public static final int DISABLED_AUTHENTICATION_FAILURE = 2;
- /** This network is temporarily disabled because of multiple DHCP failure. */
- public static final int DISABLED_DHCP_FAILURE = 3;
- /** This network is temporarily disabled because it has no Internet access. */
- public static final int DISABLED_NO_INTERNET_TEMPORARY = 4;
- /** This network is permanently disabled due to absence of user credentials */
- public static final int DISABLED_AUTHENTICATION_NO_CREDENTIALS = 5;
- /**
- * This network is permanently disabled because it has no Internet access and the user does
- * not want to stay connected.
- */
- public static final int DISABLED_NO_INTERNET_PERMANENT = 6;
- /** This network is permanently disabled due to WifiManager disabling it explicitly. */
- public static final int DISABLED_BY_WIFI_MANAGER = 7;
- /** This network is permanently disabled due to wrong password. */
- public static final int DISABLED_BY_WRONG_PASSWORD = 8;
- /** This network is permanently disabled because service is not subscribed. */
- public static final int DISABLED_AUTHENTICATION_NO_SUBSCRIPTION = 9;
- /**
- * All other disable reasons should be strictly less than this value.
- * @hide
- */
- public static final int NETWORK_SELECTION_DISABLED_MAX = 10;
-
- /**
- * Get an integer that is equal to the maximum integer value of all the
- * DISABLED_* reasons
- * e.g. {@link #DISABLED_NONE}, {@link #DISABLED_ASSOCIATION_REJECTION}, etc.
- *
- * All DISABLED_* constants will be contiguous in the range
- * 0, 1, 2, 3, ..., getMaxNetworkSelectionDisableReasons()
- *
- * <br />
- * For example, this can be used to iterate through all the network selection
- * disable reasons like so:
- * <pre>{@code
- * for (int reason = 0; reason <= getMaxNetworkSelectionDisableReasons(); reason++) {
- * ...
- * }
- * }</pre>
- */
- public static int getMaxNetworkSelectionDisableReason() {
- return NETWORK_SELECTION_DISABLED_MAX - 1;
- }
-
- /**
- * Contains info about disable reasons.
- * @hide
- */
- public static final class DisableReasonInfo {
- /**
- * String representation for the disable reason.
- * Note that these strings are persisted in
- * {@link
- * com.android.server.wifi.util.XmlUtil.NetworkSelectionStatusXmlUtil#writeToXml},
- * so do not change the string values to maintain backwards compatibility.
- */
- public final String mReasonStr;
- /**
- * Network Selection disable reason threshold, used to debounce network failures before
- * we disable them.
- */
- public final int mDisableThreshold;
- /**
- * Network Selection disable timeout for the error. After the timeout milliseconds,
- * enable the network again.
- * If this is set to Integer.MAX_VALUE, the network will be permanently disabled until
- * the next time the user manually connects to it.
- */
- public final int mDisableTimeoutMillis;
-
- /**
- * Constructor
- * @param reasonStr string representation of the error
- * @param disableThreshold number of failures before we disable the network
- * @param disableTimeoutMillis the timeout, in milliseconds, before we re-enable the
- * network after disabling it
- */
- public DisableReasonInfo(String reasonStr, int disableThreshold,
- int disableTimeoutMillis) {
- mReasonStr = reasonStr;
- mDisableThreshold = disableThreshold;
- mDisableTimeoutMillis = disableTimeoutMillis;
- }
- }
-
- /**
- * Quality network selection disable reason infos.
- * @hide
- */
- public static final SparseArray<DisableReasonInfo> DISABLE_REASON_INFOS =
- buildDisableReasonInfos();
-
- private static SparseArray<DisableReasonInfo> buildDisableReasonInfos() {
- SparseArray<DisableReasonInfo> reasons = new SparseArray<>();
-
- reasons.append(DISABLED_NONE,
- new DisableReasonInfo(
- // Note that these strings are persisted in
- // XmlUtil.NetworkSelectionStatusXmlUtil#writeToXml,
- // so do not change the string values to maintain backwards
- // compatibility.
- "NETWORK_SELECTION_ENABLE",
- -1,
- Integer.MAX_VALUE));
-
- reasons.append(DISABLED_ASSOCIATION_REJECTION,
- new DisableReasonInfo(
- // Note that there is a space at the end of this string. Cannot fix
- // since this string is persisted.
- "NETWORK_SELECTION_DISABLED_ASSOCIATION_REJECTION ",
- 5,
- 5 * 60 * 1000));
-
- reasons.append(DISABLED_AUTHENTICATION_FAILURE,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_AUTHENTICATION_FAILURE",
- 5,
- 5 * 60 * 1000));
-
- reasons.append(DISABLED_DHCP_FAILURE,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_DHCP_FAILURE",
- 5,
- 5 * 60 * 1000));
-
- reasons.append(DISABLED_NO_INTERNET_TEMPORARY,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_NO_INTERNET_TEMPORARY",
- 1,
- 10 * 60 * 1000));
-
- reasons.append(DISABLED_AUTHENTICATION_NO_CREDENTIALS,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_AUTHENTICATION_NO_CREDENTIALS",
- 1,
- Integer.MAX_VALUE));
-
- reasons.append(DISABLED_NO_INTERNET_PERMANENT,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_NO_INTERNET_PERMANENT",
- 1,
- Integer.MAX_VALUE));
-
- reasons.append(DISABLED_BY_WIFI_MANAGER,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_BY_WIFI_MANAGER",
- 1,
- Integer.MAX_VALUE));
-
- reasons.append(DISABLED_BY_WRONG_PASSWORD,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_BY_WRONG_PASSWORD",
- 1,
- Integer.MAX_VALUE));
-
- reasons.append(DISABLED_AUTHENTICATION_NO_SUBSCRIPTION,
- new DisableReasonInfo(
- "NETWORK_SELECTION_DISABLED_AUTHENTICATION_NO_SUBSCRIPTION",
- 1,
- Integer.MAX_VALUE));
-
- return reasons;
- }
-
- /**
- * Get the {@link NetworkSelectionDisableReason} int code by its string value.
- * @return the NetworkSelectionDisableReason int code corresponding to the reason string,
- * or -1 if the reason string is unrecognized.
- * @hide
- */
- @NetworkSelectionDisableReason
- public static int getDisableReasonByString(@NonNull String reasonString) {
- for (int i = 0; i < DISABLE_REASON_INFOS.size(); i++) {
- int key = DISABLE_REASON_INFOS.keyAt(i);
- DisableReasonInfo value = DISABLE_REASON_INFOS.valueAt(i);
- if (value != null && TextUtils.equals(reasonString, value.mReasonStr)) {
- return key;
- }
- }
- Log.e(TAG, "Unrecognized network disable reason: " + reasonString);
- return -1;
- }
-
- /**
- * Invalid time stamp for network selection disable
- * @hide
- */
- public static final long INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP = -1L;
-
- /**
- * This constant indicates the current configuration has connect choice set
- */
- private static final int CONNECT_CHOICE_EXISTS = 1;
-
- /**
- * This constant indicates the current configuration does not have connect choice set
- */
- private static final int CONNECT_CHOICE_NOT_EXISTS = -1;
-
- // fields for QualityNetwork Selection
- /**
- * Network selection status, should be in one of three status: enable, temporaily disabled
- * or permanently disabled
- */
- @NetworkEnabledStatus
- private int mStatus;
-
- /**
- * Reason for disable this network
- */
- @NetworkSelectionDisableReason
- private int mNetworkSelectionDisableReason;
-
- /**
- * Last time we temporarily disabled the configuration
- */
- private long mTemporarilyDisabledTimestamp = INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP;
-
- /**
- * counter for each Network selection disable reason
- */
- private int[] mNetworkSeclectionDisableCounter = new int[NETWORK_SELECTION_DISABLED_MAX];
-
- /**
- * Connect Choice over this configuration
- *
- * When current wifi configuration is visible to the user but user explicitly choose to
- * connect to another network X, the another networks X's configure key will be stored here.
- * We will consider user has a preference of X over this network. And in the future,
- * network selection will always give X a higher preference over this configuration.
- * configKey is : "SSID"-WEP-WPA_PSK-WPA_EAP
- */
- private String mConnectChoice;
-
- /**
- * Used to cache the temporary candidate during the network selection procedure. It will be
- * kept updating once a new scan result has a higher score than current one
- */
- private ScanResult mCandidate;
-
- /**
- * Used to cache the score of the current temporary candidate during the network
- * selection procedure.
- */
- private int mCandidateScore;
-
- /**
- * Indicate whether this network is visible in latest Qualified Network Selection. This
- * means there is scan result found related to this Configuration and meet the minimum
- * requirement. The saved network need not join latest Qualified Network Selection. For
- * example, it is disabled. True means network is visible in latest Qualified Network
- * Selection and false means network is invisible
- */
- private boolean mSeenInLastQualifiedNetworkSelection;
-
- /**
- * Boolean indicating if we have ever successfully connected to this network.
- *
- * This value will be set to true upon a successful connection.
- * This value will be set to false if a previous value was not stored in the config or if
- * the credentials are updated (ex. a password change).
- */
- private boolean mHasEverConnected;
-
- /**
- * Boolean indicating if captive portal has never been detected on this network.
- *
- * This should be true by default, for newly created WifiConfigurations until a captive
- * portal is detected.
- */
- private boolean mHasNeverDetectedCaptivePortal = true;
-
- /**
- * set whether this network is visible in latest Qualified Network Selection
- * @param seen value set to candidate
- * @hide
- */
- public void setSeenInLastQualifiedNetworkSelection(boolean seen) {
- mSeenInLastQualifiedNetworkSelection = seen;
- }
-
- /**
- * get whether this network is visible in latest Qualified Network Selection
- * @return returns true -- network is visible in latest Qualified Network Selection
- * false -- network is invisible in latest Qualified Network Selection
- * @hide
- */
- public boolean getSeenInLastQualifiedNetworkSelection() {
- return mSeenInLastQualifiedNetworkSelection;
- }
- /**
- * set the temporary candidate of current network selection procedure
- * @param scanCandidate {@link ScanResult} the candidate set to mCandidate
- * @hide
- */
- public void setCandidate(ScanResult scanCandidate) {
- mCandidate = scanCandidate;
- }
-
- /**
- * get the temporary candidate of current network selection procedure
- * @return returns {@link ScanResult} temporary candidate of current network selection
- * procedure
- * @hide
- */
- public ScanResult getCandidate() {
- return mCandidate;
- }
-
- /**
- * set the score of the temporary candidate of current network selection procedure
- * @param score value set to mCandidateScore
- * @hide
- */
- public void setCandidateScore(int score) {
- mCandidateScore = score;
- }
-
- /**
- * get the score of the temporary candidate of current network selection procedure
- * @return returns score of the temporary candidate of current network selection procedure
- * @hide
- */
- public int getCandidateScore() {
- return mCandidateScore;
- }
-
- /**
- * get user preferred choice over this configuration
- * @return returns configKey of user preferred choice over this configuration
- * @hide
- */
- public String getConnectChoice() {
- return mConnectChoice;
- }
-
- /**
- * set user preferred choice over this configuration
- * @param newConnectChoice, the configKey of user preferred choice over this configuration
- * @hide
- */
- public void setConnectChoice(String newConnectChoice) {
- mConnectChoice = newConnectChoice;
- }
-
- /** Get the current Quality network selection status as a String (for debugging). */
- @NonNull
- public String getNetworkStatusString() {
- return QUALITY_NETWORK_SELECTION_STATUS[mStatus];
- }
-
- /** @hide */
- public void setHasEverConnected(boolean value) {
- mHasEverConnected = value;
- }
-
- /** True if the device has ever connected to this network, false otherwise. */
- public boolean hasEverConnected() {
- return mHasEverConnected;
- }
-
- /**
- * Set whether a captive portal has never been detected on this network.
- * @hide
- */
- public void setHasNeverDetectedCaptivePortal(boolean value) {
- mHasNeverDetectedCaptivePortal = value;
- }
-
- /** @hide */
- public boolean hasNeverDetectedCaptivePortal() {
- return mHasNeverDetectedCaptivePortal;
- }
-
- /** @hide */
- public NetworkSelectionStatus() {
- // previously stored configs will not have this parameter, so we default to false.
- mHasEverConnected = false;
- }
-
- /**
- * NetworkSelectionStatus exports an immutable public API.
- * However, test code has a need to construct a NetworkSelectionStatus in a specific state.
- * (Note that mocking using Mockito does not work if the object needs to be parceled and
- * unparceled.)
- * Export a @SystemApi Builder to allow tests to construct a NetworkSelectionStatus object
- * in the desired state, without sacrificing NetworkSelectionStatus's immutability.
- */
- @VisibleForTesting
- public static final class Builder {
- private final NetworkSelectionStatus mNetworkSelectionStatus =
- new NetworkSelectionStatus();
-
- /**
- * Set the current network selection status.
- * One of:
- * {@link #NETWORK_SELECTION_ENABLED},
- * {@link #NETWORK_SELECTION_TEMPORARY_DISABLED},
- * {@link #NETWORK_SELECTION_PERMANENTLY_DISABLED}
- * @see NetworkSelectionStatus#getNetworkSelectionStatus()
- */
- @NonNull
- public Builder setNetworkSelectionStatus(@NetworkEnabledStatus int status) {
- mNetworkSelectionStatus.setNetworkSelectionStatus(status);
- return this;
- }
-
- /**
- *
- * Set the current network's disable reason.
- * One of the {@link #DISABLED_NONE} or DISABLED_* constants.
- * e.g. {@link #DISABLED_ASSOCIATION_REJECTION}.
- * @see NetworkSelectionStatus#getNetworkSelectionDisableReason()
- */
- @NonNull
- public Builder setNetworkSelectionDisableReason(
- @NetworkSelectionDisableReason int reason) {
- mNetworkSelectionStatus.setNetworkSelectionDisableReason(reason);
- return this;
- }
-
- /**
- * Build a NetworkSelectionStatus object.
- */
- @NonNull
- public NetworkSelectionStatus build() {
- NetworkSelectionStatus status = new NetworkSelectionStatus();
- status.copy(mNetworkSelectionStatus);
- return status;
- }
- }
-
- /**
- * Get the network disable reason string for a reason code (for debugging).
- * @param reason specific error reason. One of the {@link #DISABLED_NONE} or
- * DISABLED_* constants e.g. {@link #DISABLED_ASSOCIATION_REJECTION}.
- * @return network disable reason string, or null if the reason is invalid.
- */
- @Nullable
- public static String getNetworkSelectionDisableReasonString(
- @NetworkSelectionDisableReason int reason) {
- DisableReasonInfo info = DISABLE_REASON_INFOS.get(reason);
- if (info == null) {
- return null;
- } else {
- return info.mReasonStr;
- }
- }
- /**
- * get current network disable reason
- * @return current network disable reason in String (for debug purpose)
- * @hide
- */
- public String getNetworkSelectionDisableReasonString() {
- return getNetworkSelectionDisableReasonString(mNetworkSelectionDisableReason);
- }
-
- /**
- * Get the current network network selection status.
- * One of:
- * {@link #NETWORK_SELECTION_ENABLED},
- * {@link #NETWORK_SELECTION_TEMPORARY_DISABLED},
- * {@link #NETWORK_SELECTION_PERMANENTLY_DISABLED}
- */
- @NetworkEnabledStatus
- public int getNetworkSelectionStatus() {
- return mStatus;
- }
-
- /**
- * True if the current network is enabled to join network selection, false otherwise.
- * @hide
- */
- public boolean isNetworkEnabled() {
- return mStatus == NETWORK_SELECTION_ENABLED;
- }
-
- /**
- * @return whether current network is temporary disabled
- * @hide
- */
- public boolean isNetworkTemporaryDisabled() {
- return mStatus == NETWORK_SELECTION_TEMPORARY_DISABLED;
- }
-
- /**
- * True if the current network is permanently disabled, false otherwise.
- * @hide
- */
- public boolean isNetworkPermanentlyDisabled() {
- return mStatus == NETWORK_SELECTION_PERMANENTLY_DISABLED;
- }
-
- /**
- * set current network selection status
- * @param status network selection status to set
- * @hide
- */
- public void setNetworkSelectionStatus(int status) {
- if (status >= 0 && status < NETWORK_SELECTION_STATUS_MAX) {
- mStatus = status;
- }
- }
-
- /**
- * Returns the current network's disable reason.
- * One of the {@link #DISABLED_NONE} or DISABLED_* constants
- * e.g. {@link #DISABLED_ASSOCIATION_REJECTION}.
- */
- @NetworkSelectionDisableReason
- public int getNetworkSelectionDisableReason() {
- return mNetworkSelectionDisableReason;
- }
-
- /**
- * set Network disable reason
- * @param reason Network disable reason
- * @hide
- */
- public void setNetworkSelectionDisableReason(@NetworkSelectionDisableReason int reason) {
- if (reason >= 0 && reason < NETWORK_SELECTION_DISABLED_MAX) {
- mNetworkSelectionDisableReason = reason;
- } else {
- throw new IllegalArgumentException("Illegal reason value: " + reason);
- }
- }
-
- /**
- * @param timeStamp Set when current network is disabled in millisecond since January 1,
- * 1970 00:00:00.0 UTC
- * @hide
- */
- public void setDisableTime(long timeStamp) {
- mTemporarilyDisabledTimestamp = timeStamp;
- }
-
- /**
- * Returns when the current network was disabled, in milliseconds since January 1,
- * 1970 00:00:00.0 UTC.
- */
- public long getDisableTime() {
- return mTemporarilyDisabledTimestamp;
- }
-
- /**
- * Get the disable counter of a specific reason.
- * @param reason specific failure reason. One of the {@link #DISABLED_NONE} or
- * DISABLED_* constants e.g. {@link #DISABLED_ASSOCIATION_REJECTION}.
- * @exception IllegalArgumentException for invalid reason
- * @return counter number for specific error reason.
- */
- public int getDisableReasonCounter(@NetworkSelectionDisableReason int reason) {
- if (reason >= DISABLED_NONE && reason < NETWORK_SELECTION_DISABLED_MAX) {
- return mNetworkSeclectionDisableCounter[reason];
- } else {
- throw new IllegalArgumentException("Illegal reason value: " + reason);
- }
- }
-
- /**
- * set the counter of a specific failure reason
- * @param reason reason for disable error
- * @param value the counter value for this specific reason
- * @exception throw IllegalArgumentException for illegal input
- * @hide
- */
- public void setDisableReasonCounter(int reason, int value) {
- if (reason >= DISABLED_NONE && reason < NETWORK_SELECTION_DISABLED_MAX) {
- mNetworkSeclectionDisableCounter[reason] = value;
- } else {
- throw new IllegalArgumentException("Illegal reason value: " + reason);
- }
- }
-
- /**
- * increment the counter of a specific failure reason
- * @param reason a specific failure reason
- * @exception throw IllegalArgumentException for illegal input
- * @hide
- */
- public void incrementDisableReasonCounter(int reason) {
- if (reason >= DISABLED_NONE && reason < NETWORK_SELECTION_DISABLED_MAX) {
- mNetworkSeclectionDisableCounter[reason]++;
- } else {
- throw new IllegalArgumentException("Illegal reason value: " + reason);
- }
- }
-
- /**
- * clear the counter of a specific failure reason
- * @param reason a specific failure reason
- * @exception throw IllegalArgumentException for illegal input
- * @hide
- */
- public void clearDisableReasonCounter(int reason) {
- if (reason >= DISABLED_NONE && reason < NETWORK_SELECTION_DISABLED_MAX) {
- mNetworkSeclectionDisableCounter[reason] = DISABLED_NONE;
- } else {
- throw new IllegalArgumentException("Illegal reason value: " + reason);
- }
- }
-
- /**
- * clear all the failure reason counters
- * @hide
- */
- public void clearDisableReasonCounter() {
- Arrays.fill(mNetworkSeclectionDisableCounter, DISABLED_NONE);
- }
-
- /**
- * BSSID for connection to this network (through network selection procedure)
- */
- private String mNetworkSelectionBSSID;
-
- /**
- * get current network Selection BSSID
- * @return current network Selection BSSID
- * @hide
- */
- public String getNetworkSelectionBSSID() {
- return mNetworkSelectionBSSID;
- }
-
- /**
- * set network Selection BSSID
- * @param bssid The target BSSID for assocaition
- * @hide
- */
- public void setNetworkSelectionBSSID(String bssid) {
- mNetworkSelectionBSSID = bssid;
- }
-
- /** @hide */
- public void copy(NetworkSelectionStatus source) {
- mStatus = source.mStatus;
- mNetworkSelectionDisableReason = source.mNetworkSelectionDisableReason;
- for (int index = DISABLED_NONE; index < NETWORK_SELECTION_DISABLED_MAX;
- index++) {
- mNetworkSeclectionDisableCounter[index] =
- source.mNetworkSeclectionDisableCounter[index];
- }
- mTemporarilyDisabledTimestamp = source.mTemporarilyDisabledTimestamp;
- mNetworkSelectionBSSID = source.mNetworkSelectionBSSID;
- setSeenInLastQualifiedNetworkSelection(source.getSeenInLastQualifiedNetworkSelection());
- setCandidate(source.getCandidate());
- setCandidateScore(source.getCandidateScore());
- setConnectChoice(source.getConnectChoice());
- setHasEverConnected(source.hasEverConnected());
- setHasNeverDetectedCaptivePortal(source.hasNeverDetectedCaptivePortal());
- }
-
- /** @hide */
- public void writeToParcel(Parcel dest) {
- dest.writeInt(getNetworkSelectionStatus());
- dest.writeInt(getNetworkSelectionDisableReason());
- for (int index = DISABLED_NONE; index < NETWORK_SELECTION_DISABLED_MAX;
- index++) {
- dest.writeInt(getDisableReasonCounter(index));
- }
- dest.writeLong(getDisableTime());
- dest.writeString(getNetworkSelectionBSSID());
- if (getConnectChoice() != null) {
- dest.writeInt(CONNECT_CHOICE_EXISTS);
- dest.writeString(getConnectChoice());
- } else {
- dest.writeInt(CONNECT_CHOICE_NOT_EXISTS);
- }
- dest.writeInt(hasEverConnected() ? 1 : 0);
- dest.writeInt(hasNeverDetectedCaptivePortal() ? 1 : 0);
- }
-
- /** @hide */
- public void readFromParcel(Parcel in) {
- setNetworkSelectionStatus(in.readInt());
- setNetworkSelectionDisableReason(in.readInt());
- for (int index = DISABLED_NONE; index < NETWORK_SELECTION_DISABLED_MAX;
- index++) {
- setDisableReasonCounter(index, in.readInt());
- }
- setDisableTime(in.readLong());
- setNetworkSelectionBSSID(in.readString());
- if (in.readInt() == CONNECT_CHOICE_EXISTS) {
- setConnectChoice(in.readString());
- } else {
- setConnectChoice(null);
- }
- setHasEverConnected(in.readInt() != 0);
- setHasNeverDetectedCaptivePortal(in.readInt() != 0);
- }
- }
-
- /**
- * @hide
- * network selection related member
- */
- private NetworkSelectionStatus mNetworkSelectionStatus = new NetworkSelectionStatus();
-
- /**
- * This class is intended to store extra failure reason information for the most recent
- * connection attempt, so that it may be surfaced to the settings UI
- * @hide
- */
- // TODO(b/148626966): called by SUW via reflection, remove once SUW is updated
- public static class RecentFailure {
-
- private RecentFailure() {}
-
- /**
- * Association Rejection Status code (NONE for success/non-association-rejection-fail)
- */
- @RecentFailureReason
- private int mAssociationStatus = RECENT_FAILURE_NONE;
- private long mLastUpdateTimeSinceBootMillis;
-
- /**
- * @param status the association status code for the recent failure
- */
- public void setAssociationStatus(@RecentFailureReason int status,
- long updateTimeSinceBootMs) {
- mAssociationStatus = status;
- mLastUpdateTimeSinceBootMillis = updateTimeSinceBootMs;
- }
- /**
- * Sets the RecentFailure to NONE
- */
- public void clear() {
- mAssociationStatus = RECENT_FAILURE_NONE;
- mLastUpdateTimeSinceBootMillis = 0;
- }
- /**
- * Get the recent failure code. One of {@link #RECENT_FAILURE_NONE},
- * {@link #RECENT_FAILURE_AP_UNABLE_TO_HANDLE_NEW_STA},
- * {@link #RECENT_FAILURE_MBO_OCE_DISCONNECT},
- * {@link #RECENT_FAILURE_REFUSED_TEMPORARILY},
- * {@link #RECENT_FAILURE_POOR_CHANNEL_CONDITIONS}.
- * {@link #RECENT_FAILURE_DISCONNECTION_AP_BUSY}
- */
- @RecentFailureReason
- public int getAssociationStatus() {
- return mAssociationStatus;
- }
-
- /**
- * Get the timestamp the failure status is last updated, in milliseconds since boot.
- */
- public long getLastUpdateTimeSinceBootMillis() {
- return mLastUpdateTimeSinceBootMillis;
- }
- }
-
- /**
- * RecentFailure member
- * @hide
- */
- // TODO(b/148626966): called by SUW via reflection, once SUW is updated, make private and
- // rename to mRecentFailure
- @NonNull
- public final RecentFailure recentFailure = new RecentFailure();
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = "RECENT_FAILURE_", value = {
- RECENT_FAILURE_NONE,
- RECENT_FAILURE_AP_UNABLE_TO_HANDLE_NEW_STA,
- RECENT_FAILURE_MBO_OCE_DISCONNECT,
- RECENT_FAILURE_REFUSED_TEMPORARILY,
- RECENT_FAILURE_POOR_CHANNEL_CONDITIONS,
- RECENT_FAILURE_DISCONNECTION_AP_BUSY
- })
- public @interface RecentFailureReason {}
-
- /**
- * No recent failure, or no specific reason given for the recent connection failure
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_NONE = 0;
- /**
- * Connection to this network recently failed due to Association Rejection Status 17
- * (AP is full)
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_AP_UNABLE_TO_HANDLE_NEW_STA = 17;
-
- /**
- * This network recently disconnected as a result of MBO/OCE.
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_MBO_OCE_DISCONNECT = 1001;
-
- /**
- * Failed to connect because the association is rejected by the AP.
- * IEEE 802.11 association status code 30.
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_REFUSED_TEMPORARILY = 1002;
-
- /**
- * Failed to connect because of excess frame loss and/or poor channel conditions.
- * IEEE 802.11 association status code 34.
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_POOR_CHANNEL_CONDITIONS = 1003;
-
- /**
- * Disconnected by the AP because the AP can't handle all the associated stations.
- * IEEE 802.11 disconnection reason code 5.
- * @hide
- */
- @SystemApi
- public static final int RECENT_FAILURE_DISCONNECTION_AP_BUSY = 1004;
-
- /**
- * Get the failure reason for the most recent connection attempt, or
- * {@link #RECENT_FAILURE_NONE} if there was no failure.
- *
- * Failure reasons include:
- * {@link #RECENT_FAILURE_AP_UNABLE_TO_HANDLE_NEW_STA}
- * {@link #RECENT_FAILURE_MBO_OCE_DISCONNECT}
- * {@link #RECENT_FAILURE_REFUSED_TEMPORARILY}
- * {@link #RECENT_FAILURE_POOR_CHANNEL_CONDITIONS}
- * {@link #RECENT_FAILURE_DISCONNECTION_AP_BUSY}
- * @hide
- */
- @RecentFailureReason
- @SystemApi
- public int getRecentFailureReason() {
- return recentFailure.getAssociationStatus();
- }
-
- /**
- * Get the network selection status.
- * @hide
- */
- @NonNull
- @SystemApi
- public NetworkSelectionStatus getNetworkSelectionStatus() {
- return mNetworkSelectionStatus;
- }
-
- /**
- * Set the network selection status.
- * @hide
- */
- @SystemApi
- public void setNetworkSelectionStatus(@NonNull NetworkSelectionStatus status) {
- mNetworkSelectionStatus = status;
- }
-
- /**
- * @hide
- * Linked Configurations: represent the set of Wificonfigurations that are equivalent
- * regarding roaming and auto-joining.
- * The linked configuration may or may not have same SSID, and may or may not have same
- * credentials.
- * For instance, linked configurations will have same defaultGwMacAddress or same dhcp server.
- */
- public HashMap<String, Integer> linkedConfigurations;
-
- public WifiConfiguration() {
- networkId = INVALID_NETWORK_ID;
- SSID = null;
- BSSID = null;
- FQDN = null;
- roamingConsortiumIds = new long[0];
- priority = 0;
- hiddenSSID = false;
- shareThisAp = false;
- allowedKeyManagement = new BitSet();
- allowedProtocols = new BitSet();
- allowedAuthAlgorithms = new BitSet();
- allowedPairwiseCiphers = new BitSet();
- allowedGroupCiphers = new BitSet();
- allowedGroupManagementCiphers = new BitSet();
- allowedSuiteBCiphers = new BitSet();
- wepKeys = new String[4];
- for (int i = 0; i < wepKeys.length; i++) {
- wepKeys[i] = null;
- }
- enterpriseConfig = new WifiEnterpriseConfig();
- ephemeral = false;
- osu = false;
- trusted = true; // Networks are considered trusted by default.
- oemPaid = false;
- oemPrivate = false;
- carrierMerged = false;
- fromWifiNetworkSuggestion = false;
- fromWifiNetworkSpecifier = false;
- meteredHint = false;
- meteredOverride = METERED_OVERRIDE_NONE;
- useExternalScores = false;
- validatedInternetAccess = false;
- mIpConfiguration = new IpConfiguration();
- lastUpdateUid = -1;
- creatorUid = -1;
- shared = true;
- dtimInterval = 0;
- mRandomizedMacAddress = MacAddress.fromString(WifiInfo.DEFAULT_MAC_ADDRESS);
- dppConnector = null;
- dppNetAccessKey = null;
- dppNetAccessKeyExpiry = -1;
- dppCsign = null;
- }
-
- /**
- * Identify if this configuration represents a Passpoint network
- */
- public boolean isPasspoint() {
- return !TextUtils.isEmpty(FQDN)
- && !TextUtils.isEmpty(providerFriendlyName)
- && enterpriseConfig != null
- && enterpriseConfig.getEapMethod() != WifiEnterpriseConfig.Eap.NONE
- && !TextUtils.isEmpty(mPasspointUniqueId);
- }
-
- /**
- * Helper function, identify if a configuration is linked
- * @hide
- */
- public boolean isLinked(WifiConfiguration config) {
- if (config != null) {
- if (config.linkedConfigurations != null && linkedConfigurations != null) {
- if (config.linkedConfigurations.get(getKey()) != null
- && linkedConfigurations.get(config.getKey()) != null) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Helper function, idenfity if a configuration should be treated as an enterprise network
- * @hide
- */
- @UnsupportedAppUsage
- public boolean isEnterprise() {
- return (allowedKeyManagement.get(KeyMgmt.WPA_EAP)
- || allowedKeyManagement.get(KeyMgmt.IEEE8021X)
- || allowedKeyManagement.get(KeyMgmt.SUITE_B_192)
- || allowedKeyManagement.get(KeyMgmt.WAPI_CERT))
- && enterpriseConfig != null
- && enterpriseConfig.getEapMethod() != WifiEnterpriseConfig.Eap.NONE;
- }
-
- private static String logTimeOfDay(long millis) {
- Calendar c = Calendar.getInstance();
- if (millis >= 0) {
- c.setTimeInMillis(millis);
- return String.format("%tm-%td %tH:%tM:%tS.%tL", c, c, c, c, c, c);
- } else {
- return Long.toString(millis);
- }
- }
-
- @Override
- public String toString() {
- StringBuilder sbuf = new StringBuilder();
- if (this.status == WifiConfiguration.Status.CURRENT) {
- sbuf.append("* ");
- } else if (this.status == WifiConfiguration.Status.DISABLED) {
- sbuf.append("- DSBLE ");
- }
- sbuf.append("ID: ").append(this.networkId).append(" SSID: ").append(this.SSID).
- append(" PROVIDER-NAME: ").append(this.providerFriendlyName).
- append(" BSSID: ").append(this.BSSID).append(" FQDN: ").append(this.FQDN)
- .append(" HOME-PROVIDER-NETWORK: ").append(this.isHomeProviderNetwork)
- .append(" PRIO: ").append(this.priority)
- .append(" HIDDEN: ").append(this.hiddenSSID)
- .append(" PMF: ").append(this.requirePmf)
- .append("CarrierId: ").append(this.carrierId)
- .append('\n');
-
-
- sbuf.append(" NetworkSelectionStatus ")
- .append(mNetworkSelectionStatus.getNetworkStatusString())
- .append("\n");
- if (mNetworkSelectionStatus.getNetworkSelectionDisableReason() > 0) {
- sbuf.append(" mNetworkSelectionDisableReason ")
- .append(mNetworkSelectionStatus.getNetworkSelectionDisableReasonString())
- .append("\n");
-
- for (int index = NetworkSelectionStatus.DISABLED_NONE;
- index < NetworkSelectionStatus.NETWORK_SELECTION_DISABLED_MAX; index++) {
- if (mNetworkSelectionStatus.getDisableReasonCounter(index) != 0) {
- sbuf.append(
- NetworkSelectionStatus.getNetworkSelectionDisableReasonString(index))
- .append(" counter:")
- .append(mNetworkSelectionStatus.getDisableReasonCounter(index))
- .append("\n");
- }
- }
- }
- if (mNetworkSelectionStatus.getConnectChoice() != null) {
- sbuf.append(" connect choice: ").append(mNetworkSelectionStatus.getConnectChoice());
- }
- sbuf.append(" hasEverConnected: ")
- .append(mNetworkSelectionStatus.hasEverConnected()).append("\n");
- sbuf.append(" hasNeverDetectedCaptivePortal: ")
- .append(mNetworkSelectionStatus.hasNeverDetectedCaptivePortal()).append("\n");
-
- if (this.numAssociation > 0) {
- sbuf.append(" numAssociation ").append(this.numAssociation).append("\n");
- }
- if (this.numNoInternetAccessReports > 0) {
- sbuf.append(" numNoInternetAccessReports ");
- sbuf.append(this.numNoInternetAccessReports).append("\n");
- }
- if (this.validatedInternetAccess) sbuf.append(" validatedInternetAccess");
- if (this.ephemeral) sbuf.append(" ephemeral");
- if (this.osu) sbuf.append(" osu");
- if (this.trusted) sbuf.append(" trusted");
- if (this.oemPaid) sbuf.append(" oemPaid");
- if (this.oemPrivate) sbuf.append(" oemPrivate");
- if (this.carrierMerged) sbuf.append(" carrierMerged");
- if (this.fromWifiNetworkSuggestion) sbuf.append(" fromWifiNetworkSuggestion");
- if (this.fromWifiNetworkSpecifier) sbuf.append(" fromWifiNetworkSpecifier");
- if (this.meteredHint) sbuf.append(" meteredHint");
- if (this.useExternalScores) sbuf.append(" useExternalScores");
- if (this.validatedInternetAccess || this.ephemeral || this.trusted || this.oemPaid
- || this.oemPrivate || this.carrierMerged || this.fromWifiNetworkSuggestion
- || this.fromWifiNetworkSpecifier || this.meteredHint || this.useExternalScores) {
- sbuf.append("\n");
- }
- if (this.meteredOverride != METERED_OVERRIDE_NONE) {
- sbuf.append(" meteredOverride ").append(meteredOverride).append("\n");
- }
- sbuf.append(" macRandomizationSetting: ").append(macRandomizationSetting).append("\n");
- sbuf.append(" mRandomizedMacAddress: ").append(mRandomizedMacAddress).append("\n");
- sbuf.append(" randomizedMacExpirationTimeMs: ")
- .append(randomizedMacExpirationTimeMs == 0 ? "<none>"
- : logTimeOfDay(randomizedMacExpirationTimeMs)).append("\n");
- sbuf.append(" randomizedMacLastModifiedTimeMs: ")
- .append(randomizedMacLastModifiedTimeMs == 0 ? "<none>"
- : logTimeOfDay(randomizedMacLastModifiedTimeMs)).append("\n");
- sbuf.append(" KeyMgmt:");
- for (int k = 0; k < this.allowedKeyManagement.size(); k++) {
- if (this.allowedKeyManagement.get(k)) {
- sbuf.append(" ");
- if (k < KeyMgmt.strings.length) {
- sbuf.append(KeyMgmt.strings[k]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append(" Protocols:");
- for (int p = 0; p < this.allowedProtocols.size(); p++) {
- if (this.allowedProtocols.get(p)) {
- sbuf.append(" ");
- if (p < Protocol.strings.length) {
- sbuf.append(Protocol.strings[p]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" AuthAlgorithms:");
- for (int a = 0; a < this.allowedAuthAlgorithms.size(); a++) {
- if (this.allowedAuthAlgorithms.get(a)) {
- sbuf.append(" ");
- if (a < AuthAlgorithm.strings.length) {
- sbuf.append(AuthAlgorithm.strings[a]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" PairwiseCiphers:");
- for (int pc = 0; pc < this.allowedPairwiseCiphers.size(); pc++) {
- if (this.allowedPairwiseCiphers.get(pc)) {
- sbuf.append(" ");
- if (pc < PairwiseCipher.strings.length) {
- sbuf.append(PairwiseCipher.strings[pc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" GroupCiphers:");
- for (int gc = 0; gc < this.allowedGroupCiphers.size(); gc++) {
- if (this.allowedGroupCiphers.get(gc)) {
- sbuf.append(" ");
- if (gc < GroupCipher.strings.length) {
- sbuf.append(GroupCipher.strings[gc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" GroupMgmtCiphers:");
- for (int gmc = 0; gmc < this.allowedGroupManagementCiphers.size(); gmc++) {
- if (this.allowedGroupManagementCiphers.get(gmc)) {
- sbuf.append(" ");
- if (gmc < GroupMgmtCipher.strings.length) {
- sbuf.append(GroupMgmtCipher.strings[gmc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n');
- sbuf.append(" SuiteBCiphers:");
- for (int sbc = 0; sbc < this.allowedSuiteBCiphers.size(); sbc++) {
- if (this.allowedSuiteBCiphers.get(sbc)) {
- sbuf.append(" ");
- if (sbc < SuiteBCipher.strings.length) {
- sbuf.append(SuiteBCipher.strings[sbc]);
- } else {
- sbuf.append("??");
- }
- }
- }
- sbuf.append('\n').append(" PSK/SAE: ");
- if (this.preSharedKey != null) {
- sbuf.append('*');
- }
-
- sbuf.append("\nEnterprise config:\n");
- sbuf.append(enterpriseConfig);
-
- sbuf.append("\nDPP config:\n");
- if (this.dppConnector != null) {
- sbuf.append(" Dpp Connector: *\n");
- }
- if (this.dppNetAccessKey != null) {
- sbuf.append(" Dpp NetAccessKey: *\n");
- }
- if (this.dppCsign != null) {
- sbuf.append(" Dpp Csign: *\n");
- }
-
- sbuf.append("IP config:\n");
- sbuf.append(mIpConfiguration.toString());
-
- if (mNetworkSelectionStatus.getNetworkSelectionBSSID() != null) {
- sbuf.append(" networkSelectionBSSID="
- + mNetworkSelectionStatus.getNetworkSelectionBSSID());
- }
- long now_ms = SystemClock.elapsedRealtime();
- if (mNetworkSelectionStatus.getDisableTime() != NetworkSelectionStatus
- .INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP) {
- sbuf.append('\n');
- long diff = now_ms - mNetworkSelectionStatus.getDisableTime();
- if (diff <= 0) {
- sbuf.append(" blackListed since <incorrect>");
- } else {
- sbuf.append(" blackListed: ").append(Long.toString(diff / 1000)).append("sec ");
- }
- }
- if (creatorUid != 0) sbuf.append(" cuid=" + creatorUid);
- if (creatorName != null) sbuf.append(" cname=" + creatorName);
- if (lastUpdateUid != 0) sbuf.append(" luid=" + lastUpdateUid);
- if (lastUpdateName != null) sbuf.append(" lname=" + lastUpdateName);
- if (updateIdentifier != null) sbuf.append(" updateIdentifier=" + updateIdentifier);
- sbuf.append(" lcuid=" + lastConnectUid);
- sbuf.append(" allowAutojoin=" + allowAutojoin);
- sbuf.append(" noInternetAccessExpected=" + noInternetAccessExpected);
- sbuf.append(" mostRecentlyConnected=" + isMostRecentlyConnected);
-
- sbuf.append(" ");
-
- if (this.lastConnected != 0) {
- sbuf.append('\n');
- sbuf.append("lastConnected: ").append(logTimeOfDay(this.lastConnected));
- sbuf.append(" ");
- }
- sbuf.append('\n');
- if (this.linkedConfigurations != null) {
- for (String key : this.linkedConfigurations.keySet()) {
- sbuf.append(" linked: ").append(key);
- sbuf.append('\n');
- }
- }
- sbuf.append("recentFailure: ").append("Association Rejection code: ")
- .append(recentFailure.getAssociationStatus()).append(", last update time: ")
- .append(recentFailure.getLastUpdateTimeSinceBootMillis()).append("\n");
-
- sbuf.append("ShareThisAp: ").append(this.shareThisAp);
- sbuf.append('\n');
- return sbuf.toString();
- }
-
- /**
- * Get the SSID in a human-readable format, with all additional formatting removed
- * e.g. quotation marks around the SSID, "P" prefix
- * @hide
- */
- @NonNull
- @SystemApi
- public String getPrintableSsid() {
- if (SSID == null) return "";
- final int length = SSID.length();
- if (length > 2 && (SSID.charAt(0) == '"') && SSID.charAt(length - 1) == '"') {
- return SSID.substring(1, length - 1);
- }
-
- /* The ascii-encoded string format is P"<ascii-encoded-string>"
- * The decoding is implemented in the supplicant for a newly configured
- * network.
- */
- if (length > 3 && (SSID.charAt(0) == 'P') && (SSID.charAt(1) == '"') &&
- (SSID.charAt(length-1) == '"')) {
- WifiSsid wifiSsid = WifiSsid.createFromAsciiEncoded(
- SSID.substring(2, length - 1));
- return wifiSsid.toString();
- }
- return SSID;
- }
-
- /**
- * Get an identifier for associating credentials with this config
- * @param current configuration contains values for additional fields
- * that are not part of this configuration. Used
- * when a config with some fields is passed by an application.
- * @throws IllegalStateException if config is invalid for key id generation
- * @hide
- */
- public String getKeyIdForCredentials(WifiConfiguration current) {
- String keyMgmt = "";
-
- try {
- // Get current config details for fields that are not initialized
- if (TextUtils.isEmpty(SSID)) SSID = current.SSID;
- if (allowedKeyManagement.cardinality() == 0) {
- allowedKeyManagement = current.allowedKeyManagement;
- }
- if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)) {
- keyMgmt += KeyMgmt.strings[KeyMgmt.WPA_EAP];
- }
- if (allowedKeyManagement.get(KeyMgmt.OSEN)) {
- keyMgmt += KeyMgmt.strings[KeyMgmt.OSEN];
- }
- if (allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
- keyMgmt += KeyMgmt.strings[KeyMgmt.IEEE8021X];
- }
- if (allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
- keyMgmt += KeyMgmt.strings[KeyMgmt.SUITE_B_192];
- }
- if (allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
- keyMgmt += KeyMgmt.strings[KeyMgmt.WAPI_CERT];
- }
-
- if (TextUtils.isEmpty(keyMgmt)) {
- throw new IllegalStateException("Not an EAP network");
- }
- String keyId = trimStringForKeyId(SSID) + "_" + keyMgmt + "_"
- + trimStringForKeyId(enterpriseConfig.getKeyId(current != null
- ? current.enterpriseConfig : null));
-
- if (!fromWifiNetworkSuggestion) {
- return keyId;
- }
- return keyId + "_" + trimStringForKeyId(BSSID) + "_" + trimStringForKeyId(creatorName);
- } catch (NullPointerException e) {
- throw new IllegalStateException("Invalid config details");
- }
- }
-
- private String trimStringForKeyId(String string) {
- if (string == null) {
- return "";
- }
- // Remove quotes and spaces
- return string.replace("\"", "").replace(" ", "");
- }
-
- private static BitSet readBitSet(Parcel src) {
- int cardinality = src.readInt();
-
- BitSet set = new BitSet();
- for (int i = 0; i < cardinality; i++) {
- set.set(src.readInt());
- }
-
- return set;
- }
-
- private static void writeBitSet(Parcel dest, BitSet set) {
- int nextSetBit = -1;
-
- dest.writeInt(set.cardinality());
-
- while ((nextSetBit = set.nextSetBit(nextSetBit + 1)) != -1) {
- dest.writeInt(nextSetBit);
- }
- }
-
- /**
- * Get the authentication type of the network.
- * @return One of the {@link KeyMgmt} constants. e.g. {@link KeyMgmt#WPA2_PSK}.
- * @hide
- */
- @SystemApi
- @KeyMgmt.KeyMgmtScheme
- public int getAuthType() {
- if (allowedKeyManagement.cardinality() > 1) {
- if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)) {
- if (allowedKeyManagement.cardinality() == 2
- && allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
- return KeyMgmt.WPA_EAP;
- }
- if (allowedKeyManagement.cardinality() == 3
- && allowedKeyManagement.get(KeyMgmt.IEEE8021X)
- && allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
- return KeyMgmt.SUITE_B_192;
- }
- }
- throw new IllegalStateException("Invalid auth type set: " + allowedKeyManagement);
- }
- if (allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
- return KeyMgmt.WPA_PSK;
- } else if (allowedKeyManagement.get(KeyMgmt.WPA2_PSK)) {
- return KeyMgmt.WPA2_PSK;
- } else if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)) {
- return KeyMgmt.WPA_EAP;
- } else if (allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
- return KeyMgmt.IEEE8021X;
- } else if (allowedKeyManagement.get(KeyMgmt.DPP)) {
- return KeyMgmt.DPP;
- } else if (allowedKeyManagement.get(KeyMgmt.SAE)) {
- return KeyMgmt.SAE;
- } else if (allowedKeyManagement.get(KeyMgmt.OWE)) {
- return KeyMgmt.OWE;
- } else if (allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
- return KeyMgmt.SUITE_B_192;
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_PSK)) {
- return KeyMgmt.WAPI_PSK;
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
- return KeyMgmt.WAPI_CERT;
- }
- return KeyMgmt.NONE;
- }
-
- /**
- * Return a String that can be used to uniquely identify this WifiConfiguration.
- * <br />
- * Note: Do not persist this value! This value is not guaranteed to remain backwards compatible.
- */
- @NonNull
- public String getKey() {
- // Passpoint ephemeral networks have their unique identifier set. Return it as is to be
- // able to match internally.
- if (mPasspointUniqueId != null) {
- return mPasspointUniqueId;
- }
-
- String key = getSsidAndSecurityTypeString();
- if (!shared) {
- key += "-" + UserHandle.getUserHandleForUid(creatorUid).getIdentifier();
- }
-
- return key;
- }
-
- /**
- * Get a unique key which represent this Wi-Fi network. If two profiles are for
- * the same Wi-Fi network, but from different provider, they would have the same key.
- * @hide
- */
- public String getNetworkKey() {
- // Passpoint ephemeral networks have their unique identifier set. Return it as is to be
- // able to match internally.
- if (mPasspointUniqueId != null) {
- return mPasspointUniqueId;
- }
-
- String key = SSID + getDefaultSecurityType();
- if (!shared) {
- key += "-" + UserHandle.getUserHandleForUid(creatorUid).getIdentifier();
- }
-
- return key;
- }
-
- /** @hide
- * return the SSID + security type in String format.
- */
- public String getSsidAndSecurityTypeString() {
- String key;
- if (allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.WPA_PSK];
- } else if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)
- || allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.WPA_EAP];
- } else if (wepTxKeyIndex >= 0 && wepTxKeyIndex < wepKeys.length
- && wepKeys[wepTxKeyIndex] != null) {
- key = SSID + "WEP";
- } else if (allowedKeyManagement.get(KeyMgmt.OWE)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.OWE];
- } else if (allowedKeyManagement.get(KeyMgmt.SAE)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.SAE];
- } else if (allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.SUITE_B_192];
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_PSK)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.WAPI_PSK];
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.WAPI_CERT];
- } else if (allowedKeyManagement.get(KeyMgmt.OSEN)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.OSEN];
- } else if (allowedKeyManagement.get(KeyMgmt.DPP)) {
- key = SSID + KeyMgmt.strings[KeyMgmt.DPP];
- } else {
- key = SSID + KeyMgmt.strings[KeyMgmt.NONE];
- }
- return key;
- }
-
- /**
- * Get the IpConfiguration object associated with this WifiConfiguration.
- * @hide
- */
- @NonNull
- @SystemApi
- public IpConfiguration getIpConfiguration() {
- return new IpConfiguration(mIpConfiguration);
- }
-
- /**
- * Set the {@link IpConfiguration} for this network.
- * @param ipConfiguration the {@link IpConfiguration} to set, or null to use the default
- * constructor {@link IpConfiguration#IpConfiguration()}.
- * @hide
- */
- @SystemApi
- public void setIpConfiguration(@Nullable IpConfiguration ipConfiguration) {
- if (ipConfiguration == null) ipConfiguration = new IpConfiguration();
- mIpConfiguration = ipConfiguration;
- }
-
- /**
- * Get the {@link StaticIpConfiguration} for this network.
- * @return the {@link StaticIpConfiguration}, or null if unset.
- * @hide
- */
- @Nullable
- @UnsupportedAppUsage
- public StaticIpConfiguration getStaticIpConfiguration() {
- return mIpConfiguration.getStaticIpConfiguration();
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setStaticIpConfiguration(StaticIpConfiguration staticIpConfiguration) {
- mIpConfiguration.setStaticIpConfiguration(staticIpConfiguration);
- }
-
- /**
- * Get the {@link IpConfiguration.IpAssignment} for this network.
- * @hide
- */
- @NonNull
- @UnsupportedAppUsage
- public IpConfiguration.IpAssignment getIpAssignment() {
- return mIpConfiguration.getIpAssignment();
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setIpAssignment(IpConfiguration.IpAssignment ipAssignment) {
- mIpConfiguration.setIpAssignment(ipAssignment);
- }
-
- /**
- * Get the {@link IpConfiguration.ProxySettings} for this network.
- * @hide
- */
- @NonNull
- @UnsupportedAppUsage
- public IpConfiguration.ProxySettings getProxySettings() {
- return mIpConfiguration.getProxySettings();
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setProxySettings(IpConfiguration.ProxySettings proxySettings) {
- mIpConfiguration.setProxySettings(proxySettings);
- }
-
- /**
- * Returns the HTTP proxy used by this object.
- * @return a {@link ProxyInfo httpProxy} representing the proxy specified by this
- * WifiConfiguration, or {@code null} if no proxy is specified.
- */
- public ProxyInfo getHttpProxy() {
- if (mIpConfiguration.getProxySettings() == IpConfiguration.ProxySettings.NONE) {
- return null;
- }
- return new ProxyInfo(mIpConfiguration.getHttpProxy());
- }
-
- /**
- * Set the {@link ProxyInfo} for this WifiConfiguration. This method should only be used by a
- * device owner or profile owner. When other apps attempt to save a {@link WifiConfiguration}
- * with modified proxy settings, the methods {@link WifiManager#addNetwork} and
- * {@link WifiManager#updateNetwork} fail and return {@code -1}.
- *
- * @param httpProxy {@link ProxyInfo} representing the httpProxy to be used by this
- * WifiConfiguration. Setting this to {@code null} will explicitly set no
- * proxy, removing any proxy that was previously set.
- * @exception IllegalArgumentException for invalid httpProxy
- */
- public void setHttpProxy(ProxyInfo httpProxy) {
- if (httpProxy == null) {
- mIpConfiguration.setProxySettings(IpConfiguration.ProxySettings.NONE);
- mIpConfiguration.setHttpProxy(null);
- return;
- }
- ProxyInfo httpProxyCopy;
- ProxySettings proxySettingCopy;
- if (!Uri.EMPTY.equals(httpProxy.getPacFileUrl())) {
- proxySettingCopy = IpConfiguration.ProxySettings.PAC;
- // Construct a new PAC URL Proxy
- httpProxyCopy = ProxyInfo.buildPacProxy(httpProxy.getPacFileUrl(), httpProxy.getPort());
- } else {
- proxySettingCopy = IpConfiguration.ProxySettings.STATIC;
- // Construct a new HTTP Proxy
- httpProxyCopy = ProxyInfo.buildDirectProxy(httpProxy.getHost(), httpProxy.getPort(),
- Arrays.asList(httpProxy.getExclusionList()));
- }
- if (!httpProxyCopy.isValid()) {
- throw new IllegalArgumentException("Invalid ProxyInfo: " + httpProxyCopy.toString());
- }
- mIpConfiguration.setProxySettings(proxySettingCopy);
- mIpConfiguration.setHttpProxy(httpProxyCopy);
- }
-
- /**
- * Set the {@link ProxySettings} and {@link ProxyInfo} for this network.
- * @hide
- */
- @UnsupportedAppUsage
- public void setProxy(@NonNull ProxySettings settings, @NonNull ProxyInfo proxy) {
- mIpConfiguration.setProxySettings(settings);
- mIpConfiguration.setHttpProxy(proxy);
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** @hide */
- public void setPasspointManagementObjectTree(String passpointManagementObjectTree) {
- mPasspointManagementObjectTree = passpointManagementObjectTree;
- }
-
- /** @hide */
- public String getMoTree() {
- return mPasspointManagementObjectTree;
- }
-
- /** Copy constructor */
- public WifiConfiguration(@NonNull WifiConfiguration source) {
- if (source != null) {
- networkId = source.networkId;
- status = source.status;
- SSID = source.SSID;
- BSSID = source.BSSID;
- FQDN = source.FQDN;
- shareThisAp = source.shareThisAp;
- roamingConsortiumIds = source.roamingConsortiumIds.clone();
- providerFriendlyName = source.providerFriendlyName;
- isHomeProviderNetwork = source.isHomeProviderNetwork;
- preSharedKey = source.preSharedKey;
-
- mNetworkSelectionStatus.copy(source.getNetworkSelectionStatus());
- apBand = source.apBand;
- apChannel = source.apChannel;
-
- wepKeys = new String[4];
- for (int i = 0; i < wepKeys.length; i++) {
- wepKeys[i] = source.wepKeys[i];
- }
-
- wepTxKeyIndex = source.wepTxKeyIndex;
- priority = source.priority;
- hiddenSSID = source.hiddenSSID;
- allowedKeyManagement = (BitSet) source.allowedKeyManagement.clone();
- allowedProtocols = (BitSet) source.allowedProtocols.clone();
- allowedAuthAlgorithms = (BitSet) source.allowedAuthAlgorithms.clone();
- allowedPairwiseCiphers = (BitSet) source.allowedPairwiseCiphers.clone();
- allowedGroupCiphers = (BitSet) source.allowedGroupCiphers.clone();
- allowedGroupManagementCiphers = (BitSet) source.allowedGroupManagementCiphers.clone();
- allowedSuiteBCiphers = (BitSet) source.allowedSuiteBCiphers.clone();
- enterpriseConfig = new WifiEnterpriseConfig(source.enterpriseConfig);
-
- defaultGwMacAddress = source.defaultGwMacAddress;
-
- mIpConfiguration = new IpConfiguration(source.mIpConfiguration);
-
- if ((source.linkedConfigurations != null)
- && (source.linkedConfigurations.size() > 0)) {
- linkedConfigurations = new HashMap<String, Integer>();
- linkedConfigurations.putAll(source.linkedConfigurations);
- }
- validatedInternetAccess = source.validatedInternetAccess;
- isLegacyPasspointConfig = source.isLegacyPasspointConfig;
- ephemeral = source.ephemeral;
- osu = source.osu;
- trusted = source.trusted;
- oemPaid = source.oemPaid;
- oemPrivate = source.oemPrivate;
- carrierMerged = source.carrierMerged;
- fromWifiNetworkSuggestion = source.fromWifiNetworkSuggestion;
- fromWifiNetworkSpecifier = source.fromWifiNetworkSpecifier;
- meteredHint = source.meteredHint;
- meteredOverride = source.meteredOverride;
- useExternalScores = source.useExternalScores;
-
- lastConnectUid = source.lastConnectUid;
- lastUpdateUid = source.lastUpdateUid;
- creatorUid = source.creatorUid;
- creatorName = source.creatorName;
- lastUpdateName = source.lastUpdateName;
- peerWifiConfiguration = source.peerWifiConfiguration;
-
- lastConnected = source.lastConnected;
- lastDisconnected = source.lastDisconnected;
- numScorerOverride = source.numScorerOverride;
- numScorerOverrideAndSwitchedNetwork = source.numScorerOverrideAndSwitchedNetwork;
- numAssociation = source.numAssociation;
- allowAutojoin = source.allowAutojoin;
- numNoInternetAccessReports = source.numNoInternetAccessReports;
- noInternetAccessExpected = source.noInternetAccessExpected;
- shared = source.shared;
- recentFailure.setAssociationStatus(source.recentFailure.getAssociationStatus(),
- source.recentFailure.getLastUpdateTimeSinceBootMillis());
- mRandomizedMacAddress = source.mRandomizedMacAddress;
- dppConnector = source.dppConnector;
- dppNetAccessKey = source.dppNetAccessKey;
- dppNetAccessKeyExpiry = source.dppNetAccessKeyExpiry;
- dppCsign = source.dppCsign;
-
- macRandomizationSetting = source.macRandomizationSetting;
- randomizedMacExpirationTimeMs = source.randomizedMacExpirationTimeMs;
- randomizedMacLastModifiedTimeMs = source.randomizedMacLastModifiedTimeMs;
- requirePmf = source.requirePmf;
- updateIdentifier = source.updateIdentifier;
- carrierId = source.carrierId;
- subscriptionId = source.subscriptionId;
- mPasspointUniqueId = source.mPasspointUniqueId;
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(networkId);
- dest.writeInt(status);
- mNetworkSelectionStatus.writeToParcel(dest);
- dest.writeString(SSID);
- dest.writeString(BSSID);
- dest.writeInt(shareThisAp ? 1 : 0);
- dest.writeInt(apBand);
- dest.writeInt(apChannel);
- dest.writeString(FQDN);
- dest.writeString(providerFriendlyName);
- dest.writeInt(isHomeProviderNetwork ? 1 : 0);
- dest.writeInt(roamingConsortiumIds.length);
- for (long roamingConsortiumId : roamingConsortiumIds) {
- dest.writeLong(roamingConsortiumId);
- }
- dest.writeString(preSharedKey);
- for (String wepKey : wepKeys) {
- dest.writeString(wepKey);
- }
- dest.writeInt(wepTxKeyIndex);
- dest.writeInt(priority);
- dest.writeInt(hiddenSSID ? 1 : 0);
- dest.writeInt(requirePmf ? 1 : 0);
- dest.writeString(updateIdentifier);
-
- writeBitSet(dest, allowedKeyManagement);
- writeBitSet(dest, allowedProtocols);
- writeBitSet(dest, allowedAuthAlgorithms);
- writeBitSet(dest, allowedPairwiseCiphers);
- writeBitSet(dest, allowedGroupCiphers);
- writeBitSet(dest, allowedGroupManagementCiphers);
- writeBitSet(dest, allowedSuiteBCiphers);
-
- dest.writeParcelable(enterpriseConfig, flags);
-
- dest.writeParcelable(mIpConfiguration, flags);
- dest.writeString(dhcpServer);
- dest.writeString(defaultGwMacAddress);
- dest.writeInt(validatedInternetAccess ? 1 : 0);
- dest.writeInt(isLegacyPasspointConfig ? 1 : 0);
- dest.writeInt(ephemeral ? 1 : 0);
- dest.writeInt(trusted ? 1 : 0);
- dest.writeInt(oemPaid ? 1 : 0);
- dest.writeInt(oemPrivate ? 1 : 0);
- dest.writeInt(carrierMerged ? 1 : 0);
- dest.writeInt(fromWifiNetworkSuggestion ? 1 : 0);
- dest.writeInt(fromWifiNetworkSpecifier ? 1 : 0);
- dest.writeInt(meteredHint ? 1 : 0);
- dest.writeInt(meteredOverride);
- dest.writeInt(useExternalScores ? 1 : 0);
- dest.writeInt(creatorUid);
- dest.writeInt(lastConnectUid);
- dest.writeInt(lastUpdateUid);
- dest.writeString(creatorName);
- dest.writeString(lastUpdateName);
- dest.writeInt(numScorerOverride);
- dest.writeInt(numScorerOverrideAndSwitchedNetwork);
- dest.writeInt(numAssociation);
- dest.writeBoolean(allowAutojoin);
- dest.writeInt(numNoInternetAccessReports);
- dest.writeInt(noInternetAccessExpected ? 1 : 0);
- dest.writeInt(shared ? 1 : 0);
- dest.writeString(mPasspointManagementObjectTree);
- dest.writeInt(recentFailure.getAssociationStatus());
- dest.writeLong(recentFailure.getLastUpdateTimeSinceBootMillis());
- dest.writeParcelable(mRandomizedMacAddress, flags);
- dest.writeString(dppConnector);
- dest.writeString(dppNetAccessKey);
- dest.writeInt(dppNetAccessKeyExpiry);
- dest.writeString(dppCsign);
- dest.writeInt(macRandomizationSetting);
- dest.writeInt(osu ? 1 : 0);
- dest.writeLong(randomizedMacExpirationTimeMs);
- dest.writeLong(randomizedMacLastModifiedTimeMs);
- dest.writeInt(carrierId);
- dest.writeString(mPasspointUniqueId);
- dest.writeInt(subscriptionId);
- }
-
- /** Implement the Parcelable interface {@hide} */
- @UnsupportedAppUsage
- public static final @android.annotation.NonNull Creator<WifiConfiguration> CREATOR =
- new Creator<WifiConfiguration>() {
- public WifiConfiguration createFromParcel(Parcel in) {
- WifiConfiguration config = new WifiConfiguration();
- config.networkId = in.readInt();
- config.status = in.readInt();
- config.mNetworkSelectionStatus.readFromParcel(in);
- config.SSID = in.readString();
- config.BSSID = in.readString();
- config.shareThisAp = in.readInt() != 0;
- config.apBand = in.readInt();
- config.apChannel = in.readInt();
- config.FQDN = in.readString();
- config.providerFriendlyName = in.readString();
- config.isHomeProviderNetwork = in.readInt() != 0;
- int numRoamingConsortiumIds = in.readInt();
- config.roamingConsortiumIds = new long[numRoamingConsortiumIds];
- for (int i = 0; i < numRoamingConsortiumIds; i++) {
- config.roamingConsortiumIds[i] = in.readLong();
- }
- config.preSharedKey = in.readString();
- for (int i = 0; i < config.wepKeys.length; i++) {
- config.wepKeys[i] = in.readString();
- }
- config.wepTxKeyIndex = in.readInt();
- config.priority = in.readInt();
- config.hiddenSSID = in.readInt() != 0;
- config.requirePmf = in.readInt() != 0;
- config.updateIdentifier = in.readString();
-
- config.allowedKeyManagement = readBitSet(in);
- config.allowedProtocols = readBitSet(in);
- config.allowedAuthAlgorithms = readBitSet(in);
- config.allowedPairwiseCiphers = readBitSet(in);
- config.allowedGroupCiphers = readBitSet(in);
- config.allowedGroupManagementCiphers = readBitSet(in);
- config.allowedSuiteBCiphers = readBitSet(in);
-
- config.enterpriseConfig = in.readParcelable(null);
- config.setIpConfiguration(in.readParcelable(null));
- config.dhcpServer = in.readString();
- config.defaultGwMacAddress = in.readString();
- config.validatedInternetAccess = in.readInt() != 0;
- config.isLegacyPasspointConfig = in.readInt() != 0;
- config.ephemeral = in.readInt() != 0;
- config.trusted = in.readInt() != 0;
- config.oemPaid = in.readInt() != 0;
- config.oemPrivate = in.readInt() != 0;
- config.carrierMerged = in.readInt() != 0;
- config.fromWifiNetworkSuggestion = in.readInt() != 0;
- config.fromWifiNetworkSpecifier = in.readInt() != 0;
- config.meteredHint = in.readInt() != 0;
- config.meteredOverride = in.readInt();
- config.useExternalScores = in.readInt() != 0;
- config.creatorUid = in.readInt();
- config.lastConnectUid = in.readInt();
- config.lastUpdateUid = in.readInt();
- config.creatorName = in.readString();
- config.lastUpdateName = in.readString();
- config.numScorerOverride = in.readInt();
- config.numScorerOverrideAndSwitchedNetwork = in.readInt();
- config.numAssociation = in.readInt();
- config.allowAutojoin = in.readBoolean();
- config.numNoInternetAccessReports = in.readInt();
- config.noInternetAccessExpected = in.readInt() != 0;
- config.shared = in.readInt() != 0;
- config.mPasspointManagementObjectTree = in.readString();
- config.recentFailure.setAssociationStatus(in.readInt(), in.readLong());
- config.mRandomizedMacAddress = in.readParcelable(null);
- config.dppConnector = in.readString();
- config.dppNetAccessKey = in.readString();
- config.dppNetAccessKeyExpiry = in.readInt();
- config.dppCsign = in.readString();
- config.macRandomizationSetting = in.readInt();
- config.osu = in.readInt() != 0;
- config.randomizedMacExpirationTimeMs = in.readLong();
- config.randomizedMacLastModifiedTimeMs = in.readLong();
- config.carrierId = in.readInt();
- config.mPasspointUniqueId = in.readString();
- config.subscriptionId = in.readInt();
- return config;
- }
-
- public WifiConfiguration[] newArray(int size) {
- return new WifiConfiguration[size];
- }
- };
-
- /**
- * Passpoint Unique identifier
- * @hide
- */
- private String mPasspointUniqueId = null;
-
- /**
- * Set the Passpoint unique identifier
- * @param uniqueId Passpoint unique identifier to be set
- * @hide
- */
- public void setPasspointUniqueId(String uniqueId) {
- mPasspointUniqueId = uniqueId;
- }
-
- /**
- * Set the Passpoint unique identifier
- * @hide
- */
- public String getPasspointUniqueId() {
- return mPasspointUniqueId;
- }
-
- /**
- * If network is one of the most recently connected.
- * For framework internal use only. Do not parcel.
- * @hide
- */
- public boolean isMostRecentlyConnected = false;
-
- /**
- * Whether the key mgmt indicates if the WifiConfiguration needs a preSharedKey or not.
- * @return true if preSharedKey is needed, false otherwise.
- * @hide
- */
- public boolean needsPreSharedKey() {
- return allowedKeyManagement.get(KeyMgmt.WPA_PSK)
- || allowedKeyManagement.get(KeyMgmt.SAE)
- || allowedKeyManagement.get(KeyMgmt.WAPI_PSK);
- }
-
- /**
- * Get a unique key which represent this Wi-Fi configuration profile. If two profiles are for
- * the same Wi-Fi network, but from different providers (apps, carriers, or data subscriptions),
- * they would have different keys.
- * @return a unique key which represent this profile.
- * @hide
- */
- @SystemApi
- @NonNull public String getProfileKey() {
- if (mPasspointUniqueId != null) {
- return mPasspointUniqueId;
- }
-
- String key = SSID + getDefaultSecurityType();
- if (!shared) {
- key += "-" + UserHandle.getUserHandleForUid(creatorUid).getIdentifier();
- }
- if (fromWifiNetworkSuggestion) {
- key += "_" + creatorName + "-" + carrierId + "-" + subscriptionId;
- }
-
- return key;
- }
-
- /**
- * Get the default security type string.
- * @hide
- */
- public String getDefaultSecurityType() {
- String key;
- if (allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
- key = KeyMgmt.strings[KeyMgmt.WPA_PSK];
- } else if (allowedKeyManagement.get(KeyMgmt.WPA_EAP)
- || allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
- key = KeyMgmt.strings[KeyMgmt.WPA_EAP];
- } else if (wepTxKeyIndex >= 0 && wepTxKeyIndex < wepKeys.length
- && wepKeys[wepTxKeyIndex] != null) {
- key = "WEP";
- } else if (allowedKeyManagement.get(KeyMgmt.OWE)) {
- key = KeyMgmt.strings[KeyMgmt.OWE];
- } else if (allowedKeyManagement.get(KeyMgmt.SAE)) {
- key = KeyMgmt.strings[KeyMgmt.SAE];
- } else if (allowedKeyManagement.get(KeyMgmt.SUITE_B_192)) {
- key = KeyMgmt.strings[KeyMgmt.SUITE_B_192];
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_PSK)) {
- key = KeyMgmt.strings[KeyMgmt.WAPI_PSK];
- } else if (allowedKeyManagement.get(KeyMgmt.WAPI_CERT)) {
- key = KeyMgmt.strings[KeyMgmt.WAPI_CERT];
- } else if (allowedKeyManagement.get(KeyMgmt.OSEN)) {
- key = KeyMgmt.strings[KeyMgmt.OSEN];
- } else {
- key = KeyMgmt.strings[KeyMgmt.NONE];
- }
- return key;
- }
-
-}
diff --git a/wifi/java/android/net/wifi/WifiDppConfig.aidl b/wifi/java/android/net/wifi/WifiDppConfig.aidl
deleted file mode 100644
index ac42fd9ac00e..000000000000
--- a/wifi/java/android/net/wifi/WifiDppConfig.aidl
+++ /dev/null
@@ -1,20 +0,0 @@
-/**
- * Copyright (c) 2018, 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;
-
-parcelable WifiDppConfig;
-
diff --git a/wifi/java/android/net/wifi/WifiDppConfig.java b/wifi/java/android/net/wifi/WifiDppConfig.java
deleted file mode 100644
index e41adcff7cfc..000000000000
--- a/wifi/java/android/net/wifi/WifiDppConfig.java
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
- * Copyright (C) 2018 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.os.Parcel;
-import android.os.Parcelable;
-
-/** DPP configuration class
- * @hide
- */
-public class WifiDppConfig implements Parcelable {
- private static final String TAG = "WifiDppConfig";
- public static final int DPP_INVALID_CONFIG_ID = -1;
- public static final int DPP_ROLE_CONFIGURATOR = 0;
- public static final int DPP_ROLE_ENROLLEE = 1;
- public static final int DPP_TYPE_QR_CODE = 0;
- public static final int DPP_TYPE_NAN_BOOTSTRAP = 1;
- public int peer_bootstrap_id;
- public int own_bootstrap_id;
- public int dpp_role;
- public String ssid;
- public String passphrase;
- public int isAp;
- public int isDpp;
- public int conf_id;
- public int bootstrap_type;
- public String chan_list;
- public String mac_addr;
- public String info;
- public String curve;
- public int expiry;
- public String key;
-
- private DppResult mEventResult = new DppResult();
-
- public WifiDppConfig() {
- peer_bootstrap_id = DPP_INVALID_CONFIG_ID;
- own_bootstrap_id = DPP_INVALID_CONFIG_ID;
- dpp_role = DPP_INVALID_CONFIG_ID;
- isAp = DPP_INVALID_CONFIG_ID;
- isDpp = DPP_INVALID_CONFIG_ID;
- conf_id = DPP_INVALID_CONFIG_ID;
- bootstrap_type = DPP_INVALID_CONFIG_ID;
- expiry = 0;
- ssid = null;
- passphrase = null;
- chan_list = null;
- mac_addr = null;
- info = null;
- curve = null;
- key = null;
- }
-
- public DppResult getDppResult() {
- return mEventResult;
- }
-
- public void setDppResult(DppResult result) {
- mEventResult = result;
- }
-
- public void writeToParcel(Parcel dest) {
- }
-
- public void readFromParcel(Parcel in) {
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
- /** Implement the Parcelable interface {@hide} */
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(peer_bootstrap_id);
- dest.writeInt(own_bootstrap_id);
- dest.writeInt(dpp_role);
- dest.writeString(ssid);
- dest.writeString(passphrase);
- dest.writeInt(isAp);
- dest.writeInt(isDpp);
- dest.writeInt(conf_id);
- dest.writeInt(bootstrap_type);
- dest.writeString(chan_list);
- dest.writeString(mac_addr);
- dest.writeString(info);
- dest.writeString(curve);
- dest.writeInt(expiry);
- dest.writeString(key);
- mEventResult.writeToParcel(dest);
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final Creator<WifiDppConfig> CREATOR =
- new Creator<WifiDppConfig>() {
- public WifiDppConfig createFromParcel(Parcel in) {
- WifiDppConfig config = new WifiDppConfig();
- config.peer_bootstrap_id = in.readInt();
- config.own_bootstrap_id = in.readInt();
- config.dpp_role = in.readInt();
- config.ssid = in.readString();
- config.passphrase = in.readString();
- config.isAp = in.readInt();
- config.isDpp = in.readInt();
- config.conf_id = in.readInt();
- config.bootstrap_type = in.readInt();
- config.chan_list = in.readString();
- config.mac_addr = in.readString();
- config.info = in.readString();
- config.curve = in.readString();
- config.expiry = in.readInt();
- config.key = in.readString();
- config.mEventResult.readFromParcel(in);
- return config;
- }
- public WifiDppConfig[] newArray(int size) {
- return new WifiDppConfig[size];
- }
- };
- /**
- * Stores supplicant state change information passed from WifiMonitor to
- * a state machine. WifiStateMachine, SupplicantStateTracker and WpsStateMachine
- * are example state machines that handle it.
- * @hide
- */
- public static class DppResult {
-
- public boolean initiator;
- public int netID;
- public byte capab;
- public byte authMissingParam;
- public byte configEventType;
- public String iBootstrapData;
- public String ssid;
- public String connector;
- public String cSignKey;
- public String netAccessKey;
- public int netAccessKeyExpiry;
- public String passphrase;
- public String psk;
-
- public static final int DPP_EVENT_AUTH_SUCCESS = 0;
- public static final int DPP_EVENT_NOT_COMPATIBLE = 1;
- public static final int DPP_EVENT_RESPONSE_PENDING = 2;
- public static final int DPP_EVENT_SCAN_PEER_QRCODE = 3;
- public static final int DPP_EVENT_CONF = 4;
- public static final int DPP_EVENT_MISSING_AUTH = 5;
- public static final int DPP_EVENT_NETWORK_ID = 6;
-
-
- public static final int DPP_CONF_EVENT_TYPE_FAILED = 0;
- public static final int DPP_CONF_EVENT_TYPE_SENT = 1;
- public static final int DPP_CONF_EVENT_TYPE_RECEIVED = 2;
-
- public DppResult() {
- this.initiator = false;
- this.netID = -1;
- this.capab = 0;
- this.authMissingParam = 0;
- this.configEventType = 0;
- this.iBootstrapData = null;
- this.ssid = null;
- this.connector = null;
- this.cSignKey = null;
- this.netAccessKey = null;
- this.netAccessKeyExpiry = 0;
- this.passphrase = null;
- this.psk = null;
- }
-
- public void writeToParcel(Parcel dest) {
- dest.writeInt(initiator ? 1 : 0);
- dest.writeInt(netID);
- dest.writeByte(capab);
- dest.writeByte(authMissingParam);
- dest.writeByte(configEventType);
- dest.writeString(iBootstrapData);
- dest.writeString(ssid);
- dest.writeString(connector);
- dest.writeString(cSignKey);
- dest.writeString(netAccessKey);
- dest.writeInt(netAccessKeyExpiry);
- dest.writeString(passphrase);
- dest.writeString(psk);
- }
-
- public void readFromParcel(Parcel in) {
- this.initiator = (in.readInt() > 0) ? true : false;
- this.netID = in.readInt();
- this.capab = in.readByte();
- this.authMissingParam = in.readByte();
- this.configEventType = in.readByte();
- this.iBootstrapData = in.readString();
- this.ssid = in.readString();
- this.connector = in.readString();
- this.cSignKey = in.readString();
- this.netAccessKey = in.readString();
- this.netAccessKeyExpiry = in.readInt();
- this.passphrase = in.readString();
- this.psk = in.readString();
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiEnterpriseConfig.java b/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
deleted file mode 100644
index 28496c1e8834..000000000000
--- a/wifi/java/android/net/wifi/WifiEnterpriseConfig.java
+++ /dev/null
@@ -1,1526 +0,0 @@
-/*
- * Copyright (C) 2013 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.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.nio.charset.StandardCharsets;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-import java.security.interfaces.ECPublicKey;
-import java.security.interfaces.RSAPublicKey;
-import java.security.spec.ECParameterSpec;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Enterprise configuration details for Wi-Fi. Stores details about the EAP method
- * and any associated credentials.
- */
-public class WifiEnterpriseConfig implements Parcelable {
-
- /** Key prefix for WAPI AS certificates. */
- public static final String WAPI_AS_CERTIFICATE = "WAPIAS_";
-
- /** Key prefix for WAPI user certificates. */
- public static final String WAPI_USER_CERTIFICATE = "WAPIUSR_";
-
- /**
- * Intent extra: name for WAPI AS certificates
- */
- public static final String EXTRA_WAPI_AS_CERTIFICATE_NAME =
- "android.net.wifi.extra.WAPI_AS_CERTIFICATE_NAME";
-
- /**
- * Intent extra: data for WAPI AS certificates
- */
- public static final String EXTRA_WAPI_AS_CERTIFICATE_DATA =
- "android.net.wifi.extra.WAPI_AS_CERTIFICATE_DATA";
-
- /**
- * Intent extra: name for WAPI USER certificates
- */
- public static final String EXTRA_WAPI_USER_CERTIFICATE_NAME =
- "android.net.wifi.extra.WAPI_USER_CERTIFICATE_NAME";
-
- /**
- * Intent extra: data for WAPI USER certificates
- */
- public static final String EXTRA_WAPI_USER_CERTIFICATE_DATA =
- "android.net.wifi.extra.WAPI_USER_CERTIFICATE_DATA";
-
- /** @hide */
- public static final String EMPTY_VALUE = "NULL";
- /** @hide */
- public static final String EAP_KEY = "eap";
- /** @hide */
- public static final String PHASE2_KEY = "phase2";
- /** @hide */
- public static final String IDENTITY_KEY = "identity";
- /** @hide */
- public static final String ANON_IDENTITY_KEY = "anonymous_identity";
- /** @hide */
- public static final String PASSWORD_KEY = "password";
- /** @hide */
- public static final String SUBJECT_MATCH_KEY = "subject_match";
- /** @hide */
- public static final String ALTSUBJECT_MATCH_KEY = "altsubject_match";
- /** @hide */
- public static final String DOM_SUFFIX_MATCH_KEY = "domain_suffix_match";
- /** @hide */
- public static final String OPP_KEY_CACHING = "proactive_key_caching";
- /** @hide */
- public static final String EAP_ERP = "eap_erp";
- /** @hide */
- public static final String OCSP = "ocsp";
- /** @hide */
- public static final String KEY_SIMNUM = "sim_num";
-
- /**
- * String representing the keystore OpenSSL ENGINE's ID.
- * @hide
- */
- public static final String ENGINE_ID_KEYSTORE = "keystore";
-
- /**
- * String representing the keystore URI used for wpa_supplicant.
- * @hide
- */
- public static final String KEYSTORE_URI = "keystore://";
-
- /**
- * String representing the keystore URI used for wpa_supplicant,
- * Unlike #KEYSTORE_URI, this supports a list of space-delimited aliases
- * @hide
- */
- public static final String KEYSTORES_URI = "keystores://";
-
- /**
- * String to set the engine value to when it should be enabled.
- * @hide
- */
- public static final String ENGINE_ENABLE = "1";
-
- /**
- * String to set the engine value to when it should be disabled.
- * @hide
- */
- public static final String ENGINE_DISABLE = "0";
-
- /**
- * Key prefix for CA certificates.
- * Note: copied from {@link android.security.Credentials#CA_CERTIFICATE} since it is @hide.
- */
- private static final String CA_CERTIFICATE = "CACERT_";
- /**
- * Key prefix for user certificates.
- * Note: copied from {@link android.security.Credentials#USER_CERTIFICATE} since it is @hide.
- */
- private static final String USER_CERTIFICATE = "USRCERT_";
- /**
- * Key prefix for user private and secret keys.
- * Note: copied from {@link android.security.Credentials#USER_PRIVATE_KEY} since it is @hide.
- */
- private static final String USER_PRIVATE_KEY = "USRPKEY_";
-
- /** @hide */
- public static final String CA_CERT_PREFIX = KEYSTORE_URI + CA_CERTIFICATE;
- /** @hide */
- public static final String CLIENT_CERT_PREFIX = KEYSTORE_URI + USER_CERTIFICATE;
- /** @hide */
- public static final String CLIENT_CERT_KEY = "client_cert";
- /** @hide */
- public static final String CA_CERT_KEY = "ca_cert";
- /** @hide */
- public static final String CA_PATH_KEY = "ca_path";
- /** @hide */
- public static final String ENGINE_KEY = "engine";
- /** @hide */
- public static final String ENGINE_ID_KEY = "engine_id";
- /** @hide */
- public static final String PRIVATE_KEY_ID_KEY = "key_id";
- /** @hide */
- public static final String REALM_KEY = "realm";
- /** @hide */
- public static final String PLMN_KEY = "plmn";
- /** @hide */
- public static final String CA_CERT_ALIAS_DELIMITER = " ";
- /** @hide */
- public static final String WAPI_CERT_SUITE_KEY = "wapi_cert_suite";
-
- /**
- * Do not use OCSP stapling (TLS certificate status extension)
- * @hide
- */
- @SystemApi
- public static final int OCSP_NONE = 0;
-
- /**
- * Try to use OCSP stapling, but not require response
- * @hide
- */
- @SystemApi
- public static final int OCSP_REQUEST_CERT_STATUS = 1;
-
- /**
- * Require valid OCSP stapling response
- * @hide
- */
- @SystemApi
- public static final int OCSP_REQUIRE_CERT_STATUS = 2;
-
- /**
- * Require valid OCSP stapling response for all not-trusted certificates in the server
- * certificate chain
- * @hide
- */
- @SystemApi
- public static final int OCSP_REQUIRE_ALL_NON_TRUSTED_CERTS_STATUS = 3;
-
- /** @hide */
- @IntDef(prefix = {"OCSP_"}, value = {
- OCSP_NONE,
- OCSP_REQUEST_CERT_STATUS,
- OCSP_REQUIRE_CERT_STATUS,
- OCSP_REQUIRE_ALL_NON_TRUSTED_CERTS_STATUS
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface Ocsp {}
-
- /**
- * Whether to use/require OCSP (Online Certificate Status Protocol) to check server certificate.
- * @hide
- */
- private @Ocsp int mOcsp = OCSP_NONE;
-
- // Fields to copy verbatim from wpa_supplicant.
- private static final String[] SUPPLICANT_CONFIG_KEYS = new String[] {
- IDENTITY_KEY,
- ANON_IDENTITY_KEY,
- PASSWORD_KEY,
- CLIENT_CERT_KEY,
- CA_CERT_KEY,
- SUBJECT_MATCH_KEY,
- ENGINE_KEY,
- ENGINE_ID_KEY,
- PRIVATE_KEY_ID_KEY,
- ALTSUBJECT_MATCH_KEY,
- DOM_SUFFIX_MATCH_KEY,
- CA_PATH_KEY
- };
-
- /**
- * Fields that have unquoted values in {@link #mFields}.
- */
- private static final List<String> UNQUOTED_KEYS = Arrays.asList(ENGINE_KEY, OPP_KEY_CACHING,
- EAP_ERP);
-
- @UnsupportedAppUsage
- private HashMap<String, String> mFields = new HashMap<String, String>();
- private X509Certificate[] mCaCerts;
- private PrivateKey mClientPrivateKey;
- private X509Certificate[] mClientCertificateChain;
- private int mEapMethod = Eap.NONE;
- private int mPhase2Method = Phase2.NONE;
- private boolean mIsAppInstalledDeviceKeyAndCert = false;
- private boolean mIsAppInstalledCaCert = false;
-
- private static final String TAG = "WifiEnterpriseConfig";
-
- public WifiEnterpriseConfig() {
- // Do not set defaults so that the enterprise fields that are not changed
- // by API are not changed underneath
- // This is essential because an app may not have all fields like password
- // available. It allows modification of subset of fields.
-
- }
-
- /**
- * Copy over the contents of the source WifiEnterpriseConfig object over to this object.
- *
- * @param source Source WifiEnterpriseConfig object.
- * @param ignoreMaskedPassword Set to true to ignore masked password field, false otherwise.
- * @param mask if |ignoreMaskedPassword| is set, check if the incoming password field is set
- * to this value.
- */
- private void copyFrom(WifiEnterpriseConfig source, boolean ignoreMaskedPassword, String mask) {
- for (String key : source.mFields.keySet()) {
- if (ignoreMaskedPassword && key.equals(PASSWORD_KEY)
- && TextUtils.equals(source.mFields.get(key), mask)) {
- continue;
- }
- mFields.put(key, source.mFields.get(key));
- }
- if (source.mCaCerts != null) {
- mCaCerts = Arrays.copyOf(source.mCaCerts, source.mCaCerts.length);
- } else {
- mCaCerts = null;
- }
- mClientPrivateKey = source.mClientPrivateKey;
- if (source.mClientCertificateChain != null) {
- mClientCertificateChain = Arrays.copyOf(
- source.mClientCertificateChain,
- source.mClientCertificateChain.length);
- } else {
- mClientCertificateChain = null;
- }
- mEapMethod = source.mEapMethod;
- mPhase2Method = source.mPhase2Method;
- mIsAppInstalledDeviceKeyAndCert = source.mIsAppInstalledDeviceKeyAndCert;
- mIsAppInstalledCaCert = source.mIsAppInstalledCaCert;
- mOcsp = source.mOcsp;
- }
-
- /**
- * Copy constructor.
- * This copies over all the fields verbatim (does not ignore masked password fields).
- *
- * @param source Source WifiEnterpriseConfig object.
- */
- public WifiEnterpriseConfig(WifiEnterpriseConfig source) {
- copyFrom(source, false, "");
- }
-
- /**
- * Copy fields from the provided external WifiEnterpriseConfig.
- * This is needed to handle the WifiEnterpriseConfig objects which were sent by apps with the
- * password field masked.
- *
- * @param externalConfig External WifiEnterpriseConfig object.
- * @param mask String mask to compare against.
- * @hide
- */
- public void copyFromExternal(WifiEnterpriseConfig externalConfig, String mask) {
- copyFrom(externalConfig, true, convertToQuotedString(mask));
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mFields.size());
- for (Map.Entry<String, String> entry : mFields.entrySet()) {
- dest.writeString(entry.getKey());
- dest.writeString(entry.getValue());
- }
-
- dest.writeInt(mEapMethod);
- dest.writeInt(mPhase2Method);
- ParcelUtil.writeCertificates(dest, mCaCerts);
- ParcelUtil.writePrivateKey(dest, mClientPrivateKey);
- ParcelUtil.writeCertificates(dest, mClientCertificateChain);
- dest.writeBoolean(mIsAppInstalledDeviceKeyAndCert);
- dest.writeBoolean(mIsAppInstalledCaCert);
- dest.writeInt(mOcsp);
- }
-
- public static final @android.annotation.NonNull Creator<WifiEnterpriseConfig> CREATOR =
- new Creator<WifiEnterpriseConfig>() {
- @Override
- public WifiEnterpriseConfig createFromParcel(Parcel in) {
- WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
- int count = in.readInt();
- for (int i = 0; i < count; i++) {
- String key = in.readString();
- String value = in.readString();
- enterpriseConfig.mFields.put(key, value);
- }
-
- enterpriseConfig.mEapMethod = in.readInt();
- enterpriseConfig.mPhase2Method = in.readInt();
- enterpriseConfig.mCaCerts = ParcelUtil.readCertificates(in);
- enterpriseConfig.mClientPrivateKey = ParcelUtil.readPrivateKey(in);
- enterpriseConfig.mClientCertificateChain = ParcelUtil.readCertificates(in);
- enterpriseConfig.mIsAppInstalledDeviceKeyAndCert = in.readBoolean();
- enterpriseConfig.mIsAppInstalledCaCert = in.readBoolean();
- enterpriseConfig.mOcsp = in.readInt();
- return enterpriseConfig;
- }
-
- @Override
- public WifiEnterpriseConfig[] newArray(int size) {
- return new WifiEnterpriseConfig[size];
- }
- };
-
- /** The Extensible Authentication Protocol method used */
- public static final class Eap {
- /** No EAP method used. Represents an empty config */
- public static final int NONE = -1;
- /** Protected EAP */
- public static final int PEAP = 0;
- /** EAP-Transport Layer Security */
- public static final int TLS = 1;
- /** EAP-Tunneled Transport Layer Security */
- public static final int TTLS = 2;
- /** EAP-Password */
- public static final int PWD = 3;
- /** EAP-Subscriber Identity Module [RFC-4186] */
- public static final int SIM = 4;
- /** EAP-Authentication and Key Agreement [RFC-4187] */
- public static final int AKA = 5;
- /** EAP-Authentication and Key Agreement Prime [RFC-5448] */
- public static final int AKA_PRIME = 6;
- /** Hotspot 2.0 r2 OSEN */
- public static final int UNAUTH_TLS = 7;
- /** WAPI Certificate */
- public static final int WAPI_CERT = 8;
- /** @hide */
- public static final String[] strings =
- { "PEAP", "TLS", "TTLS", "PWD", "SIM", "AKA", "AKA'", "WFA-UNAUTH-TLS",
- "WAPI_CERT" };
-
- /** Prevent initialization */
- private Eap() {}
- }
-
- /** The inner authentication method used */
- public static final class Phase2 {
- public static final int NONE = 0;
- /** Password Authentication Protocol */
- public static final int PAP = 1;
- /** Microsoft Challenge Handshake Authentication Protocol */
- public static final int MSCHAP = 2;
- /** Microsoft Challenge Handshake Authentication Protocol v2 */
- public static final int MSCHAPV2 = 3;
- /** Generic Token Card */
- public static final int GTC = 4;
- /** EAP-Subscriber Identity Module [RFC-4186] */
- public static final int SIM = 5;
- /** EAP-Authentication and Key Agreement [RFC-4187] */
- public static final int AKA = 6;
- /** EAP-Authentication and Key Agreement Prime [RFC-5448] */
- public static final int AKA_PRIME = 7;
- private static final String AUTH_PREFIX = "auth=";
- private static final String AUTHEAP_PREFIX = "autheap=";
- /** @hide */
- public static final String[] strings = {EMPTY_VALUE, "PAP", "MSCHAP",
- "MSCHAPV2", "GTC", "SIM", "AKA", "AKA'" };
-
- /** Prevent initialization */
- private Phase2() {}
- }
-
- // Loader and saver interfaces for exchanging data with wpa_supplicant.
- // TODO: Decouple this object (which is just a placeholder of the configuration)
- // from the implementation that knows what wpa_supplicant wants.
- /**
- * Interface used for retrieving supplicant configuration from WifiEnterpriseConfig
- * @hide
- */
- public interface SupplicantSaver {
- /**
- * Set a value within wpa_supplicant configuration
- * @param key index to set within wpa_supplciant
- * @param value the value for the key
- * @return true if successful; false otherwise
- */
- boolean saveValue(String key, String value);
- }
-
- /**
- * Interface used for populating a WifiEnterpriseConfig from supplicant configuration
- * @hide
- */
- public interface SupplicantLoader {
- /**
- * Returns a value within wpa_supplicant configuration
- * @param key index to set within wpa_supplciant
- * @return string value if successful; null otherwise
- */
- String loadValue(String key);
- }
-
- /**
- * Internal use only; supply field values to wpa_supplicant config. The configuration
- * process aborts on the first failed call on {@code saver}.
- * @param saver proxy for setting configuration in wpa_supplciant
- * @return whether the save succeeded on all attempts
- * @hide
- */
- public boolean saveToSupplicant(SupplicantSaver saver) {
- if (!isEapMethodValid()) {
- return false;
- }
-
- // wpa_supplicant can update the anonymous identity for these kinds of networks after
- // framework reads them, so make sure the framework doesn't try to overwrite them.
- boolean shouldNotWriteAnonIdentity = mEapMethod == WifiEnterpriseConfig.Eap.SIM
- || mEapMethod == WifiEnterpriseConfig.Eap.AKA
- || mEapMethod == WifiEnterpriseConfig.Eap.AKA_PRIME;
- for (String key : mFields.keySet()) {
- if (shouldNotWriteAnonIdentity && ANON_IDENTITY_KEY.equals(key)) {
- continue;
- }
- if (!saver.saveValue(key, mFields.get(key))) {
- return false;
- }
- }
-
- if (!saver.saveValue(EAP_KEY, Eap.strings[mEapMethod])) {
- return false;
- }
-
- if (mEapMethod != Eap.TLS && mEapMethod != Eap.UNAUTH_TLS && mPhase2Method != Phase2.NONE) {
- boolean is_autheap = mEapMethod == Eap.TTLS && mPhase2Method == Phase2.GTC;
- String prefix = is_autheap ? Phase2.AUTHEAP_PREFIX : Phase2.AUTH_PREFIX;
- String value = convertToQuotedString(prefix + Phase2.strings[mPhase2Method]);
- return saver.saveValue(PHASE2_KEY, value);
- } else if (mPhase2Method == Phase2.NONE) {
- // By default, send a null phase 2 to clear old configuration values.
- return saver.saveValue(PHASE2_KEY, null);
- } else {
- Log.e(TAG, "WiFi enterprise configuration is invalid as it supplies a "
- + "phase 2 method but the phase1 method does not support it.");
- return false;
- }
- }
-
- /**
- * Internal use only; retrieve configuration from wpa_supplicant config.
- * @param loader proxy for retrieving configuration keys from wpa_supplicant
- * @hide
- */
- public void loadFromSupplicant(SupplicantLoader loader) {
- for (String key : SUPPLICANT_CONFIG_KEYS) {
- String value = loader.loadValue(key);
- if (value == null) {
- mFields.put(key, EMPTY_VALUE);
- } else {
- mFields.put(key, value);
- }
- }
- String eapMethod = loader.loadValue(EAP_KEY);
- mEapMethod = getStringIndex(Eap.strings, eapMethod, Eap.NONE);
-
- String phase2Method = removeDoubleQuotes(loader.loadValue(PHASE2_KEY));
- // Remove "auth=" or "autheap=" prefix.
- if (phase2Method.startsWith(Phase2.AUTH_PREFIX)) {
- phase2Method = phase2Method.substring(Phase2.AUTH_PREFIX.length());
- } else if (phase2Method.startsWith(Phase2.AUTHEAP_PREFIX)) {
- phase2Method = phase2Method.substring(Phase2.AUTHEAP_PREFIX.length());
- }
- mPhase2Method = getStringIndex(Phase2.strings, phase2Method, Phase2.NONE);
- }
-
- /**
- * Set the EAP authentication method.
- * @param eapMethod is one {@link Eap#PEAP}, {@link Eap#TLS}, {@link Eap#TTLS} or
- * {@link Eap#PWD}
- * @throws IllegalArgumentException on an invalid eap method
- */
- public void setEapMethod(int eapMethod) {
- switch (eapMethod) {
- /** Valid methods */
- case Eap.WAPI_CERT:
- mEapMethod = eapMethod;
- setPhase2Method(Phase2.NONE);
- break;
- case Eap.TLS:
- case Eap.UNAUTH_TLS:
- setPhase2Method(Phase2.NONE);
- /* fall through */
- case Eap.PEAP:
- case Eap.PWD:
- case Eap.TTLS:
- case Eap.SIM:
- case Eap.AKA:
- case Eap.AKA_PRIME:
- mEapMethod = eapMethod;
- setFieldValue(OPP_KEY_CACHING, "1");
- break;
- default:
- throw new IllegalArgumentException("Unknown EAP method");
- }
- }
-
- /** @hide */
- public void setSimNum(int SIMNum) {
- setFieldValue(KEY_SIMNUM, Integer.toString(SIMNum));
- }
-
- /** @hide */
- public @NonNull String getSimNum() {
- return getFieldValue(KEY_SIMNUM);
- }
-
- /**
- * Get the eap method.
- * @return eap method configured
- */
- public int getEapMethod() {
- return mEapMethod;
- }
-
- /**
- * Set Phase 2 authentication method. Sets the inner authentication method to be used in
- * phase 2 after setting up a secure channel
- * @param phase2Method is the inner authentication method and can be one of {@link Phase2#NONE},
- * {@link Phase2#PAP}, {@link Phase2#MSCHAP}, {@link Phase2#MSCHAPV2},
- * {@link Phase2#GTC}
- * @throws IllegalArgumentException on an invalid phase2 method
- *
- */
- public void setPhase2Method(int phase2Method) {
- switch (phase2Method) {
- case Phase2.NONE:
- case Phase2.PAP:
- case Phase2.MSCHAP:
- case Phase2.MSCHAPV2:
- case Phase2.GTC:
- case Phase2.SIM:
- case Phase2.AKA:
- case Phase2.AKA_PRIME:
- mPhase2Method = phase2Method;
- break;
- default:
- throw new IllegalArgumentException("Unknown Phase 2 method");
- }
- }
-
- /**
- * Get the phase 2 authentication method.
- * @return a phase 2 method defined at {@link Phase2}
- * */
- public int getPhase2Method() {
- return mPhase2Method;
- }
-
- /**
- * Set the identity
- * @param identity
- */
- public void setIdentity(String identity) {
- setFieldValue(IDENTITY_KEY, identity, "");
- }
-
- /**
- * Get the identity
- * @return the identity
- */
- public String getIdentity() {
- return getFieldValue(IDENTITY_KEY);
- }
-
- /**
- * Set anonymous identity. This is used as the unencrypted identity with
- * certain EAP types
- * @param anonymousIdentity the anonymous identity
- */
- public void setAnonymousIdentity(String anonymousIdentity) {
- setFieldValue(ANON_IDENTITY_KEY, anonymousIdentity);
- }
-
- /**
- * Get the anonymous identity
- * @return anonymous identity
- */
- public String getAnonymousIdentity() {
- return getFieldValue(ANON_IDENTITY_KEY);
- }
-
- /**
- * Set the password.
- * @param password the password
- */
- public void setPassword(String password) {
- setFieldValue(PASSWORD_KEY, password);
- }
-
- /**
- * Get the password.
- *
- * Returns locally set password value. For networks fetched from
- * framework, returns "*".
- */
- public String getPassword() {
- return getFieldValue(PASSWORD_KEY);
- }
-
- /**
- * Encode a CA certificate alias so it does not contain illegal character.
- * @hide
- */
- public static String encodeCaCertificateAlias(String alias) {
- byte[] bytes = alias.getBytes(StandardCharsets.UTF_8);
- StringBuilder sb = new StringBuilder(bytes.length * 2);
- for (byte o : bytes) {
- sb.append(String.format("%02x", o & 0xFF));
- }
- return sb.toString();
- }
-
- /**
- * Decode a previously-encoded CA certificate alias.
- * @hide
- */
- public static String decodeCaCertificateAlias(String alias) {
- byte[] data = new byte[alias.length() >> 1];
- for (int n = 0, position = 0; n < alias.length(); n += 2, position++) {
- data[position] = (byte) Integer.parseInt(alias.substring(n, n + 2), 16);
- }
- try {
- return new String(data, StandardCharsets.UTF_8);
- } catch (NumberFormatException e) {
- e.printStackTrace();
- return alias;
- }
- }
-
- /**
- * Set CA certificate alias.
- *
- * <p> See the {@link android.security.KeyChain} for details on installing or choosing
- * a certificate
- * </p>
- * @param alias identifies the certificate
- * @hide
- */
- @UnsupportedAppUsage
- public void setCaCertificateAlias(String alias) {
- setFieldValue(CA_CERT_KEY, alias, CA_CERT_PREFIX);
- }
-
- /**
- * Set CA certificate aliases. When creating installing the corresponding certificate to
- * the keystore, please use alias encoded by {@link #encodeCaCertificateAlias(String)}.
- *
- * <p> See the {@link android.security.KeyChain} for details on installing or choosing
- * a certificate.
- * </p>
- * @param aliases identifies the certificate. Can be null to indicate the absence of a
- * certificate.
- * @hide
- */
- @SystemApi
- public void setCaCertificateAliases(@Nullable String[] aliases) {
- if (aliases == null) {
- setFieldValue(CA_CERT_KEY, null, CA_CERT_PREFIX);
- } else if (aliases.length == 1) {
- // Backwards compatibility: use the original cert prefix if setting only one alias.
- setCaCertificateAlias(aliases[0]);
- } else {
- // Use KEYSTORES_URI which supports multiple aliases.
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < aliases.length; i++) {
- if (i > 0) {
- sb.append(CA_CERT_ALIAS_DELIMITER);
- }
- sb.append(encodeCaCertificateAlias(CA_CERTIFICATE + aliases[i]));
- }
- setFieldValue(CA_CERT_KEY, sb.toString(), KEYSTORES_URI);
- }
- }
-
- /**
- * Get CA certificate alias
- * @return alias to the CA certificate
- * @hide
- */
- @UnsupportedAppUsage
- public String getCaCertificateAlias() {
- return getFieldValue(CA_CERT_KEY, CA_CERT_PREFIX);
- }
-
- /**
- * Get CA certificate aliases.
- * @return alias to the CA certificate, or null if unset.
- * @hide
- */
- @Nullable
- @SystemApi
- public String[] getCaCertificateAliases() {
- String value = getFieldValue(CA_CERT_KEY);
- if (value.startsWith(CA_CERT_PREFIX)) {
- // Backwards compatibility: parse the original alias prefix.
- return new String[] {getFieldValue(CA_CERT_KEY, CA_CERT_PREFIX)};
- } else if (value.startsWith(KEYSTORES_URI)) {
- String values = value.substring(KEYSTORES_URI.length());
-
- String[] aliases = TextUtils.split(values, CA_CERT_ALIAS_DELIMITER);
- for (int i = 0; i < aliases.length; i++) {
- aliases[i] = decodeCaCertificateAlias(aliases[i]);
- if (aliases[i].startsWith(CA_CERTIFICATE)) {
- aliases[i] = aliases[i].substring(CA_CERTIFICATE.length());
- }
- }
- return aliases.length != 0 ? aliases : null;
- } else {
- return TextUtils.isEmpty(value) ? null : new String[] {value};
- }
- }
-
- /**
- * Specify a X.509 certificate that identifies the server.
- *
- * <p>A default name is automatically assigned to the certificate and used
- * with this configuration. The framework takes care of installing the
- * certificate when the config is saved and removing the certificate when
- * the config is removed.
- *
- * Note: If no certificate is set for an Enterprise configuration, either by not calling this
- * API (or the {@link #setCaCertificates(X509Certificate[])}, or by calling it with null, then
- * the server certificate validation is skipped - which means that the connection is not secure.
- *
- * @param cert X.509 CA certificate
- * @throws IllegalArgumentException if not a CA certificate
- */
- public void setCaCertificate(@Nullable X509Certificate cert) {
- if (cert != null) {
- if (cert.getBasicConstraints() >= 0) {
- mIsAppInstalledCaCert = true;
- mCaCerts = new X509Certificate[] {cert};
- } else {
- mCaCerts = null;
- throw new IllegalArgumentException("Not a CA certificate");
- }
- } else {
- mCaCerts = null;
- }
- }
-
- /**
- * Get CA certificate. If multiple CA certificates are configured previously,
- * return the first one.
- * @return X.509 CA certificate
- */
- @Nullable public X509Certificate getCaCertificate() {
- if (mCaCerts != null && mCaCerts.length > 0) {
- return mCaCerts[0];
- } else {
- return null;
- }
- }
-
- /**
- * Specify a list of X.509 certificates that identifies the server. The validation
- * passes if the CA of server certificate matches one of the given certificates.
-
- * <p>Default names are automatically assigned to the certificates and used
- * with this configuration. The framework takes care of installing the
- * certificates when the config is saved and removing the certificates when
- * the config is removed.
- *
- * Note: If no certificates are set for an Enterprise configuration, either by not calling this
- * API (or the {@link #setCaCertificate(X509Certificate)}, or by calling it with null, then the
- * server certificate validation is skipped - which means that the
- * connection is not secure.
- *
- * @param certs X.509 CA certificates
- * @throws IllegalArgumentException if any of the provided certificates is
- * not a CA certificate
- */
- public void setCaCertificates(@Nullable X509Certificate[] certs) {
- if (certs != null) {
- X509Certificate[] newCerts = new X509Certificate[certs.length];
- for (int i = 0; i < certs.length; i++) {
- if (certs[i].getBasicConstraints() >= 0) {
- newCerts[i] = certs[i];
- } else {
- mCaCerts = null;
- throw new IllegalArgumentException("Not a CA certificate");
- }
- }
- mCaCerts = newCerts;
- mIsAppInstalledCaCert = true;
- } else {
- mCaCerts = null;
- }
- }
-
- /**
- * Get CA certificates.
- */
- @Nullable public X509Certificate[] getCaCertificates() {
- if (mCaCerts != null && mCaCerts.length > 0) {
- return mCaCerts;
- } else {
- return null;
- }
- }
-
- /**
- * @hide
- */
- public void resetCaCertificate() {
- mCaCerts = null;
- }
-
- /**
- * Set the ca_path directive on wpa_supplicant.
- *
- * From wpa_supplicant documentation:
- *
- * Directory path for CA certificate files (PEM). This path may contain
- * multiple CA certificates in OpenSSL format. Common use for this is to
- * point to system trusted CA list which is often installed into directory
- * like /etc/ssl/certs. If configured, these certificates are added to the
- * list of trusted CAs. ca_cert may also be included in that case, but it is
- * not required.
- *
- * Note: If no certificate path is set for an Enterprise configuration, either by not calling
- * this API, or by calling it with null, and no certificate is set by
- * {@link #setCaCertificate(X509Certificate)} or {@link #setCaCertificates(X509Certificate[])},
- * then the server certificate validation is skipped - which means that the connection is not
- * secure.
- *
- * @param path The path for CA certificate files, or empty string to clear.
- * @hide
- */
- @SystemApi
- public void setCaPath(@NonNull String path) {
- setFieldValue(CA_PATH_KEY, path);
- }
-
- /**
- * Get the ca_path directive from wpa_supplicant.
- * @return The path for CA certificate files, or an empty string if unset.
- * @hide
- */
- @NonNull
- @SystemApi
- public String getCaPath() {
- return getFieldValue(CA_PATH_KEY);
- }
-
- /**
- * Set Client certificate alias.
- *
- * <p> See the {@link android.security.KeyChain} for details on installing or choosing
- * a certificate
- * </p>
- * @param alias identifies the certificate, or empty string to clear.
- * @hide
- */
- @SystemApi
- public void setClientCertificateAlias(@NonNull String alias) {
- setFieldValue(CLIENT_CERT_KEY, alias, CLIENT_CERT_PREFIX);
- setFieldValue(PRIVATE_KEY_ID_KEY, alias, USER_PRIVATE_KEY);
- // Also, set engine parameters
- if (TextUtils.isEmpty(alias)) {
- setFieldValue(ENGINE_KEY, ENGINE_DISABLE);
- setFieldValue(ENGINE_ID_KEY, "");
- } else {
- setFieldValue(ENGINE_KEY, ENGINE_ENABLE);
- setFieldValue(ENGINE_ID_KEY, ENGINE_ID_KEYSTORE);
- }
- }
-
- /**
- * Get client certificate alias.
- * @return alias to the client certificate, or an empty string if unset.
- * @hide
- */
- @NonNull
- @SystemApi
- public String getClientCertificateAlias() {
- return getFieldValue(CLIENT_CERT_KEY, CLIENT_CERT_PREFIX);
- }
-
- /**
- * Specify a private key and client certificate for client authorization.
- *
- * <p>A default name is automatically assigned to the key entry and used
- * with this configuration. The framework takes care of installing the
- * key entry when the config is saved and removing the key entry when
- * the config is removed.
-
- * @param privateKey a PrivateKey instance for the end certificate.
- * @param clientCertificate an X509Certificate representing the end certificate.
- * @throws IllegalArgumentException for an invalid key or certificate.
- */
- public void setClientKeyEntry(PrivateKey privateKey, X509Certificate clientCertificate) {
- X509Certificate[] clientCertificates = null;
- if (clientCertificate != null) {
- clientCertificates = new X509Certificate[] {clientCertificate};
- }
- setClientKeyEntryWithCertificateChain(privateKey, clientCertificates);
- }
-
- /**
- * Specify a private key and client certificate chain for client authorization.
- *
- * <p>A default name is automatically assigned to the key entry and used
- * with this configuration. The framework takes care of installing the
- * key entry when the config is saved and removing the key entry when
- * the config is removed.
- *
- * @param privateKey a PrivateKey instance for the end certificate.
- * @param clientCertificateChain an array of X509Certificate instances which starts with
- * end certificate and continues with additional CA certificates necessary to
- * link the end certificate with some root certificate known by the authenticator.
- * @throws IllegalArgumentException for an invalid key or certificate.
- */
- public void setClientKeyEntryWithCertificateChain(PrivateKey privateKey,
- X509Certificate[] clientCertificateChain) {
- X509Certificate[] newCerts = null;
- if (clientCertificateChain != null && clientCertificateChain.length > 0) {
- // We validate that this is a well formed chain that starts
- // with an end-certificate and is followed by CA certificates.
- // We don't validate that each following certificate verifies
- // the previous. https://en.wikipedia.org/wiki/Chain_of_trust
- //
- // Basic constraints is an X.509 extension type that defines
- // whether a given certificate is allowed to sign additional
- // certificates and what path length restrictions may exist.
- // We use this to judge whether the certificate is an end
- // certificate or a CA certificate.
- // https://cryptography.io/en/latest/x509/reference/
- if (clientCertificateChain[0].getBasicConstraints() != -1) {
- throw new IllegalArgumentException(
- "First certificate in the chain must be a client end certificate");
- }
-
- for (int i = 1; i < clientCertificateChain.length; i++) {
- if (clientCertificateChain[i].getBasicConstraints() == -1) {
- throw new IllegalArgumentException(
- "All certificates following the first must be CA certificates");
- }
- }
- newCerts = Arrays.copyOf(clientCertificateChain,
- clientCertificateChain.length);
-
- if (privateKey == null) {
- throw new IllegalArgumentException("Client cert without a private key");
- }
- if (privateKey.getEncoded() == null) {
- throw new IllegalArgumentException("Private key cannot be encoded");
- }
- }
-
- mClientPrivateKey = privateKey;
- mClientCertificateChain = newCerts;
- mIsAppInstalledDeviceKeyAndCert = true;
- }
-
- /**
- * Get client certificate
- *
- * @return X.509 client certificate
- */
- public X509Certificate getClientCertificate() {
- if (mClientCertificateChain != null && mClientCertificateChain.length > 0) {
- return mClientCertificateChain[0];
- } else {
- return null;
- }
- }
-
- /**
- * Get the complete client certificate chain in the same order as it was last supplied.
- *
- * <p>If the chain was last supplied by a call to
- * {@link #setClientKeyEntry(java.security.PrivateKey, java.security.cert.X509Certificate)}
- * with a non-null * certificate instance, a single-element array containing the certificate
- * will be * returned. If {@link #setClientKeyEntryWithCertificateChain(
- * java.security.PrivateKey, java.security.cert.X509Certificate[])} was last called with a
- * non-empty array, this array will be returned in the same order as it was supplied.
- * Otherwise, {@code null} will be returned.
- *
- * @return X.509 client certificates
- */
- @Nullable public X509Certificate[] getClientCertificateChain() {
- if (mClientCertificateChain != null && mClientCertificateChain.length > 0) {
- return mClientCertificateChain;
- } else {
- return null;
- }
- }
-
- /**
- * @hide
- */
- public void resetClientKeyEntry() {
- mClientPrivateKey = null;
- mClientCertificateChain = null;
- }
-
- /**
- * Get the client private key as supplied in {@link #setClientKeyEntryWithCertificateChain}, or
- * null if unset.
- */
- @Nullable
- public PrivateKey getClientPrivateKey() {
- return mClientPrivateKey;
- }
-
- /**
- * Set subject match (deprecated). This is the substring to be matched against the subject of
- * the authentication server certificate.
- * @param subjectMatch substring to be matched
- * @deprecated in favor of altSubjectMatch
- */
- public void setSubjectMatch(String subjectMatch) {
- setFieldValue(SUBJECT_MATCH_KEY, subjectMatch);
- }
-
- /**
- * Get subject match (deprecated)
- * @return the subject match string
- * @deprecated in favor of altSubjectMatch
- */
- public String getSubjectMatch() {
- return getFieldValue(SUBJECT_MATCH_KEY);
- }
-
- /**
- * Set alternate subject match. This is the substring to be matched against the
- * alternate subject of the authentication server certificate.
- *
- * Note: If no alternate subject is set for an Enterprise configuration, either by not calling
- * this API, or by calling it with null, or not setting domain suffix match using the
- * {@link #setDomainSuffixMatch(String)}, then the server certificate validation is incomplete -
- * which means that the connection is not secure.
- *
- * @param altSubjectMatch substring to be matched, for example
- * DNS:server.example.com;EMAIL:server@example.com
- */
- public void setAltSubjectMatch(String altSubjectMatch) {
- setFieldValue(ALTSUBJECT_MATCH_KEY, altSubjectMatch);
- }
-
- /**
- * Get alternate subject match
- * @return the alternate subject match string
- */
- public String getAltSubjectMatch() {
- return getFieldValue(ALTSUBJECT_MATCH_KEY);
- }
-
- /**
- * Set the domain_suffix_match directive on wpa_supplicant. This is the parameter to use
- * for Hotspot 2.0 defined matching of AAA server certs per WFA HS2.0 spec, section 7.3.3.2,
- * second paragraph.
- *
- * <p>From wpa_supplicant documentation:
- * <p>Constraint for server domain name. If set, this FQDN is used as a suffix match requirement
- * for the AAAserver certificate in SubjectAltName dNSName element(s). If a matching dNSName is
- * found, this constraint is met.
- * <p>Suffix match here means that the host/domain name is compared one label at a time starting
- * from the top-level domain and all the labels in domain_suffix_match shall be included in the
- * certificate. The certificate may include additional sub-level labels in addition to the
- * required labels.
- * <p>More than one match string can be provided by using semicolons to separate the strings
- * (e.g., example.org;example.com). When multiple strings are specified, a match with any one of
- * the values is considered a sufficient match for the certificate, i.e., the conditions are
- * ORed ogether.
- * <p>For example, domain_suffix_match=example.com would match test.example.com but would not
- * match test-example.com.
- *
- * Note: If no domain suffix is set for an Enterprise configuration, either by not calling this
- * API, or by calling it with null, or not setting alternate subject match using the
- * {@link #setAltSubjectMatch(String)}, then the server certificate
- * validation is incomplete - which means that the connection is not secure.
- *
- * @param domain The domain value
- */
- public void setDomainSuffixMatch(String domain) {
- setFieldValue(DOM_SUFFIX_MATCH_KEY, domain);
- }
-
- /**
- * Get the domain_suffix_match value. See setDomSuffixMatch.
- * @return The domain value.
- */
- public String getDomainSuffixMatch() {
- return getFieldValue(DOM_SUFFIX_MATCH_KEY);
- }
-
- /**
- * Set realm for Passpoint credential; realm identifies a set of networks where your
- * Passpoint credential can be used
- * @param realm the realm
- */
- public void setRealm(String realm) {
- setFieldValue(REALM_KEY, realm);
- }
-
- /**
- * Get realm for Passpoint credential; see {@link #setRealm(String)} for more information
- * @return the realm
- */
- public String getRealm() {
- return getFieldValue(REALM_KEY);
- }
-
- /**
- * Set plmn (Public Land Mobile Network) of the provider of Passpoint credential
- * @param plmn the plmn value derived from mcc (mobile country code) & mnc (mobile network code)
- */
- public void setPlmn(String plmn) {
- setFieldValue(PLMN_KEY, plmn);
- }
-
- /**
- * Get plmn (Public Land Mobile Network) for Passpoint credential; see {@link #setPlmn
- * (String)} for more information
- * @return the plmn
- */
- public String getPlmn() {
- return getFieldValue(PLMN_KEY);
- }
-
- /** See {@link WifiConfiguration#getKeyIdForCredentials} @hide */
- public String getKeyId(WifiEnterpriseConfig current) {
- // If EAP method is not initialized, use current config details
- if (mEapMethod == Eap.NONE) {
- return (current != null) ? current.getKeyId(null) : EMPTY_VALUE;
- }
- if (!isEapMethodValid()) {
- return EMPTY_VALUE;
- }
- return Eap.strings[mEapMethod] + "_" + Phase2.strings[mPhase2Method];
- }
-
- private String removeDoubleQuotes(String string) {
- if (TextUtils.isEmpty(string)) return "";
- int length = string.length();
- if ((length > 1) && (string.charAt(0) == '"')
- && (string.charAt(length - 1) == '"')) {
- return string.substring(1, length - 1);
- }
- return string;
- }
-
- private String convertToQuotedString(String string) {
- return "\"" + string + "\"";
- }
-
- /**
- * Returns the index at which the toBeFound string is found in the array.
- * @param arr array of strings
- * @param toBeFound string to be found
- * @param defaultIndex default index to be returned when string is not found
- * @return the index into array
- */
- private int getStringIndex(String arr[], String toBeFound, int defaultIndex) {
- if (TextUtils.isEmpty(toBeFound)) return defaultIndex;
- for (int i = 0; i < arr.length; i++) {
- if (toBeFound.equals(arr[i])) return i;
- }
- return defaultIndex;
- }
-
- /**
- * Returns the field value for the key with prefix removed.
- * @param key into the hash
- * @param prefix is the prefix that the value may have
- * @return value
- * @hide
- */
- private String getFieldValue(String key, String prefix) {
- // TODO: Should raise an exception if |key| is EAP_KEY or PHASE2_KEY since
- // neither of these keys should be retrieved in this manner.
- String value = mFields.get(key);
- // Uninitialized or known to be empty after reading from supplicant
- if (TextUtils.isEmpty(value) || EMPTY_VALUE.equals(value)) return "";
-
- value = removeDoubleQuotes(value);
- if (value.startsWith(prefix)) {
- return value.substring(prefix.length());
- } else {
- return value;
- }
- }
-
- /**
- * Returns the field value for the key.
- * @param key into the hash
- * @return value
- * @hide
- */
- public String getFieldValue(String key) {
- return getFieldValue(key, "");
- }
-
- /**
- * Set a value with an optional prefix at key
- * @param key into the hash
- * @param value to be set
- * @param prefix an optional value to be prefixed to actual value
- * @hide
- */
- private void setFieldValue(String key, String value, String prefix) {
- // TODO: Should raise an exception if |key| is EAP_KEY or PHASE2_KEY since
- // neither of these keys should be set in this manner.
- if (TextUtils.isEmpty(value)) {
- mFields.put(key, EMPTY_VALUE);
- } else {
- String valueToSet;
- if (!UNQUOTED_KEYS.contains(key)) {
- valueToSet = convertToQuotedString(prefix + value);
- } else {
- valueToSet = prefix + value;
- }
- mFields.put(key, valueToSet);
- }
- }
-
- /**
- * Set a value at key
- * @param key into the hash
- * @param value to be set
- * @hide
- */
- public void setFieldValue(String key, String value) {
- setFieldValue(key, value, "");
- }
-
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- for (String key : mFields.keySet()) {
- // Don't display password in toString().
- String value = PASSWORD_KEY.equals(key) ? "<removed>" : mFields.get(key);
- sb.append(key).append(" ").append(value).append("\n");
- }
- if (mEapMethod >= 0 && mEapMethod < Eap.strings.length) {
- sb.append("eap_method: ").append(Eap.strings[mEapMethod]).append("\n");
- }
- if (mPhase2Method > 0 && mPhase2Method < Phase2.strings.length) {
- sb.append("phase2_method: ").append(Phase2.strings[mPhase2Method]).append("\n");
- }
- sb.append(" ocsp: ").append(mOcsp).append("\n");
- return sb.toString();
- }
-
- /**
- * Returns whether the EAP method data is valid, i.e., whether mEapMethod and mPhase2Method
- * are valid indices into {@code Eap.strings[]} and {@code Phase2.strings[]} respectively.
- */
- private boolean isEapMethodValid() {
- if (mEapMethod == Eap.NONE) {
- Log.e(TAG, "WiFi enterprise configuration is invalid as it supplies no EAP method.");
- return false;
- }
- if (mEapMethod < 0 || mEapMethod >= Eap.strings.length) {
- Log.e(TAG, "mEapMethod is invald for WiFi enterprise configuration: " + mEapMethod);
- return false;
- }
- if (mPhase2Method < 0 || mPhase2Method >= Phase2.strings.length) {
- Log.e(TAG, "mPhase2Method is invald for WiFi enterprise configuration: "
- + mPhase2Method);
- return false;
- }
- return true;
- }
-
- /**
- * Check if certificate was installed by an app, or manually (not by an app). If true,
- * certificate and keys will be removed from key storage when this network is removed. If not,
- * then certificates and keys remain persistent until the user manually removes them.
- *
- * @return true if certificate was installed by an app, false if certificate was installed
- * manually by the user.
- * @hide
- */
- public boolean isAppInstalledDeviceKeyAndCert() {
- return mIsAppInstalledDeviceKeyAndCert;
- }
-
- /**
- * Initialize the value of the app installed device key and cert flag.
- *
- * @param isAppInstalledDeviceKeyAndCert true or false
- * @hide
- */
- public void initIsAppInstalledDeviceKeyAndCert(boolean isAppInstalledDeviceKeyAndCert) {
- mIsAppInstalledDeviceKeyAndCert = isAppInstalledDeviceKeyAndCert;
- }
-
- /**
- * Check if CA certificate was installed by an app, or manually (not by an app). If true,
- * CA certificate will be removed from key storage when this network is removed. If not,
- * then certificates and keys remain persistent until the user manually removes them.
- *
- * @return true if CA certificate was installed by an app, false if CA certificate was installed
- * manually by the user.
- * @hide
- */
- public boolean isAppInstalledCaCert() {
- return mIsAppInstalledCaCert;
- }
-
- /**
- * Initialize the value of the app installed root CA cert flag.
- *
- * @param isAppInstalledCaCert true or false
- * @hide
- */
- public void initIsAppInstalledCaCert(boolean isAppInstalledCaCert) {
- mIsAppInstalledCaCert = isAppInstalledCaCert;
- }
-
- /**
- * Set the OCSP type.
- * @param ocsp is one of {@link ##OCSP_NONE}, {@link #OCSP_REQUEST_CERT_STATUS},
- * {@link #OCSP_REQUIRE_CERT_STATUS} or
- * {@link #OCSP_REQUIRE_ALL_NON_TRUSTED_CERTS_STATUS}
- * @throws IllegalArgumentException if the OCSP type is invalid
- * @hide
- */
- @SystemApi
- public void setOcsp(@Ocsp int ocsp) {
- if (ocsp >= OCSP_NONE && ocsp <= OCSP_REQUIRE_ALL_NON_TRUSTED_CERTS_STATUS) {
- mOcsp = ocsp;
- } else {
- throw new IllegalArgumentException("Invalid OCSP type.");
- }
- }
-
- /**
- * Get the OCSP type.
- * @hide
- */
- @SystemApi
- public @Ocsp int getOcsp() {
- return mOcsp;
- }
-
- /**
- * Utility method to determine whether the configuration's authentication method is SIM-based.
- *
- * @return true if the credential information requires SIM card for current authentication
- * method, otherwise it returns false.
- */
- public boolean isAuthenticationSimBased() {
- if (mEapMethod == Eap.SIM || mEapMethod == Eap.AKA || mEapMethod == Eap.AKA_PRIME) {
- return true;
- }
- if (mEapMethod == Eap.PEAP) {
- return mPhase2Method == Phase2.SIM || mPhase2Method == Phase2.AKA
- || mPhase2Method == Phase2.AKA_PRIME;
- }
- return false;
- }
-
- /**
- * Set the WAPI certificate suite name on wpa_supplicant.
- *
- * If this field is not specified, WAPI-CERT uses ASU ID from WAI packet
- * as the certificate suite name automatically.
- *
- * @param wapiCertSuite The name for WAPI certificate suite, or empty string to clear.
- * @hide
- */
- @SystemApi
- public void setWapiCertSuite(@NonNull String wapiCertSuite) {
- setFieldValue(WAPI_CERT_SUITE_KEY, wapiCertSuite);
- }
-
- /**
- * Get the WAPI certificate suite name
- * @return the certificate suite name
- * @hide
- */
- @NonNull
- @SystemApi
- public String getWapiCertSuite() {
- return getFieldValue(WAPI_CERT_SUITE_KEY);
- }
-
- /**
- * Method determines whether the Enterprise configuration is insecure. An insecure
- * configuration is one where EAP method requires a CA certification, i.e. PEAP, TLS, or
- * TTLS, and any of the following conditions are met:
- * - Both certificate and CA path are not configured.
- * - Both alternative subject match and domain suffix match are not set.
- *
- * Note: this method does not exhaustively check security of the configuration - i.e. a return
- * value of {@code false} is not a guarantee that the configuration is secure.
- * @hide
- */
- public boolean isInsecure() {
- if (mEapMethod != Eap.PEAP && mEapMethod != Eap.TLS && mEapMethod != Eap.TTLS) {
- return false;
- }
- if (TextUtils.isEmpty(getAltSubjectMatch())
- && TextUtils.isEmpty(getDomainSuffixMatch())) {
- // Both subject and domain match are not set, it's insecure.
- return true;
- }
- if (mIsAppInstalledCaCert) {
- // CA certificate is installed by App, it's secure.
- return false;
- }
- if (getCaCertificateAliases() != null) {
- // CA certificate alias from keyStore is set, it's secure.
- return false;
- }
- return TextUtils.isEmpty(getCaPath());
- }
-
- /**
- * Check if a given certificate Get the Suite-B cipher from the certificate
- *
- * @param x509Certificate Certificate to process
- * @return true if the certificate OID matches the Suite-B requirements for RSA or ECDSA
- * certificates, or false otherwise.
- * @hide
- */
- public static boolean isSuiteBCipherCert(@Nullable X509Certificate x509Certificate) {
- if (x509Certificate == null) {
- return false;
- }
- final String sigAlgOid = x509Certificate.getSigAlgOID();
-
- // Wi-Fi alliance requires the use of both ECDSA secp384r1 and RSA 3072 certificates
- // in WPA3-Enterprise 192-bit security networks, which are also known as Suite-B-192
- // networks, even though NSA Suite-B-192 mandates ECDSA only. The use of the term
- // Suite-B was already coined in the IEEE 802.11-2016 specification for
- // AKM 00-0F-AC but the test plan for WPA3-Enterprise 192-bit for APs mandates
- // support for both RSA and ECDSA, and for STAs it mandates ECDSA and optionally
- // RSA. In order to be compatible with all WPA3-Enterprise 192-bit deployments,
- // we are supporting both types here.
- if (sigAlgOid.equals("1.2.840.113549.1.1.12")) {
- // sha384WithRSAEncryption
- if (x509Certificate.getPublicKey() instanceof RSAPublicKey) {
- final RSAPublicKey rsaPublicKey = (RSAPublicKey) x509Certificate.getPublicKey();
- if (rsaPublicKey.getModulus() != null
- && rsaPublicKey.getModulus().bitLength() >= 3072) {
- return true;
- }
- }
- } else if (sigAlgOid.equals("1.2.840.10045.4.3.3")) {
- // ecdsa-with-SHA384
- if (x509Certificate.getPublicKey() instanceof ECPublicKey) {
- final ECPublicKey ecPublicKey = (ECPublicKey) x509Certificate.getPublicKey();
- final ECParameterSpec ecParameterSpec = ecPublicKey.getParams();
-
- if (ecParameterSpec != null && ecParameterSpec.getOrder() != null
- && ecParameterSpec.getOrder().bitLength() >= 384) {
- return true;
- }
- }
- }
- return false;
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiFrameworkInitializer.java b/wifi/java/android/net/wifi/WifiFrameworkInitializer.java
deleted file mode 100644
index 1507199b0264..000000000000
--- a/wifi/java/android/net/wifi/WifiFrameworkInitializer.java
+++ /dev/null
@@ -1,121 +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 android.net.wifi;
-
-import android.annotation.SystemApi;
-import android.app.SystemServiceRegistry;
-import android.content.Context;
-import android.net.wifi.aware.IWifiAwareManager;
-import android.net.wifi.aware.WifiAwareManager;
-import android.net.wifi.p2p.IWifiP2pManager;
-import android.net.wifi.p2p.WifiP2pManager;
-import android.net.wifi.rtt.IWifiRttManager;
-import android.net.wifi.rtt.WifiRttManager;
-import android.os.HandlerThread;
-import android.os.Looper;
-
-/**
- * Class for performing registration for all Wifi services.
- *
- * @hide
- */
-@SystemApi
-public class WifiFrameworkInitializer {
-
- /**
- * A class implementing the lazy holder idiom: the unique static instance
- * of {@link #INSTANCE} is instantiated in a thread-safe way (guaranteed by
- * the language specs) the first time that NoPreloadHolder is referenced in getInstanceLooper().
- *
- * This is necessary because we can't spawn a new thread in {@link #registerServiceWrappers()}.
- * {@link #registerServiceWrappers()} is called during the Zygote phase, which disallows
- * spawning new threads. Naming the class "NoPreloadHolder" ensures that the classloader will
- * not preload this class, inadvertently spawning the thread too early.
- */
- private static class NoPreloadHolder {
- private static final HandlerThread INSTANCE = createInstance();
-
- private static HandlerThread createInstance() {
- HandlerThread thread = new HandlerThread("WifiManagerThread");
- thread.start();
- return thread;
- }
- }
-
- private static Looper getInstanceLooper() {
- return NoPreloadHolder.INSTANCE.getLooper();
- }
-
- private WifiFrameworkInitializer() {}
-
- /**
- * Called by {@link SystemServiceRegistry}'s static initializer and registers all Wifi services
- * to {@link Context}, so that {@link Context#getSystemService} can return them.
- *
- * @throws IllegalStateException if this is called from anywhere besides
- * {@link SystemServiceRegistry}
- */
- public static void registerServiceWrappers() {
- SystemServiceRegistry.registerContextAwareService(
- Context.WIFI_SERVICE,
- WifiManager.class,
- (context, serviceBinder) -> {
- IWifiManager service = IWifiManager.Stub.asInterface(serviceBinder);
- return new WifiManager(context, service, getInstanceLooper());
- }
- );
- SystemServiceRegistry.registerStaticService(
- Context.WIFI_P2P_SERVICE,
- WifiP2pManager.class,
- serviceBinder -> {
- IWifiP2pManager service = IWifiP2pManager.Stub.asInterface(serviceBinder);
- return new WifiP2pManager(service);
- }
- );
- SystemServiceRegistry.registerContextAwareService(
- Context.WIFI_AWARE_SERVICE,
- WifiAwareManager.class,
- (context, serviceBinder) -> {
- IWifiAwareManager service = IWifiAwareManager.Stub.asInterface(serviceBinder);
- return new WifiAwareManager(context, service);
- }
- );
- SystemServiceRegistry.registerContextAwareService(
- Context.WIFI_SCANNING_SERVICE,
- WifiScanner.class,
- (context, serviceBinder) -> {
- IWifiScanner service = IWifiScanner.Stub.asInterface(serviceBinder);
- return new WifiScanner(context, service, getInstanceLooper());
- }
- );
- SystemServiceRegistry.registerContextAwareService(
- Context.WIFI_RTT_RANGING_SERVICE,
- WifiRttManager.class,
- (context, serviceBinder) -> {
- IWifiRttManager service = IWifiRttManager.Stub.asInterface(serviceBinder);
- return new WifiRttManager(context, service);
- }
- );
- SystemServiceRegistry.registerContextAwareService(
- Context.WIFI_RTT_SERVICE,
- RttManager.class,
- context -> {
- WifiRttManager wifiRttManager = context.getSystemService(WifiRttManager.class);
- return new RttManager(context, wifiRttManager);
- }
- );
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiInfo.java b/wifi/java/android/net/wifi/WifiInfo.java
deleted file mode 100644
index 7175567f5973..000000000000
--- a/wifi/java/android/net/wifi/WifiInfo.java
+++ /dev/null
@@ -1,1209 +0,0 @@
-/*
- * Copyright (C) 2008 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.annotation.IntRange;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.net.NetworkInfo.DetailedState;
-import android.os.Build;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.telephony.SubscriptionManager;
-import android.text.TextUtils;
-
-import com.android.modules.utils.build.SdkLevel;
-import com.android.net.module.util.Inet4AddressUtils;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.EnumMap;
-import java.util.Locale;
-
-/**
- * Describes the state of any Wi-Fi connection that is active or
- * is in the process of being set up.
- */
-public class WifiInfo implements Parcelable {
- private static final String TAG = "WifiInfo";
- /**
- * This is the map described in the Javadoc comment above. The positions
- * of the elements of the array must correspond to the ordinal values
- * of <code>DetailedState</code>.
- */
- private static final EnumMap<SupplicantState, DetailedState> stateMap =
- new EnumMap<SupplicantState, DetailedState>(SupplicantState.class);
-
- /**
- * Default MAC address reported to a client that does not have the
- * android.permission.LOCAL_MAC_ADDRESS permission.
- *
- * @hide
- */
- @SystemApi
- public static final String DEFAULT_MAC_ADDRESS = "02:00:00:00:00:00";
-
- static {
- stateMap.put(SupplicantState.DISCONNECTED, DetailedState.DISCONNECTED);
- stateMap.put(SupplicantState.INTERFACE_DISABLED, DetailedState.DISCONNECTED);
- stateMap.put(SupplicantState.INACTIVE, DetailedState.IDLE);
- stateMap.put(SupplicantState.SCANNING, DetailedState.SCANNING);
- stateMap.put(SupplicantState.AUTHENTICATING, DetailedState.CONNECTING);
- stateMap.put(SupplicantState.ASSOCIATING, DetailedState.CONNECTING);
- stateMap.put(SupplicantState.ASSOCIATED, DetailedState.CONNECTING);
- stateMap.put(SupplicantState.FOUR_WAY_HANDSHAKE, DetailedState.AUTHENTICATING);
- stateMap.put(SupplicantState.GROUP_HANDSHAKE, DetailedState.AUTHENTICATING);
- stateMap.put(SupplicantState.COMPLETED, DetailedState.OBTAINING_IPADDR);
- stateMap.put(SupplicantState.DORMANT, DetailedState.DISCONNECTED);
- stateMap.put(SupplicantState.UNINITIALIZED, DetailedState.IDLE);
- stateMap.put(SupplicantState.INVALID, DetailedState.FAILED);
- }
-
- private SupplicantState mSupplicantState;
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- private String mBSSID;
- @UnsupportedAppUsage
- private WifiSsid mWifiSsid;
- private int mNetworkId;
-
- /**
- * Used to indicate that the RSSI is invalid, for example if no RSSI measurements are available
- * yet.
- * @hide
- */
- @SystemApi
- public static final int INVALID_RSSI = -127;
-
- /** @hide **/
- public static final int MIN_RSSI = -126;
-
- /** @hide **/
- public static final int MAX_RSSI = 200;
-
-
- /**
- * Received Signal Strength Indicator
- */
- private int mRssi;
-
- /**
- * Wi-Fi standard for the connection
- */
- private @WifiAnnotations.WifiStandard int mWifiStandard;
-
- /**
- * The unit in which links speeds are expressed.
- */
- public static final String LINK_SPEED_UNITS = "Mbps";
- private int mLinkSpeed;
-
- /**
- * Constant for unknown link speed.
- */
- public static final int LINK_SPEED_UNKNOWN = -1;
-
- /**
- * Tx(transmit) Link speed in Mbps
- */
- private int mTxLinkSpeed;
-
- /**
- * Max supported Tx(transmit) link speed in Mbps
- */
- private int mMaxSupportedTxLinkSpeed;
-
- /**
- * Rx(receive) Link speed in Mbps
- */
- private int mRxLinkSpeed;
-
- /**
- * Max supported Rx(receive) link speed in Mbps
- */
- private int mMaxSupportedRxLinkSpeed;
-
- /**
- * Frequency in MHz
- */
- public static final String FREQUENCY_UNITS = "MHz";
- private int mFrequency;
-
- @UnsupportedAppUsage
- private InetAddress mIpAddress;
- @UnsupportedAppUsage
- private String mMacAddress = DEFAULT_MAC_ADDRESS;
-
- /**
- * Whether the network is ephemeral or not.
- */
- private boolean mEphemeral;
-
- /**
- * Whether the network is trusted or not.
- */
- private boolean mTrusted;
-
- /**
- * Whether the network is oem paid or not.
- */
- private boolean mOemPaid;
-
- /**
- * Whether the network is oem private or not.
- */
- private boolean mOemPrivate;
-
- /**
- * Whether the network is a carrier merged network.
- */
- private boolean mCarrierMerged;
-
- /**
- * OSU (Online Sign Up) AP for Passpoint R2.
- */
- private boolean mOsuAp;
-
- /**
- * Fully qualified domain name of a Passpoint configuration
- */
- private String mFqdn;
-
- /**
- * Name of Passpoint credential provider
- */
- private String mProviderFriendlyName;
-
- /**
- * If connected to a network suggestion or specifier, store the package name of the app,
- * else null.
- */
- private String mRequestingPackageName;
-
- /**
- * Identify which Telephony subscription provides this network.
- */
- private int mSubscriptionId;
-
- /**
- * Running total count of lost (not ACKed) transmitted unicast data packets.
- * @hide
- */
- public long txBad;
- /**
- * Running total count of transmitted unicast data retry packets.
- * @hide
- */
- public long txRetries;
- /**
- * Running total count of successfully transmitted (ACKed) unicast data packets.
- * @hide
- */
- public long txSuccess;
- /**
- * Running total count of received unicast data packets.
- * @hide
- */
- public long rxSuccess;
-
- private double mLostTxPacketsPerSecond;
-
- /**
- * Average rate of lost transmitted packets, in units of packets per second.
- * @hide
- */
- @SystemApi
- public double getLostTxPacketsPerSecond() {
- return mLostTxPacketsPerSecond;
- }
-
- /** @hide */
- public void setLostTxPacketsPerSecond(double lostTxPacketsPerSecond) {
- mLostTxPacketsPerSecond = lostTxPacketsPerSecond;
- }
-
- private double mTxRetriedTxPacketsPerSecond;
-
- /**
- * Average rate of transmitted retry packets, in units of packets per second.
- * @hide
- */
- @SystemApi
- public double getRetriedTxPacketsPerSecond() {
- return mTxRetriedTxPacketsPerSecond;
- }
-
- /** @hide */
- public void setRetriedTxPacketsRate(double txRetriedTxPacketsPerSecond) {
- mTxRetriedTxPacketsPerSecond = txRetriedTxPacketsPerSecond;
- }
-
- private double mSuccessfulTxPacketsPerSecond;
-
- /**
- * Average rate of successfully transmitted unicast packets, in units of packets per second.
- * @hide
- */
- @SystemApi
- public double getSuccessfulTxPacketsPerSecond() {
- return mSuccessfulTxPacketsPerSecond;
- }
-
- /** @hide */
- public void setSuccessfulTxPacketsPerSecond(double successfulTxPacketsPerSecond) {
- mSuccessfulTxPacketsPerSecond = successfulTxPacketsPerSecond;
- }
-
- private double mSuccessfulRxPacketsPerSecond;
-
- /**
- * Average rate of received unicast data packets, in units of packets per second.
- * @hide
- */
- @SystemApi
- public double getSuccessfulRxPacketsPerSecond() {
- return mSuccessfulRxPacketsPerSecond;
- }
-
- /** @hide */
- public void setSuccessfulRxPacketsPerSecond(double successfulRxPacketsPerSecond) {
- mSuccessfulRxPacketsPerSecond = successfulRxPacketsPerSecond;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public int score;
-
- /**
- * The current Wifi score.
- * NOTE: this value should only be used for debugging purposes. Do not rely on this value for
- * any computations. The meaning of this value can and will change at any time without warning.
- * @hide
- */
- @SystemApi
- public int getScore() {
- return score;
- }
-
- /** @hide */
- public void setScore(int score) {
- this.score = score;
- }
-
- /**
- * Flag indicating that AP has hinted that upstream connection is metered,
- * and sensitive to heavy data transfers.
- */
- private boolean mMeteredHint;
-
- /**
- * Passpoint unique key
- */
- private String mPasspointUniqueId;
-
- private boolean mVhtMax8SpatialStreamsSupport;
-
- private boolean mHe8ssCapableAp;
-
- /** @hide */
- @UnsupportedAppUsage
- public WifiInfo() {
- mWifiSsid = null;
- mBSSID = null;
- mNetworkId = -1;
- mSupplicantState = SupplicantState.UNINITIALIZED;
- mRssi = INVALID_RSSI;
- mLinkSpeed = LINK_SPEED_UNKNOWN;
- mFrequency = -1;
- mSubscriptionId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
- }
-
- /** @hide */
- public void reset() {
- setInetAddress(null);
- setBSSID(null);
- setSSID(null);
- setNetworkId(-1);
- setRssi(INVALID_RSSI);
- setLinkSpeed(LINK_SPEED_UNKNOWN);
- setTxLinkSpeedMbps(LINK_SPEED_UNKNOWN);
- setRxLinkSpeedMbps(LINK_SPEED_UNKNOWN);
- setMaxSupportedTxLinkSpeedMbps(LINK_SPEED_UNKNOWN);
- setMaxSupportedRxLinkSpeedMbps(LINK_SPEED_UNKNOWN);
- setFrequency(-1);
- setMeteredHint(false);
- setEphemeral(false);
- setTrusted(false);
- setOemPaid(false);
- setOemPrivate(false);
- setCarrierMerged(false);
- setOsuAp(false);
- setRequestingPackageName(null);
- setFQDN(null);
- setProviderFriendlyName(null);
- setPasspointUniqueId(null);
- setSubscriptionId(SubscriptionManager.INVALID_SUBSCRIPTION_ID);
- setHe8ssCapableAp(false);
- setVhtMax8SpatialStreamsSupport(false);
- txBad = 0;
- txSuccess = 0;
- rxSuccess = 0;
- txRetries = 0;
- mLostTxPacketsPerSecond = 0;
- mSuccessfulTxPacketsPerSecond = 0;
- mSuccessfulRxPacketsPerSecond = 0;
- mTxRetriedTxPacketsPerSecond = 0;
- score = 0;
- }
-
- /**
- * Copy constructor
- * @hide
- */
- public WifiInfo(WifiInfo source) {
- if (source != null) {
- mSupplicantState = source.mSupplicantState;
- mBSSID = source.mBSSID;
- mWifiSsid = source.mWifiSsid;
- mNetworkId = source.mNetworkId;
- mRssi = source.mRssi;
- mLinkSpeed = source.mLinkSpeed;
- mTxLinkSpeed = source.mTxLinkSpeed;
- mRxLinkSpeed = source.mRxLinkSpeed;
- mFrequency = source.mFrequency;
- mIpAddress = source.mIpAddress;
- mMacAddress = source.mMacAddress;
- mMeteredHint = source.mMeteredHint;
- mEphemeral = source.mEphemeral;
- mTrusted = source.mTrusted;
- mOemPaid = source.mOemPaid;
- mOemPrivate = source.mOemPrivate;
- mCarrierMerged = source.mCarrierMerged;
- mRequestingPackageName =
- source.mRequestingPackageName;
- mOsuAp = source.mOsuAp;
- mFqdn = source.mFqdn;
- mProviderFriendlyName = source.mProviderFriendlyName;
- mSubscriptionId = source.mSubscriptionId;
- mVhtMax8SpatialStreamsSupport = source.mVhtMax8SpatialStreamsSupport;
- mHe8ssCapableAp = source.mHe8ssCapableAp;
- txBad = source.txBad;
- txRetries = source.txRetries;
- txSuccess = source.txSuccess;
- rxSuccess = source.rxSuccess;
- mLostTxPacketsPerSecond = source.mLostTxPacketsPerSecond;
- mTxRetriedTxPacketsPerSecond = source.mTxRetriedTxPacketsPerSecond;
- mSuccessfulTxPacketsPerSecond = source.mSuccessfulTxPacketsPerSecond;
- mSuccessfulRxPacketsPerSecond = source.mSuccessfulRxPacketsPerSecond;
- score = source.score;
- mWifiStandard = source.mWifiStandard;
- mMaxSupportedTxLinkSpeed = source.mMaxSupportedTxLinkSpeed;
- mMaxSupportedRxLinkSpeed = source.mMaxSupportedRxLinkSpeed;
- mPasspointUniqueId = source.mPasspointUniqueId;
- }
- }
-
- /** Builder for WifiInfo */
- public static final class Builder {
- private final WifiInfo mWifiInfo = new WifiInfo();
-
- /**
- * Set the SSID, in the form of a raw byte array.
- * @see WifiInfo#getSSID()
- */
- @NonNull
- public Builder setSsid(@NonNull byte[] ssid) {
- mWifiInfo.setSSID(WifiSsid.createFromByteArray(ssid));
- return this;
- }
-
- /**
- * Set the BSSID.
- * @see WifiInfo#getBSSID()
- */
- @NonNull
- public Builder setBssid(@NonNull String bssid) {
- mWifiInfo.setBSSID(bssid);
- return this;
- }
-
- /**
- * Set the RSSI, in dBm.
- * @see WifiInfo#getRssi()
- */
- @NonNull
- public Builder setRssi(int rssi) {
- mWifiInfo.setRssi(rssi);
- return this;
- }
-
- /**
- * Set the network ID.
- * @see WifiInfo#getNetworkId()
- */
- @NonNull
- public Builder setNetworkId(int networkId) {
- mWifiInfo.setNetworkId(networkId);
- return this;
- }
-
- /**
- * Build a WifiInfo object.
- */
- @NonNull
- public WifiInfo build() {
- return new WifiInfo(mWifiInfo);
- }
- }
-
- /** @hide */
- public void setSSID(WifiSsid wifiSsid) {
- mWifiSsid = wifiSsid;
- }
-
- /**
- * Returns the service set identifier (SSID) of the current 802.11 network.
- * <p>
- * If the SSID can be decoded as UTF-8, it will be returned surrounded by double
- * quotation marks. Otherwise, it is returned as a string of hex digits.
- * The SSID may be {@link WifiManager#UNKNOWN_SSID}, if there is no network currently connected
- * or if the caller has insufficient permissions to access the SSID.
- * </p>
- * <p>
- * Prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}, this method
- * always returned the SSID with no quotes around it.
- * </p>
- *
- * @return the SSID.
- */
- public String getSSID() {
- if (mWifiSsid != null) {
- String unicode = mWifiSsid.toString();
- if (!TextUtils.isEmpty(unicode)) {
- return "\"" + unicode + "\"";
- } else {
- String hex = mWifiSsid.getHexString();
- return (hex != null) ? hex : WifiManager.UNKNOWN_SSID;
- }
- }
- return WifiManager.UNKNOWN_SSID;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public WifiSsid getWifiSsid() {
- return mWifiSsid;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setBSSID(String BSSID) {
- mBSSID = BSSID;
- }
-
- /**
- * Return the basic service set identifier (BSSID) of the current access point.
- * <p>
- * The BSSID may be
- * <lt>{@code null}, if there is no network currently connected.</lt>
- * <lt>{@code "02:00:00:00:00:00"}, if the caller has insufficient permissions to access the
- * BSSID.<lt>
- * </p>
- *
- * @return the BSSID, in the form of a six-byte MAC address: {@code XX:XX:XX:XX:XX:XX}
- */
- public String getBSSID() {
- return mBSSID;
- }
-
- /**
- * Returns the received signal strength indicator of the current 802.11
- * network, in dBm.
- *
- * <p>Use {@link android.net.wifi.WifiManager#calculateSignalLevel} to convert this number into
- * an absolute signal level which can be displayed to a user.
- *
- * @return the RSSI.
- */
- public int getRssi() {
- return mRssi;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setRssi(int rssi) {
- if (rssi < INVALID_RSSI)
- rssi = INVALID_RSSI;
- if (rssi > MAX_RSSI)
- rssi = MAX_RSSI;
- mRssi = rssi;
- }
-
- /**
- * Sets the Wi-Fi standard
- * @hide
- */
- public void setWifiStandard(@WifiAnnotations.WifiStandard int wifiStandard) {
- mWifiStandard = wifiStandard;
- }
-
- /**
- * Get connection Wi-Fi standard
- * @return the connection Wi-Fi standard
- */
- public @WifiAnnotations.WifiStandard int getWifiStandard() {
- return mWifiStandard;
- }
-
- /**
- * Returns the current link speed in {@link #LINK_SPEED_UNITS}.
- * @return the link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is unknown.
- * @see #LINK_SPEED_UNITS
- * @see #LINK_SPEED_UNKNOWN
- */
- public int getLinkSpeed() {
- return mLinkSpeed;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setLinkSpeed(int linkSpeed) {
- mLinkSpeed = linkSpeed;
- }
-
- /**
- * Returns the current transmit link speed in Mbps.
- * @return the Tx link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is unknown.
- * @see #LINK_SPEED_UNKNOWN
- */
- @IntRange(from = -1)
- public int getTxLinkSpeedMbps() {
- return mTxLinkSpeed;
- }
-
- /**
- * Returns the maximum supported transmit link speed in Mbps
- * @return the max supported tx link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is
- * unknown. @see #LINK_SPEED_UNKNOWN
- */
- public int getMaxSupportedTxLinkSpeedMbps() {
- return mMaxSupportedTxLinkSpeed;
- }
-
- /**
- * Update the last transmitted packet bit rate in Mbps.
- * @hide
- */
- public void setTxLinkSpeedMbps(int txLinkSpeed) {
- mTxLinkSpeed = txLinkSpeed;
- }
-
- /**
- * Set the maximum supported transmit link speed in Mbps
- * @hide
- */
- public void setMaxSupportedTxLinkSpeedMbps(int maxSupportedTxLinkSpeed) {
- mMaxSupportedTxLinkSpeed = maxSupportedTxLinkSpeed;
- }
-
- /**
- * Returns the current receive link speed in Mbps.
- * @return the Rx link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is unknown.
- * @see #LINK_SPEED_UNKNOWN
- */
- @IntRange(from = -1)
- public int getRxLinkSpeedMbps() {
- return mRxLinkSpeed;
- }
-
- /**
- * Returns the maximum supported receive link speed in Mbps
- * @return the max supported Rx link speed or {@link #LINK_SPEED_UNKNOWN} if link speed is
- * unknown. @see #LINK_SPEED_UNKNOWN
- */
- public int getMaxSupportedRxLinkSpeedMbps() {
- return mMaxSupportedRxLinkSpeed;
- }
-
- /**
- * Update the last received packet bit rate in Mbps.
- * @hide
- */
- public void setRxLinkSpeedMbps(int rxLinkSpeed) {
- mRxLinkSpeed = rxLinkSpeed;
- }
-
- /**
- * Set the maximum supported receive link speed in Mbps
- * @hide
- */
- public void setMaxSupportedRxLinkSpeedMbps(int maxSupportedRxLinkSpeed) {
- mMaxSupportedRxLinkSpeed = maxSupportedRxLinkSpeed;
- }
-
- /**
- * Returns the current frequency in {@link #FREQUENCY_UNITS}.
- * @return the frequency.
- * @see #FREQUENCY_UNITS
- */
- public int getFrequency() {
- return mFrequency;
- }
-
- /** @hide */
- public void setFrequency(int frequency) {
- this.mFrequency = frequency;
- }
-
- /**
- * @hide
- */
- public boolean is24GHz() {
- return ScanResult.is24GHz(mFrequency);
- }
-
- /**
- * @hide
- */
- @UnsupportedAppUsage
- public boolean is5GHz() {
- return ScanResult.is5GHz(mFrequency);
- }
-
- /**
- * @hide
- */
- public boolean is6GHz() {
- return ScanResult.is6GHz(mFrequency);
- }
-
- /**
- * Record the MAC address of the WLAN interface
- * @param macAddress the MAC address in {@code XX:XX:XX:XX:XX:XX} form
- * @hide
- */
- @UnsupportedAppUsage
- public void setMacAddress(String macAddress) {
- this.mMacAddress = macAddress;
- }
-
- public String getMacAddress() {
- return mMacAddress;
- }
-
- /**
- * @return true if {@link #getMacAddress()} has a real MAC address.
- *
- * @hide
- */
- public boolean hasRealMacAddress() {
- return mMacAddress != null && !DEFAULT_MAC_ADDRESS.equals(mMacAddress);
- }
-
- /**
- * Indicates if we've dynamically detected this active network connection as
- * being metered.
- *
- * @see WifiConfiguration#isMetered(WifiConfiguration, WifiInfo)
- * @hide
- */
- public void setMeteredHint(boolean meteredHint) {
- mMeteredHint = meteredHint;
- }
-
- /** {@hide} */
- @UnsupportedAppUsage
- public boolean getMeteredHint() {
- return mMeteredHint;
- }
-
- /** {@hide} */
- public void setEphemeral(boolean ephemeral) {
- mEphemeral = ephemeral;
- }
-
- /**
- * Returns true if the current Wifi network is ephemeral, false otherwise.
- * An ephemeral network is a network that is temporary and not persisted in the system.
- * Ephemeral networks cannot be forgotten, only disabled with
- * {@link WifiManager#disableEphemeralNetwork(String)}.
- *
- * @hide
- */
- @SystemApi
- public boolean isEphemeral() {
- return mEphemeral;
- }
-
- /** {@hide} */
- public void setTrusted(boolean trusted) {
- mTrusted = trusted;
- }
-
- /**
- * Returns true if the current Wifi network is a trusted network, false otherwise.
- * @see WifiNetworkSuggestion.Builder#setUntrusted(boolean).
- * {@hide}
- */
- @SystemApi
- public boolean isTrusted() {
- return mTrusted;
- }
-
- /** {@hide} */
- public void setOemPaid(boolean oemPaid) {
- mOemPaid = oemPaid;
- }
-
- /**
- * Returns true if the current Wifi network is an oem paid network, false otherwise.
- * @see WifiNetworkSuggestion.Builder#setOemPaid(boolean).
- * {@hide}
- */
- @SystemApi
- public boolean isOemPaid() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mOemPaid;
- }
-
- /** {@hide} */
- public void setOemPrivate(boolean oemPrivate) {
- mOemPrivate = oemPrivate;
- }
-
- /**
- * Returns true if the current Wifi network is an oem private network, false otherwise.
- * @see WifiNetworkSuggestion.Builder#setOemPrivate(boolean).
- * {@hide}
- */
- @SystemApi
- public boolean isOemPrivate() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mOemPrivate;
- }
-
- /**
- * {@hide}
- */
- public void setCarrierMerged(boolean carrierMerged) {
- mCarrierMerged = carrierMerged;
- }
-
- /**
- * Returns true if the current Wifi network is a carrier merged network, false otherwise.
- * @see WifiNetworkSuggestion.Builder#setCarrierMerged(boolean).
- * {@hide}
- */
- @SystemApi
- public boolean isCarrierMerged() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mCarrierMerged;
- }
-
-
- /** {@hide} */
- public void setOsuAp(boolean osuAp) {
- mOsuAp = osuAp;
- }
-
- /** {@hide} */
- @SystemApi
- public boolean isOsuAp() {
- return mOsuAp;
- }
-
- /** {@hide} */
- @SystemApi
- public boolean isPasspointAp() {
- return mFqdn != null && mProviderFriendlyName != null;
- }
-
- /** {@hide} */
- public void setFQDN(@Nullable String fqdn) {
- mFqdn = fqdn;
- }
-
- /**
- * Returns the Fully Qualified Domain Name of the network if it is a Passpoint network.
- * <p>
- * The FQDN may be
- * <lt>{@code null} if no network currently connected, currently connected network is not
- * passpoint network or the caller has insufficient permissions to access the FQDN.</lt>
- * </p>
- */
- public @Nullable String getPasspointFqdn() {
- return mFqdn;
- }
-
- /** {@hide} */
- public void setProviderFriendlyName(@Nullable String providerFriendlyName) {
- mProviderFriendlyName = providerFriendlyName;
- }
-
- /**
- * Returns the Provider Friendly Name of the network if it is a Passpoint network.
- * <p>
- * The Provider Friendly Name may be
- * <lt>{@code null} if no network currently connected, currently connected network is not
- * passpoint network or the caller has insufficient permissions to access the Provider Friendly
- * Name. </lt>
- * </p>
- */
- public @Nullable String getPasspointProviderFriendlyName() {
- return mProviderFriendlyName;
- }
-
- /** {@hide} */
- public void setRequestingPackageName(@Nullable String packageName) {
- mRequestingPackageName = packageName;
- }
-
- /**
- * If this network was created in response to an app request (e.g. through Network Suggestion
- * or Network Specifier), return the package name of the app that made the request.
- * Null otherwise.
- * @hide
- */
- @SystemApi
- public @Nullable String getRequestingPackageName() {
- return mRequestingPackageName;
- }
-
- /** {@hide} */
- public void setSubscriptionId(int subId) {
- mSubscriptionId = subId;
- }
-
- /**
- * If this network is provisioned by a carrier, returns subscription Id corresponding to the
- * associated SIM on the device. If this network is not provisioned by a carrier, returns
- * {@link android.telephony.SubscriptionManager#INVALID_SUBSCRIPTION_ID}
- *
- * @see WifiNetworkSuggestion.Builder#setSubscriptionId(int)
- * @see android.telephony.SubscriptionInfo#getSubscriptionId()
- * {@hide}
- */
- @SystemApi
- public int getSubscriptionId() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mSubscriptionId;
- }
-
-
- /** @hide */
- @UnsupportedAppUsage
- public void setNetworkId(int id) {
- mNetworkId = id;
- }
-
- /**
- * Each configured network has a unique small integer ID, used to identify
- * the network. This method returns the ID for the currently connected network.
- * <p>
- * The networkId may be {@code -1} if there is no currently connected network or if the caller
- * has insufficient permissions to access the network ID.
- * </p>
- *
- * @return the network ID.
- */
- public int getNetworkId() {
- return mNetworkId;
- }
-
- /**
- * Return the detailed state of the supplicant's negotiation with an
- * access point, in the form of a {@link SupplicantState SupplicantState} object.
- * @return the current {@link SupplicantState SupplicantState}
- */
- public SupplicantState getSupplicantState() {
- return mSupplicantState;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setSupplicantState(SupplicantState state) {
- mSupplicantState = state;
- }
-
- /** @hide */
- public void setInetAddress(InetAddress address) {
- mIpAddress = address;
- }
-
- public int getIpAddress() {
- int result = 0;
- if (mIpAddress instanceof Inet4Address) {
- result = Inet4AddressUtils.inet4AddressToIntHTL((Inet4Address) mIpAddress);
- }
- return result;
- }
-
- /**
- * @return {@code true} if this network does not broadcast its SSID, so an
- * SSID-specific probe request must be used for scans.
- */
- public boolean getHiddenSSID() {
- if (mWifiSsid == null) return false;
- return mWifiSsid.isHidden();
- }
-
- /**
- * Map a supplicant state into a fine-grained network connectivity state.
- * @param suppState the supplicant state
- * @return the corresponding {@link DetailedState}
- */
- public static DetailedState getDetailedStateOf(SupplicantState suppState) {
- return stateMap.get(suppState);
- }
-
- /**
- * Set the <code>SupplicantState</code> from the string name
- * of the state.
- * @param stateName the name of the state, as a <code>String</code> returned
- * in an event sent by {@code wpa_supplicant}.
- */
- @UnsupportedAppUsage
- void setSupplicantState(String stateName) {
- mSupplicantState = valueOf(stateName);
- }
-
- static SupplicantState valueOf(String stateName) {
- if ("4WAY_HANDSHAKE".equalsIgnoreCase(stateName))
- return SupplicantState.FOUR_WAY_HANDSHAKE;
- else {
- try {
- return SupplicantState.valueOf(stateName.toUpperCase(Locale.ROOT));
- } catch (IllegalArgumentException e) {
- return SupplicantState.INVALID;
- }
- }
- }
-
- /** @hide */
- public void setVhtMax8SpatialStreamsSupport(boolean vhtMax8SpatialStreamsSupport) {
- mVhtMax8SpatialStreamsSupport = vhtMax8SpatialStreamsSupport;
- }
-
- /** @hide */
- public boolean isVhtMax8SpatialStreamsSupported() {
- return mVhtMax8SpatialStreamsSupport;
- }
-
- /** @hide */
- public void setHe8ssCapableAp(boolean he8ssCapableAp) {
- mHe8ssCapableAp = he8ssCapableAp;
- }
-
- /** @hide */
- public boolean isHe8ssCapableAp() {
- return mHe8ssCapableAp;
- }
-
- /**
- * Remove double quotes (") surrounding a SSID string, if present. Otherwise, return the
- * string unmodified. Return null if the input string was null.
- * @hide
- */
- @Nullable
- @SystemApi
- public static String sanitizeSsid(@Nullable String string) {
- return removeDoubleQuotes(string);
- }
-
- /** @hide */
- @UnsupportedAppUsage
- @Nullable
- public static String removeDoubleQuotes(@Nullable String string) {
- if (string == null) return null;
- final int length = string.length();
- if ((length > 1) && (string.charAt(0) == '"') && (string.charAt(length - 1) == '"')) {
- return string.substring(1, length - 1);
- }
- return string;
- }
-
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- String none = "<none>";
-
- sb.append("SSID: ").append(mWifiSsid == null ? WifiManager.UNKNOWN_SSID : mWifiSsid)
- .append(", BSSID: ").append(mBSSID == null ? none : mBSSID)
- .append(", MAC: ").append(mMacAddress == null ? none : mMacAddress)
- .append(", Supplicant state: ")
- .append(mSupplicantState == null ? none : mSupplicantState)
- .append(", HE Eight Max VHT Spatial Streams Supported AP: ").append(mHe8ssCapableAp)
- .append(", Eight Max VHT Spatial streams support: ").append(mVhtMax8SpatialStreamsSupport)
- .append(", Wi-Fi standard: ").append(mWifiStandard)
- .append(", RSSI: ").append(mRssi)
- .append(", Link speed: ").append(mLinkSpeed).append(LINK_SPEED_UNITS)
- .append(", Tx Link speed: ").append(mTxLinkSpeed).append(LINK_SPEED_UNITS)
- .append(", Max Supported Tx Link speed: ")
- .append(mMaxSupportedTxLinkSpeed).append(LINK_SPEED_UNITS)
- .append(", Rx Link speed: ").append(mRxLinkSpeed).append(LINK_SPEED_UNITS)
- .append(", Max Supported Rx Link speed: ")
- .append(mMaxSupportedRxLinkSpeed).append(LINK_SPEED_UNITS)
- .append(", Frequency: ").append(mFrequency).append(FREQUENCY_UNITS)
- .append(", Net ID: ").append(mNetworkId)
- .append(", Metered hint: ").append(mMeteredHint)
- .append(", score: ").append(Integer.toString(score));
- return sb.toString();
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mNetworkId);
- dest.writeInt(mRssi);
- dest.writeInt(mLinkSpeed);
- dest.writeInt(mTxLinkSpeed);
- dest.writeInt(mRxLinkSpeed);
- dest.writeInt(mFrequency);
- if (mIpAddress != null) {
- dest.writeByte((byte)1);
- dest.writeByteArray(mIpAddress.getAddress());
- } else {
- dest.writeByte((byte)0);
- }
- if (mWifiSsid != null) {
- dest.writeInt(1);
- mWifiSsid.writeToParcel(dest, flags);
- } else {
- dest.writeInt(0);
- }
- dest.writeString(mBSSID);
- dest.writeString(mMacAddress);
- dest.writeInt(mMeteredHint ? 1 : 0);
- dest.writeInt(mEphemeral ? 1 : 0);
- dest.writeInt(mTrusted ? 1 : 0);
- dest.writeInt(mOemPaid ? 1 : 0);
- dest.writeInt(mOemPrivate ? 1 : 0);
- dest.writeInt(mCarrierMerged ? 1 : 0);
- dest.writeInt(score);
- dest.writeLong(txSuccess);
- dest.writeDouble(mSuccessfulTxPacketsPerSecond);
- dest.writeLong(txRetries);
- dest.writeDouble(mTxRetriedTxPacketsPerSecond);
- dest.writeLong(txBad);
- dest.writeDouble(mLostTxPacketsPerSecond);
- dest.writeLong(rxSuccess);
- dest.writeDouble(mSuccessfulRxPacketsPerSecond);
- mSupplicantState.writeToParcel(dest, flags);
- dest.writeInt(mOsuAp ? 1 : 0);
- dest.writeString(mRequestingPackageName);
- dest.writeString(mFqdn);
- dest.writeString(mProviderFriendlyName);
- dest.writeInt(mVhtMax8SpatialStreamsSupport ? 1 : 0);
- dest.writeInt(mHe8ssCapableAp ? 1 : 0);
- dest.writeInt(mWifiStandard);
- dest.writeInt(mMaxSupportedTxLinkSpeed);
- dest.writeInt(mMaxSupportedRxLinkSpeed);
- dest.writeString(mPasspointUniqueId);
- dest.writeInt(mSubscriptionId);
- }
-
- /** Implement the Parcelable interface {@hide} */
- @UnsupportedAppUsage
- public static final @android.annotation.NonNull Creator<WifiInfo> CREATOR =
- new Creator<WifiInfo>() {
- public WifiInfo createFromParcel(Parcel in) {
- WifiInfo info = new WifiInfo();
- info.setNetworkId(in.readInt());
- info.setRssi(in.readInt());
- info.setLinkSpeed(in.readInt());
- info.setTxLinkSpeedMbps(in.readInt());
- info.setRxLinkSpeedMbps(in.readInt());
- info.setFrequency(in.readInt());
- if (in.readByte() == 1) {
- try {
- info.setInetAddress(InetAddress.getByAddress(in.createByteArray()));
- } catch (UnknownHostException e) {}
- }
- if (in.readInt() == 1) {
- info.mWifiSsid = WifiSsid.CREATOR.createFromParcel(in);
- }
- info.mBSSID = in.readString();
- info.mMacAddress = in.readString();
- info.mMeteredHint = in.readInt() != 0;
- info.mEphemeral = in.readInt() != 0;
- info.mTrusted = in.readInt() != 0;
- info.mOemPaid = in.readInt() != 0;
- info.mOemPrivate = in.readInt() != 0;
- info.mCarrierMerged = in.readInt() != 0;
- info.score = in.readInt();
- info.txSuccess = in.readLong();
- info.mSuccessfulTxPacketsPerSecond = in.readDouble();
- info.txRetries = in.readLong();
- info.mTxRetriedTxPacketsPerSecond = in.readDouble();
- info.txBad = in.readLong();
- info.mLostTxPacketsPerSecond = in.readDouble();
- info.rxSuccess = in.readLong();
- info.mSuccessfulRxPacketsPerSecond = in.readDouble();
- info.mSupplicantState = SupplicantState.CREATOR.createFromParcel(in);
- info.mOsuAp = in.readInt() != 0;
- info.mRequestingPackageName = in.readString();
- info.mFqdn = in.readString();
- info.mProviderFriendlyName = in.readString();
- info.mVhtMax8SpatialStreamsSupport = in.readInt() != 0;
- info.mHe8ssCapableAp = in.readInt() != 0;
- info.mWifiStandard = in.readInt();
- info.mMaxSupportedTxLinkSpeed = in.readInt();
- info.mMaxSupportedRxLinkSpeed = in.readInt();
- info.mPasspointUniqueId = in.readString();
- info.mSubscriptionId = in.readInt();
- return info;
- }
-
- public WifiInfo[] newArray(int size) {
- return new WifiInfo[size];
- }
- };
-
- /**
- * Set the Passpoint unique identifier for the current connection
- *
- * @param passpointUniqueId Unique identifier
- * @hide
- */
- public void setPasspointUniqueId(@Nullable String passpointUniqueId) {
- mPasspointUniqueId = passpointUniqueId;
- }
-
- /**
- * Get the Passpoint unique identifier for the current connection
- *
- * @return Passpoint unique identifier
- * @hide
- */
- public @Nullable String getPasspointUniqueId() {
- return mPasspointUniqueId;
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiManager.java b/wifi/java/android/net/wifi/WifiManager.java
deleted file mode 100644
index ccf3e01e327d..000000000000
--- a/wifi/java/android/net/wifi/WifiManager.java
+++ /dev/null
@@ -1,7185 +0,0 @@
-/*
- * Copyright (C) 2008 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 static android.Manifest.permission.ACCESS_FINE_LOCATION;
-import static android.Manifest.permission.ACCESS_WIFI_STATE;
-import static android.Manifest.permission.READ_WIFI_CREDENTIAL;
-
-import android.annotation.CallbackExecutor;
-import android.annotation.IntDef;
-import android.annotation.IntRange;
-import android.annotation.NonNull;
-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.app.ActivityManager;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.content.Context;
-import android.content.pm.ParceledListSlice;
-import android.net.ConnectivityManager;
-import android.net.DhcpInfo;
-import android.net.MacAddress;
-import android.net.Network;
-import android.net.NetworkStack;
-import android.net.wifi.hotspot2.IProvisioningCallback;
-import android.net.wifi.hotspot2.OsuProvider;
-import android.net.wifi.hotspot2.PasspointConfiguration;
-import android.net.wifi.hotspot2.ProvisioningCallback;
-import android.os.Binder;
-import android.os.Build;
-import android.os.Handler;
-import android.os.HandlerExecutor;
-import android.os.IBinder;
-import android.os.Looper;
-import android.os.RemoteException;
-import android.os.WorkSource;
-import android.os.connectivity.WifiActivityEnergyInfo;
-import android.telephony.SubscriptionInfo;
-import android.telephony.TelephonyManager;
-import android.text.TextUtils;
-import android.util.CloseGuard;
-import android.util.Log;
-import android.util.Pair;
-import android.util.SparseArray;
-
-import com.android.internal.annotations.GuardedBy;
-import com.android.internal.annotations.VisibleForTesting;
-import com.android.modules.utils.build.SdkLevel;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.ref.Reference;
-import java.lang.ref.WeakReference;
-import java.net.InetAddress;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.concurrent.Executor;
-
-/**
- * This class provides the primary API for managing all aspects of Wi-Fi
- * connectivity.
- * <p>
- * On releases before {@link android.os.Build.VERSION_CODES#N}, this object
- * should only be obtained from an {@linkplain Context#getApplicationContext()
- * application context}, and not from any other derived context to avoid memory
- * leaks within the calling process.
- * <p>
- * It deals with several categories of items:
- * </p>
- * <ul>
- * <li>The list of configured networks. The list can be viewed and updated, and
- * attributes of individual entries can be modified.</li>
- * <li>The currently active Wi-Fi network, if any. Connectivity can be
- * established or torn down, and dynamic information about the state of the
- * network can be queried.</li>
- * <li>Results of access point scans, containing enough information to make
- * decisions about what access point to connect to.</li>
- * <li>It defines the names of various Intent actions that are broadcast upon
- * any sort of change in Wi-Fi state.
- * </ul>
- * <p>
- * This is the API to use when performing Wi-Fi specific operations. To perform
- * operations that pertain to network connectivity at an abstract level, use
- * {@link android.net.ConnectivityManager}.
- * </p>
- */
-@SystemService(Context.WIFI_SERVICE)
-public class WifiManager {
-
- private static final String TAG = "WifiManager";
- // Supplicant error codes:
- /**
- * The error code if there was a problem authenticating.
- * @deprecated This is no longer supported.
- */
- @Deprecated
- public static final int ERROR_AUTHENTICATING = 1;
-
- /**
- * The reason code if there is no error during authentication.
- * It could also imply that there no authentication in progress,
- * this reason code also serves as a reset value.
- * @deprecated This is no longer supported.
- * @hide
- */
- @Deprecated
- public static final int ERROR_AUTH_FAILURE_NONE = 0;
-
- /**
- * The reason code if there was a timeout authenticating.
- * @deprecated This is no longer supported.
- * @hide
- */
- @Deprecated
- public static final int ERROR_AUTH_FAILURE_TIMEOUT = 1;
-
- /**
- * The reason code if there was a wrong password while
- * authenticating.
- * @deprecated This is no longer supported.
- * @hide
- */
- @Deprecated
- public static final int ERROR_AUTH_FAILURE_WRONG_PSWD = 2;
-
- /**
- * The reason code if there was EAP failure while
- * authenticating.
- * @deprecated This is no longer supported.
- * @hide
- */
- @Deprecated
- public static final int ERROR_AUTH_FAILURE_EAP_FAILURE = 3;
-
- /** @hide */
- public static final int NETWORK_SUGGESTIONS_MAX_PER_APP_LOW_RAM = 256;
-
- /** @hide */
- public static final int NETWORK_SUGGESTIONS_MAX_PER_APP_HIGH_RAM = 1024;
-
- /**
- * Reason code if all of the network suggestions were successfully added or removed.
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_SUCCESS = 0;
-
- /**
- * Reason code if there was an internal error in the platform while processing the addition or
- * removal of suggestions.
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL = 1;
-
- /**
- * Reason code if the user has disallowed "android:change_wifi_state" app-ops from the app.
- * @see android.app.AppOpsManager#unsafeCheckOp(String, int, String).
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_APP_DISALLOWED = 2;
-
- /**
- * Reason code if one or more of the network suggestions added already exists in platform's
- * database.
- * Note: this code will not be returned with Android 11 as in-place modification is allowed,
- * please check {@link #addNetworkSuggestions(List)}.
- * @see WifiNetworkSuggestion#equals(Object)
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE = 3;
-
- /**
- * Reason code if the number of network suggestions provided by the app crosses the max
- * threshold set per app.
- * The framework will reject all suggestions provided by {@link #addNetworkSuggestions(List)} if
- * the total size exceeds the limit.
- * @see #getMaxNumberOfNetworkSuggestionsPerApp()
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_EXCEEDS_MAX_PER_APP = 4;
-
- /**
- * Reason code if one or more of the network suggestions removed does not exist in platform's
- * database.
- * The framework won't remove any suggestions if one or more of suggestions provided
- * by {@link #removeNetworkSuggestions(List)} does not exist in database.
- * @see WifiNetworkSuggestion#equals(Object)
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID = 5;
-
- /**
- * Reason code if one or more of the network suggestions added is not allowed.
- * The framework will reject all suggestions provided by {@link #addNetworkSuggestions(List)}
- * if one or more of them is not allowed.
- * This error may be caused by suggestion is using SIM-based encryption method, but calling app
- * is not carrier privileged.
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_NOT_ALLOWED = 6;
-
- /**
- * Reason code if one or more of the network suggestions added is invalid. Framework will reject
- * all the suggestions in the list.
- * The framework will reject all suggestions provided by {@link #addNetworkSuggestions(List)}
- * if one or more of them is invalid.
- * Please use {@link WifiNetworkSuggestion.Builder} to create network suggestions.
- */
- public static final int STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_INVALID = 7;
-
- /** @hide */
- @IntDef(prefix = { "STATUS_NETWORK_SUGGESTIONS_" }, value = {
- STATUS_NETWORK_SUGGESTIONS_SUCCESS,
- STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL,
- STATUS_NETWORK_SUGGESTIONS_ERROR_APP_DISALLOWED,
- STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE,
- STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_EXCEEDS_MAX_PER_APP,
- STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID,
- STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_NOT_ALLOWED,
- STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_INVALID,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface NetworkSuggestionsStatusCode {}
-
- /**
- * Reason code if suggested network connection attempt failed with an unknown failure.
- */
- public static final int STATUS_SUGGESTION_CONNECTION_FAILURE_UNKNOWN = 0;
- /**
- * Reason code if suggested network connection attempt failed with association failure.
- */
- public static final int STATUS_SUGGESTION_CONNECTION_FAILURE_ASSOCIATION = 1;
- /**
- * Reason code if suggested network connection attempt failed with an authentication failure.
- */
- public static final int STATUS_SUGGESTION_CONNECTION_FAILURE_AUTHENTICATION = 2;
- /**
- * Reason code if suggested network connection attempt failed with an IP provision failure.
- */
- public static final int STATUS_SUGGESTION_CONNECTION_FAILURE_IP_PROVISIONING = 3;
-
- /** @hide */
- @IntDef(prefix = {"STATUS_SUGGESTION_CONNECTION_FAILURE_"},
- value = {STATUS_SUGGESTION_CONNECTION_FAILURE_UNKNOWN,
- STATUS_SUGGESTION_CONNECTION_FAILURE_ASSOCIATION,
- STATUS_SUGGESTION_CONNECTION_FAILURE_AUTHENTICATION,
- STATUS_SUGGESTION_CONNECTION_FAILURE_IP_PROVISIONING
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface SuggestionConnectionStatusCode {}
-
- /**
- * Status code if suggestion approval status is unknown, an App which hasn't made any
- * suggestions will get this code.
- */
- public static final int STATUS_SUGGESTION_APPROVAL_UNKNOWN = 0;
-
- /**
- * Status code if the calling app is still pending user approval for suggestions.
- */
- public static final int STATUS_SUGGESTION_APPROVAL_PENDING = 1;
-
- /**
- * Status code if the calling app got the user approval for suggestions.
- */
- public static final int STATUS_SUGGESTION_APPROVAL_APPROVED_BY_USER = 2;
-
- /**
- * Status code if the calling app suggestions were rejected by the user.
- */
- public static final int STATUS_SUGGESTION_APPROVAL_REJECTED_BY_USER = 3;
-
- /**
- * Status code if the calling app was approved by virtue of being a carrier privileged app.
- * @see TelephonyManager#hasCarrierPrivileges().
- */
- public static final int STATUS_SUGGESTION_APPROVAL_APPROVED_BY_CARRIER_PRIVILEGE = 4;
-
- /** @hide */
- @IntDef(prefix = {"STATUS_SUGGESTION_APPROVAL_"},
- value = {STATUS_SUGGESTION_APPROVAL_UNKNOWN,
- STATUS_SUGGESTION_APPROVAL_PENDING,
- STATUS_SUGGESTION_APPROVAL_APPROVED_BY_USER,
- STATUS_SUGGESTION_APPROVAL_REJECTED_BY_USER,
- STATUS_SUGGESTION_APPROVAL_APPROVED_BY_CARRIER_PRIVILEGE
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface SuggestionUserApprovalStatus {}
-
- /**
- * Broadcast intent action indicating whether Wi-Fi scanning is currently available.
- * Available extras:
- * - {@link #EXTRA_SCAN_AVAILABLE}
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String ACTION_WIFI_SCAN_AVAILABILITY_CHANGED =
- "android.net.wifi.action.WIFI_SCAN_AVAILABILITY_CHANGED";
-
- /**
- * A boolean extra indicating whether scanning is currently available.
- * Sent in the broadcast {@link #ACTION_WIFI_SCAN_AVAILABILITY_CHANGED}.
- * Its value is true if scanning is currently available, false otherwise.
- */
- public static final String EXTRA_SCAN_AVAILABLE = "android.net.wifi.extra.SCAN_AVAILABLE";
-
- /**
- *
- *
- * @hide
- **/
- public static final String WIFI_ALERT = "com.qualcomm.qti.net.wifi.WIFI_ALERT";
-
- /**
- *
- *
- * @hide
- **/
- public static final String WIFI_NETWORK_DISCONNECTION = "com.qualcomm.qti.net.wifi.WIFI_NETWORK_DISCONNECTION";
-
- /**
- *
- * see alert reason code
- * @hide
- **/
- public static final String EXTRA_WIFI_ALERT_REASON = "alert_reasoncode";
-
- /**
- *
- * see wifi network disconnection arg 1
- * @hide
- **/
- public static final String EXTRA_WIFI_NETWORK_DISCONNECTION_ARG1 = "network_disconnection_arg1";
-
- /**
- *
- * see wifi network disconnection arg 2
- * @hide
- **/
- public static final String EXTRA_WIFI_NETWORK_DISCONNECTION_ARG2 = "network_disconnection_arg2";
-
- /**
- * Broadcast intent action indicating that the credential of a Wi-Fi network
- * has been changed. One extra provides the ssid of the network. Another
- * extra provides the event type, whether the credential is saved or forgot.
- * @hide
- */
- @SystemApi
- public static final String WIFI_CREDENTIAL_CHANGED_ACTION =
- "android.net.wifi.WIFI_CREDENTIAL_CHANGED";
- /** @hide */
- @SystemApi
- public static final String EXTRA_WIFI_CREDENTIAL_EVENT_TYPE = "et";
- /** @hide */
- @SystemApi
- public static final String EXTRA_WIFI_CREDENTIAL_SSID = "ssid";
- /** @hide */
- @SystemApi
- public static final int WIFI_CREDENTIAL_SAVED = 0;
- /** @hide */
- @SystemApi
- public static final int WIFI_CREDENTIAL_FORGOT = 1;
-
- /** @hide */
- @SystemApi
- public static final int PASSPOINT_HOME_NETWORK = 0;
-
- /** @hide */
- @SystemApi
- public static final int PASSPOINT_ROAMING_NETWORK = 1;
-
- /**
- * Broadcast intent action indicating that a Passpoint provider icon has been received.
- *
- * Included extras:
- * {@link #EXTRA_BSSID_LONG}
- * {@link #EXTRA_FILENAME}
- * {@link #EXTRA_ICON}
- *
- * Receiver Required Permission: android.Manifest.permission.ACCESS_WIFI_STATE
- *
- * <p>Note: The broadcast is only delivered to registered receivers - no manifest registered
- * components will be launched.
- *
- * @hide
- */
- public static final String ACTION_PASSPOINT_ICON = "android.net.wifi.action.PASSPOINT_ICON";
- /**
- * BSSID of an AP in long representation. The {@link #EXTRA_BSSID} contains BSSID in
- * String representation.
- *
- * Retrieve with {@link android.content.Intent#getLongExtra(String, long)}.
- *
- * @hide
- */
- public static final String EXTRA_BSSID_LONG = "android.net.wifi.extra.BSSID_LONG";
- /**
- * Icon data.
- *
- * Retrieve with {@link android.content.Intent#getParcelableExtra(String)} and cast into
- * {@link android.graphics.drawable.Icon}.
- *
- * @hide
- */
- public static final String EXTRA_ICON = "android.net.wifi.extra.ICON";
- /**
- * Name of a file.
- *
- * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
- *
- * @hide
- */
- public static final String EXTRA_FILENAME = "android.net.wifi.extra.FILENAME";
-
- /**
- * Broadcast intent action indicating a Passpoint OSU Providers List element has been received.
- *
- * Included extras:
- * {@link #EXTRA_BSSID_LONG}
- * {@link #EXTRA_ANQP_ELEMENT_DATA}
- *
- * Receiver Required Permission: android.Manifest.permission.ACCESS_WIFI_STATE
- *
- * <p>Note: The broadcast is only delivered to registered receivers - no manifest registered
- * components will be launched.
- *
- * @hide
- */
- public static final String ACTION_PASSPOINT_OSU_PROVIDERS_LIST =
- "android.net.wifi.action.PASSPOINT_OSU_PROVIDERS_LIST";
- /**
- * Raw binary data of an ANQP (Access Network Query Protocol) element.
- *
- * Retrieve with {@link android.content.Intent#getByteArrayExtra(String)}.
- *
- * @hide
- */
- public static final String EXTRA_ANQP_ELEMENT_DATA =
- "android.net.wifi.extra.ANQP_ELEMENT_DATA";
-
- /**
- * Broadcast intent action indicating that a Passpoint Deauth Imminent frame has been received.
- *
- * Included extras:
- * {@link #EXTRA_BSSID_LONG}
- * {@link #EXTRA_ESS}
- * {@link #EXTRA_DELAY}
- * {@link #EXTRA_URL}
- *
- * Receiver Required Permission: android.Manifest.permission.ACCESS_WIFI_STATE
- *
- * <p>Note: The broadcast is only delivered to registered receivers - no manifest registered
- * components will be launched.
- *
- * @hide
- */
- public static final String ACTION_PASSPOINT_DEAUTH_IMMINENT =
- "android.net.wifi.action.PASSPOINT_DEAUTH_IMMINENT";
- /**
- * Flag indicating BSS (Basic Service Set) or ESS (Extended Service Set). This will be set to
- * {@code true} for ESS.
- *
- * Retrieve with {@link android.content.Intent#getBooleanExtra(String, boolean)}.
- *
- * @hide
- */
- public static final String EXTRA_ESS = "android.net.wifi.extra.ESS";
- /**
- * Delay in seconds.
- *
- * Retrieve with {@link android.content.Intent#getIntExtra(String, int)}.
- *
- * @hide
- */
- public static final String EXTRA_DELAY = "android.net.wifi.extra.DELAY";
-
- /**
- * Broadcast intent action indicating a Passpoint subscription remediation frame has been
- * received.
- *
- * Included extras:
- * {@link #EXTRA_BSSID_LONG}
- * {@link #EXTRA_SUBSCRIPTION_REMEDIATION_METHOD}
- * {@link #EXTRA_URL}
- *
- * Receiver Required Permission: android.Manifest.permission.ACCESS_WIFI_STATE
- *
- * <p>Note: The broadcast is only delivered to registered receivers - no manifest registered
- * components will be launched.
- *
- * @hide
- */
- public static final String ACTION_PASSPOINT_SUBSCRIPTION_REMEDIATION =
- "android.net.wifi.action.PASSPOINT_SUBSCRIPTION_REMEDIATION";
- /**
- * The protocol supported by the subscription remediation server. The possible values are:
- * 0 - OMA DM
- * 1 - SOAP XML SPP
- *
- * Retrieve with {@link android.content.Intent#getIntExtra(String, int)}.
- *
- * @hide
- */
- public static final String EXTRA_SUBSCRIPTION_REMEDIATION_METHOD =
- "android.net.wifi.extra.SUBSCRIPTION_REMEDIATION_METHOD";
-
- /**
- * Activity Action: Receiver should launch Passpoint OSU (Online Sign Up) view.
- * Included extras:
- *
- * {@link #EXTRA_OSU_NETWORK}: {@link Network} instance associated with OSU AP.
- * {@link #EXTRA_URL}: String representation of a server URL used for OSU process.
- *
- * @hide
- */
- @SystemApi
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_PASSPOINT_LAUNCH_OSU_VIEW =
- "android.net.wifi.action.PASSPOINT_LAUNCH_OSU_VIEW";
-
- /**
- * The lookup key for a {@link android.net.Network} associated with a Passpoint OSU server.
- * Included in the {@link #ACTION_PASSPOINT_LAUNCH_OSU_VIEW} broadcast.
- *
- * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_OSU_NETWORK = "android.net.wifi.extra.OSU_NETWORK";
-
- /**
- * String representation of an URL for Passpoint OSU.
- * Included in the {@link #ACTION_PASSPOINT_LAUNCH_OSU_VIEW} broadcast.
- *
- * Retrieve with {@link android.content.Intent#getStringExtra(String)}.
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_URL = "android.net.wifi.extra.URL";
-
- /**
- * Broadcast intent action indicating that Wi-Fi has been enabled, disabled,
- * enabling, disabling, or unknown. One extra provides this state as an int.
- * Another extra provides the previous state, if available. No network-related
- * permissions are required to subscribe to this broadcast.
- *
- * <p class="note">This broadcast is not delivered to manifest receivers in
- * applications that target API version 26 or later.
- *
- * @see #EXTRA_WIFI_STATE
- * @see #EXTRA_PREVIOUS_WIFI_STATE
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String WIFI_STATE_CHANGED_ACTION =
- "android.net.wifi.WIFI_STATE_CHANGED";
- /**
- * The lookup key for an int that indicates whether Wi-Fi is enabled,
- * disabled, enabling, disabling, or unknown. Retrieve it with
- * {@link android.content.Intent#getIntExtra(String,int)}.
- *
- * @see #WIFI_STATE_DISABLED
- * @see #WIFI_STATE_DISABLING
- * @see #WIFI_STATE_ENABLED
- * @see #WIFI_STATE_ENABLING
- * @see #WIFI_STATE_UNKNOWN
- */
- public static final String EXTRA_WIFI_STATE = "wifi_state";
- /**
- * The previous Wi-Fi state.
- *
- * @see #EXTRA_WIFI_STATE
- */
- public static final String EXTRA_PREVIOUS_WIFI_STATE = "previous_wifi_state";
-
- /**
- * Wi-Fi is currently being disabled. The state will change to {@link #WIFI_STATE_DISABLED} if
- * it finishes successfully.
- *
- * @see #WIFI_STATE_CHANGED_ACTION
- * @see #getWifiState()
- */
- public static final int WIFI_STATE_DISABLING = 0;
- /**
- * Wi-Fi is disabled.
- *
- * @see #WIFI_STATE_CHANGED_ACTION
- * @see #getWifiState()
- */
- public static final int WIFI_STATE_DISABLED = 1;
- /**
- * Wi-Fi is currently being enabled. The state will change to {@link #WIFI_STATE_ENABLED} if
- * it finishes successfully.
- *
- * @see #WIFI_STATE_CHANGED_ACTION
- * @see #getWifiState()
- */
- public static final int WIFI_STATE_ENABLING = 2;
- /**
- * Wi-Fi is enabled.
- *
- * @see #WIFI_STATE_CHANGED_ACTION
- * @see #getWifiState()
- */
- public static final int WIFI_STATE_ENABLED = 3;
- /**
- * Wi-Fi is in an unknown state. This state will occur when an error happens while enabling
- * or disabling.
- *
- * @see #WIFI_STATE_CHANGED_ACTION
- * @see #getWifiState()
- */
- public static final int WIFI_STATE_UNKNOWN = 4;
-
- /**
- * Broadcast intent action indicating that Wi-Fi AP has been enabled, disabled,
- * enabling, disabling, or failed.
- *
- * @hide
- */
- @SystemApi
- public static final String WIFI_AP_STATE_CHANGED_ACTION =
- "android.net.wifi.WIFI_AP_STATE_CHANGED";
-
- /**
- * The lookup key for an int that indicates whether Wi-Fi AP is enabled,
- * disabled, enabling, disabling, or failed. Retrieve it with
- * {@link android.content.Intent#getIntExtra(String,int)}.
- *
- * @see #WIFI_AP_STATE_DISABLED
- * @see #WIFI_AP_STATE_DISABLING
- * @see #WIFI_AP_STATE_ENABLED
- * @see #WIFI_AP_STATE_ENABLING
- * @see #WIFI_AP_STATE_FAILED
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_WIFI_AP_STATE = "wifi_state";
-
- /**
- * An extra containing the int error code for Soft AP start failure.
- * Can be obtained from the {@link #WIFI_AP_STATE_CHANGED_ACTION} using
- * {@link android.content.Intent#getIntExtra}.
- * This extra will only be attached if {@link #EXTRA_WIFI_AP_STATE} is
- * attached and is equal to {@link #WIFI_AP_STATE_FAILED}.
- *
- * The error code will be one of:
- * {@link #SAP_START_FAILURE_GENERAL},
- * {@link #SAP_START_FAILURE_NO_CHANNEL},
- * {@link #SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_WIFI_AP_FAILURE_REASON =
- "android.net.wifi.extra.WIFI_AP_FAILURE_REASON";
- /**
- * The look up key for a string that gives additonal info about EXTRA_WIFI_AP_FAILURE_REASON
- * currently support no_5ghz_support
- * @see #WIFI_AP_FAILURE_DESC_NO_5GHZ_SUPPORT
- *
- * @hide
- */
- public static final String EXTRA_WIFI_AP_FAILURE_DESCRIPTION = "wifi_ap_error_description";
- /**
- * If Wi-Fi AP start failed with SAP_START_FAILURE_NO_CHANNEL reason code and has this
- * description means that no supported channel exists on 5G band
- *
- * @hide
- */
- public static final String WIFI_AP_FAILURE_DESC_NO_5GHZ_SUPPORT = "wifi_ap_error_no_5g_support";
- /**
- * The previous Wi-Fi state.
- *
- * @see #EXTRA_WIFI_AP_STATE
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_PREVIOUS_WIFI_AP_STATE = "previous_wifi_state";
- /**
- * The lookup key for a String extra that stores the interface name used for the Soft AP.
- * This extra is included in the broadcast {@link #WIFI_AP_STATE_CHANGED_ACTION}.
- * Retrieve its value with {@link android.content.Intent#getStringExtra(String)}.
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_WIFI_AP_INTERFACE_NAME =
- "android.net.wifi.extra.WIFI_AP_INTERFACE_NAME";
- /**
- * The lookup key for an int extra that stores the intended IP mode for this Soft AP.
- * One of {@link #IFACE_IP_MODE_TETHERED} or {@link #IFACE_IP_MODE_LOCAL_ONLY}.
- * This extra is included in the broadcast {@link #WIFI_AP_STATE_CHANGED_ACTION}.
- * Retrieve its value with {@link android.content.Intent#getIntExtra(String, int)}.
- *
- * @hide
- */
- @SystemApi
- public static final String EXTRA_WIFI_AP_MODE = "android.net.wifi.extra.WIFI_AP_MODE";
-
- /** @hide */
- @IntDef(flag = false, prefix = { "WIFI_AP_STATE_" }, value = {
- WIFI_AP_STATE_DISABLING,
- WIFI_AP_STATE_DISABLED,
- WIFI_AP_STATE_ENABLING,
- WIFI_AP_STATE_ENABLED,
- WIFI_AP_STATE_FAILED,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface WifiApState {}
-
- /**
- * Wi-Fi AP is currently being disabled. The state will change to
- * {@link #WIFI_AP_STATE_DISABLED} if it finishes successfully.
- *
- * @see #WIFI_AP_STATE_CHANGED_ACTION
- * @see #getWifiApState()
- *
- * @hide
- */
- @SystemApi
- public static final int WIFI_AP_STATE_DISABLING = 10;
- /**
- * Wi-Fi AP is disabled.
- *
- * @see #WIFI_AP_STATE_CHANGED_ACTION
- * @see #getWifiState()
- *
- * @hide
- */
- @SystemApi
- public static final int WIFI_AP_STATE_DISABLED = 11;
- /**
- * Wi-Fi AP is currently being enabled. The state will change to
- * {@link #WIFI_AP_STATE_ENABLED} if it finishes successfully.
- *
- * @see #WIFI_AP_STATE_CHANGED_ACTION
- * @see #getWifiApState()
- *
- * @hide
- */
- @SystemApi
- public static final int WIFI_AP_STATE_ENABLING = 12;
- /**
- * Wi-Fi AP is enabled.
- *
- * @see #WIFI_AP_STATE_CHANGED_ACTION
- * @see #getWifiApState()
- *
- * @hide
- */
- @SystemApi
- public static final int WIFI_AP_STATE_ENABLED = 13;
- /**
- * Wi-Fi AP is in a failed state. This state will occur when an error occurs during
- * enabling or disabling
- *
- * @see #WIFI_AP_STATE_CHANGED_ACTION
- * @see #getWifiApState()
- *
- * @hide
- */
- @SystemApi
- public static final int WIFI_AP_STATE_FAILED = 14;
-
- /** @hide */
- @IntDef(flag = false, prefix = { "SAP_START_FAILURE_" }, value = {
- SAP_START_FAILURE_GENERAL,
- SAP_START_FAILURE_NO_CHANNEL,
- SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface SapStartFailure {}
-
- /**
- * All other reasons for AP start failure besides {@link #SAP_START_FAILURE_NO_CHANNEL} and
- * {@link #SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}.
- *
- * @hide
- */
- @SystemApi
- public static final int SAP_START_FAILURE_GENERAL= 0;
-
- /**
- * If Wi-Fi AP start failed, this reason code means that no legal channel exists on user
- * selected band due to regulatory constraints.
- *
- * @hide
- */
- @SystemApi
- public static final int SAP_START_FAILURE_NO_CHANNEL = 1;
-
- /**
- * If Wi-Fi AP start failed, this reason code means that the specified configuration
- * is not supported by the current HAL version.
- *
- * @hide
- */
- @SystemApi
- public static final int SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION = 2;
-
-
- /** @hide */
- @IntDef(flag = false, prefix = { "SAP_CLIENT_BLOCKED_REASON_" }, value = {
- SAP_CLIENT_BLOCK_REASON_CODE_BLOCKED_BY_USER,
- SAP_CLIENT_BLOCK_REASON_CODE_NO_MORE_STAS,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface SapClientBlockedReason {}
-
- /**
- * If Soft Ap client is blocked, this reason code means that client doesn't exist in the
- * specified configuration {@link SoftApConfiguration.Builder#setBlockedClientList(List)}
- * and {@link SoftApConfiguration.Builder#setAllowedClientList(List)}
- * and the {@link SoftApConfiguration.Builder#setClientControlByUserEnabled(boolean)}
- * is configured as well.
- * @hide
- */
- @SystemApi
- public static final int SAP_CLIENT_BLOCK_REASON_CODE_BLOCKED_BY_USER = 0;
-
- /**
- * If Soft Ap client is blocked, this reason code means that no more clients can be
- * associated to this AP since it reached maximum capacity. The maximum capacity is
- * the minimum of {@link SoftApConfiguration.Builder#setMaxNumberOfClients(int)} and
- * {@link SoftApCapability#getMaxSupportedClients} which get from
- * {@link WifiManager.SoftApCallback#onCapabilityChanged(SoftApCapability)}.
- *
- * @hide
- */
- @SystemApi
- public static final int SAP_CLIENT_BLOCK_REASON_CODE_NO_MORE_STAS = 1;
-
- /**
- * Client disconnected for unspecified reason. This could for example be because the AP is being
- * shut down.
- * @hide
- */
- public static final int SAP_CLIENT_DISCONNECT_REASON_CODE_UNSPECIFIED = 2;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"IFACE_IP_MODE_"}, value = {
- IFACE_IP_MODE_UNSPECIFIED,
- IFACE_IP_MODE_CONFIGURATION_ERROR,
- IFACE_IP_MODE_TETHERED,
- IFACE_IP_MODE_LOCAL_ONLY})
- public @interface IfaceIpMode {}
-
- /**
- * Interface IP mode unspecified.
- *
- * @see #updateInterfaceIpState(String, int)
- *
- * @hide
- */
- @SystemApi
- public static final int IFACE_IP_MODE_UNSPECIFIED = -1;
-
- /**
- * Interface IP mode for configuration error.
- *
- * @see #updateInterfaceIpState(String, int)
- *
- * @hide
- */
- @SystemApi
- public static final int IFACE_IP_MODE_CONFIGURATION_ERROR = 0;
-
- /**
- * Interface IP mode for tethering.
- *
- * @see #updateInterfaceIpState(String, int)
- *
- * @hide
- */
- @SystemApi
- public static final int IFACE_IP_MODE_TETHERED = 1;
-
- /**
- * Interface IP mode for Local Only Hotspot.
- *
- * @see #updateInterfaceIpState(String, int)
- *
- * @hide
- */
- @SystemApi
- public static final int IFACE_IP_MODE_LOCAL_ONLY = 2;
-
- /**
- * Broadcast intent action indicating that the wifi network settings
- * had been reset.
- *
- * Note: This intent is sent as a directed broadcast to each manifest registered receiver.
- * Intent will not be received by dynamically registered receivers.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_CARRIER_PROVISIONING)
- public static final String ACTION_NETWORK_SETTINGS_RESET =
- "android.net.wifi.action.NETWORK_SETTINGS_RESET";
-
- /**
- * Broadcast intent action indicating that a connection to the supplicant has
- * been established (and it is now possible
- * to perform Wi-Fi operations) or the connection to the supplicant has been
- * lost. One extra provides the connection state as a boolean, where {@code true}
- * means CONNECTED.
- * @deprecated This is no longer supported.
- * @see #EXTRA_SUPPLICANT_CONNECTED
- */
- @Deprecated
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String SUPPLICANT_CONNECTION_CHANGE_ACTION =
- "android.net.wifi.supplicant.CONNECTION_CHANGE";
- /**
- * The lookup key for a boolean that indicates whether a connection to
- * the supplicant daemon has been gained or lost. {@code true} means
- * a connection now exists.
- * Retrieve it with {@link android.content.Intent#getBooleanExtra(String,boolean)}.
- * @deprecated This is no longer supported.
- */
- @Deprecated
- public static final String EXTRA_SUPPLICANT_CONNECTED = "connected";
- /**
- * Broadcast intent action indicating that the state of Wi-Fi connectivity
- * has changed. An extra provides the new state
- * in the form of a {@link android.net.NetworkInfo} object. No network-related
- * permissions are required to subscribe to this broadcast.
- *
- * <p class="note">This broadcast is not delivered to manifest receivers in
- * applications that target API version 26 or later.
- * @see #EXTRA_NETWORK_INFO
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String NETWORK_STATE_CHANGED_ACTION = "android.net.wifi.STATE_CHANGE";
- /**
- * The lookup key for a {@link android.net.NetworkInfo} object associated with the
- * Wi-Fi network. Retrieve with
- * {@link android.content.Intent#getParcelableExtra(String)}.
- */
- public static final String EXTRA_NETWORK_INFO = "networkInfo";
- /**
- * The lookup key for a String giving the BSSID of the access point to which
- * we are connected. No longer used.
- */
- @Deprecated
- public static final String EXTRA_BSSID = "bssid";
- /**
- * The lookup key for a {@link android.net.wifi.WifiInfo} object giving the
- * information about the access point to which we are connected.
- * No longer used.
- */
- @Deprecated
- public static final String EXTRA_WIFI_INFO = "wifiInfo";
- /**
- * Broadcast intent action indicating that the state of establishing a connection to
- * an access point has changed.One extra provides the new
- * {@link SupplicantState}. Note that the supplicant state is Wi-Fi specific, and
- * is not generally the most useful thing to look at if you are just interested in
- * the overall state of connectivity.
- * @see #EXTRA_NEW_STATE
- * @see #EXTRA_SUPPLICANT_ERROR
- * @deprecated This is no longer supported.
- */
- @Deprecated
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String SUPPLICANT_STATE_CHANGED_ACTION =
- "android.net.wifi.supplicant.STATE_CHANGE";
- /**
- * The lookup key for a {@link SupplicantState} describing the new state
- * Retrieve with
- * {@link android.content.Intent#getParcelableExtra(String)}.
- * @deprecated This is no longer supported.
- */
- @Deprecated
- public static final String EXTRA_NEW_STATE = "newState";
-
- /**
- * The lookup key for a {@link SupplicantState} describing the supplicant
- * error code if any
- * Retrieve with
- * {@link android.content.Intent#getIntExtra(String, int)}.
- * @see #ERROR_AUTHENTICATING
- * @deprecated This is no longer supported.
- */
- @Deprecated
- public static final String EXTRA_SUPPLICANT_ERROR = "supplicantError";
-
- /**
- * The lookup key for a {@link SupplicantState} describing the supplicant
- * error reason if any
- * Retrieve with
- * {@link android.content.Intent#getIntExtra(String, int)}.
- * @see #ERROR_AUTH_FAILURE_#REASON_CODE
- * @deprecated This is no longer supported.
- * @hide
- */
- @Deprecated
- public static final String EXTRA_SUPPLICANT_ERROR_REASON = "supplicantErrorReason";
-
- /**
- * Broadcast intent action indicating that the configured networks changed.
- * This can be as a result of adding/updating/deleting a network.
- * <br />
- * {@link #EXTRA_CHANGE_REASON} contains whether the configuration was added/changed/removed.
- * {@link #EXTRA_WIFI_CONFIGURATION} is never set beginning in
- * {@link android.os.Build.VERSION_CODES#R}.
- * {@link #EXTRA_MULTIPLE_NETWORKS_CHANGED} is set for backwards compatibility reasons, but
- * its value is always true beginning in {@link android.os.Build.VERSION_CODES#R}, even if only
- * a single network changed.
- * <br />
- * The {@link android.Manifest.permission#ACCESS_WIFI_STATE ACCESS_WIFI_STATE} permission is
- * required to receive this broadcast.
- *
- * @hide
- */
- @SystemApi
- public static final String CONFIGURED_NETWORKS_CHANGED_ACTION =
- "android.net.wifi.CONFIGURED_NETWORKS_CHANGE";
- /**
- * The lookup key for a {@link android.net.wifi.WifiConfiguration} object representing
- * the changed Wi-Fi configuration when the {@link #CONFIGURED_NETWORKS_CHANGED_ACTION}
- * broadcast is sent.
- * @deprecated This extra is never set beginning in {@link android.os.Build.VERSION_CODES#R},
- * regardless of the target SDK version. Use {@link #getConfiguredNetworks} to get the full list
- * of configured networks.
- * @hide
- */
- @Deprecated
- @SystemApi
- public static final String EXTRA_WIFI_CONFIGURATION = "wifiConfiguration";
- /**
- * Multiple network configurations have changed.
- * @see #CONFIGURED_NETWORKS_CHANGED_ACTION
- * @deprecated This extra's value is always true beginning in
- * {@link android.os.Build.VERSION_CODES#R}, regardless of the target SDK version.
- * @hide
- */
- @Deprecated
- @SystemApi
- public static final String EXTRA_MULTIPLE_NETWORKS_CHANGED = "multipleChanges";
- /**
- * The lookup key for an integer indicating the reason a Wi-Fi network configuration
- * has changed. One of {@link #CHANGE_REASON_ADDED}, {@link #CHANGE_REASON_REMOVED},
- * {@link #CHANGE_REASON_CONFIG_CHANGE}.
- *
- * @see #CONFIGURED_NETWORKS_CHANGED_ACTION
- * @hide
- */
- @SystemApi
- public static final String EXTRA_CHANGE_REASON = "changeReason";
- /**
- * The configuration is new and was added.
- * @hide
- */
- @SystemApi
- public static final int CHANGE_REASON_ADDED = 0;
- /**
- * The configuration was removed and is no longer present in the system's list of
- * configured networks.
- * @hide
- */
- @SystemApi
- public static final int CHANGE_REASON_REMOVED = 1;
- /**
- * The configuration has changed as a result of explicit action or because the system
- * took an automated action such as disabling a malfunctioning configuration.
- * @hide
- */
- @SystemApi
- public static final int CHANGE_REASON_CONFIG_CHANGE = 2;
- /**
- * An access point scan has completed, and results are available.
- * Call {@link #getScanResults()} to obtain the results.
- * The broadcast intent may contain an extra field with the key {@link #EXTRA_RESULTS_UPDATED}
- * and a {@code boolean} value indicating if the scan was successful.
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String SCAN_RESULTS_AVAILABLE_ACTION = "android.net.wifi.SCAN_RESULTS";
-
- /**
- * Lookup key for a {@code boolean} extra in intent {@link #SCAN_RESULTS_AVAILABLE_ACTION}
- * representing if the scan was successful or not.
- * Scans may fail for multiple reasons, these may include:
- * <ol>
- * <li>An app requested too many scans in a certain period of time.
- * This may lead to additional scan request rejections via "scan throttling" for both
- * foreground and background apps.
- * Note: Apps holding android.Manifest.permission.NETWORK_SETTINGS permission are
- * exempted from scan throttling.
- * </li>
- * <li>The device is idle and scanning is disabled.</li>
- * <li>Wifi hardware reported a scan failure.</li>
- * </ol>
- * @return true scan was successful, results are updated
- * @return false scan was not successful, results haven't been updated since previous scan
- */
- public static final String EXTRA_RESULTS_UPDATED = "resultsUpdated";
-
- /**
- * A batch of access point scans has been completed and the results areavailable.
- * Call {@link #getBatchedScanResults()} to obtain the results.
- * @deprecated This API is nolonger supported.
- * Use {@link android.net.wifi.WifiScanner} API
- * @hide
- */
- @Deprecated
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String BATCHED_SCAN_RESULTS_AVAILABLE_ACTION =
- "android.net.wifi.BATCHED_RESULTS";
-
- /**
- * The RSSI (signal strength) has changed.
- *
- * Receiver Required Permission: android.Manifest.permission.ACCESS_WIFI_STATE
- * @see #EXTRA_NEW_RSSI
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String RSSI_CHANGED_ACTION = "android.net.wifi.RSSI_CHANGED";
- /**
- * The lookup key for an {@code int} giving the new RSSI in dBm.
- */
- public static final String EXTRA_NEW_RSSI = "newRssi";
-
- /**
- * @see #ACTION_LINK_CONFIGURATION_CHANGED
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final String LINK_CONFIGURATION_CHANGED_ACTION =
- "android.net.wifi.LINK_CONFIGURATION_CHANGED";
-
- /**
- * Broadcast intent action indicating that the link configuration changed on wifi.
- * <br /> No permissions are required to listen to this broadcast.
- * @hide
- */
- @SystemApi
- public static final String ACTION_LINK_CONFIGURATION_CHANGED =
- // should be android.net.wifi.action.LINK_CONFIGURATION_CHANGED, but due to
- // @UnsupportedAppUsage leaving it as android.net.wifi.LINK_CONFIGURATION_CHANGED.
- LINK_CONFIGURATION_CHANGED_ACTION;
-
- /**
- * The lookup key for a {@link android.net.LinkProperties} object associated with the
- * Wi-Fi network.
- * Included in the {@link #ACTION_LINK_CONFIGURATION_CHANGED} broadcast.
- *
- * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
- *
- * @deprecated this extra is no longer populated.
- *
- * @hide
- */
- @Deprecated
- @SystemApi
- public static final String EXTRA_LINK_PROPERTIES = "android.net.wifi.extra.LINK_PROPERTIES";
-
- /**
- * The lookup key for a {@link android.net.NetworkCapabilities} object associated with the
- * Wi-Fi network. Retrieve with
- * {@link android.content.Intent#getParcelableExtra(String)}.
- * @hide
- */
- public static final String EXTRA_NETWORK_CAPABILITIES = "networkCapabilities";
-
- /**
- * The network IDs of the configured networks could have changed.
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String NETWORK_IDS_CHANGED_ACTION = "android.net.wifi.NETWORK_IDS_CHANGED";
-
- /**
- * Broadcast intent action indicating DPP Event arrival notificaiton.
- * @see #EXTRA_DPP_DATA.
- * @hide
- */
- public static final String DPP_EVENT_ACTION = "com.qualcomm.qti.net.wifi.DPP_EVENT";
-
- /**
- * This shall point to DppResult Type.
- * @hide
- */
- public static final String EXTRA_DPP_EVENT_TYPE = "dppEventType";
-
- /**
- * This shall point to WifiDppConfig object. Retrieve with
- * {@link android.content.Intent#getParcelableExtra(String)}.
- * @hide
- */
- public static final String EXTRA_DPP_EVENT_DATA = "dppEventData";
-
- /**
- * Activity Action: Show a system activity that allows the user to enable
- * scans to be available even with Wi-Fi turned off.
- *
- * <p>Notification of the result of this activity is posted using the
- * {@link android.app.Activity#onActivityResult} callback. The
- * <code>resultCode</code>
- * will be {@link android.app.Activity#RESULT_OK} if scan always mode has
- * been turned on or {@link android.app.Activity#RESULT_CANCELED} if the user
- * has rejected the request or an error has occurred.
- */
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE =
- "android.net.wifi.action.REQUEST_SCAN_ALWAYS_AVAILABLE";
-
- /**
- * Activity Action: Pick a Wi-Fi network to connect to.
- * <p>Input: Nothing.
- * <p>Output: Nothing.
- */
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_PICK_WIFI_NETWORK = "android.net.wifi.PICK_WIFI_NETWORK";
-
- /**
- * Activity Action: Receiver should show UI to get user approval to enable WiFi.
- * <p>Input: {@link android.content.Intent#EXTRA_PACKAGE_NAME} string extra with
- * the name of the app requesting the action.
- * <p>Output: Nothing.
- * <p>No permissions are required to send this action.
- * @hide
- */
- @SystemApi
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_REQUEST_ENABLE = "android.net.wifi.action.REQUEST_ENABLE";
-
- /**
- * Activity Action: Receiver should show UI to get user approval to disable WiFi.
- * <p>Input: {@link android.content.Intent#EXTRA_PACKAGE_NAME} string extra with
- * the name of the app requesting the action.
- * <p>Output: Nothing.
- * <p>No permissions are required to send this action.
- * @hide
- */
- @SystemApi
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String ACTION_REQUEST_DISABLE = "android.net.wifi.action.REQUEST_DISABLE";
-
- /**
- * Broadcast intent action indicating that WifiCountryCode was updated with new
- * country code.
- *
- * @see #EXTRA_COUNTRY_CODE
- *
- * @hide
- */
- @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
- public static final String WIFI_COUNTRY_CODE_CHANGED_ACTION =
- "android.net.wifi.COUNTRY_CODE_CHANGED";
-
- /**
- * The lookup key for a string that indicates the 2 char new country code
- *
- * @hide
- */
- public static final String EXTRA_COUNTRY_CODE = "country_code";
-
- /**
- * Directed broadcast intent action indicating that the device has connected to one of the
- * network suggestions provided by the app. This will be sent post connection to a network
- * which was created with {@link WifiNetworkSuggestion.Builder#setIsAppInteractionRequired(
- * boolean)}
- * flag set.
- * <p>
- * Note: The broadcast is sent to the app only if it holds
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission.
- *
- * @see #EXTRA_NETWORK_SUGGESTION
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION =
- "android.net.wifi.action.WIFI_NETWORK_SUGGESTION_POST_CONNECTION";
- /**
- * Sent as as a part of {@link #ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION} that holds
- * an instance of {@link WifiNetworkSuggestion} corresponding to the connected network.
- */
- public static final String EXTRA_NETWORK_SUGGESTION =
- "android.net.wifi.extra.NETWORK_SUGGESTION";
-
- /**
- * Internally used Wi-Fi lock mode representing the case were no locks are held.
- * @hide
- */
- public static final int WIFI_MODE_NO_LOCKS_HELD = 0;
-
- /**
- * In this Wi-Fi lock mode, Wi-Fi will be kept active,
- * and will behave normally, i.e., it will attempt to automatically
- * establish a connection to a remembered access point that is
- * within range, and will do periodic scans if there are remembered
- * access points but none are in range.
- *
- * @deprecated This API is non-functional and will have no impact.
- */
- @Deprecated
- public static final int WIFI_MODE_FULL = 1;
-
- /**
- * In this Wi-Fi lock mode, Wi-Fi will be kept active,
- * but the only operation that will be supported is initiation of
- * scans, and the subsequent reporting of scan results. No attempts
- * will be made to automatically connect to remembered access points,
- * nor will periodic scans be automatically performed looking for
- * remembered access points. Scans must be explicitly requested by
- * an application in this mode.
- *
- * @deprecated This API is non-functional and will have no impact.
- */
- @Deprecated
- public static final int WIFI_MODE_SCAN_ONLY = 2;
-
- /**
- * In this Wi-Fi lock mode, Wi-Fi will not go to power save.
- * This results in operating with low packet latency.
- * The lock is only active when the device is connected to an access point.
- * The lock is active even when the device screen is off or the acquiring application is
- * running in the background.
- * This mode will consume more power and hence should be used only
- * when there is a need for this tradeoff.
- * <p>
- * An example use case is when a voice connection needs to be
- * kept active even after the device screen goes off.
- * Holding a {@link #WIFI_MODE_FULL_HIGH_PERF} lock for the
- * duration of the voice call may improve the call quality.
- * <p>
- * When there is no support from the hardware, the {@link #WIFI_MODE_FULL_HIGH_PERF}
- * lock will have no impact.
- */
- public static final int WIFI_MODE_FULL_HIGH_PERF = 3;
-
- /**
- * In this Wi-Fi lock mode, Wi-Fi will operate with a priority to achieve low latency.
- * {@link #WIFI_MODE_FULL_LOW_LATENCY} lock has the following limitations:
- * <ol>
- * <li>The lock is only active when the device is connected to an access point.</li>
- * <li>The lock is only active when the screen is on.</li>
- * <li>The lock is only active when the acquiring app is running in the foreground.</li>
- * </ol>
- * Low latency mode optimizes for reduced packet latency,
- * and as a result other performance measures may suffer when there are trade-offs to make:
- * <ol>
- * <li>Battery life may be reduced.</li>
- * <li>Throughput may be reduced.</li>
- * <li>Frequency of Wi-Fi scanning may be reduced. This may result in: </li>
- * <ul>
- * <li>The device may not roam or switch to the AP with highest signal quality.</li>
- * <li>Location accuracy may be reduced.</li>
- * </ul>
- * </ol>
- * <p>
- * Example use cases are real time gaming or virtual reality applications where
- * low latency is a key factor for user experience.
- * <p>
- * Note: For an app which acquires both {@link #WIFI_MODE_FULL_LOW_LATENCY} and
- * {@link #WIFI_MODE_FULL_HIGH_PERF} locks, {@link #WIFI_MODE_FULL_LOW_LATENCY}
- * lock will be effective when app is running in foreground and screen is on,
- * while the {@link #WIFI_MODE_FULL_HIGH_PERF} lock will take effect otherwise.
- */
- public static final int WIFI_MODE_FULL_LOW_LATENCY = 4;
-
-
- /** Anything worse than or equal to this will show 0 bars. */
- @UnsupportedAppUsage
- private static final int MIN_RSSI = -100;
-
- /** Anything better than or equal to this will show the max bars. */
- @UnsupportedAppUsage
- private static final int MAX_RSSI = -55;
-
- /**
- * Number of RSSI levels used in the framework to initiate {@link #RSSI_CHANGED_ACTION}
- * broadcast, where each level corresponds to a range of RSSI values.
- * The {@link #RSSI_CHANGED_ACTION} broadcast will only fire if the RSSI
- * change is significant enough to change the RSSI signal level.
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int RSSI_LEVELS = 5;
-
- //TODO (b/146346676): This needs to be removed, not used in the code.
- /**
- * Auto settings in the driver. The driver could choose to operate on both
- * 2.4 GHz and 5 GHz or make a dynamic decision on selecting the band.
- * @hide
- */
- @UnsupportedAppUsage
- public static final int WIFI_FREQUENCY_BAND_AUTO = 0;
-
- /**
- * Operation on 5 GHz alone
- * @hide
- */
- @UnsupportedAppUsage
- public static final int WIFI_FREQUENCY_BAND_5GHZ = 1;
-
- /**
- * Operation on 2.4 GHz alone
- * @hide
- */
- @UnsupportedAppUsage
- public static final int WIFI_FREQUENCY_BAND_2GHZ = 2;
-
- /** @hide */
- public static final boolean DEFAULT_POOR_NETWORK_AVOIDANCE_ENABLED = false;
-
- /**
- * Maximum number of active locks we allow.
- * This limit was added to prevent apps from creating a ridiculous number
- * of locks and crashing the system by overflowing the global ref table.
- */
- private static final int MAX_ACTIVE_LOCKS = 50;
-
- /** Indicates an invalid SSID. */
- public static final String UNKNOWN_SSID = "<unknown ssid>";
-
- /** @hide */
- public static final MacAddress ALL_ZEROS_MAC_ADDRESS =
- MacAddress.fromString("00:00:00:00:00:00");
-
- /* Number of currently active WifiLocks and MulticastLocks */
- @UnsupportedAppUsage
- private int mActiveLockCount;
-
- private Context mContext;
- @UnsupportedAppUsage
- IWifiManager mService;
- private final int mTargetSdkVersion;
-
- private Looper mLooper;
- private boolean mVerboseLoggingEnabled = false;
-
- private final Object mLock = new Object(); // lock guarding access to the following vars
- @GuardedBy("mLock")
- private LocalOnlyHotspotCallbackProxy mLOHSCallbackProxy;
- @GuardedBy("mLock")
- private LocalOnlyHotspotObserverProxy mLOHSObserverProxy;
-
- /**
- * Create a new WifiManager instance.
- * Applications will almost always want to use
- * {@link android.content.Context#getSystemService Context.getSystemService} to retrieve
- * the standard {@link android.content.Context#WIFI_SERVICE Context.WIFI_SERVICE}.
- *
- * @param context the application context
- * @param service the Binder interface
- * @param looper the Looper used to deliver callbacks
- * @hide - hide this because it takes in a parameter of type IWifiManager, which
- * is a system private class.
- */
- public WifiManager(@NonNull Context context, @NonNull IWifiManager service,
- @NonNull Looper looper) {
- mContext = context;
- mService = service;
- mLooper = looper;
- mTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
- updateVerboseLoggingEnabledFromService();
- }
-
- /**
- * Return a list of all the networks configured for the current foreground
- * user.
- *
- * Not all fields of WifiConfiguration are returned. Only the following
- * fields are filled in:
- * <ul>
- * <li>networkId</li>
- * <li>SSID</li>
- * <li>BSSID</li>
- * <li>priority</li>
- * <li>allowedProtocols</li>
- * <li>allowedKeyManagement</li>
- * <li>allowedAuthAlgorithms</li>
- * <li>allowedPairwiseCiphers</li>
- * <li>allowedGroupCiphers</li>
- * <li>status</li>
- * </ul>
- * @return a list of network configurations in the form of a list
- * of {@link WifiConfiguration} objects.
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * <b>Compatibility Note:</b> For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return an
- * empty list.
- * <p>
- * Deprecation Exemptions:
- * <ul>
- * <li>Device Owner (DO), Profile Owner (PO) and system apps will have access to the full list.
- * <li>Callers with Carrier privilege will receive a restricted list only containing
- * configurations which they created.
- * </ul>
- */
- @Deprecated
- @RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
- public List<WifiConfiguration> getConfiguredNetworks() {
- try {
- ParceledListSlice<WifiConfiguration> parceledList =
- mService.getConfiguredNetworks(mContext.getOpPackageName(),
- mContext.getAttributionTag());
- if (parceledList == null) {
- return Collections.emptyList();
- }
- return parceledList.getList();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- @SystemApi
- @RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE, READ_WIFI_CREDENTIAL})
- public List<WifiConfiguration> getPrivilegedConfiguredNetworks() {
- try {
- ParceledListSlice<WifiConfiguration> parceledList =
- mService.getPrivilegedConfiguredNetworks(mContext.getOpPackageName(),
- mContext.getAttributionTag());
- if (parceledList == null) {
- return Collections.emptyList();
- }
- return parceledList.getList();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns a list of all matching WifiConfigurations for a given list of ScanResult.
- *
- * An empty list will be returned when no configurations are installed or if no configurations
- * match the ScanResult.
- *
- * @param scanResults a list of scanResult that represents the BSSID
- * @return List that consists of {@link WifiConfiguration} and corresponding scanResults per
- * network type({@link #PASSPOINT_HOME_NETWORK} and {@link #PASSPOINT_ROAMING_NETWORK}).
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- @NonNull
- public List<Pair<WifiConfiguration, Map<Integer, List<ScanResult>>>> getAllMatchingWifiConfigs(
- @NonNull List<ScanResult> scanResults) {
- List<Pair<WifiConfiguration, Map<Integer, List<ScanResult>>>> configs = new ArrayList<>();
- try {
- Map<String, Map<Integer, List<ScanResult>>> results =
- mService.getAllMatchingPasspointProfilesForScanResults(scanResults);
- if (results.isEmpty()) {
- return configs;
- }
- List<WifiConfiguration> wifiConfigurations =
- mService.getWifiConfigsForPasspointProfiles(
- new ArrayList<>(results.keySet()));
- for (WifiConfiguration configuration : wifiConfigurations) {
- Map<Integer, List<ScanResult>> scanResultsPerNetworkType =
- results.get(configuration.getProfileKey());
- if (scanResultsPerNetworkType != null) {
- configs.add(Pair.create(configuration, scanResultsPerNetworkType));
- }
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
-
- return configs;
- }
-
- /**
- * Retrieve a list of {@link WifiConfiguration} for available {@link WifiNetworkSuggestion}
- * matching the given list of {@link ScanResult}.
- *
- * An available {@link WifiNetworkSuggestion} must satisfy:
- * <ul>
- * <li> Matching one of the {@link ScanResult} from the given list.
- * <li> and {@link WifiNetworkSuggestion.Builder#setIsUserAllowedToManuallyConnect(boolean)} set
- * to true.
- * </ul>
- *
- * @param scanResults a list of scanResult.
- * @return a list of @link WifiConfiguration} for available {@link WifiNetworkSuggestion}
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- @NonNull
- public List<WifiConfiguration> getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(
- @NonNull List<ScanResult> scanResults) {
- try {
- return mService.getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(scanResults);
- } catch (RemoteException e) {
- throw e.rethrowAsRuntimeException();
- }
- }
-
- /**
- * Returns a list of unique Hotspot 2.0 OSU (Online Sign-Up) providers associated with a given
- * list of ScanResult.
- *
- * An empty list will be returned if no match is found.
- *
- * @param scanResults a list of ScanResult
- * @return Map that consists {@link OsuProvider} and a list of matching {@link ScanResult}
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- @NonNull
- public Map<OsuProvider, List<ScanResult>> getMatchingOsuProviders(
- @Nullable List<ScanResult> scanResults) {
- if (scanResults == null) {
- return new HashMap<>();
- }
- try {
- return mService.getMatchingOsuProviders(scanResults);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns the matching Passpoint R2 configurations for given OSU (Online Sign-Up) providers.
- *
- * Given a list of OSU providers, this only returns OSU providers that already have Passpoint R2
- * configurations in the device.
- * An empty map will be returned when there is no matching Passpoint R2 configuration for the
- * given OsuProviders.
- *
- * @param osuProviders a set of {@link OsuProvider}
- * @return Map that consists of {@link OsuProvider} and matching {@link PasspointConfiguration}.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- @NonNull
- public Map<OsuProvider, PasspointConfiguration> getMatchingPasspointConfigsForOsuProviders(
- @NonNull Set<OsuProvider> osuProviders) {
- try {
- return mService.getMatchingPasspointConfigsForOsuProviders(
- new ArrayList<>(osuProviders));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Add a new network description to the set of configured networks.
- * The {@code networkId} field of the supplied configuration object
- * is ignored.
- * <p/>
- * The new network will be marked DISABLED by default. To enable it,
- * called {@link #enableNetwork}.
- *
- * @param config the set of variables that describe the configuration,
- * contained in a {@link WifiConfiguration} object.
- * If the {@link WifiConfiguration} has an Http Proxy set
- * the calling app must be System, or be provisioned as the Profile or Device Owner.
- * @return the ID of the newly created network description. This is used in
- * other operations to specified the network to be acted upon.
- * Returns {@code -1} on failure.
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * <b>Compatibility Note:</b> For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code -1}.
- * <p>
- * Deprecation Exemptions:
- * <ul>
- * <li>Device Owner (DO), Profile Owner (PO) and system apps.
- * </ul>
- */
- @Deprecated
- public int addNetwork(WifiConfiguration config) {
- if (config == null) {
- return -1;
- }
- config.networkId = -1;
- return addOrUpdateNetwork(config);
- }
-
- /**
- * Update the network description of an existing configured network.
- *
- * @param config the set of variables that describe the configuration,
- * contained in a {@link WifiConfiguration} object. It may
- * be sparse, so that only the items that are being changed
- * are non-<code>null</code>. The {@code networkId} field
- * must be set to the ID of the existing network being updated.
- * If the {@link WifiConfiguration} has an Http Proxy set
- * the calling app must be System, or be provisioned as the Profile or Device Owner.
- * @return Returns the {@code networkId} of the supplied
- * {@code WifiConfiguration} on success.
- * <br/>
- * Returns {@code -1} on failure, including when the {@code networkId}
- * field of the {@code WifiConfiguration} does not refer to an
- * existing network.
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * <b>Compatibility Note:</b> For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code -1}.
- * <p>
- * Deprecation Exemptions:
- * <ul>
- * <li>Device Owner (DO), Profile Owner (PO) and system apps.
- * </ul>
- */
- @Deprecated
- public int updateNetwork(WifiConfiguration config) {
- if (config == null || config.networkId < 0) {
- return -1;
- }
- return addOrUpdateNetwork(config);
- }
-
-
- /**
- * Check the WifiSharing mode.
- *
- * @return true if Current Sta network connected with extending coverage
- * option. false if it is not.
- *
- * @hide no intent to publish
- */
- public boolean isExtendingWifi() {
- try {
- return mService.isExtendingWifi();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Check Wifi coverage extend feature enabled or not.
- *
- * @return true if Wifi extend feature is enabled.
- *
- * @hide no intent to publish
- */
- public boolean isWifiCoverageExtendFeatureEnabled() {
- try {
- return mService.isWifiCoverageExtendFeatureEnabled();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Enable/disable Wifi coverage extend feature.
- *
- * @hide no intent to publish
- */
- public void enableWifiCoverageExtendFeature(boolean enable) {
- try {
- mService.enableWifiCoverageExtendFeature(enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get SoftAp Wi-Fi generation.
- *
- * @return Wi-Fi generation if SoftAp enabled or -1.
- *
- * @hide no intent to publish
- */
- public int getSoftApWifiStandard() {
- try {
- return mService.getSoftApWifiStandard();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Internal method for doing the RPC that creates a new network description
- * or updates an existing one.
- *
- * @param config The possibly sparse object containing the variables that
- * are to set or updated in the network description.
- * @return the ID of the network on success, {@code -1} on failure.
- */
- private int addOrUpdateNetwork(WifiConfiguration config) {
- try {
- return mService.addOrUpdateNetwork(config, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Interface for indicating user selection from the list of networks presented in the
- * {@link NetworkRequestMatchCallback#onMatch(List)}.
- *
- * The platform will implement this callback and pass it along with the
- * {@link NetworkRequestMatchCallback#onUserSelectionCallbackRegistration(
- * NetworkRequestUserSelectionCallback)}. The UI component handling
- * {@link NetworkRequestMatchCallback} will invoke {@link #select(WifiConfiguration)} or
- * {@link #reject()} to return the user's selection back to the platform via this callback.
- * @hide
- */
- @SystemApi
- public interface NetworkRequestUserSelectionCallback {
- /**
- * User selected this network to connect to.
- * @param wifiConfiguration WifiConfiguration object corresponding to the network
- * user selected.
- */
- @SuppressLint("CallbackMethodName")
- default void select(@NonNull WifiConfiguration wifiConfiguration) {}
-
- /**
- * User rejected the app's request.
- */
- @SuppressLint("CallbackMethodName")
- default void reject() {}
- }
-
- /**
- * Interface for network request callback. Should be implemented by applications and passed when
- * calling {@link #registerNetworkRequestMatchCallback(Executor,
- * WifiManager.NetworkRequestMatchCallback)}.
- *
- * This is meant to be implemented by a UI component to present the user with a list of networks
- * matching the app's request. The user is allowed to pick one of these networks to connect to
- * or reject the request by the app.
- * @hide
- */
- @SystemApi
- public interface NetworkRequestMatchCallback {
- /**
- * Invoked to register a callback to be invoked to convey user selection. The callback
- * object passed in this method is to be invoked by the UI component after the service sends
- * a list of matching scan networks using {@link #onMatch(List)} and user picks a network
- * from that list.
- *
- * @param userSelectionCallback Callback object to send back the user selection.
- */
- default void onUserSelectionCallbackRegistration(
- @NonNull NetworkRequestUserSelectionCallback userSelectionCallback) {}
-
- /**
- * Invoked when the active network request is aborted, either because
- * <li> The app released the request, OR</li>
- * <li> Request was overridden by a new request</li>
- * This signals the end of processing for the current request and should stop the UI
- * component. No subsequent calls from the UI component will be handled by the platform.
- */
- default void onAbort() {}
-
- /**
- * Invoked when a network request initiated by an app matches some networks in scan results.
- * This may be invoked multiple times for a single network request as the platform finds new
- * matching networks in scan results.
- *
- * @param scanResults List of {@link ScanResult} objects corresponding to the networks
- * matching the request.
- */
- default void onMatch(@NonNull List<ScanResult> scanResults) {}
-
- /**
- * Invoked on a successful connection with the network that the user selected
- * via {@link NetworkRequestUserSelectionCallback}.
- *
- * @param wifiConfiguration WifiConfiguration object corresponding to the network that the
- * user selected.
- */
- default void onUserSelectionConnectSuccess(@NonNull WifiConfiguration wifiConfiguration) {}
-
- /**
- * Invoked on failure to establish connection with the network that the user selected
- * via {@link NetworkRequestUserSelectionCallback}.
- *
- * @param wifiConfiguration WifiConfiguration object corresponding to the network
- * user selected.
- */
- default void onUserSelectionConnectFailure(@NonNull WifiConfiguration wifiConfiguration) {}
- }
-
- /**
- * Callback proxy for NetworkRequestUserSelectionCallback objects.
- * @hide
- */
- private class NetworkRequestUserSelectionCallbackProxy implements
- NetworkRequestUserSelectionCallback {
- private final INetworkRequestUserSelectionCallback mCallback;
-
- NetworkRequestUserSelectionCallbackProxy(
- INetworkRequestUserSelectionCallback callback) {
- mCallback = callback;
- }
-
- @Override
- public void select(@NonNull WifiConfiguration wifiConfiguration) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestUserSelectionCallbackProxy: select "
- + "wificonfiguration: " + wifiConfiguration);
- }
- try {
- mCallback.select(wifiConfiguration);
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to invoke onSelected", e);
- throw e.rethrowFromSystemServer();
- }
- }
-
- @Override
- public void reject() {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestUserSelectionCallbackProxy: reject");
- }
- try {
- mCallback.reject();
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to invoke onRejected", e);
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Callback proxy for NetworkRequestMatchCallback objects.
- * @hide
- */
- private class NetworkRequestMatchCallbackProxy extends INetworkRequestMatchCallback.Stub {
- private final Executor mExecutor;
- private final NetworkRequestMatchCallback mCallback;
-
- NetworkRequestMatchCallbackProxy(Executor executor, NetworkRequestMatchCallback callback) {
- mExecutor = executor;
- mCallback = callback;
- }
-
- @Override
- public void onUserSelectionCallbackRegistration(
- INetworkRequestUserSelectionCallback userSelectionCallback) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestMatchCallbackProxy: "
- + "onUserSelectionCallbackRegistration callback: " + userSelectionCallback);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onUserSelectionCallbackRegistration(
- new NetworkRequestUserSelectionCallbackProxy(userSelectionCallback));
- });
- }
-
- @Override
- public void onAbort() {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestMatchCallbackProxy: onAbort");
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onAbort();
- });
- }
-
- @Override
- public void onMatch(List<ScanResult> scanResults) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestMatchCallbackProxy: onMatch scanResults: "
- + scanResults);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onMatch(scanResults);
- });
- }
-
- @Override
- public void onUserSelectionConnectSuccess(WifiConfiguration wifiConfiguration) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestMatchCallbackProxy: onUserSelectionConnectSuccess "
- + " wificonfiguration: " + wifiConfiguration);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onUserSelectionConnectSuccess(wifiConfiguration);
- });
- }
-
- @Override
- public void onUserSelectionConnectFailure(WifiConfiguration wifiConfiguration) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "NetworkRequestMatchCallbackProxy: onUserSelectionConnectFailure"
- + " wificonfiguration: " + wifiConfiguration);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onUserSelectionConnectFailure(wifiConfiguration);
- });
- }
- }
-
- /**
- * Registers a callback for NetworkRequest matches. See {@link NetworkRequestMatchCallback}.
- * Caller can unregister a previously registered callback using
- * {@link #unregisterNetworkRequestMatchCallback(NetworkRequestMatchCallback)}
- * <p>
- * Applications should have the
- * {@link android.Manifest.permission#NETWORK_SETTINGS} permission. Callers
- * without the permission will trigger a {@link java.lang.SecurityException}.
- * <p>
- *
- * @param executor The Executor on whose thread to execute the callbacks of the {@code callback}
- * object.
- * @param callback Callback for network match events to register.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void registerNetworkRequestMatchCallback(@NonNull @CallbackExecutor Executor executor,
- @NonNull NetworkRequestMatchCallback callback) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "registerNetworkRequestMatchCallback: callback=" + callback
- + ", executor=" + executor);
-
- Binder binder = new Binder();
- try {
- mService.registerNetworkRequestMatchCallback(
- binder, new NetworkRequestMatchCallbackProxy(executor, callback),
- callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Unregisters a callback for NetworkRequest matches. See {@link NetworkRequestMatchCallback}.
- * <p>
- * Applications should have the
- * {@link android.Manifest.permission#NETWORK_SETTINGS} permission. Callers
- * without the permission will trigger a {@link java.lang.SecurityException}.
- * <p>
- *
- * @param callback Callback for network match events to unregister.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void unregisterNetworkRequestMatchCallback(
- @NonNull NetworkRequestMatchCallback callback) {
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "unregisterNetworkRequestMatchCallback: callback=" + callback);
-
- try {
- mService.unregisterNetworkRequestMatchCallback(callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Provide a list of network suggestions to the device. See {@link WifiNetworkSuggestion}
- * for a detailed explanation of the parameters.
- * When the device decides to connect to one of the provided network suggestions, platform sends
- * a directed broadcast {@link #ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION} to the app if
- * the network was created with
- * {@link WifiNetworkSuggestion.Builder#setIsAppInteractionRequired(boolean)} flag set and the
- * app holds {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION}
- * permission.
- *<p>
- * NOTE:
- * <li> These networks are just a suggestion to the platform. The platform will ultimately
- * decide on which network the device connects to. </li>
- * <li> When an app is uninstalled or disabled, all its suggested networks are discarded.
- * If the device is currently connected to a suggested network which is being removed then the
- * device will disconnect from that network.</li>
- * <li> If user reset network settings, all added suggestions will be discarded. Apps can use
- * {@link #getNetworkSuggestions()} to check if their suggestions are in the device.</li>
- * <li> In-place modification of existing suggestions are allowed.
- * <li> If the provided suggestions include any previously provided suggestions by the app,
- * previous suggestions will be updated.</li>
- * <li>If one of the provided suggestions marks a previously unmetered suggestion as metered and
- * the device is currently connected to that suggested network, then the device will disconnect
- * from that network. The system will immediately re-evaluate all the network candidates
- * and possibly reconnect back to the same suggestion. This disconnect is to make sure that any
- * traffic flowing over unmetered networks isn't accidentally continued over a metered network.
- * </li>
- * </li>
- *
- * @param networkSuggestions List of network suggestions provided by the app.
- * @return Status code for the operation. One of the STATUS_NETWORK_SUGGESTIONS_ values.
- * @throws {@link SecurityException} if the caller is missing required permissions.
- * @see WifiNetworkSuggestion#equals(Object)
- */
- @RequiresPermission(android.Manifest.permission.CHANGE_WIFI_STATE)
- public @NetworkSuggestionsStatusCode int addNetworkSuggestions(
- @NonNull List<WifiNetworkSuggestion> networkSuggestions) {
- try {
- return mService.addNetworkSuggestions(
- networkSuggestions, mContext.getOpPackageName(), mContext.getAttributionTag());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Remove some or all of the network suggestions that were previously provided by the app.
- * If one of the suggestions being removed was used to establish connection to the current
- * network, then the device will immediately disconnect from that network.
- *
- * See {@link WifiNetworkSuggestion} for a detailed explanation of the parameters.
- * See {@link WifiNetworkSuggestion#equals(Object)} for the equivalence evaluation used.
- *
- * @param networkSuggestions List of network suggestions to be removed. Pass an empty list
- * to remove all the previous suggestions provided by the app.
- * @return Status code for the operation. One of the STATUS_NETWORK_SUGGESTIONS_ values.
- * Any matching suggestions are removed from the device and will not be considered for any
- * further connection attempts.
- */
- @RequiresPermission(android.Manifest.permission.CHANGE_WIFI_STATE)
- public @NetworkSuggestionsStatusCode int removeNetworkSuggestions(
- @NonNull List<WifiNetworkSuggestion> networkSuggestions) {
- try {
- return mService.removeNetworkSuggestions(
- networkSuggestions, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get all network suggestions provided by the calling app.
- * See {@link #addNetworkSuggestions(List)}
- * See {@link #removeNetworkSuggestions(List)}
- * @return a list of {@link WifiNetworkSuggestion}
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public @NonNull List<WifiNetworkSuggestion> getNetworkSuggestions() {
- try {
- return mService.getNetworkSuggestions(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowAsRuntimeException();
- }
- }
-
- /**
- * Returns the max number of network suggestions that are allowed per app on the device.
- * @see #addNetworkSuggestions(List)
- * @see #removeNetworkSuggestions(List)
- */
- public int getMaxNumberOfNetworkSuggestionsPerApp() {
- return getMaxNumberOfNetworkSuggestionsPerApp(
- mContext.getSystemService(ActivityManager.class).isLowRamDevice());
- }
-
- /** @hide */
- public static int getMaxNumberOfNetworkSuggestionsPerApp(boolean isLowRamDevice) {
- return isLowRamDevice
- ? NETWORK_SUGGESTIONS_MAX_PER_APP_LOW_RAM
- : NETWORK_SUGGESTIONS_MAX_PER_APP_HIGH_RAM;
- }
-
- /**
- * Get the Suggestion approval status of the calling app. When an app makes suggestions using
- * the {@link #addNetworkSuggestions(List)} API they may trigger a user approval flow. This API
- * provides the current approval status.
- *
- * @return Status code for the user approval. One of the STATUS_SUGGESTION_APPROVAL_ values.
- * @throws {@link SecurityException} if the caller is missing required permissions.
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public @SuggestionUserApprovalStatus int getNetworkSuggestionUserApprovalStatus() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- try {
- return mService.getNetworkSuggestionUserApprovalStatus(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowAsRuntimeException();
- }
- }
-
- /**
- * Add or update a Passpoint configuration. The configuration provides a credential
- * for connecting to Passpoint networks that are operated by the Passpoint
- * service provider specified in the configuration.
- *
- * Each configuration is uniquely identified by a unique key which depends on the contents of
- * the configuration. This allows the caller to install multiple profiles with the same FQDN
- * (Fully qualified domain name). Therefore, in order to update an existing profile, it is
- * first required to remove it using {@link WifiManager#removePasspointConfiguration(String)}.
- * Otherwise, a new profile will be added with both configuration.
- *
- * @param config The Passpoint configuration to be added
- * @throws IllegalArgumentException if configuration is invalid or Passpoint is not enabled on
- * the device.
- *
- * Deprecated for general app usage - except DO/PO apps.
- * See {@link WifiNetworkSuggestion.Builder#setPasspointConfig(PasspointConfiguration)} to
- * create a passpoint suggestion.
- * See {@link #addNetworkSuggestions(List)}, {@link #removeNetworkSuggestions(List)} for new
- * API to add Wi-Fi networks for consideration when auto-connecting to wifi.
- * <b>Compatibility Note:</b> For applications targeting
- * {@link android.os.Build.VERSION_CODES#R} or above, this API will always fail and throw
- * {@link IllegalArgumentException}.
- * <p>
- * Deprecation Exemptions:
- * <ul>
- * <li>Device Owner (DO), Profile Owner (PO) and system apps.
- * </ul>
- */
- public void addOrUpdatePasspointConfiguration(PasspointConfiguration config) {
- try {
- if (!mService.addOrUpdatePasspointConfiguration(config, mContext.getOpPackageName())) {
- throw new IllegalArgumentException();
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Remove the Passpoint configuration identified by its FQDN (Fully Qualified Domain Name) added
- * by the caller.
- *
- * @param fqdn The FQDN of the Passpoint configuration added by the caller to be removed
- * @throws IllegalArgumentException if no configuration is associated with the given FQDN or
- * Passpoint is not enabled on the device.
- * @deprecated This will be non-functional in a future release.
- */
- @Deprecated
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_CARRIER_PROVISIONING
- })
- public void removePasspointConfiguration(String fqdn) {
- try {
- if (!mService.removePasspointConfiguration(fqdn, mContext.getOpPackageName())) {
- throw new IllegalArgumentException();
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return the list of installed Passpoint configurations added by the caller.
- *
- * An empty list will be returned when no configurations are installed.
- *
- * @return A list of {@link PasspointConfiguration} added by the caller
- * @deprecated This will be non-functional in a future release.
- */
- @Deprecated
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- public List<PasspointConfiguration> getPasspointConfigurations() {
- try {
- return mService.getPasspointConfigurations(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Query for a Hotspot 2.0 release 2 OSU icon file. An {@link #ACTION_PASSPOINT_ICON} intent
- * will be broadcasted once the request is completed. The presence of the intent extra
- * {@link #EXTRA_ICON} will indicate the result of the request.
- * A missing intent extra {@link #EXTRA_ICON} will indicate a failure.
- *
- * @param bssid The BSSID of the AP
- * @param fileName Name of the icon file (remote file) to query from the AP
- *
- * @throws UnsupportedOperationException if Passpoint is not enabled on the device.
- * @hide
- */
- public void queryPasspointIcon(long bssid, String fileName) {
- try {
- mService.queryPasspointIcon(bssid, fileName);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Match the currently associated network against the SP matching the given FQDN
- * @param fqdn FQDN of the SP
- * @return ordinal [HomeProvider, RoamingProvider, Incomplete, None, Declined]
- * @hide
- */
- public int matchProviderWithCurrentNetwork(String fqdn) {
- try {
- return mService.matchProviderWithCurrentNetwork(fqdn);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Remove the specified network from the list of configured networks.
- * This may result in the asynchronous delivery of state change
- * events.
- *
- * Applications are not allowed to remove networks created by other
- * applications.
- *
- * @param netId the ID of the network as returned by {@link #addNetwork} or {@link
- * #getConfiguredNetworks}.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * <b>Compatibility Note:</b> For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}.
- * <p>
- * Deprecation Exemptions:
- * <ul>
- * <li>Device Owner (DO), Profile Owner (PO) and system apps.
- * </ul>
- */
- @Deprecated
- public boolean removeNetwork(int netId) {
- try {
- return mService.removeNetwork(netId, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow a previously configured network to be associated with. If
- * <code>attemptConnect</code> is true, an attempt to connect to the selected
- * network is initiated. This may result in the asynchronous delivery
- * of state change events.
- * <p>
- * <b>Note:</b> Network communication may not use Wi-Fi even if Wi-Fi is connected;
- * traffic may instead be sent through another network, such as cellular data,
- * Bluetooth tethering, or Ethernet. For example, traffic will never use a
- * Wi-Fi network that does not provide Internet access (e.g. a wireless
- * printer), if another network that does offer Internet access (e.g.
- * cellular data) is available. Applications that need to ensure that their
- * network traffic uses Wi-Fi should use APIs such as
- * {@link Network#bindSocket(java.net.Socket)},
- * {@link Network#openConnection(java.net.URL)}, or
- * {@link ConnectivityManager#bindProcessToNetwork} to do so.
- *
- * Applications are not allowed to enable networks created by other
- * applications.
- *
- * @param netId the ID of the network as returned by {@link #addNetwork} or {@link
- * #getConfiguredNetworks}.
- * @param attemptConnect The way to select a particular network to connect to is specify
- * {@code true} for this parameter.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * <b>Compatibility Note:</b> For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}.
- * Deprecation Exemptions:
- * <ul>
- * <li>Device Owner (DO), Profile Owner (PO) and system apps.
- * </ul>
- */
- @Deprecated
- public boolean enableNetwork(int netId, boolean attemptConnect) {
- try {
- return mService.enableNetwork(netId, attemptConnect, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Disable a configured network. The specified network will not be
- * a candidate for associating. This may result in the asynchronous
- * delivery of state change events.
- *
- * Applications are not allowed to disable networks created by other
- * applications.
- *
- * @param netId the ID of the network as returned by {@link #addNetwork} or {@link
- * #getConfiguredNetworks}.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * <b>Compatibility Note:</b> For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}.
- * <p>
- * Deprecation Exemptions:
- * <ul>
- * <li>Device Owner (DO), Profile Owner (PO) and system apps.
- * </ul>
- */
- @Deprecated
- public boolean disableNetwork(int netId) {
- try {
- return mService.disableNetwork(netId, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Disassociate from the currently active access point. This may result
- * in the asynchronous delivery of state change events.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * <b>Compatibility Note:</b> For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}.
- * <p>
- * Deprecation Exemptions:
- * <ul>
- * <li>Device Owner (DO), Profile Owner (PO) and system apps.
- * </ul>
- */
- @Deprecated
- public boolean disconnect() {
- try {
- return mService.disconnect(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Reconnect to the currently active access point, if we are currently
- * disconnected. This may result in the asynchronous delivery of state
- * change events.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * <b>Compatibility Note:</b> For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}.
- * <p>
- * Deprecation Exemptions:
- * <ul>
- * <li>Device Owner (DO), Profile Owner (PO) and system apps.
- * </ul>
- */
- @Deprecated
- public boolean reconnect() {
- try {
- return mService.reconnect(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Reconnect to the currently active access point, even if we are already
- * connected. This may result in the asynchronous delivery of state
- * change events.
- * @return {@code true} if the operation succeeded
- *
- * @deprecated
- * a) See {@link WifiNetworkSpecifier.Builder#build()} for new
- * mechanism to trigger connection to a Wi-Fi network.
- * b) See {@link #addNetworkSuggestions(List)},
- * {@link #removeNetworkSuggestions(List)} for new API to add Wi-Fi networks for consideration
- * when auto-connecting to wifi.
- * <b>Compatibility Note:</b> For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always return false.
- */
- @Deprecated
- public boolean reassociate() {
- try {
- return mService.reassociate(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Check that the supplicant daemon is responding to requests.
- * @return {@code true} if we were able to communicate with the supplicant and
- * it returned the expected response to the PING message.
- * @deprecated Will return the output of {@link #isWifiEnabled()} instead.
- */
- @Deprecated
- public boolean pingSupplicant() {
- return isWifiEnabled();
- }
-
- /** @hide */
- public static final long WIFI_FEATURE_INFRA = 0x0001L; // Basic infrastructure mode
- /** @hide */
- public static final long WIFI_FEATURE_PASSPOINT = 0x0004L; // Support for GAS/ANQP
- /** @hide */
- public static final long WIFI_FEATURE_P2P = 0x0008L; // Wifi-Direct
- /** @hide */
- public static final long WIFI_FEATURE_MOBILE_HOTSPOT = 0x0010L; // Soft AP
- /** @hide */
- public static final long WIFI_FEATURE_SCANNER = 0x0020L; // WifiScanner APIs
- /** @hide */
- public static final long WIFI_FEATURE_AWARE = 0x0040L; // Wi-Fi AWare networking
- /** @hide */
- public static final long WIFI_FEATURE_D2D_RTT = 0x0080L; // Device-to-device RTT
- /** @hide */
- public static final long WIFI_FEATURE_D2AP_RTT = 0x0100L; // Device-to-AP RTT
- /** @hide */
- public static final long WIFI_FEATURE_BATCH_SCAN = 0x0200L; // Batched Scan (deprecated)
- /** @hide */
- public static final long WIFI_FEATURE_PNO = 0x0400L; // Preferred network offload
- /** @hide */
- public static final long WIFI_FEATURE_ADDITIONAL_STA = 0x0800L; // Support for two STAs
- /** @hide */
- public static final long WIFI_FEATURE_TDLS = 0x1000L; // Tunnel directed link setup
- /** @hide */
- public static final long WIFI_FEATURE_TDLS_OFFCHANNEL = 0x2000L; // TDLS off channel
- /** @hide */
- public static final long WIFI_FEATURE_EPR = 0x4000L; // Enhanced power reporting
- /** @hide */
- public static final long WIFI_FEATURE_AP_STA = 0x8000L; // AP STA Concurrency
- /** @hide */
- public static final long WIFI_FEATURE_LINK_LAYER_STATS = 0x10000L; // Link layer stats
- /** @hide */
- public static final long WIFI_FEATURE_LOGGER = 0x20000L; // WiFi Logger
- /** @hide */
- public static final long WIFI_FEATURE_HAL_EPNO = 0x40000L; // Enhanced PNO
- /** @hide */
- public static final long WIFI_FEATURE_RSSI_MONITOR = 0x80000L; // RSSI Monitor
- /** @hide */
- public static final long WIFI_FEATURE_MKEEP_ALIVE = 0x100000L; // mkeep_alive
- /** @hide */
- public static final long WIFI_FEATURE_CONFIG_NDO = 0x200000L; // ND offload
- /** @hide */
- public static final long WIFI_FEATURE_TRANSMIT_POWER = 0x400000L; // Capture transmit power
- /** @hide */
- public static final long WIFI_FEATURE_CONTROL_ROAMING = 0x800000L; // Control firmware roaming
- /** @hide */
- public static final long WIFI_FEATURE_IE_WHITELIST = 0x1000000L; // Probe IE white listing
- /** @hide */
- public static final long WIFI_FEATURE_SCAN_RAND = 0x2000000L; // Random MAC & Probe seq
- /** @hide */
- public static final long WIFI_FEATURE_TX_POWER_LIMIT = 0x4000000L; // Set Tx power limit
- /** @hide */
- public static final long WIFI_FEATURE_WPA3_SAE = 0x8000000L; // WPA3-Personal SAE
- /** @hide */
- public static final long WIFI_FEATURE_WPA3_SUITE_B = 0x10000000L; // WPA3-Enterprise Suite-B
- /** @hide */
- public static final long WIFI_FEATURE_OWE = 0x20000000L; // Enhanced Open
- /** @hide */
- public static final long WIFI_FEATURE_LOW_LATENCY = 0x40000000L; // Low Latency modes
- /** @hide */
- public static final long WIFI_FEATURE_DPP = 0x80000000L; // DPP (Easy-Connect)
- /** @hide */
- public static final long WIFI_FEATURE_P2P_RAND_MAC = 0x100000000L; // Random P2P MAC
- /** @hide */
- public static final long WIFI_FEATURE_CONNECTED_RAND_MAC = 0x200000000L; // Random STA MAC
- /** @hide */
- public static final long WIFI_FEATURE_AP_RAND_MAC = 0x400000000L; // Random AP MAC
- /** @hide */
- public static final long WIFI_FEATURE_MBO = 0x800000000L; // MBO Support
- /** @hide */
- public static final long WIFI_FEATURE_OCE = 0x1000000000L; // OCE Support
- /** @hide */
- public static final long WIFI_FEATURE_WAPI = 0x2000000000L; // WAPI
- /** @hide */
- public static final long WIFI_FEATURE_INFRA_60G = 0x4000000000L; // 60 GHz Band Support
-
- /** @hide */
- public static final long WIFI_FEATURE_FILS_SHA256 = 0x4000000000L; // FILS-SHA256
-
- /** @hide */
- public static final long WIFI_FEATURE_FILS_SHA384 = 0x8000000000L; // FILS-SHA384
-
- /** @hide */
- public static final long WIFI_FEATURE_SAE_PK = 0x10000000000L; // SAE-PK
-
- /** @hide */
- public static final long WIFI_FEATURE_STA_BRIDGED_AP = 0x20000000000L; // STA + Bridged AP
-
- /** @hide */
- public static final long WIFI_FEATURE_BRIDGED_AP = 0x40000000000L; // Bridged AP
-
- private long getSupportedFeatures() {
- try {
- return mService.getSupportedFeatures();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- private boolean isFeatureSupported(long feature) {
- return (getSupportedFeatures() & feature) == feature;
- }
-
- /**
- * @return true if this adapter supports Passpoint
- * @hide
- */
- public boolean isPasspointSupported() {
- return isFeatureSupported(WIFI_FEATURE_PASSPOINT);
- }
-
- /**
- * @return true if this adapter supports WifiP2pManager (Wi-Fi Direct)
- */
- public boolean isP2pSupported() {
- return isFeatureSupported(WIFI_FEATURE_P2P);
- }
-
- /**
- * @return true if this adapter supports portable Wi-Fi hotspot
- * @hide
- */
- @SystemApi
- public boolean isPortableHotspotSupported() {
- return isFeatureSupported(WIFI_FEATURE_MOBILE_HOTSPOT);
- }
-
- /**
- * @return true if this adapter supports WifiScanner APIs
- * @hide
- */
- @SystemApi
- public boolean isWifiScannerSupported() {
- return isFeatureSupported(WIFI_FEATURE_SCANNER);
- }
-
- /**
- * @return true if this adapter supports Neighbour Awareness Network APIs
- * @hide
- */
- public boolean isWifiAwareSupported() {
- return isFeatureSupported(WIFI_FEATURE_AWARE);
- }
-
- /**
- * Query whether the device supports Station (STA) + Access point (AP) concurrency or not.
- *
- * @return true if this device supports STA + AP concurrency, false otherwise.
- */
- public boolean isStaApConcurrencySupported() {
- return isFeatureSupported(WIFI_FEATURE_AP_STA);
- }
-
- /**
- * Query whether the device supports 2 or more concurrent stations (STA) or not.
- *
- * @return true if this device supports multiple STA concurrency, false otherwise.
- */
- public boolean isMultiStaConcurrencySupported() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return isFeatureSupported(WIFI_FEATURE_ADDITIONAL_STA);
- }
-
- /**
- * @deprecated Please use {@link android.content.pm.PackageManager#hasSystemFeature(String)}
- * with {@link android.content.pm.PackageManager#FEATURE_WIFI_RTT} and
- * {@link android.content.pm.PackageManager#FEATURE_WIFI_AWARE}.
- *
- * @return true if this adapter supports Device-to-device RTT
- * @hide
- */
- @Deprecated
- @SystemApi
- public boolean isDeviceToDeviceRttSupported() {
- return isFeatureSupported(WIFI_FEATURE_D2D_RTT);
- }
-
- /**
- * @deprecated Please use {@link android.content.pm.PackageManager#hasSystemFeature(String)}
- * with {@link android.content.pm.PackageManager#FEATURE_WIFI_RTT}.
- *
- * @return true if this adapter supports Device-to-AP RTT
- */
- @Deprecated
- public boolean isDeviceToApRttSupported() {
- return isFeatureSupported(WIFI_FEATURE_D2AP_RTT);
- }
-
- /**
- * @return true if this adapter supports offloaded connectivity scan
- */
- public boolean isPreferredNetworkOffloadSupported() {
- return isFeatureSupported(WIFI_FEATURE_PNO);
- }
-
- /**
- * @return true if this adapter supports Tunnel Directed Link Setup
- */
- public boolean isTdlsSupported() {
- return isFeatureSupported(WIFI_FEATURE_TDLS);
- }
-
- /**
- * @return true if this adapter supports Off Channel Tunnel Directed Link Setup
- * @hide
- */
- public boolean isOffChannelTdlsSupported() {
- return isFeatureSupported(WIFI_FEATURE_TDLS_OFFCHANNEL);
- }
-
- /**
- * @return true if this adapter supports advanced power/performance counters
- */
- public boolean isEnhancedPowerReportingSupported() {
- return isFeatureSupported(WIFI_FEATURE_LINK_LAYER_STATS);
- }
-
- /**
- * @return true if this device supports connected MAC randomization.
- * @hide
- */
- @SystemApi
- public boolean isConnectedMacRandomizationSupported() {
- return isFeatureSupported(WIFI_FEATURE_CONNECTED_RAND_MAC);
- }
-
- /**
- * @return true if this device supports connected MAC randomization.
- * @hide
- */
- @SystemApi
- public boolean isApMacRandomizationSupported() {
- return isFeatureSupported(WIFI_FEATURE_AP_RAND_MAC);
- }
-
- /**
- * Check if the chipset supports 5GHz band.
- * @return {@code true} if supported, {@code false} otherwise.
- */
- public boolean is5GHzBandSupported() {
- try {
- return mService.is5GHzBandSupported();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Check if the chipset supports the 60GHz frequency band.
- *
- * @return {@code true} if supported, {@code false} otherwise.
- * @hide
- */
- @SystemApi
- public boolean is60GHzBandSupported() {
- try {
- return mService.is60GHzBandSupported();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Check if the chipset supports 6GHz band.
- * @return {@code true} if supported, {@code false} otherwise.
- */
- public boolean is6GHzBandSupported() {
- try {
- return mService.is6GHzBandSupported();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Check if the chipset supports a certain Wi-Fi standard.
- * @param standard the IEEE 802.11 standard to check on.
- * valid values from {@link ScanResult}'s {@code WIFI_STANDARD_}
- * @return {@code true} if supported, {@code false} otherwise.
- */
- public boolean isWifiStandardSupported(@WifiAnnotations.WifiStandard int standard) {
- try {
- return mService.isWifiStandardSupported(standard);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Query whether the device supports Station (STA) + Bridged access point (AP)
- * concurrency or not.
- *
- * The bridged AP support means that the device supports AP + AP concurrency with the 2 APs
- * bridged together.
- *
- * See {@link SoftApConfiguration.Builder#setBands(int[])}
- * or {@link SoftApConfiguration.Builder#setChannels(SparseIntArray)} to configure bridged AP
- * when the bridged AP supported.
- *
- * @return true if this device supports STA + bridged AP concurrency, false otherwise.
- */
- public boolean isStaBridgedApConcurrencySupported() {
- return isFeatureSupported(WIFI_FEATURE_STA_BRIDGED_AP);
- }
-
- /**
- * Query whether the device supports Bridged Access point (AP) concurrency or not.
- *
- * The bridged AP support means that the device supports AP + AP concurrency with the 2 APs
- * bridged together.
- *
- * See {@link SoftApConfiguration.Builder#setBands(int[])}
- * or {@link SoftApConfiguration.Builder#setChannels(SparseIntArray)} to configure bridged AP
- * when the bridged AP supported.
- *
- * @return true if this device supports bridged AP concurrency, false otherwise.
- */
- public boolean isBridgedApConcurrencySupported() {
- return isFeatureSupported(WIFI_FEATURE_BRIDGED_AP);
- }
-
-
- /**
- * Interface for Wi-Fi activity energy info listener. Should be implemented by applications and
- * set when calling {@link WifiManager#getWifiActivityEnergyInfoAsync}.
- *
- * @hide
- */
- @SystemApi
- public interface OnWifiActivityEnergyInfoListener {
- /**
- * Called when Wi-Fi activity energy info is available.
- * Note: this listener is triggered at most once for each call to
- * {@link #getWifiActivityEnergyInfoAsync}.
- *
- * @param info the latest {@link WifiActivityEnergyInfo}, or null if unavailable.
- */
- void onWifiActivityEnergyInfo(@Nullable WifiActivityEnergyInfo info);
- }
-
- private static class OnWifiActivityEnergyInfoProxy
- extends IOnWifiActivityEnergyInfoListener.Stub {
- private final Object mLock = new Object();
- @Nullable @GuardedBy("mLock") private Executor mExecutor;
- @Nullable @GuardedBy("mLock") private OnWifiActivityEnergyInfoListener mListener;
-
- OnWifiActivityEnergyInfoProxy(Executor executor,
- OnWifiActivityEnergyInfoListener listener) {
- mExecutor = executor;
- mListener = listener;
- }
-
- @Override
- public void onWifiActivityEnergyInfo(WifiActivityEnergyInfo info) {
- Executor executor;
- OnWifiActivityEnergyInfoListener listener;
- synchronized (mLock) {
- if (mExecutor == null || mListener == null) {
- return;
- }
- executor = mExecutor;
- listener = mListener;
- // null out to allow garbage collection, prevent triggering listener more than once
- mExecutor = null;
- mListener = null;
- }
- Binder.clearCallingIdentity();
- executor.execute(() -> listener.onWifiActivityEnergyInfo(info));
- }
- }
-
- /**
- * Request to get the current {@link WifiActivityEnergyInfo} asynchronously.
- * Note: This method will return null if {@link #isEnhancedPowerReportingSupported()} returns
- * false.
- *
- * @param executor the executor that the listener will be invoked on
- * @param listener the listener that will receive the {@link WifiActivityEnergyInfo} object
- * when it becomes available. The listener will be triggered at most once for
- * each call to this method.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(ACCESS_WIFI_STATE)
- public void getWifiActivityEnergyInfoAsync(
- @NonNull @CallbackExecutor Executor executor,
- @NonNull OnWifiActivityEnergyInfoListener listener) {
- Objects.requireNonNull(executor, "executor cannot be null");
- Objects.requireNonNull(listener, "listener cannot be null");
- try {
- mService.getWifiActivityEnergyInfoAsync(
- new OnWifiActivityEnergyInfoProxy(executor, listener));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Request a scan for access points. Returns immediately. The availability
- * of the results is made known later by means of an asynchronous event sent
- * on completion of the scan.
- * <p>
- * To initiate a Wi-Fi scan, declare the
- * {@link android.Manifest.permission#CHANGE_WIFI_STATE}
- * permission in the manifest, and perform these steps:
- * </p>
- * <ol style="1">
- * <li>Invoke the following method:
- * {@code ((WifiManager) getSystemService(WIFI_SERVICE)).startScan()}</li>
- * <li>
- * Register a BroadcastReceiver to listen to
- * {@code SCAN_RESULTS_AVAILABLE_ACTION}.</li>
- * <li>When a broadcast is received, call:
- * {@code ((WifiManager) getSystemService(WIFI_SERVICE)).getScanResults()}</li>
- * </ol>
- * @return {@code true} if the operation succeeded, i.e., the scan was initiated.
- * @deprecated The ability for apps to trigger scan requests will be removed in a future
- * release.
- */
- @Deprecated
- public boolean startScan() {
- return startScan(null);
- }
-
- /** @hide */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS)
- public boolean startScan(WorkSource workSource) {
- try {
- String packageName = mContext.getOpPackageName();
- String attributionTag = mContext.getAttributionTag();
- return mService.startScan(packageName, attributionTag);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * WPS has been deprecated from Client mode operation.
- *
- * @return null
- * @hide
- * @deprecated This API is deprecated
- */
- public String getCurrentNetworkWpsNfcConfigurationToken() {
- return null;
- }
-
- /**
- * Return dynamic information about the current Wi-Fi connection, if any is active.
- * <p>
- * In the connected state, access to the SSID and BSSID requires
- * the same permissions as {@link #getScanResults}. If such access is not allowed,
- * {@link WifiInfo#getSSID} will return {@link #UNKNOWN_SSID} and
- * {@link WifiInfo#getBSSID} will return {@code "02:00:00:00:00:00"}.
- * {@link WifiInfo#getPasspointFqdn()} will return null.
- * {@link WifiInfo#getPasspointProviderFriendlyName()} will return null.
- *
- * @return the Wi-Fi information, contained in {@link WifiInfo}.
- */
- public WifiInfo getConnectionInfo() {
- try {
- return mService.getConnectionInfo(mContext.getOpPackageName(),
- mContext.getAttributionTag());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return the results of the latest access point scan.
- * @return the list of access points found in the most recent scan. An app must hold
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION} permission
- * in order to get valid results.
- */
- public List<ScanResult> getScanResults() {
- try {
- return mService.getScanResults(mContext.getOpPackageName(),
- mContext.getAttributionTag());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get the filtered ScanResults which match the network configurations specified by the
- * {@code networkSuggestionsToMatch}. Suggestions which use {@link WifiConfiguration} use
- * SSID and the security type to match. Suggestions which use {@link PasspointConfigration}
- * use the matching rules of Hotspot 2.0.
- * @param networkSuggestionsToMatch The list of {@link WifiNetworkSuggestion} to match against.
- * These may or may not be suggestions which are installed on the device.
- * @param scanResults The scan results to be filtered. Optional - if not provided(empty list),
- * the Wi-Fi service will use the most recent scan results which the system has.
- * @return The map of {@link WifiNetworkSuggestion} to the list of {@link ScanResult}
- * corresponding to networks which match them.
- * @hide
- */
- @SystemApi
- @RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
- @NonNull
- public Map<WifiNetworkSuggestion, List<ScanResult>> getMatchingScanResults(
- @NonNull List<WifiNetworkSuggestion> networkSuggestionsToMatch,
- @Nullable List<ScanResult> scanResults) {
- if (networkSuggestionsToMatch == null) {
- throw new IllegalArgumentException("networkSuggestions must not be null.");
- }
- try {
- return mService.getMatchingScanResults(
- networkSuggestionsToMatch, scanResults,
- mContext.getOpPackageName(), mContext.getAttributionTag());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Set if scanning is always available.
- *
- * If set to {@code true}, apps can issue {@link #startScan} and fetch scan results
- * even when Wi-Fi is turned off.
- *
- * @param isAvailable true to enable, false to disable.
- * @hide
- * @see #isScanAlwaysAvailable()
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setScanAlwaysAvailable(boolean isAvailable) {
- try {
- mService.setScanAlwaysAvailable(isAvailable, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Check if scanning is always available.
- *
- * If this return {@code true}, apps can issue {@link #startScan} and fetch scan results
- * even when Wi-Fi is turned off.
- *
- * To change this setting, see {@link #ACTION_REQUEST_SCAN_ALWAYS_AVAILABLE}.
- * @deprecated The ability for apps to trigger scan requests will be removed in a future
- * release.
- */
- @Deprecated
- public boolean isScanAlwaysAvailable() {
- try {
- return mService.isScanAlwaysAvailable();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Tell the device to persist the current list of configured networks.
- * <p>
- * Note: It is possible for this method to change the network IDs of
- * existing networks. You should assume the network IDs can be different
- * after calling this method.
- *
- * @return {@code false}.
- * @deprecated There is no need to call this method -
- * {@link #addNetwork(WifiConfiguration)}, {@link #updateNetwork(WifiConfiguration)}
- * and {@link #removeNetwork(int)} already persist the configurations automatically.
- */
- @Deprecated
- public boolean saveConfiguration() {
- return false;
- }
-
- /**
- * Get the country code.
- * @return the country code in ISO 3166 alpha-2 (2-letter) uppercase format, or null if
- * there is no country code configured.
- * @hide
- */
- @Nullable
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public String getCountryCode() {
- try {
- return mService.getCountryCode();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return the DHCP-assigned addresses from the last successful DHCP request,
- * if any.
- * @return the DHCP information
- */
- public DhcpInfo getDhcpInfo() {
- try {
- return mService.getDhcpInfo();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Enable or disable Wi-Fi.
- * <p>
- * Applications must have the {@link android.Manifest.permission#CHANGE_WIFI_STATE}
- * permission to toggle wifi.
- *
- * @param enabled {@code true} to enable, {@code false} to disable.
- * @return {@code false} if the request cannot be satisfied; {@code true} indicates that wifi is
- * either already in the requested state, or in progress toward the requested state.
- * @throws {@link java.lang.SecurityException} if the caller is missing required permissions.
- *
- * @deprecated Starting with Build.VERSION_CODES#Q, applications are not allowed to
- * enable/disable Wi-Fi.
- * <b>Compatibility Note:</b> For applications targeting
- * {@link android.os.Build.VERSION_CODES#Q} or above, this API will always fail and return
- * {@code false}. If apps are targeting an older SDK ({@link android.os.Build.VERSION_CODES#P}
- * or below), they can continue to use this API.
- * <p>
- * Deprecation Exemptions:
- * <ul>
- * <li>Device Owner (DO), Profile Owner (PO) and system apps.
- * </ul>
- */
- @Deprecated
- public boolean setWifiEnabled(boolean enabled) {
- try {
- return mService.setWifiEnabled(mContext.getOpPackageName(), enabled);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Gets the Wi-Fi enabled state.
- * @return One of {@link #WIFI_STATE_DISABLED},
- * {@link #WIFI_STATE_DISABLING}, {@link #WIFI_STATE_ENABLED},
- * {@link #WIFI_STATE_ENABLING}, {@link #WIFI_STATE_UNKNOWN}
- * @see #isWifiEnabled()
- */
- public int getWifiState() {
- try {
- return mService.getWifiEnabledState();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return whether Wi-Fi is enabled or disabled.
- * @return {@code true} if Wi-Fi is enabled
- * @see #getWifiState()
- */
- public boolean isWifiEnabled() {
- return getWifiState() == WIFI_STATE_ENABLED;
- }
-
- /**
- * Calculates the level of the signal. This should be used any time a signal
- * is being shown.
- *
- * @param rssi The power of the signal measured in RSSI.
- * @param numLevels The number of levels to consider in the calculated level.
- * @return A level of the signal, given in the range of 0 to numLevels-1 (both inclusive).
- * @deprecated Callers should use {@link #calculateSignalLevel(int)} instead to get the
- * signal level using the system default RSSI thresholds, or otherwise compute the RSSI level
- * themselves using their own formula.
- */
- @Deprecated
- public static int calculateSignalLevel(int rssi, int numLevels) {
- if (rssi <= MIN_RSSI) {
- return 0;
- } else if (rssi >= MAX_RSSI) {
- return numLevels - 1;
- } else {
- float inputRange = (MAX_RSSI - MIN_RSSI);
- float outputRange = (numLevels - 1);
- return (int)((float)(rssi - MIN_RSSI) * outputRange / inputRange);
- }
- }
-
- /**
- * Given a raw RSSI, return the RSSI signal quality rating using the system default RSSI
- * quality rating thresholds.
- * @param rssi a raw RSSI value, in dBm, usually between -55 and -90
- * @return the RSSI signal quality rating, in the range
- * [0, {@link #getMaxSignalLevel()}], where 0 is the lowest (worst signal) RSSI
- * rating and {@link #getMaxSignalLevel()} is the highest (best signal) RSSI rating.
- */
- @IntRange(from = 0)
- public int calculateSignalLevel(int rssi) {
- try {
- return mService.calculateSignalLevel(rssi);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get the system default maximum signal level.
- * This is the maximum RSSI level returned by {@link #calculateSignalLevel(int)}.
- */
- @IntRange(from = 0)
- public int getMaxSignalLevel() {
- return calculateSignalLevel(Integer.MAX_VALUE);
- }
-
- /**
- * Compares two signal strengths.
- *
- * @param rssiA The power of the first signal measured in RSSI.
- * @param rssiB The power of the second signal measured in RSSI.
- * @return Returns <0 if the first signal is weaker than the second signal,
- * 0 if the two signals have the same strength, and >0 if the first
- * signal is stronger than the second signal.
- */
- public static int compareSignalLevel(int rssiA, int rssiB) {
- return rssiA - rssiB;
- }
-
- /**
- * Call allowing ConnectivityService to update WifiService with interface mode changes.
- *
- * @param ifaceName String name of the updated interface, or null to represent all interfaces
- * @param mode int representing the new mode, one of:
- * {@link #IFACE_IP_MODE_TETHERED},
- * {@link #IFACE_IP_MODE_LOCAL_ONLY},
- * {@link #IFACE_IP_MODE_CONFIGURATION_ERROR},
- * {@link #IFACE_IP_MODE_UNSPECIFIED}
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_STACK,
- NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
- })
- public void updateInterfaceIpState(@Nullable String ifaceName, @IfaceIpMode int mode) {
- try {
- mService.updateInterfaceIpState(ifaceName, mode);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /* Wi-Fi/Cellular Coex */
-
- /**
- * Mandatory coex restriction flag for Wi-Fi Direct.
- *
- * @see #setCoexUnsafeChannels(Set, int)
- *
- * @hide
- */
- @SystemApi
- public static final int COEX_RESTRICTION_WIFI_DIRECT = 0x1 << 0;
-
- /**
- * Mandatory coex restriction flag for SoftAP
- *
- * @see #setCoexUnsafeChannels(Set, int)
- *
- * @hide
- */
- @SystemApi
- public static final int COEX_RESTRICTION_SOFTAP = 0x1 << 1;
-
- /**
- * Mandatory coex restriction flag for Wi-Fi Aware.
- *
- * @see #setCoexUnsafeChannels(Set, int)
- *
- * @hide
- */
- @SystemApi
- public static final int COEX_RESTRICTION_WIFI_AWARE = 0x1 << 2;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(flag = true, prefix = {"COEX_RESTRICTION_"}, value = {
- COEX_RESTRICTION_WIFI_DIRECT,
- COEX_RESTRICTION_SOFTAP,
- COEX_RESTRICTION_WIFI_AWARE
- })
- public @interface CoexRestriction {}
-
- /**
- * Specify the set of {@link CoexUnsafeChannel} to propagate through the framework for
- * Wi-Fi/Cellular coex channel avoidance if the default algorithm is disabled via overlay
- * (i.e. config_wifiCoexDefaultAlgorithmEnabled = false). Otherwise do nothing.
- *
- * @param unsafeChannels Set of {@link CoexUnsafeChannel} to avoid.
- * @param restrictions Bitmap of {@link CoexRestriction} specifying the mandatory restricted
- * uses of the specified channels. If any restrictions are set, then the
- * supplied CoexUnsafeChannels will be completely avoided for the
- * specified modes, rather than be avoided with best effort.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_COEX_UNSAFE_CHANNELS)
- public void setCoexUnsafeChannels(@NonNull Set<CoexUnsafeChannel> unsafeChannels,
- int restrictions) {
- if (unsafeChannels == null) {
- throw new IllegalArgumentException("unsafeChannels must not be null");
- }
- try {
- mService.setCoexUnsafeChannels(new ArrayList<>(unsafeChannels), restrictions);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns the set of current {@link CoexUnsafeChannel} being used for Wi-Fi/Cellular coex
- * channel avoidance.
- *
- * This returns the set calculated by the default algorithm if
- * config_wifiCoexDefaultAlgorithmEnabled is {@code true}. Otherwise, returns the set supplied
- * in {@link #setCoexUnsafeChannels(Set, int)}.
- *
- * If any {@link CoexRestriction} flags are set in {@link #getCoexRestrictions()}, then the
- * CoexUnsafeChannels should be totally avoided (i.e. not best effort) for the Wi-Fi modes
- * specified by the flags.
- *
- * @return Set of current CoexUnsafeChannels.
- *
- * @hide
- */
- @NonNull
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_ACCESS_COEX_UNSAFE_CHANNELS)
- public Set<CoexUnsafeChannel> getCoexUnsafeChannels() {
- try {
- return new HashSet<>(mService.getCoexUnsafeChannels());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns the current coex restrictions being used for Wi-Fi/Cellular coex
- * channel avoidance.
- *
- * This returns the restrictions calculated by the default algorithm if
- * config_wifiCoexDefaultAlgorithmEnabled is {@code true}. Otherwise, returns the value supplied
- * in {@link #setCoexUnsafeChannels(Set, int)}.
- *
- * @return int containing a bitwise-OR combination of {@link CoexRestriction}.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_ACCESS_COEX_UNSAFE_CHANNELS)
- public int getCoexRestrictions() {
- try {
- return mService.getCoexRestrictions();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Registers a CoexCallback to listen on the current CoexUnsafeChannels and restrictions being
- * used for Wi-Fi/cellular coex channel avoidance.
- * @param executor Executor to execute listener callback on
- * @param callback CoexCallback to register
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_ACCESS_COEX_UNSAFE_CHANNELS)
- public void registerCoexCallback(
- @NonNull @CallbackExecutor Executor executor, @NonNull CoexCallback callback) {
- if (executor == null) throw new IllegalArgumentException("executor must not be null");
- if (callback == null) throw new IllegalArgumentException("callback must not be null");
- CoexCallback.CoexCallbackProxy proxy = callback.getProxy();
- proxy.initProxy(executor, callback);
- try {
- mService.registerCoexCallback(proxy);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Unregisters a CoexCallback from listening on the current CoexUnsafeChannels and restrictions
- * being used for Wi-Fi/cellular coex channel avoidance.
- * @param callback CoexCallback to unregister
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_ACCESS_COEX_UNSAFE_CHANNELS)
- public void unregisterCoexCallback(@NonNull CoexCallback callback) {
- if (callback == null) throw new IllegalArgumentException("callback must not be null");
- CoexCallback.CoexCallbackProxy proxy = callback.getProxy();
- try {
- mService.unregisterCoexCallback(proxy);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- } finally {
- proxy.cleanUpProxy();
- }
- }
-
- /**
- * Abstract callback class for applications to receive updates about current CoexUnsafeChannels
- * for Wi-Fi/Cellular coex channel avoidance.
- *
- * @hide
- */
- @SystemApi
- public abstract static class CoexCallback {
- private final CoexCallbackProxy mCoexCallbackProxy;
-
- public CoexCallback() {
- mCoexCallbackProxy = new CoexCallbackProxy();
- }
-
- /*package*/ @NonNull
- CoexCallbackProxy getProxy() {
- return mCoexCallbackProxy;
- }
-
- /**
- * Indicates that the current CoexUnsafeChannels or restrictions have changed.
- * Clients should call {@link #getCoexUnsafeChannels()} and {@link #getCoexRestrictions()}
- * to get the updated values.
- */
- public abstract void onCoexUnsafeChannelsChanged();
-
- /**
- * Callback proxy for CoexCallback objects.
- */
- private static class CoexCallbackProxy extends ICoexCallback.Stub {
- private final Object mLock = new Object();
- @Nullable @GuardedBy("mLock") private Executor mExecutor;
- @Nullable @GuardedBy("mLock") private CoexCallback mCallback;
-
- CoexCallbackProxy() {
- mExecutor = null;
- mCallback = null;
- }
-
- /*package*/ void initProxy(@NonNull Executor executor,
- @NonNull CoexCallback callback) {
- synchronized (mLock) {
- mExecutor = executor;
- mCallback = callback;
- }
- }
-
- /*package*/ void cleanUpProxy() {
- synchronized (mLock) {
- mExecutor = null;
- mCallback = null;
- }
- }
-
- @Override
- public void onCoexUnsafeChannelsChanged() {
- Executor executor;
- CoexCallback callback;
- synchronized (mLock) {
- executor = mExecutor;
- callback = mCallback;
- }
- if (executor == null || callback == null) {
- return;
- }
- Binder.clearCallingIdentity();
- executor.execute(callback::onCoexUnsafeChannelsChanged);
- }
- }
- }
-
- /**
- * Start Soft AP (hotspot) mode for tethering purposes with the specified configuration.
- * Note that starting Soft AP mode may disable station mode operation if the device does not
- * support concurrency.
- * @param wifiConfig SSID, security and channel details as part of WifiConfiguration, or null to
- * use the persisted Soft AP configuration that was previously set using
- * {@link #setWifiApConfiguration(WifiConfiguration)}.
- * @return {@code true} if the operation succeeded, {@code false} otherwise
- *
- * @hide
- */
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_STACK,
- NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
- })
- public boolean startSoftAp(@Nullable WifiConfiguration wifiConfig) {
- try {
- return mService.startSoftAp(wifiConfig, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Start Soft AP (hotspot) mode for tethering purposes with the specified configuration.
- * Note that starting Soft AP mode may disable station mode operation if the device does not
- * support concurrency.
- * @param softApConfig A valid SoftApConfiguration specifying the configuration of the SAP,
- * or null to use the persisted Soft AP configuration that was previously
- * set using {@link #setSoftApConfiguration(softApConfiguration)}.
- * @return {@code true} if the operation succeeded, {@code false} otherwise
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_STACK,
- NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
- })
- public boolean startTetheredHotspot(@Nullable SoftApConfiguration softApConfig) {
- try {
- return mService.startTetheredHotspot(softApConfig, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
-
- /**
- * Stop SoftAp mode.
- * Note that stopping softap mode will restore the previous wifi mode.
- * @return {@code true} if the operation succeeds, {@code false} otherwise
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_STACK,
- NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK
- })
- public boolean stopSoftAp() {
- try {
- return mService.stopSoftAp();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Request a local only hotspot that an application can use to communicate between co-located
- * devices connected to the created WiFi hotspot. The network created by this method will not
- * have Internet access. Each application can make a single request for the hotspot, but
- * multiple applications could be requesting the hotspot at the same time. When multiple
- * applications have successfully registered concurrently, they will be sharing the underlying
- * hotspot. {@link LocalOnlyHotspotCallback#onStarted(LocalOnlyHotspotReservation)} is called
- * when the hotspot is ready for use by the application.
- * <p>
- * Each application can make a single active call to this method. The {@link
- * LocalOnlyHotspotCallback#onStarted(LocalOnlyHotspotReservation)} callback supplies the
- * requestor with a {@link LocalOnlyHotspotReservation} that contains a
- * {@link SoftApConfiguration} with the SSID, security type and credentials needed to connect
- * to the hotspot. Communicating this information is up to the application.
- * <p>
- * If the LocalOnlyHotspot cannot be created, the {@link LocalOnlyHotspotCallback#onFailed(int)}
- * method will be called. Example failures include errors bringing up the network or if
- * there is an incompatible operating mode. For example, if the user is currently using Wifi
- * Tethering to provide an upstream to another device, LocalOnlyHotspot will not start due to
- * an incompatible mode. The possible error codes include:
- * {@link LocalOnlyHotspotCallback#ERROR_NO_CHANNEL},
- * {@link LocalOnlyHotspotCallback#ERROR_GENERIC},
- * {@link LocalOnlyHotspotCallback#ERROR_INCOMPATIBLE_MODE} and
- * {@link LocalOnlyHotspotCallback#ERROR_TETHERING_DISALLOWED}.
- * <p>
- * Internally, requests will be tracked to prevent the hotspot from being torn down while apps
- * are still using it. The {@link LocalOnlyHotspotReservation} object passed in the {@link
- * LocalOnlyHotspotCallback#onStarted(LocalOnlyHotspotReservation)} call should be closed when
- * the LocalOnlyHotspot is no longer needed using {@link LocalOnlyHotspotReservation#close()}.
- * Since the hotspot may be shared among multiple applications, removing the final registered
- * application request will trigger the hotspot teardown. This means that applications should
- * not listen to broadcasts containing wifi state to determine if the hotspot was stopped after
- * they are done using it. Additionally, once {@link LocalOnlyHotspotReservation#close()} is
- * called, applications will not receive callbacks of any kind.
- * <p>
- * Applications should be aware that the user may also stop the LocalOnlyHotspot through the
- * Settings UI; it is not guaranteed to stay up as long as there is a requesting application.
- * The requestors will be notified of this case via
- * {@link LocalOnlyHotspotCallback#onStopped()}. Other cases may arise where the hotspot is
- * torn down (Emergency mode, etc). Application developers should be aware that it can stop
- * unexpectedly, but they will receive a notification if they have properly registered.
- * <p>
- * Applications should also be aware that this network will be shared with other applications.
- * Applications are responsible for protecting their data on this network (e.g., TLS).
- * <p>
- * Applications need to have the following permissions to start LocalOnlyHotspot: {@link
- * android.Manifest.permission#CHANGE_WIFI_STATE} and {@link
- * android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION}. Callers without
- * the permissions will trigger a {@link java.lang.SecurityException}.
- * <p>
- * @param callback LocalOnlyHotspotCallback for the application to receive updates about
- * operating status.
- * @param handler Handler to be used for callbacks. If the caller passes a null Handler, the
- * main thread will be used.
- */
- @RequiresPermission(allOf = {
- android.Manifest.permission.CHANGE_WIFI_STATE,
- android.Manifest.permission.ACCESS_FINE_LOCATION})
- public void startLocalOnlyHotspot(LocalOnlyHotspotCallback callback,
- @Nullable Handler handler) {
- Executor executor = handler == null ? null : new HandlerExecutor(handler);
- startLocalOnlyHotspotInternal(null, executor, callback);
- }
-
- /**
- * Starts a local-only hotspot with a specific configuration applied. See
- * {@link #startLocalOnlyHotspot(LocalOnlyHotspotCallback, Handler)}.
- *
- * Applications need either {@link android.Manifest.permission#NETWORK_SETUP_WIZARD} or
- * {@link android.Manifest.permission#NETWORK_SETTINGS} to call this method.
- *
- * Since custom configuration settings may be incompatible with each other, the hotspot started
- * through this method cannot coexist with another hotspot created through
- * startLocalOnlyHotspot. If this is attempted, the first hotspot request wins and others
- * receive {@link LocalOnlyHotspotCallback#ERROR_GENERIC} through
- * {@link LocalOnlyHotspotCallback#onFailed}.
- *
- * @param config Custom configuration for the hotspot. See {@link SoftApConfiguration}.
- * @param executor Executor to run callback methods on, or null to use the main thread.
- * @param callback Callback object for updates about hotspot status, or null for no updates.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void startLocalOnlyHotspot(@NonNull SoftApConfiguration config,
- @Nullable Executor executor,
- @Nullable LocalOnlyHotspotCallback callback) {
- Objects.requireNonNull(config);
- startLocalOnlyHotspotInternal(config, executor, callback);
- }
-
- /**
- * Common implementation of both configurable and non-configurable LOHS.
- *
- * @param config App-specified configuration, or null. When present, additional privileges are
- * required, and the hotspot cannot be shared with other clients.
- * @param executor Executor to run callback methods on, or null to use the main thread.
- * @param callback Callback object for updates about hotspot status, or null for no updates.
- */
- private void startLocalOnlyHotspotInternal(
- @Nullable SoftApConfiguration config,
- @Nullable Executor executor,
- @Nullable LocalOnlyHotspotCallback callback) {
- if (executor == null) {
- executor = mContext.getMainExecutor();
- }
- synchronized (mLock) {
- LocalOnlyHotspotCallbackProxy proxy =
- new LocalOnlyHotspotCallbackProxy(this, executor, callback);
- try {
- String packageName = mContext.getOpPackageName();
- String featureId = mContext.getAttributionTag();
- int returnCode = mService.startLocalOnlyHotspot(proxy, packageName, featureId,
- config);
- if (returnCode != LocalOnlyHotspotCallback.REQUEST_REGISTERED) {
- // Send message to the proxy to make sure we call back on the correct thread
- proxy.onHotspotFailed(returnCode);
- return;
- }
- mLOHSCallbackProxy = proxy;
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Cancels a pending local only hotspot request. This can be used by the calling application to
- * cancel the existing request if the provided callback has not been triggered. Calling this
- * method will be equivalent to closing the returned LocalOnlyHotspotReservation, but it is not
- * explicitly required.
- * <p>
- * When cancelling this request, application developers should be aware that there may still be
- * outstanding local only hotspot requests and the hotspot may still start, or continue running.
- * Additionally, if a callback was registered, it will no longer be triggered after calling
- * cancel.
- *
- * @hide
- */
- @UnsupportedAppUsage
- public void cancelLocalOnlyHotspotRequest() {
- synchronized (mLock) {
- stopLocalOnlyHotspot();
- }
- }
-
- /**
- * Method used to inform WifiService that the LocalOnlyHotspot is no longer needed. This
- * method is used by WifiManager to release LocalOnlyHotspotReservations held by calling
- * applications and removes the internal tracking for the hotspot request. When all requesting
- * applications are finished using the hotspot, it will be stopped and WiFi will return to the
- * previous operational mode.
- *
- * This method should not be called by applications. Instead, they should call the close()
- * method on their LocalOnlyHotspotReservation.
- */
- private void stopLocalOnlyHotspot() {
- synchronized (mLock) {
- if (mLOHSCallbackProxy == null) {
- // nothing to do, the callback was already cleaned up.
- return;
- }
- mLOHSCallbackProxy = null;
- try {
- mService.stopLocalOnlyHotspot();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Allow callers (Settings UI) to watch LocalOnlyHotspot state changes. Callers will
- * receive a {@link LocalOnlyHotspotSubscription} object as a parameter of the
- * {@link LocalOnlyHotspotObserver#onRegistered(LocalOnlyHotspotSubscription)}. The registered
- * callers will receive the {@link LocalOnlyHotspotObserver#onStarted(SoftApConfiguration)} and
- * {@link LocalOnlyHotspotObserver#onStopped()} callbacks.
- * <p>
- * Applications should have the
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION}
- * permission. Callers without the permission will trigger a
- * {@link java.lang.SecurityException}.
- * <p>
- * @param observer LocalOnlyHotspotObserver callback.
- * @param handler Handler to use for callbacks
- *
- * @hide
- */
- public void watchLocalOnlyHotspot(LocalOnlyHotspotObserver observer,
- @Nullable Handler handler) {
- Executor executor = handler == null ? mContext.getMainExecutor()
- : new HandlerExecutor(handler);
- synchronized (mLock) {
- mLOHSObserverProxy =
- new LocalOnlyHotspotObserverProxy(this, executor, observer);
- try {
- mService.startWatchLocalOnlyHotspot(mLOHSObserverProxy);
- mLOHSObserverProxy.registered();
- } catch (RemoteException e) {
- mLOHSObserverProxy = null;
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Allow callers to stop watching LocalOnlyHotspot state changes. After calling this method,
- * applications will no longer receive callbacks.
- *
- * @hide
- */
- public void unregisterLocalOnlyHotspotObserver() {
- synchronized (mLock) {
- if (mLOHSObserverProxy == null) {
- // nothing to do, the callback was already cleaned up
- return;
- }
- mLOHSObserverProxy = null;
- try {
- mService.stopWatchLocalOnlyHotspot();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Gets the tethered Wi-Fi hotspot enabled state.
- * @return One of {@link #WIFI_AP_STATE_DISABLED},
- * {@link #WIFI_AP_STATE_DISABLING}, {@link #WIFI_AP_STATE_ENABLED},
- * {@link #WIFI_AP_STATE_ENABLING}, {@link #WIFI_AP_STATE_FAILED}
- * @see #isWifiApEnabled()
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
- public int getWifiApState() {
- try {
- return mService.getWifiApEnabledState();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return whether tethered Wi-Fi AP is enabled or disabled.
- * @return {@code true} if tethered Wi-Fi AP is enabled
- * @see #getWifiApState()
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
- public boolean isWifiApEnabled() {
- return getWifiApState() == WIFI_AP_STATE_ENABLED;
- }
-
- /**
- * Gets the tethered Wi-Fi AP Configuration.
- * @return AP details in WifiConfiguration
- *
- * Note that AP detail may contain configuration which is cannot be represented
- * by the legacy WifiConfiguration, in such cases a null will be returned.
- *
- * @deprecated This API is deprecated. Use {@link #getSoftApConfiguration()} instead.
- * @hide
- */
- @Nullable
- @SystemApi
- @RequiresPermission(android.Manifest.permission.ACCESS_WIFI_STATE)
- @Deprecated
- public WifiConfiguration getWifiApConfiguration() {
- try {
- return mService.getWifiApConfiguration();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Gets the Wi-Fi tethered AP Configuration.
- * @return AP details in {@link SoftApConfiguration}
- *
- * @hide
- */
- @NonNull
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.OVERRIDE_WIFI_CONFIG
- })
- public SoftApConfiguration getSoftApConfiguration() {
- try {
- return mService.getSoftApConfiguration();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Sets the tethered Wi-Fi AP Configuration.
- * @return {@code true} if the operation succeeded, {@code false} otherwise
- *
- * @deprecated This API is deprecated. Use {@link #setSoftApConfiguration(SoftApConfiguration)}
- * instead.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.CHANGE_WIFI_STATE)
- @Deprecated
- public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
- try {
- return mService.setWifiApConfiguration(wifiConfig, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Sets the tethered Wi-Fi AP Configuration.
- *
- * If the API is called while the tethered soft AP is enabled, the configuration will apply to
- * the current soft AP if the new configuration only includes
- * {@link SoftApConfiguration.Builder#setMaxNumberOfClients(int)}
- * or {@link SoftApConfiguration.Builder#setShutdownTimeoutMillis(long)}
- * or {@link SoftApConfiguration.Builder#setClientControlByUserEnabled(boolean)}
- * or {@link SoftApConfiguration.Builder#setBlockedClientList(List)}
- * or {@link SoftApConfiguration.Builder#setAllowedClientList(List)}
- *
- * Otherwise, the configuration changes will be applied when the Soft AP is next started
- * (the framework will not stop/start the AP).
- *
- * @param softApConfig A valid SoftApConfiguration specifying the configuration of the SAP.
- * @return {@code true} if the operation succeeded, {@code false} otherwise
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.OVERRIDE_WIFI_CONFIG
- })
- public boolean setSoftApConfiguration(@NonNull SoftApConfiguration softApConfig) {
- try {
- return mService.setSoftApConfiguration(
- softApConfig, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Enable/Disable TDLS on a specific local route.
- *
- * <p>
- * TDLS enables two wireless endpoints to talk to each other directly
- * without going through the access point that is managing the local
- * network. It saves bandwidth and improves quality of the link.
- * </p>
- * <p>
- * This API enables/disables the option of using TDLS. If enabled, the
- * underlying hardware is free to use TDLS or a hop through the access
- * point. If disabled, existing TDLS session is torn down and
- * hardware is restricted to use access point for transferring wireless
- * packets. Default value for all routes is 'disabled', meaning restricted
- * to use access point for transferring packets.
- * </p>
- *
- * @param remoteIPAddress IP address of the endpoint to setup TDLS with
- * @param enable true = setup and false = tear down TDLS
- */
- public void setTdlsEnabled(InetAddress remoteIPAddress, boolean enable) {
- try {
- mService.enableTdls(remoteIPAddress.getHostAddress(), enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Similar to {@link #setTdlsEnabled(InetAddress, boolean) }, except
- * this version allows you to specify remote endpoint with a MAC address.
- * @param remoteMacAddress MAC address of the remote endpoint such as 00:00:0c:9f:f2:ab
- * @param enable true = setup and false = tear down TDLS
- */
- public void setTdlsEnabledWithMacAddress(String remoteMacAddress, boolean enable) {
- try {
- mService.enableTdlsWithMacAddress(remoteMacAddress, enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation failed due to an internal error.
- * @hide
- */
- public static final int ERROR = 0;
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation is already in progress
- * @hide
- */
- public static final int IN_PROGRESS = 1;
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation failed because the framework is busy and
- * unable to service the request
- * @hide
- */
- public static final int BUSY = 2;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef({ERROR, IN_PROGRESS, BUSY})
- public @interface ActionListenerFailureReason {}
-
- /* WPS specific errors */
- /** WPS overlap detected
- * @deprecated This is deprecated
- */
- public static final int WPS_OVERLAP_ERROR = 3;
- /** WEP on WPS is prohibited
- * @deprecated This is deprecated
- */
- public static final int WPS_WEP_PROHIBITED = 4;
- /** TKIP only prohibited
- * @deprecated This is deprecated
- */
- public static final int WPS_TKIP_ONLY_PROHIBITED = 5;
- /** Authentication failure on WPS
- * @deprecated This is deprecated
- */
- public static final int WPS_AUTH_FAILURE = 6;
- /** WPS timed out
- * @deprecated This is deprecated
- */
- public static final int WPS_TIMED_OUT = 7;
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation failed due to invalid inputs
- * @hide
- */
- public static final int INVALID_ARGS = 8;
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation failed due to user permissions.
- * @hide
- */
- public static final int NOT_AUTHORIZED = 9;
-
- /**
- * Interface for callback invocation on an application action
- * @hide
- */
- @SystemApi
- public interface ActionListener {
- /**
- * The operation succeeded.
- */
- void onSuccess();
- /**
- * The operation failed.
- * @param reason The reason for failure depends on the operation.
- */
- void onFailure(@ActionListenerFailureReason int reason);
- }
-
- /** Interface for callback invocation on a start WPS action
- * @deprecated This is deprecated
- */
- public static abstract class WpsCallback {
-
- /** WPS start succeeded
- * @deprecated This API is deprecated
- */
- public abstract void onStarted(String pin);
-
- /** WPS operation completed successfully
- * @deprecated This API is deprecated
- */
- public abstract void onSucceeded();
-
- /**
- * WPS operation failed
- * @param reason The reason for failure could be one of
- * {@link #WPS_TKIP_ONLY_PROHIBITED}, {@link #WPS_OVERLAP_ERROR},
- * {@link #WPS_WEP_PROHIBITED}, {@link #WPS_TIMED_OUT} or {@link #WPS_AUTH_FAILURE}
- * and some generic errors.
- * @deprecated This API is deprecated
- */
- public abstract void onFailed(int reason);
- }
-
- /**
- * Base class for soft AP callback. Should be extended by applications and set when calling
- * {@link WifiManager#registerSoftApCallback(Executor, SoftApCallback)}.
- *
- * @hide
- */
- @SystemApi
- public interface SoftApCallback {
- /**
- * Called when soft AP state changes.
- *
- * @param state the new AP state. One of {@link #WIFI_AP_STATE_DISABLED},
- * {@link #WIFI_AP_STATE_DISABLING}, {@link #WIFI_AP_STATE_ENABLED},
- * {@link #WIFI_AP_STATE_ENABLING}, {@link #WIFI_AP_STATE_FAILED}
- * @param failureReason reason when in failed state. One of
- * {@link #SAP_START_FAILURE_GENERAL},
- * {@link #SAP_START_FAILURE_NO_CHANNEL},
- * {@link #SAP_START_FAILURE_UNSUPPORTED_CONFIGURATION}
- */
- default void onStateChanged(@WifiApState int state, @SapStartFailure int failureReason) {}
-
- /**
- * Called when the connected clients to soft AP changes.
- *
- * @param clients the currently connected clients
- */
- default void onConnectedClientsChanged(@NonNull List<WifiClient> clients) {}
-
- /**
- * Called when information of softap changes.
- *
- * @param softApInfo is the softap information. {@link SoftApInfo}
- */
- default void onInfoChanged(@NonNull SoftApInfo softApInfo) {
- // Do nothing: can be updated to add SoftApInfo details (e.g. channel) to the UI.
- }
-
- /**
- * Called when capability of softap changes.
- *
- * @param softApCapability is the softap capability. {@link SoftApCapability}
- */
- default void onCapabilityChanged(@NonNull SoftApCapability softApCapability) {
- // Do nothing: can be updated to add SoftApCapability details (e.g. meximum supported
- // client number) to the UI.
- }
-
- /**
- * Called when client trying to connect but device blocked the client with specific reason.
- *
- * Can be used to ask user to update client to allowed list or blocked list
- * when reason is {@link SAP_CLIENT_BLOCK_REASON_CODE_BLOCKED_BY_USER}, or
- * indicate the block due to maximum supported client number limitation when reason is
- * {@link SAP_CLIENT_BLOCK_REASON_CODE_NO_MORE_STAS}.
- *
- * @param client the currently blocked client.
- * @param blockedReason one of blocked reason from {@link SapClientBlockedReason}
- */
- default void onBlockedClientConnecting(@NonNull WifiClient client,
- @SapClientBlockedReason int blockedReason) {
- // Do nothing: can be used to ask user to update client to allowed list or blocked list.
- }
- }
-
- /**
- * Callback proxy for SoftApCallback objects.
- *
- * @hide
- */
- private class SoftApCallbackProxy extends ISoftApCallback.Stub {
- private final Executor mExecutor;
- private final SoftApCallback mCallback;
-
- SoftApCallbackProxy(Executor executor, SoftApCallback callback) {
- mExecutor = executor;
- mCallback = callback;
- }
-
- @Override
- public void onStateChanged(int state, int failureReason) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "SoftApCallbackProxy: onStateChanged: state=" + state
- + ", failureReason=" + failureReason);
- }
-
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onStateChanged(state, failureReason);
- });
- }
-
- @Override
- public void onConnectedClientsChanged(List<WifiClient> clients) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "SoftApCallbackProxy: onConnectedClientsChanged: clients="
- + clients.size() + " clients");
- }
-
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onConnectedClientsChanged(clients);
- });
- }
-
- @Override
- public void onInfoChanged(SoftApInfo softApInfo) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "SoftApCallbackProxy: onInfoChange: softApInfo=" + softApInfo);
- }
-
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onInfoChanged(softApInfo);
- });
- }
-
- @Override
- public void onCapabilityChanged(SoftApCapability capability) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "SoftApCallbackProxy: onCapabilityChanged: SoftApCapability="
- + capability);
- }
-
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onCapabilityChanged(capability);
- });
- }
-
- @Override
- public void onBlockedClientConnecting(@NonNull WifiClient client, int blockedReason) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "SoftApCallbackProxy: onBlockedClientConnecting: client=" + client
- + " with reason = " + blockedReason);
- }
-
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onBlockedClientConnecting(client, blockedReason);
- });
- }
- }
-
- /**
- * Registers a callback for Soft AP. See {@link SoftApCallback}. Caller will receive the
- * following callbacks on registration:
- * <ul>
- * <li> {@link SoftApCallback#onStateChanged(int, int)}</li>
- * <li> {@link SoftApCallback#onConnectedClientsChanged(List<WifiClient>)}</li>
- * <li> {@link SoftApCallback#onInfoChanged(SoftApInfo)}</li>
- * <li> {@link SoftApCallback#onCapabilityChanged(SoftApCapability)}</li>
- * </ul>
- * These will be dispatched on registration to provide the caller with the current state
- * (and are not an indication of any current change). Note that receiving an immediate
- * WIFI_AP_STATE_FAILED value for soft AP state indicates that the latest attempt to start
- * soft AP has failed. Caller can unregister a previously registered callback using
- * {@link #unregisterSoftApCallback}
- * <p>
- * Applications should have the
- * {@link android.Manifest.permission#NETWORK_SETTINGS NETWORK_SETTINGS} permission. Callers
- * without the permission will trigger a {@link java.lang.SecurityException}.
- * <p>
- *
- * @param executor The Executor on whose thread to execute the callbacks of the {@code callback}
- * object.
- * @param callback Callback for soft AP events
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void registerSoftApCallback(@NonNull @CallbackExecutor Executor executor,
- @NonNull SoftApCallback callback) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "registerSoftApCallback: callback=" + callback + ", executor=" + executor);
-
- Binder binder = new Binder();
- try {
- mService.registerSoftApCallback(
- binder, new SoftApCallbackProxy(executor, callback), callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow callers to unregister a previously registered callback. After calling this method,
- * applications will no longer receive soft AP events.
- *
- * @param callback Callback to unregister for soft AP events
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void unregisterSoftApCallback(@NonNull SoftApCallback callback) {
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "unregisterSoftApCallback: callback=" + callback);
-
- try {
- mService.unregisterSoftApCallback(callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * LocalOnlyHotspotReservation that contains the {@link SoftApConfiguration} for the active
- * LocalOnlyHotspot request.
- * <p>
- * Applications requesting LocalOnlyHotspot for sharing will receive an instance of the
- * LocalOnlyHotspotReservation in the
- * {@link LocalOnlyHotspotCallback#onStarted(LocalOnlyHotspotReservation)} call. This
- * reservation contains the relevant {@link SoftApConfiguration}.
- * When an application is done with the LocalOnlyHotspot, they should call {@link
- * LocalOnlyHotspotReservation#close()}. Once this happens, the application will not receive
- * any further callbacks. If the LocalOnlyHotspot is stopped due to a
- * user triggered mode change, applications will be notified via the {@link
- * LocalOnlyHotspotCallback#onStopped()} callback.
- */
- public class LocalOnlyHotspotReservation implements AutoCloseable {
-
- private final CloseGuard mCloseGuard = new CloseGuard();
- private final SoftApConfiguration mSoftApConfig;
- private final WifiConfiguration mWifiConfig;
- private boolean mClosed = false;
-
- /** @hide */
- @VisibleForTesting
- public LocalOnlyHotspotReservation(SoftApConfiguration config) {
- mSoftApConfig = config;
- mWifiConfig = config.toWifiConfiguration();
- mCloseGuard.open("close");
- }
-
- /**
- * Returns the {@link WifiConfiguration} of the current Local Only Hotspot (LOHS).
- * May be null if hotspot enabled and security type is not
- * {@code WifiConfiguration.KeyMgmt.None} or {@code WifiConfiguration.KeyMgmt.WPA2_PSK}.
- *
- * @deprecated Use {@code WifiManager#getSoftApConfiguration()} to get the
- * LOHS configuration.
- */
- @Deprecated
- @Nullable
- public WifiConfiguration getWifiConfiguration() {
- return mWifiConfig;
- }
-
- /**
- * Returns the {@link SoftApConfiguration} of the current Local Only Hotspot (LOHS).
- */
- @NonNull
- public SoftApConfiguration getSoftApConfiguration() {
- return mSoftApConfig;
- }
-
- @Override
- public void close() {
- try {
- synchronized (mLock) {
- if (!mClosed) {
- mClosed = true;
- stopLocalOnlyHotspot();
- mCloseGuard.close();
- }
- }
- } catch (Exception e) {
- Log.e(TAG, "Failed to stop Local Only Hotspot.");
- } finally {
- Reference.reachabilityFence(this);
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- try {
- if (mCloseGuard != null) {
- mCloseGuard.warnIfOpen();
- }
- close();
- } finally {
- super.finalize();
- }
- }
- }
-
- /**
- * Callback class for applications to receive updates about the LocalOnlyHotspot status.
- */
- public static class LocalOnlyHotspotCallback {
- /** @hide */
- public static final int REQUEST_REGISTERED = 0;
-
- public static final int ERROR_NO_CHANNEL = 1;
- public static final int ERROR_GENERIC = 2;
- public static final int ERROR_INCOMPATIBLE_MODE = 3;
- public static final int ERROR_TETHERING_DISALLOWED = 4;
-
- /** LocalOnlyHotspot start succeeded. */
- public void onStarted(LocalOnlyHotspotReservation reservation) {};
-
- /**
- * LocalOnlyHotspot stopped.
- * <p>
- * The LocalOnlyHotspot can be disabled at any time by the user. When this happens,
- * applications will be notified that it was stopped. This will not be invoked when an
- * application calls {@link LocalOnlyHotspotReservation#close()}.
- */
- public void onStopped() {};
-
- /**
- * LocalOnlyHotspot failed to start.
- * <p>
- * Applications can attempt to call
- * {@link WifiManager#startLocalOnlyHotspot(LocalOnlyHotspotCallback, Handler)} again at
- * a later time.
- * <p>
- * @param reason The reason for failure could be one of: {@link
- * #ERROR_TETHERING_DISALLOWED}, {@link #ERROR_INCOMPATIBLE_MODE},
- * {@link #ERROR_NO_CHANNEL}, or {@link #ERROR_GENERIC}.
- */
- public void onFailed(int reason) { };
- }
-
- /**
- * Callback proxy for LocalOnlyHotspotCallback objects.
- */
- private static class LocalOnlyHotspotCallbackProxy extends ILocalOnlyHotspotCallback.Stub {
- private final WeakReference<WifiManager> mWifiManager;
- private final Executor mExecutor;
- private final LocalOnlyHotspotCallback mCallback;
-
- /**
- * Constructs a {@link LocalOnlyHotspotCallbackProxy} using the specified executor. All
- * callbacks will run using the given executor.
- *
- * @param manager WifiManager
- * @param executor Executor for delivering callbacks.
- * @param callback LocalOnlyHotspotCallback to notify the calling application, or null.
- */
- LocalOnlyHotspotCallbackProxy(
- @NonNull WifiManager manager,
- @NonNull Executor executor,
- @Nullable LocalOnlyHotspotCallback callback) {
- mWifiManager = new WeakReference<>(manager);
- mExecutor = executor;
- mCallback = callback;
- }
-
- @Override
- public void onHotspotStarted(SoftApConfiguration config) {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- if (config == null) {
- Log.e(TAG, "LocalOnlyHotspotCallbackProxy: config cannot be null.");
- onHotspotFailed(LocalOnlyHotspotCallback.ERROR_GENERIC);
- return;
- }
- final LocalOnlyHotspotReservation reservation =
- manager.new LocalOnlyHotspotReservation(config);
- if (mCallback == null) return;
- mExecutor.execute(() -> mCallback.onStarted(reservation));
- }
-
- @Override
- public void onHotspotStopped() {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- Log.w(TAG, "LocalOnlyHotspotCallbackProxy: hotspot stopped");
- if (mCallback == null) return;
- mExecutor.execute(() -> mCallback.onStopped());
- }
-
- @Override
- public void onHotspotFailed(int reason) {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- Log.w(TAG, "LocalOnlyHotspotCallbackProxy: failed to start. reason: "
- + reason);
- if (mCallback == null) return;
- mExecutor.execute(() -> mCallback.onFailed(reason));
- }
- }
-
- /**
- * LocalOnlyHotspotSubscription that is an AutoCloseable object for tracking applications
- * watching for LocalOnlyHotspot changes.
- *
- * @hide
- */
- public class LocalOnlyHotspotSubscription implements AutoCloseable {
- private final CloseGuard mCloseGuard = new CloseGuard();
-
- /** @hide */
- @VisibleForTesting
- public LocalOnlyHotspotSubscription() {
- mCloseGuard.open("close");
- }
-
- @Override
- public void close() {
- try {
- unregisterLocalOnlyHotspotObserver();
- mCloseGuard.close();
- } catch (Exception e) {
- Log.e(TAG, "Failed to unregister LocalOnlyHotspotObserver.");
- } finally {
- Reference.reachabilityFence(this);
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- try {
- if (mCloseGuard != null) {
- mCloseGuard.warnIfOpen();
- }
- close();
- } finally {
- super.finalize();
- }
- }
- }
-
- /**
- * Class to notify calling applications that watch for changes in LocalOnlyHotspot of updates.
- *
- * @hide
- */
- public static class LocalOnlyHotspotObserver {
- /**
- * Confirm registration for LocalOnlyHotspotChanges by returning a
- * LocalOnlyHotspotSubscription.
- */
- public void onRegistered(LocalOnlyHotspotSubscription subscription) {};
-
- /**
- * LocalOnlyHotspot started with the supplied config.
- */
- public void onStarted(SoftApConfiguration config) {};
-
- /**
- * LocalOnlyHotspot stopped.
- */
- public void onStopped() {};
- }
-
- /**
- * Callback proxy for LocalOnlyHotspotObserver objects.
- */
- private static class LocalOnlyHotspotObserverProxy extends ILocalOnlyHotspotCallback.Stub {
- private final WeakReference<WifiManager> mWifiManager;
- private final Executor mExecutor;
- private final LocalOnlyHotspotObserver mObserver;
-
- /**
- * Constructs a {@link LocalOnlyHotspotObserverProxy} using the specified looper.
- * All callbacks will be delivered on the thread of the specified looper.
- *
- * @param manager WifiManager
- * @param executor Executor for delivering callbacks
- * @param observer LocalOnlyHotspotObserver to notify the calling application.
- */
- LocalOnlyHotspotObserverProxy(WifiManager manager, Executor executor,
- final LocalOnlyHotspotObserver observer) {
- mWifiManager = new WeakReference<>(manager);
- mExecutor = executor;
- mObserver = observer;
- }
-
- public void registered() throws RemoteException {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- mExecutor.execute(() ->
- mObserver.onRegistered(manager.new LocalOnlyHotspotSubscription()));
- }
-
- @Override
- public void onHotspotStarted(SoftApConfiguration config) {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- if (config == null) {
- Log.e(TAG, "LocalOnlyHotspotObserverProxy: config cannot be null.");
- return;
- }
- mExecutor.execute(() -> mObserver.onStarted(config));
- }
-
- @Override
- public void onHotspotStopped() {
- WifiManager manager = mWifiManager.get();
- if (manager == null) return;
-
- mExecutor.execute(() -> mObserver.onStopped());
- }
-
- @Override
- public void onHotspotFailed(int reason) {
- // do nothing
- }
- }
-
- /**
- * Callback proxy for ActionListener objects.
- */
- private class ActionListenerProxy extends IActionListener.Stub {
- private final String mActionTag;
- private final Handler mHandler;
- private final ActionListener mCallback;
-
- ActionListenerProxy(String actionTag, Looper looper, ActionListener callback) {
- mActionTag = actionTag;
- mHandler = new Handler(looper);
- mCallback = callback;
- }
-
- @Override
- public void onSuccess() {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "ActionListenerProxy:" + mActionTag + ": onSuccess");
- }
- mHandler.post(() -> {
- mCallback.onSuccess();
- });
- }
-
- @Override
- public void onFailure(@ActionListenerFailureReason int reason) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "ActionListenerProxy:" + mActionTag + ": onFailure=" + reason);
- }
- mHandler.post(() -> {
- mCallback.onFailure(reason);
- });
- }
- }
-
- private void connectInternal(@Nullable WifiConfiguration config, int networkId,
- @Nullable ActionListener listener) {
- ActionListenerProxy listenerProxy = null;
- if (listener != null) {
- listenerProxy = new ActionListenerProxy("connect", mLooper, listener);
- }
- try {
- mService.connect(config, networkId, listenerProxy);
- } catch (RemoteException e) {
- if (listenerProxy != null) listenerProxy.onFailure(ERROR);
- } catch (SecurityException e) {
- if (listenerProxy != null) listenerProxy.onFailure(NOT_AUTHORIZED);
- }
- }
-
- /**
- * Connect to a network with the given configuration. The network also
- * gets added to the list of configured networks for the foreground user.
- *
- * For a new network, this function is used instead of a
- * sequence of addNetwork(), enableNetwork(), and reconnect()
- *
- * @param config the set of variables that describe the configuration,
- * contained in a {@link WifiConfiguration} object.
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be
- * initialized again
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD,
- android.Manifest.permission.NETWORK_STACK
- })
- public void connect(@NonNull WifiConfiguration config, @Nullable ActionListener listener) {
- if (config == null) throw new IllegalArgumentException("config cannot be null");
- connectInternal(config, WifiConfiguration.INVALID_NETWORK_ID, listener);
- }
-
- /**
- * Connect to a network with the given networkId.
- *
- * This function is used instead of a enableNetwork() and reconnect()
- *
- * <li> This API will cause reconnect if the credentials of the current active
- * connection has been changed.</li>
- * <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}.
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be
- * initialized again
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD,
- android.Manifest.permission.NETWORK_STACK
- })
- public void connect(int networkId, @Nullable ActionListener listener) {
- if (networkId < 0) throw new IllegalArgumentException("Network id cannot be negative");
- connectInternal(null, networkId, listener);
- }
-
- /**
- * Temporarily disable autojoin for all currently visible and provisioned (saved, suggested)
- * wifi networks except merged carrier networks from the provided subscription ID.
- *
- * Disabled networks will get automatically re-enabled when they are out of range for a period
- * of time, or after the maximum disable duration specified in the framework.
- *
- * Calling {@link #stopTemporarilyDisablingAllNonCarrierMergedWifi()} will immediately re-enable
- * autojoin on all disabled networks.
- *
- * @param subscriptionId the subscription ID of the carrier whose merged wifi networks won't be
- * disabled {@link android.telephony.SubscriptionInfo#getSubscriptionId()}
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void startTemporarilyDisablingAllNonCarrierMergedWifi(int subscriptionId) {
- try {
- mService.startTemporarilyDisablingAllNonCarrierMergedWifi(subscriptionId);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Re-enable autojoin for all non carrier merged wifi networks temporarily disconnected by
- * {@link #startTemporarilyDisablingAllNonCarrierMergedWifi(int)}.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void stopTemporarilyDisablingAllNonCarrierMergedWifi() {
- try {
- mService.stopTemporarilyDisablingAllNonCarrierMergedWifi();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Save the given network to the list of configured networks for the
- * foreground user. If the network already exists, the configuration
- * is updated. Any new network is enabled by default.
- *
- * For a new network, this function is used instead of a
- * sequence of addNetwork() and enableNetwork().
- *
- * For an existing network, it accomplishes the task of updateNetwork()
- *
- * <li> This API will cause reconnect if the credentials of the current active
- * connection has been changed.</li>
- * <li> This API will cause disconnect if the current active connection is marked metered.</li>
- *
- * @param config the set of variables that describe the configuration,
- * contained in a {@link WifiConfiguration} object.
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be
- * initialized again
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD,
- android.Manifest.permission.NETWORK_STACK
- })
- public void save(@NonNull WifiConfiguration config, @Nullable ActionListener listener) {
- if (config == null) throw new IllegalArgumentException("config cannot be null");
- ActionListenerProxy listenerProxy = null;
- if (listener != null) {
- listenerProxy = new ActionListenerProxy("save", mLooper, listener);
- }
- try {
- mService.save(config, listenerProxy);
- } catch (RemoteException e) {
- if (listenerProxy != null) listenerProxy.onFailure(ERROR);
- } catch (SecurityException e) {
- if (listenerProxy != null) listenerProxy.onFailure(NOT_AUTHORIZED);
- }
- }
-
- /**
- * Delete the network from the list of configured networks for the
- * foreground user.
- *
- * This function is used instead of a sequence of removeNetwork()
- *
- * @param config the set of variables that describe the configuration,
- * contained in a {@link WifiConfiguration} object.
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be
- * initialized again
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD,
- android.Manifest.permission.NETWORK_STACK
- })
- public void forget(int netId, @Nullable ActionListener listener) {
- if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
- ActionListenerProxy listenerProxy = null;
- if (listener != null) {
- listenerProxy = new ActionListenerProxy("forget", mLooper, listener);
- }
- try {
- mService.forget(netId, listenerProxy);
- } catch (RemoteException e) {
- if (listenerProxy != null) listenerProxy.onFailure(ERROR);
- } catch (SecurityException e) {
- if (listenerProxy != null) listenerProxy.onFailure(NOT_AUTHORIZED);
- }
- }
-
- /**
- * Disable network
- *
- * @param netId is the network Id
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be
- * initialized again
- * @deprecated This API is deprecated. Use {@link #disableNetwork(int)} instead.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD,
- android.Manifest.permission.NETWORK_STACK
- })
- @Deprecated
- public void disable(int netId, @Nullable ActionListener listener) {
- if (netId < 0) throw new IllegalArgumentException("Network id cannot be negative");
- // Simple wrapper which forwards the call to disableNetwork. This is a temporary
- // implementation until we can remove this API completely.
- boolean status = disableNetwork(netId);
- if (listener != null) {
- if (status) {
- listener.onSuccess();
- } else {
- listener.onFailure(ERROR);
- }
- }
- }
-
- /**
- * Enable/disable auto-join globally.
- *
- * @param allowAutojoin true to allow auto-join, false to disallow auto-join
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void allowAutojoinGlobal(boolean allowAutojoin) {
- try {
- mService.allowAutojoinGlobal(allowAutojoin);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
-
- /**
- * Sets the user choice for allowing auto-join to a network.
- * The updated choice will be made available through the updated config supplied by the
- * CONFIGURED_NETWORKS_CHANGED broadcast.
- *
- * @param netId the id of the network to allow/disallow auto-join for.
- * @param allowAutojoin true to allow auto-join, false to disallow auto-join
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void allowAutojoin(int netId, boolean allowAutojoin) {
- try {
- mService.allowAutojoin(netId, allowAutojoin);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Configure auto-join settings for a Passpoint profile.
- *
- * @param fqdn the FQDN (fully qualified domain name) of the passpoint profile.
- * @param allowAutojoin true to enable auto-join, false to disable auto-join.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void allowAutojoinPasspoint(@NonNull String fqdn, boolean allowAutojoin) {
- try {
- mService.allowAutojoinPasspoint(fqdn, allowAutojoin);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Configure MAC randomization setting for a Passpoint profile.
- * MAC randomization is enabled by default.
- *
- * @param fqdn the FQDN (fully qualified domain name) of the passpoint profile.
- * @param enable true to enable MAC randomization, false to disable MAC randomization.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setMacRandomizationSettingPasspointEnabled(@NonNull String fqdn, boolean enable) {
- try {
- mService.setMacRandomizationSettingPasspointEnabled(fqdn, enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Sets the user's choice of metered override for a Passpoint profile.
- *
- * @param fqdn the FQDN (fully qualified domain name) of the passpoint profile.
- * @param meteredOverride One of three values: {@link WifiConfiguration#METERED_OVERRIDE_NONE},
- * {@link WifiConfiguration#METERED_OVERRIDE_METERED},
- * {@link WifiConfiguration#METERED_OVERRIDE_NOT_METERED}
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setPasspointMeteredOverride(@NonNull String fqdn,
- @WifiConfiguration.MeteredOverride int meteredOverride) {
- try {
- mService.setPasspointMeteredOverride(fqdn, meteredOverride);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Temporarily disable a network. Should always trigger with user disconnect network.
- *
- * @param network Input can be SSID or FQDN. And caller must ensure that the SSID passed thru
- * this API matched the WifiConfiguration.SSID rules, and thus be surrounded by
- * quotes.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_STACK
- })
- public void disableEphemeralNetwork(@NonNull String network) {
- if (TextUtils.isEmpty(network)) {
- throw new IllegalArgumentException("SSID cannot be null or empty!");
- }
- try {
- mService.disableEphemeralNetwork(network, mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * WPS suport has been deprecated from Client mode and this method will immediately trigger
- * {@link WpsCallback#onFailed(int)} with a generic error.
- *
- * @param config WPS configuration (does not support {@link WpsInfo#LABEL})
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be initialized again
- * @deprecated This API is deprecated
- */
- public void startWps(WpsInfo config, WpsCallback listener) {
- if (listener != null ) {
- listener.onFailed(ERROR);
- }
- }
-
- /**
- * WPS support has been deprecated from Client mode and this method will immediately trigger
- * {@link WpsCallback#onFailed(int)} with a generic error.
- *
- * @param listener for callbacks on success or failure. Can be null.
- * @throws IllegalStateException if the WifiManager instance needs to be initialized again
- * @deprecated This API is deprecated
- */
- public void cancelWps(WpsCallback listener) {
- if (listener != null) {
- listener.onFailed(ERROR);
- }
- }
-
- /**
- * Allows an application to keep the Wi-Fi radio awake.
- * Normally the Wi-Fi radio may turn off when the user has not used the device in a while.
- * Acquiring a WifiLock will keep the radio on until the lock is released. Multiple
- * applications may hold WifiLocks, and the radio will only be allowed to turn off when no
- * WifiLocks are held in any application.
- * <p>
- * Before using a WifiLock, consider carefully if your application requires Wi-Fi access, or
- * could function over a mobile network, if available. A program that needs to download large
- * files should hold a WifiLock to ensure that the download will complete, but a program whose
- * network usage is occasional or low-bandwidth should not hold a WifiLock to avoid adversely
- * affecting battery life.
- * <p>
- * Note that WifiLocks cannot override the user-level "Wi-Fi Enabled" setting, nor Airplane
- * Mode. They simply keep the radio from turning off when Wi-Fi is already on but the device
- * is idle.
- * <p>
- * Any application using a WifiLock must request the {@code android.permission.WAKE_LOCK}
- * permission in an {@code <uses-permission>} element of the application's manifest.
- */
- public class WifiLock {
- private String mTag;
- private final IBinder mBinder;
- private int mRefCount;
- int mLockType;
- private boolean mRefCounted;
- private boolean mHeld;
- private WorkSource mWorkSource;
-
- private WifiLock(int lockType, String tag) {
- mTag = tag;
- mLockType = lockType;
- mBinder = new Binder();
- mRefCount = 0;
- mRefCounted = true;
- mHeld = false;
- }
-
- /**
- * Locks the Wi-Fi radio on until {@link #release} is called.
- *
- * If this WifiLock is reference-counted, each call to {@code acquire} will increment the
- * reference count, and the radio will remain locked as long as the reference count is
- * above zero.
- *
- * If this WifiLock is not reference-counted, the first call to {@code acquire} will lock
- * the radio, but subsequent calls will be ignored. Only one call to {@link #release}
- * will be required, regardless of the number of times that {@code acquire} is called.
- */
- public void acquire() {
- synchronized (mBinder) {
- if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) {
- try {
- mService.acquireWifiLock(mBinder, mLockType, mTag, mWorkSource);
- synchronized (WifiManager.this) {
- if (mActiveLockCount >= MAX_ACTIVE_LOCKS) {
- mService.releaseWifiLock(mBinder);
- throw new UnsupportedOperationException(
- "Exceeded maximum number of wifi locks");
- }
- mActiveLockCount++;
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- mHeld = true;
- }
- }
- }
-
- /**
- * Unlocks the Wi-Fi radio, allowing it to turn off when the device is idle.
- *
- * If this WifiLock is reference-counted, each call to {@code release} will decrement the
- * reference count, and the radio will be unlocked only when the reference count reaches
- * zero. If the reference count goes below zero (that is, if {@code release} is called
- * a greater number of times than {@link #acquire}), an exception is thrown.
- *
- * If this WifiLock is not reference-counted, the first call to {@code release} (after
- * the radio was locked using {@link #acquire}) will unlock the radio, and subsequent
- * calls will be ignored.
- */
- public void release() {
- synchronized (mBinder) {
- if (mRefCounted ? (--mRefCount == 0) : (mHeld)) {
- try {
- mService.releaseWifiLock(mBinder);
- synchronized (WifiManager.this) {
- mActiveLockCount--;
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- mHeld = false;
- }
- if (mRefCount < 0) {
- throw new RuntimeException("WifiLock under-locked " + mTag);
- }
- }
- }
-
- /**
- * Controls whether this is a reference-counted or non-reference-counted WifiLock.
- *
- * Reference-counted WifiLocks keep track of the number of calls to {@link #acquire} and
- * {@link #release}, and only allow the radio to sleep when every call to {@link #acquire}
- * has been balanced with a call to {@link #release}. Non-reference-counted WifiLocks
- * lock the radio whenever {@link #acquire} is called and it is unlocked, and unlock the
- * radio whenever {@link #release} is called and it is locked.
- *
- * @param refCounted true if this WifiLock should keep a reference count
- */
- public void setReferenceCounted(boolean refCounted) {
- mRefCounted = refCounted;
- }
-
- /**
- * Checks whether this WifiLock is currently held.
- *
- * @return true if this WifiLock is held, false otherwise
- */
- public boolean isHeld() {
- synchronized (mBinder) {
- return mHeld;
- }
- }
-
- public void setWorkSource(WorkSource ws) {
- synchronized (mBinder) {
- if (ws != null && ws.isEmpty()) {
- ws = null;
- }
- boolean changed = true;
- if (ws == null) {
- mWorkSource = null;
- } else {
- ws = ws.withoutNames();
- if (mWorkSource == null) {
- changed = mWorkSource != null;
- mWorkSource = new WorkSource(ws);
- } else {
- changed = !mWorkSource.equals(ws);
- if (changed) {
- mWorkSource.set(ws);
- }
- }
- }
- if (changed && mHeld) {
- try {
- mService.updateWifiLockWorkSource(mBinder, mWorkSource);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
- }
-
- public String toString() {
- String s1, s2, s3;
- synchronized (mBinder) {
- s1 = Integer.toHexString(System.identityHashCode(this));
- s2 = mHeld ? "held; " : "";
- if (mRefCounted) {
- s3 = "refcounted: refcount = " + mRefCount;
- } else {
- s3 = "not refcounted";
- }
- return "WifiLock{ " + s1 + "; " + s2 + s3 + " }";
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
- synchronized (mBinder) {
- if (mHeld) {
- try {
- mService.releaseWifiLock(mBinder);
- synchronized (WifiManager.this) {
- mActiveLockCount--;
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
- }
- }
-
- /**
- * Creates a new WifiLock.
- *
- * @param lockType the type of lock to create. See {@link #WIFI_MODE_FULL_HIGH_PERF}
- * and {@link #WIFI_MODE_FULL_LOW_LATENCY} for descriptions of the types of Wi-Fi locks.
- * @param tag a tag for the WifiLock to identify it in debugging messages. This string is
- * never shown to the user under normal conditions, but should be descriptive
- * enough to identify your application and the specific WifiLock within it, if it
- * holds multiple WifiLocks.
- *
- * @return a new, unacquired WifiLock with the given tag.
- *
- * @see WifiLock
- */
- public WifiLock createWifiLock(int lockType, String tag) {
- return new WifiLock(lockType, tag);
- }
-
- /**
- * Creates a new WifiLock.
- *
- * @param tag a tag for the WifiLock to identify it in debugging messages. This string is
- * never shown to the user under normal conditions, but should be descriptive
- * enough to identify your application and the specific WifiLock within it, if it
- * holds multiple WifiLocks.
- *
- * @return a new, unacquired WifiLock with the given tag.
- *
- * @see WifiLock
- *
- * @deprecated This API is non-functional.
- */
- @Deprecated
- public WifiLock createWifiLock(String tag) {
- return new WifiLock(WIFI_MODE_FULL, tag);
- }
-
- /**
- * Create a new MulticastLock
- *
- * @param tag a tag for the MulticastLock to identify it in debugging
- * messages. This string is never shown to the user under
- * normal conditions, but should be descriptive enough to
- * identify your application and the specific MulticastLock
- * within it, if it holds multiple MulticastLocks.
- *
- * @return a new, unacquired MulticastLock with the given tag.
- *
- * @see MulticastLock
- */
- public MulticastLock createMulticastLock(String tag) {
- return new MulticastLock(tag);
- }
-
- /**
- * Allows an application to receive Wifi Multicast packets.
- * Normally the Wifi stack filters out packets not explicitly
- * addressed to this device. Acquring a MulticastLock will
- * cause the stack to receive packets addressed to multicast
- * addresses. Processing these extra packets can cause a noticeable
- * battery drain and should be disabled when not needed.
- */
- public class MulticastLock {
- private String mTag;
- private final IBinder mBinder;
- private int mRefCount;
- private boolean mRefCounted;
- private boolean mHeld;
-
- private MulticastLock(String tag) {
- mTag = tag;
- mBinder = new Binder();
- mRefCount = 0;
- mRefCounted = true;
- mHeld = false;
- }
-
- /**
- * Locks Wifi Multicast on until {@link #release} is called.
- *
- * If this MulticastLock is reference-counted each call to
- * {@code acquire} will increment the reference count, and the
- * wifi interface will receive multicast packets as long as the
- * reference count is above zero.
- *
- * If this MulticastLock is not reference-counted, the first call to
- * {@code acquire} will turn on the multicast packets, but subsequent
- * calls will be ignored. Only one call to {@link #release} will
- * be required, regardless of the number of times that {@code acquire}
- * is called.
- *
- * Note that other applications may also lock Wifi Multicast on.
- * Only they can relinquish their lock.
- *
- * Also note that applications cannot leave Multicast locked on.
- * When an app exits or crashes, any Multicast locks will be released.
- */
- public void acquire() {
- synchronized (mBinder) {
- if (mRefCounted ? (++mRefCount == 1) : (!mHeld)) {
- try {
- mService.acquireMulticastLock(mBinder, mTag);
- synchronized (WifiManager.this) {
- if (mActiveLockCount >= MAX_ACTIVE_LOCKS) {
- mService.releaseMulticastLock(mTag);
- throw new UnsupportedOperationException(
- "Exceeded maximum number of wifi locks");
- }
- mActiveLockCount++;
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- mHeld = true;
- }
- }
- }
-
- /**
- * Unlocks Wifi Multicast, restoring the filter of packets
- * not addressed specifically to this device and saving power.
- *
- * If this MulticastLock is reference-counted, each call to
- * {@code release} will decrement the reference count, and the
- * multicast packets will only stop being received when the reference
- * count reaches zero. If the reference count goes below zero (that
- * is, if {@code release} is called a greater number of times than
- * {@link #acquire}), an exception is thrown.
- *
- * If this MulticastLock is not reference-counted, the first call to
- * {@code release} (after the radio was multicast locked using
- * {@link #acquire}) will unlock the multicast, and subsequent calls
- * will be ignored.
- *
- * Note that if any other Wifi Multicast Locks are still outstanding
- * this {@code release} call will not have an immediate effect. Only
- * when all applications have released all their Multicast Locks will
- * the Multicast filter be turned back on.
- *
- * Also note that when an app exits or crashes all of its Multicast
- * Locks will be automatically released.
- */
- public void release() {
- synchronized (mBinder) {
- if (mRefCounted ? (--mRefCount == 0) : (mHeld)) {
- try {
- mService.releaseMulticastLock(mTag);
- synchronized (WifiManager.this) {
- mActiveLockCount--;
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- mHeld = false;
- }
- if (mRefCount < 0) {
- throw new RuntimeException("MulticastLock under-locked "
- + mTag);
- }
- }
- }
-
- /**
- * Controls whether this is a reference-counted or non-reference-
- * counted MulticastLock.
- *
- * Reference-counted MulticastLocks keep track of the number of calls
- * to {@link #acquire} and {@link #release}, and only stop the
- * reception of multicast packets when every call to {@link #acquire}
- * has been balanced with a call to {@link #release}. Non-reference-
- * counted MulticastLocks allow the reception of multicast packets
- * whenever {@link #acquire} is called and stop accepting multicast
- * packets whenever {@link #release} is called.
- *
- * @param refCounted true if this MulticastLock should keep a reference
- * count
- */
- public void setReferenceCounted(boolean refCounted) {
- mRefCounted = refCounted;
- }
-
- /**
- * Checks whether this MulticastLock is currently held.
- *
- * @return true if this MulticastLock is held, false otherwise
- */
- public boolean isHeld() {
- synchronized (mBinder) {
- return mHeld;
- }
- }
-
- public String toString() {
- String s1, s2, s3;
- synchronized (mBinder) {
- s1 = Integer.toHexString(System.identityHashCode(this));
- s2 = mHeld ? "held; " : "";
- if (mRefCounted) {
- s3 = "refcounted: refcount = " + mRefCount;
- } else {
- s3 = "not refcounted";
- }
- return "MulticastLock{ " + s1 + "; " + s2 + s3 + " }";
- }
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
- setReferenceCounted(false);
- release();
- }
- }
-
- /**
- * Check multicast filter status.
- *
- * @return true if multicast packets are allowed.
- *
- * @hide pending API council approval
- */
- public boolean isMulticastEnabled() {
- try {
- return mService.isMulticastEnabled();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Initialize the multicast filtering to 'on'
- * @hide no intent to publish
- */
- @UnsupportedAppUsage
- public boolean initializeMulticastFiltering() {
- try {
- mService.initializeMulticastFiltering();
- return true;
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Set Wi-Fi verbose logging level from developer settings.
- *
- * @param enable true to enable verbose logging, false to disable.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setVerboseLoggingEnabled(boolean enable) {
- enableVerboseLogging(enable ? 1 : 0);
- }
-
- /** @hide */
- @UnsupportedAppUsage(
- maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "Use {@code #setVerboseLoggingEnabled(boolean)} instead."
- )
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void enableVerboseLogging (int verbose) {
- try {
- mService.enableVerboseLogging(verbose);
- } catch (Exception e) {
- //ignore any failure here
- Log.e(TAG, "enableVerboseLogging " + e.toString());
- }
- }
-
- /**
- * Get the persisted Wi-Fi verbose logging level, set by
- * {@link #setVerboseLoggingEnabled(boolean)}.
- * No permissions are required to call this method.
- *
- * @return true to indicate that verbose logging is enabled, false to indicate that verbose
- * logging is disabled.
- *
- * @hide
- */
- @SystemApi
- public boolean isVerboseLoggingEnabled() {
- return getVerboseLoggingLevel() > 0;
- }
-
- /** @hide */
- // TODO(b/145484145): remove once SUW stops calling this via reflection
- @UnsupportedAppUsage(
- maxTargetSdk = Build.VERSION_CODES.Q,
- publicAlternatives = "Use {@code #isVerboseLoggingEnabled()} instead."
- )
- public int getVerboseLoggingLevel() {
- try {
- return mService.getVerboseLoggingLevel();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Removes all saved Wi-Fi networks, Passpoint configurations, ephemeral networks, Network
- * Requests, and Network Suggestions.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void factoryReset() {
- try {
- mService.factoryReset(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get {@link Network} object of current wifi network, or null if not connected.
- * @hide
- */
- @Nullable
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- public Network getCurrentNetwork() {
- try {
- return mService.getCurrentNetwork();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Deprecated
- * returns false
- * @hide
- * @deprecated
- */
- public boolean setEnableAutoJoinWhenAssociated(boolean enabled) {
- return false;
- }
-
- /**
- * Deprecated
- * returns false
- * @hide
- * @deprecated
- */
- public boolean getEnableAutoJoinWhenAssociated() {
- return false;
- }
-
- /**
- * Returns a byte stream representing the data that needs to be backed up to save the
- * current Wifi state.
- * This Wifi state can be restored by calling {@link #restoreBackupData(byte[])}.
- * @hide
- */
- @NonNull
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public byte[] retrieveBackupData() {
- try {
- return mService.retrieveBackupData();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Restore state from the backed up data.
- * @param data byte stream in the same format produced by {@link #retrieveBackupData()}
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void restoreBackupData(@NonNull byte[] data) {
- try {
- mService.restoreBackupData(data);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns a byte stream representing the data that needs to be backed up to save the
- * current soft ap config data.
- *
- * This soft ap config can be restored by calling {@link #restoreSoftApBackupData(byte[])}
- * @hide
- */
- @NonNull
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public byte[] retrieveSoftApBackupData() {
- try {
- return mService.retrieveSoftApBackupData();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns soft ap config from the backed up data or null if data is invalid.
- * @param data byte stream in the same format produced by {@link #retrieveSoftApBackupData()}
- *
- * @hide
- */
- @Nullable
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public SoftApConfiguration restoreSoftApBackupData(@NonNull byte[] data) {
- try {
- return mService.restoreSoftApBackupData(data);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Restore state from the older version of back up data.
- * The old backup data was essentially a backup of wpa_supplicant.conf
- * and ipconfig.txt file.
- * @param supplicantData bytes representing wpa_supplicant.conf
- * @param ipConfigData bytes representing ipconfig.txt
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void restoreSupplicantBackupData(
- @NonNull byte[] supplicantData, @NonNull byte[] ipConfigData) {
- try {
- mService.restoreSupplicantBackupData(supplicantData, ipConfigData);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Start subscription provisioning flow
- *
- * @param provider {@link OsuProvider} to provision with
- * @param executor the Executor on which to run the callback.
- * @param callback {@link ProvisioningCallback} for updates regarding provisioning flow
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD
- })
- public void startSubscriptionProvisioning(@NonNull OsuProvider provider,
- @NonNull @CallbackExecutor Executor executor, @NonNull ProvisioningCallback callback) {
- // Verify arguments
- if (executor == null) {
- throw new IllegalArgumentException("executor must not be null");
- }
- if (callback == null) {
- throw new IllegalArgumentException("callback must not be null");
- }
- try {
- mService.startSubscriptionProvisioning(provider,
- new ProvisioningCallbackProxy(executor, callback));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Helper class to support OSU Provisioning callbacks
- */
- private static class ProvisioningCallbackProxy extends IProvisioningCallback.Stub {
- private final Executor mExecutor;
- private final ProvisioningCallback mCallback;
-
- ProvisioningCallbackProxy(Executor executor, ProvisioningCallback callback) {
- mExecutor = executor;
- mCallback = callback;
- }
- @Override
- public void onProvisioningStatus(int status) {
- mExecutor.execute(() -> mCallback.onProvisioningStatus(status));
- }
-
- @Override
- public void onProvisioningFailure(int status) {
- mExecutor.execute(() -> mCallback.onProvisioningFailure(status));
- }
-
- @Override
- public void onProvisioningComplete() {
- mExecutor.execute(() -> mCallback.onProvisioningComplete());
- }
- }
-
- /**
- * Interface for Traffic state callback. Should be extended by applications and set when
- * calling {@link #registerTrafficStateCallback(Executor, WifiManager.TrafficStateCallback)}.
- * @hide
- */
- @SystemApi
- public interface TrafficStateCallback {
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"DATA_ACTIVITY_"}, value = {
- DATA_ACTIVITY_NONE,
- DATA_ACTIVITY_IN,
- DATA_ACTIVITY_OUT,
- DATA_ACTIVITY_INOUT})
- @interface DataActivity {}
-
- // Lowest bit indicates data reception and the second lowest bit indicates data transmitted
- /** No data in or out */
- int DATA_ACTIVITY_NONE = 0x00;
- /** Data in, no data out */
- int DATA_ACTIVITY_IN = 0x01;
- /** Data out, no data in */
- int DATA_ACTIVITY_OUT = 0x02;
- /** Data in and out */
- int DATA_ACTIVITY_INOUT = 0x03;
-
- /**
- * Callback invoked to inform clients about the current traffic state.
- *
- * @param state One of the values: {@link #DATA_ACTIVITY_NONE}, {@link #DATA_ACTIVITY_IN},
- * {@link #DATA_ACTIVITY_OUT} & {@link #DATA_ACTIVITY_INOUT}.
- */
- void onStateChanged(@DataActivity int state);
- }
-
- /**
- * Callback proxy for TrafficStateCallback objects.
- *
- * @hide
- */
- private class TrafficStateCallbackProxy extends ITrafficStateCallback.Stub {
- private final Executor mExecutor;
- private final TrafficStateCallback mCallback;
-
- TrafficStateCallbackProxy(Executor executor, TrafficStateCallback callback) {
- mExecutor = executor;
- mCallback = callback;
- }
-
- @Override
- public void onStateChanged(int state) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "TrafficStateCallbackProxy: onStateChanged state=" + state);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mCallback.onStateChanged(state);
- });
- }
- }
-
- /**
- * Registers a callback for monitoring traffic state. See {@link TrafficStateCallback}. These
- * callbacks will be invoked periodically by platform to inform clients about the current
- * traffic state. Caller can unregister a previously registered callback using
- * {@link #unregisterTrafficStateCallback(TrafficStateCallback)}
- * <p>
- * Applications should have the
- * {@link android.Manifest.permission#NETWORK_SETTINGS NETWORK_SETTINGS} permission. Callers
- * without the permission will trigger a {@link java.lang.SecurityException}.
- * <p>
- *
- * @param executor The Executor on whose thread to execute the callbacks of the {@code callback}
- * object.
- * @param callback Callback for traffic state events
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void registerTrafficStateCallback(@NonNull @CallbackExecutor Executor executor,
- @NonNull TrafficStateCallback callback) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "registerTrafficStateCallback: callback=" + callback + ", executor=" + executor);
-
- Binder binder = new Binder();
- try {
- mService.registerTrafficStateCallback(
- binder, new TrafficStateCallbackProxy(executor, callback), callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow callers to unregister a previously registered callback. After calling this method,
- * applications will no longer receive traffic state notifications.
- *
- * @param callback Callback to unregister for traffic state events
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void unregisterTrafficStateCallback(@NonNull TrafficStateCallback callback) {
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "unregisterTrafficStateCallback: callback=" + callback);
-
- try {
- mService.unregisterTrafficStateCallback(callback.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Helper method to update the local verbose logging flag based on the verbose logging
- * level from wifi service.
- */
- private void updateVerboseLoggingEnabledFromService() {
- mVerboseLoggingEnabled = isVerboseLoggingEnabled();
- }
-
- /**
- * Get driver Capabilities.
- *
- * @param capaType ASCII string, capability type ex: key_mgmt.
- * @return String of capabilities from driver for type capaParameter.
- * {@hide}
- */
- @NonNull
- public String getCapabilities(@NonNull String capaType) {
- try {
- return mService.getCapabilities(capaType);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
-
- /**
- * Add the DPP bootstrap info obtained from QR code.
- *
- * @param uri:The URI obtained from the QR code reader.
- *
- * @return: Handle to strored info else -1 on failure
- * @hide
- */
- public int dppAddBootstrapQrCode(String uri) {
- try {
- return mService.dppAddBootstrapQrCode(uri);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
-
- /**
- * Generate bootstrap URI based on the passed arguments
- *
- * @param config – bootstrap generate config, mandatory parameters
- * are: type, frequency, mac_addr, curve, key.
- *
- * @return: Handle to strored URI info else -1 on failure
- * @hide
- */
- public int dppBootstrapGenerate(WifiDppConfig config) {
- try {
- return mService.dppBootstrapGenerate(config);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get bootstrap URI based on bootstrap ID
- *
- * @param bootstrap_id: Stored bootstrap ID
- *
- * @return: URI string else -1 on failure
- * @hide
- */
- public String dppGetUri(int bootstrap_id) {
- try {
- return mService.dppGetUri(bootstrap_id);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Remove bootstrap URI based on bootstrap ID.
- *
- * @param bootstrap_id: Stored bootstrap ID. 0 to remove all.
- *
- * @return: 0 – Success or -1 on failure
- * @hide
- */
- public int dppBootstrapRemove(int bootstrap_id) {
- try {
- return mService.dppBootstrapRemove(bootstrap_id);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * start listen on the channel specified waiting to receive
- * the DPP Authentication request.
- *
- * @param frequency: DPP listen frequency
- * @param dpp_role: Configurator/Enrollee role
- * @param qr_mutual: Mutual authentication required
- * @param netrole_ap: network role
- *
- * @return: Returns 0 if a DPP-listen work is successfully
- * queued and -1 on failure.
- * @hide
- */
- public int dppListen(String frequency, int dpp_role, boolean qr_mutual,
- boolean netrole_ap) {
- try {
- return mService.dppListen(frequency, dpp_role, qr_mutual, netrole_ap);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * stop ongoing dpp listen.
- *
- * @hide
- */
- public void dppStopListen() {
- try {
- mService.dppStopListen();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Adds the DPP configurator
- *
- * @param curve curve used for dpp encryption
- * @param key private key
- * @param expiry timeout in seconds
- *
- * @return: Identifier of the added configurator or -1 on failure
- * @hide
- */
- public int dppConfiguratorAdd(String curve, String key, int expiry) {
- try {
- return mService.dppConfiguratorAdd(curve, key, expiry);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Remove the added configurator through dppConfiguratorAdd.
- *
- * @param config_id: DPP Configurator ID. 0 to remove all.
- *
- * @return: Handle to strored info else -1 on failure
- * @hide
- */
- public int dppConfiguratorRemove(int config_id) {
- try {
- return mService.dppConfiguratorRemove(config_id);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Start DPP authentication and provisioning with the specified peer
- *
- * @param config – dpp auth init config mandatory parameters
- * are: peer_bootstrap_id, own_bootstrap_id, dpp_role,
- * ssid, passphrase, isDpp, conf_id, expiry.
- *
- * @return: 0 if DPP auth request was transmitted and -1 on failure
- * @hide
- */
- public int dppStartAuth(WifiDppConfig config) {
- try {
- return mService.dppStartAuth(config);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Retrieve Private key to be used for configurator
- *
- * @param id: id of configurator
- *
- * @return: KEY string else -1 on failure
- * @hide
- */
- public String dppConfiguratorGetKey(int id) {
- try {
- return mService.dppConfiguratorGetKey(id);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * @return true if this device supports WPA3-Personal SAE
- */
- public boolean isWpa3SaeSupported() {
- return isFeatureSupported(WIFI_FEATURE_WPA3_SAE);
- }
-
- /**
- * @return true if this device supports WPA3-Enterprise Suite-B-192
- */
- public boolean isWpa3SuiteBSupported() {
- return isFeatureSupported(WIFI_FEATURE_WPA3_SUITE_B);
- }
-
- /**
- * @return true if this device supports Wi-Fi Enhanced Open (OWE)
- */
- public boolean isEnhancedOpenSupported() {
- return isFeatureSupported(WIFI_FEATURE_OWE);
- }
-
- /**
- * Wi-Fi Easy Connect (DPP) introduces standardized mechanisms to simplify the provisioning and
- * configuration of Wi-Fi devices.
- * For more details, visit <a href="https://www.wi-fi.org/">https://www.wi-fi.org/</a> and
- * search for "Easy Connect" or "Device Provisioning Protocol specification".
- *
- * @return true if this device supports Wi-Fi Easy-connect (Device Provisioning Protocol)
- */
- public boolean isEasyConnectSupported() {
- return isFeatureSupported(WIFI_FEATURE_DPP);
- }
-
- /**
- * @return true if this device supports WAPI.
- */
- public boolean isWapiSupported() {
- return isFeatureSupported(WIFI_FEATURE_WAPI);
- }
-
- /**
- * @return true if this device supports WPA3 AP validation.
- */
- public boolean isWpa3ApValidationSupported() {
- return isFeatureSupported(WIFI_FEATURE_SAE_PK);
- }
-
- /**
- * Gets the factory Wi-Fi MAC addresses.
- * @return Array of String representing Wi-Fi MAC addresses sorted lexically or an empty Array
- * if failed.
- * @hide
- */
- @NonNull
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public String[] getFactoryMacAddresses() {
- try {
- return mService.getFactoryMacAddresses();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"DEVICE_MOBILITY_STATE_"}, value = {
- DEVICE_MOBILITY_STATE_UNKNOWN,
- DEVICE_MOBILITY_STATE_HIGH_MVMT,
- DEVICE_MOBILITY_STATE_LOW_MVMT,
- DEVICE_MOBILITY_STATE_STATIONARY})
- public @interface DeviceMobilityState {}
-
- /**
- * Unknown device mobility state
- *
- * @see #setDeviceMobilityState(int)
- *
- * @hide
- */
- @SystemApi
- public static final int DEVICE_MOBILITY_STATE_UNKNOWN = 0;
-
- /**
- * High movement device mobility state.
- * e.g. on a bike, in a motor vehicle
- *
- * @see #setDeviceMobilityState(int)
- *
- * @hide
- */
- @SystemApi
- public static final int DEVICE_MOBILITY_STATE_HIGH_MVMT = 1;
-
- /**
- * Low movement device mobility state.
- * e.g. walking, running
- *
- * @see #setDeviceMobilityState(int)
- *
- * @hide
- */
- @SystemApi
- public static final int DEVICE_MOBILITY_STATE_LOW_MVMT = 2;
-
- /**
- * Stationary device mobility state
- *
- * @see #setDeviceMobilityState(int)
- *
- * @hide
- */
- @SystemApi
- public static final int DEVICE_MOBILITY_STATE_STATIONARY = 3;
-
- /**
- * Updates the device mobility state. Wifi uses this information to adjust the interval between
- * Wifi scans in order to balance power consumption with scan accuracy.
- * The default mobility state when the device boots is {@link #DEVICE_MOBILITY_STATE_UNKNOWN}.
- * This API should be called whenever there is a change in the mobility state.
- * @param state the updated device mobility state
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_SET_DEVICE_MOBILITY_STATE)
- public void setDeviceMobilityState(@DeviceMobilityState int state) {
- try {
- mService.setDeviceMobilityState(state);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /* Easy Connect - AKA Device Provisioning Protocol (DPP) */
-
- /**
- * Easy Connect Network role: Station.
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_NETWORK_ROLE_STA = 0;
-
- /**
- * Easy Connect Network role: Access Point.
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_NETWORK_ROLE_AP = 1;
-
- /** @hide */
- @IntDef(prefix = {"EASY_CONNECT_NETWORK_ROLE_"}, value = {
- EASY_CONNECT_NETWORK_ROLE_STA,
- EASY_CONNECT_NETWORK_ROLE_AP,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface EasyConnectNetworkRole {
- }
-
- /**
- * Easy Connect Device information maximum allowed length.
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_DEVICE_INFO_MAXIMUM_LENGTH = 40;
-
- /**
- * Easy Connect Cryptography Curve name: prime256v1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1 = 0;
-
- /**
- * Easy Connect Cryptography Curve name: secp384r1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_SECP384R1 = 1;
-
- /**
- * Easy Connect Cryptography Curve name: secp521r1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_SECP521R1 = 2;
-
-
- /**
- * Easy Connect Cryptography Curve name: brainpoolP256r1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP256R1 = 3;
-
-
- /**
- * Easy Connect Cryptography Curve name: brainpoolP384r1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP384R1 = 4;
-
-
- /**
- * Easy Connect Cryptography Curve name: brainpoolP512r1
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP512R1 = 5;
-
- /**
- * Easy Connect Cryptography Curve name: default
- * This allows framework to choose manadatory curve prime256v1.
- *
- * @hide
- */
- @SystemApi
- public static final int EASY_CONNECT_CRYPTOGRAPHY_CURVE_DEFAULT =
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1;
-
- /** @hide */
- @IntDef(prefix = {"EASY_CONNECT_CRYPTOGRAPHY_CURVE_"}, value = {
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_DEFAULT,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_SECP384R1,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_SECP521R1,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP256R1,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP384R1,
- EASY_CONNECT_CRYPTOGRAPHY_CURVE_BRAINPOOLP512R1,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface EasyConnectCryptographyCurve {
- }
-
- /**
- * Start Easy Connect (DPP) in Configurator-Initiator role. The current device will initiate
- * Easy Connect bootstrapping with a peer, and configure the peer with the SSID and password of
- * the specified network using the Easy Connect protocol on an encrypted link.
- *
- * @param enrolleeUri URI of the Enrollee obtained separately (e.g. QR code scanning)
- * @param selectedNetworkId Selected network ID to be sent to the peer
- * @param enrolleeNetworkRole The network role of the enrollee
- * @param callback Callback for status updates
- * @param executor The Executor on which to run the callback.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void startEasyConnectAsConfiguratorInitiator(@NonNull String enrolleeUri,
- int selectedNetworkId, @EasyConnectNetworkRole int enrolleeNetworkRole,
- @NonNull @CallbackExecutor Executor executor,
- @NonNull EasyConnectStatusCallback callback) {
- Binder binder = new Binder();
- try {
- mService.startDppAsConfiguratorInitiator(binder, enrolleeUri, selectedNetworkId,
- enrolleeNetworkRole, new EasyConnectCallbackProxy(executor, callback));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Start Easy Connect (DPP) in Enrollee-Initiator role. The current device will initiate Easy
- * Connect bootstrapping with a peer, and receive the SSID and password from the peer
- * configurator.
- *
- * @param configuratorUri URI of the Configurator obtained separately (e.g. QR code scanning)
- * @param callback Callback for status updates
- * @param executor The Executor on which to run the callback.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void startEasyConnectAsEnrolleeInitiator(@NonNull String configuratorUri,
- @NonNull @CallbackExecutor Executor executor,
- @NonNull EasyConnectStatusCallback callback) {
- Binder binder = new Binder();
- try {
- mService.startDppAsEnrolleeInitiator(binder, configuratorUri,
- new EasyConnectCallbackProxy(executor, callback));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Start Easy Connect (DPP) in Enrollee-Responder role.
- * The device will:
- * 1. Generate a DPP bootstrap URI and return it using the
- * {@link EasyConnectStatusCallback#onBootstrapUriGenerated(String)} method.
- * 2. Start DPP as a Responder, waiting for an Initiator device to start the DPP
- * authentication process.
- * The caller should use the URI provided in step #1, for instance display it as a QR code
- * or communicate it in some other way to the initiator device.
- *
- * @param deviceInfo Device specific information to add to the DPP URI. This field allows
- * the users of the configurators to identify the device.
- * Optional - if not provided or in case of an empty string,
- * Info field (I:) will be skipped in the generated DPP URI.
- * Allowed Range of ASCII characters in deviceInfo - %x20-7E.
- * semicolon and space are not allowed.
- * Due to the limitation of maximum allowed characters in QR code,
- * framework limits to a max of
- * {@link #EASY_CONNECT_DEVICE_INFO_MAXIMUM_LENGTH} characters in
- * deviceInfo.
- * Violation of these rules will result in an exception.
- * @param curve Elliptic curve cryptography used to generate DPP
- * public/private key pair. If application is not interested in a
- * specific curve, choose default curve
- * {@link #EASY_CONNECT_CRYPTOGRAPHY_CURVE_DEFAULT}.
- * @param callback Callback for status updates
- * @param executor The Executor on which to run the callback.
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void startEasyConnectAsEnrolleeResponder(@Nullable String deviceInfo,
- @EasyConnectCryptographyCurve int curve,
- @NonNull @CallbackExecutor Executor executor,
- @NonNull EasyConnectStatusCallback callback) {
- Binder binder = new Binder();
- try {
- mService.startDppAsEnrolleeResponder(binder, deviceInfo, curve,
- new EasyConnectCallbackProxy(executor, callback));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Stop or abort a current Easy Connect (DPP) session. This call, once processed, will
- * terminate any ongoing transaction, and clean up all associated resources. Caller should not
- * expect any callbacks once this call is made. However, due to the asynchronous nature of
- * this call, a callback may be fired if it was already pending in the queue.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void stopEasyConnectSession() {
- try {
- /* Request lower layers to stop/abort and clear resources */
- mService.stopDppSession();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Helper class to support Easy Connect (DPP) callbacks
- *
- * @hide
- */
- private static class EasyConnectCallbackProxy extends IDppCallback.Stub {
- private final Executor mExecutor;
- private final EasyConnectStatusCallback mEasyConnectStatusCallback;
-
- EasyConnectCallbackProxy(Executor executor,
- EasyConnectStatusCallback easyConnectStatusCallback) {
- mExecutor = executor;
- mEasyConnectStatusCallback = easyConnectStatusCallback;
- }
-
- @Override
- public void onSuccessConfigReceived(int newNetworkId) {
- Log.d(TAG, "Easy Connect onSuccessConfigReceived callback");
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mEasyConnectStatusCallback.onEnrolleeSuccess(newNetworkId);
- });
- }
-
- @Override
- public void onSuccess(int status) {
- Log.d(TAG, "Easy Connect onSuccess callback");
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mEasyConnectStatusCallback.onConfiguratorSuccess(status);
- });
- }
-
- @Override
- public void onFailure(int status, String ssid, String channelList,
- int[] operatingClassArray) {
- Log.d(TAG, "Easy Connect onFailure callback");
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- SparseArray<int[]> channelListArray = parseDppChannelList(channelList);
- mEasyConnectStatusCallback.onFailure(status, ssid, channelListArray,
- operatingClassArray);
- });
- }
-
- @Override
- public void onProgress(int status) {
- Log.d(TAG, "Easy Connect onProgress callback");
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mEasyConnectStatusCallback.onProgress(status);
- });
- }
-
- @Override
- public void onBootstrapUriGenerated(String uri) {
- Log.d(TAG, "Easy Connect onBootstrapUriGenerated callback");
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> {
- mEasyConnectStatusCallback.onBootstrapUriGenerated(uri);
- });
- }
- }
-
- /**
- * Interface for Wi-Fi usability statistics listener. Should be implemented by applications and
- * set when calling {@link WifiManager#addOnWifiUsabilityStatsListener(Executor,
- * OnWifiUsabilityStatsListener)}.
- *
- * @hide
- */
- @SystemApi
- public interface OnWifiUsabilityStatsListener {
- /**
- * Called when Wi-Fi usability statistics is updated.
- *
- * @param seqNum The sequence number of statistics, used to derive the timing of updated
- * Wi-Fi usability statistics, set by framework and incremented by one after
- * each update.
- * @param isSameBssidAndFreq The flag to indicate whether the BSSID and the frequency of
- * network stays the same or not relative to the last update of
- * Wi-Fi usability stats.
- * @param stats The updated Wi-Fi usability statistics.
- */
- void onWifiUsabilityStats(int seqNum, boolean isSameBssidAndFreq,
- @NonNull WifiUsabilityStatsEntry stats);
- }
-
- /**
- * Adds a listener for Wi-Fi usability statistics. See {@link OnWifiUsabilityStatsListener}.
- * Multiple listeners can be added. Callers will be invoked periodically by framework to
- * inform clients about the current Wi-Fi usability statistics. Callers can remove a previously
- * added listener using {@link removeOnWifiUsabilityStatsListener}.
- *
- * @param executor The executor on which callback will be invoked.
- * @param listener Listener for Wifi usability statistics.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE)
- public void addOnWifiUsabilityStatsListener(@NonNull @CallbackExecutor Executor executor,
- @NonNull OnWifiUsabilityStatsListener listener) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (listener == null) throw new IllegalArgumentException("listener cannot be null");
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "addOnWifiUsabilityStatsListener: listener=" + listener);
- }
- try {
- mService.addOnWifiUsabilityStatsListener(new Binder(),
- new IOnWifiUsabilityStatsListener.Stub() {
- @Override
- public void onWifiUsabilityStats(int seqNum, boolean isSameBssidAndFreq,
- WifiUsabilityStatsEntry stats) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "OnWifiUsabilityStatsListener: "
- + "onWifiUsabilityStats: seqNum=" + seqNum);
- }
- Binder.clearCallingIdentity();
- executor.execute(() -> listener.onWifiUsabilityStats(
- seqNum, isSameBssidAndFreq, stats));
- }
- },
- listener.hashCode()
- );
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow callers to remove a previously registered listener. After calling this method,
- * applications will no longer receive Wi-Fi usability statistics.
- *
- * @param listener Listener to remove the Wi-Fi usability statistics.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE)
- public void removeOnWifiUsabilityStatsListener(@NonNull OnWifiUsabilityStatsListener listener) {
- if (listener == null) throw new IllegalArgumentException("listener cannot be null");
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "removeOnWifiUsabilityStatsListener: listener=" + listener);
- }
- try {
- mService.removeOnWifiUsabilityStatsListener(listener.hashCode());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Provide a Wi-Fi usability score information to be recorded (but not acted upon) by the
- * framework. The Wi-Fi usability score is derived from {@link OnWifiUsabilityStatsListener}
- * where a score is matched to Wi-Fi usability statistics using the sequence number. The score
- * is used to quantify whether Wi-Fi is usable in a future time.
- *
- * @param seqNum Sequence number of the Wi-Fi usability score.
- * @param score The Wi-Fi usability score, expected range: [0, 100].
- * @param predictionHorizonSec Prediction horizon of the Wi-Fi usability score in second,
- * expected range: [0, 30].
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE)
- public void updateWifiUsabilityScore(int seqNum, int score, int predictionHorizonSec) {
- try {
- mService.updateWifiUsabilityScore(seqNum, score, predictionHorizonSec);
- } 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)}.
- */
- public abstract static class ScanResultsCallback {
- private final ScanResultsCallbackProxy mScanResultsCallbackProxy;
-
- public ScanResultsCallback() {
- mScanResultsCallbackProxy = new ScanResultsCallbackProxy();
- }
-
- /**
- * Called when new scan results are available.
- * Clients should use {@link WifiManager#getScanResults()} to get the scan results.
- */
- public abstract void onScanResultsAvailable();
-
- /*package*/ @NonNull ScanResultsCallbackProxy getProxy() {
- return mScanResultsCallbackProxy;
- }
-
- private static class ScanResultsCallbackProxy extends IScanResultsCallback.Stub {
- private final Object mLock = new Object();
- @Nullable @GuardedBy("mLock") private Executor mExecutor;
- @Nullable @GuardedBy("mLock") private ScanResultsCallback mCallback;
-
- ScanResultsCallbackProxy() {
- mCallback = null;
- mExecutor = null;
- }
-
- /*package*/ void initProxy(@NonNull Executor executor,
- @NonNull ScanResultsCallback callback) {
- synchronized (mLock) {
- mExecutor = executor;
- mCallback = callback;
- }
- }
-
- /*package*/ void cleanUpProxy() {
- synchronized (mLock) {
- mExecutor = null;
- mCallback = null;
- }
- }
-
- @Override
- public void onScanResultsAvailable() {
- ScanResultsCallback callback;
- Executor executor;
- synchronized (mLock) {
- executor = mExecutor;
- callback = mCallback;
- }
- if (callback == null || executor == null) {
- return;
- }
- Binder.clearCallingIdentity();
- executor.execute(callback::onScanResultsAvailable);
- }
- }
- }
-
- /**
- * Register a callback for Scan Results. See {@link ScanResultsCallback}.
- * Caller will receive the event when scan results are available.
- * Caller should use {@link WifiManager#getScanResults()} requires
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} to get the scan results.
- * Caller can remove a previously registered callback using
- * {@link WifiManager#unregisterScanResultsCallback(ScanResultsCallback)}
- * Same caller can add multiple listeners.
- * <p>
- * Applications should have the
- * {@link android.Manifest.permission#ACCESS_WIFI_STATE} permission. Callers
- * without the permission will trigger a {@link java.lang.SecurityException}.
- * <p>
- *
- * @param executor The executor to execute the callback of the {@code callback} object.
- * @param callback callback for Scan Results events
- */
-
- @RequiresPermission(ACCESS_WIFI_STATE)
- public void registerScanResultsCallback(@NonNull @CallbackExecutor Executor executor,
- @NonNull ScanResultsCallback callback) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
-
- Log.v(TAG, "registerScanResultsCallback: callback=" + callback
- + ", executor=" + executor);
- ScanResultsCallback.ScanResultsCallbackProxy proxy = callback.getProxy();
- proxy.initProxy(executor, callback);
- try {
- mService.registerScanResultsCallback(proxy);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow callers to unregister a previously registered callback. After calling this method,
- * applications will no longer receive Scan Results events.
- *
- * @param callback callback to unregister for Scan Results events
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public void unregisterScanResultsCallback(@NonNull ScanResultsCallback callback) {
- if (callback == null) throw new IllegalArgumentException("callback cannot be null");
- Log.v(TAG, "unregisterScanResultsCallback: Callback=" + callback);
- ScanResultsCallback.ScanResultsCallbackProxy proxy = callback.getProxy();
- try {
- mService.unregisterScanResultsCallback(proxy);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- } finally {
- proxy.cleanUpProxy();
- }
- }
-
- /**
- * Interface for suggestion connection status listener.
- * Should be implemented by applications and set when calling
- * {@link WifiManager#addSuggestionConnectionStatusListener(
- * Executor, SuggestionConnectionStatusListener)}.
- */
- public interface SuggestionConnectionStatusListener {
-
- /**
- * Called when the framework attempted to connect to a suggestion provided by the
- * registering app, but the connection to the suggestion failed.
- * @param wifiNetworkSuggestion The suggestion which failed to connect.
- * @param failureReason the connection failure reason code. One of
- * {@link #STATUS_SUGGESTION_CONNECTION_FAILURE_ASSOCIATION},
- * {@link #STATUS_SUGGESTION_CONNECTION_FAILURE_AUTHENTICATION},
- * {@link #STATUS_SUGGESTION_CONNECTION_FAILURE_IP_PROVISIONING}
- * {@link #STATUS_SUGGESTION_CONNECTION_FAILURE_UNKNOWN}
- */
- void onConnectionStatus(
- @NonNull WifiNetworkSuggestion wifiNetworkSuggestion,
- @SuggestionConnectionStatusCode int failureReason);
- }
-
- private class SuggestionConnectionStatusListenerProxy extends
- ISuggestionConnectionStatusListener.Stub {
- private final Executor mExecutor;
- private final SuggestionConnectionStatusListener mListener;
-
- SuggestionConnectionStatusListenerProxy(@NonNull Executor executor,
- @NonNull SuggestionConnectionStatusListener listener) {
- mExecutor = executor;
- mListener = listener;
- }
-
- @Override
- public void onConnectionStatus(@NonNull WifiNetworkSuggestion wifiNetworkSuggestion,
- int failureReason) {
- mExecutor.execute(() ->
- mListener.onConnectionStatus(wifiNetworkSuggestion, failureReason));
- }
-
- }
-
- /**
- * Add a listener for suggestion networks. See {@link SuggestionConnectionStatusListener}.
- * Caller will receive the event when suggested network have connection failure.
- * Caller can remove a previously registered listener using
- * {@link WifiManager#removeSuggestionConnectionStatusListener(
- * SuggestionConnectionStatusListener)}
- * Same caller can add multiple listeners to monitor the event.
- * <p>
- * Applications should have the
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and
- * {@link android.Manifest.permission#ACCESS_WIFI_STATE} permissions.
- * Callers without the permission will trigger a {@link java.lang.SecurityException}.
- * <p>
- *
- * @param executor The executor to execute the listener of the {@code listener} object.
- * @param listener listener for suggestion network connection failure.
- */
- @RequiresPermission(allOf = {ACCESS_FINE_LOCATION, ACCESS_WIFI_STATE})
- public void addSuggestionConnectionStatusListener(@NonNull @CallbackExecutor Executor executor,
- @NonNull SuggestionConnectionStatusListener listener) {
- if (listener == null) throw new IllegalArgumentException("Listener cannot be null");
- if (executor == null) throw new IllegalArgumentException("Executor cannot be null");
- Log.v(TAG, "addSuggestionConnectionStatusListener listener=" + listener
- + ", executor=" + executor);
- try {
- mService.registerSuggestionConnectionStatusListener(new Binder(),
- new SuggestionConnectionStatusListenerProxy(executor, listener),
- listener.hashCode(), mContext.getOpPackageName(), mContext.getAttributionTag());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
-
- }
-
- /**
- * Allow callers to remove a previously registered listener. After calling this method,
- * applications will no longer receive suggestion connection events through that listener.
- *
- * @param listener listener to remove.
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public void removeSuggestionConnectionStatusListener(
- @NonNull SuggestionConnectionStatusListener listener) {
- if (listener == null) throw new IllegalArgumentException("Listener cannot be null");
- Log.v(TAG, "removeSuggestionConnectionStatusListener: listener=" + listener);
- try {
- mService.unregisterSuggestionConnectionStatusListener(listener.hashCode(),
- mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Parse the list of channels the DPP enrollee reports when it fails to find an AP.
- *
- * @param channelList List of channels in the format defined in the DPP specification.
- * @return A parsed sparse array, where the operating class is the key.
- * @hide
- */
- @VisibleForTesting
- public static SparseArray<int[]> parseDppChannelList(String channelList) {
- SparseArray<int[]> channelListArray = new SparseArray<>();
-
- if (TextUtils.isEmpty(channelList)) {
- return channelListArray;
- }
- StringTokenizer str = new StringTokenizer(channelList, ",");
- String classStr = null;
- List<Integer> channelsInClass = new ArrayList<>();
-
- try {
- while (str.hasMoreElements()) {
- String cur = str.nextToken();
-
- /**
- * Example for a channel list:
- *
- * 81/1,2,3,4,5,6,7,8,9,10,11,115/36,40,44,48,118/52,56,60,64,121/100,104,108,112,
- * 116,120,124,128,132,136,140,0/144,124/149,153,157,161,125/165
- *
- * Detect operating class by the delimiter of '/' and use a string tokenizer with
- * ',' as a delimiter.
- */
- int classDelim = cur.indexOf('/');
- if (classDelim != -1) {
- if (classStr != null) {
- // Store the last channel array in the sparse array, where the operating
- // class is the key (as an integer).
- int[] channelsArray = new int[channelsInClass.size()];
- for (int i = 0; i < channelsInClass.size(); i++) {
- channelsArray[i] = channelsInClass.get(i);
- }
- channelListArray.append(Integer.parseInt(classStr), channelsArray);
- channelsInClass = new ArrayList<>();
- }
-
- // Init a new operating class and store the first channel
- classStr = cur.substring(0, classDelim);
- String channelStr = cur.substring(classDelim + 1);
- channelsInClass.add(Integer.parseInt(channelStr));
- } else {
- if (classStr == null) {
- // Invalid format
- Log.e(TAG, "Cannot parse DPP channel list");
- return new SparseArray<>();
- }
- channelsInClass.add(Integer.parseInt(cur));
- }
- }
-
- // Store the last array
- if (classStr != null) {
- int[] channelsArray = new int[channelsInClass.size()];
- for (int i = 0; i < channelsInClass.size(); i++) {
- channelsArray[i] = channelsInClass.get(i);
- }
- channelListArray.append(Integer.parseInt(classStr), channelsArray);
- }
- return channelListArray;
- } catch (NumberFormatException e) {
- Log.e(TAG, "Cannot parse DPP channel list");
- return new SparseArray<>();
- }
- }
-
- /**
- * Callback interface for framework to receive network status updates and trigger of updating
- * {@link WifiUsabilityStatsEntry}.
- *
- * @hide
- */
- @SystemApi
- public interface ScoreUpdateObserver {
- /**
- * Called by applications to indicate network status.
- *
- * @param sessionId The ID to indicate current Wi-Fi network connection obtained from
- * {@link WifiConnectedNetworkScorer#onStart(int)}.
- * @param score The score representing link quality of current Wi-Fi network connection.
- * Populated by connected network scorer in applications..
- */
- void notifyScoreUpdate(int sessionId, int score);
-
- /**
- * Called by applications to trigger an update of {@link WifiUsabilityStatsEntry}.
- * To receive update applications need to add WifiUsabilityStatsEntry listener. See
- * {@link addOnWifiUsabilityStatsListener(Executor, OnWifiUsabilityStatsListener)}.
- *
- * @param sessionId The ID to indicate current Wi-Fi network connection obtained from
- * {@link WifiConnectedNetworkScorer#onStart(int)}.
- */
- void triggerUpdateOfWifiUsabilityStats(int sessionId);
- }
-
- /**
- * Callback proxy for {@link ScoreUpdateObserver} objects.
- *
- * @hide
- */
- private class ScoreUpdateObserverProxy implements ScoreUpdateObserver {
- private final IScoreUpdateObserver mScoreUpdateObserver;
-
- private ScoreUpdateObserverProxy(IScoreUpdateObserver observer) {
- mScoreUpdateObserver = observer;
- }
-
- @Override
- public void notifyScoreUpdate(int sessionId, int score) {
- try {
- mScoreUpdateObserver.notifyScoreUpdate(sessionId, score);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- @Override
- public void triggerUpdateOfWifiUsabilityStats(int sessionId) {
- try {
- mScoreUpdateObserver.triggerUpdateOfWifiUsabilityStats(sessionId);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /**
- * Interface for Wi-Fi connected network scorer. Should be implemented by applications and set
- * when calling
- * {@link WifiManager#setWifiConnectedNetworkScorer(Executor, WifiConnectedNetworkScorer)}.
- *
- * @hide
- */
- @SystemApi
- public interface WifiConnectedNetworkScorer {
- /**
- * Called by framework to indicate the start of a network connection.
- * @param sessionId The ID to indicate current Wi-Fi network connection.
- */
- void onStart(int sessionId);
-
- /**
- * Called by framework to indicate the end of a network connection.
- * @param sessionId The ID to indicate current Wi-Fi network connection obtained from
- * {@link WifiConnectedNetworkScorer#onStart(int)}.
- */
- void onStop(int sessionId);
-
- /**
- * Framework sets callback for score change events after application sets its scorer.
- * @param observerImpl The instance for {@link WifiManager#ScoreUpdateObserver}. Should be
- * implemented and instantiated by framework.
- */
- void onSetScoreUpdateObserver(@NonNull ScoreUpdateObserver observerImpl);
- }
-
- /**
- * Callback proxy for {@link WifiConnectedNetworkScorer} objects.
- *
- * @hide
- */
- private class WifiConnectedNetworkScorerProxy extends IWifiConnectedNetworkScorer.Stub {
- private Executor mExecutor;
- private WifiConnectedNetworkScorer mScorer;
-
- WifiConnectedNetworkScorerProxy(Executor executor, WifiConnectedNetworkScorer scorer) {
- mExecutor = executor;
- mScorer = scorer;
- }
-
- @Override
- public void onStart(int sessionId) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "WifiConnectedNetworkScorer: " + "onStart: sessionId=" + sessionId);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> mScorer.onStart(sessionId));
- }
-
- @Override
- public void onStop(int sessionId) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "WifiConnectedNetworkScorer: " + "onStop: sessionId=" + sessionId);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> mScorer.onStop(sessionId));
- }
-
- @Override
- public void onSetScoreUpdateObserver(IScoreUpdateObserver observerImpl) {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "WifiConnectedNetworkScorer: "
- + "onSetScoreUpdateObserver: observerImpl=" + observerImpl);
- }
- Binder.clearCallingIdentity();
- mExecutor.execute(() -> mScorer.onSetScoreUpdateObserver(
- new ScoreUpdateObserverProxy(observerImpl)));
- }
- }
-
- /**
- * Set a callback for Wi-Fi connected network scorer. See {@link WifiConnectedNetworkScorer}.
- * Only a single scorer can be set. Caller will be invoked periodically by framework to inform
- * client about start and stop of Wi-Fi connection. Caller can clear a previously set scorer
- * using {@link clearWifiConnectedNetworkScorer()}.
- *
- * @param executor The executor on which callback will be invoked.
- * @param scorer Scorer for Wi-Fi network implemented by application.
- * @return true Scorer is set successfully.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE)
- public boolean setWifiConnectedNetworkScorer(@NonNull @CallbackExecutor Executor executor,
- @NonNull WifiConnectedNetworkScorer scorer) {
- if (executor == null) throw new IllegalArgumentException("executor cannot be null");
- if (scorer == null) throw new IllegalArgumentException("scorer cannot be null");
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "setWifiConnectedNetworkScorer: scorer=" + scorer);
- }
- try {
- return mService.setWifiConnectedNetworkScorer(new Binder(),
- new WifiConnectedNetworkScorerProxy(executor, scorer));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Allow caller to clear a previously set scorer. After calling this method,
- * client will no longer receive information about start and stop of Wi-Fi connection.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE)
- public void clearWifiConnectedNetworkScorer() {
- if (mVerboseLoggingEnabled) {
- Log.v(TAG, "clearWifiConnectedNetworkScorer");
- }
- try {
- mService.clearWifiConnectedNetworkScorer();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Enable/disable wifi scan throttling from 3rd party apps.
- *
- * <p>
- * The throttling limits for apps are described in
- * <a href="Wi-Fi Scan Throttling">
- * https://developer.android.com/guide/topics/connectivity/wifi-scan#wifi-scan-throttling</a>
- * </p>
- *
- * @param enable true to allow scan throttling, false to disallow scan throttling.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setScanThrottleEnabled(boolean enable) {
- try {
- mService.setScanThrottleEnabled(enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get the persisted Wi-Fi scan throttle state. Defaults to true, unless changed by the user via
- * Developer options.
- *
- * <p>
- * The throttling limits for apps are described in
- * <a href="Wi-Fi Scan Throttling">
- * https://developer.android.com/guide/topics/connectivity/wifi-scan#wifi-scan-throttling</a>
- * </p>
- *
- * @return true to indicate that scan throttling is enabled, false to indicate that scan
- * throttling is disabled.
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public boolean isScanThrottleEnabled() {
- try {
- return mService.isScanThrottleEnabled();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Enable/disable wifi auto wakeup feature.
- *
- * <p>
- * The feature is described in
- * <a href="Wi-Fi Turn on automatically">
- * https://source.android.com/devices/tech/connect/wifi-infrastructure
- * #turn_on_wi-fi_automatically
- * </a>
- *
- * @param enable true to enable, false to disable.
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void setAutoWakeupEnabled(boolean enable) {
- try {
- mService.setAutoWakeupEnabled(enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get the persisted Wi-Fi auto wakeup feature state. Defaults to false, unless changed by the
- * user via Settings.
- *
- * <p>
- * The feature is described in
- * <a href="Wi-Fi Turn on automatically">
- * https://source.android.com/devices/tech/connect/wifi-infrastructure
- * #turn_on_wi-fi_automatically
- * </a>
- *
- * @return true to indicate that wakeup feature is enabled, false to indicate that wakeup
- * feature is disabled.
- */
- @RequiresPermission(ACCESS_WIFI_STATE)
- public boolean isAutoWakeupEnabled() {
- try {
- return mService.isAutoWakeupEnabled();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Sets the state of carrier offload on merged or unmerged networks for specified subscription.
- *
- * <p>
- * When a subscription's carrier network offload is disabled, all network suggestions related to
- * this subscription will not be considered for auto join.
- * <p>
- * If calling app want disable all carrier network offload from a specified subscription, should
- * call this API twice to disable both merged and unmerged carrier network suggestions.
- *
- * @param subscriptionId See {@link SubscriptionInfo#getSubscriptionId()}.
- * @param merged True for carrier merged network, false otherwise.
- * See {@link WifiNetworkSuggestion.Builder#setCarrierMerged(boolean)}
- * @param enabled True for enable carrier network offload, false otherwise.
- * @see #isCarrierNetworkOffloadEnabled(int, boolean)
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public void setCarrierNetworkOffloadEnabled(int subscriptionId, boolean merged,
- boolean enabled) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- try {
- mService.setCarrierNetworkOffloadEnabled(subscriptionId, merged, enabled);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get the carrier network offload state for merged or unmerged networks for specified
- * subscription.
- * @param subscriptionId subscription ID see {@link SubscriptionInfo#getSubscriptionId()}
- * @param merged True for carrier merged network, false otherwise.
- * See {@link WifiNetworkSuggestion.Builder#setCarrierMerged(boolean)}
- * @return True to indicate that carrier network offload is enabled, false otherwise.
- * @see #setCarrierNetworkOffloadEnabled(int, boolean, boolean)
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_SETUP_WIZARD})
- public boolean isCarrierNetworkOffloadEnabled(int subscriptionId, boolean merged) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- try {
- return mService.isCarrierNetworkOffloadEnabled(subscriptionId, merged);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get device VHT 8SS capability info.
- *
- * @return true if device supports VHT 8SS or false.
- *
- * @hide no intent to publish
- */
- public boolean isVht8ssCapableDevice() {
- try {
- return mService.isVht8ssCapableDevice();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Run driver command from user space
- * @hide
- */
- public String doDriverCmd(String command)
- {
- try {
- return mService.doDriverCmd(command);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiMigration.java b/wifi/java/android/net/wifi/WifiMigration.java
deleted file mode 100755
index 5792d27a94f9..000000000000
--- a/wifi/java/android/net/wifi/WifiMigration.java
+++ /dev/null
@@ -1,558 +0,0 @@
-/*
- * Copyright (C) 2020 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 static android.os.Environment.getDataMiscCeDirectory;
-import static android.os.Environment.getDataMiscDirectory;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.content.Context;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.os.UserHandle;
-import android.provider.Settings;
-import android.util.AtomicFile;
-import android.util.SparseArray;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Objects;
-
-/**
- * Class used to provide one time hooks for existing OEM devices to migrate their config store
- * data and other settings to the wifi apex.
- * @hide
- */
-@SystemApi
-public final class WifiMigration {
- /**
- * Directory to read the wifi config store files from under.
- */
- private static final String LEGACY_WIFI_STORE_DIRECTORY_NAME = "wifi";
- /**
- * Config store file for general shared store file.
- * AOSP Path on Android 10: /data/misc/wifi/WifiConfigStore.xml
- */
- public static final int STORE_FILE_SHARED_GENERAL = 0;
- /**
- * Config store file for softap shared store file.
- * AOSP Path on Android 10: /data/misc/wifi/softap.conf
- */
- public static final int STORE_FILE_SHARED_SOFTAP = 1;
- /**
- * Config store file for general user store file.
- * AOSP Path on Android 10: /data/misc_ce/<userId>/wifi/WifiConfigStore.xml
- */
- public static final int STORE_FILE_USER_GENERAL = 2;
- /**
- * Config store file for network suggestions user store file.
- * AOSP Path on Android 10: /data/misc_ce/<userId>/wifi/WifiConfigStoreNetworkSuggestions.xml
- */
- public static final int STORE_FILE_USER_NETWORK_SUGGESTIONS = 3;
-
- /** @hide */
- @IntDef(prefix = { "STORE_FILE_SHARED_" }, value = {
- STORE_FILE_SHARED_GENERAL,
- STORE_FILE_SHARED_SOFTAP,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface SharedStoreFileId { }
-
- /** @hide */
- @IntDef(prefix = { "STORE_FILE_USER_" }, value = {
- STORE_FILE_USER_GENERAL,
- STORE_FILE_USER_NETWORK_SUGGESTIONS
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface UserStoreFileId { }
-
- /**
- * Mapping of Store file Id to Store file names.
- *
- * NOTE: This is the default path for the files on AOSP devices. If the OEM has modified
- * the path or renamed the files, please edit this appropriately.
- */
- private static final SparseArray<String> STORE_ID_TO_FILE_NAME =
- new SparseArray<String>() {{
- put(STORE_FILE_SHARED_GENERAL, "WifiConfigStore.xml");
- put(STORE_FILE_SHARED_SOFTAP, "WifiConfigStoreSoftAp.xml");
- put(STORE_FILE_USER_GENERAL, "WifiConfigStore.xml");
- put(STORE_FILE_USER_NETWORK_SUGGESTIONS, "WifiConfigStoreNetworkSuggestions.xml");
- }};
-
- /**
- * Pre-apex wifi shared folder.
- */
- private static File getLegacyWifiSharedDirectory() {
- return new File(getDataMiscDirectory(), LEGACY_WIFI_STORE_DIRECTORY_NAME);
- }
-
- /**
- * Pre-apex wifi user folder.
- */
- private static File getLegacyWifiUserDirectory(int userId) {
- return new File(getDataMiscCeDirectory(userId), LEGACY_WIFI_STORE_DIRECTORY_NAME);
- }
-
- /**
- * Legacy files were stored as AtomicFile. So, always use AtomicFile to operate on it to ensure
- * data integrity.
- */
- private static AtomicFile getSharedAtomicFile(@SharedStoreFileId int storeFileId) {
- return new AtomicFile(new File(
- getLegacyWifiSharedDirectory(),
- STORE_ID_TO_FILE_NAME.get(storeFileId)));
- }
-
- /**
- * Legacy files were stored as AtomicFile. So, always use AtomicFile to operate on it to ensure
- * data integrity.
- */
- private static AtomicFile getUserAtomicFile(@UserStoreFileId int storeFileId, int userId) {
- return new AtomicFile(new File(
- getLegacyWifiUserDirectory(userId),
- STORE_ID_TO_FILE_NAME.get(storeFileId)));
- }
-
- private WifiMigration() { }
-
- /**
- * Load data from legacy shared wifi config store file.
- * <p>
- * Expected AOSP format is available in the sample files under {@code /frameworks/base/wifi/
- * java/android/net/wifi/migration_samples}.
- * </p>
- * <p>
- * Note:
- * <li>OEMs need to change the implementation of
- * {@link #convertAndRetrieveSharedConfigStoreFile(int)} only if their existing config store
- * format or file locations differs from the vanilla AOSP implementation.</li>
- * <li>The wifi apex will invoke
- * {@link #convertAndRetrieveSharedConfigStoreFile(int)}
- * method on every bootup, it is the responsibility of the OEM implementation to ensure that
- * they perform the necessary in place conversion of their config store file to conform to the
- * AOSP format. The OEM should ensure that the method should only return the
- * {@link InputStream} stream for the data to be migrated only on the first bootup.</li>
- * <li>Once the migration is done, the apex will invoke
- * {@link #removeSharedConfigStoreFile(int)} to delete the store file.</li>
- * <li>The only relevant invocation of {@link #convertAndRetrieveSharedConfigStoreFile(int)}
- * occurs when a previously released device upgrades to the wifi apex from an OEM
- * implementation of the wifi stack.
- * <li>Ensure that the legacy file paths are accessible to the wifi module (sepolicy rules, file
- * permissions, etc). Since the wifi service continues to run inside system_server process, this
- * method will be called from the same context (so ideally the file should still be accessible).
- * </li>
- *
- * @param storeFileId Identifier for the config store file. One of
- * {@link #STORE_FILE_SHARED_GENERAL} or {@link #STORE_FILE_SHARED_GENERAL}
- * @return Instance of {@link InputStream} for migrating data, null if no migration is
- * necessary.
- * @throws IllegalArgumentException on invalid storeFileId.
- */
- @Nullable
- public static InputStream convertAndRetrieveSharedConfigStoreFile(
- @SharedStoreFileId int storeFileId) {
- if (storeFileId != STORE_FILE_SHARED_GENERAL && storeFileId != STORE_FILE_SHARED_SOFTAP) {
- throw new IllegalArgumentException("Invalid shared store file id");
- }
- try {
- // OEMs should do conversions necessary here before returning the stream.
- return getSharedAtomicFile(storeFileId).openRead();
- } catch (FileNotFoundException e) {
- // Special handling for softap.conf.
- // Note: OEM devices upgrading from Q -> R will only have the softap.conf file.
- // Test devices running previous R builds however may have already migrated to the
- // XML format. So, check for that above before falling back to check for legacy file.
- if (storeFileId == STORE_FILE_SHARED_SOFTAP) {
- return SoftApConfToXmlMigrationUtil.convert();
- }
- return null;
- }
- }
-
- /**
- * Remove the legacy shared wifi config store file.
- *
- * @param storeFileId Identifier for the config store file. One of
- * {@link #STORE_FILE_SHARED_GENERAL} or {@link #STORE_FILE_SHARED_GENERAL}
- * @throws IllegalArgumentException on invalid storeFileId.
- */
- public static void removeSharedConfigStoreFile(@SharedStoreFileId int storeFileId) {
- if (storeFileId != STORE_FILE_SHARED_GENERAL && storeFileId != STORE_FILE_SHARED_SOFTAP) {
- throw new IllegalArgumentException("Invalid shared store file id");
- }
- AtomicFile file = getSharedAtomicFile(storeFileId);
- if (file.exists()) {
- file.delete();
- return;
- }
- // Special handling for softap.conf.
- // Note: OEM devices upgrading from Q -> R will only have the softap.conf file.
- // Test devices running previous R builds however may have already migrated to the
- // XML format. So, check for that above before falling back to check for legacy file.
- if (storeFileId == STORE_FILE_SHARED_SOFTAP) {
- SoftApConfToXmlMigrationUtil.remove();
- }
- }
-
- /**
- * Load data from legacy user wifi config store file.
- * <p>
- * Expected AOSP format is available in the sample files under {@code /frameworks/base/wifi/
- * java/android/net/wifi/migration_samples}.
- * </p>
- * <p>
- * Note:
- * <li>OEMs need to change the implementation of
- * {@link #convertAndRetrieveUserConfigStoreFile(int, UserHandle)} only if their existing config
- * store format or file locations differs from the vanilla AOSP implementation.</li>
- * <li>The wifi apex will invoke
- * {@link #convertAndRetrieveUserConfigStoreFile(int, UserHandle)}
- * method on every bootup, it is the responsibility of the OEM implementation to ensure that
- * they perform the necessary in place conversion of their config store file to conform to the
- * AOSP format. The OEM should ensure that the method should only return the
- * {@link InputStream} stream for the data to be migrated only on the first bootup.</li>
- * <li>Once the migration is done, the apex will invoke
- * {@link #removeUserConfigStoreFile(int, UserHandle)} to delete the store file.</li>
- * <li>The only relevant invocation of
- * {@link #convertAndRetrieveUserConfigStoreFile(int, UserHandle)} occurs when a previously
- * released device upgrades to the wifi apex from an OEM implementation of the wifi
- * stack.
- * </li>
- * <li>Ensure that the legacy file paths are accessible to the wifi module (sepolicy rules, file
- * permissions, etc). Since the wifi service continues to run inside system_server process, this
- * method will be called from the same context (so ideally the file should still be accessible).
- * </li>
- *
- * @param storeFileId Identifier for the config store file. One of
- * {@link #STORE_FILE_USER_GENERAL} or {@link #STORE_FILE_USER_NETWORK_SUGGESTIONS}
- * @param userHandle User handle.
- * @return Instance of {@link InputStream} for migrating data, null if no migration is
- * necessary.
- * @throws IllegalArgumentException on invalid storeFileId or userHandle.
- */
- @Nullable
- public static InputStream convertAndRetrieveUserConfigStoreFile(
- @UserStoreFileId int storeFileId, @NonNull UserHandle userHandle) {
- if (storeFileId != STORE_FILE_USER_GENERAL
- && storeFileId != STORE_FILE_USER_NETWORK_SUGGESTIONS) {
- throw new IllegalArgumentException("Invalid user store file id");
- }
- Objects.requireNonNull(userHandle);
- try {
- // OEMs should do conversions necessary here before returning the stream.
- return getUserAtomicFile(storeFileId, userHandle.getIdentifier()).openRead();
- } catch (FileNotFoundException e) {
- return null;
- }
- }
-
- /**
- * Remove the legacy user wifi config store file.
- *
- * @param storeFileId Identifier for the config store file. One of
- * {@link #STORE_FILE_USER_GENERAL} or {@link #STORE_FILE_USER_NETWORK_SUGGESTIONS}
- * @param userHandle User handle.
- * @throws IllegalArgumentException on invalid storeFileId or userHandle.
- */
- public static void removeUserConfigStoreFile(
- @UserStoreFileId int storeFileId, @NonNull UserHandle userHandle) {
- if (storeFileId != STORE_FILE_USER_GENERAL
- && storeFileId != STORE_FILE_USER_NETWORK_SUGGESTIONS) {
- throw new IllegalArgumentException("Invalid user store file id");
- }
- Objects.requireNonNull(userHandle);
- AtomicFile file = getUserAtomicFile(storeFileId, userHandle.getIdentifier());
- if (file.exists()) {
- file.delete();
- }
- }
-
- /**
- * Container for all the wifi settings data to migrate.
- */
- public static final class SettingsMigrationData implements Parcelable {
- private final boolean mScanAlwaysAvailable;
- private final boolean mP2pFactoryResetPending;
- private final String mP2pDeviceName;
- private final boolean mSoftApTimeoutEnabled;
- private final boolean mWakeupEnabled;
- private final boolean mScanThrottleEnabled;
- private final boolean mVerboseLoggingEnabled;
-
- private SettingsMigrationData(boolean scanAlwaysAvailable, boolean p2pFactoryResetPending,
- @Nullable String p2pDeviceName, boolean softApTimeoutEnabled, boolean wakeupEnabled,
- boolean scanThrottleEnabled, boolean verboseLoggingEnabled) {
- mScanAlwaysAvailable = scanAlwaysAvailable;
- mP2pFactoryResetPending = p2pFactoryResetPending;
- mP2pDeviceName = p2pDeviceName;
- mSoftApTimeoutEnabled = softApTimeoutEnabled;
- mWakeupEnabled = wakeupEnabled;
- mScanThrottleEnabled = scanThrottleEnabled;
- mVerboseLoggingEnabled = verboseLoggingEnabled;
- }
-
- public static final @NonNull Parcelable.Creator<SettingsMigrationData> CREATOR =
- new Parcelable.Creator<SettingsMigrationData>() {
- @Override
- public SettingsMigrationData createFromParcel(Parcel in) {
- boolean scanAlwaysAvailable = in.readBoolean();
- boolean p2pFactoryResetPending = in.readBoolean();
- String p2pDeviceName = in.readString();
- boolean softApTimeoutEnabled = in.readBoolean();
- boolean wakeupEnabled = in.readBoolean();
- boolean scanThrottleEnabled = in.readBoolean();
- boolean verboseLoggingEnabled = in.readBoolean();
- return new SettingsMigrationData(
- scanAlwaysAvailable, p2pFactoryResetPending,
- p2pDeviceName, softApTimeoutEnabled, wakeupEnabled,
- scanThrottleEnabled, verboseLoggingEnabled);
- }
-
- @Override
- public SettingsMigrationData[] newArray(int size) {
- return new SettingsMigrationData[size];
- }
- };
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeBoolean(mScanAlwaysAvailable);
- dest.writeBoolean(mP2pFactoryResetPending);
- dest.writeString(mP2pDeviceName);
- dest.writeBoolean(mSoftApTimeoutEnabled);
- dest.writeBoolean(mWakeupEnabled);
- dest.writeBoolean(mScanThrottleEnabled);
- dest.writeBoolean(mVerboseLoggingEnabled);
- }
-
- /**
- * @return True if scans are allowed even when wifi is toggled off, false otherwise.
- */
- public boolean isScanAlwaysAvailable() {
- return mScanAlwaysAvailable;
- }
-
- /**
- * @return indicate whether factory reset request is pending.
- */
- public boolean isP2pFactoryResetPending() {
- return mP2pFactoryResetPending;
- }
-
- /**
- * @return the Wi-Fi peer-to-peer device name
- */
- public @Nullable String getP2pDeviceName() {
- return mP2pDeviceName;
- }
-
- /**
- * @return Whether soft AP will shut down after a timeout period when no devices are
- * connected.
- */
- public boolean isSoftApTimeoutEnabled() {
- return mSoftApTimeoutEnabled;
- }
-
- /**
- * @return whether Wi-Fi Wakeup feature is enabled.
- */
- public boolean isWakeUpEnabled() {
- return mWakeupEnabled;
- }
-
- /**
- * @return Whether wifi scan throttle is enabled or not.
- */
- public boolean isScanThrottleEnabled() {
- return mScanThrottleEnabled;
- }
-
- /**
- * @return Whether to enable verbose logging in Wi-Fi.
- */
- public boolean isVerboseLoggingEnabled() {
- return mVerboseLoggingEnabled;
- }
-
- /**
- * Builder to create instance of {@link SettingsMigrationData}.
- */
- public static final class Builder {
- private boolean mScanAlwaysAvailable;
- private boolean mP2pFactoryResetPending;
- private String mP2pDeviceName;
- private boolean mSoftApTimeoutEnabled;
- private boolean mWakeupEnabled;
- private boolean mScanThrottleEnabled;
- private boolean mVerboseLoggingEnabled;
-
- public Builder() {
- }
-
- /**
- * Setting to allow scans even when wifi is toggled off.
- *
- * @param available true if available, false otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setScanAlwaysAvailable(boolean available) {
- mScanAlwaysAvailable = available;
- return this;
- }
-
- /**
- * Indicate whether factory reset request is pending.
- *
- * @param pending true if pending, false otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setP2pFactoryResetPending(boolean pending) {
- mP2pFactoryResetPending = pending;
- return this;
- }
-
- /**
- * The Wi-Fi peer-to-peer device name
- *
- * @param name Name if set, null otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setP2pDeviceName(@Nullable String name) {
- mP2pDeviceName = name;
- return this;
- }
-
- /**
- * Whether soft AP will shut down after a timeout period when no devices are connected.
- *
- * @param enabled true if enabled, false otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setSoftApTimeoutEnabled(boolean enabled) {
- mSoftApTimeoutEnabled = enabled;
- return this;
- }
-
- /**
- * Value to specify if Wi-Fi Wakeup feature is enabled.
- *
- * @param enabled true if enabled, false otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setWakeUpEnabled(boolean enabled) {
- mWakeupEnabled = enabled;
- return this;
- }
-
- /**
- * Whether wifi scan throttle is enabled or not.
- *
- * @param enabled true if enabled, false otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setScanThrottleEnabled(boolean enabled) {
- mScanThrottleEnabled = enabled;
- return this;
- }
-
- /**
- * Setting to enable verbose logging in Wi-Fi.
- *
- * @param enabled true if enabled, false otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setVerboseLoggingEnabled(boolean enabled) {
- mVerboseLoggingEnabled = enabled;
- return this;
- }
-
- /**
- * Build an instance of {@link SettingsMigrationData}.
- *
- * @return Instance of {@link SettingsMigrationData}.
- */
- public @NonNull SettingsMigrationData build() {
- return new SettingsMigrationData(mScanAlwaysAvailable, mP2pFactoryResetPending,
- mP2pDeviceName, mSoftApTimeoutEnabled, mWakeupEnabled, mScanThrottleEnabled,
- mVerboseLoggingEnabled);
- }
- }
- }
-
- /**
- * Load data from Settings.Global values.
- *
- * <p>
- * Note:
- * <li> This is method is invoked once on the first bootup. OEM can safely delete these settings
- * once the migration is complete. The first & only relevant invocation of
- * {@link #loadFromSettings(Context)} ()} occurs when a previously released
- * device upgrades to the wifi apex from an OEM implementation of the wifi stack.
- * </li>
- *
- * @param context Context to use for loading the settings provider.
- * @return Instance of {@link SettingsMigrationData} for migrating data.
- */
- @NonNull
- public static SettingsMigrationData loadFromSettings(@NonNull Context context) {
- if (Settings.Global.getInt(
- context.getContentResolver(), Settings.Global.WIFI_MIGRATION_COMPLETED, 0) == 1) {
- // migration already complete, ignore.
- return null;
- }
- SettingsMigrationData data = new SettingsMigrationData.Builder()
- .setScanAlwaysAvailable(
- Settings.Global.getInt(context.getContentResolver(),
- Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 1)
- .setP2pFactoryResetPending(
- Settings.Global.getInt(context.getContentResolver(),
- Settings.Global.WIFI_P2P_PENDING_FACTORY_RESET, 0) == 1)
- .setP2pDeviceName(
- Settings.Global.getString(context.getContentResolver(),
- Settings.Global.WIFI_P2P_DEVICE_NAME))
- .setSoftApTimeoutEnabled(
- Settings.Global.getInt(context.getContentResolver(),
- Settings.Global.SOFT_AP_TIMEOUT_ENABLED, 1) == 1)
- .setWakeUpEnabled(
- Settings.Global.getInt(context.getContentResolver(),
- Settings.Global.WIFI_WAKEUP_ENABLED, 0) == 1)
- .setScanThrottleEnabled(
- Settings.Global.getInt(context.getContentResolver(),
- Settings.Global.WIFI_SCAN_THROTTLE_ENABLED, 1) == 1)
- .setVerboseLoggingEnabled(
- Settings.Global.getInt(context.getContentResolver(),
- Settings.Global.WIFI_VERBOSE_LOGGING_ENABLED, 0) == 1)
- .build();
- Settings.Global.putInt(
- context.getContentResolver(), Settings.Global.WIFI_MIGRATION_COMPLETED, 1);
- return data;
-
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java b/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
deleted file mode 100644
index 0d13805a08d8..000000000000
--- a/wifi/java/android/net/wifi/WifiNetworkAgentSpecifier.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2018 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 static com.android.internal.util.Preconditions.checkNotNull;
-import static com.android.internal.util.Preconditions.checkState;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.net.MacAddress;
-import android.net.MatchAllNetworkSpecifier;
-import android.net.NetworkRequest;
-import android.net.NetworkSpecifier;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.Objects;
-
-/**
- * Network specifier object used by wifi's {@link android.net.NetworkAgent}.
- * @hide
- */
-public final class WifiNetworkAgentSpecifier extends NetworkSpecifier implements Parcelable {
- /**
- * Security credentials for the currently connected network.
- */
- private final WifiConfiguration mWifiConfiguration;
-
- public WifiNetworkAgentSpecifier(@NonNull WifiConfiguration wifiConfiguration) {
- checkNotNull(wifiConfiguration);
-
- mWifiConfiguration = wifiConfiguration;
- }
-
- /**
- * @hide
- */
- public static final @android.annotation.NonNull Creator<WifiNetworkAgentSpecifier> CREATOR =
- new Creator<WifiNetworkAgentSpecifier>() {
- @Override
- public WifiNetworkAgentSpecifier createFromParcel(@NonNull Parcel in) {
- WifiConfiguration wifiConfiguration = in.readParcelable(null);
- return new WifiNetworkAgentSpecifier(wifiConfiguration);
- }
-
- @Override
- public WifiNetworkAgentSpecifier[] newArray(int size) {
- return new WifiNetworkAgentSpecifier[size];
- }
- };
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeParcelable(mWifiConfiguration, flags);
- }
-
- @Override
- public boolean canBeSatisfiedBy(@Nullable NetworkSpecifier other) {
- if (this == other) {
- return true;
- }
- // Any generic requests should be satisifed by a specific wifi network.
- if (other == null || other instanceof MatchAllNetworkSpecifier) {
- return true;
- }
- if (other instanceof WifiNetworkSpecifier) {
- return satisfiesNetworkSpecifier((WifiNetworkSpecifier) other);
- }
- return equals(other);
- }
-
- /**
- * Match {@link WifiNetworkSpecifier} in app's {@link NetworkRequest} with the
- * {@link WifiNetworkAgentSpecifier} in wifi platform's {@link android.net.NetworkAgent}.
- */
- public boolean satisfiesNetworkSpecifier(@NonNull WifiNetworkSpecifier ns) {
- // None of these should be null by construction.
- // {@link WifiNetworkSpecifier.Builder} enforces non-null in {@link WifiNetworkSpecifier}.
- // {@link WifiNetworkFactory} ensures non-null in {@link WifiNetworkAgentSpecifier}.
- checkNotNull(ns);
- checkNotNull(ns.ssidPatternMatcher);
- checkNotNull(ns.bssidPatternMatcher);
- checkNotNull(ns.wifiConfiguration.allowedKeyManagement);
- checkNotNull(this.mWifiConfiguration.SSID);
- checkNotNull(this.mWifiConfiguration.BSSID);
- checkNotNull(this.mWifiConfiguration.allowedKeyManagement);
-
- final String ssidWithQuotes = this.mWifiConfiguration.SSID;
- checkState(ssidWithQuotes.startsWith("\"") && ssidWithQuotes.endsWith("\""));
- final String ssidWithoutQuotes = ssidWithQuotes.substring(1, ssidWithQuotes.length() - 1);
- if (!ns.ssidPatternMatcher.match(ssidWithoutQuotes)) {
- return false;
- }
- final MacAddress bssid = MacAddress.fromString(this.mWifiConfiguration.BSSID);
- final MacAddress matchBaseAddress = ns.bssidPatternMatcher.first;
- final MacAddress matchMask = ns.bssidPatternMatcher.second;
- if (!bssid.matches(matchBaseAddress, matchMask)) {
- return false;
- }
- if (!ns.wifiConfiguration.allowedKeyManagement.equals(
- this.mWifiConfiguration.allowedKeyManagement)) {
- return false;
- }
- return true;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(
- mWifiConfiguration.SSID,
- mWifiConfiguration.BSSID,
- mWifiConfiguration.allowedKeyManagement);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof WifiNetworkAgentSpecifier)) {
- return false;
- }
- WifiNetworkAgentSpecifier lhs = (WifiNetworkAgentSpecifier) obj;
- return Objects.equals(this.mWifiConfiguration.SSID, lhs.mWifiConfiguration.SSID)
- && Objects.equals(this.mWifiConfiguration.BSSID, lhs.mWifiConfiguration.BSSID)
- && Objects.equals(this.mWifiConfiguration.allowedKeyManagement,
- lhs.mWifiConfiguration.allowedKeyManagement);
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("WifiNetworkAgentSpecifier [");
- sb.append("WifiConfiguration=")
- .append(", SSID=").append(mWifiConfiguration.SSID)
- .append(", BSSID=").append(mWifiConfiguration.BSSID)
- .append("]");
- return sb.toString();
- }
-
- @Override
- public NetworkSpecifier redact() {
- return null;
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiNetworkConnectionStatistics.java b/wifi/java/android/net/wifi/WifiNetworkConnectionStatistics.java
deleted file mode 100644
index 95b2e77c5c1e..000000000000
--- a/wifi/java/android/net/wifi/WifiNetworkConnectionStatistics.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2014 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.annotation.NonNull;
-import android.annotation.SystemApi;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * Connection Statistics For a WiFi Network.
- * @hide
- */
-@SystemApi
-public class WifiNetworkConnectionStatistics implements Parcelable {
- private static final String TAG = "WifiNetworkConnnectionStatistics";
-
- public int numConnection;
- public int numUsage;
-
- public WifiNetworkConnectionStatistics(int connection, int usage) {
- numConnection = connection;
- numUsage = usage;
- }
-
- public WifiNetworkConnectionStatistics() { }
-
- @NonNull
- @Override
- public String toString() {
- StringBuilder sbuf = new StringBuilder();
- sbuf.append("c=").append(numConnection);
- sbuf.append(" u=").append(numUsage);
- return sbuf.toString();
- }
-
-
- /** copy constructor*/
- public WifiNetworkConnectionStatistics(WifiNetworkConnectionStatistics source) {
- numConnection = source.numConnection;
- numUsage = source.numUsage;
- }
-
- /** Implement the Parcelable interface */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface */
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(numConnection);
- dest.writeInt(numUsage);
- }
-
- /** Implement the Parcelable interface */
- public static final @android.annotation.NonNull Creator<WifiNetworkConnectionStatistics> CREATOR =
- new Creator<WifiNetworkConnectionStatistics>() {
- public WifiNetworkConnectionStatistics createFromParcel(Parcel in) {
- int numConnection = in.readInt();
- int numUsage = in.readInt();
- WifiNetworkConnectionStatistics stats =
- new WifiNetworkConnectionStatistics(numConnection, numUsage);
- return stats;
- }
-
- public WifiNetworkConnectionStatistics[] newArray(int size) {
- return new WifiNetworkConnectionStatistics[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/WifiNetworkScoreCache.java b/wifi/java/android/net/wifi/WifiNetworkScoreCache.java
deleted file mode 100755
index 378549d62edf..000000000000
--- a/wifi/java/android/net/wifi/WifiNetworkScoreCache.java
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
- * Copyright (C) 2014 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.Manifest.permission;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.content.Context;
-import android.net.INetworkScoreCache;
-import android.net.NetworkKey;
-import android.net.ScoredNetwork;
-import android.os.Handler;
-import android.os.Process;
-import android.util.Log;
-import android.util.LruCache;
-
-import com.android.internal.annotations.GuardedBy;
-
-import java.io.FileDescriptor;
-import java.io.PrintWriter;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * {@link INetworkScoreCache} implementation for Wifi Networks.
- *
- * TODO: This should not be part of wifi mainline module.
- * @hide
- */
-public class WifiNetworkScoreCache extends INetworkScoreCache.Stub {
- private static final String TAG = "WifiNetworkScoreCache";
- private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
-
- // A Network scorer returns a score in the range [-128, +127]
- // We treat the lowest possible score as though there were no score, effectively allowing the
- // scorer to provide an RSSI threshold below which a network should not be used.
- public static final int INVALID_NETWORK_SCORE = Byte.MIN_VALUE;
-
- /** Default number entries to be stored in the {@link LruCache}. */
- private static final int DEFAULT_MAX_CACHE_SIZE = 100;
-
- // See {@link #CacheListener}.
- @Nullable
- @GuardedBy("mLock")
- private CacheListener mListener;
-
- private final Context mContext;
- private final Object mLock = new Object();
-
- // The key is of the form "<ssid>"<bssid>
- // TODO: What about SSIDs that can't be encoded as UTF-8?
- @GuardedBy("mLock")
- private final LruCache<String, ScoredNetwork> mCache;
-
- public WifiNetworkScoreCache(Context context) {
- this(context, null /* listener */);
- }
-
- /**
- * Instantiates a WifiNetworkScoreCache.
- *
- * @param context Application context
- * @param listener CacheListener for cache updates
- */
- public WifiNetworkScoreCache(Context context, @Nullable CacheListener listener) {
- this(context, listener, DEFAULT_MAX_CACHE_SIZE);
- }
-
- public WifiNetworkScoreCache(
- Context context, @Nullable CacheListener listener, int maxCacheSize) {
- mContext = context.getApplicationContext();
- mListener = listener;
- mCache = new LruCache<>(maxCacheSize);
- }
-
- @Override public final void updateScores(List<ScoredNetwork> networks) {
- if (networks == null || networks.isEmpty()) {
- return;
- }
- if (DBG) {
- Log.d(TAG, "updateScores list size=" + networks.size());
- }
-
- boolean changed = false;
-
- synchronized(mLock) {
- for (ScoredNetwork network : networks) {
- String networkKey = buildNetworkKey(network);
- if (networkKey == null) {
- if (DBG) {
- Log.d(TAG, "Failed to build network key for ScoredNetwork" + network);
- }
- continue;
- }
- mCache.put(networkKey, network);
- changed = true;
- }
-
- if (mListener != null && changed) {
- mListener.post(networks);
- }
- }
- }
-
- @Override public final void clearScores() {
- synchronized (mLock) {
- mCache.evictAll();
- }
- }
-
- /**
- * Returns whether there is any score info for the given ScanResult.
- *
- * This includes null-score info, so it should only be used when determining whether to request
- * scores from the network scorer.
- */
- public boolean isScoredNetwork(ScanResult result) {
- return getScoredNetwork(result) != null;
- }
-
- /**
- * Returns whether there is a non-null score curve for the given ScanResult.
- *
- * A null score curve has special meaning - we should never connect to an ephemeral network if
- * the score curve is null.
- */
- public boolean hasScoreCurve(ScanResult result) {
- ScoredNetwork network = getScoredNetwork(result);
- return network != null && network.rssiCurve != null;
- }
-
- public int getNetworkScore(ScanResult result) {
- int score = INVALID_NETWORK_SCORE;
-
- ScoredNetwork network = getScoredNetwork(result);
- if (network != null && network.rssiCurve != null) {
- score = network.rssiCurve.lookupScore(result.level);
- if (DBG) {
- Log.d(TAG, "getNetworkScore found scored network " + network.networkKey
- + " score " + Integer.toString(score)
- + " RSSI " + result.level);
- }
- }
- return score;
- }
-
- /**
- * Returns the ScoredNetwork metered hint for a given ScanResult.
- *
- * If there is no ScoredNetwork associated with the ScanResult then false will be returned.
- */
- public boolean getMeteredHint(ScanResult result) {
- ScoredNetwork network = getScoredNetwork(result);
- return network != null && network.meteredHint;
- }
-
- public int getNetworkScore(ScanResult result, boolean isActiveNetwork) {
- int score = INVALID_NETWORK_SCORE;
-
- ScoredNetwork network = getScoredNetwork(result);
- if (network != null && network.rssiCurve != null) {
- score = network.rssiCurve.lookupScore(result.level, isActiveNetwork);
- if (DBG) {
- Log.d(TAG, "getNetworkScore found scored network " + network.networkKey
- + " score " + Integer.toString(score)
- + " RSSI " + result.level
- + " isActiveNetwork " + isActiveNetwork);
- }
- }
- return score;
- }
-
- @Nullable
- public ScoredNetwork getScoredNetwork(ScanResult result) {
- String key = buildNetworkKey(result);
- if (key == null) return null;
-
- synchronized(mLock) {
- ScoredNetwork network = mCache.get(key);
- return network;
- }
- }
-
- /** Returns the ScoredNetwork for the given key. */
- @Nullable
- public ScoredNetwork getScoredNetwork(NetworkKey networkKey) {
- String key = buildNetworkKey(networkKey);
- if (key == null) {
- if (DBG) {
- Log.d(TAG, "Could not build key string for Network Key: " + networkKey);
- }
- return null;
- }
- synchronized (mLock) {
- return mCache.get(key);
- }
- }
-
- private String buildNetworkKey(ScoredNetwork network) {
- if (network == null) {
- return null;
- }
- return buildNetworkKey(network.networkKey);
- }
-
- private String buildNetworkKey(NetworkKey networkKey) {
- if (networkKey == null) {
- return null;
- }
- if (networkKey.wifiKey == null) return null;
- if (networkKey.type == NetworkKey.TYPE_WIFI) {
- String key = networkKey.wifiKey.ssid;
- if (key == null) return null;
- if (networkKey.wifiKey.bssid != null) {
- key = key + networkKey.wifiKey.bssid;
- }
- return key;
- }
- return null;
- }
-
- private String buildNetworkKey(ScanResult result) {
- if (result == null || result.SSID == null) {
- return null;
- }
- StringBuilder key = new StringBuilder("\"");
- key.append(result.SSID);
- key.append("\"");
- if (result.BSSID != null) {
- key.append(result.BSSID);
- }
- return key.toString();
- }
-
- @Override protected final void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
- mContext.enforceCallingOrSelfPermission(permission.DUMP, TAG);
- String header = String.format("WifiNetworkScoreCache (%s/%d)",
- mContext.getPackageName(), Process.myUid());
- writer.println(header);
- writer.println(" All score curves:");
- synchronized (mLock) {
- for (ScoredNetwork score : mCache.snapshot().values()) {
- writer.println(" " + score);
- }
- writer.println(" Network scores for latest ScanResults:");
- WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
- for (ScanResult scanResult : wifiManager.getScanResults()) {
- writer.println(
- " " + buildNetworkKey(scanResult) + ": " + getNetworkScore(scanResult));
- }
- }
- }
-
- /** Registers a CacheListener instance, replacing the previous listener if it existed. */
- public void registerListener(CacheListener listener) {
- synchronized (mLock) {
- mListener = listener;
- }
- }
-
- /** Removes the registered CacheListener. */
- public void unregisterListener() {
- synchronized (mLock) {
- mListener = null;
- }
- }
-
- /** Listener for updates to the cache inside WifiNetworkScoreCache. */
- public abstract static class CacheListener {
- private Handler mHandler;
-
- /**
- * Constructor for CacheListener.
- *
- * @param handler the Handler on which to invoke the {@link #networkCacheUpdated} method.
- * This cannot be null.
- */
- public CacheListener(@NonNull Handler handler) {
- Objects.requireNonNull(handler);
- mHandler = handler;
- }
-
- /** Invokes the {@link #networkCacheUpdated(List<ScoredNetwork>)} method on the handler. */
- void post(List<ScoredNetwork> updatedNetworks) {
- mHandler.post(new Runnable() {
- @Override
- public void run() {
- networkCacheUpdated(updatedNetworks);
- }
- });
- }
-
- /**
- * Invoked whenever the cache is updated.
- *
- * <p>Clearing the cache does not invoke this method.
- *
- * @param updatedNetworks the networks that were updated
- */
- public abstract void networkCacheUpdated(List<ScoredNetwork> updatedNetworks);
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiNetworkSpecifier.java b/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
deleted file mode 100644
index be3b45d8c82a..000000000000
--- a/wifi/java/android/net/wifi/WifiNetworkSpecifier.java
+++ /dev/null
@@ -1,655 +0,0 @@
-/*
- * Copyright (C) 2018 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 static com.android.internal.util.Preconditions.checkNotNull;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.net.MacAddress;
-import android.net.NetworkRequest;
-import android.net.NetworkSpecifier;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.os.PatternMatcher;
-import android.text.TextUtils;
-import android.util.Pair;
-
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.StandardCharsets;
-import java.util.Objects;
-
-/**
- * Network specifier object used to request a local Wi-Fi network. Apps should use the
- * {@link WifiNetworkSpecifier.Builder} class to create an instance.
- */
-public final class WifiNetworkSpecifier extends NetworkSpecifier implements Parcelable {
- private static final String TAG = "WifiNetworkSpecifier";
-
- /**
- * Builder used to create {@link WifiNetworkSpecifier} objects.
- */
- public static final class Builder {
- private static final String MATCH_ALL_SSID_PATTERN_PATH = ".*";
- private static final String MATCH_EMPTY_SSID_PATTERN_PATH = "";
- private static final Pair<MacAddress, MacAddress> MATCH_NO_BSSID_PATTERN1 =
- new Pair<>(MacAddress.BROADCAST_ADDRESS, MacAddress.BROADCAST_ADDRESS);
- private static final Pair<MacAddress, MacAddress> MATCH_NO_BSSID_PATTERN2 =
- new Pair<>(WifiManager.ALL_ZEROS_MAC_ADDRESS, MacAddress.BROADCAST_ADDRESS);
- private static final Pair<MacAddress, MacAddress> MATCH_ALL_BSSID_PATTERN =
- new Pair<>(WifiManager.ALL_ZEROS_MAC_ADDRESS, WifiManager.ALL_ZEROS_MAC_ADDRESS);
- private static final MacAddress MATCH_EXACT_BSSID_PATTERN_MASK =
- MacAddress.BROADCAST_ADDRESS;
-
- /**
- * Set WPA Enterprise type according to certificate security level.
- * This is for backward compatibility in R.
- */
- private static final int WPA3_ENTERPRISE_AUTO = 0;
- /** Set WPA Enterprise type to standard mode only. */
- private static final int WPA3_ENTERPRISE_STANDARD = 1;
- /** Set WPA Enterprise type to 192 bit mode only. */
- private static final int WPA3_ENTERPRISE_192_BIT = 2;
-
- /**
- * SSID pattern match specified by the app.
- */
- private @Nullable PatternMatcher mSsidPatternMatcher;
- /**
- * BSSID pattern match specified by the app.
- * Pair of <BaseAddress, Mask>.
- */
- private @Nullable Pair<MacAddress, MacAddress> mBssidPatternMatcher;
- /**
- * Whether this is an OWE network or not.
- */
- private boolean mIsEnhancedOpen;
- /**
- * Pre-shared key for use with WPA-PSK networks.
- */
- private @Nullable String mWpa2PskPassphrase;
- /**
- * Pre-shared key for use with WPA3-SAE networks.
- */
- private @Nullable String mWpa3SaePassphrase;
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the WPA/WPA2-Enterprise networks.
- */
- private @Nullable WifiEnterpriseConfig mWpa2EnterpriseConfig;
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the WPA3-Enterprise networks.
- */
- private @Nullable WifiEnterpriseConfig mWpa3EnterpriseConfig;
- /**
- * Indicate what type this WPA3-Enterprise network is.
- */
- private int mWpa3EnterpriseType = WPA3_ENTERPRISE_AUTO;
- /**
- * This is a network that does not broadcast its SSID, so an
- * SSID-specific probe request must be used for scans.
- */
- private boolean mIsHiddenSSID;
-
- public Builder() {
- mSsidPatternMatcher = null;
- mBssidPatternMatcher = null;
- mIsEnhancedOpen = false;
- mWpa2PskPassphrase = null;
- mWpa3SaePassphrase = null;
- mWpa2EnterpriseConfig = null;
- mWpa3EnterpriseConfig = null;
- mIsHiddenSSID = false;
- }
-
- /**
- * Set the unicode SSID match pattern to use for filtering networks from scan results.
- * <p>
- * <li>Overrides any previous value set using {@link #setSsid(String)} or
- * {@link #setSsidPattern(PatternMatcher)}.</li>
- *
- * @param ssidPattern Instance of {@link PatternMatcher} containing the UTF-8 encoded
- * string pattern to use for matching the network's SSID.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setSsidPattern(@NonNull PatternMatcher ssidPattern) {
- checkNotNull(ssidPattern);
- mSsidPatternMatcher = ssidPattern;
- return this;
- }
-
- /**
- * Set the unicode SSID for the network.
- * <p>
- * <li>Sets the SSID to use for filtering networks from scan results. Will only match
- * networks whose SSID is identical to the UTF-8 encoding of the specified value.</li>
- * <li>Overrides any previous value set using {@link #setSsid(String)} or
- * {@link #setSsidPattern(PatternMatcher)}.</li>
- *
- * @param ssid The SSID of the network. It must be valid Unicode.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the SSID is not valid unicode.
- */
- public @NonNull Builder setSsid(@NonNull String ssid) {
- checkNotNull(ssid);
- final CharsetEncoder unicodeEncoder = StandardCharsets.UTF_8.newEncoder();
- if (!unicodeEncoder.canEncode(ssid)) {
- throw new IllegalArgumentException("SSID is not a valid unicode string");
- }
- mSsidPatternMatcher = new PatternMatcher(ssid, PatternMatcher.PATTERN_LITERAL);
- return this;
- }
-
- /**
- * Set the BSSID match pattern to use for filtering networks from scan results.
- * Will match all networks with BSSID which satisfies the following:
- * {@code BSSID & mask == baseAddress}.
- * <p>
- * <li>Overrides any previous value set using {@link #setBssid(MacAddress)} or
- * {@link #setBssidPattern(MacAddress, MacAddress)}.</li>
- *
- * @param baseAddress Base address for BSSID pattern.
- * @param mask Mask for BSSID pattern.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setBssidPattern(
- @NonNull MacAddress baseAddress, @NonNull MacAddress mask) {
- checkNotNull(baseAddress);
- checkNotNull(mask);
- mBssidPatternMatcher = Pair.create(baseAddress, mask);
- return this;
- }
-
- /**
- * Set the BSSID to use for filtering networks from scan results. Will only match network
- * whose BSSID is identical to the specified value.
- * <p>
- * <li>Sets the BSSID to use for filtering networks from scan results. Will only match
- * networks whose BSSID is identical to specified value.</li>
- * <li>Overrides any previous value set using {@link #setBssid(MacAddress)} or
- * {@link #setBssidPattern(MacAddress, MacAddress)}.</li>
- *
- * @param bssid BSSID of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setBssid(@NonNull MacAddress bssid) {
- checkNotNull(bssid);
- mBssidPatternMatcher = Pair.create(bssid, MATCH_EXACT_BSSID_PATTERN_MASK);
- return this;
- }
-
- /**
- * Specifies whether this represents an Enhanced Open (OWE) network.
- *
- * @param isEnhancedOpen {@code true} to indicate that the network uses enhanced open,
- * {@code false} otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsEnhancedOpen(boolean isEnhancedOpen) {
- mIsEnhancedOpen = isEnhancedOpen;
- return this;
- }
-
- /**
- * Set the ASCII WPA2 passphrase for this network. Needed for authenticating to
- * WPA2-PSK networks.
- *
- * @param passphrase passphrase of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
- */
- public @NonNull Builder setWpa2Passphrase(@NonNull String passphrase) {
- checkNotNull(passphrase);
- final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
- if (!asciiEncoder.canEncode(passphrase)) {
- throw new IllegalArgumentException("passphrase not ASCII encodable");
- }
- mWpa2PskPassphrase = passphrase;
- return this;
- }
-
- /**
- * Set the ASCII WPA3 passphrase for this network. Needed for authenticating to WPA3-SAE
- * networks.
- *
- * @param passphrase passphrase of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
- */
- public @NonNull Builder setWpa3Passphrase(@NonNull String passphrase) {
- checkNotNull(passphrase);
- final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
- if (!asciiEncoder.canEncode(passphrase)) {
- throw new IllegalArgumentException("passphrase not ASCII encodable");
- }
- mWpa3SaePassphrase = passphrase;
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA2-EAP networks. See {@link WifiEnterpriseConfig} for description.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setWpa2EnterpriseConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- mWpa2EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA3-Enterprise networks (standard and 192-bit security). See
- * {@link WifiEnterpriseConfig} for description. For 192-bit security networks, both the
- * client and CA certificates must be provided, and must be of type of either
- * sha384WithRSAEncryption (OID 1.2.840.113549.1.1.12) or ecdsa-with-SHA384
- * (OID 1.2.840.10045.4.3.3).
- *
- * @deprecated use {@link #setWpa3EnterpriseStandardModeConfig(WifiEnterpriseConfig)} or
- * {@link #setWpa3Enterprise192BitModeConfig(WifiEnterpriseConfig)} to specify
- * WPA3-Enterprise type explicitly.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- @Deprecated
- public @NonNull Builder setWpa3EnterpriseConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to standard WPA3-Enterprise networks. See {@link WifiEnterpriseConfig} for description.
- * For WPA3-Enterprise in 192-bit security mode networks,
- * see {@link #setWpa3Enterprise192BitModeConfig(WifiEnterpriseConfig)} for description.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setWpa3EnterpriseStandardModeConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- mWpa3EnterpriseType = WPA3_ENTERPRISE_STANDARD;
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA3-Enterprise in 192-bit security mode networks. See {@link WifiEnterpriseConfig}
- * for description. Both the client and CA certificates must be provided,
- * and must be of type of either sha384WithRSAEncryption with key length of 3072bit or
- * more (OID 1.2.840.113549.1.1.12), or ecdsa-with-SHA384 with key length of 384bit or
- * more (OID 1.2.840.10045.4.3.3).
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the EAP type or certificates do not
- * meet 192-bit mode requirements.
- */
- public @NonNull Builder setWpa3Enterprise192BitModeConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- if (enterpriseConfig.getEapMethod() != WifiEnterpriseConfig.Eap.TLS) {
- throw new IllegalArgumentException("The 192-bit mode network type must be TLS");
- }
- if (!WifiEnterpriseConfig.isSuiteBCipherCert(
- enterpriseConfig.getClientCertificate())) {
- throw new IllegalArgumentException(
- "The client certificate does not meet 192-bit mode requirements.");
- }
- if (!WifiEnterpriseConfig.isSuiteBCipherCert(
- enterpriseConfig.getCaCertificate())) {
- throw new IllegalArgumentException(
- "The CA certificate does not meet 192-bit mode requirements.");
- }
-
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- mWpa3EnterpriseType = WPA3_ENTERPRISE_192_BIT;
- return this;
- }
-
- /**
- * Specifies whether this represents a hidden network.
- * <p>
- * <li>Setting this disallows the usage of {@link #setSsidPattern(PatternMatcher)} since
- * hidden networks need to be explicitly probed for.</li>
- * <li>If not set, defaults to false (i.e not a hidden network).</li>
- *
- * @param isHiddenSsid {@code true} to indicate that the network is hidden, {@code false}
- * otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsHiddenSsid(boolean isHiddenSsid) {
- mIsHiddenSSID = isHiddenSsid;
- return this;
- }
-
- private void setSecurityParamsInWifiConfiguration(
- @NonNull WifiConfiguration configuration) {
- if (!TextUtils.isEmpty(mWpa2PskPassphrase)) { // WPA-PSK network.
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_PSK);
- // WifiConfiguration.preSharedKey needs quotes around ASCII password.
- configuration.preSharedKey = "\"" + mWpa2PskPassphrase + "\"";
- } else if (!TextUtils.isEmpty(mWpa3SaePassphrase)) { // WPA3-SAE network.
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_SAE);
- // WifiConfiguration.preSharedKey needs quotes around ASCII password.
- configuration.preSharedKey = "\"" + mWpa3SaePassphrase + "\"";
- } else if (mWpa2EnterpriseConfig != null) { // WPA-EAP network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP);
- configuration.enterpriseConfig = mWpa2EnterpriseConfig;
- } else if (mWpa3EnterpriseConfig != null) { // WPA3-Enterprise
- if (mWpa3EnterpriseType == WPA3_ENTERPRISE_AUTO
- && mWpa3EnterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TLS
- && WifiEnterpriseConfig.isSuiteBCipherCert(
- mWpa3EnterpriseConfig.getClientCertificate())
- && WifiEnterpriseConfig.isSuiteBCipherCert(
- mWpa3EnterpriseConfig.getCaCertificate())) {
- // WPA3-Enterprise in 192-bit security mode
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT);
- } else if (mWpa3EnterpriseType == WPA3_ENTERPRISE_192_BIT) {
- // WPA3-Enterprise in 192-bit security mode
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT);
- } else {
- // WPA3-Enterprise
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE);
- }
- configuration.enterpriseConfig = mWpa3EnterpriseConfig;
- } else if (mIsEnhancedOpen) { // OWE network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OWE);
- } else { // Open network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OPEN);
- }
- }
-
- /**
- * Helper method to build WifiConfiguration object from the builder.
- * @return Instance of {@link WifiConfiguration}.
- */
- private WifiConfiguration buildWifiConfiguration() {
- final WifiConfiguration wifiConfiguration = new WifiConfiguration();
- // WifiConfiguration.SSID needs quotes around unicode SSID.
- if (mSsidPatternMatcher.getType() == PatternMatcher.PATTERN_LITERAL) {
- wifiConfiguration.SSID = "\"" + mSsidPatternMatcher.getPath() + "\"";
- }
- if (mBssidPatternMatcher.second == MATCH_EXACT_BSSID_PATTERN_MASK) {
- wifiConfiguration.BSSID = mBssidPatternMatcher.first.toString();
- }
- setSecurityParamsInWifiConfiguration(wifiConfiguration);
- wifiConfiguration.hiddenSSID = mIsHiddenSSID;
- return wifiConfiguration;
- }
-
- private boolean hasSetAnyPattern() {
- return mSsidPatternMatcher != null || mBssidPatternMatcher != null;
- }
-
- private void setMatchAnyPatternIfUnset() {
- if (mSsidPatternMatcher == null) {
- mSsidPatternMatcher = new PatternMatcher(MATCH_ALL_SSID_PATTERN_PATH,
- PatternMatcher.PATTERN_SIMPLE_GLOB);
- }
- if (mBssidPatternMatcher == null) {
- mBssidPatternMatcher = MATCH_ALL_BSSID_PATTERN;
- }
- }
-
- private boolean hasSetMatchNonePattern() {
- if (mSsidPatternMatcher.getType() != PatternMatcher.PATTERN_PREFIX
- && mSsidPatternMatcher.getPath().equals(MATCH_EMPTY_SSID_PATTERN_PATH)) {
- return true;
- }
- if (mBssidPatternMatcher.equals(MATCH_NO_BSSID_PATTERN1)) {
- return true;
- }
- if (mBssidPatternMatcher.equals(MATCH_NO_BSSID_PATTERN2)) {
- return true;
- }
- return false;
- }
-
- private boolean hasSetMatchAllPattern() {
- if ((mSsidPatternMatcher.match(MATCH_EMPTY_SSID_PATTERN_PATH))
- && mBssidPatternMatcher.equals(MATCH_ALL_BSSID_PATTERN)) {
- return true;
- }
- return false;
- }
-
- private void validateSecurityParams() {
- int numSecurityTypes = 0;
- numSecurityTypes += mIsEnhancedOpen ? 1 : 0;
- numSecurityTypes += !TextUtils.isEmpty(mWpa2PskPassphrase) ? 1 : 0;
- numSecurityTypes += !TextUtils.isEmpty(mWpa3SaePassphrase) ? 1 : 0;
- numSecurityTypes += mWpa2EnterpriseConfig != null ? 1 : 0;
- numSecurityTypes += mWpa3EnterpriseConfig != null ? 1 : 0;
- if (numSecurityTypes > 1) {
- throw new IllegalStateException("only one of setIsEnhancedOpen, setWpa2Passphrase,"
- + "setWpa3Passphrase, setWpa2EnterpriseConfig or setWpa3EnterpriseConfig"
- + " can be invoked for network specifier");
- }
- }
-
- /**
- * Create a specifier object used to request a local Wi-Fi network. The generated
- * {@link NetworkSpecifier} should be used in
- * {@link NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} when building
- * the {@link NetworkRequest}. These specifiers can only be used to request a local wifi
- * network (i.e no internet capability). So, the device will not switch it's default route
- * to wifi if there are other transports (cellular for example) available.
- *<p>
- * Note: Apps can set a combination of network match params:
- * <li> SSID Pattern using {@link #setSsidPattern(PatternMatcher)} OR Specific SSID using
- * {@link #setSsid(String)}. </li>
- * AND/OR
- * <li> BSSID Pattern using {@link #setBssidPattern(MacAddress, MacAddress)} OR Specific
- * BSSID using {@link #setBssid(MacAddress)} </li>
- * to trigger connection to a network that matches the set params.
- * The system will find the set of networks matching the request and present the user
- * with a system dialog which will allow the user to select a specific Wi-Fi network to
- * connect to or to deny the request.
- *</p>
- *
- * For example:
- * To connect to an open network with a SSID prefix of "test" and a BSSID OUI of "10:03:23":
- *
- * <pre>{@code
- * final NetworkSpecifier specifier =
- * new Builder()
- * .setSsidPattern(new PatternMatcher("test", PatterMatcher.PATTERN_PREFIX))
- * .setBssidPattern(MacAddress.fromString("10:03:23:00:00:00"),
- * MacAddress.fromString("ff:ff:ff:00:00:00"))
- * .build()
- * final NetworkRequest request =
- * new NetworkRequest.Builder()
- * .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
- * .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
- * .setNetworkSpecifier(specifier)
- * .build();
- * final ConnectivityManager connectivityManager =
- * context.getSystemService(Context.CONNECTIVITY_SERVICE);
- * final NetworkCallback networkCallback = new NetworkCallback() {
- * ...
- * {@literal @}Override
- * void onAvailable(...) {}
- * // etc.
- * };
- * connectivityManager.requestNetwork(request, networkCallback);
- * }</pre>
- *
- * @return Instance of {@link NetworkSpecifier}.
- * @throws IllegalStateException on invalid params set.
- */
- public @NonNull WifiNetworkSpecifier build() {
- if (!hasSetAnyPattern()) {
- throw new IllegalStateException("one of setSsidPattern/setSsid/setBssidPattern/"
- + "setBssid should be invoked for specifier");
- }
- setMatchAnyPatternIfUnset();
- if (hasSetMatchNonePattern()) {
- throw new IllegalStateException("cannot set match-none pattern for specifier");
- }
- if (hasSetMatchAllPattern()) {
- throw new IllegalStateException("cannot set match-all pattern for specifier");
- }
- if (mIsHiddenSSID && mSsidPatternMatcher.getType() != PatternMatcher.PATTERN_LITERAL) {
- throw new IllegalStateException("setSsid should also be invoked when "
- + "setIsHiddenSsid is invoked for network specifier");
- }
- validateSecurityParams();
-
- return new WifiNetworkSpecifier(
- mSsidPatternMatcher,
- mBssidPatternMatcher,
- buildWifiConfiguration());
- }
- }
-
- /**
- * SSID pattern match specified by the app.
- * @hide
- */
- public final PatternMatcher ssidPatternMatcher;
-
- /**
- * BSSID pattern match specified by the app.
- * Pair of <BaseAddress, Mask>.
- * @hide
- */
- public final Pair<MacAddress, MacAddress> bssidPatternMatcher;
-
- /**
- * Security credentials for the network.
- * <p>
- * Note: {@link WifiConfiguration#SSID} & {@link WifiConfiguration#BSSID} fields from
- * WifiConfiguration are not used. Instead we use the {@link #ssidPatternMatcher} &
- * {@link #bssidPatternMatcher} fields embedded directly
- * within {@link WifiNetworkSpecifier}.
- * @hide
- */
- public final WifiConfiguration wifiConfiguration;
-
- /** @hide */
- public WifiNetworkSpecifier() throws IllegalAccessException {
- throw new IllegalAccessException("Use the builder to create an instance");
- }
-
- /** @hide */
- public WifiNetworkSpecifier(@NonNull PatternMatcher ssidPatternMatcher,
- @NonNull Pair<MacAddress, MacAddress> bssidPatternMatcher,
- @NonNull WifiConfiguration wifiConfiguration) {
- checkNotNull(ssidPatternMatcher);
- checkNotNull(bssidPatternMatcher);
- checkNotNull(wifiConfiguration);
-
- this.ssidPatternMatcher = ssidPatternMatcher;
- this.bssidPatternMatcher = bssidPatternMatcher;
- this.wifiConfiguration = wifiConfiguration;
- }
-
- public static final @NonNull Creator<WifiNetworkSpecifier> CREATOR =
- new Creator<WifiNetworkSpecifier>() {
- @Override
- public WifiNetworkSpecifier createFromParcel(Parcel in) {
- PatternMatcher ssidPatternMatcher = in.readParcelable(/* classLoader */null);
- MacAddress baseAddress = in.readParcelable(null);
- MacAddress mask = in.readParcelable(null);
- Pair<MacAddress, MacAddress> bssidPatternMatcher =
- Pair.create(baseAddress, mask);
- WifiConfiguration wifiConfiguration = in.readParcelable(null);
- return new WifiNetworkSpecifier(ssidPatternMatcher, bssidPatternMatcher,
- wifiConfiguration);
- }
-
- @Override
- public WifiNetworkSpecifier[] newArray(int size) {
- return new WifiNetworkSpecifier[size];
- }
- };
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeParcelable(ssidPatternMatcher, flags);
- dest.writeParcelable(bssidPatternMatcher.first, flags);
- dest.writeParcelable(bssidPatternMatcher.second, flags);
- dest.writeParcelable(wifiConfiguration, flags);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(
- ssidPatternMatcher.getPath(), ssidPatternMatcher.getType(), bssidPatternMatcher,
- wifiConfiguration.allowedKeyManagement);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof WifiNetworkSpecifier)) {
- return false;
- }
- WifiNetworkSpecifier lhs = (WifiNetworkSpecifier) obj;
- return Objects.equals(this.ssidPatternMatcher.getPath(),
- lhs.ssidPatternMatcher.getPath())
- && Objects.equals(this.ssidPatternMatcher.getType(),
- lhs.ssidPatternMatcher.getType())
- && Objects.equals(this.bssidPatternMatcher,
- lhs.bssidPatternMatcher)
- && Objects.equals(this.wifiConfiguration.allowedKeyManagement,
- lhs.wifiConfiguration.allowedKeyManagement);
- }
-
- @Override
- public String toString() {
- return new StringBuilder()
- .append("WifiNetworkSpecifier [")
- .append(", SSID Match pattern=").append(ssidPatternMatcher)
- .append(", BSSID Match pattern=").append(bssidPatternMatcher)
- .append(", SSID=").append(wifiConfiguration.SSID)
- .append(", BSSID=").append(wifiConfiguration.BSSID)
- .append("]")
- .toString();
- }
-
- /** @hide */
- @Override
- public boolean canBeSatisfiedBy(NetworkSpecifier other) {
- if (other instanceof WifiNetworkAgentSpecifier) {
- return ((WifiNetworkAgentSpecifier) other).satisfiesNetworkSpecifier(this);
- }
- // Specific requests are checked for equality although testing for equality of 2 patterns do
- // not make much sense!
- return equals(other);
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java b/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
deleted file mode 100644
index b7450c538ff8..000000000000
--- a/wifi/java/android/net/wifi/WifiNetworkSuggestion.java
+++ /dev/null
@@ -1,1406 +0,0 @@
-/*
- * Copyright (C) 2018 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 static com.android.internal.util.Preconditions.checkNotNull;
-
-import android.annotation.IntRange;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.net.NetworkCapabilities;
-import android.net.NetworkRequest;
-import android.net.wifi.hotspot2.PasspointConfiguration;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.telephony.SubscriptionInfo;
-import android.telephony.SubscriptionManager;
-import android.telephony.TelephonyManager;
-import android.text.TextUtils;
-
-import com.android.modules.utils.build.SdkLevel;
-
-import java.nio.charset.CharsetEncoder;
-import java.nio.charset.StandardCharsets;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * The Network Suggestion object is used to provide a Wi-Fi network for consideration when
- * auto-connecting to networks. Apps cannot directly create this object, they must use
- * {@link WifiNetworkSuggestion.Builder#build()} to obtain an instance of this object.
- *<p>
- * Apps can provide a list of such networks to the platform using
- * {@link WifiManager#addNetworkSuggestions(List)}.
- */
-public final class WifiNetworkSuggestion implements Parcelable {
- /**
- * Builder used to create {@link WifiNetworkSuggestion} objects.
- */
- public static final class Builder {
- private static final int UNASSIGNED_PRIORITY = -1;
-
- /**
- * Set WPA Enterprise type according to certificate security level.
- * This is for backward compatibility in R.
- */
- private static final int WPA3_ENTERPRISE_AUTO = 0;
- /** Set WPA Enterprise type to standard mode only. */
- private static final int WPA3_ENTERPRISE_STANDARD = 1;
- /** Set WPA Enterprise type to 192 bit mode only. */
- private static final int WPA3_ENTERPRISE_192_BIT = 2;
-
- /**
- * SSID of the network.
- */
- private String mSsid;
- /**
- * Optional BSSID within the network.
- */
- private MacAddress mBssid;
- /**
- * Whether this is an OWE network or not.
- */
- private boolean mIsEnhancedOpen;
- /**
- * Pre-shared key for use with WPA-PSK networks.
- */
- private @Nullable String mWpa2PskPassphrase;
- /**
- * Pre-shared key for use with WPA3-SAE networks.
- */
- private @Nullable String mWpa3SaePassphrase;
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the WPA/WPA2-Enterprise networks.
- */
- private @Nullable WifiEnterpriseConfig mWpa2EnterpriseConfig;
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the WPA3-Enterprise networks.
- */
- private @Nullable WifiEnterpriseConfig mWpa3EnterpriseConfig;
- /**
- * Indicate what type this WPA3-Enterprise network is.
- */
- private int mWpa3EnterpriseType = WPA3_ENTERPRISE_AUTO;
- /**
- * The passpoint config for use with Hotspot 2.0 network
- */
- private @Nullable PasspointConfiguration mPasspointConfiguration;
- /**
- * This is a network that does not broadcast its SSID, so an
- * SSID-specific probe request must be used for scans.
- */
- private boolean mIsHiddenSSID;
- /**
- * Whether app needs to log in to captive portal to obtain Internet access.
- */
- private boolean mIsAppInteractionRequired;
- /**
- * Whether user needs to log in to captive portal to obtain Internet access.
- */
- private boolean mIsUserInteractionRequired;
- /**
- * Whether this network is metered or not.
- */
- private int mMeteredOverride;
- /**
- * Priority of this network among other network suggestions from same priority group
- * provided by the app.
- * The lower the number, the higher the priority (i.e value of 0 = highest priority).
- */
- private int mPriority;
- /**
- * Priority group ID, while suggestion priority will only effect inside the priority group.
- */
- private int mPriorityGroup;
-
- /**
- * The carrier ID identifies the operator who provides this network configuration.
- * see {@link TelephonyManager#getSimCarrierId()}
- */
- private int mCarrierId;
-
- /**
- * The Subscription ID identifies the SIM card for which this network configuration is
- * valid.
- */
- private int mSubscriptionId;
-
- /**
- * Whether this network is shared credential with user to allow user manually connect.
- */
- private boolean mIsSharedWithUser;
-
- /**
- * Whether the setCredentialSharedWithUser have been called.
- */
- private boolean mIsSharedWithUserSet;
-
- /**
- * Whether this network is initialized with auto-join enabled (the default) or not.
- */
- private boolean mIsInitialAutojoinEnabled;
-
- /**
- * Pre-shared key for use with WAPI-PSK networks.
- */
- private @Nullable String mWapiPskPassphrase;
-
- /**
- * The enterprise configuration details specifying the EAP method,
- * certificates and other settings associated with the WAPI networks.
- */
- private @Nullable WifiEnterpriseConfig mWapiEnterpriseConfig;
-
- /**
- * Whether this network will be brought up as untrusted (TRUSTED capability bit removed).
- */
- private boolean mIsNetworkUntrusted;
-
- /**
- * Whether this network will be brought up as OEM paid (OEM_PAID capability bit added).
- */
- private boolean mIsNetworkOemPaid;
-
- /**
- * Whether this network will be brought up as OEM private (OEM_PRIVATE capability bit
- * added).
- */
- private boolean mIsNetworkOemPrivate;
-
- /**
- * Whether this network is a carrier merged network.
- */
- private boolean mIsCarrierMerged;
-
- /**
- * Whether this network will use enhanced MAC randomization.
- */
- private boolean mIsEnhancedMacRandomizationEnabled;
-
- public Builder() {
- mSsid = null;
- mBssid = null;
- mIsEnhancedOpen = false;
- mWpa2PskPassphrase = null;
- mWpa3SaePassphrase = null;
- mWpa2EnterpriseConfig = null;
- mWpa3EnterpriseConfig = null;
- mPasspointConfiguration = null;
- mIsHiddenSSID = false;
- mIsAppInteractionRequired = false;
- mIsUserInteractionRequired = false;
- mMeteredOverride = WifiConfiguration.METERED_OVERRIDE_NONE;
- mIsSharedWithUser = true;
- mIsSharedWithUserSet = false;
- mIsInitialAutojoinEnabled = true;
- mPriority = UNASSIGNED_PRIORITY;
- mCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
- mWapiPskPassphrase = null;
- mWapiEnterpriseConfig = null;
- mIsNetworkUntrusted = false;
- mIsNetworkOemPaid = false;
- mIsNetworkOemPrivate = false;
- mIsCarrierMerged = false;
- mPriorityGroup = 0;
- mIsEnhancedMacRandomizationEnabled = false;
- mSubscriptionId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
- }
-
- /**
- * Set the unicode SSID for the network.
- * <p>
- * <li>Overrides any previous value set using {@link #setSsid(String)}.</li>
- *
- * @param ssid The SSID of the network. It must be valid Unicode.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the SSID is not valid unicode.
- */
- public @NonNull Builder setSsid(@NonNull String ssid) {
- checkNotNull(ssid);
- final CharsetEncoder unicodeEncoder = StandardCharsets.UTF_8.newEncoder();
- if (!unicodeEncoder.canEncode(ssid)) {
- throw new IllegalArgumentException("SSID is not a valid unicode string");
- }
- mSsid = new String(ssid);
- return this;
- }
-
- /**
- * Set the BSSID to use for filtering networks from scan results. Will only match network
- * whose BSSID is identical to the specified value.
- * <p>
- * <li Sets a specific BSSID for the network suggestion. If set, only the specified BSSID
- * with the specified SSID will be considered for connection.
- * <li>If set, only the specified BSSID with the specified SSID will be considered for
- * connection.</li>
- * <li>If not set, all BSSIDs with the specified SSID will be considered for connection.
- * </li>
- * <li>Overrides any previous value set using {@link #setBssid(MacAddress)}.</li>
- *
- * @param bssid BSSID of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setBssid(@NonNull MacAddress bssid) {
- checkNotNull(bssid);
- mBssid = MacAddress.fromBytes(bssid.toByteArray());
- return this;
- }
-
- /**
- * Specifies whether this represents an Enhanced Open (OWE) network.
- *
- * @param isEnhancedOpen {@code true} to indicate that the network used enhanced open,
- * {@code false} otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsEnhancedOpen(boolean isEnhancedOpen) {
- mIsEnhancedOpen = isEnhancedOpen;
- return this;
- }
-
- /**
- * Set the ASCII WPA2 passphrase for this network. Needed for authenticating to
- * WPA2-PSK networks.
- *
- * @param passphrase passphrase of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
- */
- public @NonNull Builder setWpa2Passphrase(@NonNull String passphrase) {
- checkNotNull(passphrase);
- final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
- if (!asciiEncoder.canEncode(passphrase)) {
- throw new IllegalArgumentException("passphrase not ASCII encodable");
- }
- mWpa2PskPassphrase = passphrase;
- return this;
- }
-
- /**
- * Set the ASCII WPA3 passphrase for this network. Needed for authenticating to WPA3-SAE
- * networks.
- *
- * @param passphrase passphrase of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
- */
- public @NonNull Builder setWpa3Passphrase(@NonNull String passphrase) {
- checkNotNull(passphrase);
- final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
- if (!asciiEncoder.canEncode(passphrase)) {
- throw new IllegalArgumentException("passphrase not ASCII encodable");
- }
- mWpa3SaePassphrase = passphrase;
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA2 enterprise networks. See {@link WifiEnterpriseConfig} for description.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if configuration CA certificate or
- * AltSubjectMatch/DomainSuffixMatch is not set.
- */
- public @NonNull Builder setWpa2EnterpriseConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- if (enterpriseConfig.isInsecure()) {
- throw new IllegalArgumentException("Enterprise configuration is insecure");
- }
- mWpa2EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA3-Enterprise networks (standard and 192-bit security). See
- * {@link WifiEnterpriseConfig} for description. For 192-bit security networks, both the
- * client and CA certificates must be provided, and must be of type of either
- * sha384WithRSAEncryption (OID 1.2.840.113549.1.1.12) or ecdsa-with-SHA384
- * (OID 1.2.840.10045.4.3.3).
- *
- * @deprecated use {@link #setWpa3EnterpriseStandardModeConfig(WifiEnterpriseConfig)} or
- * {@link #setWpa3Enterprise192BitModeConfig(WifiEnterpriseConfig)} to specify
- * WPA3-Enterprise type explicitly.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if configuration CA certificate or
- * AltSubjectMatch/DomainSuffixMatch is not set.
- */
- @Deprecated
- public @NonNull Builder setWpa3EnterpriseConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- if (enterpriseConfig.isInsecure()) {
- throw new IllegalArgumentException("Enterprise configuration is insecure");
- }
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA3-Enterprise standard networks. See {@link WifiEnterpriseConfig} for description.
- * For WPA3-Enterprise in 192-bit security mode networks,
- * see {@link #setWpa3Enterprise192BitModeConfig(WifiEnterpriseConfig)} for description.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if configuration CA certificate or
- * AltSubjectMatch/DomainSuffixMatch is not set.
- */
- public @NonNull Builder setWpa3EnterpriseStandardModeConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- if (enterpriseConfig.isInsecure()) {
- throw new IllegalArgumentException("Enterprise configuration is insecure");
- }
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- mWpa3EnterpriseType = WPA3_ENTERPRISE_STANDARD;
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WPA3-Enterprise in 192-bit security mode networks. See {@link WifiEnterpriseConfig}
- * for description. Both the client and CA certificates must be provided,
- * and must be of type of either sha384WithRSAEncryption with key length of 3072bit or
- * more (OID 1.2.840.113549.1.1.12), or ecdsa-with-SHA384 with key length of 384bit or
- * more (OID 1.2.840.10045.4.3.3).
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the EAP type or certificates do not
- * meet 192-bit mode requirements.
- */
- public @NonNull Builder setWpa3Enterprise192BitModeConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- if (enterpriseConfig.getEapMethod() != WifiEnterpriseConfig.Eap.TLS) {
- throw new IllegalArgumentException("The 192-bit mode network type must be TLS");
- }
- if (!WifiEnterpriseConfig.isSuiteBCipherCert(
- enterpriseConfig.getClientCertificate())) {
- throw new IllegalArgumentException(
- "The client certificate does not meet 192-bit mode requirements.");
- }
- if (!WifiEnterpriseConfig.isSuiteBCipherCert(
- enterpriseConfig.getCaCertificate())) {
- throw new IllegalArgumentException(
- "The CA certificate does not meet 192-bit mode requirements.");
- }
-
- mWpa3EnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- mWpa3EnterpriseType = WPA3_ENTERPRISE_192_BIT;
- return this;
- }
-
- /**
- * Set the associated Passpoint configuration for this network. Needed for authenticating
- * to Hotspot 2.0 networks. See {@link PasspointConfiguration} for description.
- *
- * @param passpointConfig Instance of {@link PasspointConfiguration}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if passpoint configuration is invalid.
- */
- public @NonNull Builder setPasspointConfig(
- @NonNull PasspointConfiguration passpointConfig) {
- checkNotNull(passpointConfig);
- if (!passpointConfig.validate()) {
- throw new IllegalArgumentException("Passpoint configuration is invalid");
- }
- mPasspointConfiguration = passpointConfig;
- return this;
- }
-
- /**
- * Set the carrier ID of the network operator. The carrier ID associates a Suggested
- * network with a specific carrier (and therefore SIM). The carrier ID must be provided
- * for any network which uses the SIM-based authentication: e.g. EAP-SIM, EAP-AKA,
- * EAP-AKA', and EAP-PEAP with SIM-based phase 2 authentication.
- * @param carrierId see {@link TelephonyManager#getSimCarrierId()}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_CARRIER_PROVISIONING)
- public @NonNull Builder setCarrierId(int carrierId) {
- mCarrierId = carrierId;
- return this;
- }
-
- /**
- * Set the subscription ID of the SIM card for which this suggestion is targeted.
- * The suggestion will only apply to that SIM card.
- * <p>
- * The subscription ID must belong to a carrier ID which meets either of the following
- * conditions:
- * <li>The carrier ID specified by the cross carrier provider, or</li>
- * <li>The carrier ID which is used to validate the suggesting carrier-privileged app, see
- * {@link TelephonyManager#hasCarrierPrivileges()}</li>
- *
- * @param subId subscription ID see {@link SubscriptionInfo#getSubscriptionId()}
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setSubscriptionId(int subId) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mSubscriptionId = subId;
- return this;
- }
-
- /**
- * Set the priority group ID, {@link #setPriority(int)} will only impact the network
- * suggestions from the same priority group within the same app.
- *
- * @param priorityGroup priority group id, if not set default is 0.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setPriorityGroup(int priorityGroup) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mPriorityGroup = priorityGroup;
- return this;
- }
-
- /**
- * Set the ASCII WAPI passphrase for this network. Needed for authenticating to
- * WAPI-PSK networks.
- *
- * @param passphrase passphrase of the network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the passphrase is not ASCII encodable.
- *
- */
- public @NonNull Builder setWapiPassphrase(@NonNull String passphrase) {
- checkNotNull(passphrase);
- final CharsetEncoder asciiEncoder = StandardCharsets.US_ASCII.newEncoder();
- if (!asciiEncoder.canEncode(passphrase)) {
- throw new IllegalArgumentException("passphrase not ASCII encodable");
- }
- mWapiPskPassphrase = passphrase;
- return this;
- }
-
- /**
- * Set the associated enterprise configuration for this network. Needed for authenticating
- * to WAPI-CERT networks. See {@link WifiEnterpriseConfig} for description.
- *
- * @param enterpriseConfig Instance of {@link WifiEnterpriseConfig}.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setWapiEnterpriseConfig(
- @NonNull WifiEnterpriseConfig enterpriseConfig) {
- checkNotNull(enterpriseConfig);
- mWapiEnterpriseConfig = new WifiEnterpriseConfig(enterpriseConfig);
- return this;
- }
-
- /**
- * Specifies whether this represents a hidden network.
- * <p>
- * <li>If not set, defaults to false (i.e not a hidden network).</li>
- *
- * @param isHiddenSsid {@code true} to indicate that the network is hidden, {@code false}
- * otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsHiddenSsid(boolean isHiddenSsid) {
- mIsHiddenSSID = isHiddenSsid;
- return this;
- }
-
- /**
- * Specifies the MAC randomization method.
- * <p>
- * Suggested networks will never use the device (factory) MAC address to associate to the
- * network - instead they use a locally generated random MAC address. This method controls
- * the strategy for generating the random MAC address:
- * <li> Persisted MAC randomization (false - the default): generates the MAC address from a
- * secret seed and information from the Wi-Fi configuration (SSID or Passpoint profile).
- * This means that the same generated MAC address will be used for each subsequent
- * association. </li>
- * <li> Enhanced MAC randomization (true): periodically generates a new MAC
- * address for new connections. Under this option, the randomized MAC address should change
- * if the suggestion is removed and then added back. </li>
- *
- * @param enabled {@code true} to periodically change the randomized MAC address.
- * {@code false} to use the same randomized MAC for all connections to this
- * network.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsEnhancedMacRandomizationEnabled(boolean enabled) {
- mIsEnhancedMacRandomizationEnabled = enabled;
- return this;
- }
-
- /**
- * Specifies whether the app needs to log in to a captive portal to obtain Internet access.
- * <p>
- * This will dictate if the directed broadcast
- * {@link WifiManager#ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION} will be sent to the
- * app after successfully connecting to the network.
- * Use this for captive portal type networks where the app needs to authenticate the user
- * before the device can access the network.
- * <p>
- * <li>If not set, defaults to false (i.e no app interaction required).</li>
- *
- * @param isAppInteractionRequired {@code true} to indicate that app interaction is
- * required, {@code false} otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsAppInteractionRequired(boolean isAppInteractionRequired) {
- mIsAppInteractionRequired = isAppInteractionRequired;
- return this;
- }
-
- /**
- * Specifies whether the user needs to log in to a captive portal to obtain Internet access.
- * <p>
- * <li>If not set, defaults to false (i.e no user interaction required).</li>
- *
- * @param isUserInteractionRequired {@code true} to indicate that user interaction is
- * required, {@code false} otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsUserInteractionRequired(boolean isUserInteractionRequired) {
- mIsUserInteractionRequired = isUserInteractionRequired;
- return this;
- }
-
- /**
- * Specify the priority of this network among other network suggestions provided by the same
- * app (priorities have no impact on suggestions by different apps) and within the same
- * priority group, see {@link #setPriorityGroup(int)}.
- * The higher the number, the higher the priority (i.e value of 0 = lowest priority).
- * <p>
- * <li>If not set, defaults a lower priority than any assigned priority.</li>
- *
- * @param priority Integer number representing the priority among suggestions by the app.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @throws IllegalArgumentException if the priority value is negative.
- */
- public @NonNull Builder setPriority(@IntRange(from = 0) int priority) {
- if (priority < 0) {
- throw new IllegalArgumentException("Invalid priority value " + priority);
- }
- mPriority = priority;
- return this;
- }
-
- /**
- * Specifies whether this network is metered.
- * <p>
- * <li>If not set, defaults to detect automatically.</li>
- *
- * @param isMetered {@code true} to indicate that the network is metered, {@code false}
- * for not metered.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsMetered(boolean isMetered) {
- if (isMetered) {
- mMeteredOverride = WifiConfiguration.METERED_OVERRIDE_METERED;
- } else {
- mMeteredOverride = WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
- }
- return this;
- }
-
- /**
- * Specifies whether the network credentials provided with this suggestion can be used by
- * the user to explicitly (manually) connect to this network. If true this network will
- * appear in the Wi-Fi Picker (in Settings) and the user will be able to select and connect
- * to it with the provided credentials. If false, the user will need to enter network
- * credentials and the resulting configuration will become a user saved network.
- * <p>
- * <li>Note: Only valid for secure (non-open) networks.
- * <li>If not set, defaults to true (i.e. allow user to manually connect) for secure
- * networks and false for open networks.</li>
- *
- * @param isShared {@code true} to indicate that the credentials may be used by the user to
- * manually connect to the network, {@code false} otherwise.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setCredentialSharedWithUser(boolean isShared) {
- mIsSharedWithUser = isShared;
- mIsSharedWithUserSet = true;
- return this;
- }
-
- /**
- * Specifies whether the suggestion is created with auto-join enabled or disabled. The
- * user may modify the auto-join configuration of a suggestion directly once the device
- * associates to the network.
- * <p>
- * If auto-join is initialized as disabled the user may still be able to manually connect
- * to the network. Therefore, disabling auto-join only makes sense if
- * {@link #setCredentialSharedWithUser(boolean)} is set to true (the default) which
- * itself implies a secure (non-open) network.
- * <p>
- * If not set, defaults to true (i.e. auto-join is initialized as enabled).
- *
- * @param enabled true for initializing with auto-join enabled (the default), false to
- * initializing with auto-join disabled.
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setIsInitialAutojoinEnabled(boolean enabled) {
- mIsInitialAutojoinEnabled = enabled;
- return this;
- }
-
- /**
- * Specifies whether the system will bring up the network (if selected) as untrusted. An
- * untrusted network has its {@link NetworkCapabilities#NET_CAPABILITY_TRUSTED}
- * capability removed. The Wi-Fi network selection process may use this information to
- * influence priority of the suggested network for Wi-Fi network selection (most likely to
- * reduce it). The connectivity service may use this information to influence the overall
- * network configuration of the device.
- * <p>
- * <li> These suggestions are only considered for network selection if a
- * {@link NetworkRequest} without {@link NetworkCapabilities#NET_CAPABILITY_TRUSTED}
- * capability is filed.
- * <li> An untrusted network's credentials may not be shared with the user using
- * {@link #setCredentialSharedWithUser(boolean)}.</li>
- * <li> If not set, defaults to false (i.e. network is trusted).</li>
- *
- * @param isUntrusted Boolean indicating whether the network should be brought up untrusted
- * (if true) or trusted (if false).
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setUntrusted(boolean isUntrusted) {
- mIsNetworkUntrusted = isUntrusted;
- return this;
- }
-
- /**
- * Specifies whether the system will bring up the network (if selected) as OEM paid. An
- * OEM paid network has {@link NetworkCapabilities#NET_CAPABILITY_OEM_PAID} capability
- * added.
- * Note:
- * <li>The connectivity service may use this information to influence the overall
- * network configuration of the device. This network is typically only available to system
- * apps.
- * <li>On devices which do not support concurrent connection (indicated via
- * {@link WifiManager#isMultiStaConcurrencySupported()}, Wi-Fi network selection process may
- * use this information to influence priority of the suggested network for Wi-Fi network
- * selection (most likely to reduce it).
- * <li>On devices which support more than 1 concurrent connections (indicated via
- * {@link WifiManager#isMultiStaConcurrencySupported()}, these OEM paid networks will be
- * brought up as a secondary concurrent connection (primary connection will be used
- * for networks available to the user and all apps.
- * <p>
- * <li> An OEM paid network's credentials may not be shared with the user using
- * {@link #setCredentialSharedWithUser(boolean)}.</li>
- * <li> These suggestions are only considered for network selection if a
- * {@link NetworkRequest} with {@link NetworkCapabilities#NET_CAPABILITY_OEM_PAID}
- * capability is filed.
- * <li> Each suggestion can have both {@link #setOemPaid(boolean)} and
- * {@link #setOemPrivate(boolean)} set if the app wants these suggestions considered
- * for creating either an OEM paid network or OEM private network determined based on
- * the {@link NetworkRequest} that is active.
- * <li> If not set, defaults to false (i.e. network is not OEM paid).</li>
- *
- * @param isOemPaid Boolean indicating whether the network should be brought up as OEM paid
- * (if true) or not OEM paid (if false).
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @hide
- */
- @SystemApi
- public @NonNull Builder setOemPaid(boolean isOemPaid) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mIsNetworkOemPaid = isOemPaid;
- return this;
- }
-
- /**
- * Specifies whether the system will bring up the network (if selected) as OEM private. An
- * OEM private network has {@link NetworkCapabilities#NET_CAPABILITY_OEM_PRIVATE} capability
- * added.
- * Note:
- * <li>The connectivity service may use this information to influence the overall
- * network configuration of the device. This network is typically only available to system
- * apps.
- * <li>On devices which do not support concurrent connection (indicated via
- * {@link WifiManager#isMultiStaConcurrencySupported()}, Wi-Fi network selection process may
- * use this information to influence priority of the suggested network for Wi-Fi network
- * selection (most likely to reduce it).
- * <li>On devices which support more than 1 concurrent connections (indicated via
- * {@link WifiManager#isMultiStaConcurrencySupported()}, these OEM private networks will be
- * brought up as a secondary concurrent connection (primary connection will be used
- * for networks available to the user and all apps.
- * <p>
- * <li> An OEM private network's credentials may not be shared with the user using
- * {@link #setCredentialSharedWithUser(boolean)}.</li>
- * <li> These suggestions are only considered for network selection if a
- * {@link NetworkRequest} with {@link NetworkCapabilities#NET_CAPABILITY_OEM_PRIVATE}
- * capability is filed.
- * <li> Each suggestion can have both {@link #setOemPaid(boolean)} and
- * {@link #setOemPrivate(boolean)} set if the app wants these suggestions considered
- * for creating either an OEM paid network or OEM private network determined based on
- * the {@link NetworkRequest} that is active.
- * <li> If not set, defaults to false (i.e. network is not OEM private).</li>
- *
- * @param isOemPrivate Boolean indicating whether the network should be brought up as OEM
- * private (if true) or not OEM private (if false).
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- * @hide
- */
- @SystemApi
- public @NonNull Builder setOemPrivate(boolean isOemPrivate) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mIsNetworkOemPrivate = isOemPrivate;
- return this;
- }
-
- /**
- * Specifies whether the suggestion represents a carrier merged network. A carrier merged
- * Wi-Fi network is treated as part of the mobile carrier network. Such configuration may
- * impact the user interface and data usage accounting.
- * <p>
- * <li>A suggestion marked as carrier merged must be metered enterprise network with a valid
- * subscription Id set.
- * @see #setIsMetered(boolean)
- * @see #setSubscriptionId(int)
- * @see #setWpa2EnterpriseConfig(WifiEnterpriseConfig)
- * @see #setWpa3Enterprise192BitModeConfig(WifiEnterpriseConfig)
- * @see #setWpa3EnterpriseStandardModeConfig(WifiEnterpriseConfig)
- * @see #setPasspointConfig(PasspointConfiguration)
- * </li>
- * <li>If not set, defaults to false (i.e. not a carrier merged network.)</li>
- * </p>
- * @param isCarrierMerged Boolean indicating whether the network is treated a carrier
- * merged network (if true) or non-merged network (if false);
- * @return Instance of {@link Builder} to enable chaining of the builder method.
- */
- public @NonNull Builder setCarrierMerged(boolean isCarrierMerged) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- mIsCarrierMerged = isCarrierMerged;
- return this;
- }
-
- private void setSecurityParamsInWifiConfiguration(
- @NonNull WifiConfiguration configuration) {
- if (!TextUtils.isEmpty(mWpa2PskPassphrase)) { // WPA-PSK network.
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_PSK);
- // WifiConfiguration.preSharedKey needs quotes around ASCII password.
- configuration.preSharedKey = "\"" + mWpa2PskPassphrase + "\"";
- } else if (!TextUtils.isEmpty(mWpa3SaePassphrase)) { // WPA3-SAE network.
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_SAE);
- // WifiConfiguration.preSharedKey needs quotes around ASCII password.
- configuration.preSharedKey = "\"" + mWpa3SaePassphrase + "\"";
- } else if (mWpa2EnterpriseConfig != null) { // WPA-EAP network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP);
- configuration.enterpriseConfig = mWpa2EnterpriseConfig;
- } else if (mWpa3EnterpriseConfig != null) { // WPA3-Enterprise
- if (mWpa3EnterpriseType == WPA3_ENTERPRISE_AUTO
- && mWpa3EnterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TLS
- && WifiEnterpriseConfig.isSuiteBCipherCert(
- mWpa3EnterpriseConfig.getClientCertificate())
- && WifiEnterpriseConfig.isSuiteBCipherCert(
- mWpa3EnterpriseConfig.getCaCertificate())) {
- // WPA3-Enterprise in 192-bit security mode
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT);
- } else if (mWpa3EnterpriseType == WPA3_ENTERPRISE_192_BIT) {
- // WPA3-Enterprise in 192-bit security mode
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT);
- } else {
- // WPA3-Enterprise
- configuration.setSecurityParams(
- WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE);
- }
- configuration.enterpriseConfig = mWpa3EnterpriseConfig;
- } else if (mIsEnhancedOpen) { // OWE network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OWE);
- } else if (!TextUtils.isEmpty(mWapiPskPassphrase)) { // WAPI-PSK network.
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_WAPI_PSK);
- // WifiConfiguration.preSharedKey needs quotes around ASCII password.
- configuration.preSharedKey = "\"" + mWapiPskPassphrase + "\"";
- } else if (mWapiEnterpriseConfig != null) { // WAPI-CERT network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_WAPI_CERT);
- configuration.enterpriseConfig = mWapiEnterpriseConfig;
- } else { // Open network
- configuration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_OPEN);
- }
- }
-
- /**
- * Helper method to build WifiConfiguration object from the builder.
- * @return Instance of {@link WifiConfiguration}.
- */
- private WifiConfiguration buildWifiConfiguration() {
- final WifiConfiguration wifiConfiguration = new WifiConfiguration();
- // WifiConfiguration.SSID needs quotes around unicode SSID.
- wifiConfiguration.SSID = "\"" + mSsid + "\"";
- if (mBssid != null) {
- wifiConfiguration.BSSID = mBssid.toString();
- }
-
- setSecurityParamsInWifiConfiguration(wifiConfiguration);
-
- wifiConfiguration.hiddenSSID = mIsHiddenSSID;
- wifiConfiguration.priority = mPriority;
- wifiConfiguration.meteredOverride = mMeteredOverride;
- wifiConfiguration.carrierId = mCarrierId;
- wifiConfiguration.trusted = !mIsNetworkUntrusted;
- wifiConfiguration.oemPaid = mIsNetworkOemPaid;
- wifiConfiguration.oemPrivate = mIsNetworkOemPrivate;
- wifiConfiguration.carrierMerged = mIsCarrierMerged;
- wifiConfiguration.macRandomizationSetting = mIsEnhancedMacRandomizationEnabled
- ? WifiConfiguration.RANDOMIZATION_ENHANCED
- : WifiConfiguration.RANDOMIZATION_PERSISTENT;
- wifiConfiguration.subscriptionId = mSubscriptionId;
- return wifiConfiguration;
- }
-
- private void validateSecurityParams() {
- int numSecurityTypes = 0;
- numSecurityTypes += mIsEnhancedOpen ? 1 : 0;
- numSecurityTypes += !TextUtils.isEmpty(mWpa2PskPassphrase) ? 1 : 0;
- numSecurityTypes += !TextUtils.isEmpty(mWpa3SaePassphrase) ? 1 : 0;
- numSecurityTypes += !TextUtils.isEmpty(mWapiPskPassphrase) ? 1 : 0;
- numSecurityTypes += mWpa2EnterpriseConfig != null ? 1 : 0;
- numSecurityTypes += mWpa3EnterpriseConfig != null ? 1 : 0;
- numSecurityTypes += mWapiEnterpriseConfig != null ? 1 : 0;
- numSecurityTypes += mPasspointConfiguration != null ? 1 : 0;
- if (numSecurityTypes > 1) {
- throw new IllegalStateException("only one of setIsEnhancedOpen, setWpa2Passphrase,"
- + " setWpa3Passphrase, setWpa2EnterpriseConfig, setWpa3EnterpriseConfig"
- + " setWapiPassphrase, setWapiCertSuite, setIsWapiCertSuiteAuto"
- + " or setPasspointConfig can be invoked for network suggestion");
- }
- }
-
- private WifiConfiguration buildWifiConfigurationForPasspoint() {
- WifiConfiguration wifiConfiguration = new WifiConfiguration();
- wifiConfiguration.FQDN = mPasspointConfiguration.getHomeSp().getFqdn();
- wifiConfiguration.setPasspointUniqueId(mPasspointConfiguration.getUniqueId());
- wifiConfiguration.priority = mPriority;
- wifiConfiguration.meteredOverride = mMeteredOverride;
- wifiConfiguration.trusted = !mIsNetworkUntrusted;
- wifiConfiguration.oemPaid = mIsNetworkOemPaid;
- wifiConfiguration.oemPrivate = mIsNetworkOemPrivate;
- wifiConfiguration.carrierMerged = mIsCarrierMerged;
- wifiConfiguration.subscriptionId = mSubscriptionId;
- mPasspointConfiguration.setCarrierId(mCarrierId);
- mPasspointConfiguration.setSubscriptionId(mSubscriptionId);
- mPasspointConfiguration.setMeteredOverride(wifiConfiguration.meteredOverride);
- mPasspointConfiguration.setOemPrivate(mIsNetworkOemPrivate);
- mPasspointConfiguration.setOemPaid(mIsNetworkOemPaid);
- mPasspointConfiguration.setCarrierMerged(mIsCarrierMerged);
- wifiConfiguration.macRandomizationSetting = mIsEnhancedMacRandomizationEnabled
- ? WifiConfiguration.RANDOMIZATION_ENHANCED
- : WifiConfiguration.RANDOMIZATION_PERSISTENT;
- return wifiConfiguration;
- }
-
- /**
- * Create a network suggestion object for use in
- * {@link WifiManager#addNetworkSuggestions(List)}.
- *
- *<p class="note">
- * <b>Note:</b> Apps can set a combination of SSID using {@link #setSsid(String)} and BSSID
- * using {@link #setBssid(MacAddress)} to provide more fine grained network suggestions to
- * the platform.
- * </p>
- *
- * For example:
- * To provide credentials for one open, one WPA2, one WPA3 network with their
- * corresponding SSID's and one with Passpoint config:
- *
- * <pre>{@code
- * final WifiNetworkSuggestion suggestion1 =
- * new Builder()
- * .setSsid("test111111")
- * .build();
- * final WifiNetworkSuggestion suggestion2 =
- * new Builder()
- * .setSsid("test222222")
- * .setWpa2Passphrase("test123456")
- * .build();
- * final WifiNetworkSuggestion suggestion3 =
- * new Builder()
- * .setSsid("test333333")
- * .setWpa3Passphrase("test6789")
- * .build();
- * final PasspointConfiguration passpointConfig= new PasspointConfiguration();
- * // configure passpointConfig to include a valid Passpoint configuration
- * final WifiNetworkSuggestion suggestion4 =
- * new Builder()
- * .setPasspointConfig(passpointConfig)
- * .build();
- * final List<WifiNetworkSuggestion> suggestionsList =
- * new ArrayList<WifiNetworkSuggestion> { {
- * add(suggestion1);
- * add(suggestion2);
- * add(suggestion3);
- * add(suggestion4);
- * } };
- * final WifiManager wifiManager =
- * context.getSystemService(Context.WIFI_SERVICE);
- * wifiManager.addNetworkSuggestions(suggestionsList);
- * // ...
- * }</pre>
- *
- * @return Instance of {@link WifiNetworkSuggestion}
- * @throws IllegalStateException on invalid params set
- * @see WifiNetworkSuggestion
- */
- public @NonNull WifiNetworkSuggestion build() {
- validateSecurityParams();
- WifiConfiguration wifiConfiguration;
- if (mPasspointConfiguration != null) {
- if (mSsid != null) {
- throw new IllegalStateException("setSsid should not be invoked for suggestion "
- + "with Passpoint configuration");
- }
- if (mIsHiddenSSID) {
- throw new IllegalStateException("setIsHiddenSsid should not be invoked for "
- + "suggestion with Passpoint configuration");
- }
- wifiConfiguration = buildWifiConfigurationForPasspoint();
- mPasspointConfiguration.setEnhancedMacRandomizationEnabled(
- mIsEnhancedMacRandomizationEnabled);
- } else {
- if (mSsid == null) {
- throw new IllegalStateException("setSsid should be invoked for suggestion");
- }
- if (TextUtils.isEmpty(mSsid)) {
- throw new IllegalStateException("invalid ssid for suggestion");
- }
- if (mBssid != null
- && (mBssid.equals(MacAddress.BROADCAST_ADDRESS)
- || mBssid.equals(WifiManager.ALL_ZEROS_MAC_ADDRESS))) {
- throw new IllegalStateException("invalid bssid for suggestion");
- }
- wifiConfiguration = buildWifiConfiguration();
- if (wifiConfiguration.isOpenNetwork()) {
- if (mIsSharedWithUserSet && mIsSharedWithUser) {
- throw new IllegalStateException("Open network should not be "
- + "setCredentialSharedWithUser to true");
- }
- mIsSharedWithUser = false;
- }
- }
- if (!mIsSharedWithUser && !mIsInitialAutojoinEnabled) {
- throw new IllegalStateException("Should have not a network with both "
- + "setCredentialSharedWithUser and "
- + "setIsAutojoinEnabled set to false");
- }
- if (mIsNetworkUntrusted) {
- if (mIsSharedWithUserSet && mIsSharedWithUser) {
- throw new IllegalStateException("Should not be both"
- + "setCredentialSharedWithUser and +"
- + "setUntrusted to true");
- }
- mIsSharedWithUser = false;
- }
- if (mIsNetworkOemPaid) {
- if (mIsSharedWithUserSet && mIsSharedWithUser) {
- throw new IllegalStateException("Should not be both"
- + "setCredentialSharedWithUser and +"
- + "setOemPaid to true");
- }
- mIsSharedWithUser = false;
- }
- if (mIsNetworkOemPrivate) {
- if (mIsSharedWithUserSet && mIsSharedWithUser) {
- throw new IllegalStateException("Should not be both"
- + "setCredentialSharedWithUser and +"
- + "setOemPrivate to true");
- }
- mIsSharedWithUser = false;
- }
- if (mIsCarrierMerged) {
- if (mSubscriptionId == SubscriptionManager.INVALID_SUBSCRIPTION_ID
- || mMeteredOverride != WifiConfiguration.METERED_OVERRIDE_METERED
- || !isEnterpriseSuggestion()) {
- throw new IllegalStateException("A carrier merged network must be a metered, "
- + "enterprise network with valid subscription Id");
- }
- }
- return new WifiNetworkSuggestion(
- wifiConfiguration,
- mPasspointConfiguration,
- mIsAppInteractionRequired,
- mIsUserInteractionRequired,
- mIsSharedWithUser,
- mIsInitialAutojoinEnabled,
- mPriorityGroup);
- }
-
- private boolean isEnterpriseSuggestion() {
- return !(mWpa2EnterpriseConfig == null && mWpa3EnterpriseConfig == null
- && mWapiEnterpriseConfig == null && mPasspointConfiguration == null);
- }
- }
-
-
-
- /**
- * Network configuration for the provided network.
- * @hide
- */
- @NonNull
- public final WifiConfiguration wifiConfiguration;
-
- /**
- * Passpoint configuration for the provided network.
- * @hide
- */
- @Nullable
- public final PasspointConfiguration passpointConfiguration;
-
- /**
- * Whether app needs to log in to captive portal to obtain Internet access.
- * @hide
- */
- public final boolean isAppInteractionRequired;
-
- /**
- * Whether user needs to log in to captive portal to obtain Internet access.
- * @hide
- */
- public final boolean isUserInteractionRequired;
-
- /**
- * Whether app share credential with the user, allow user use provided credential to
- * connect network manually.
- * @hide
- */
- public final boolean isUserAllowedToManuallyConnect;
-
- /**
- * Whether the suggestion will be initialized as auto-joined or not.
- * @hide
- */
- public final boolean isInitialAutoJoinEnabled;
-
- /**
- * Priority group ID.
- * @hide
- */
- public final int priorityGroup;
-
- /** @hide */
- public WifiNetworkSuggestion() {
- this.wifiConfiguration = new WifiConfiguration();
- this.passpointConfiguration = null;
- this.isAppInteractionRequired = false;
- this.isUserInteractionRequired = false;
- this.isUserAllowedToManuallyConnect = true;
- this.isInitialAutoJoinEnabled = true;
- this.priorityGroup = 0;
- }
-
- /** @hide */
- public WifiNetworkSuggestion(@NonNull WifiConfiguration networkConfiguration,
- @Nullable PasspointConfiguration passpointConfiguration,
- boolean isAppInteractionRequired,
- boolean isUserInteractionRequired,
- boolean isUserAllowedToManuallyConnect,
- boolean isInitialAutoJoinEnabled, int priorityGroup) {
- checkNotNull(networkConfiguration);
- this.wifiConfiguration = networkConfiguration;
- this.passpointConfiguration = passpointConfiguration;
-
- this.isAppInteractionRequired = isAppInteractionRequired;
- this.isUserInteractionRequired = isUserInteractionRequired;
- this.isUserAllowedToManuallyConnect = isUserAllowedToManuallyConnect;
- this.isInitialAutoJoinEnabled = isInitialAutoJoinEnabled;
- this.priorityGroup = priorityGroup;
- }
-
- public static final @NonNull Creator<WifiNetworkSuggestion> CREATOR =
- new Creator<WifiNetworkSuggestion>() {
- @Override
- public WifiNetworkSuggestion createFromParcel(Parcel in) {
- return new WifiNetworkSuggestion(
- in.readParcelable(null), // wifiConfiguration
- in.readParcelable(null), // PasspointConfiguration
- in.readBoolean(), // isAppInteractionRequired
- in.readBoolean(), // isUserInteractionRequired
- in.readBoolean(), // isSharedCredentialWithUser
- in.readBoolean(), // isAutojoinEnabled
- in.readInt() // priorityGroup
- );
- }
-
- @Override
- public WifiNetworkSuggestion[] newArray(int size) {
- return new WifiNetworkSuggestion[size];
- }
- };
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeParcelable(wifiConfiguration, flags);
- dest.writeParcelable(passpointConfiguration, flags);
- dest.writeBoolean(isAppInteractionRequired);
- dest.writeBoolean(isUserInteractionRequired);
- dest.writeBoolean(isUserAllowedToManuallyConnect);
- dest.writeBoolean(isInitialAutoJoinEnabled);
- dest.writeInt(priorityGroup);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(wifiConfiguration.SSID, wifiConfiguration.BSSID,
- wifiConfiguration.getDefaultSecurityType(),
- wifiConfiguration.getPasspointUniqueId(),
- wifiConfiguration.subscriptionId, wifiConfiguration.carrierId);
- }
-
- /**
- * Equals for network suggestions.
- */
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof WifiNetworkSuggestion)) {
- return false;
- }
- WifiNetworkSuggestion lhs = (WifiNetworkSuggestion) obj;
- if (this.passpointConfiguration == null ^ lhs.passpointConfiguration == null) {
- return false;
- }
-
- return TextUtils.equals(this.wifiConfiguration.SSID, lhs.wifiConfiguration.SSID)
- && TextUtils.equals(this.wifiConfiguration.BSSID, lhs.wifiConfiguration.BSSID)
- && TextUtils.equals(this.wifiConfiguration.getDefaultSecurityType(),
- lhs.wifiConfiguration.getDefaultSecurityType())
- && TextUtils.equals(this.wifiConfiguration.getPasspointUniqueId(),
- lhs.wifiConfiguration.getPasspointUniqueId())
- && this.wifiConfiguration.carrierId == lhs.wifiConfiguration.carrierId
- && this.wifiConfiguration.subscriptionId == lhs.wifiConfiguration.subscriptionId;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("WifiNetworkSuggestion[ ")
- .append("SSID=").append(wifiConfiguration.SSID)
- .append(", BSSID=").append(wifiConfiguration.BSSID)
- .append(", FQDN=").append(wifiConfiguration.FQDN)
- .append(", isAppInteractionRequired=").append(isAppInteractionRequired)
- .append(", isUserInteractionRequired=").append(isUserInteractionRequired)
- .append(", isCredentialSharedWithUser=").append(isUserAllowedToManuallyConnect)
- .append(", isInitialAutoJoinEnabled=").append(isInitialAutoJoinEnabled)
- .append(", isUnTrusted=").append(!wifiConfiguration.trusted)
- .append(", isOemPaid=").append(wifiConfiguration.oemPaid)
- .append(", isOemPrivate=").append(wifiConfiguration.oemPrivate)
- .append(", isCarrierMerged").append(wifiConfiguration.carrierMerged)
- .append(", priorityGroup=").append(priorityGroup)
- .append(" ]");
- return sb.toString();
- }
-
- /**
- * Get the {@link WifiConfiguration} associated with this Suggestion.
- * @hide
- */
- @SystemApi
- @NonNull
- public WifiConfiguration getWifiConfiguration() {
- return wifiConfiguration;
- }
-
- /**
- * Get the BSSID, or null if unset.
- * @see Builder#setBssid(MacAddress)
- */
- @Nullable
- public MacAddress getBssid() {
- if (wifiConfiguration.BSSID == null) {
- return null;
- }
- return MacAddress.fromString(wifiConfiguration.BSSID);
- }
-
- /** @see Builder#setCredentialSharedWithUser(boolean) */
- public boolean isCredentialSharedWithUser() {
- return isUserAllowedToManuallyConnect;
- }
-
- /** @see Builder#setIsAppInteractionRequired(boolean) */
- public boolean isAppInteractionRequired() {
- return isAppInteractionRequired;
- }
-
- /** @see Builder#setIsEnhancedOpen(boolean) */
- public boolean isEnhancedOpen() {
- return wifiConfiguration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.OWE);
- }
-
- /** @see Builder#setIsHiddenSsid(boolean) */
- public boolean isHiddenSsid() {
- return wifiConfiguration.hiddenSSID;
- }
-
- /** @see Builder#setIsInitialAutojoinEnabled(boolean) */
- public boolean isInitialAutojoinEnabled() {
- return isInitialAutoJoinEnabled;
- }
-
- /** @see Builder#setIsMetered(boolean) */
- public boolean isMetered() {
- return wifiConfiguration.meteredOverride == WifiConfiguration.METERED_OVERRIDE_METERED;
- }
-
- /** @see Builder#setIsUserInteractionRequired(boolean) */
- public boolean isUserInteractionRequired() {
- return isUserInteractionRequired;
- }
-
- /**
- * Get the {@link PasspointConfiguration} associated with this Suggestion, or null if this
- * Suggestion is not for a Passpoint network.
- */
- @Nullable
- public PasspointConfiguration getPasspointConfig() {
- return passpointConfiguration;
- }
-
- /** @see Builder#setPriority(int) */
- @IntRange(from = 0)
- public int getPriority() {
- return wifiConfiguration.priority;
- }
-
- /**
- * Return the SSID of the network, or null if this is a Passpoint network.
- * @see Builder#setSsid(String)
- */
- @Nullable
- public String getSsid() {
- if (wifiConfiguration.SSID == null) {
- return null;
- }
- return WifiInfo.sanitizeSsid(wifiConfiguration.SSID);
- }
-
- /** @see Builder#setUntrusted(boolean) */
- public boolean isUntrusted() {
- return !wifiConfiguration.trusted;
- }
-
- /**
- * @see Builder#setOemPaid(boolean)
- * @hide
- */
- @SystemApi
- public boolean isOemPaid() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return wifiConfiguration.oemPaid;
- }
-
- /**
- * @see Builder#setOemPrivate(boolean)
- * @hide
- */
- @SystemApi
- public boolean isOemPrivate() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return wifiConfiguration.oemPrivate;
- }
-
- /**
- * @see Builder#setCarrierMerged(boolean)
- */
- public boolean isCarrierMerged() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return wifiConfiguration.carrierMerged;
- }
-
- /**
- * Get the WifiEnterpriseConfig, or null if unset.
- * @see Builder#setWapiEnterpriseConfig(WifiEnterpriseConfig)
- * @see Builder#setWpa2EnterpriseConfig(WifiEnterpriseConfig)
- * @see Builder#setWpa3EnterpriseConfig(WifiEnterpriseConfig)
- */
- @Nullable
- public WifiEnterpriseConfig getEnterpriseConfig() {
- if (!wifiConfiguration.isEnterprise()) {
- return null;
- }
- return wifiConfiguration.enterpriseConfig;
- }
-
- /**
- * Get the passphrase, or null if unset.
- * @see Builder#setWapiPassphrase(String)
- * @see Builder#setWpa2Passphrase(String)
- * @see Builder#setWpa3Passphrase(String)
- */
- @Nullable
- public String getPassphrase() {
- if (wifiConfiguration.preSharedKey == null) {
- return null;
- }
- return WifiInfo.removeDoubleQuotes(wifiConfiguration.preSharedKey);
- }
-
- /**
- * @see Builder#setPriorityGroup(int)
- */
- public int getPriorityGroup() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return priorityGroup;
- }
-
- /**
- * @see Builder#setSubscriptionId(int)
- */
- public int getSubscriptionId() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return wifiConfiguration.subscriptionId;
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiScanner.java b/wifi/java/android/net/wifi/WifiScanner.java
deleted file mode 100644
index 7c051f0962c4..000000000000
--- a/wifi/java/android/net/wifi/WifiScanner.java
+++ /dev/null
@@ -1,1704 +0,0 @@
-/*
- * Copyright (C) 2008 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.Manifest;
-import android.annotation.CallbackExecutor;
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
-import android.annotation.SuppressLint;
-import android.annotation.SystemApi;
-import android.annotation.SystemService;
-import android.content.Context;
-import android.os.Binder;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.os.Messenger;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.os.RemoteException;
-import android.os.WorkSource;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.SparseArray;
-
-import com.android.internal.util.AsyncChannel;
-import com.android.internal.util.Protocol;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Objects;
-import java.util.concurrent.Executor;
-
-/**
- * This class provides a way to scan the Wifi universe around the device
- * @hide
- */
-@SystemApi
-@SystemService(Context.WIFI_SCANNING_SERVICE)
-public class WifiScanner {
-
- /** @hide */
- public static final int WIFI_BAND_INDEX_24_GHZ = 0;
- /** @hide */
- public static final int WIFI_BAND_INDEX_5_GHZ = 1;
- /** @hide */
- public static final int WIFI_BAND_INDEX_5_GHZ_DFS_ONLY = 2;
- /** @hide */
- public static final int WIFI_BAND_INDEX_6_GHZ = 3;
- /** @hide */
- public static final int WIFI_BAND_INDEX_60_GHZ = 4;
- /** @hide */
- public static final int WIFI_BAND_COUNT = 5;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"WIFI_BAND_INDEX_"}, value = {
- WIFI_BAND_INDEX_24_GHZ,
- WIFI_BAND_INDEX_5_GHZ,
- WIFI_BAND_INDEX_5_GHZ_DFS_ONLY,
- WIFI_BAND_INDEX_6_GHZ,
- WIFI_BAND_INDEX_60_GHZ})
- public @interface WifiBandIndex {}
-
- /** no band specified; use channel list instead */
- public static final int WIFI_BAND_UNSPECIFIED = 0;
- /** 2.4 GHz band */
- public static final int WIFI_BAND_24_GHZ = 1 << WIFI_BAND_INDEX_24_GHZ;
- /** 5 GHz band excluding DFS channels */
- public static final int WIFI_BAND_5_GHZ = 1 << WIFI_BAND_INDEX_5_GHZ;
- /** DFS channels from 5 GHz band only */
- public static final int WIFI_BAND_5_GHZ_DFS_ONLY = 1 << WIFI_BAND_INDEX_5_GHZ_DFS_ONLY;
- /** 6 GHz band */
- public static final int WIFI_BAND_6_GHZ = 1 << WIFI_BAND_INDEX_6_GHZ;
- /** 60 GHz band */
- public static final int WIFI_BAND_60_GHZ = 1 << WIFI_BAND_INDEX_60_GHZ;
-
- /**
- * Combination of bands
- * Note that those are only the common band combinations,
- * other combinations can be created by combining any of the basic bands above
- */
- /** Both 2.4 GHz band and 5 GHz band; no DFS channels */
- public static final int WIFI_BAND_BOTH = WIFI_BAND_24_GHZ | WIFI_BAND_5_GHZ;
- /**
- * 2.4Ghz band + DFS channels from 5 GHz band only
- * @hide
- */
- public static final int WIFI_BAND_24_GHZ_WITH_5GHZ_DFS =
- WIFI_BAND_24_GHZ | WIFI_BAND_5_GHZ_DFS_ONLY;
- /** 5 GHz band including DFS channels */
- public static final int WIFI_BAND_5_GHZ_WITH_DFS = WIFI_BAND_5_GHZ | WIFI_BAND_5_GHZ_DFS_ONLY;
- /** Both 2.4 GHz band and 5 GHz band; with DFS channels */
- public static final int WIFI_BAND_BOTH_WITH_DFS =
- WIFI_BAND_24_GHZ | WIFI_BAND_5_GHZ | WIFI_BAND_5_GHZ_DFS_ONLY;
- /** 2.4 GHz band and 5 GHz band (no DFS channels) and 6 GHz */
- public static final int WIFI_BAND_24_5_6_GHZ = WIFI_BAND_BOTH | WIFI_BAND_6_GHZ;
- /** 2.4 GHz band and 5 GHz band; with DFS channels and 6 GHz */
- public static final int WIFI_BAND_24_5_WITH_DFS_6_GHZ =
- WIFI_BAND_BOTH_WITH_DFS | WIFI_BAND_6_GHZ;
- /** @hide */
- public static final int WIFI_BAND_24_5_6_60_GHZ =
- WIFI_BAND_24_5_6_GHZ | WIFI_BAND_60_GHZ;
- /** @hide */
- public static final int WIFI_BAND_24_5_WITH_DFS_6_60_GHZ =
- WIFI_BAND_24_5_6_60_GHZ | WIFI_BAND_5_GHZ_DFS_ONLY;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"WIFI_BAND_"}, value = {
- WIFI_BAND_UNSPECIFIED,
- WIFI_BAND_24_GHZ,
- WIFI_BAND_5_GHZ,
- WIFI_BAND_BOTH,
- WIFI_BAND_5_GHZ_DFS_ONLY,
- WIFI_BAND_24_GHZ_WITH_5GHZ_DFS,
- WIFI_BAND_5_GHZ_WITH_DFS,
- WIFI_BAND_BOTH_WITH_DFS,
- WIFI_BAND_6_GHZ,
- WIFI_BAND_24_5_6_GHZ,
- WIFI_BAND_24_5_WITH_DFS_6_GHZ,
- WIFI_BAND_60_GHZ,
- WIFI_BAND_24_5_6_60_GHZ,
- WIFI_BAND_24_5_WITH_DFS_6_60_GHZ})
- public @interface WifiBand {}
-
- /**
- * All bands
- * @hide
- */
- public static final int WIFI_BAND_ALL = (1 << WIFI_BAND_COUNT) - 1;
-
- /** Minimum supported scanning period */
- public static final int MIN_SCAN_PERIOD_MS = 1000;
- /** Maximum supported scanning period */
- public static final int MAX_SCAN_PERIOD_MS = 1024000;
-
- /** No Error */
- public static final int REASON_SUCCEEDED = 0;
- /** Unknown error */
- public static final int REASON_UNSPECIFIED = -1;
- /** Invalid listener */
- public static final int REASON_INVALID_LISTENER = -2;
- /** Invalid request */
- public static final int REASON_INVALID_REQUEST = -3;
- /** Invalid request */
- public static final int REASON_NOT_AUTHORIZED = -4;
- /** An outstanding request with the same listener hasn't finished yet. */
- public static final int REASON_DUPLICATE_REQEUST = -5;
-
- /** @hide */
- public static final String GET_AVAILABLE_CHANNELS_EXTRA = "Channels";
-
- /**
- * Generic action callback invocation interface
- * @hide
- */
- @SystemApi
- public static interface ActionListener {
- public void onSuccess();
- public void onFailure(int reason, String description);
- }
-
- /**
- * Test if scan is a full scan. i.e. scanning all available bands.
- * For backward compatibility, since some apps don't include 6GHz in their requests yet,
- * lacking 6GHz band does not cause the result to be false.
- *
- * @param bandScanned bands that are fully scanned
- * @param excludeDfs when true, DFS band is excluded from the check
- * @return true if all bands are scanned, false otherwise
- *
- * @hide
- */
- public static boolean isFullBandScan(@WifiBand int bandScanned, boolean excludeDfs) {
- return (bandScanned | WIFI_BAND_6_GHZ | WIFI_BAND_60_GHZ
- | (excludeDfs ? WIFI_BAND_5_GHZ_DFS_ONLY : 0))
- == WIFI_BAND_ALL;
- }
-
- /**
- * Returns a list of all the possible channels for the given band(s).
- *
- * @param band one of the WifiScanner#WIFI_BAND_* constants, e.g. {@link #WIFI_BAND_24_GHZ}
- * @return a list of all the frequencies, in MHz, for the given band(s) e.g. channel 1 is
- * 2412, or null if an error occurred.
- *
- * @hide
- */
- @SystemApi
- @NonNull
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public List<Integer> getAvailableChannels(int band) {
- try {
- Bundle bundle = mService.getAvailableChannels(band, mContext.getOpPackageName(),
- mContext.getAttributionTag());
- List<Integer> channels = bundle.getIntegerArrayList(GET_AVAILABLE_CHANNELS_EXTRA);
- return channels == null ? new ArrayList<>() : channels;
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * provides channel specification for scanning
- */
- public static class ChannelSpec {
- /**
- * channel frequency in MHz; for example channel 1 is specified as 2412
- */
- public int frequency;
- /**
- * if true, scan this channel in passive fashion.
- * This flag is ignored on DFS channel specification.
- * @hide
- */
- public boolean passive; /* ignored on DFS channels */
- /**
- * how long to dwell on this channel
- * @hide
- */
- public int dwellTimeMS; /* not supported for now */
-
- /**
- * default constructor for channel spec
- */
- public ChannelSpec(int frequency) {
- this.frequency = frequency;
- passive = false;
- dwellTimeMS = 0;
- }
- }
-
- /**
- * reports {@link ScanListener#onResults} when underlying buffers are full
- * this is simply the lack of the {@link #REPORT_EVENT_AFTER_EACH_SCAN} flag
- * @deprecated It is not supported anymore.
- */
- @Deprecated
- public static final int REPORT_EVENT_AFTER_BUFFER_FULL = 0;
- /**
- * reports {@link ScanListener#onResults} after each scan
- */
- public static final int REPORT_EVENT_AFTER_EACH_SCAN = (1 << 0);
- /**
- * reports {@link ScanListener#onFullResult} whenever each beacon is discovered
- */
- public static final int REPORT_EVENT_FULL_SCAN_RESULT = (1 << 1);
- /**
- * Do not place scans in the chip's scan history buffer
- */
- public static final int REPORT_EVENT_NO_BATCH = (1 << 2);
-
- /**
- * Optimize the scan for lower latency.
- * @see ScanSettings#type
- */
- public static final int SCAN_TYPE_LOW_LATENCY = 0;
- /**
- * Optimize the scan for lower power usage.
- * @see ScanSettings#type
- */
- public static final int SCAN_TYPE_LOW_POWER = 1;
- /**
- * Optimize the scan for higher accuracy.
- * @see ScanSettings#type
- */
- public static final int SCAN_TYPE_HIGH_ACCURACY = 2;
-
- /** {@hide} */
- public static final String SCAN_PARAMS_SCAN_SETTINGS_KEY = "ScanSettings";
- /** {@hide} */
- public static final String SCAN_PARAMS_WORK_SOURCE_KEY = "WorkSource";
- /** {@hide} */
- public static final String REQUEST_PACKAGE_NAME_KEY = "PackageName";
- /** {@hide} */
- public static final String REQUEST_FEATURE_ID_KEY = "FeatureId";
-
- /**
- * scan configuration parameters to be sent to {@link #startBackgroundScan}
- */
- public static class ScanSettings implements Parcelable {
- /** Hidden network to be scanned for. */
- public static class HiddenNetwork {
- /** SSID of the network */
- @NonNull
- public final String ssid;
-
- /** Default constructor for HiddenNetwork. */
- public HiddenNetwork(@NonNull String ssid) {
- this.ssid = ssid;
- }
- }
-
- /** one of the WIFI_BAND values */
- public int band;
- /** list of channels; used when band is set to WIFI_BAND_UNSPECIFIED */
- public ChannelSpec[] channels;
- /**
- * List of hidden networks to scan for. Explicit probe requests are sent out for such
- * networks during scan. Only valid for single scan requests.
- */
- @NonNull
- @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
- public final List<HiddenNetwork> hiddenNetworks = new ArrayList<>();
- /**
- * period of background scan; in millisecond, 0 => single shot scan
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int periodInMs;
- /**
- * must have a valid REPORT_EVENT value
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int reportEvents;
- /**
- * defines number of bssids to cache from each scan
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int numBssidsPerScan;
- /**
- * defines number of scans to cache; use it with REPORT_EVENT_AFTER_BUFFER_FULL
- * to wake up at fixed interval
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int maxScansToCache;
- /**
- * if maxPeriodInMs is non zero or different than period, then this bucket is
- * a truncated binary exponential backoff bucket and the scan period will grow
- * exponentially as per formula: actual_period(N) = period * (2 ^ (N/stepCount))
- * to maxPeriodInMs
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int maxPeriodInMs;
- /**
- * for truncated binary exponential back off bucket, number of scans to perform
- * for a given period
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public int stepCount;
- /**
- * Flag to indicate if the scan settings are targeted for PNO scan.
- * {@hide}
- */
- public boolean isPnoScan;
- /**
- * Indicate the type of scan to be performed by the wifi chip.
- *
- * On devices with multiple hardware radio chains (and hence different modes of scan),
- * this type serves as an indication to the hardware on what mode of scan to perform.
- * Only apps holding {@link android.Manifest.permission.NETWORK_STACK} permission can set
- * this value.
- *
- * Note: This serves as an intent and not as a stipulation, the wifi chip
- * might honor or ignore the indication based on the current radio conditions. Always
- * use the {@link ScanResult#radioChainInfos} to figure out the radio chain configuration
- * used to receive the corresponding scan result.
- *
- * One of {@link #SCAN_TYPE_LOW_LATENCY}, {@link #SCAN_TYPE_LOW_POWER},
- * {@link #SCAN_TYPE_HIGH_ACCURACY}.
- * Default value: {@link #SCAN_TYPE_LOW_LATENCY}.
- */
- @WifiAnnotations.ScanType
- @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
- public int type = SCAN_TYPE_LOW_LATENCY;
- /**
- * This scan request may ignore location settings while receiving scans. This should only
- * be used in emergency situations.
- * {@hide}
- */
- @SystemApi
- public boolean ignoreLocationSettings;
- /**
- * This scan request will be hidden from app-ops noting for location information. This
- * should only be used by FLP/NLP module on the device which is using the scan results to
- * compute results for behalf on their clients. FLP/NLP module using this flag should ensure
- * that they note in app-ops the eventual delivery of location information computed using
- * these results to their client .
- * {@hide}
- */
- @SystemApi
- public boolean hideFromAppOps;
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(band);
- dest.writeInt(periodInMs);
- dest.writeInt(reportEvents);
- dest.writeInt(numBssidsPerScan);
- dest.writeInt(maxScansToCache);
- dest.writeInt(maxPeriodInMs);
- dest.writeInt(stepCount);
- dest.writeInt(isPnoScan ? 1 : 0);
- dest.writeInt(type);
- dest.writeInt(ignoreLocationSettings ? 1 : 0);
- dest.writeInt(hideFromAppOps ? 1 : 0);
- if (channels != null) {
- dest.writeInt(channels.length);
- for (int i = 0; i < channels.length; i++) {
- dest.writeInt(channels[i].frequency);
- dest.writeInt(channels[i].dwellTimeMS);
- dest.writeInt(channels[i].passive ? 1 : 0);
- }
- } else {
- dest.writeInt(0);
- }
- dest.writeInt(hiddenNetworks.size());
- for (HiddenNetwork hiddenNetwork : hiddenNetworks) {
- dest.writeString(hiddenNetwork.ssid);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator<ScanSettings> CREATOR =
- new Creator<ScanSettings>() {
- public ScanSettings createFromParcel(Parcel in) {
- ScanSettings settings = new ScanSettings();
- settings.band = in.readInt();
- settings.periodInMs = in.readInt();
- settings.reportEvents = in.readInt();
- settings.numBssidsPerScan = in.readInt();
- settings.maxScansToCache = in.readInt();
- settings.maxPeriodInMs = in.readInt();
- settings.stepCount = in.readInt();
- settings.isPnoScan = in.readInt() == 1;
- settings.type = in.readInt();
- settings.ignoreLocationSettings = in.readInt() == 1;
- settings.hideFromAppOps = in.readInt() == 1;
- int num_channels = in.readInt();
- settings.channels = new ChannelSpec[num_channels];
- for (int i = 0; i < num_channels; i++) {
- int frequency = in.readInt();
- ChannelSpec spec = new ChannelSpec(frequency);
- spec.dwellTimeMS = in.readInt();
- spec.passive = in.readInt() == 1;
- settings.channels[i] = spec;
- }
- int numNetworks = in.readInt();
- settings.hiddenNetworks.clear();
- for (int i = 0; i < numNetworks; i++) {
- String ssid = in.readString();
- settings.hiddenNetworks.add(new HiddenNetwork(ssid));
- }
- return settings;
- }
-
- public ScanSettings[] newArray(int size) {
- return new ScanSettings[size];
- }
- };
- }
-
- /**
- * all the information garnered from a single scan
- */
- public static class ScanData implements Parcelable {
- /** scan identifier */
- private int mId;
- /** additional information about scan
- * 0 => no special issues encountered in the scan
- * non-zero => scan was truncated, so results may not be complete
- */
- private int mFlags;
- /**
- * Indicates the buckets that were scanned to generate these results.
- * This is not relevant to WifiScanner API users and is used internally.
- * {@hide}
- */
- private int mBucketsScanned;
- /**
- * Bands scanned. One of the WIFI_BAND values.
- * Will be {@link #WIFI_BAND_UNSPECIFIED} if the list of channels do not fully cover
- * any of the bands.
- * {@hide}
- */
- private int mBandScanned;
- /** all scan results discovered in this scan, sorted by timestamp in ascending order */
- private final List<ScanResult> mResults;
-
- ScanData() {
- mResults = new ArrayList<>();
- }
-
- public ScanData(int id, int flags, ScanResult[] results) {
- mId = id;
- mFlags = flags;
- mResults = new ArrayList<>(Arrays.asList(results));
- }
-
- /** {@hide} */
- public ScanData(int id, int flags, int bucketsScanned, int bandScanned,
- ScanResult[] results) {
- this(id, flags, bucketsScanned, bandScanned, new ArrayList<>(Arrays.asList(results)));
- }
-
- /** {@hide} */
- public ScanData(int id, int flags, int bucketsScanned, int bandScanned,
- List<ScanResult> results) {
- mId = id;
- mFlags = flags;
- mBucketsScanned = bucketsScanned;
- mBandScanned = bandScanned;
- mResults = results;
- }
-
- public ScanData(ScanData s) {
- mId = s.mId;
- mFlags = s.mFlags;
- mBucketsScanned = s.mBucketsScanned;
- mBandScanned = s.mBandScanned;
- mResults = new ArrayList<>();
- for (ScanResult scanResult : s.mResults) {
- mResults.add(new ScanResult(scanResult));
- }
- }
-
- public int getId() {
- return mId;
- }
-
- public int getFlags() {
- return mFlags;
- }
-
- /** {@hide} */
- public int getBucketsScanned() {
- return mBucketsScanned;
- }
-
- /** {@hide} */
- public int getBandScanned() {
- return mBandScanned;
- }
-
- public ScanResult[] getResults() {
- return mResults.toArray(new ScanResult[0]);
- }
-
- /** {@hide} */
- public void addResults(@NonNull ScanResult[] newResults) {
- for (ScanResult result : newResults) {
- mResults.add(new ScanResult(result));
- }
- }
-
- /** {@hide} */
- public void addResults(@NonNull ScanData s) {
- mBandScanned |= s.mBandScanned;
- mFlags |= s.mFlags;
- addResults(s.getResults());
- }
-
- /** {@hide} */
- public boolean isFullBandScanResults() {
- return (mBandScanned & WifiScanner.WIFI_BAND_24_GHZ) != 0
- && (mBandScanned & WifiScanner.WIFI_BAND_5_GHZ) != 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mId);
- dest.writeInt(mFlags);
- dest.writeInt(mBucketsScanned);
- dest.writeInt(mBandScanned);
- dest.writeParcelableList(mResults, 0);
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator<ScanData> CREATOR =
- new Creator<ScanData>() {
- public ScanData createFromParcel(Parcel in) {
- int id = in.readInt();
- int flags = in.readInt();
- int bucketsScanned = in.readInt();
- int bandScanned = in.readInt();
- List<ScanResult> results = new ArrayList<>();
- in.readParcelableList(results, ScanResult.class.getClassLoader());
- return new ScanData(id, flags, bucketsScanned, bandScanned, results);
- }
-
- public ScanData[] newArray(int size) {
- return new ScanData[size];
- }
- };
- }
-
- public static class ParcelableScanData implements Parcelable {
-
- public ScanData mResults[];
-
- public ParcelableScanData(ScanData[] results) {
- mResults = results;
- }
-
- public ScanData[] getResults() {
- return mResults;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- if (mResults != null) {
- dest.writeInt(mResults.length);
- for (int i = 0; i < mResults.length; i++) {
- ScanData result = mResults[i];
- result.writeToParcel(dest, flags);
- }
- } else {
- dest.writeInt(0);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator<ParcelableScanData> CREATOR =
- new Creator<ParcelableScanData>() {
- public ParcelableScanData createFromParcel(Parcel in) {
- int n = in.readInt();
- ScanData results[] = new ScanData[n];
- for (int i = 0; i < n; i++) {
- results[i] = ScanData.CREATOR.createFromParcel(in);
- }
- return new ParcelableScanData(results);
- }
-
- public ParcelableScanData[] newArray(int size) {
- return new ParcelableScanData[size];
- }
- };
- }
-
- public static class ParcelableScanResults implements Parcelable {
-
- public ScanResult mResults[];
-
- public ParcelableScanResults(ScanResult[] results) {
- mResults = results;
- }
-
- public ScanResult[] getResults() {
- return mResults;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- if (mResults != null) {
- dest.writeInt(mResults.length);
- for (int i = 0; i < mResults.length; i++) {
- ScanResult result = mResults[i];
- result.writeToParcel(dest, flags);
- }
- } else {
- dest.writeInt(0);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator<ParcelableScanResults> CREATOR =
- new Creator<ParcelableScanResults>() {
- public ParcelableScanResults createFromParcel(Parcel in) {
- int n = in.readInt();
- ScanResult results[] = new ScanResult[n];
- for (int i = 0; i < n; i++) {
- results[i] = ScanResult.CREATOR.createFromParcel(in);
- }
- return new ParcelableScanResults(results);
- }
-
- public ParcelableScanResults[] newArray(int size) {
- return new ParcelableScanResults[size];
- }
- };
- }
-
- /** {@hide} */
- public static final String PNO_PARAMS_PNO_SETTINGS_KEY = "PnoSettings";
- /** {@hide} */
- public static final String PNO_PARAMS_SCAN_SETTINGS_KEY = "ScanSettings";
- /**
- * PNO scan configuration parameters to be sent to {@link #startPnoScan}.
- * Note: This structure needs to be in sync with |wifi_epno_params| struct in gscan HAL API.
- * {@hide}
- */
- public static class PnoSettings implements Parcelable {
- /**
- * Pno network to be added to the PNO scan filtering.
- * {@hide}
- */
- public static class PnoNetwork {
- /*
- * Pno flags bitmask to be set in {@link #PnoNetwork.flags}
- */
- /** Whether directed scan needs to be performed (for hidden SSIDs) */
- public static final byte FLAG_DIRECTED_SCAN = (1 << 0);
- /** Whether PNO event shall be triggered if the network is found on A band */
- public static final byte FLAG_A_BAND = (1 << 1);
- /** Whether PNO event shall be triggered if the network is found on G band */
- public static final byte FLAG_G_BAND = (1 << 2);
- /**
- * Whether strict matching is required
- * If required then the firmware must store the network's SSID and not just a hash
- */
- public static final byte FLAG_STRICT_MATCH = (1 << 3);
- /**
- * If this SSID should be considered the same network as the currently connected
- * one for scoring.
- */
- public static final byte FLAG_SAME_NETWORK = (1 << 4);
-
- /*
- * Code for matching the beacon AUTH IE - additional codes. Bitmask to be set in
- * {@link #PnoNetwork.authBitField}
- */
- /** Open Network */
- public static final byte AUTH_CODE_OPEN = (1 << 0);
- /** WPA_PSK or WPA2PSK */
- public static final byte AUTH_CODE_PSK = (1 << 1);
- /** any EAPOL */
- public static final byte AUTH_CODE_EAPOL = (1 << 2);
-
- /** SSID of the network */
- public String ssid;
- /** Bitmask of the FLAG_XXX */
- public byte flags = 0;
- /** Bitmask of the ATUH_XXX */
- public byte authBitField = 0;
- /** frequencies on which the particular network needs to be scanned for */
- public int[] frequencies = {};
-
- /**
- * default constructor for PnoNetwork
- */
- public PnoNetwork(String ssid) {
- this.ssid = ssid;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(ssid, flags, authBitField);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof PnoNetwork)) {
- return false;
- }
- PnoNetwork lhs = (PnoNetwork) obj;
- return TextUtils.equals(this.ssid, lhs.ssid)
- && this.flags == lhs.flags
- && this.authBitField == lhs.authBitField;
- }
- }
-
- /** Connected vs Disconnected PNO flag {@hide} */
- public boolean isConnected;
- /** Minimum 5GHz RSSI for a BSSID to be considered */
- public int min5GHzRssi;
- /** Minimum 2.4GHz RSSI for a BSSID to be considered */
- public int min24GHzRssi;
- /** Minimum 6GHz RSSI for a BSSID to be considered */
- public int min6GHzRssi;
- /** Pno Network filter list */
- public PnoNetwork[] networkList;
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(isConnected ? 1 : 0);
- dest.writeInt(min5GHzRssi);
- dest.writeInt(min24GHzRssi);
- dest.writeInt(min6GHzRssi);
- if (networkList != null) {
- dest.writeInt(networkList.length);
- for (int i = 0; i < networkList.length; i++) {
- dest.writeString(networkList[i].ssid);
- dest.writeByte(networkList[i].flags);
- dest.writeByte(networkList[i].authBitField);
- dest.writeIntArray(networkList[i].frequencies);
- }
- } else {
- dest.writeInt(0);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator<PnoSettings> CREATOR =
- new Creator<PnoSettings>() {
- public PnoSettings createFromParcel(Parcel in) {
- PnoSettings settings = new PnoSettings();
- settings.isConnected = in.readInt() == 1;
- settings.min5GHzRssi = in.readInt();
- settings.min24GHzRssi = in.readInt();
- settings.min6GHzRssi = in.readInt();
- int numNetworks = in.readInt();
- settings.networkList = new PnoNetwork[numNetworks];
- for (int i = 0; i < numNetworks; i++) {
- String ssid = in.readString();
- PnoNetwork network = new PnoNetwork(ssid);
- network.flags = in.readByte();
- network.authBitField = in.readByte();
- network.frequencies = in.createIntArray();
- settings.networkList[i] = network;
- }
- return settings;
- }
-
- public PnoSettings[] newArray(int size) {
- return new PnoSettings[size];
- }
- };
-
- }
-
- /**
- * interface to get scan events on; specify this on {@link #startBackgroundScan} or
- * {@link #startScan}
- */
- public interface ScanListener extends ActionListener {
- /**
- * Framework co-ordinates scans across multiple apps; so it may not give exactly the
- * same period requested. If period of a scan is changed; it is reported by this event.
- * @deprecated Background scan support has always been hardware vendor dependent. This
- * support may not be present on newer devices. Use {@link #startScan(ScanSettings,
- * ScanListener)} instead for single scans.
- */
- @Deprecated
- public void onPeriodChanged(int periodInMs);
- /**
- * reports results retrieved from background scan and single shot scans
- */
- public void onResults(ScanData[] results);
- /**
- * reports full scan result for each access point found in scan
- */
- public void onFullResult(ScanResult fullScanResult);
- }
-
- /**
- * interface to get PNO scan events on; specify this on {@link #startDisconnectedPnoScan} and
- * {@link #startConnectedPnoScan}.
- * {@hide}
- */
- public interface PnoScanListener extends ScanListener {
- /**
- * Invoked when one of the PNO networks are found in scan results.
- */
- void onPnoNetworkFound(ScanResult[] results);
- }
-
- /**
- * Enable/Disable wifi scanning.
- *
- * @param enable set to true to enable scanning, set to false to disable all types of scanning.
- *
- * @see WifiManager#ACTION_WIFI_SCAN_AVAILABILITY_CHANGED
- * {@hide}
- */
- @SystemApi
- @RequiresPermission(Manifest.permission.NETWORK_STACK)
- public void setScanningEnabled(boolean enable) {
- validateChannel();
- mAsyncChannel.sendMessage(enable ? CMD_ENABLE : CMD_DISABLE);
- }
-
- /**
- * Register a listener that will receive results from all single scans.
- * Either the {@link ScanListener#onSuccess()} or {@link ScanListener#onFailure(int, String)}
- * method will be called once when the listener is registered.
- * Afterwards (assuming onSuccess was called), all subsequent single scan results will be
- * delivered to the listener. It is possible that onFullResult will not be called for all
- * results of the first scan if the listener was registered during the scan.
- *
- * @param executor the Executor on which to run the callback.
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this request, and must also be specified to cancel the request.
- * Multiple requests should also not share this object.
- */
- @RequiresPermission(Manifest.permission.NETWORK_STACK)
- public void registerScanListener(@NonNull @CallbackExecutor Executor executor,
- @NonNull ScanListener listener) {
- Objects.requireNonNull(executor, "executor cannot be null");
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = addListener(listener, executor);
- if (key == INVALID_KEY) return;
- validateChannel();
- mAsyncChannel.sendMessage(CMD_REGISTER_SCAN_LISTENER, 0, key);
- }
-
- /**
- * Overload of {@link #registerScanListener(Executor, ScanListener)} that executes the callback
- * synchronously.
- * @hide
- */
- @RequiresPermission(Manifest.permission.NETWORK_STACK)
- public void registerScanListener(@NonNull ScanListener listener) {
- registerScanListener(new SynchronousExecutor(), listener);
- }
-
- /**
- * Deregister a listener for ongoing single scans
- * @param listener specifies which scan to cancel; must be same object as passed in {@link
- * #registerScanListener}
- */
- public void unregisterScanListener(@NonNull ScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = removeListener(listener);
- if (key == INVALID_KEY) return;
- validateChannel();
- mAsyncChannel.sendMessage(CMD_DEREGISTER_SCAN_LISTENER, 0, key);
- }
-
- /** start wifi scan in background
- * @param settings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void startBackgroundScan(ScanSettings settings, ScanListener listener) {
- startBackgroundScan(settings, listener, null);
- }
-
- /** start wifi scan in background
- * @param settings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param workSource WorkSource to blame for power usage
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- * @deprecated Background scan support has always been hardware vendor dependent. This support
- * may not be present on newer devices. Use {@link #startScan(ScanSettings, ScanListener)}
- * instead for single scans.
- */
- @Deprecated
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void startBackgroundScan(ScanSettings settings, ScanListener listener,
- WorkSource workSource) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = addListener(listener);
- if (key == INVALID_KEY) return;
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putParcelable(SCAN_PARAMS_SCAN_SETTINGS_KEY, settings);
- scanParams.putParcelable(SCAN_PARAMS_WORK_SOURCE_KEY, workSource);
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- mAsyncChannel.sendMessage(CMD_START_BACKGROUND_SCAN, 0, key, scanParams);
- }
-
- /**
- * stop an ongoing wifi scan
- * @param listener specifies which scan to cancel; must be same object as passed in {@link
- * #startBackgroundScan}
- * @deprecated Background scan support has always been hardware vendor dependent. This support
- * may not be present on newer devices. Use {@link #startScan(ScanSettings, ScanListener)}
- * instead for single scans.
- */
- @Deprecated
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void stopBackgroundScan(ScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = removeListener(listener);
- if (key == INVALID_KEY) return;
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- mAsyncChannel.sendMessage(CMD_STOP_BACKGROUND_SCAN, 0, key, scanParams);
- }
-
- /**
- * reports currently available scan results on appropriate listeners
- * @return true if all scan results were reported correctly
- * @deprecated Background scan support has always been hardware vendor dependent. This support
- * may not be present on newer devices. Use {@link #startScan(ScanSettings, ScanListener)}
- * instead for single scans.
- */
- @Deprecated
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public boolean getScanResults() {
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- Message reply =
- mAsyncChannel.sendMessageSynchronously(CMD_GET_SCAN_RESULTS, 0, 0, scanParams);
- return reply.what == CMD_OP_SUCCEEDED;
- }
-
- /**
- * starts a single scan and reports results asynchronously
- * @param settings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void startScan(ScanSettings settings, ScanListener listener) {
- startScan(settings, listener, null);
- }
-
- /**
- * starts a single scan and reports results asynchronously
- * @param settings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- * @param workSource WorkSource to blame for power usage
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void startScan(ScanSettings settings, ScanListener listener, WorkSource workSource) {
- startScan(settings, null, listener, workSource);
- }
-
- /**
- * starts a single scan and reports results asynchronously
- * @param settings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param executor the Executor on which to run the callback.
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- * @param workSource WorkSource to blame for power usage
- * @hide
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void startScan(ScanSettings settings, @Nullable @CallbackExecutor Executor executor,
- ScanListener listener, WorkSource workSource) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = addListener(listener, executor);
- if (key == INVALID_KEY) return;
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putParcelable(SCAN_PARAMS_SCAN_SETTINGS_KEY, settings);
- scanParams.putParcelable(SCAN_PARAMS_WORK_SOURCE_KEY, workSource);
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- mAsyncChannel.sendMessage(CMD_START_SINGLE_SCAN, 0, key, scanParams);
- }
-
- /**
- * stops an ongoing single shot scan; only useful after {@link #startScan} if onResults()
- * hasn't been called on the listener, ignored otherwise
- * @param listener
- */
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public void stopScan(ScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = removeListener(listener);
- if (key == INVALID_KEY) return;
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- mAsyncChannel.sendMessage(CMD_STOP_SINGLE_SCAN, 0, key, scanParams);
- }
-
- /**
- * Retrieve the most recent scan results from a single scan request.
- */
- @NonNull
- @RequiresPermission(android.Manifest.permission.LOCATION_HARDWARE)
- public List<ScanResult> getSingleScanResults() {
- validateChannel();
- Bundle scanParams = new Bundle();
- scanParams.putString(REQUEST_PACKAGE_NAME_KEY, mContext.getOpPackageName());
- scanParams.putString(REQUEST_FEATURE_ID_KEY, mContext.getAttributionTag());
- Message reply = mAsyncChannel.sendMessageSynchronously(CMD_GET_SINGLE_SCAN_RESULTS, 0, 0,
- scanParams);
- if (reply.what == WifiScanner.CMD_OP_SUCCEEDED) {
- return Arrays.asList(((ParcelableScanResults) reply.obj).getResults());
- }
- OperationResult result = (OperationResult) reply.obj;
- Log.e(TAG, "Error retrieving SingleScan results reason: " + result.reason
- + " description: " + result.description);
- return new ArrayList<>();
- }
-
- private void startPnoScan(ScanSettings scanSettings, PnoSettings pnoSettings, int key) {
- // Bundle up both the settings and send it across.
- Bundle pnoParams = new Bundle();
- // Set the PNO scan flag.
- scanSettings.isPnoScan = true;
- pnoParams.putParcelable(PNO_PARAMS_SCAN_SETTINGS_KEY, scanSettings);
- pnoParams.putParcelable(PNO_PARAMS_PNO_SETTINGS_KEY, pnoSettings);
- mAsyncChannel.sendMessage(CMD_START_PNO_SCAN, 0, key, pnoParams);
- }
- /**
- * Start wifi connected PNO scan
- * @param scanSettings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param pnoSettings specifies various parameters for PNO; for more information look at
- * {@link PnoSettings}
- * @param executor the Executor on which to run the callback.
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- * {@hide}
- */
- public void startConnectedPnoScan(ScanSettings scanSettings, PnoSettings pnoSettings,
- @NonNull @CallbackExecutor Executor executor, PnoScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- Objects.requireNonNull(pnoSettings, "pnoSettings cannot be null");
- int key = addListener(listener, executor);
- if (key == INVALID_KEY) return;
- validateChannel();
- pnoSettings.isConnected = true;
- startPnoScan(scanSettings, pnoSettings, key);
- }
- /**
- * Start wifi disconnected PNO scan
- * @param scanSettings specifies various parameters for the scan; for more information look at
- * {@link ScanSettings}
- * @param pnoSettings specifies various parameters for PNO; for more information look at
- * {@link PnoSettings}
- * @param listener specifies the object to report events to. This object is also treated as a
- * key for this scan, and must also be specified to cancel the scan. Multiple
- * scans should also not share this object.
- * {@hide}
- */
- @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
- public void startDisconnectedPnoScan(ScanSettings scanSettings, PnoSettings pnoSettings,
- @NonNull @CallbackExecutor Executor executor, PnoScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- Objects.requireNonNull(pnoSettings, "pnoSettings cannot be null");
- int key = addListener(listener, executor);
- if (key == INVALID_KEY) return;
- validateChannel();
- pnoSettings.isConnected = false;
- startPnoScan(scanSettings, pnoSettings, key);
- }
- /**
- * Stop an ongoing wifi PNO scan
- * @param listener specifies which scan to cancel; must be same object as passed in {@link
- * #startPnoScan}
- * {@hide}
- */
- @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
- public void stopPnoScan(ScanListener listener) {
- Objects.requireNonNull(listener, "listener cannot be null");
- int key = removeListener(listener);
- if (key == INVALID_KEY) return;
- validateChannel();
- mAsyncChannel.sendMessage(CMD_STOP_PNO_SCAN, 0, key);
- }
-
- /** specifies information about an access point of interest */
- @Deprecated
- public static class BssidInfo {
- /** bssid of the access point; in XX:XX:XX:XX:XX:XX format */
- public String bssid;
- /** low signal strength threshold; more information at {@link ScanResult#level} */
- public int low; /* minimum RSSI */
- /** high signal threshold; more information at {@link ScanResult#level} */
- public int high; /* maximum RSSI */
- /** channel frequency (in KHz) where you may find this BSSID */
- public int frequencyHint;
- }
-
- /** @hide */
- @SystemApi
- @Deprecated
- public static class WifiChangeSettings implements Parcelable {
- public int rssiSampleSize; /* sample size for RSSI averaging */
- public int lostApSampleSize; /* samples to confirm AP's loss */
- public int unchangedSampleSize; /* samples to confirm no change */
- public int minApsBreachingThreshold; /* change threshold to trigger event */
- public int periodInMs; /* scan period in millisecond */
- public BssidInfo[] bssidInfos;
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator<WifiChangeSettings> CREATOR =
- new Creator<WifiChangeSettings>() {
- public WifiChangeSettings createFromParcel(Parcel in) {
- return new WifiChangeSettings();
- }
-
- public WifiChangeSettings[] newArray(int size) {
- return new WifiChangeSettings[size];
- }
- };
-
- }
-
- /** configure WifiChange detection
- * @param rssiSampleSize number of samples used for RSSI averaging
- * @param lostApSampleSize number of samples to confirm an access point's loss
- * @param unchangedSampleSize number of samples to confirm there are no changes
- * @param minApsBreachingThreshold minimum number of access points that need to be
- * out of range to detect WifiChange
- * @param periodInMs indicates period of scan to find changes
- * @param bssidInfos access points to watch
- */
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void configureWifiChange(
- int rssiSampleSize, /* sample size for RSSI averaging */
- int lostApSampleSize, /* samples to confirm AP's loss */
- int unchangedSampleSize, /* samples to confirm no change */
- int minApsBreachingThreshold, /* change threshold to trigger event */
- int periodInMs, /* period of scan */
- BssidInfo[] bssidInfos /* signal thresholds to cross */
- )
- {
- throw new UnsupportedOperationException();
- }
-
- /**
- * interface to get wifi change events on; use this on {@link #startTrackingWifiChange}
- */
- @Deprecated
- public interface WifiChangeListener extends ActionListener {
- /** indicates that changes were detected in wifi environment
- * @param results indicate the access points that exhibited change
- */
- public void onChanging(ScanResult[] results); /* changes are found */
- /** indicates that no wifi changes are being detected for a while
- * @param results indicate the access points that are bing monitored for change
- */
- public void onQuiescence(ScanResult[] results); /* changes settled down */
- }
-
- /**
- * track changes in wifi environment
- * @param listener object to report events on; this object must be unique and must also be
- * provided on {@link #stopTrackingWifiChange}
- */
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void startTrackingWifiChange(WifiChangeListener listener) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * stop tracking changes in wifi environment
- * @param listener object that was provided to report events on {@link
- * #stopTrackingWifiChange}
- */
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void stopTrackingWifiChange(WifiChangeListener listener) {
- throw new UnsupportedOperationException();
- }
-
- /** @hide */
- @SystemApi
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void configureWifiChange(WifiChangeSettings settings) {
- throw new UnsupportedOperationException();
- }
-
- /** interface to receive hotlist events on; use this on {@link #setHotlist} */
- @Deprecated
- public static interface BssidListener extends ActionListener {
- /** indicates that access points were found by on going scans
- * @param results list of scan results, one for each access point visible currently
- */
- public void onFound(ScanResult[] results);
- /** indicates that access points were missed by on going scans
- * @param results list of scan results, for each access point that is not visible anymore
- */
- public void onLost(ScanResult[] results);
- }
-
- /** @hide */
- @SystemApi
- @Deprecated
- public static class HotlistSettings implements Parcelable {
- public BssidInfo[] bssidInfos;
- public int apLostThreshold;
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator<HotlistSettings> CREATOR =
- new Creator<HotlistSettings>() {
- public HotlistSettings createFromParcel(Parcel in) {
- HotlistSettings settings = new HotlistSettings();
- return settings;
- }
-
- public HotlistSettings[] newArray(int size) {
- return new HotlistSettings[size];
- }
- };
- }
-
- /**
- * set interesting access points to find
- * @param bssidInfos access points of interest
- * @param apLostThreshold number of scans needed to indicate that AP is lost
- * @param listener object provided to report events on; this object must be unique and must
- * also be provided on {@link #stopTrackingBssids}
- */
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void startTrackingBssids(BssidInfo[] bssidInfos,
- int apLostThreshold, BssidListener listener) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * remove tracking of interesting access points
- * @param listener same object provided in {@link #startTrackingBssids}
- */
- @Deprecated
- @SuppressLint("RequiresPermission")
- public void stopTrackingBssids(BssidListener listener) {
- throw new UnsupportedOperationException();
- }
-
-
- /* private members and methods */
-
- private static final String TAG = "WifiScanner";
- private static final boolean DBG = false;
-
- /* commands for Wifi Service */
- private static final int BASE = Protocol.BASE_WIFI_SCANNER;
-
- /** @hide */
- public static final int CMD_START_BACKGROUND_SCAN = BASE + 2;
- /** @hide */
- public static final int CMD_STOP_BACKGROUND_SCAN = BASE + 3;
- /** @hide */
- public static final int CMD_GET_SCAN_RESULTS = BASE + 4;
- /** @hide */
- public static final int CMD_SCAN_RESULT = BASE + 5;
- /** @hide */
- public static final int CMD_OP_SUCCEEDED = BASE + 17;
- /** @hide */
- public static final int CMD_OP_FAILED = BASE + 18;
- /** @hide */
- public static final int CMD_FULL_SCAN_RESULT = BASE + 20;
- /** @hide */
- public static final int CMD_START_SINGLE_SCAN = BASE + 21;
- /** @hide */
- public static final int CMD_STOP_SINGLE_SCAN = BASE + 22;
- /** @hide */
- public static final int CMD_SINGLE_SCAN_COMPLETED = BASE + 23;
- /** @hide */
- public static final int CMD_START_PNO_SCAN = BASE + 24;
- /** @hide */
- public static final int CMD_STOP_PNO_SCAN = BASE + 25;
- /** @hide */
- public static final int CMD_PNO_NETWORK_FOUND = BASE + 26;
- /** @hide */
- public static final int CMD_REGISTER_SCAN_LISTENER = BASE + 27;
- /** @hide */
- public static final int CMD_DEREGISTER_SCAN_LISTENER = BASE + 28;
- /** @hide */
- public static final int CMD_GET_SINGLE_SCAN_RESULTS = BASE + 29;
- /** @hide */
- public static final int CMD_ENABLE = BASE + 30;
- /** @hide */
- public static final int CMD_DISABLE = BASE + 31;
-
- private Context mContext;
- private IWifiScanner mService;
-
- private static final int INVALID_KEY = 0;
- private int mListenerKey = 1;
-
- private final SparseArray mListenerMap = new SparseArray();
- private final SparseArray<Executor> mExecutorMap = new SparseArray<>();
- private final Object mListenerMapLock = new Object();
-
- private AsyncChannel mAsyncChannel;
- private final Handler mInternalHandler;
-
- /**
- * Create a new WifiScanner instance.
- * Applications will almost always want to use
- * {@link android.content.Context#getSystemService Context.getSystemService()} to retrieve
- * the standard {@link android.content.Context#WIFI_SERVICE Context.WIFI_SERVICE}.
- *
- * @param context the application context
- * @param service the Binder interface for {@link Context#WIFI_SCANNING_SERVICE}
- * @param looper the Looper used to deliver callbacks
- *
- * @hide
- */
- public WifiScanner(@NonNull Context context, @NonNull IWifiScanner service,
- @NonNull Looper looper) {
- mContext = context;
- mService = service;
-
- Messenger messenger = null;
- try {
- messenger = mService.getMessenger();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
-
- if (messenger == null) {
- throw new IllegalStateException("getMessenger() returned null! This is invalid.");
- }
-
- mAsyncChannel = new AsyncChannel();
-
- mInternalHandler = new ServiceHandler(looper);
- mAsyncChannel.connectSync(mContext, mInternalHandler, messenger);
- // We cannot use fullyConnectSync because it sends the FULL_CONNECTION message
- // synchronously, which causes WifiScanningService to receive the wrong replyTo value.
- mAsyncChannel.sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
- }
-
- private void validateChannel() {
- if (mAsyncChannel == null) throw new IllegalStateException(
- "No permission to access and change wifi or a bad initialization");
- }
-
- private int addListener(ActionListener listener) {
- return addListener(listener, null);
- }
-
- // Add a listener into listener map. If the listener already exists, return INVALID_KEY and
- // send an error message to internal handler; Otherwise add the listener to the listener map and
- // return the key of the listener.
- private int addListener(ActionListener listener, Executor executor) {
- synchronized (mListenerMapLock) {
- boolean keyExists = (getListenerKey(listener) != INVALID_KEY);
- // Note we need to put the listener into listener map even if it's a duplicate as the
- // internal handler will need the key to find the listener. In case of duplicates,
- // removing duplicate key logic will be handled in internal handler.
- int key = putListener(listener);
- if (keyExists) {
- if (DBG) Log.d(TAG, "listener key already exists");
- OperationResult operationResult = new OperationResult(REASON_DUPLICATE_REQEUST,
- "Outstanding request with same key not stopped yet");
- Message message = Message.obtain(mInternalHandler, CMD_OP_FAILED, 0, key,
- operationResult);
- message.sendToTarget();
- return INVALID_KEY;
- } else {
- mExecutorMap.put(key, executor);
- return key;
- }
- }
- }
-
- private int putListener(Object listener) {
- if (listener == null) return INVALID_KEY;
- int key;
- synchronized (mListenerMapLock) {
- do {
- key = mListenerKey++;
- } while (key == INVALID_KEY);
- mListenerMap.put(key, listener);
- }
- return key;
- }
-
- private static class ListenerWithExecutor {
- @Nullable final Object mListener;
- @Nullable final Executor mExecutor;
-
- ListenerWithExecutor(@Nullable Object listener, @Nullable Executor executor) {
- mListener = listener;
- mExecutor = executor;
- }
- }
-
- private ListenerWithExecutor getListenerWithExecutor(int key) {
- if (key == INVALID_KEY) return new ListenerWithExecutor(null, null);
- synchronized (mListenerMapLock) {
- Object listener = mListenerMap.get(key);
- Executor executor = mExecutorMap.get(key);
- return new ListenerWithExecutor(listener, executor);
- }
- }
-
- private int getListenerKey(Object listener) {
- if (listener == null) return INVALID_KEY;
- synchronized (mListenerMapLock) {
- int index = mListenerMap.indexOfValue(listener);
- if (index == -1) {
- return INVALID_KEY;
- } else {
- return mListenerMap.keyAt(index);
- }
- }
- }
-
- private Object removeListener(int key) {
- if (key == INVALID_KEY) return null;
- synchronized (mListenerMapLock) {
- Object listener = mListenerMap.get(key);
- mListenerMap.remove(key);
- mExecutorMap.remove(key);
- return listener;
- }
- }
-
- private int removeListener(Object listener) {
- int key = getListenerKey(listener);
- if (key == INVALID_KEY) {
- Log.e(TAG, "listener cannot be found");
- return key;
- }
- synchronized (mListenerMapLock) {
- mListenerMap.remove(key);
- mExecutorMap.remove(key);
- return key;
- }
- }
-
- /** @hide */
- public static class OperationResult implements Parcelable {
- public int reason;
- public String description;
-
- public OperationResult(int reason, String description) {
- this.reason = reason;
- this.description = description;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(reason);
- dest.writeString(description);
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @NonNull Creator<OperationResult> CREATOR =
- new Creator<OperationResult>() {
- public OperationResult createFromParcel(Parcel in) {
- int reason = in.readInt();
- String description = in.readString();
- return new OperationResult(reason, description);
- }
-
- public OperationResult[] newArray(int size) {
- return new OperationResult[size];
- }
- };
- }
-
- private class ServiceHandler extends Handler {
- ServiceHandler(Looper looper) {
- super(looper);
- }
- @Override
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED:
- return;
- case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
- Log.e(TAG, "Channel connection lost");
- // This will cause all further async API calls on the WifiManager
- // to fail and throw an exception
- mAsyncChannel = null;
- getLooper().quit();
- return;
- }
-
- ListenerWithExecutor listenerWithExecutor = getListenerWithExecutor(msg.arg2);
- Object listener = listenerWithExecutor.mListener;
-
- if (listener == null) {
- if (DBG) Log.d(TAG, "invalid listener key = " + msg.arg2);
- return;
- } else {
- if (DBG) Log.d(TAG, "listener key = " + msg.arg2);
- }
-
- Executor executor = listenerWithExecutor.mExecutor;
- if (executor == null) {
- executor = new SynchronousExecutor();
- }
-
- switch (msg.what) {
- /* ActionListeners grouped together */
- case CMD_OP_SUCCEEDED: {
- ActionListener actionListener = (ActionListener) listener;
- Binder.clearCallingIdentity();
- executor.execute(actionListener::onSuccess);
- } break;
- case CMD_OP_FAILED: {
- OperationResult result = (OperationResult) msg.obj;
- ActionListener actionListener = (ActionListener) listener;
- removeListener(msg.arg2);
- Binder.clearCallingIdentity();
- executor.execute(() ->
- actionListener.onFailure(result.reason, result.description));
- } break;
- case CMD_SCAN_RESULT: {
- ScanListener scanListener = (ScanListener) listener;
- ParcelableScanData parcelableScanData = (ParcelableScanData) msg.obj;
- Binder.clearCallingIdentity();
- executor.execute(() -> scanListener.onResults(parcelableScanData.getResults()));
- } break;
- case CMD_FULL_SCAN_RESULT: {
- ScanResult result = (ScanResult) msg.obj;
- ScanListener scanListener = ((ScanListener) listener);
- Binder.clearCallingIdentity();
- executor.execute(() -> scanListener.onFullResult(result));
- } break;
- case CMD_SINGLE_SCAN_COMPLETED: {
- if (DBG) Log.d(TAG, "removing listener for single scan");
- removeListener(msg.arg2);
- } break;
- case CMD_PNO_NETWORK_FOUND: {
- PnoScanListener pnoScanListener = (PnoScanListener) listener;
- ParcelableScanResults parcelableScanResults = (ParcelableScanResults) msg.obj;
- Binder.clearCallingIdentity();
- executor.execute(() ->
- pnoScanListener.onPnoNetworkFound(parcelableScanResults.getResults()));
- } break;
- default: {
- if (DBG) Log.d(TAG, "Ignoring message " + msg.what);
- } break;
- }
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/WifiSsid.java b/wifi/java/android/net/wifi/WifiSsid.java
deleted file mode 100644
index 704ae81f71aa..000000000000
--- a/wifi/java/android/net/wifi/WifiSsid.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*
- * Copyright (C) 2012 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.annotation.NonNull;
-import android.annotation.Nullable;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.io.ByteArrayOutputStream;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetDecoder;
-import java.nio.charset.CoderResult;
-import java.nio.charset.CodingErrorAction;
-import java.util.Arrays;
-import java.util.Locale;
-
-/**
- * Stores SSID octets and handles conversion.
- *
- * For Ascii encoded string, any octet < 32 or > 127 is encoded as
- * a "\x" followed by the hex representation of the octet.
- * Exception chars are ", \, \e, \n, \r, \t which are escaped by a \
- * See src/utils/common.c for the implementation in the supplicant.
- *
- * @hide
- */
-public final class WifiSsid implements Parcelable {
- private static final String TAG = "WifiSsid";
-
- @UnsupportedAppUsage
- public final ByteArrayOutputStream octets = new ByteArrayOutputStream(32);
-
- private static final int HEX_RADIX = 16;
-
- @UnsupportedAppUsage
- public static final String NONE = WifiManager.UNKNOWN_SSID;
-
- private WifiSsid() {
- }
-
- /**
- * Create a WifiSsid from a raw byte array. If the byte array is null, return an empty WifiSsid
- * object.
- */
- @NonNull
- public static WifiSsid createFromByteArray(@Nullable byte[] ssid) {
- WifiSsid wifiSsid = new WifiSsid();
- if (ssid != null) {
- wifiSsid.octets.write(ssid, 0 /* the start offset */, ssid.length);
- }
- return wifiSsid;
- }
-
- @UnsupportedAppUsage
- public static WifiSsid createFromAsciiEncoded(String asciiEncoded) {
- WifiSsid a = new WifiSsid();
- a.convertToBytes(asciiEncoded);
- return a;
- }
-
- public static WifiSsid createFromHex(String hexStr) {
- WifiSsid a = new WifiSsid();
- if (hexStr == null) return a;
-
- if (hexStr.startsWith("0x") || hexStr.startsWith("0X")) {
- hexStr = hexStr.substring(2);
- }
-
- for (int i = 0; i < hexStr.length()-1; i += 2) {
- int val;
- try {
- val = Integer.parseInt(hexStr.substring(i, i + 2), HEX_RADIX);
- } catch(NumberFormatException e) {
- val = 0;
- }
- a.octets.write(val);
- }
- return a;
- }
-
- /* This function is equivalent to printf_decode() at src/utils/common.c in
- * the supplicant */
- private void convertToBytes(String asciiEncoded) {
- int i = 0;
- int val = 0;
- while (i< asciiEncoded.length()) {
- char c = asciiEncoded.charAt(i);
- switch (c) {
- case '\\':
- i++;
- switch(asciiEncoded.charAt(i)) {
- case '\\':
- octets.write('\\');
- i++;
- break;
- case '"':
- octets.write('"');
- i++;
- break;
- case 'n':
- octets.write('\n');
- i++;
- break;
- case 'r':
- octets.write('\r');
- i++;
- break;
- case 't':
- octets.write('\t');
- i++;
- break;
- case 'e':
- octets.write(27); //escape char
- i++;
- break;
- case 'x':
- i++;
- try {
- val = Integer.parseInt(asciiEncoded.substring(i, i + 2), HEX_RADIX);
- } catch (NumberFormatException e) {
- val = -1;
- } catch (StringIndexOutOfBoundsException e) {
- val = -1;
- }
- if (val < 0) {
- val = Character.digit(asciiEncoded.charAt(i), HEX_RADIX);
- if (val < 0) break;
- octets.write(val);
- i++;
- } else {
- octets.write(val);
- i += 2;
- }
- break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- val = asciiEncoded.charAt(i) - '0';
- i++;
- if (asciiEncoded.charAt(i) >= '0' && asciiEncoded.charAt(i) <= '7') {
- val = val * 8 + asciiEncoded.charAt(i) - '0';
- i++;
- }
- if (asciiEncoded.charAt(i) >= '0' && asciiEncoded.charAt(i) <= '7') {
- val = val * 8 + asciiEncoded.charAt(i) - '0';
- i++;
- }
- octets.write(val);
- break;
- default:
- break;
- }
- break;
- default:
- octets.write(c);
- i++;
- break;
- }
- }
- }
-
- /**
- * Converts this SSID to an unquoted UTF-8 String representation.
- * @return the SSID string, or {@link WifiManager#UNKNOWN_SSID} if there was an error.
- */
- @Override
- public String toString() {
- byte[] ssidBytes = octets.toByteArray();
- // Supplicant returns \x00\x00\x00\x00\x00\x00\x00\x00 hex string
- // for a hidden access point. Make sure we maintain the previous
- // behavior of returning empty string for this case.
- if (octets.size() <= 0 || isArrayAllZeroes(ssidBytes)) return "";
- // TODO: Handle conversion to other charsets upon failure
- Charset charset = Charset.forName("UTF-8");
- CharsetDecoder decoder = charset.newDecoder()
- .onMalformedInput(CodingErrorAction.REPLACE)
- .onUnmappableCharacter(CodingErrorAction.REPLACE);
- CharBuffer out = CharBuffer.allocate(32);
-
- CoderResult result = decoder.decode(ByteBuffer.wrap(ssidBytes), out, true);
- out.flip();
- if (result.isError()) {
- return WifiManager.UNKNOWN_SSID;
- }
- return out.toString();
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof WifiSsid)) {
- return false;
- }
- WifiSsid that = (WifiSsid) thatObject;
- return Arrays.equals(octets.toByteArray(), that.octets.toByteArray());
- }
-
- @Override
- public int hashCode() {
- return Arrays.hashCode(octets.toByteArray());
- }
-
- private boolean isArrayAllZeroes(byte[] ssidBytes) {
- for (int i = 0; i< ssidBytes.length; i++) {
- if (ssidBytes[i] != 0) return false;
- }
- return true;
- }
-
- /** @hide */
- public boolean isHidden() {
- return isArrayAllZeroes(octets.toByteArray());
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public byte[] getOctets() {
- return octets.toByteArray();
- }
-
- /** @hide */
- public String getHexString() {
- String out = "0x";
- byte[] ssidbytes = getOctets();
- for (int i = 0; i < octets.size(); i++) {
- out += String.format(Locale.US, "%02x", ssidbytes[i]);
- }
- return (octets.size() > 0) ? out : null;
- }
-
- /** Implement the Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface */
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeInt(octets.size());
- dest.writeByteArray(octets.toByteArray());
- }
-
- /** Implement the Parcelable interface */
- @UnsupportedAppUsage
- public static final @NonNull Creator<WifiSsid> CREATOR =
- new Creator<WifiSsid>() {
- @Override
- public WifiSsid createFromParcel(Parcel in) {
- WifiSsid ssid = new WifiSsid();
- int length = in.readInt();
- byte[] b = new byte[length];
- in.readByteArray(b);
- ssid.octets.write(b, 0, length);
- return ssid;
- }
-
- @Override
- public WifiSsid[] newArray(int size) {
- return new WifiSsid[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java b/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
deleted file mode 100644
index 8f3635fd2f04..000000000000
--- a/wifi/java/android/net/wifi/WifiUsabilityStatsEntry.java
+++ /dev/null
@@ -1,351 +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 android.net.wifi;
-
-import android.annotation.IntDef;
-import android.annotation.SystemApi;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import android.telephony.Annotation.NetworkType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-/**
- * This class makes a subset of
- * com.android.server.wifi.nano.WifiMetricsProto.WifiUsabilityStatsEntry parcelable.
- *
- * @hide
- */
-@SystemApi
-public final class WifiUsabilityStatsEntry implements Parcelable {
- /** {@hide} */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"PROBE_STATUS_"}, value = {
- PROBE_STATUS_UNKNOWN,
- PROBE_STATUS_NO_PROBE,
- PROBE_STATUS_SUCCESS,
- PROBE_STATUS_FAILURE})
- public @interface ProbeStatus {}
-
- /** Link probe status is unknown */
- public static final int PROBE_STATUS_UNKNOWN = 0;
- /** Link probe is not triggered */
- public static final int PROBE_STATUS_NO_PROBE = 1;
- /** Link probe is triggered and the result is success */
- public static final int PROBE_STATUS_SUCCESS = 2;
- /** Link probe is triggered and the result is failure */
- public static final int PROBE_STATUS_FAILURE = 3;
-
- /** Absolute milliseconds from device boot when these stats were sampled */
- private final long mTimeStampMillis;
- /** The RSSI (in dBm) at the sample time */
- private final int mRssi;
- /** Link speed at the sample time in Mbps */
- private final int mLinkSpeedMbps;
- /** The total number of tx success counted from the last radio chip reset */
- private final long mTotalTxSuccess;
- /** The total number of MPDU data packet retries counted from the last radio chip reset */
- private final long mTotalTxRetries;
- /** The total number of tx bad counted from the last radio chip reset */
- private final long mTotalTxBad;
- /** The total number of rx success counted from the last radio chip reset */
- private final long mTotalRxSuccess;
- /** The total time the wifi radio is on in ms counted from the last radio chip reset */
- private final long mTotalRadioOnTimeMillis;
- /** The total time the wifi radio is doing tx in ms counted from the last radio chip reset */
- private final long mTotalRadioTxTimeMillis;
- /** The total time the wifi radio is doing rx in ms counted from the last radio chip reset */
- private final long mTotalRadioRxTimeMillis;
- /** The total time spent on all types of scans in ms counted from the last radio chip reset */
- private final long mTotalScanTimeMillis;
- /** The total time spent on nan scans in ms counted from the last radio chip reset */
- private final long mTotalNanScanTimeMillis;
- /** The total time spent on background scans in ms counted from the last radio chip reset */
- private final long mTotalBackgroundScanTimeMillis;
- /** The total time spent on roam scans in ms counted from the last radio chip reset */
- private final long mTotalRoamScanTimeMillis;
- /** The total time spent on pno scans in ms counted from the last radio chip reset */
- private final long mTotalPnoScanTimeMillis;
- /** The total time spent on hotspot2.0 scans and GAS exchange in ms counted from the last radio
- * chip reset */
- private final long mTotalHotspot2ScanTimeMillis;
- /** The total time CCA is on busy status on the current frequency in ms counted from the last
- * radio chip reset */
- private final long mTotalCcaBusyFreqTimeMillis;
- /** The total radio on time on the current frequency from the last radio chip reset */
- private final long mTotalRadioOnFreqTimeMillis;
- /** The total number of beacons received from the last radio chip reset */
- private final long mTotalBeaconRx;
- /** The status of link probe since last stats update */
- @ProbeStatus private final int mProbeStatusSinceLastUpdate;
- /** The elapsed time of the most recent link probe since last stats update */
- private final int mProbeElapsedTimeSinceLastUpdateMillis;
- /** The MCS rate of the most recent link probe since last stats update */
- private final int mProbeMcsRateSinceLastUpdate;
- /** Rx link speed at the sample time in Mbps */
- private final int mRxLinkSpeedMbps;
- private final @NetworkType int mCellularDataNetworkType;
- private final int mCellularSignalStrengthDbm;
- private final int mCellularSignalStrengthDb;
- private final boolean mIsSameRegisteredCell;
-
- /** Constructor function {@hide} */
- public WifiUsabilityStatsEntry(long timeStampMillis, int rssi, int linkSpeedMbps,
- long totalTxSuccess, long totalTxRetries, long totalTxBad, long totalRxSuccess,
- long totalRadioOnTimeMillis, long totalRadioTxTimeMillis, long totalRadioRxTimeMillis,
- long totalScanTimeMillis, long totalNanScanTimeMillis,
- long totalBackgroundScanTimeMillis,
- long totalRoamScanTimeMillis, long totalPnoScanTimeMillis,
- long totalHotspot2ScanTimeMillis,
- long totalCcaBusyFreqTimeMillis, long totalRadioOnFreqTimeMillis, long totalBeaconRx,
- @ProbeStatus int probeStatusSinceLastUpdate, int probeElapsedTimeSinceLastUpdateMillis,
- int probeMcsRateSinceLastUpdate, int rxLinkSpeedMbps,
- @NetworkType int cellularDataNetworkType,
- int cellularSignalStrengthDbm, int cellularSignalStrengthDb,
- boolean isSameRegisteredCell) {
- mTimeStampMillis = timeStampMillis;
- mRssi = rssi;
- mLinkSpeedMbps = linkSpeedMbps;
- mTotalTxSuccess = totalTxSuccess;
- mTotalTxRetries = totalTxRetries;
- mTotalTxBad = totalTxBad;
- mTotalRxSuccess = totalRxSuccess;
- mTotalRadioOnTimeMillis = totalRadioOnTimeMillis;
- mTotalRadioTxTimeMillis = totalRadioTxTimeMillis;
- mTotalRadioRxTimeMillis = totalRadioRxTimeMillis;
- mTotalScanTimeMillis = totalScanTimeMillis;
- mTotalNanScanTimeMillis = totalNanScanTimeMillis;
- mTotalBackgroundScanTimeMillis = totalBackgroundScanTimeMillis;
- mTotalRoamScanTimeMillis = totalRoamScanTimeMillis;
- mTotalPnoScanTimeMillis = totalPnoScanTimeMillis;
- mTotalHotspot2ScanTimeMillis = totalHotspot2ScanTimeMillis;
- mTotalCcaBusyFreqTimeMillis = totalCcaBusyFreqTimeMillis;
- mTotalRadioOnFreqTimeMillis = totalRadioOnFreqTimeMillis;
- mTotalBeaconRx = totalBeaconRx;
- mProbeStatusSinceLastUpdate = probeStatusSinceLastUpdate;
- mProbeElapsedTimeSinceLastUpdateMillis = probeElapsedTimeSinceLastUpdateMillis;
- mProbeMcsRateSinceLastUpdate = probeMcsRateSinceLastUpdate;
- mRxLinkSpeedMbps = rxLinkSpeedMbps;
- mCellularDataNetworkType = cellularDataNetworkType;
- mCellularSignalStrengthDbm = cellularSignalStrengthDbm;
- mCellularSignalStrengthDb = cellularSignalStrengthDb;
- mIsSameRegisteredCell = isSameRegisteredCell;
- }
-
- /** Implement the Parcelable interface */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeLong(mTimeStampMillis);
- dest.writeInt(mRssi);
- dest.writeInt(mLinkSpeedMbps);
- dest.writeLong(mTotalTxSuccess);
- dest.writeLong(mTotalTxRetries);
- dest.writeLong(mTotalTxBad);
- dest.writeLong(mTotalRxSuccess);
- dest.writeLong(mTotalRadioOnTimeMillis);
- dest.writeLong(mTotalRadioTxTimeMillis);
- dest.writeLong(mTotalRadioRxTimeMillis);
- dest.writeLong(mTotalScanTimeMillis);
- dest.writeLong(mTotalNanScanTimeMillis);
- dest.writeLong(mTotalBackgroundScanTimeMillis);
- dest.writeLong(mTotalRoamScanTimeMillis);
- dest.writeLong(mTotalPnoScanTimeMillis);
- dest.writeLong(mTotalHotspot2ScanTimeMillis);
- dest.writeLong(mTotalCcaBusyFreqTimeMillis);
- dest.writeLong(mTotalRadioOnFreqTimeMillis);
- dest.writeLong(mTotalBeaconRx);
- dest.writeInt(mProbeStatusSinceLastUpdate);
- dest.writeInt(mProbeElapsedTimeSinceLastUpdateMillis);
- dest.writeInt(mProbeMcsRateSinceLastUpdate);
- dest.writeInt(mRxLinkSpeedMbps);
- dest.writeInt(mCellularDataNetworkType);
- dest.writeInt(mCellularSignalStrengthDbm);
- dest.writeInt(mCellularSignalStrengthDb);
- dest.writeBoolean(mIsSameRegisteredCell);
- }
-
- /** Implement the Parcelable interface */
- public static final @android.annotation.NonNull Creator<WifiUsabilityStatsEntry> CREATOR =
- new Creator<WifiUsabilityStatsEntry>() {
- public WifiUsabilityStatsEntry createFromParcel(Parcel in) {
- return new WifiUsabilityStatsEntry(
- in.readLong(), in.readInt(),
- in.readInt(), in.readLong(), in.readLong(),
- in.readLong(), in.readLong(), in.readLong(),
- in.readLong(), in.readLong(), in.readLong(),
- in.readLong(), in.readLong(), in.readLong(),
- in.readLong(), in.readLong(), in.readLong(),
- in.readLong(), in.readLong(), in.readInt(),
- in.readInt(), in.readInt(), in.readInt(),
- in.readInt(), in.readInt(), in.readInt(),
- in.readBoolean()
- );
- }
-
- public WifiUsabilityStatsEntry[] newArray(int size) {
- return new WifiUsabilityStatsEntry[size];
- }
- };
-
- /** Absolute milliseconds from device boot when these stats were sampled */
- public long getTimeStampMillis() {
- return mTimeStampMillis;
- }
-
- /** The RSSI (in dBm) at the sample time */
- public int getRssi() {
- return mRssi;
- }
-
- /** Link speed at the sample time in Mbps */
- public int getLinkSpeedMbps() {
- return mLinkSpeedMbps;
- }
-
- /** The total number of tx success counted from the last radio chip reset */
- public long getTotalTxSuccess() {
- return mTotalTxSuccess;
- }
-
- /** The total number of MPDU data packet retries counted from the last radio chip reset */
- public long getTotalTxRetries() {
- return mTotalTxRetries;
- }
-
- /** The total number of tx bad counted from the last radio chip reset */
- public long getTotalTxBad() {
- return mTotalTxBad;
- }
-
- /** The total number of rx success counted from the last radio chip reset */
- public long getTotalRxSuccess() {
- return mTotalRxSuccess;
- }
-
- /** The total time the wifi radio is on in ms counted from the last radio chip reset */
- public long getTotalRadioOnTimeMillis() {
- return mTotalRadioOnTimeMillis;
- }
-
- /** The total time the wifi radio is doing tx in ms counted from the last radio chip reset */
- public long getTotalRadioTxTimeMillis() {
- return mTotalRadioTxTimeMillis;
- }
-
- /** The total time the wifi radio is doing rx in ms counted from the last radio chip reset */
- public long getTotalRadioRxTimeMillis() {
- return mTotalRadioRxTimeMillis;
- }
-
- /** The total time spent on all types of scans in ms counted from the last radio chip reset */
- public long getTotalScanTimeMillis() {
- return mTotalScanTimeMillis;
- }
-
- /** The total time spent on nan scans in ms counted from the last radio chip reset */
- public long getTotalNanScanTimeMillis() {
- return mTotalNanScanTimeMillis;
- }
-
- /** The total time spent on background scans in ms counted from the last radio chip reset */
- public long getTotalBackgroundScanTimeMillis() {
- return mTotalBackgroundScanTimeMillis;
- }
-
- /** The total time spent on roam scans in ms counted from the last radio chip reset */
- public long getTotalRoamScanTimeMillis() {
- return mTotalRoamScanTimeMillis;
- }
-
- /** The total time spent on pno scans in ms counted from the last radio chip reset */
- public long getTotalPnoScanTimeMillis() {
- return mTotalPnoScanTimeMillis;
- }
-
- /** The total time spent on hotspot2.0 scans and GAS exchange in ms counted from the last radio
- * chip reset */
- public long getTotalHotspot2ScanTimeMillis() {
- return mTotalHotspot2ScanTimeMillis;
- }
-
- /** The total time CCA is on busy status on the current frequency in ms counted from the last
- * radio chip reset */
- public long getTotalCcaBusyFreqTimeMillis() {
- return mTotalCcaBusyFreqTimeMillis;
- }
-
- /** The total radio on time on the current frequency from the last radio chip reset */
- public long getTotalRadioOnFreqTimeMillis() {
- return mTotalRadioOnFreqTimeMillis;
- }
-
- /** The total number of beacons received from the last radio chip reset */
- public long getTotalBeaconRx() {
- return mTotalBeaconRx;
- }
-
- /** The status of link probe since last stats update */
- @ProbeStatus public int getProbeStatusSinceLastUpdate() {
- return mProbeStatusSinceLastUpdate;
- }
-
- /** The elapsed time of the most recent link probe since last stats update */
- public int getProbeElapsedTimeSinceLastUpdateMillis() {
- return mProbeElapsedTimeSinceLastUpdateMillis;
- }
-
- /** The MCS rate of the most recent link probe since last stats update */
- public int getProbeMcsRateSinceLastUpdate() {
- return mProbeMcsRateSinceLastUpdate;
- }
-
- /** Rx link speed at the sample time in Mbps */
- public int getRxLinkSpeedMbps() {
- return mRxLinkSpeedMbps;
- }
-
- /** Cellular data network type currently in use on the device for data transmission */
- @NetworkType public int getCellularDataNetworkType() {
- return mCellularDataNetworkType;
- }
-
- /**
- * Cellular signal strength in dBm, NR: CsiRsrp, LTE: Rsrp, WCDMA/TDSCDMA: Rscp,
- * CDMA: Rssi, EVDO: Rssi, GSM: Rssi
- */
- public int getCellularSignalStrengthDbm() {
- return mCellularSignalStrengthDbm;
- }
-
- /**
- * Cellular signal strength in dB, NR: CsiSinr, LTE: Rsrq, WCDMA: EcNo, TDSCDMA: invalid,
- * CDMA: Ecio, EVDO: SNR, GSM: invalid
- */
- public int getCellularSignalStrengthDb() {
- return mCellularSignalStrengthDb;
- }
-
- /** Whether the primary registered cell of current entry is same as that of previous entry */
- public boolean isSameRegisteredCell() {
- return mIsSameRegisteredCell;
- }
-}
diff --git a/wifi/java/android/net/wifi/WpsInfo.java b/wifi/java/android/net/wifi/WpsInfo.java
deleted file mode 100644
index 689ace5bf5b9..000000000000
--- a/wifi/java/android/net/wifi/WpsInfo.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2011 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.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * A class representing Wi-Fi Protected Setup
- *
- * {@see android.net.wifi.p2p.WifiP2pConfig}
- */
-public class WpsInfo implements Parcelable {
-
- /** Push button configuration */
- public static final int PBC = 0;
- /** Display pin method configuration - pin is generated and displayed on device */
- public static final int DISPLAY = 1;
- /** Keypad pin method configuration - pin is entered on device */
- public static final int KEYPAD = 2;
- /** Label pin method configuration - pin is labelled on device */
- public static final int LABEL = 3;
- /** Invalid configuration */
- public static final int INVALID = 4;
-
- /** Wi-Fi Protected Setup. www.wi-fi.org/wifi-protected-setup has details */
- public int setup;
-
- /** Passed with pin method KEYPAD */
- public String BSSID;
-
- /** Passed with pin method configuration */
- public String pin;
-
- public WpsInfo() {
- setup = INVALID;
- BSSID = null;
- pin = null;
- }
-
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
- sbuf.append(" setup: ").append(setup);
- sbuf.append('\n');
- sbuf.append(" BSSID: ").append(BSSID);
- sbuf.append('\n');
- sbuf.append(" pin: ").append(pin);
- sbuf.append('\n');
- return sbuf.toString();
- }
-
- /** Implement the Parcelable interface */
- public int describeContents() {
- return 0;
- }
-
- /* Copy constructor */
- public WpsInfo(WpsInfo source) {
- if (source != null) {
- setup = source.setup;
- BSSID = source.BSSID;
- pin = source.pin;
- }
- }
-
- /** Implement the Parcelable interface */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(setup);
- dest.writeString(BSSID);
- dest.writeString(pin);
- }
-
- /** Implement the Parcelable interface */
- public static final @android.annotation.NonNull Creator<WpsInfo> CREATOR =
- new Creator<WpsInfo>() {
- public WpsInfo createFromParcel(Parcel in) {
- WpsInfo config = new WpsInfo();
- config.setup = in.readInt();
- config.BSSID = in.readString();
- config.pin = in.readString();
- return config;
- }
-
- public WpsInfo[] newArray(int size) {
- return new WpsInfo[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/aware/AttachCallback.java b/wifi/java/android/net/wifi/aware/AttachCallback.java
deleted file mode 100644
index c368b4692de4..000000000000
--- a/wifi/java/android/net/wifi/aware/AttachCallback.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-/**
- * Base class for Aware attach callbacks. Should be extended by applications and set when calling
- * {@link WifiAwareManager#attach(AttachCallback, android.os.Handler)}. These are callbacks
- * applying to the Aware connection as a whole - not to specific publish or subscribe sessions -
- * for that see {@link DiscoverySessionCallback}.
- */
-public class AttachCallback {
- /**
- * Called when Aware attach operation
- * {@link WifiAwareManager#attach(AttachCallback, android.os.Handler)}
- * is completed and that we can now start discovery sessions or connections.
- *
- * @param session The Aware object on which we can execute further Aware operations - e.g.
- * discovery, connections.
- */
- public void onAttached(WifiAwareSession session) {
- /* empty */
- }
-
- /**
- * Called when Aware attach operation
- * {@link WifiAwareManager#attach(AttachCallback, android.os.Handler)} failed.
- */
- public void onAttachFailed() {
- /* empty */
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/AwareResources.java b/wifi/java/android/net/wifi/aware/AwareResources.java
deleted file mode 100644
index cee1f40c05cd..000000000000
--- a/wifi/java/android/net/wifi/aware/AwareResources.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright (C) 2020 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.aware;
-
-import android.annotation.NonNull;
-import android.os.Handler;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * The resources of the Aware service.
- */
-public final class AwareResources implements Parcelable {
- /**
- * Number of the NDPs are available.
- */
- private int mNumOfAvailableNdps;
-
- /**
- * Number of the publish sessions are available.
- */
- private int mNumOfAvailablePublishSessions;
-
- /**
- * Number of the subscribe sessions are available.
- */
- private int mNumOfAvailableSubscribeSessions;
-
- /**
- * @hide : should not be created by apps
- */
- public AwareResources() {
- }
-
- /**
- * Return the number of Aware data-paths (also known as NDPs - NAN Data Paths) which an app
- * could create. Please refer to the {@link WifiAwareNetworkSpecifier} to create
- * a Network Specifier and request a data-path.
- * <p>
- * Note that these resources aren't reserved - other apps could use them by the time you
- * attempt to create a data-path.
- * </p>
- * @return A Non-negative integer, number of data-paths that could be created.
- */
- public int getNumOfAvailableDataPaths() {
- return mNumOfAvailableNdps;
- }
-
- /**
- * Return the number of Aware publish sessions which an app could create. Please refer to the
- * {@link WifiAwareSession#publish(PublishConfig, DiscoverySessionCallback, Handler)}
- * to create a publish session.
- * <p>
- * Note that these resources aren't reserved - other apps could use them by the time you
- * attempt to create a publish session.
- * </p>
- * @return A Non-negative integer, number of publish sessions that could be created.
- */
- public int getNumOfAvailablePublishSessions() {
- return mNumOfAvailablePublishSessions;
- }
-
- /**
- * Return the number of Aware subscribe sessions which an app could create. Please refer to the
- * {@link WifiAwareSession#subscribe(SubscribeConfig, DiscoverySessionCallback, Handler)}
- * to create a publish session.
- * <p>
- * Note that these resources aren't reserved - other apps could use them by the time you
- * attempt to create a subscribe session.
- * </p>
- * @return A Non-negative integer, number of subscribe sessions that could be created.
- */
- public int getNumOfAvailableSubscribeSessions() {
- return mNumOfAvailableSubscribeSessions;
- }
-
- /**
- * Set the number of the available NDPs.
- * @hide
- * @param numOfAvailableNdps Number of available NDPs.
- */
- public void setNumOfAvailableDataPaths(int numOfAvailableNdps) {
- mNumOfAvailableNdps = numOfAvailableNdps;
- }
-
- /**
- * Set the number of the available publish sessions.
- * @hide
- * @param numOfAvailablePublishSessions Number of available publish sessions.
- */
- public void setNumOfAvailablePublishSessions(int numOfAvailablePublishSessions) {
- mNumOfAvailablePublishSessions = numOfAvailablePublishSessions;
- }
-
- /**
- * Set the number of the available subscribe sessions.
- * @hide
- * @param numOfAvailableSubscribeSessions Number of available subscribe sessions.
- */
- public void setNumOfAvailableSubscribeSessions(int numOfAvailableSubscribeSessions) {
- mNumOfAvailableSubscribeSessions = numOfAvailableSubscribeSessions;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeInt(mNumOfAvailableNdps);
- dest.writeInt(mNumOfAvailablePublishSessions);
- dest.writeInt(mNumOfAvailableSubscribeSessions);
- }
-
- public static final @android.annotation.NonNull Creator<AwareResources> CREATOR =
- new Creator<AwareResources>() {
- @Override
- public AwareResources createFromParcel(Parcel in) {
- AwareResources awareResources = new AwareResources();
- awareResources.setNumOfAvailableDataPaths(in.readInt());
- awareResources.setNumOfAvailablePublishSessions(in.readInt());
- awareResources.setNumOfAvailableSubscribeSessions(in.readInt());
- return awareResources;
- }
-
- @Override
- public AwareResources[] newArray(int size) {
- return new AwareResources[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/aware/Characteristics.java b/wifi/java/android/net/wifi/aware/Characteristics.java
deleted file mode 100644
index 9bdda7f7d323..000000000000
--- a/wifi/java/android/net/wifi/aware/Characteristics.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.annotation.IntDef;
-import android.os.Bundle;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import com.android.modules.utils.build.SdkLevel;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-
-/**
- * The characteristics of the Wi-Fi Aware implementation.
- */
-public final class Characteristics implements Parcelable {
- /** @hide */
- public static final String KEY_MAX_SERVICE_NAME_LENGTH = "key_max_service_name_length";
- /** @hide */
- public static final String KEY_MAX_SERVICE_SPECIFIC_INFO_LENGTH =
- "key_max_service_specific_info_length";
- /** @hide */
- public static final String KEY_MAX_MATCH_FILTER_LENGTH = "key_max_match_filter_length";
- /** @hide */
- public static final String KEY_SUPPORTED_CIPHER_SUITES = "key_supported_cipher_suites";
- /** @hide */
- public static final String KEY_IS_INSTANT_COMMUNICATION_MODE_SUPPORTED =
- "key_is_instant_communication_mode_supported";
-
- private Bundle mCharacteristics = new Bundle();
-
- /** @hide : should not be created by apps */
- public Characteristics(Bundle characteristics) {
- mCharacteristics = characteristics;
- }
-
- /**
- * Returns the maximum string length that can be used to specify a Aware service name. Restricts
- * the parameters of the {@link PublishConfig.Builder#setServiceName(String)} and
- * {@link SubscribeConfig.Builder#setServiceName(String)}.
- *
- * @return A positive integer, maximum string length of Aware service name.
- */
- public int getMaxServiceNameLength() {
- return mCharacteristics.getInt(KEY_MAX_SERVICE_NAME_LENGTH);
- }
-
- /**
- * Returns the maximum length of byte array that can be used to specify a Aware service specific
- * information field: the arbitrary load used in discovery or the message length of Aware
- * message exchange. Restricts the parameters of the
- * {@link PublishConfig.Builder#setServiceSpecificInfo(byte[])},
- * {@link SubscribeConfig.Builder#setServiceSpecificInfo(byte[])}, and
- * {@link DiscoverySession#sendMessage(PeerHandle, int, byte[])}
- * variants.
- *
- * @return A positive integer, maximum length of byte array for Aware messaging.
- */
- public int getMaxServiceSpecificInfoLength() {
- return mCharacteristics.getInt(KEY_MAX_SERVICE_SPECIFIC_INFO_LENGTH);
- }
-
- /**
- * Returns the maximum length of byte array that can be used to specify a Aware match filter.
- * Restricts the parameters of the
- * {@link PublishConfig.Builder#setMatchFilter(java.util.List)} and
- * {@link SubscribeConfig.Builder#setMatchFilter(java.util.List)}.
- *
- * @return A positive integer, maximum length of byte array for Aware discovery match filter.
- */
- public int getMaxMatchFilterLength() {
- return mCharacteristics.getInt(KEY_MAX_MATCH_FILTER_LENGTH);
- }
-
- /**
- * Check if instant communication mode is supported by device.
- * @return True if supported, false otherwise.
- */
- public boolean isInstantCommunicationModeSupported() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- return mCharacteristics.getBoolean(KEY_IS_INSTANT_COMMUNICATION_MODE_SUPPORTED);
- }
-
- /** @hide */
- @IntDef(flag = true, prefix = { "WIFI_AWARE_CIPHER_SUITE_" }, value = {
- WIFI_AWARE_CIPHER_SUITE_NCS_SK_128,
- WIFI_AWARE_CIPHER_SUITE_NCS_SK_256,
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface WifiAwareCipherSuites {}
-
- /**
- * Wi-Fi Aware supported ciphier suite representing NCS SK 128: 128 bit shared-key.
- */
- public static final int WIFI_AWARE_CIPHER_SUITE_NCS_SK_128 = 1 << 0;
-
- /**
- * Wi-Fi Aware supported ciphier suite representing NCS SK 256: 256 bit shared-key.
- */
- public static final int WIFI_AWARE_CIPHER_SUITE_NCS_SK_256 = 1 << 1;
-
- /**
- * Returns the set of cipher suites supported by the device for use in Wi-Fi Aware data-paths.
- * The device automatically picks the strongest cipher suite when initiating a data-path setup.
- *
- * @return A set of flags from {@link #WIFI_AWARE_CIPHER_SUITE_NCS_SK_128}, or
- * {@link #WIFI_AWARE_CIPHER_SUITE_NCS_SK_256}.
- */
- public @WifiAwareCipherSuites int getSupportedCipherSuites() {
- return mCharacteristics.getInt(KEY_SUPPORTED_CIPHER_SUITES);
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeBundle(mCharacteristics);
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- public static final @android.annotation.NonNull Creator<Characteristics> CREATOR =
- new Creator<Characteristics>() {
- @Override
- public Characteristics createFromParcel(Parcel in) {
- Characteristics c = new Characteristics(in.readBundle());
- return c;
- }
-
- @Override
- public Characteristics[] newArray(int size) {
- return new Characteristics[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/aware/ConfigRequest.aidl b/wifi/java/android/net/wifi/aware/ConfigRequest.aidl
deleted file mode 100644
index 68a7c85eabc4..000000000000
--- a/wifi/java/android/net/wifi/aware/ConfigRequest.aidl
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-parcelable ConfigRequest;
diff --git a/wifi/java/android/net/wifi/aware/ConfigRequest.java b/wifi/java/android/net/wifi/aware/ConfigRequest.java
deleted file mode 100644
index 61ab92c9416f..000000000000
--- a/wifi/java/android/net/wifi/aware/ConfigRequest.java
+++ /dev/null
@@ -1,385 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.Arrays;
-
-/**
- * Defines a request object to configure a Wi-Fi Aware network. Built using
- * {@link ConfigRequest.Builder}. Configuration is requested using
- * {@link WifiAwareManager#attach(AttachCallback, android.os.Handler)}.
- * Note that the actual achieved configuration may be different from the
- * requested configuration - since different applications may request different
- * configurations.
- *
- * @hide
- */
-public final class ConfigRequest implements Parcelable {
- /**
- * Lower range of possible cluster ID.
- */
- public static final int CLUSTER_ID_MIN = 0;
-
- /**
- * Upper range of possible cluster ID.
- */
- public static final int CLUSTER_ID_MAX = 0xFFFF;
-
- /**
- * Indices for configuration variables which are specified per band.
- */
- public static final int NAN_BAND_24GHZ = 0;
- public static final int NAN_BAND_5GHZ = 1;
- public static final int NAN_BAND_6GHZ = 2;
-
- /**
- * Magic values for Discovery Window (DW) interval configuration
- */
- public static final int DW_INTERVAL_NOT_INIT = -1;
- public static final int DW_DISABLE = 0; // only valid for 5GHz
-
- /**
- * Indicates whether 5G band support is requested.
- */
- public final boolean mSupport5gBand;
-
- /**
- * Indicates whether 6G band support is requested.
- */
- public final boolean mSupport6gBand;
-
- /**
- * Specifies the desired master preference.
- */
- public final int mMasterPreference;
-
- /**
- * Specifies the desired lower range of the cluster ID. Must be lower then
- * {@link ConfigRequest#mClusterHigh}.
- */
- public final int mClusterLow;
-
- /**
- * Specifies the desired higher range of the cluster ID. Must be higher then
- * {@link ConfigRequest#mClusterLow}.
- */
- public final int mClusterHigh;
-
- /**
- * Specifies the discovery window interval for the device on NAN_BAND_*.
- */
- public final int mDiscoveryWindowInterval[];
-
- private ConfigRequest(boolean support5gBand, boolean support6gBand, int masterPreference,
- int clusterLow, int clusterHigh, int[] discoveryWindowInterval) {
- mSupport5gBand = support5gBand;
- mSupport6gBand = support6gBand;
- mMasterPreference = masterPreference;
- mClusterLow = clusterLow;
- mClusterHigh = clusterHigh;
- mDiscoveryWindowInterval = discoveryWindowInterval;
- }
-
- @Override
- public String toString() {
- return "ConfigRequest [mSupport5gBand=" + mSupport5gBand
- + ", mSupport6gBand=" + mSupport6gBand
- + ", mMasterPreference=" + mMasterPreference
- + ", mClusterLow=" + mClusterLow
- + ", mClusterHigh=" + mClusterHigh
- + ", mDiscoveryWindowInterval=" + Arrays.toString(mDiscoveryWindowInterval) + "]";
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mSupport5gBand ? 1 : 0);
- dest.writeInt(mSupport6gBand ? 1 : 0);
- dest.writeInt(mMasterPreference);
- dest.writeInt(mClusterLow);
- dest.writeInt(mClusterHigh);
- dest.writeIntArray(mDiscoveryWindowInterval);
- }
-
- public static final @android.annotation.NonNull Creator<ConfigRequest> CREATOR = new Creator<ConfigRequest>() {
- @Override
- public ConfigRequest[] newArray(int size) {
- return new ConfigRequest[size];
- }
-
- @Override
- public ConfigRequest createFromParcel(Parcel in) {
- boolean support5gBand = in.readInt() != 0;
- boolean support6gBand = in.readInt() != 0;
- int masterPreference = in.readInt();
- int clusterLow = in.readInt();
- int clusterHigh = in.readInt();
- int discoveryWindowInterval[] = in.createIntArray();
-
- return new ConfigRequest(support5gBand, support6gBand, masterPreference, clusterLow,
- clusterHigh, discoveryWindowInterval);
- }
- };
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
-
- if (!(o instanceof ConfigRequest)) {
- return false;
- }
-
- ConfigRequest lhs = (ConfigRequest) o;
-
- return mSupport5gBand == lhs.mSupport5gBand
- && mSupport6gBand == lhs.mSupport6gBand
- && mMasterPreference == lhs.mMasterPreference
- && mClusterLow == lhs.mClusterLow && mClusterHigh == lhs.mClusterHigh
- && Arrays.equals(mDiscoveryWindowInterval, lhs.mDiscoveryWindowInterval);
- }
-
- @Override
- public int hashCode() {
- int result = 17;
-
- result = 31 * result + (mSupport5gBand ? 1 : 0);
- result = 31 * result + (mSupport6gBand ? 1 : 0);
- result = 31 * result + mMasterPreference;
- result = 31 * result + mClusterLow;
- result = 31 * result + mClusterHigh;
- result = 31 * result + Arrays.hashCode(mDiscoveryWindowInterval);
-
- return result;
- }
-
- /**
- * Verifies that the contents of the ConfigRequest are valid. Otherwise
- * throws an IllegalArgumentException.
- */
- public void validate() throws IllegalArgumentException {
- if (mMasterPreference < 0) {
- throw new IllegalArgumentException(
- "Master Preference specification must be non-negative");
- }
- if (mMasterPreference == 1 || mMasterPreference == 255 || mMasterPreference > 255) {
- throw new IllegalArgumentException("Master Preference specification must not "
- + "exceed 255 or use 1 or 255 (reserved values)");
- }
- if (mClusterLow < CLUSTER_ID_MIN) {
- throw new IllegalArgumentException("Cluster specification must be non-negative");
- }
- if (mClusterLow > CLUSTER_ID_MAX) {
- throw new IllegalArgumentException("Cluster specification must not exceed 0xFFFF");
- }
- if (mClusterHigh < CLUSTER_ID_MIN) {
- throw new IllegalArgumentException("Cluster specification must be non-negative");
- }
- if (mClusterHigh > CLUSTER_ID_MAX) {
- throw new IllegalArgumentException("Cluster specification must not exceed 0xFFFF");
- }
- if (mClusterLow > mClusterHigh) {
- throw new IllegalArgumentException(
- "Invalid argument combination - must have Cluster Low <= Cluster High");
- }
- if (mDiscoveryWindowInterval.length != 3) {
- throw new IllegalArgumentException(
- "Invalid discovery window interval: must have 3 elements (2.4 & 5 & 6");
- }
- if (mDiscoveryWindowInterval[NAN_BAND_24GHZ] != DW_INTERVAL_NOT_INIT &&
- (mDiscoveryWindowInterval[NAN_BAND_24GHZ] < 1 // valid for 2.4GHz: [1-5]
- || mDiscoveryWindowInterval[NAN_BAND_24GHZ] > 5)) {
- throw new IllegalArgumentException(
- "Invalid discovery window interval for 2.4GHz: valid is UNSET or [1,5]");
- }
- if (mDiscoveryWindowInterval[NAN_BAND_5GHZ] != DW_INTERVAL_NOT_INIT &&
- (mDiscoveryWindowInterval[NAN_BAND_5GHZ] < 0 // valid for 5GHz: [0-5]
- || mDiscoveryWindowInterval[NAN_BAND_5GHZ] > 5)) {
- throw new IllegalArgumentException(
- "Invalid discovery window interval for 5GHz: valid is UNSET or [0,5]");
- }
- if (mDiscoveryWindowInterval[NAN_BAND_6GHZ] != DW_INTERVAL_NOT_INIT
- && (mDiscoveryWindowInterval[NAN_BAND_6GHZ] < 0 // valid for 6GHz: [0-5]
- || mDiscoveryWindowInterval[NAN_BAND_6GHZ] > 5)) {
- throw new IllegalArgumentException(
- "Invalid discovery window interval for 6GHz: valid is UNSET or [0,5]");
- }
- }
-
- /**
- * Builder used to build {@link ConfigRequest} objects.
- */
- public static final class Builder {
- private boolean mSupport5gBand = true;
- private boolean mSupport6gBand = false;
- private int mMasterPreference = 0;
- private int mClusterLow = CLUSTER_ID_MIN;
- private int mClusterHigh = CLUSTER_ID_MAX;
- private int[] mDiscoveryWindowInterval = {DW_INTERVAL_NOT_INIT, DW_INTERVAL_NOT_INIT,
- DW_INTERVAL_NOT_INIT};
-
- /**
- * Specify whether 5G band support is required in this request. Disabled by default.
- *
- * @param support5gBand Support for 5G band is required.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setSupport5gBand(boolean support5gBand) {
- mSupport5gBand = support5gBand;
- return this;
- }
-
- /**
- * Specify whether 6G band support is required in this request. Disabled by default.
- *
- * @param support6gBand Support for 6G band is required.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setSupport6gBand(boolean support6gBand) {
- mSupport6gBand = support6gBand;
- return this;
- }
-
- /**
- * Specify the Master Preference requested. The permitted range is 0 (the default) to
- * 255 with 1 and 255 excluded (reserved).
- *
- * @param masterPreference The requested master preference
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setMasterPreference(int masterPreference) {
- if (masterPreference < 0) {
- throw new IllegalArgumentException(
- "Master Preference specification must be non-negative");
- }
- if (masterPreference == 1 || masterPreference == 255 || masterPreference > 255) {
- throw new IllegalArgumentException("Master Preference specification must not "
- + "exceed 255 or use 1 or 255 (reserved values)");
- }
-
- mMasterPreference = masterPreference;
- return this;
- }
-
- /**
- * The Cluster ID is generated randomly for new Aware networks. Specify
- * the lower range of the cluster ID. The upper range is specified using
- * the {@link ConfigRequest.Builder#setClusterHigh(int)}. The permitted
- * range is 0 (the default) to the value specified by
- * {@link ConfigRequest.Builder#setClusterHigh(int)}. Equality of Low and High is
- * permitted which restricts the Cluster ID to the specified value.
- *
- * @param clusterLow The lower range of the generated cluster ID.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setClusterLow(..).setClusterHigh(..)}.
- */
- public Builder setClusterLow(int clusterLow) {
- if (clusterLow < CLUSTER_ID_MIN) {
- throw new IllegalArgumentException("Cluster specification must be non-negative");
- }
- if (clusterLow > CLUSTER_ID_MAX) {
- throw new IllegalArgumentException("Cluster specification must not exceed 0xFFFF");
- }
-
- mClusterLow = clusterLow;
- return this;
- }
-
- /**
- * The Cluster ID is generated randomly for new Aware networks. Specify
- * the lower upper of the cluster ID. The lower range is specified using
- * the {@link ConfigRequest.Builder#setClusterLow(int)}. The permitted
- * range is the value specified by
- * {@link ConfigRequest.Builder#setClusterLow(int)} to 0xFFFF (the default). Equality of
- * Low and High is permitted which restricts the Cluster ID to the specified value.
- *
- * @param clusterHigh The upper range of the generated cluster ID.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setClusterLow(..).setClusterHigh(..)}.
- */
- public Builder setClusterHigh(int clusterHigh) {
- if (clusterHigh < CLUSTER_ID_MIN) {
- throw new IllegalArgumentException("Cluster specification must be non-negative");
- }
- if (clusterHigh > CLUSTER_ID_MAX) {
- throw new IllegalArgumentException("Cluster specification must not exceed 0xFFFF");
- }
-
- mClusterHigh = clusterHigh;
- return this;
- }
-
- /**
- * The discovery window interval specifies the discovery windows in which the device will be
- * awake. The configuration enables trading off latency vs. power (higher interval means
- * higher discovery latency but lower power).
- *
- * @param band Either {@link #NAN_BAND_24GHZ} or {@link #NAN_BAND_5GHZ} or
- * {@link #NAN_BAND_6GHZ}.
- * @param interval A value of 1, 2, 3, 4, or 5 indicating an interval of 2^(interval-1). For
- * the 5GHz band a value of 0 indicates that the device will not be awake
- * for any discovery windows.
- *
- * @return The builder itself to facilitate chaining operations
- * {@code builder.setDiscoveryWindowInterval(...).setMasterPreference(...)}.
- */
- public Builder setDiscoveryWindowInterval(int band, int interval) {
- if (band != NAN_BAND_24GHZ && band != NAN_BAND_5GHZ && band != NAN_BAND_6GHZ) {
- throw new IllegalArgumentException("Invalid band value");
- }
- if ((band == NAN_BAND_24GHZ && (interval < 1 || interval > 5))
- || (band == NAN_BAND_5GHZ && (interval < 0 || interval > 5))
- || (band == NAN_BAND_6GHZ && (interval < 0 || interval > 5))) {
- throw new IllegalArgumentException(
- "Invalid interval value: 2.4 GHz [1,5] or 5GHz/6GHz [0,5]");
- }
-
- mDiscoveryWindowInterval[band] = interval;
- return this;
- }
-
- /**
- * Build {@link ConfigRequest} given the current requests made on the
- * builder.
- */
- public ConfigRequest build() {
- if (mClusterLow > mClusterHigh) {
- throw new IllegalArgumentException(
- "Invalid argument combination - must have Cluster Low <= Cluster High");
- }
-
- return new ConfigRequest(mSupport5gBand, mSupport6gBand, mMasterPreference, mClusterLow,
- mClusterHigh, mDiscoveryWindowInterval);
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/DiscoverySession.java b/wifi/java/android/net/wifi/aware/DiscoverySession.java
deleted file mode 100644
index 4d92ae174e6d..000000000000
--- a/wifi/java/android/net/wifi/aware/DiscoverySession.java
+++ /dev/null
@@ -1,431 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.NetworkSpecifier;
-import android.util.CloseGuard;
-import android.util.Log;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.lang.ref.Reference;
-import java.lang.ref.WeakReference;
-
-/**
- * A class representing a single publish or subscribe Aware session. This object
- * will not be created directly - only its child classes are available:
- * {@link PublishDiscoverySession} and {@link SubscribeDiscoverySession}. This
- * class provides functionality common to both publish and subscribe discovery sessions:
- * <ul>
- * <li>Sending messages: {@link #sendMessage(PeerHandle, int, byte[])} method.
- * <li>Creating a network-specifier when requesting a Aware connection using
- * {@link WifiAwareNetworkSpecifier.Builder}.
- * </ul>
- * <p>
- * The {@link #close()} method must be called to destroy discovery sessions once they are
- * no longer needed.
- */
-public class DiscoverySession implements AutoCloseable {
- private static final String TAG = "DiscoverySession";
- private static final boolean DBG = false;
- private static final boolean VDBG = false; // STOPSHIP if true
-
- private static final int MAX_SEND_RETRY_COUNT = 5;
-
- /** @hide */
- protected WeakReference<WifiAwareManager> mMgr;
- /** @hide */
- protected final int mClientId;
- /** @hide */
- protected final int mSessionId;
- /** @hide */
- protected boolean mTerminated = false;
-
- private final CloseGuard mCloseGuard = new CloseGuard();
-
- /**
- * Return the maximum permitted retry count when sending messages using
- * {@link #sendMessage(PeerHandle, int, byte[], int)}.
- *
- * @return Maximum retry count when sending messages.
- *
- * @hide
- */
- public static int getMaxSendRetryCount() {
- return MAX_SEND_RETRY_COUNT;
- }
-
- /** @hide */
- public DiscoverySession(WifiAwareManager manager, int clientId, int sessionId) {
- if (VDBG) {
- Log.v(TAG, "New discovery session created: manager=" + manager + ", clientId="
- + clientId + ", sessionId=" + sessionId);
- }
-
- mMgr = new WeakReference<>(manager);
- mClientId = clientId;
- mSessionId = sessionId;
-
- mCloseGuard.open("close");
- }
-
- /**
- * Destroy the publish or subscribe session - free any resources, and stop
- * transmitting packets on-air (for an active session) or listening for
- * matches (for a passive session). The session may not be used for any
- * additional operations after its destruction.
- * <p>
- * This operation must be done on a session which is no longer needed. Otherwise system
- * resources will continue to be utilized until the application exits. The only
- * exception is a session for which we received a termination callback,
- * {@link DiscoverySessionCallback#onSessionTerminated()}.
- */
- @Override
- public void close() {
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.w(TAG, "destroy: called post GC on WifiAwareManager");
- return;
- }
- mgr.terminateSession(mClientId, mSessionId);
- mTerminated = true;
- mMgr.clear();
- mCloseGuard.close();
- Reference.reachabilityFence(this);
- }
-
- /**
- * Sets the status of the session to terminated - i.e. an indication that
- * already terminated rather than executing a termination.
- *
- * @hide
- */
- public void setTerminated() {
- if (mTerminated) {
- Log.w(TAG, "terminate: already terminated.");
- return;
- }
-
- mTerminated = true;
- mMgr.clear();
- mCloseGuard.close();
- }
-
- /** @hide */
- @Override
- protected void finalize() throws Throwable {
- try {
- if (mCloseGuard != null) {
- mCloseGuard.warnIfOpen();
- }
-
- if (!mTerminated) {
- close();
- }
- } finally {
- super.finalize();
- }
- }
-
- /**
- * Access the client ID of the Aware session.
- *
- * Note: internal visibility for testing.
- *
- * @return The internal client ID.
- *
- * @hide
- */
- @VisibleForTesting
- public int getClientId() {
- return mClientId;
- }
-
- /**
- * Access the discovery session ID of the Aware session.
- *
- * Note: internal visibility for testing.
- *
- * @return The internal discovery session ID.
- *
- * @hide
- */
- @VisibleForTesting
- public int getSessionId() {
- return mSessionId;
- }
-
- /**
- * Sends a message to the specified destination. Aware messages are transmitted in the context
- * of a discovery session - executed subsequent to a publish/subscribe
- * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle,
- * byte[], java.util.List)} event.
- * <p>
- * Aware messages are not guaranteed delivery. Callbacks on
- * {@link DiscoverySessionCallback} indicate message was transmitted successfully,
- * {@link DiscoverySessionCallback#onMessageSendSucceeded(int)}, or transmission
- * failed (possibly after several retries) -
- * {@link DiscoverySessionCallback#onMessageSendFailed(int)}.
- * <p>
- * The peer will get a callback indicating a message was received using
- * {@link DiscoverySessionCallback#onMessageReceived(PeerHandle,
- * byte[])}.
- *
- * @param peerHandle The peer's handle for the message. Must be a result of an
- * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle,
- * byte[], java.util.List)} or
- * {@link DiscoverySessionCallback#onMessageReceived(PeerHandle,
- * byte[])} events.
- * @param messageId An arbitrary integer used by the caller to identify the message. The same
- * integer ID will be returned in the callbacks indicating message send success or
- * failure. The {@code messageId} is not used internally by the Aware service - it
- * can be arbitrary and non-unique.
- * @param message The message to be transmitted.
- * @param retryCount An integer specifying how many additional service-level (as opposed to PHY
- * or MAC level) retries should be attempted if there is no ACK from the receiver
- * (note: no retransmissions are attempted in other failure cases). A value of 0
- * indicates no retries. Max permitted value is {@link #getMaxSendRetryCount()}.
- *
- * @hide
- */
- public void sendMessage(@NonNull PeerHandle peerHandle, int messageId,
- @Nullable byte[] message, int retryCount) {
- if (mTerminated) {
- Log.w(TAG, "sendMessage: called on terminated session");
- return;
- }
-
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.w(TAG, "sendMessage: called post GC on WifiAwareManager");
- return;
- }
-
- mgr.sendMessage(mClientId, mSessionId, peerHandle, message, messageId, retryCount);
- }
-
- /**
- * Sends a message to the specified destination. Aware messages are transmitted in the context
- * of a discovery session - executed subsequent to a publish/subscribe
- * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle,
- * byte[], java.util.List)} event.
- * <p>
- * Aware messages are not guaranteed delivery. Callbacks on
- * {@link DiscoverySessionCallback} indicate message was transmitted successfully,
- * {@link DiscoverySessionCallback#onMessageSendSucceeded(int)}, or transmission
- * failed (possibly after several retries) -
- * {@link DiscoverySessionCallback#onMessageSendFailed(int)}.
- * <p>
- * The peer will get a callback indicating a message was received using
- * {@link DiscoverySessionCallback#onMessageReceived(PeerHandle,
- * byte[])}.
- *
- * @param peerHandle The peer's handle for the message. Must be a result of an
- * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle,
- * byte[], java.util.List)} or
- * {@link DiscoverySessionCallback#onMessageReceived(PeerHandle,
- * byte[])} events.
- * @param messageId An arbitrary integer used by the caller to identify the message. The same
- * integer ID will be returned in the callbacks indicating message send success or
- * failure. The {@code messageId} is not used internally by the Aware service - it
- * can be arbitrary and non-unique.
- * @param message The message to be transmitted.
- */
- public void sendMessage(@NonNull PeerHandle peerHandle, int messageId,
- @Nullable byte[] message) {
- sendMessage(peerHandle, messageId, message, 0);
- }
-
- /**
- * Create a {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} for
- * an unencrypted WiFi Aware connection (link) to the specified peer. The
- * {@link android.net.NetworkRequest.Builder#addTransportType(int)} should be set to
- * {@link android.net.NetworkCapabilities#TRANSPORT_WIFI_AWARE}.
- * <p>
- * This method should be used when setting up a connection with a peer discovered through Aware
- * discovery or communication (in such scenarios the MAC address of the peer is shielded by
- * an opaque peer ID handle). If an Aware connection is needed to a peer discovered using other
- * OOB (out-of-band) mechanism then use the alternative
- * {@link WifiAwareSession#createNetworkSpecifierOpen(int, byte[])} method - which uses the
- * peer's MAC address.
- * <p>
- * Note: per the Wi-Fi Aware specification the roles are fixed - a Subscriber is an INITIATOR
- * and a Publisher is a RESPONDER.
- * <p>
- * To set up an encrypted link use the
- * {@link #createNetworkSpecifierPassphrase(PeerHandle, String)} API.
- * @deprecated Use the replacement {@link WifiAwareNetworkSpecifier.Builder}.
- *
- * @param peerHandle The peer's handle obtained through
- * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle, byte[], java.util.List)}
- * or
- * {@link DiscoverySessionCallback#onMessageReceived(PeerHandle, byte[])}.
- * On a RESPONDER this value is used to gate the acceptance of a connection
- * request from only that peer.
- *
- * @return A {@link NetworkSpecifier} to be used to construct
- * {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} to pass to
- * {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest,
- * android.net.ConnectivityManager.NetworkCallback)}
- * [or other varieties of that API].
- */
- @Deprecated
- public NetworkSpecifier createNetworkSpecifierOpen(@NonNull PeerHandle peerHandle) {
- if (mTerminated) {
- Log.w(TAG, "createNetworkSpecifierOpen: called on terminated session");
- return null;
- }
-
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.w(TAG, "createNetworkSpecifierOpen: called post GC on WifiAwareManager");
- return null;
- }
-
- int role = this instanceof SubscribeDiscoverySession
- ? WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
- : WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER;
-
- return mgr.createNetworkSpecifier(mClientId, role, mSessionId, peerHandle, null, null);
- }
-
- /**
- * Create a {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} for
- * an encrypted WiFi Aware connection (link) to the specified peer. The
- * {@link android.net.NetworkRequest.Builder#addTransportType(int)} should be set to
- * {@link android.net.NetworkCapabilities#TRANSPORT_WIFI_AWARE}.
- * <p>
- * This method should be used when setting up a connection with a peer discovered through Aware
- * discovery or communication (in such scenarios the MAC address of the peer is shielded by
- * an opaque peer ID handle). If an Aware connection is needed to a peer discovered using other
- * OOB (out-of-band) mechanism then use the alternative
- * {@link WifiAwareSession#createNetworkSpecifierPassphrase(int, byte[], String)} method -
- * which uses the peer's MAC address.
- * <p>
- * Note: per the Wi-Fi Aware specification the roles are fixed - a Subscriber is an INITIATOR
- * and a Publisher is a RESPONDER.
- * @deprecated Use the replacement {@link WifiAwareNetworkSpecifier.Builder}.
- *
- * @param peerHandle The peer's handle obtained through
- * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle,
- * byte[], java.util.List)} or
- * {@link DiscoverySessionCallback#onMessageReceived(PeerHandle,
- * byte[])}. On a RESPONDER this value is used to gate the acceptance of a connection request
- * from only that peer.
- * @param passphrase The passphrase to be used to encrypt the link. The PMK is generated from
- * the passphrase. Use the
- * {@link #createNetworkSpecifierOpen(PeerHandle)} API to
- * specify an open (unencrypted) link.
- *
- * @return A {@link NetworkSpecifier} to be used to construct
- * {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} to pass to
- * {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest,
- * android.net.ConnectivityManager.NetworkCallback)}
- * [or other varieties of that API].
- */
- @Deprecated
- public NetworkSpecifier createNetworkSpecifierPassphrase(
- @NonNull PeerHandle peerHandle, @NonNull String passphrase) {
- if (!WifiAwareUtils.validatePassphrase(passphrase)) {
- throw new IllegalArgumentException("Passphrase must meet length requirements");
- }
-
- if (mTerminated) {
- Log.w(TAG, "createNetworkSpecifierPassphrase: called on terminated session");
- return null;
- }
-
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.w(TAG, "createNetworkSpecifierPassphrase: called post GC on WifiAwareManager");
- return null;
- }
-
- int role = this instanceof SubscribeDiscoverySession
- ? WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
- : WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER;
-
- return mgr.createNetworkSpecifier(mClientId, role, mSessionId, peerHandle, null,
- passphrase);
- }
-
- /**
- * Create a {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} for
- * an encrypted WiFi Aware connection (link) to the specified peer. The
- * {@link android.net.NetworkRequest.Builder#addTransportType(int)} should be set to
- * {@link android.net.NetworkCapabilities#TRANSPORT_WIFI_AWARE}.
- * <p>
- * This method should be used when setting up a connection with a peer discovered through Aware
- * discovery or communication (in such scenarios the MAC address of the peer is shielded by
- * an opaque peer ID handle). If an Aware connection is needed to a peer discovered using other
- * OOB (out-of-band) mechanism then use the alternative
- * {@link WifiAwareSession#createNetworkSpecifierPmk(int, byte[], byte[])} method - which uses
- * the peer's MAC address.
- * <p>
- * Note: per the Wi-Fi Aware specification the roles are fixed - a Subscriber is an INITIATOR
- * and a Publisher is a RESPONDER.
- * @deprecated Use the replacement {@link WifiAwareNetworkSpecifier.Builder}.
- *
- * @param peerHandle The peer's handle obtained through
- * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle,
- * byte[], java.util.List)} or
- * {@link DiscoverySessionCallback#onMessageReceived(PeerHandle,
- * byte[])}. On a RESPONDER this value is used to gate the acceptance of a connection request
- * from only that peer.
- * @param pmk A PMK (pairwise master key, see IEEE 802.11i) specifying the key to use for
- * encrypting the data-path. Use the
- * {@link #createNetworkSpecifierPassphrase(PeerHandle, String)} to specify a
- * Passphrase or {@link #createNetworkSpecifierOpen(PeerHandle)} to specify an
- * open (unencrypted) link.
- *
- * @return A {@link NetworkSpecifier} to be used to construct
- * {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} to pass to
- * {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest,
- * android.net.ConnectivityManager.NetworkCallback)}
- * [or other varieties of that API].
- *
- * @hide
- */
- @Deprecated
- @SystemApi
- public NetworkSpecifier createNetworkSpecifierPmk(@NonNull PeerHandle peerHandle,
- @NonNull byte[] pmk) {
- if (!WifiAwareUtils.validatePmk(pmk)) {
- throw new IllegalArgumentException("PMK must 32 bytes");
- }
-
- if (mTerminated) {
- Log.w(TAG, "createNetworkSpecifierPmk: called on terminated session");
- return null;
- }
-
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.w(TAG, "createNetworkSpecifierPmk: called post GC on WifiAwareManager");
- return null;
- }
-
- int role = this instanceof SubscribeDiscoverySession
- ? WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
- : WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER;
-
- return mgr.createNetworkSpecifier(mClientId, role, mSessionId, peerHandle, pmk, null);
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/DiscoverySessionCallback.java b/wifi/java/android/net/wifi/aware/DiscoverySessionCallback.java
deleted file mode 100644
index da8e17e2f41a..000000000000
--- a/wifi/java/android/net/wifi/aware/DiscoverySessionCallback.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.annotation.NonNull;
-
-import java.util.List;
-
-/**
- * Base class for Aware session events callbacks. Should be extended by
- * applications wanting notifications. The callbacks are set when a
- * publish or subscribe session is created using
- * {@link WifiAwareSession#publish(PublishConfig, DiscoverySessionCallback,
- * android.os.Handler)} or
- * {@link WifiAwareSession#subscribe(SubscribeConfig, DiscoverySessionCallback,
- * android.os.Handler)}.
- * <p>
- * A single callback is set at session creation - it cannot be replaced.
- */
-public class DiscoverySessionCallback {
- /**
- * Called when a publish operation is started successfully in response to a
- * {@link WifiAwareSession#publish(PublishConfig, DiscoverySessionCallback,
- * android.os.Handler)} operation.
- *
- * @param session The {@link PublishDiscoverySession} used to control the
- * discovery session.
- */
- public void onPublishStarted(@NonNull PublishDiscoverySession session) {
- /* empty */
- }
-
- /**
- * Called when a subscribe operation is started successfully in response to a
- * {@link WifiAwareSession#subscribe(SubscribeConfig, DiscoverySessionCallback,
- * android.os.Handler)} operation.
- *
- * @param session The {@link SubscribeDiscoverySession} used to control the
- * discovery session.
- */
- public void onSubscribeStarted(@NonNull SubscribeDiscoverySession session) {
- /* empty */
- }
-
- /**
- * Called when a publish or subscribe discovery session configuration update request
- * succeeds. Called in response to
- * {@link PublishDiscoverySession#updatePublish(PublishConfig)} or
- * {@link SubscribeDiscoverySession#updateSubscribe(SubscribeConfig)}.
- */
- public void onSessionConfigUpdated() {
- /* empty */
- }
-
- /**
- * Called when a publish or subscribe discovery session cannot be created:
- * {@link WifiAwareSession#publish(PublishConfig, DiscoverySessionCallback,
- * android.os.Handler)} or
- * {@link WifiAwareSession#subscribe(SubscribeConfig, DiscoverySessionCallback,
- * android.os.Handler)}, or when a configuration update fails:
- * {@link PublishDiscoverySession#updatePublish(PublishConfig)} or
- * {@link SubscribeDiscoverySession#updateSubscribe(SubscribeConfig)}.
- * <p>
- * For discovery session updates failure leaves the session running with its previous
- * configuration - the discovery session is not terminated.
- */
- public void onSessionConfigFailed() {
- /* empty */
- }
-
- /**
- * Called when a discovery session (publish or subscribe) terminates. Termination may be due
- * to user-request (either directly through {@link DiscoverySession#close()} or
- * application-specified expiration, e.g. {@link PublishConfig.Builder#setTtlSec(int)}
- * or {@link SubscribeConfig.Builder#setTtlSec(int)}).
- */
- public void onSessionTerminated() {
- /* empty */
- }
-
- /**
- * Called when a discovery (publish or subscribe) operation results in a
- * service discovery.
- * <p>
- * Note that this method and
- * {@link #onServiceDiscoveredWithinRange(PeerHandle, byte[], List, int)} may be called
- * multiple times per service discovery.
- *
- * @param peerHandle An opaque handle to the peer matching our discovery operation.
- * @param serviceSpecificInfo The service specific information (arbitrary
- * byte array) provided by the peer as part of its discovery
- * configuration.
- * @param matchFilter The filter which resulted in this service discovery. For
- * {@link PublishConfig#PUBLISH_TYPE_UNSOLICITED},
- * {@link SubscribeConfig#SUBSCRIBE_TYPE_PASSIVE} discovery sessions this is the publisher's
- * match filter. For {@link PublishConfig#PUBLISH_TYPE_SOLICITED},
- * {@link SubscribeConfig#SUBSCRIBE_TYPE_ACTIVE} discovery sessions this
- * is the subscriber's match filter.
- */
- public void onServiceDiscovered(PeerHandle peerHandle,
- byte[] serviceSpecificInfo, List<byte[]> matchFilter) {
- /* empty */
- }
-
- /**
- * Called when a discovery (publish or subscribe) operation results in a
- * service discovery. Called when a Subscribe service was configured with a range requirement
- * {@link SubscribeConfig.Builder#setMinDistanceMm(int)} and/or
- * {@link SubscribeConfig.Builder#setMaxDistanceMm(int)} and the Publish service was configured
- * with {@link PublishConfig.Builder#setRangingEnabled(boolean)}.
- * <p>
- * If either Publisher or Subscriber does not enable Ranging, or if Ranging is temporarily
- * disabled by the underlying device, service discovery proceeds without ranging and the
- * {@link #onServiceDiscovered(PeerHandle, byte[], List)} is called.
- * <p>
- * Note that this method and {@link #onServiceDiscovered(PeerHandle, byte[], List)} may be
- * called multiple times per service discovery.
- *
- * @param peerHandle An opaque handle to the peer matching our discovery operation.
- * @param serviceSpecificInfo The service specific information (arbitrary
- * byte array) provided by the peer as part of its discovery
- * configuration.
- * @param matchFilter The filter which resulted in this service discovery. For
- * {@link PublishConfig#PUBLISH_TYPE_UNSOLICITED},
- * {@link SubscribeConfig#SUBSCRIBE_TYPE_PASSIVE} discovery sessions this is the publisher's
- * match filter. For {@link PublishConfig#PUBLISH_TYPE_SOLICITED},
- * {@link SubscribeConfig#SUBSCRIBE_TYPE_ACTIVE} discovery sessions this
- * is the subscriber's match filter.
- * @param distanceMm The measured distance to the Publisher in mm. Note: the measured distance
- * may be negative for very close devices.
- */
- public void onServiceDiscoveredWithinRange(PeerHandle peerHandle,
- byte[] serviceSpecificInfo, List<byte[]> matchFilter, int distanceMm) {
- /* empty */
- }
-
- /**
- * Called in response to
- * {@link DiscoverySession#sendMessage(PeerHandle, int, byte[])}
- * when a message is transmitted successfully - i.e. when it was received successfully by the
- * peer (corresponds to an ACK being received).
- * <p>
- * Note that either this callback or
- * {@link DiscoverySessionCallback#onMessageSendFailed(int)} will be
- * received - never both.
- *
- * @param messageId The arbitrary message ID specified when sending the message.
- */
- public void onMessageSendSucceeded(@SuppressWarnings("unused") int messageId) {
- /* empty */
- }
-
- /**
- * Called when message transmission initiated with
- * {@link DiscoverySession#sendMessage(PeerHandle, int, byte[])} fails. E.g. when no ACK is
- * received from the peer.
- * <p>
- * Note that either this callback or
- * {@link DiscoverySessionCallback#onMessageSendSucceeded(int)} will be received
- * - never both.
- *
- * @param messageId The arbitrary message ID specified when sending the message.
- */
- public void onMessageSendFailed(@SuppressWarnings("unused") int messageId) {
- /* empty */
- }
-
- /**
- * Called when a message is received from a discovery session peer - in response to the
- * peer's {@link DiscoverySession#sendMessage(PeerHandle, int, byte[])}.
- *
- * @param peerHandle An opaque handle to the peer matching our discovery operation.
- * @param message A byte array containing the message.
- */
- public void onMessageReceived(PeerHandle peerHandle, byte[] message) {
- /* empty */
- }
-
- /**
- * Called when the discovered service is not available. All further operations on this
- * discovery session will fail. If the service is available again,
- * {@link #onServiceDiscovered(PeerHandle, byte[], List)} or
- * {@link #onServiceDiscoveredWithinRange(PeerHandle, byte[], List, int)} will be called.
- *
- * @param peerHandle An opaque handle to the peer matching our discovery operation.
- * @param reason Discovered service lost reason code. One of
- * {@link WifiAwareManager#WIFI_AWARE_DISCOVERY_LOST_REASON_PEER_NOT_VISIBLE},
- * {@link WifiAwareManager#WIFI_AWARE_DISCOVERY_LOST_REASON_UNKNOWN
- */
- public void onServiceLost(@NonNull PeerHandle peerHandle,
- @WifiAwareManager.DiscoveryLostReasonCode int reason) {
- /* empty */
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/IWifiAwareDiscoverySessionCallback.aidl b/wifi/java/android/net/wifi/aware/IWifiAwareDiscoverySessionCallback.aidl
deleted file mode 100644
index e3e7c8e6c747..000000000000
--- a/wifi/java/android/net/wifi/aware/IWifiAwareDiscoverySessionCallback.aidl
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-/**
- * Callback interface that WifiAwareManager implements
- *
- * {@hide}
- */
-oneway interface IWifiAwareDiscoverySessionCallback
-{
- void onSessionStarted(int discoverySessionId);
- void onSessionConfigSuccess();
- void onSessionConfigFail(int reason);
- void onSessionTerminated(int reason);
-
- void onMatch(int peerId, in byte[] serviceSpecificInfo, in byte[] matchFilter);
- void onMatchWithDistance(int peerId, in byte[] serviceSpecificInfo, in byte[] matchFilter,
- int distanceMm);
-
- void onMessageSendSuccess(int messageId);
- void onMessageSendFail(int messageId, int reason);
- void onMessageReceived(int peerId, in byte[] message);
- void onMatchExpired(int peerId);
-}
diff --git a/wifi/java/android/net/wifi/aware/IWifiAwareEventCallback.aidl b/wifi/java/android/net/wifi/aware/IWifiAwareEventCallback.aidl
deleted file mode 100644
index b646567512ac..000000000000
--- a/wifi/java/android/net/wifi/aware/IWifiAwareEventCallback.aidl
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.net.wifi.aware.ConfigRequest;
-
-/**
- * Callback interface that WifiAwareManager implements
- *
- * {@hide}
- */
-oneway interface IWifiAwareEventCallback
-{
- void onConnectSuccess(int clientId);
- void onConnectFail(int reason);
- void onIdentityChanged(in byte[] mac);
-}
diff --git a/wifi/java/android/net/wifi/aware/IWifiAwareMacAddressProvider.aidl b/wifi/java/android/net/wifi/aware/IWifiAwareMacAddressProvider.aidl
deleted file mode 100644
index 0e7289cd9c46..000000000000
--- a/wifi/java/android/net/wifi/aware/IWifiAwareMacAddressProvider.aidl
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2017 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.aware;
-
-/**
- * Callback for IWifiAwareManager.getMacAddressFromPeerHandle
- *
- * @hide
- */
-oneway interface IWifiAwareMacAddressProvider
-{
- void macAddress(in Map peerIdToMacMap);
-}
diff --git a/wifi/java/android/net/wifi/aware/IWifiAwareManager.aidl b/wifi/java/android/net/wifi/aware/IWifiAwareManager.aidl
deleted file mode 100644
index c90c4d8a27b2..000000000000
--- a/wifi/java/android/net/wifi/aware/IWifiAwareManager.aidl
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.app.PendingIntent;
-
-import android.net.wifi.aware.ConfigRequest;
-import android.net.wifi.aware.IWifiAwareDiscoverySessionCallback;
-import android.net.wifi.aware.IWifiAwareEventCallback;
-import android.net.wifi.aware.IWifiAwareMacAddressProvider;
-import android.net.wifi.aware.PublishConfig;
-import android.net.wifi.aware.SubscribeConfig;
-import android.net.wifi.aware.Characteristics;
-import android.net.wifi.aware.AwareResources;
-
-/**
- * Interface that WifiAwareService implements
- *
- * {@hide}
- */
-interface IWifiAwareManager
-{
- // Aware API
- boolean isUsageEnabled();
- Characteristics getCharacteristics();
- AwareResources getAvailableAwareResources();
- boolean isDeviceAttached();
- void enableInstantCommunicationMode(in String callingPackage, boolean enable);
- boolean isInstantCommunicationModeEnabled();
-
- // client API
- void connect(in IBinder binder, in String callingPackage, in String callingFeatureId,
- in IWifiAwareEventCallback callback, in ConfigRequest configRequest,
- boolean notifyOnIdentityChanged);
- void disconnect(int clientId, in IBinder binder);
-
- void publish(in String callingPackage, in String callingFeatureId, int clientId,
- in PublishConfig publishConfig, in IWifiAwareDiscoverySessionCallback callback);
- void subscribe(in String callingPackage, in String callingFeatureId, int clientId,
- in SubscribeConfig subscribeConfig, in IWifiAwareDiscoverySessionCallback callback);
-
- // session API
- void updatePublish(int clientId, int discoverySessionId, in PublishConfig publishConfig);
- void updateSubscribe(int clientId, int discoverySessionId, in SubscribeConfig subscribeConfig);
- void sendMessage(int clientId, int discoverySessionId, int peerId, in byte[] message,
- int messageId, int retryCount);
- void terminateSession(int clientId, int discoverySessionId);
-
- // internal APIs: intended to be used between System Services (restricted permissions)
- void requestMacAddresses(int uid, in List peerIds, in IWifiAwareMacAddressProvider callback);
-}
diff --git a/wifi/java/android/net/wifi/aware/IdentityChangedListener.java b/wifi/java/android/net/wifi/aware/IdentityChangedListener.java
deleted file mode 100644
index a8b19b3e2f64..000000000000
--- a/wifi/java/android/net/wifi/aware/IdentityChangedListener.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-/**
- * Base class for a listener which is called with the MAC address of the Aware interface whenever
- * it is changed. Change may be due to device joining a cluster, starting a cluster, or discovery
- * interface change (addresses are randomized at regular intervals). The implication is that
- * peers you've been communicating with may no longer recognize you and you need to re-establish
- * your identity - e.g. by starting a discovery session. This actual MAC address of the
- * interface may also be useful if the application uses alternative (non-Aware) discovery but needs
- * to set up a Aware connection. The provided Aware discovery interface MAC address can then be used
- * in {@link WifiAwareSession#createNetworkSpecifierOpen(int, byte[])} or
- * {@link WifiAwareSession#createNetworkSpecifierPassphrase(int, byte[], String)}.
- */
-public class IdentityChangedListener {
- /**
- * @param mac The MAC address of the Aware discovery interface. The application must have the
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} to get the actual MAC address,
- * otherwise all 0's will be provided.
- */
- public void onIdentityChanged(byte[] mac) {
- /* empty */
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/ParcelablePeerHandle.java b/wifi/java/android/net/wifi/aware/ParcelablePeerHandle.java
deleted file mode 100644
index ca473db691e3..000000000000
--- a/wifi/java/android/net/wifi/aware/ParcelablePeerHandle.java
+++ /dev/null
@@ -1,60 +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 android.net.wifi.aware;
-
-import android.annotation.NonNull;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * A Parcelable {@link PeerHandle}. Can be constructed from a {@code PeerHandle} and then passed
- * to any of the APIs which take a {@code PeerHandle} as inputs.
- */
-public final class ParcelablePeerHandle extends PeerHandle implements Parcelable {
- /**
- * Construct a parcelable version of {@link PeerHandle}.
- *
- * @param peerHandle The {@link PeerHandle} to be made parcelable.
- */
- public ParcelablePeerHandle(@NonNull PeerHandle peerHandle) {
- super(peerHandle.peerId);
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(peerId);
- }
-
- public static final @android.annotation.NonNull Creator<ParcelablePeerHandle> CREATOR =
- new Creator<ParcelablePeerHandle>() {
- @Override
- public ParcelablePeerHandle[] newArray(int size) {
- return new ParcelablePeerHandle[size];
- }
-
- @Override
- public ParcelablePeerHandle createFromParcel(Parcel in) {
- int peerHandle = in.readInt();
- return new ParcelablePeerHandle(new PeerHandle(peerHandle));
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/aware/PeerHandle.java b/wifi/java/android/net/wifi/aware/PeerHandle.java
deleted file mode 100644
index 422e177ed7ad..000000000000
--- a/wifi/java/android/net/wifi/aware/PeerHandle.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-/**
- * Opaque object used to represent a Wi-Fi Aware peer. Obtained from discovery sessions in
- * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle, byte[], java.util.List)} or
- * received messages in {@link DiscoverySessionCallback#onMessageReceived(PeerHandle, byte[])}, and
- * used when sending messages e,g, {@link DiscoverySession#sendMessage(PeerHandle, int, byte[])},
- * or when configuring a network link to a peer, e.g.
- * {@link DiscoverySession#createNetworkSpecifierOpen(PeerHandle)} or
- * {@link DiscoverySession#createNetworkSpecifierPassphrase(PeerHandle, String)}.
- * <p>
- * Note that while a {@code PeerHandle} can be used to track a particular peer (i.e. you can compare
- * the values received from subsequent messages) - it is good practice not to rely on it. Instead
- * use an application level peer identifier encoded in the message,
- * {@link DiscoverySession#sendMessage(PeerHandle, int, byte[])}, and/or in the Publish
- * configuration's service-specific information field,
- * {@link PublishConfig.Builder#setServiceSpecificInfo(byte[])}, or match filter,
- * {@link PublishConfig.Builder#setMatchFilter(java.util.List)}.
- * <p>A parcelable handle object is available with {@link ParcelablePeerHandle}.
- */
-public class PeerHandle {
- /** @hide */
- public PeerHandle(int peerId) {
- this.peerId = peerId;
- }
-
- /** @hide */
- public int peerId;
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
-
- if (!(o instanceof PeerHandle)) {
- return false;
- }
-
- return peerId == ((PeerHandle) o).peerId;
- }
-
- @Override
- public int hashCode() {
- return peerId;
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/PublishConfig.java b/wifi/java/android/net/wifi/aware/PublishConfig.java
deleted file mode 100644
index a8844c1d3812..000000000000
--- a/wifi/java/android/net/wifi/aware/PublishConfig.java
+++ /dev/null
@@ -1,393 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.net.wifi.util.HexEncoding;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * Defines the configuration of a Aware publish session. Built using
- * {@link PublishConfig.Builder}. A publish session is created using
- * {@link WifiAwareSession#publish(PublishConfig, DiscoverySessionCallback,
- * android.os.Handler)} or updated using
- * {@link PublishDiscoverySession#updatePublish(PublishConfig)}.
- */
-public final class PublishConfig implements Parcelable {
- /** @hide */
- @IntDef({
- PUBLISH_TYPE_UNSOLICITED, PUBLISH_TYPE_SOLICITED })
- @Retention(RetentionPolicy.SOURCE)
- public @interface PublishTypes {
- }
-
- /**
- * Defines an unsolicited publish session - a publish session where the publisher is
- * advertising itself by broadcasting on-the-air. An unsolicited publish session is paired
- * with an passive subscribe session {@link SubscribeConfig#SUBSCRIBE_TYPE_PASSIVE}.
- * Configuration is done using {@link PublishConfig.Builder#setPublishType(int)}.
- */
- public static final int PUBLISH_TYPE_UNSOLICITED = 0;
-
- /**
- * Defines a solicited publish session - a publish session which is silent, waiting for a
- * matching active subscribe session - and responding to it in unicast. A
- * solicited publish session is paired with an active subscribe session
- * {@link SubscribeConfig#SUBSCRIBE_TYPE_ACTIVE}. Configuration is done using
- * {@link PublishConfig.Builder#setPublishType(int)}.
- */
- public static final int PUBLISH_TYPE_SOLICITED = 1;
-
- /** @hide */
- public final byte[] mServiceName;
-
- /** @hide */
- public final byte[] mServiceSpecificInfo;
-
- /** @hide */
- public final byte[] mMatchFilter;
-
- /** @hide */
- public final int mPublishType;
-
- /** @hide */
- public final int mTtlSec;
-
- /** @hide */
- public final boolean mEnableTerminateNotification;
-
- /** @hide */
- public final boolean mEnableRanging;
-
- /** @hide */
- public PublishConfig(byte[] serviceName, byte[] serviceSpecificInfo, byte[] matchFilter,
- int publishType, int ttlSec, boolean enableTerminateNotification,
- boolean enableRanging) {
- mServiceName = serviceName;
- mServiceSpecificInfo = serviceSpecificInfo;
- mMatchFilter = matchFilter;
- mPublishType = publishType;
- mTtlSec = ttlSec;
- mEnableTerminateNotification = enableTerminateNotification;
- mEnableRanging = enableRanging;
- }
-
- @Override
- public String toString() {
- return "PublishConfig [mServiceName='" + (mServiceName == null ? "<null>" : String.valueOf(
- HexEncoding.encode(mServiceName))) + ", mServiceName.length=" + (
- mServiceName == null ? 0 : mServiceName.length) + ", mServiceSpecificInfo='" + (
- (mServiceSpecificInfo == null) ? "<null>" : String.valueOf(
- HexEncoding.encode(mServiceSpecificInfo)))
- + ", mServiceSpecificInfo.length=" + (mServiceSpecificInfo == null ? 0
- : mServiceSpecificInfo.length) + ", mMatchFilter="
- + (new TlvBufferUtils.TlvIterable(0, 1, mMatchFilter)).toString()
- + ", mMatchFilter.length=" + (mMatchFilter == null ? 0 : mMatchFilter.length)
- + ", mPublishType=" + mPublishType + ", mTtlSec=" + mTtlSec
- + ", mEnableTerminateNotification=" + mEnableTerminateNotification
- + ", mEnableRanging=" + mEnableRanging + "]";
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeByteArray(mServiceName);
- dest.writeByteArray(mServiceSpecificInfo);
- dest.writeByteArray(mMatchFilter);
- dest.writeInt(mPublishType);
- dest.writeInt(mTtlSec);
- dest.writeInt(mEnableTerminateNotification ? 1 : 0);
- dest.writeInt(mEnableRanging ? 1 : 0);
- }
-
- public static final @android.annotation.NonNull Creator<PublishConfig> CREATOR = new Creator<PublishConfig>() {
- @Override
- public PublishConfig[] newArray(int size) {
- return new PublishConfig[size];
- }
-
- @Override
- public PublishConfig createFromParcel(Parcel in) {
- byte[] serviceName = in.createByteArray();
- byte[] ssi = in.createByteArray();
- byte[] matchFilter = in.createByteArray();
- int publishType = in.readInt();
- int ttlSec = in.readInt();
- boolean enableTerminateNotification = in.readInt() != 0;
- boolean enableRanging = in.readInt() != 0;
-
- return new PublishConfig(serviceName, ssi, matchFilter, publishType,
- ttlSec, enableTerminateNotification, enableRanging);
- }
- };
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
-
- if (!(o instanceof PublishConfig)) {
- return false;
- }
-
- PublishConfig lhs = (PublishConfig) o;
-
- return Arrays.equals(mServiceName, lhs.mServiceName) && Arrays.equals(mServiceSpecificInfo,
- lhs.mServiceSpecificInfo) && Arrays.equals(mMatchFilter, lhs.mMatchFilter)
- && mPublishType == lhs.mPublishType
- && mTtlSec == lhs.mTtlSec
- && mEnableTerminateNotification == lhs.mEnableTerminateNotification
- && mEnableRanging == lhs.mEnableRanging;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(Arrays.hashCode(mServiceName), Arrays.hashCode(mServiceSpecificInfo),
- Arrays.hashCode(mMatchFilter), mPublishType, mTtlSec, mEnableTerminateNotification,
- mEnableRanging);
- }
-
- /**
- * Verifies that the contents of the PublishConfig are valid. Otherwise
- * throws an IllegalArgumentException.
- *
- * @hide
- */
- public void assertValid(Characteristics characteristics, boolean rttSupported)
- throws IllegalArgumentException {
- WifiAwareUtils.validateServiceName(mServiceName);
-
- if (!TlvBufferUtils.isValid(mMatchFilter, 0, 1)) {
- throw new IllegalArgumentException(
- "Invalid txFilter configuration - LV fields do not match up to length");
- }
- if (mPublishType < PUBLISH_TYPE_UNSOLICITED || mPublishType > PUBLISH_TYPE_SOLICITED) {
- throw new IllegalArgumentException("Invalid publishType - " + mPublishType);
- }
- if (mTtlSec < 0) {
- throw new IllegalArgumentException("Invalid ttlSec - must be non-negative");
- }
-
- if (characteristics != null) {
- int maxServiceNameLength = characteristics.getMaxServiceNameLength();
- if (maxServiceNameLength != 0 && mServiceName.length > maxServiceNameLength) {
- throw new IllegalArgumentException(
- "Service name longer than supported by device characteristics");
- }
- int maxServiceSpecificInfoLength = characteristics.getMaxServiceSpecificInfoLength();
- if (maxServiceSpecificInfoLength != 0 && mServiceSpecificInfo != null
- && mServiceSpecificInfo.length > maxServiceSpecificInfoLength) {
- throw new IllegalArgumentException(
- "Service specific info longer than supported by device characteristics");
- }
- int maxMatchFilterLength = characteristics.getMaxMatchFilterLength();
- if (maxMatchFilterLength != 0 && mMatchFilter != null
- && mMatchFilter.length > maxMatchFilterLength) {
- throw new IllegalArgumentException(
- "Match filter longer than supported by device characteristics");
- }
- }
-
- if (!rttSupported && mEnableRanging) {
- throw new IllegalArgumentException("Ranging is not supported");
- }
- }
-
- /**
- * Builder used to build {@link PublishConfig} objects.
- */
- public static final class Builder {
- private byte[] mServiceName;
- private byte[] mServiceSpecificInfo;
- private byte[] mMatchFilter;
- private int mPublishType = PUBLISH_TYPE_UNSOLICITED;
- private int mTtlSec = 0;
- private boolean mEnableTerminateNotification = true;
- private boolean mEnableRanging = false;
-
- /**
- * Specify the service name of the publish session. The actual on-air
- * value is a 6 byte hashed representation of this string.
- * <p>
- * The Service Name is a UTF-8 encoded string from 1 to 255 bytes in length.
- * The only acceptable single-byte UTF-8 symbols for a Service Name are alphanumeric
- * values (A-Z, a-z, 0-9), the hyphen ('-'), and the period ('.'). All valid multi-byte
- * UTF-8 characters are acceptable in a Service Name.
- * <p>
- * Must be called - an empty ServiceName is not valid.
- *
- * @param serviceName The service name for the publish session.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setServiceName(@NonNull String serviceName) {
- if (serviceName == null) {
- throw new IllegalArgumentException("Invalid service name - must be non-null");
- }
- mServiceName = serviceName.getBytes(StandardCharsets.UTF_8);
- return this;
- }
-
- /**
- * Specify service specific information for the publish session. This is
- * a free-form byte array available to the application to send
- * additional information as part of the discovery operation - it
- * will not be used to determine whether a publish/subscribe match
- * occurs.
- * <p>
- * Optional. Empty by default.
- *
- * @param serviceSpecificInfo A byte-array for the service-specific
- * information field.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setServiceSpecificInfo(@Nullable byte[] serviceSpecificInfo) {
- mServiceSpecificInfo = serviceSpecificInfo;
- return this;
- }
-
- /**
- * The match filter for a publish session. Used to determine whether a service
- * discovery occurred - in addition to relying on the service name.
- * <p>
- * Optional. Empty by default.
- *
- * @param matchFilter A list of match filter entries (each of which is an arbitrary byte
- * array).
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setMatchFilter(@Nullable List<byte[]> matchFilter) {
- mMatchFilter = new TlvBufferUtils.TlvConstructor(0, 1).allocateAndPut(
- matchFilter).getArray();
- return this;
- }
-
- /**
- * Specify the type of the publish session: solicited (aka active - publish
- * packets are transmitted over-the-air), or unsolicited (aka passive -
- * no publish packets are transmitted, a match is made against an active
- * subscribe session whose packets are transmitted over-the-air).
- *
- * @param publishType Publish session type:
- * {@link PublishConfig#PUBLISH_TYPE_SOLICITED} or
- * {@link PublishConfig#PUBLISH_TYPE_UNSOLICITED} (the default).
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setPublishType(@PublishTypes int publishType) {
- if (publishType < PUBLISH_TYPE_UNSOLICITED || publishType > PUBLISH_TYPE_SOLICITED) {
- throw new IllegalArgumentException("Invalid publishType - " + publishType);
- }
- mPublishType = publishType;
- return this;
- }
-
- /**
- * Sets the time interval (in seconds) an unsolicited (
- * {@link PublishConfig.Builder#setPublishType(int)}) publish session
- * will be alive - broadcasting a packet. When the TTL is reached
- * an event will be generated for
- * {@link DiscoverySessionCallback#onSessionTerminated()} [unless
- * {@link #setTerminateNotificationEnabled(boolean)} disables the callback].
- * <p>
- * Optional. 0 by default - indicating the session doesn't terminate on its own.
- * Session will be terminated when {@link DiscoverySession#close()} is
- * called.
- *
- * @param ttlSec Lifetime of a publish session in seconds.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setTtlSec(int ttlSec) {
- if (ttlSec < 0) {
- throw new IllegalArgumentException("Invalid ttlSec - must be non-negative");
- }
- mTtlSec = ttlSec;
- return this;
- }
-
- /**
- * Configure whether a publish terminate notification
- * {@link DiscoverySessionCallback#onSessionTerminated()} is reported
- * back to the callback.
- *
- * @param enable If true the terminate callback will be called when the
- * publish is terminated. Otherwise it will not be called.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setTerminateNotificationEnabled(boolean enable) {
- mEnableTerminateNotification = enable;
- return this;
- }
-
- /**
- * Configure whether the publish discovery session supports ranging and allows peers to
- * measure distance to it. This API is used in conjunction with
- * {@link SubscribeConfig.Builder#setMinDistanceMm(int)} and
- * {@link SubscribeConfig.Builder#setMaxDistanceMm(int)} to specify a minimum and/or
- * maximum distance at which discovery will be triggered.
- * <p>
- * Optional. Disabled by default - i.e. any peer attempt to measure distance to this device
- * will be refused and discovery will proceed without ranging constraints.
- * <p>
- * The device must support Wi-Fi RTT for this feature to be used. Feature support is checked
- * as described in {@link android.net.wifi.rtt}.
- *
- * @param enable If true, ranging is supported on request of the peer.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setRangingEnabled(boolean enable) {
- mEnableRanging = enable;
- return this;
- }
-
- /**
- * Build {@link PublishConfig} given the current requests made on the
- * builder.
- */
- public PublishConfig build() {
- return new PublishConfig(mServiceName, mServiceSpecificInfo, mMatchFilter, mPublishType,
- mTtlSec, mEnableTerminateNotification, mEnableRanging);
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/PublishDiscoverySession.java b/wifi/java/android/net/wifi/aware/PublishDiscoverySession.java
deleted file mode 100644
index 1c99c87195a9..000000000000
--- a/wifi/java/android/net/wifi/aware/PublishDiscoverySession.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.annotation.NonNull;
-import android.util.Log;
-
-/**
- * A class representing a Aware publish session. Created when
- * {@link WifiAwareSession#publish(PublishConfig, DiscoverySessionCallback,
- * android.os.Handler)} is called and a discovery session is created and returned in
- * {@link DiscoverySessionCallback#onPublishStarted(PublishDiscoverySession)}. See
- * baseline functionality of all discovery sessions in {@link DiscoverySession}. This
- * object allows updating an existing/running publish discovery session using
- * {@link #updatePublish(PublishConfig)}.
- */
-public class PublishDiscoverySession extends DiscoverySession {
- private static final String TAG = "PublishDiscoverySession";
-
- /** @hide */
- public PublishDiscoverySession(WifiAwareManager manager, int clientId, int sessionId) {
- super(manager, clientId, sessionId);
- }
-
- /**
- * Re-configure the currently active publish session. The
- * {@link DiscoverySessionCallback} is not replaced - the same listener used
- * at creation is still used. The results of the configuration are returned using
- * {@link DiscoverySessionCallback}:
- * <ul>
- * <li>{@link DiscoverySessionCallback#onSessionConfigUpdated()}: configuration
- * update succeeded.
- * <li>{@link DiscoverySessionCallback#onSessionConfigFailed()}: configuration
- * update failed. The publish discovery session is still running using its previous
- * configuration (i.e. update failure does not terminate the session).
- * </ul>
- *
- * @param publishConfig The new discovery publish session configuration ({@link PublishConfig}).
- */
- public void updatePublish(@NonNull PublishConfig publishConfig) {
- if (mTerminated) {
- Log.w(TAG, "updatePublish: called on terminated session");
- return;
- } else {
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.w(TAG, "updatePublish: called post GC on WifiAwareManager");
- return;
- }
-
- mgr.updatePublish(mClientId, mSessionId, publishConfig);
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/SubscribeConfig.java b/wifi/java/android/net/wifi/aware/SubscribeConfig.java
deleted file mode 100644
index 76780f421af2..000000000000
--- a/wifi/java/android/net/wifi/aware/SubscribeConfig.java
+++ /dev/null
@@ -1,497 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.net.wifi.util.HexEncoding;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * Defines the configuration of a Aware subscribe session. Built using
- * {@link SubscribeConfig.Builder}. Subscribe is done using
- * {@link WifiAwareSession#subscribe(SubscribeConfig, DiscoverySessionCallback,
- * android.os.Handler)} or
- * {@link SubscribeDiscoverySession#updateSubscribe(SubscribeConfig)}.
- */
-public final class SubscribeConfig implements Parcelable {
- /** @hide */
- @IntDef({
- SUBSCRIBE_TYPE_PASSIVE, SUBSCRIBE_TYPE_ACTIVE })
- @Retention(RetentionPolicy.SOURCE)
- public @interface SubscribeTypes {
- }
-
- /**
- * Defines a passive subscribe session - a subscribe session where
- * subscribe packets are not transmitted over-the-air and the device listens
- * and matches to transmitted publish packets. Configuration is done using
- * {@link SubscribeConfig.Builder#setSubscribeType(int)}.
- */
- public static final int SUBSCRIBE_TYPE_PASSIVE = 0;
-
- /**
- * Defines an active subscribe session - a subscribe session where
- * subscribe packets are transmitted over-the-air. Configuration is done
- * using {@link SubscribeConfig.Builder#setSubscribeType(int)}.
- */
- public static final int SUBSCRIBE_TYPE_ACTIVE = 1;
-
- /** @hide */
- public final byte[] mServiceName;
-
- /** @hide */
- public final byte[] mServiceSpecificInfo;
-
- /** @hide */
- public final byte[] mMatchFilter;
-
- /** @hide */
- public final int mSubscribeType;
-
- /** @hide */
- public final int mTtlSec;
-
- /** @hide */
- public final boolean mEnableTerminateNotification;
-
- /** @hide */
- public final boolean mMinDistanceMmSet;
-
- /** @hide */
- public final int mMinDistanceMm;
-
- /** @hide */
- public final boolean mMaxDistanceMmSet;
-
- /** @hide */
- public final int mMaxDistanceMm;
-
- /** @hide */
- public SubscribeConfig(byte[] serviceName, byte[] serviceSpecificInfo, byte[] matchFilter,
- int subscribeType, int ttlSec, boolean enableTerminateNotification,
- boolean minDistanceMmSet, int minDistanceMm, boolean maxDistanceMmSet,
- int maxDistanceMm) {
- mServiceName = serviceName;
- mServiceSpecificInfo = serviceSpecificInfo;
- mMatchFilter = matchFilter;
- mSubscribeType = subscribeType;
- mTtlSec = ttlSec;
- mEnableTerminateNotification = enableTerminateNotification;
- mMinDistanceMm = minDistanceMm;
- mMinDistanceMmSet = minDistanceMmSet;
- mMaxDistanceMm = maxDistanceMm;
- mMaxDistanceMmSet = maxDistanceMmSet;
- }
-
- @Override
- public String toString() {
- return "SubscribeConfig [mServiceName='" + (mServiceName == null ? "<null>"
- : String.valueOf(HexEncoding.encode(mServiceName))) + ", mServiceName.length=" + (
- mServiceName == null ? 0 : mServiceName.length) + ", mServiceSpecificInfo='" + (
- (mServiceSpecificInfo == null) ? "<null>" : String.valueOf(
- HexEncoding.encode(mServiceSpecificInfo)))
- + ", mServiceSpecificInfo.length=" + (mServiceSpecificInfo == null ? 0
- : mServiceSpecificInfo.length) + ", mMatchFilter="
- + (new TlvBufferUtils.TlvIterable(0, 1, mMatchFilter)).toString()
- + ", mMatchFilter.length=" + (mMatchFilter == null ? 0 : mMatchFilter.length)
- + ", mSubscribeType=" + mSubscribeType + ", mTtlSec=" + mTtlSec
- + ", mEnableTerminateNotification=" + mEnableTerminateNotification
- + ", mMinDistanceMm=" + mMinDistanceMm
- + ", mMinDistanceMmSet=" + mMinDistanceMmSet
- + ", mMaxDistanceMm=" + mMaxDistanceMm
- + ", mMaxDistanceMmSet=" + mMaxDistanceMmSet + "]";
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeByteArray(mServiceName);
- dest.writeByteArray(mServiceSpecificInfo);
- dest.writeByteArray(mMatchFilter);
- dest.writeInt(mSubscribeType);
- dest.writeInt(mTtlSec);
- dest.writeInt(mEnableTerminateNotification ? 1 : 0);
- dest.writeInt(mMinDistanceMm);
- dest.writeInt(mMinDistanceMmSet ? 1 : 0);
- dest.writeInt(mMaxDistanceMm);
- dest.writeInt(mMaxDistanceMmSet ? 1 : 0);
- }
-
- public static final @android.annotation.NonNull Creator<SubscribeConfig> CREATOR = new Creator<SubscribeConfig>() {
- @Override
- public SubscribeConfig[] newArray(int size) {
- return new SubscribeConfig[size];
- }
-
- @Override
- public SubscribeConfig createFromParcel(Parcel in) {
- byte[] serviceName = in.createByteArray();
- byte[] ssi = in.createByteArray();
- byte[] matchFilter = in.createByteArray();
- int subscribeType = in.readInt();
- int ttlSec = in.readInt();
- boolean enableTerminateNotification = in.readInt() != 0;
- int minDistanceMm = in.readInt();
- boolean minDistanceMmSet = in.readInt() != 0;
- int maxDistanceMm = in.readInt();
- boolean maxDistanceMmSet = in.readInt() != 0;
-
- return new SubscribeConfig(serviceName, ssi, matchFilter, subscribeType, ttlSec,
- enableTerminateNotification, minDistanceMmSet, minDistanceMm, maxDistanceMmSet,
- maxDistanceMm);
- }
- };
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
-
- if (!(o instanceof SubscribeConfig)) {
- return false;
- }
-
- SubscribeConfig lhs = (SubscribeConfig) o;
-
- if (!(Arrays.equals(mServiceName, lhs.mServiceName) && Arrays.equals(
- mServiceSpecificInfo, lhs.mServiceSpecificInfo) && Arrays.equals(mMatchFilter,
- lhs.mMatchFilter) && mSubscribeType == lhs.mSubscribeType && mTtlSec == lhs.mTtlSec
- && mEnableTerminateNotification == lhs.mEnableTerminateNotification
- && mMinDistanceMmSet == lhs.mMinDistanceMmSet
- && mMaxDistanceMmSet == lhs.mMaxDistanceMmSet)) {
- return false;
- }
-
- if (mMinDistanceMmSet && mMinDistanceMm != lhs.mMinDistanceMm) {
- return false;
- }
-
- if (mMaxDistanceMmSet && mMaxDistanceMm != lhs.mMaxDistanceMm) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int hashCode() {
- int result = Objects.hash(Arrays.hashCode(mServiceName),
- Arrays.hashCode(mServiceSpecificInfo), Arrays.hashCode(mMatchFilter),
- mSubscribeType, mTtlSec, mEnableTerminateNotification, mMinDistanceMmSet,
- mMaxDistanceMmSet);
-
- if (mMinDistanceMmSet) {
- result = Objects.hash(result, mMinDistanceMm);
- }
- if (mMaxDistanceMmSet) {
- result = Objects.hash(result, mMaxDistanceMm);
- }
-
- return result;
- }
-
- /**
- * Verifies that the contents of the SubscribeConfig are valid. Otherwise
- * throws an IllegalArgumentException.
- *
- * @hide
- */
- public void assertValid(Characteristics characteristics, boolean rttSupported)
- throws IllegalArgumentException {
- WifiAwareUtils.validateServiceName(mServiceName);
-
- if (!TlvBufferUtils.isValid(mMatchFilter, 0, 1)) {
- throw new IllegalArgumentException(
- "Invalid matchFilter configuration - LV fields do not match up to length");
- }
- if (mSubscribeType < SUBSCRIBE_TYPE_PASSIVE || mSubscribeType > SUBSCRIBE_TYPE_ACTIVE) {
- throw new IllegalArgumentException("Invalid subscribeType - " + mSubscribeType);
- }
- if (mTtlSec < 0) {
- throw new IllegalArgumentException("Invalid ttlSec - must be non-negative");
- }
-
- if (characteristics != null) {
- int maxServiceNameLength = characteristics.getMaxServiceNameLength();
- if (maxServiceNameLength != 0 && mServiceName.length > maxServiceNameLength) {
- throw new IllegalArgumentException(
- "Service name longer than supported by device characteristics");
- }
- int maxServiceSpecificInfoLength = characteristics.getMaxServiceSpecificInfoLength();
- if (maxServiceSpecificInfoLength != 0 && mServiceSpecificInfo != null
- && mServiceSpecificInfo.length > maxServiceSpecificInfoLength) {
- throw new IllegalArgumentException(
- "Service specific info longer than supported by device characteristics");
- }
- int maxMatchFilterLength = characteristics.getMaxMatchFilterLength();
- if (maxMatchFilterLength != 0 && mMatchFilter != null
- && mMatchFilter.length > maxMatchFilterLength) {
- throw new IllegalArgumentException(
- "Match filter longer than supported by device characteristics");
- }
- }
-
- if (mMinDistanceMmSet && mMinDistanceMm < 0) {
- throw new IllegalArgumentException("Minimum distance must be non-negative");
- }
- if (mMaxDistanceMmSet && mMaxDistanceMm < 0) {
- throw new IllegalArgumentException("Maximum distance must be non-negative");
- }
- if (mMinDistanceMmSet && mMaxDistanceMmSet && mMaxDistanceMm <= mMinDistanceMm) {
- throw new IllegalArgumentException(
- "Maximum distance must be greater than minimum distance");
- }
-
- if (!rttSupported && (mMinDistanceMmSet || mMaxDistanceMmSet)) {
- throw new IllegalArgumentException("Ranging is not supported");
- }
- }
-
- /**
- * Builder used to build {@link SubscribeConfig} objects.
- */
- public static final class Builder {
- private byte[] mServiceName;
- private byte[] mServiceSpecificInfo;
- private byte[] mMatchFilter;
- private int mSubscribeType = SUBSCRIBE_TYPE_PASSIVE;
- private int mTtlSec = 0;
- private boolean mEnableTerminateNotification = true;
- private boolean mMinDistanceMmSet = false;
- private int mMinDistanceMm;
- private boolean mMaxDistanceMmSet = false;
- private int mMaxDistanceMm;
-
- /**
- * Specify the service name of the subscribe session. The actual on-air
- * value is a 6 byte hashed representation of this string.
- * <p>
- * The Service Name is a UTF-8 encoded string from 1 to 255 bytes in length.
- * The only acceptable single-byte UTF-8 symbols for a Service Name are alphanumeric
- * values (A-Z, a-z, 0-9), the hyphen ('-'), and the period ('.'). All valid multi-byte
- * UTF-8 characters are acceptable in a Service Name.
- * <p>
- * Must be called - an empty ServiceName is not valid.
- *
- * @param serviceName The service name for the subscribe session.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setServiceName(@NonNull String serviceName) {
- if (serviceName == null) {
- throw new IllegalArgumentException("Invalid service name - must be non-null");
- }
- mServiceName = serviceName.getBytes(StandardCharsets.UTF_8);
- return this;
- }
-
- /**
- * Specify service specific information for the subscribe session. This is
- * a free-form byte array available to the application to send
- * additional information as part of the discovery operation - i.e. it
- * will not be used to determine whether a publish/subscribe match
- * occurs.
- * <p>
- * Optional. Empty by default.
- *
- * @param serviceSpecificInfo A byte-array for the service-specific
- * information field.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setServiceSpecificInfo(@Nullable byte[] serviceSpecificInfo) {
- mServiceSpecificInfo = serviceSpecificInfo;
- return this;
- }
-
- /**
- * The match filter for a subscribe session. Used to determine whether a service
- * discovery occurred - in addition to relying on the service name.
- * <p>
- * Optional. Empty by default.
- *
- * @param matchFilter A list of match filter entries (each of which is an arbitrary byte
- * array).
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setMatchFilter(@Nullable List<byte[]> matchFilter) {
- mMatchFilter = new TlvBufferUtils.TlvConstructor(0, 1).allocateAndPut(
- matchFilter).getArray();
- return this;
- }
-
- /**
- * Sets the type of the subscribe session: active (subscribe packets are
- * transmitted over-the-air), or passive (no subscribe packets are
- * transmitted, a match is made against a solicited/active publish
- * session whose packets are transmitted over-the-air).
- *
- * @param subscribeType Subscribe session type:
- * {@link SubscribeConfig#SUBSCRIBE_TYPE_ACTIVE} or
- * {@link SubscribeConfig#SUBSCRIBE_TYPE_PASSIVE}.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setSubscribeType(@SubscribeTypes int subscribeType) {
- if (subscribeType < SUBSCRIBE_TYPE_PASSIVE || subscribeType > SUBSCRIBE_TYPE_ACTIVE) {
- throw new IllegalArgumentException("Invalid subscribeType - " + subscribeType);
- }
- mSubscribeType = subscribeType;
- return this;
- }
-
- /**
- * Sets the time interval (in seconds) an active (
- * {@link SubscribeConfig.Builder#setSubscribeType(int)}) subscribe session
- * will be alive - i.e. broadcasting a packet. When the TTL is reached
- * an event will be generated for
- * {@link DiscoverySessionCallback#onSessionTerminated()}.
- * <p>
- * Optional. 0 by default - indicating the session doesn't terminate on its own.
- * Session will be terminated when {@link DiscoverySession#close()} is
- * called.
- *
- * @param ttlSec Lifetime of a subscribe session in seconds.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setTtlSec(int ttlSec) {
- if (ttlSec < 0) {
- throw new IllegalArgumentException("Invalid ttlSec - must be non-negative");
- }
- mTtlSec = ttlSec;
- return this;
- }
-
- /**
- * Configure whether a subscribe terminate notification
- * {@link DiscoverySessionCallback#onSessionTerminated()} is reported
- * back to the callback.
- *
- * @param enable If true the terminate callback will be called when the
- * subscribe is terminated. Otherwise it will not be called.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setTerminateNotificationEnabled(boolean enable) {
- mEnableTerminateNotification = enable;
- return this;
- }
-
- /**
- * Configure the minimum distance to a discovered publisher at which to trigger a discovery
- * notification. I.e. discovery will be triggered if we've found a matching publisher
- * (based on the other criteria in this configuration) <b>and</b> the distance to the
- * publisher is larger than the value specified in this API. Can be used in conjunction with
- * {@link #setMaxDistanceMm(int)} to specify a geofence, i.e. discovery with min <=
- * distance <= max.
- * <p>
- * For ranging to be used in discovery it must also be enabled on the publisher using
- * {@link PublishConfig.Builder#setRangingEnabled(boolean)}. However, ranging may
- * not be available or enabled on the publisher or may be temporarily disabled on either
- * subscriber or publisher - in such cases discovery will proceed without ranging.
- * <p>
- * When ranging is enabled and available on both publisher and subscriber and a service
- * is discovered based on geofence constraints the
- * {@link DiscoverySessionCallback#onServiceDiscoveredWithinRange(PeerHandle, byte[], List, int)}
- * is called, otherwise the
- * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle, byte[], List)}
- * is called.
- * <p>
- * The device must support Wi-Fi RTT for this feature to be used. Feature support is checked
- * as described in {@link android.net.wifi.rtt}.
- *
- * @param minDistanceMm Minimum distance, in mm, to the publisher above which to trigger
- * discovery.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setMinDistanceMm(int minDistanceMm) {
- mMinDistanceMm = minDistanceMm;
- mMinDistanceMmSet = true;
- return this;
- }
-
- /**
- * Configure the maximum distance to a discovered publisher at which to trigger a discovery
- * notification. I.e. discovery will be triggered if we've found a matching publisher
- * (based on the other criteria in this configuration) <b>and</b> the distance to the
- * publisher is smaller than the value specified in this API. Can be used in conjunction
- * with {@link #setMinDistanceMm(int)} to specify a geofence, i.e. discovery with min <=
- * distance <= max.
- * <p>
- * For ranging to be used in discovery it must also be enabled on the publisher using
- * {@link PublishConfig.Builder#setRangingEnabled(boolean)}. However, ranging may
- * not be available or enabled on the publisher or may be temporarily disabled on either
- * subscriber or publisher - in such cases discovery will proceed without ranging.
- * <p>
- * When ranging is enabled and available on both publisher and subscriber and a service
- * is discovered based on geofence constraints the
- * {@link DiscoverySessionCallback#onServiceDiscoveredWithinRange(PeerHandle, byte[], List, int)}
- * is called, otherwise the
- * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle, byte[], List)}
- * is called.
- * <p>
- * The device must support Wi-Fi RTT for this feature to be used. Feature support is checked
- * as described in {@link android.net.wifi.rtt}.
- *
- * @param maxDistanceMm Maximum distance, in mm, to the publisher below which to trigger
- * discovery.
- *
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder setMaxDistanceMm(int maxDistanceMm) {
- mMaxDistanceMm = maxDistanceMm;
- mMaxDistanceMmSet = true;
- return this;
- }
-
- /**
- * Build {@link SubscribeConfig} given the current requests made on the
- * builder.
- */
- public SubscribeConfig build() {
- return new SubscribeConfig(mServiceName, mServiceSpecificInfo, mMatchFilter,
- mSubscribeType, mTtlSec, mEnableTerminateNotification,
- mMinDistanceMmSet, mMinDistanceMm, mMaxDistanceMmSet, mMaxDistanceMm);
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/SubscribeDiscoverySession.java b/wifi/java/android/net/wifi/aware/SubscribeDiscoverySession.java
deleted file mode 100644
index ca88a908cdbd..000000000000
--- a/wifi/java/android/net/wifi/aware/SubscribeDiscoverySession.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.annotation.NonNull;
-import android.util.Log;
-
-/**
- * A class representing a Aware subscribe session. Created when
- * {@link WifiAwareSession#subscribe(SubscribeConfig,
- * DiscoverySessionCallback, android.os.Handler)}
- * is called and a discovery session is created and returned in
- * {@link DiscoverySessionCallback#onSubscribeStarted(SubscribeDiscoverySession)}.
- * See baseline functionality of all discovery sessions in {@link DiscoverySession}.
- * This object allows updating an existing/running subscribe discovery session using
- * {@link #updateSubscribe(SubscribeConfig)}.
- */
-public class SubscribeDiscoverySession extends DiscoverySession {
- private static final String TAG = "SubscribeDiscSession";
-
- /**
- * {@hide}
- */
- public SubscribeDiscoverySession(WifiAwareManager manager, int clientId,
- int sessionId) {
- super(manager, clientId, sessionId);
- }
-
- /**
- * Re-configure the currently active subscribe session. The
- * {@link DiscoverySessionCallback} is not replaced - the same listener used
- * at creation is still used. The results of the configuration are returned using
- * {@link DiscoverySessionCallback}:
- * <ul>
- * <li>{@link DiscoverySessionCallback#onSessionConfigUpdated()}: configuration
- * update succeeded.
- * <li>{@link DiscoverySessionCallback#onSessionConfigFailed()}: configuration
- * update failed. The subscribe discovery session is still running using its previous
- * configuration (i.e. update failure does not terminate the session).
- * </ul>
- *
- * @param subscribeConfig The new discovery subscribe session configuration
- * ({@link SubscribeConfig}).
- */
- public void updateSubscribe(@NonNull SubscribeConfig subscribeConfig) {
- if (mTerminated) {
- Log.w(TAG, "updateSubscribe: called on terminated session");
- return;
- } else {
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.w(TAG, "updateSubscribe: called post GC on WifiAwareManager");
- return;
- }
-
- mgr.updateSubscribe(mClientId, mSessionId, subscribeConfig);
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/TlvBufferUtils.java b/wifi/java/android/net/wifi/aware/TlvBufferUtils.java
deleted file mode 100644
index 2d3cc1eda643..000000000000
--- a/wifi/java/android/net/wifi/aware/TlvBufferUtils.java
+++ /dev/null
@@ -1,714 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.annotation.Nullable;
-
-import java.nio.BufferOverflowException;
-import java.nio.ByteOrder;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-
-/**
- * Utility class to construct and parse byte arrays using the TLV format -
- * Type/Length/Value format. The utilities accept a configuration of the size of
- * the Type field and the Length field. A Type field size of 0 is allowed -
- * allowing usage for LV (no T) array formats.
- *
- * @hide
- */
-public class TlvBufferUtils {
- private TlvBufferUtils() {
- // no reason to ever create this class
- }
-
- /**
- * Utility class to construct byte arrays using the TLV format -
- * Type/Length/Value.
- * <p>
- * A constructor is created specifying the size of the Type (T) and Length
- * (L) fields. A specification of zero size T field is allowed - resulting
- * in LV type format.
- * <p>
- * The byte array is either provided (using
- * {@link TlvConstructor#wrap(byte[])}) or allocated (using
- * {@link TlvConstructor#allocate(int)}).
- * <p>
- * Values are added to the structure using the {@code TlvConstructor.put*()}
- * methods.
- * <p>
- * The final byte array is obtained using {@link TlvConstructor#getArray()}.
- */
- public static class TlvConstructor {
- private int mTypeSize;
- private int mLengthSize;
- private ByteOrder mByteOrder = ByteOrder.BIG_ENDIAN;
-
- private byte[] mArray;
- private int mArrayLength;
- private int mPosition;
-
- /**
- * Define a TLV constructor with the specified size of the Type (T) and
- * Length (L) fields.
- *
- * @param typeSize Number of bytes used for the Type (T) field. Values
- * of 0, 1, or 2 bytes are allowed. A specification of 0
- * bytes implies that the field being constructed has the LV
- * format rather than the TLV format.
- * @param lengthSize Number of bytes used for the Length (L) field.
- * Values of 1 or 2 bytes are allowed.
- */
- public TlvConstructor(int typeSize, int lengthSize) {
- if (typeSize < 0 || typeSize > 2 || lengthSize <= 0 || lengthSize > 2) {
- throw new IllegalArgumentException(
- "Invalid sizes - typeSize=" + typeSize + ", lengthSize=" + lengthSize);
- }
- mTypeSize = typeSize;
- mLengthSize = lengthSize;
- mPosition = 0;
- }
-
- /**
- * Configure the TLV constructor to use a particular byte order. Should be
- * {@link ByteOrder#BIG_ENDIAN} (the default at construction) or
- * {@link ByteOrder#LITTLE_ENDIAN}.
- *
- * @return The constructor to facilitate chaining
- * {@code ctr.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor setByteOrder(ByteOrder byteOrder) {
- mByteOrder = byteOrder;
- return this;
- }
-
- /**
- * Set the byte array to be used to construct the TLV.
- *
- * @param array Byte array to be formatted.
- * @return The constructor to facilitate chaining
- * {@code ctr.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor wrap(@Nullable byte[] array) {
- mArray = array;
- mArrayLength = (array == null) ? 0 : array.length;
- mPosition = 0;
- return this;
- }
-
- /**
- * Allocates a new byte array to be used ot construct a TLV.
- *
- * @param capacity The size of the byte array to be allocated.
- * @return The constructor to facilitate chaining
- * {@code ctr.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor allocate(int capacity) {
- mArray = new byte[capacity];
- mArrayLength = capacity;
- mPosition = 0;
- return this;
- }
-
- /**
- * Creates a TLV array (of the previously specified Type and Length sizes) from the input
- * list. Allocates an array matching the contents (and required Type and Length
- * fields), copies the contents, and set the Length fields. The Type field is set to 0.
- *
- * @param list A list of fields to be added to the TLV buffer.
- * @return The constructor of the TLV.
- */
- public TlvConstructor allocateAndPut(@Nullable List<byte[]> list) {
- if (list != null) {
- int size = 0;
- for (byte[] field : list) {
- size += mTypeSize + mLengthSize;
- if (field != null) {
- size += field.length;
- }
- }
- allocate(size);
- for (byte[] field : list) {
- putByteArray(0, field);
- }
- }
- return this;
- }
-
- /**
- * Copies a byte into the TLV with the indicated type. For an LV
- * formatted structure (i.e. typeLength=0 in {@link TlvConstructor
- * TlvConstructor(int, int)} ) the type field is ignored.
- *
- * @param type The value to be placed into the Type field.
- * @param b The byte to be inserted into the structure.
- * @return The constructor to facilitate chaining
- * {@code ctr.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor putByte(int type, byte b) {
- checkLength(1);
- addHeader(type, 1);
- mArray[mPosition++] = b;
- return this;
- }
-
- /**
- * Copies a raw byte into the TLV buffer - without a type or a length.
- *
- * @param b The byte to be inserted into the structure.
- * @return The constructor to facilitate chaining {@code cts.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor putRawByte(byte b) {
- checkRawLength(1);
- mArray[mPosition++] = b;
- return this;
- }
-
- /**
- * Copies a byte array into the TLV with the indicated type. For an LV
- * formatted structure (i.e. typeLength=0 in {@link TlvConstructor
- * TlvConstructor(int, int)} ) the type field is ignored.
- *
- * @param type The value to be placed into the Type field.
- * @param array The array to be copied into the TLV structure.
- * @param offset Start copying from the array at the specified offset.
- * @param length Copy the specified number (length) of bytes from the
- * array.
- * @return The constructor to facilitate chaining
- * {@code ctr.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor putByteArray(int type, @Nullable byte[] array, int offset,
- int length) {
- checkLength(length);
- addHeader(type, length);
- if (length != 0) {
- System.arraycopy(array, offset, mArray, mPosition, length);
- }
- mPosition += length;
- return this;
- }
-
- /**
- * Copies a byte array into the TLV with the indicated type. For an LV
- * formatted structure (i.e. typeLength=0 in {@link TlvConstructor
- * TlvConstructor(int, int)} ) the type field is ignored.
- *
- * @param type The value to be placed into the Type field.
- * @param array The array to be copied (in full) into the TLV structure.
- * @return The constructor to facilitate chaining
- * {@code ctr.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor putByteArray(int type, @Nullable byte[] array) {
- return putByteArray(type, array, 0, (array == null) ? 0 : array.length);
- }
-
- /**
- * Copies a byte array into the TLV - without a type or a length.
- *
- * @param array The array to be copied (in full) into the TLV structure.
- * @return The constructor to facilitate chaining
- * {@code ctr.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor putRawByteArray(@Nullable byte[] array) {
- if (array == null) return this;
-
- checkRawLength(array.length);
- System.arraycopy(array, 0, mArray, mPosition, array.length);
- mPosition += array.length;
- return this;
- }
-
- /**
- * Places a zero length element (i.e. Length field = 0) into the TLV.
- * For an LV formatted structure (i.e. typeLength=0 in
- * {@link TlvConstructor TlvConstructor(int, int)} ) the type field is
- * ignored.
- *
- * @param type The value to be placed into the Type field.
- * @return The constructor to facilitate chaining
- * {@code ctr.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor putZeroLengthElement(int type) {
- checkLength(0);
- addHeader(type, 0);
- return this;
- }
-
- /**
- * Copies short into the TLV with the indicated type. For an LV
- * formatted structure (i.e. typeLength=0 in {@link TlvConstructor
- * TlvConstructor(int, int)} ) the type field is ignored.
- *
- * @param type The value to be placed into the Type field.
- * @param data The short to be inserted into the structure.
- * @return The constructor to facilitate chaining
- * {@code ctr.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor putShort(int type, short data) {
- checkLength(2);
- addHeader(type, 2);
- pokeShort(mArray, mPosition, data, mByteOrder);
- mPosition += 2;
- return this;
- }
-
- /**
- * Copies integer into the TLV with the indicated type. For an LV
- * formatted structure (i.e. typeLength=0 in {@link TlvConstructor
- * TlvConstructor(int, int)} ) the type field is ignored.
- *
- * @param type The value to be placed into the Type field.
- * @param data The integer to be inserted into the structure.
- * @return The constructor to facilitate chaining
- * {@code ctr.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor putInt(int type, int data) {
- checkLength(4);
- addHeader(type, 4);
- pokeInt(mArray, mPosition, data, mByteOrder);
- mPosition += 4;
- return this;
- }
-
- /**
- * Copies a String's byte representation into the TLV with the indicated
- * type. For an LV formatted structure (i.e. typeLength=0 in
- * {@link TlvConstructor TlvConstructor(int, int)} ) the type field is
- * ignored.
- *
- * @param type The value to be placed into the Type field.
- * @param data The string whose bytes are to be inserted into the
- * structure.
- * @return The constructor to facilitate chaining
- * {@code ctr.putXXX(..).putXXX(..)}.
- */
- public TlvConstructor putString(int type, @Nullable String data) {
- byte[] bytes = null;
- int length = 0;
- if (data != null) {
- bytes = data.getBytes();
- length = bytes.length;
- }
- return putByteArray(type, bytes, 0, length);
- }
-
- /**
- * Returns the constructed TLV formatted byte-array. This array is a copy of the wrapped
- * or allocated array - truncated to just the significant bytes - i.e. those written into
- * the (T)LV.
- *
- * @return The byte array containing the TLV formatted structure.
- */
- public byte[] getArray() {
- return Arrays.copyOf(mArray, getActualLength());
- }
-
- /**
- * Returns the size of the TLV formatted portion of the wrapped or
- * allocated byte array. The array itself is returned with
- * {@link TlvConstructor#getArray()}.
- *
- * @return The size of the TLV formatted portion of the byte array.
- */
- private int getActualLength() {
- return mPosition;
- }
-
- private void checkLength(int dataLength) {
- if (mPosition + mTypeSize + mLengthSize + dataLength > mArrayLength) {
- throw new BufferOverflowException();
- }
- }
-
- private void checkRawLength(int dataLength) {
- if (mPosition + dataLength > mArrayLength) {
- throw new BufferOverflowException();
- }
- }
-
- private void addHeader(int type, int length) {
- if (mTypeSize == 1) {
- mArray[mPosition] = (byte) type;
- } else if (mTypeSize == 2) {
- pokeShort(mArray, mPosition, (short) type, mByteOrder);
- }
- mPosition += mTypeSize;
-
- if (mLengthSize == 1) {
- mArray[mPosition] = (byte) length;
- } else if (mLengthSize == 2) {
- pokeShort(mArray, mPosition, (short) length, mByteOrder);
- }
- mPosition += mLengthSize;
- }
- }
-
- /**
- * Utility class used when iterating over a TLV formatted byte-array. Use
- * {@link TlvIterable} to iterate over array. A {@link TlvElement}
- * represents each entry in a TLV formatted byte-array.
- */
- public static class TlvElement {
- /**
- * The Type (T) field of the current TLV element. Note that for LV
- * formatted byte-arrays (i.e. TLV whose Type/T size is 0) the value of
- * this field is undefined.
- */
- public int type;
-
- /**
- * The Length (L) field of the current TLV element.
- */
- public int length;
-
- /**
- * Control of the endianess of the TLV element - true for big-endian, false for little-
- * endian.
- */
- public ByteOrder byteOrder = ByteOrder.BIG_ENDIAN;
-
- /**
- * The Value (V) field - a raw byte array representing the current TLV
- * element where the entry starts at {@link TlvElement#offset}.
- */
- private byte[] mRefArray;
-
- /**
- * The offset to be used into {@link TlvElement#mRefArray} to access the
- * raw data representing the current TLV element.
- */
- public int offset;
-
- private TlvElement(int type, int length, @Nullable byte[] refArray, int offset) {
- this.type = type;
- this.length = length;
- mRefArray = refArray;
- this.offset = offset;
-
- if (offset + length > refArray.length) {
- throw new BufferOverflowException();
- }
- }
-
- /**
- * Return the raw byte array of the Value (V) field.
- *
- * @return The Value (V) field as a byte array.
- */
- public byte[] getRawData() {
- return Arrays.copyOfRange(mRefArray, offset, offset + length);
- }
-
- /**
- * Utility function to return a byte representation of a TLV element of
- * length 1. Note: an attempt to call this function on a TLV item whose
- * {@link TlvElement#length} is != 1 will result in an exception.
- *
- * @return byte representation of current TLV element.
- */
- public byte getByte() {
- if (length != 1) {
- throw new IllegalArgumentException(
- "Accesing a byte from a TLV element of length " + length);
- }
- return mRefArray[offset];
- }
-
- /**
- * Utility function to return a short representation of a TLV element of
- * length 2. Note: an attempt to call this function on a TLV item whose
- * {@link TlvElement#length} is != 2 will result in an exception.
- *
- * @return short representation of current TLV element.
- */
- public short getShort() {
- if (length != 2) {
- throw new IllegalArgumentException(
- "Accesing a short from a TLV element of length " + length);
- }
- return peekShort(mRefArray, offset, byteOrder);
- }
-
- /**
- * Utility function to return an integer representation of a TLV element
- * of length 4. Note: an attempt to call this function on a TLV item
- * whose {@link TlvElement#length} is != 4 will result in an exception.
- *
- * @return integer representation of current TLV element.
- */
- public int getInt() {
- if (length != 4) {
- throw new IllegalArgumentException(
- "Accesing an int from a TLV element of length " + length);
- }
- return peekInt(mRefArray, offset, byteOrder);
- }
-
- /**
- * Utility function to return a String representation of a TLV element.
- *
- * @return String repersentation of the current TLV element.
- */
- public String getString() {
- return new String(mRefArray, offset, length);
- }
- }
-
- /**
- * Utility class to iterate over a TLV formatted byte-array.
- */
- public static class TlvIterable implements Iterable<TlvElement> {
- private int mTypeSize;
- private int mLengthSize;
- private ByteOrder mByteOrder = ByteOrder.BIG_ENDIAN;
- private byte[] mArray;
- private int mArrayLength;
-
- /**
- * Constructs a TlvIterable object - specifying the format of the TLV
- * (the sizes of the Type and Length fields), and the byte array whose
- * data is to be parsed.
- *
- * @param typeSize Number of bytes used for the Type (T) field. Valid
- * values are 0 (i.e. indicating the format is LV rather than
- * TLV), 1, and 2 bytes.
- * @param lengthSize Number of bytes used for the Length (L) field.
- * Values values are 1 or 2 bytes.
- * @param array The TLV formatted byte-array to parse.
- */
- public TlvIterable(int typeSize, int lengthSize, @Nullable byte[] array) {
- if (typeSize < 0 || typeSize > 2 || lengthSize <= 0 || lengthSize > 2) {
- throw new IllegalArgumentException(
- "Invalid sizes - typeSize=" + typeSize + ", lengthSize=" + lengthSize);
- }
- mTypeSize = typeSize;
- mLengthSize = lengthSize;
- mArray = array;
- mArrayLength = (array == null) ? 0 : array.length;
- }
-
- /**
- * Configure the TLV iterator to use little-endian byte ordering.
- */
- public void setByteOrder(ByteOrder byteOrder) {
- mByteOrder = byteOrder;
- }
-
- /**
- * Prints out a parsed representation of the TLV-formatted byte array.
- * Whenever possible bytes, shorts, and integer are printed out (for
- * fields whose length is 1, 2, or 4 respectively).
- */
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
-
- builder.append("[");
- boolean first = true;
- for (TlvElement tlv : this) {
- if (!first) {
- builder.append(",");
- }
- first = false;
- builder.append(" (");
- if (mTypeSize != 0) {
- builder.append("T=" + tlv.type + ",");
- }
- builder.append("L=" + tlv.length + ") ");
- if (tlv.length == 0) {
- builder.append("<null>");
- } else if (tlv.length == 1) {
- builder.append(tlv.getByte());
- } else if (tlv.length == 2) {
- builder.append(tlv.getShort());
- } else if (tlv.length == 4) {
- builder.append(tlv.getInt());
- } else {
- builder.append("<bytes>");
- }
- if (tlv.length != 0) {
- builder.append(" (S='" + tlv.getString() + "')");
- }
- }
- builder.append("]");
-
- return builder.toString();
- }
-
- /**
- * Returns a List with the raw contents (no types) of the iterator.
- */
- public List<byte[]> toList() {
- List<byte[]> list = new ArrayList<>();
- for (TlvElement tlv : this) {
- list.add(Arrays.copyOfRange(tlv.mRefArray, tlv.offset, tlv.offset + tlv.length));
- }
-
- return list;
- }
-
- /**
- * Returns an iterator to step through a TLV formatted byte-array. The
- * individual elements returned by the iterator are {@link TlvElement}.
- */
- @Override
- public Iterator<TlvElement> iterator() {
- return new Iterator<TlvElement>() {
- private int mOffset = 0;
-
- @Override
- public boolean hasNext() {
- return mOffset < mArrayLength;
- }
-
- @Override
- public TlvElement next() {
- if (!hasNext()) {
- throw new NoSuchElementException();
- }
-
- int type = 0;
- if (mTypeSize == 1) {
- type = mArray[mOffset];
- } else if (mTypeSize == 2) {
- type = peekShort(mArray, mOffset, mByteOrder);
- }
- mOffset += mTypeSize;
-
- int length = 0;
- if (mLengthSize == 1) {
- length = mArray[mOffset];
- } else if (mLengthSize == 2) {
- length = peekShort(mArray, mOffset, mByteOrder);
- }
- mOffset += mLengthSize;
-
- TlvElement tlv = new TlvElement(type, length, mArray, mOffset);
- tlv.byteOrder = mByteOrder;
- mOffset += length;
- return tlv;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
- };
- }
- }
-
- /**
- * Validates that a (T)LV array is constructed correctly. I.e. that its specified Length
- * fields correctly fill the specified length (and do not overshoot). Uses big-endian
- * byte ordering.
- *
- * @param array The (T)LV array to verify.
- * @param typeSize The size (in bytes) of the type field. Valid values are 0, 1, or 2.
- * @param lengthSize The size (in bytes) of the length field. Valid values are 1 or 2.
- * @return A boolean indicating whether the array is valid (true) or invalid (false).
- */
- public static boolean isValid(@Nullable byte[] array, int typeSize, int lengthSize) {
- return isValidEndian(array, typeSize, lengthSize, ByteOrder.BIG_ENDIAN);
- }
-
- /**
- * Validates that a (T)LV array is constructed correctly. I.e. that its specified Length
- * fields correctly fill the specified length (and do not overshoot).
- *
- * @param array The (T)LV array to verify.
- * @param typeSize The size (in bytes) of the type field. Valid values are 0, 1, or 2.
- * @param lengthSize The size (in bytes) of the length field. Valid values are 1 or 2.
- * @param byteOrder The endianness of the byte array: {@link ByteOrder#BIG_ENDIAN} or
- * {@link ByteOrder#LITTLE_ENDIAN}.
- * @return A boolean indicating whether the array is valid (true) or invalid (false).
- */
- public static boolean isValidEndian(@Nullable byte[] array, int typeSize, int lengthSize,
- ByteOrder byteOrder) {
- if (typeSize < 0 || typeSize > 2) {
- throw new IllegalArgumentException(
- "Invalid arguments - typeSize must be 0, 1, or 2: typeSize=" + typeSize);
- }
- if (lengthSize <= 0 || lengthSize > 2) {
- throw new IllegalArgumentException(
- "Invalid arguments - lengthSize must be 1 or 2: lengthSize=" + lengthSize);
- }
- if (array == null) {
- return true;
- }
-
- int nextTlvIndex = 0;
- while (nextTlvIndex + typeSize + lengthSize <= array.length) {
- nextTlvIndex += typeSize;
- if (lengthSize == 1) {
- nextTlvIndex += lengthSize + array[nextTlvIndex];
- } else {
- nextTlvIndex += lengthSize + peekShort(array, nextTlvIndex, byteOrder);
- }
- }
-
- return nextTlvIndex == array.length;
- }
-
- private static void pokeShort(byte[] dst, int offset, short value, ByteOrder order) {
- if (order == ByteOrder.BIG_ENDIAN) {
- dst[offset++] = (byte) ((value >> 8) & 0xff);
- dst[offset ] = (byte) ((value >> 0) & 0xff);
- } else {
- dst[offset++] = (byte) ((value >> 0) & 0xff);
- dst[offset ] = (byte) ((value >> 8) & 0xff);
- }
- }
-
- private static void pokeInt(byte[] dst, int offset, int value, ByteOrder order) {
- if (order == ByteOrder.BIG_ENDIAN) {
- dst[offset++] = (byte) ((value >> 24) & 0xff);
- dst[offset++] = (byte) ((value >> 16) & 0xff);
- dst[offset++] = (byte) ((value >> 8) & 0xff);
- dst[offset ] = (byte) ((value >> 0) & 0xff);
- } else {
- dst[offset++] = (byte) ((value >> 0) & 0xff);
- dst[offset++] = (byte) ((value >> 8) & 0xff);
- dst[offset++] = (byte) ((value >> 16) & 0xff);
- dst[offset ] = (byte) ((value >> 24) & 0xff);
- }
- }
-
- private static short peekShort(byte[] src, int offset, ByteOrder order) {
- if (order == ByteOrder.BIG_ENDIAN) {
- return (short) ((src[offset] << 8) | (src[offset + 1] & 0xff));
- } else {
- return (short) ((src[offset + 1] << 8) | (src[offset] & 0xff));
- }
- }
-
- private static int peekInt(byte[] src, int offset, ByteOrder order) {
- if (order == ByteOrder.BIG_ENDIAN) {
- return ((src[offset++] & 0xff) << 24)
- | ((src[offset++] & 0xff) << 16)
- | ((src[offset++] & 0xff) << 8)
- | ((src[offset ] & 0xff) << 0);
- } else {
- return ((src[offset++] & 0xff) << 0)
- | ((src[offset++] & 0xff) << 8)
- | ((src[offset++] & 0xff) << 16)
- | ((src[offset ] & 0xff) << 24);
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareAgentNetworkSpecifier.java b/wifi/java/android/net/wifi/aware/WifiAwareAgentNetworkSpecifier.java
deleted file mode 100644
index 9ae3bd0c93c0..000000000000
--- a/wifi/java/android/net/wifi/aware/WifiAwareAgentNetworkSpecifier.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright (C) 2017 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.aware;
-
-import android.net.NetworkSpecifier;
-import android.net.wifi.util.HexEncoding;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
-
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.StringJoiner;
-
-/**
- * A network specifier object used to represent the capabilities of an network agent. A collection
- * of multiple WifiAwareNetworkSpecifier objects whose matching critiera (satisfiedBy) is an OR:
- * a match on any of the network specifiers in the collection is a match.
- *
- * This class is not intended for use in network requests.
- *
- * @hide
- */
-public class WifiAwareAgentNetworkSpecifier extends NetworkSpecifier implements Parcelable {
- private static final String TAG = "WifiAwareAgentNs";
-
- private static final boolean VDBG = false; // STOPSHIP if true
-
- private Set<ByteArrayWrapper> mNetworkSpecifiers = new HashSet<>();
- private MessageDigest mDigester;
-
- public WifiAwareAgentNetworkSpecifier() {
- initialize();
- }
-
- public WifiAwareAgentNetworkSpecifier(WifiAwareNetworkSpecifier ns) {
- initialize();
- mNetworkSpecifiers.add(convert(ns));
- }
-
- public WifiAwareAgentNetworkSpecifier(WifiAwareNetworkSpecifier[] nss) {
- initialize();
- for (WifiAwareNetworkSpecifier ns : nss) {
- mNetworkSpecifiers.add(convert(ns));
- }
- }
-
- public boolean isEmpty() {
- return mNetworkSpecifiers.isEmpty();
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeArray(mNetworkSpecifiers.toArray());
- }
-
- public static final @android.annotation.NonNull Creator<WifiAwareAgentNetworkSpecifier> CREATOR =
- new Creator<WifiAwareAgentNetworkSpecifier>() {
- @Override
- public WifiAwareAgentNetworkSpecifier createFromParcel(Parcel in) {
- WifiAwareAgentNetworkSpecifier agentNs = new WifiAwareAgentNetworkSpecifier();
- Object[] objs = in.readArray(null);
- for (Object obj : objs) {
- agentNs.mNetworkSpecifiers.add((ByteArrayWrapper) obj);
- }
- return agentNs;
- }
-
- @Override
- public WifiAwareAgentNetworkSpecifier[] newArray(int size) {
- return new WifiAwareAgentNetworkSpecifier[size];
- }
- };
-
- @Override
- public int hashCode() {
- return mNetworkSpecifiers.hashCode();
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!(obj instanceof WifiAwareAgentNetworkSpecifier)) {
- return false;
- }
- return mNetworkSpecifiers.equals(((WifiAwareAgentNetworkSpecifier) obj).mNetworkSpecifiers);
- }
-
- @Override
- public String toString() {
- StringJoiner sj = new StringJoiner(",");
- for (ByteArrayWrapper baw: mNetworkSpecifiers) {
- sj.add(baw.toString());
- }
- return sj.toString();
- }
-
- @Override
- public boolean canBeSatisfiedBy(NetworkSpecifier other) {
- if (!(other instanceof WifiAwareAgentNetworkSpecifier)) {
- return false;
- }
- WifiAwareAgentNetworkSpecifier otherNs = (WifiAwareAgentNetworkSpecifier) other;
-
- // called as old.satifiedBy(new): satisfied if old contained in new
- for (ByteArrayWrapper baw: mNetworkSpecifiers) {
- if (!otherNs.mNetworkSpecifiers.contains(baw)) {
- return false;
- }
- }
-
- return true;
- }
-
- public boolean satisfiesAwareNetworkSpecifier(WifiAwareNetworkSpecifier ns) {
- if (VDBG) Log.v(TAG, "satisfiesAwareNetworkSpecifier: ns=" + ns);
- ByteArrayWrapper nsBytes = convert(ns);
- return mNetworkSpecifiers.contains(nsBytes);
- }
-
- @Override
- public NetworkSpecifier redact() {
- return null;
- }
-
- private void initialize() {
- try {
- mDigester = MessageDigest.getInstance("SHA-256");
- } catch (NoSuchAlgorithmException e) {
- Log.e(TAG, "Can not instantiate a SHA-256 digester!? Will match nothing.");
- return;
- }
- }
-
- private ByteArrayWrapper convert(WifiAwareNetworkSpecifier ns) {
- if (mDigester == null) {
- return null;
- }
-
- Parcel parcel = Parcel.obtain();
- ns.writeToParcel(parcel, 0);
- byte[] bytes = parcel.marshall();
-
- mDigester.reset();
- mDigester.update(bytes);
- return new ByteArrayWrapper(mDigester.digest());
- }
-
- private static class ByteArrayWrapper implements Parcelable {
- private byte[] mData;
-
- ByteArrayWrapper(byte[] data) {
- mData = data;
- }
-
- @Override
- public int hashCode() {
- return Arrays.hashCode(mData);
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
- if (!(obj instanceof ByteArrayWrapper)) {
- return false;
- }
- return Arrays.equals(((ByteArrayWrapper) obj).mData, mData);
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeByteArray(mData);
- }
-
- public static final @android.annotation.NonNull Creator<ByteArrayWrapper> CREATOR =
- new Creator<ByteArrayWrapper>() {
- @Override
- public ByteArrayWrapper createFromParcel(Parcel in) {
- return new ByteArrayWrapper(in.createByteArray());
- }
-
- @Override
- public ByteArrayWrapper[] newArray(int size) {
- return new ByteArrayWrapper[size];
- }
- };
-
- @Override
- public String toString() {
- return new String(HexEncoding.encode(mData));
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareManager.java b/wifi/java/android/net/wifi/aware/WifiAwareManager.java
deleted file mode 100644
index 540bf2a72b34..000000000000
--- a/wifi/java/android/net/wifi/aware/WifiAwareManager.java
+++ /dev/null
@@ -1,938 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
-import android.annotation.SdkConstant;
-import android.annotation.SdkConstant.SdkConstantType;
-import android.annotation.SystemApi;
-import android.annotation.SystemService;
-import android.content.Context;
-import android.net.ConnectivityManager;
-import android.net.NetworkRequest;
-import android.net.NetworkSpecifier;
-import android.net.wifi.util.HexEncoding;
-import android.os.Binder;
-import android.os.Build;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.os.RemoteException;
-import android.util.Log;
-
-import com.android.modules.utils.build.SdkLevel;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.ref.WeakReference;
-import java.nio.BufferOverflowException;
-import java.util.List;
-
-/**
- * This class provides the primary API for managing Wi-Fi Aware operations:
- * discovery and peer-to-peer data connections.
- * <p>
- * The class provides access to:
- * <ul>
- * <li>Initialize a Aware cluster (peer-to-peer synchronization). Refer to
- * {@link #attach(AttachCallback, Handler)}.
- * <li>Create discovery sessions (publish or subscribe sessions). Refer to
- * {@link WifiAwareSession#publish(PublishConfig, DiscoverySessionCallback, Handler)} and
- * {@link WifiAwareSession#subscribe(SubscribeConfig, DiscoverySessionCallback, Handler)}.
- * <li>Create a Aware network specifier to be used with
- * {@link ConnectivityManager#requestNetwork(NetworkRequest, ConnectivityManager.NetworkCallback)}
- * to set-up a Aware connection with a peer. Refer to {@link WifiAwareNetworkSpecifier.Builder}.
- * </ul>
- * <p>
- * Aware may not be usable when Wi-Fi is disabled (and other conditions). To validate that
- * the functionality is available use the {@link #isAvailable()} function. To track
- * changes in Aware usability register for the {@link #ACTION_WIFI_AWARE_STATE_CHANGED}
- * broadcast. Note that this broadcast is not sticky - you should register for it and then
- * check the above API to avoid a race condition.
- * <p>
- * An application must use {@link #attach(AttachCallback, Handler)} to initialize a
- * Aware cluster - before making any other Aware operation. Aware cluster membership is a
- * device-wide operation - the API guarantees that the device is in a cluster or joins a
- * Aware cluster (or starts one if none can be found). Information about attach success (or
- * failure) are returned in callbacks of {@link AttachCallback}. Proceed with Aware
- * discovery or connection setup only after receiving confirmation that Aware attach
- * succeeded - {@link AttachCallback#onAttached(WifiAwareSession)}. When an
- * application is finished using Aware it <b>must</b> use the
- * {@link WifiAwareSession#close()} API to indicate to the Aware service that the device
- * may detach from the Aware cluster. The device will actually disable Aware once the last
- * application detaches.
- * <p>
- * Once a Aware attach is confirmed use the
- * {@link WifiAwareSession#publish(PublishConfig, DiscoverySessionCallback, Handler)}
- * or
- * {@link WifiAwareSession#subscribe(SubscribeConfig, DiscoverySessionCallback,
- * Handler)} to create publish or subscribe Aware discovery sessions. Events are called on the
- * provided callback object {@link DiscoverySessionCallback}. Specifically, the
- * {@link DiscoverySessionCallback#onPublishStarted(PublishDiscoverySession)}
- * and
- * {@link DiscoverySessionCallback#onSubscribeStarted(
- *SubscribeDiscoverySession)}
- * return {@link PublishDiscoverySession} and
- * {@link SubscribeDiscoverySession}
- * objects respectively on which additional session operations can be performed, e.g. updating
- * the session {@link PublishDiscoverySession#updatePublish(PublishConfig)} and
- * {@link SubscribeDiscoverySession#updateSubscribe(SubscribeConfig)}. Sessions can
- * also be used to send messages using the
- * {@link DiscoverySession#sendMessage(PeerHandle, int, byte[])} APIs. When an
- * application is finished with a discovery session it <b>must</b> terminate it using the
- * {@link DiscoverySession#close()} API.
- * <p>
- * Creating connections between Aware devices is managed by the standard
- * {@link ConnectivityManager#requestNetwork(NetworkRequest,
- * ConnectivityManager.NetworkCallback)}.
- * The {@link NetworkRequest} object should be constructed with:
- * <ul>
- * <li>{@link NetworkRequest.Builder#addTransportType(int)} of
- * {@link android.net.NetworkCapabilities#TRANSPORT_WIFI_AWARE}.
- * <li>{@link NetworkRequest.Builder#setNetworkSpecifier(String)} using
- * {@link WifiAwareNetworkSpecifier.Builder}.
- * </ul>
- */
-@SystemService(Context.WIFI_AWARE_SERVICE)
-public class WifiAwareManager {
- private static final String TAG = "WifiAwareManager";
- private static final boolean DBG = false;
- private static final boolean VDBG = false; // STOPSHIP if true
-
- /**
- * Broadcast intent action to indicate that the state of Wi-Fi Aware availability has changed.
- * Use the {@link #isAvailable()} to query the current status.
- * This broadcast is <b>not</b> sticky, use the {@link #isAvailable()} API after registering
- * the broadcast to check the current state of Wi-Fi Aware.
- * <p>Note: The broadcast is only delivered to registered receivers - no manifest registered
- * components will be launched.
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String ACTION_WIFI_AWARE_STATE_CHANGED =
- "android.net.wifi.aware.action.WIFI_AWARE_STATE_CHANGED";
-
- /** @hide */
- @IntDef({
- WIFI_AWARE_DATA_PATH_ROLE_INITIATOR, WIFI_AWARE_DATA_PATH_ROLE_RESPONDER})
- @Retention(RetentionPolicy.SOURCE)
- public @interface DataPathRole {
- }
-
- /**
- * Connection creation role is that of INITIATOR. Used to create a network specifier string
- * when requesting a Aware network.
- *
- * @see WifiAwareSession#createNetworkSpecifierOpen(int, byte[])
- * @see WifiAwareSession#createNetworkSpecifierPassphrase(int, byte[], String)
- */
- public static final int WIFI_AWARE_DATA_PATH_ROLE_INITIATOR = 0;
-
- /**
- * Connection creation role is that of RESPONDER. Used to create a network specifier string
- * when requesting a Aware network.
- *
- * @see WifiAwareSession#createNetworkSpecifierOpen(int, byte[])
- * @see WifiAwareSession#createNetworkSpecifierPassphrase(int, byte[], String)
- */
- public static final int WIFI_AWARE_DATA_PATH_ROLE_RESPONDER = 1;
-
- /** @hide */
- @IntDef({
- WIFI_AWARE_DISCOVERY_LOST_REASON_UNKNOWN,
- WIFI_AWARE_DISCOVERY_LOST_REASON_PEER_NOT_VISIBLE})
- @Retention(RetentionPolicy.SOURCE)
- public @interface DiscoveryLostReasonCode {
- }
-
- /**
- * Reason code provided in {@link DiscoverySessionCallback#onServiceLost(PeerHandle, int)}
- * indicating that the service was lost for unknown reason.
- */
- public static final int WIFI_AWARE_DISCOVERY_LOST_REASON_UNKNOWN = 0;
-
- /**
- * Reason code provided in {@link DiscoverySessionCallback#onServiceLost(PeerHandle, int)}
- * indicating that the service advertised by the peer is no longer visible. This may be because
- * the peer is out of range or because the peer stopped advertising this service.
- */
- public static final int WIFI_AWARE_DISCOVERY_LOST_REASON_PEER_NOT_VISIBLE = 1;
-
- private final Context mContext;
- private final IWifiAwareManager mService;
-
- private final Object mLock = new Object(); // lock access to the following vars
-
- /** @hide */
- public WifiAwareManager(@NonNull Context context, @NonNull IWifiAwareManager service) {
- mContext = context;
- mService = service;
- }
-
- /**
- * Returns the current status of Aware API: whether or not Aware is available. To track
- * changes in the state of Aware API register for the
- * {@link #ACTION_WIFI_AWARE_STATE_CHANGED} broadcast.
- *
- * @return A boolean indicating whether the app can use the Aware API at this time (true) or
- * not (false).
- */
- public boolean isAvailable() {
- try {
- return mService.isUsageEnabled();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return the current status of the Aware service: whether ot not the device is already attached
- * to an Aware cluster. To attach to an Aware cluster, please use
- * {@link #attach(AttachCallback, Handler)} or
- * {@link #attach(AttachCallback, IdentityChangedListener, Handler)}.
- * @return A boolean indicating whether the device is attached to a cluster at this time (true)
- * or not (false).
- */
- public boolean isDeviceAttached() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- try {
- return mService.isDeviceAttached();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Enable the Wifi Aware Instant communication mode. If the device doesn't support this feature
- * calling this API will result no action.
- * @see Characteristics#isInstantCommunicationModeSupported()
- * @param enable true for enable, false otherwise.
- * @hide
- */
- @SystemApi
- public void enableInstantCommunicationMode(boolean enable) {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- try {
- mService.enableInstantCommunicationMode(mContext.getOpPackageName(), enable);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return the current status of the Wifi Aware instant communication mode.
- * If the device doesn't support this feature, return will always be false.
- * @see Characteristics#isInstantCommunicationModeSupported()
- * @return true if it is enabled, false otherwise.
- */
- public boolean isInstantCommunicationModeEnabled() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- try {
- return mService.isInstantCommunicationModeEnabled();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns the characteristics of the Wi-Fi Aware interface: a set of parameters which specify
- * limitations on configurations, e.g. the maximum service name length.
- *
- * @return An object specifying configuration limitations of Aware.
- */
- public @Nullable Characteristics getCharacteristics() {
- try {
- return mService.getCharacteristics();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return the available resources of the Wi-Fi aware service: a set of parameters which specify
- * limitations on service usage, e.g the number of data-paths which could be created..
- *
- * @return An object specifying the currently available resource of the Wi-Fi Aware service.
- */
- public @Nullable AwareResources getAvailableAwareResources() {
- if (!SdkLevel.isAtLeastS()) {
- throw new UnsupportedOperationException();
- }
- try {
- return mService.getAvailableAwareResources();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Attach to the Wi-Fi Aware service - enabling the application to create discovery sessions or
- * create connections to peers. The device will attach to an existing cluster if it can find
- * one or create a new cluster (if it is the first to enable Aware in its vicinity). Results
- * (e.g. successful attach to a cluster) are provided to the {@code attachCallback} object.
- * An application <b>must</b> call {@link WifiAwareSession#close()} when done with the
- * Wi-Fi Aware object.
- * <p>
- * Note: a Aware cluster is a shared resource - if the device is already attached to a cluster
- * then this function will simply indicate success immediately using the same {@code
- * attachCallback}.
- *
- * @param attachCallback A callback for attach events, extended from
- * {@link AttachCallback}.
- * @param handler The Handler on whose thread to execute the callbacks of the {@code
- * attachCallback} object. If a null is provided then the application's main thread will be
- * used.
- */
- public void attach(@NonNull AttachCallback attachCallback, @Nullable Handler handler) {
- attach(handler, null, attachCallback, null);
- }
-
- /**
- * Attach to the Wi-Fi Aware service - enabling the application to create discovery sessions or
- * create connections to peers. The device will attach to an existing cluster if it can find
- * one or create a new cluster (if it is the first to enable Aware in its vicinity). Results
- * (e.g. successful attach to a cluster) are provided to the {@code attachCallback} object.
- * An application <b>must</b> call {@link WifiAwareSession#close()} when done with the
- * Wi-Fi Aware object.
- * <p>
- * Note: a Aware cluster is a shared resource - if the device is already attached to a cluster
- * then this function will simply indicate success immediately using the same {@code
- * attachCallback}.
- * <p>
- * This version of the API attaches a listener to receive the MAC address of the Aware interface
- * on startup and whenever it is updated (it is randomized at regular intervals for privacy).
- * The application must have the {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
- * permission to execute this attach request. Otherwise, use the
- * {@link #attach(AttachCallback, Handler)} version. Note that aside from permission
- * requirements this listener will wake up the host at regular intervals causing higher power
- * consumption, do not use it unless the information is necessary (e.g. for OOB discovery).
- *
- * @param attachCallback A callback for attach events, extended from
- * {@link AttachCallback}.
- * @param identityChangedListener A listener for changed identity, extended from
- * {@link IdentityChangedListener}.
- * @param handler The Handler on whose thread to execute the callbacks of the {@code
- * attachCallback} and {@code identityChangedListener} objects. If a null is provided then the
- * application's main thread will be used.
- */
- public void attach(@NonNull AttachCallback attachCallback,
- @NonNull IdentityChangedListener identityChangedListener,
- @Nullable Handler handler) {
- attach(handler, null, attachCallback, identityChangedListener);
- }
-
- /** @hide */
- public void attach(Handler handler, ConfigRequest configRequest,
- AttachCallback attachCallback,
- IdentityChangedListener identityChangedListener) {
- if (VDBG) {
- Log.v(TAG, "attach(): handler=" + handler + ", callback=" + attachCallback
- + ", configRequest=" + configRequest + ", identityChangedListener="
- + identityChangedListener);
- }
-
- if (attachCallback == null) {
- throw new IllegalArgumentException("Null callback provided");
- }
-
- synchronized (mLock) {
- Looper looper = (handler == null) ? Looper.getMainLooper() : handler.getLooper();
-
- try {
- Binder binder = new Binder();
- mService.connect(binder, mContext.getOpPackageName(), mContext.getAttributionTag(),
- new WifiAwareEventCallbackProxy(this, looper, binder, attachCallback,
- identityChangedListener), configRequest,
- identityChangedListener != null);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
- }
-
- /** @hide */
- public void disconnect(int clientId, Binder binder) {
- if (VDBG) Log.v(TAG, "disconnect()");
-
- try {
- mService.disconnect(clientId, binder);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- public void publish(int clientId, Looper looper, PublishConfig publishConfig,
- DiscoverySessionCallback callback) {
- if (VDBG) Log.v(TAG, "publish(): clientId=" + clientId + ", config=" + publishConfig);
-
- if (callback == null) {
- throw new IllegalArgumentException("Null callback provided");
- }
-
- try {
- mService.publish(mContext.getOpPackageName(), mContext.getAttributionTag(), clientId,
- publishConfig,
- new WifiAwareDiscoverySessionCallbackProxy(this, looper, true, callback,
- clientId));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- public void updatePublish(int clientId, int sessionId, PublishConfig publishConfig) {
- if (VDBG) {
- Log.v(TAG, "updatePublish(): clientId=" + clientId + ",sessionId=" + sessionId
- + ", config=" + publishConfig);
- }
-
- try {
- mService.updatePublish(clientId, sessionId, publishConfig);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- public void subscribe(int clientId, Looper looper, SubscribeConfig subscribeConfig,
- DiscoverySessionCallback callback) {
- if (VDBG) {
- if (VDBG) {
- Log.v(TAG,
- "subscribe(): clientId=" + clientId + ", config=" + subscribeConfig);
- }
- }
-
- if (callback == null) {
- throw new IllegalArgumentException("Null callback provided");
- }
-
- try {
- mService.subscribe(mContext.getOpPackageName(), mContext.getAttributionTag(), clientId,
- subscribeConfig,
- new WifiAwareDiscoverySessionCallbackProxy(this, looper, false, callback,
- clientId));
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- public void updateSubscribe(int clientId, int sessionId, SubscribeConfig subscribeConfig) {
- if (VDBG) {
- Log.v(TAG, "updateSubscribe(): clientId=" + clientId + ",sessionId=" + sessionId
- + ", config=" + subscribeConfig);
- }
-
- try {
- mService.updateSubscribe(clientId, sessionId, subscribeConfig);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- public void terminateSession(int clientId, int sessionId) {
- if (VDBG) {
- Log.d(TAG,
- "terminateSession(): clientId=" + clientId + ", sessionId=" + sessionId);
- }
-
- try {
- mService.terminateSession(clientId, sessionId);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- public void sendMessage(int clientId, int sessionId, PeerHandle peerHandle, byte[] message,
- int messageId, int retryCount) {
- if (peerHandle == null) {
- throw new IllegalArgumentException(
- "sendMessage: invalid peerHandle - must be non-null");
- }
-
- if (VDBG) {
- Log.v(TAG, "sendMessage(): clientId=" + clientId + ", sessionId=" + sessionId
- + ", peerHandle=" + peerHandle.peerId + ", messageId="
- + messageId + ", retryCount=" + retryCount);
- }
-
- try {
- mService.sendMessage(clientId, sessionId, peerHandle.peerId, message, messageId,
- retryCount);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
- public void requestMacAddresses(int uid, List<Integer> peerIds,
- IWifiAwareMacAddressProvider callback) {
- try {
- mService.requestMacAddresses(uid, peerIds, callback);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** @hide */
- public NetworkSpecifier createNetworkSpecifier(int clientId, int role, int sessionId,
- @NonNull PeerHandle peerHandle, @Nullable byte[] pmk, @Nullable String passphrase) {
- if (VDBG) {
- Log.v(TAG, "createNetworkSpecifier: role=" + role + ", sessionId=" + sessionId
- + ", peerHandle=" + ((peerHandle == null) ? peerHandle : peerHandle.peerId)
- + ", pmk=" + ((pmk == null) ? "null" : "non-null")
- + ", passphrase=" + ((passphrase == null) ? "null" : "non-null"));
- }
-
- if (!WifiAwareUtils.isLegacyVersion(mContext, Build.VERSION_CODES.Q)) {
- throw new UnsupportedOperationException(
- "API deprecated - use WifiAwareNetworkSpecifier.Builder");
- }
-
- if (role != WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
- && role != WIFI_AWARE_DATA_PATH_ROLE_RESPONDER) {
- throw new IllegalArgumentException(
- "createNetworkSpecifier: Invalid 'role' argument when creating a network "
- + "specifier");
- }
- if (role == WIFI_AWARE_DATA_PATH_ROLE_INITIATOR || !WifiAwareUtils.isLegacyVersion(mContext,
- Build.VERSION_CODES.P)) {
- if (peerHandle == null) {
- throw new IllegalArgumentException(
- "createNetworkSpecifier: Invalid peer handle - cannot be null");
- }
- }
-
- return new WifiAwareNetworkSpecifier(
- (peerHandle == null) ? WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_IB_ANY_PEER
- : WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_IB,
- role,
- clientId,
- sessionId,
- peerHandle != null ? peerHandle.peerId : 0, // 0 is an invalid peer ID
- null, // peerMac (not used in this method)
- pmk,
- passphrase,
- 0, // no port info for deprecated IB APIs
- -1); // no transport info for deprecated IB APIs
- }
-
- /** @hide */
- public NetworkSpecifier createNetworkSpecifier(int clientId, @DataPathRole int role,
- @NonNull byte[] peer, @Nullable byte[] pmk, @Nullable String passphrase) {
- if (VDBG) {
- Log.v(TAG, "createNetworkSpecifier: role=" + role
- + ", pmk=" + ((pmk == null) ? "null" : "non-null")
- + ", passphrase=" + ((passphrase == null) ? "null" : "non-null"));
- }
-
- if (role != WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
- && role != WIFI_AWARE_DATA_PATH_ROLE_RESPONDER) {
- throw new IllegalArgumentException(
- "createNetworkSpecifier: Invalid 'role' argument when creating a network "
- + "specifier");
- }
- if (role == WIFI_AWARE_DATA_PATH_ROLE_INITIATOR || !WifiAwareUtils.isLegacyVersion(mContext,
- Build.VERSION_CODES.P)) {
- if (peer == null) {
- throw new IllegalArgumentException(
- "createNetworkSpecifier: Invalid peer MAC - cannot be null");
- }
- }
- if (peer != null && peer.length != 6) {
- throw new IllegalArgumentException("createNetworkSpecifier: Invalid peer MAC address");
- }
-
- return new WifiAwareNetworkSpecifier(
- (peer == null) ? WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_OOB_ANY_PEER
- : WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_OOB,
- role,
- clientId,
- 0, // 0 is an invalid session ID
- 0, // 0 is an invalid peer ID
- peer,
- pmk,
- passphrase,
- 0, // no port info for OOB APIs
- -1); // no transport protocol info for OOB APIs
- }
-
- private static class WifiAwareEventCallbackProxy extends IWifiAwareEventCallback.Stub {
- private static final int CALLBACK_CONNECT_SUCCESS = 0;
- private static final int CALLBACK_CONNECT_FAIL = 1;
- private static final int CALLBACK_IDENTITY_CHANGED = 2;
-
- private final Handler mHandler;
- private final WeakReference<WifiAwareManager> mAwareManager;
- private final Binder mBinder;
- private final Looper mLooper;
-
- /**
- * Constructs a {@link AttachCallback} using the specified looper.
- * All callbacks will delivered on the thread of the specified looper.
- *
- * @param looper The looper on which to execute the callbacks.
- */
- WifiAwareEventCallbackProxy(WifiAwareManager mgr, Looper looper, Binder binder,
- final AttachCallback attachCallback,
- final IdentityChangedListener identityChangedListener) {
- mAwareManager = new WeakReference<>(mgr);
- mLooper = looper;
- mBinder = binder;
-
- if (VDBG) Log.v(TAG, "WifiAwareEventCallbackProxy ctor: looper=" + looper);
- mHandler = new Handler(looper) {
- @Override
- public void handleMessage(Message msg) {
- if (DBG) {
- Log.d(TAG, "WifiAwareEventCallbackProxy: What=" + msg.what + ", msg="
- + msg);
- }
-
- WifiAwareManager mgr = mAwareManager.get();
- if (mgr == null) {
- Log.w(TAG, "WifiAwareEventCallbackProxy: handleMessage post GC");
- return;
- }
-
- switch (msg.what) {
- case CALLBACK_CONNECT_SUCCESS:
- attachCallback.onAttached(
- new WifiAwareSession(mgr, mBinder, msg.arg1));
- break;
- case CALLBACK_CONNECT_FAIL:
- mAwareManager.clear();
- attachCallback.onAttachFailed();
- break;
- case CALLBACK_IDENTITY_CHANGED:
- if (identityChangedListener == null) {
- Log.e(TAG, "CALLBACK_IDENTITY_CHANGED: null listener.");
- } else {
- identityChangedListener.onIdentityChanged((byte[]) msg.obj);
- }
- break;
- }
- }
- };
- }
-
- @Override
- public void onConnectSuccess(int clientId) {
- if (VDBG) Log.v(TAG, "onConnectSuccess");
-
- Message msg = mHandler.obtainMessage(CALLBACK_CONNECT_SUCCESS);
- msg.arg1 = clientId;
- mHandler.sendMessage(msg);
- }
-
- @Override
- public void onConnectFail(int reason) {
- if (VDBG) Log.v(TAG, "onConnectFail: reason=" + reason);
-
- Message msg = mHandler.obtainMessage(CALLBACK_CONNECT_FAIL);
- msg.arg1 = reason;
- mHandler.sendMessage(msg);
- }
-
- @Override
- public void onIdentityChanged(byte[] mac) {
- if (VDBG) Log.v(TAG, "onIdentityChanged: mac=" + new String(HexEncoding.encode(mac)));
-
- Message msg = mHandler.obtainMessage(CALLBACK_IDENTITY_CHANGED);
- msg.obj = mac;
- mHandler.sendMessage(msg);
- }
- }
-
- private static class WifiAwareDiscoverySessionCallbackProxy extends
- IWifiAwareDiscoverySessionCallback.Stub {
- private static final int CALLBACK_SESSION_STARTED = 0;
- private static final int CALLBACK_SESSION_CONFIG_SUCCESS = 1;
- private static final int CALLBACK_SESSION_CONFIG_FAIL = 2;
- private static final int CALLBACK_SESSION_TERMINATED = 3;
- private static final int CALLBACK_MATCH = 4;
- private static final int CALLBACK_MESSAGE_SEND_SUCCESS = 5;
- private static final int CALLBACK_MESSAGE_SEND_FAIL = 6;
- private static final int CALLBACK_MESSAGE_RECEIVED = 7;
- private static final int CALLBACK_MATCH_WITH_DISTANCE = 8;
- private static final int CALLBACK_MATCH_EXPIRED = 9;
-
- private static final String MESSAGE_BUNDLE_KEY_MESSAGE = "message";
- private static final String MESSAGE_BUNDLE_KEY_MESSAGE2 = "message2";
-
- private final WeakReference<WifiAwareManager> mAwareManager;
- private final boolean mIsPublish;
- private final DiscoverySessionCallback mOriginalCallback;
- private final int mClientId;
-
- private final Handler mHandler;
- private DiscoverySession mSession;
-
- WifiAwareDiscoverySessionCallbackProxy(WifiAwareManager mgr, Looper looper,
- boolean isPublish, DiscoverySessionCallback originalCallback,
- int clientId) {
- mAwareManager = new WeakReference<>(mgr);
- mIsPublish = isPublish;
- mOriginalCallback = originalCallback;
- mClientId = clientId;
-
- if (VDBG) {
- Log.v(TAG, "WifiAwareDiscoverySessionCallbackProxy ctor: isPublish=" + isPublish);
- }
-
- mHandler = new Handler(looper) {
- @Override
- public void handleMessage(Message msg) {
- if (DBG) Log.d(TAG, "What=" + msg.what + ", msg=" + msg);
-
- if (mAwareManager.get() == null) {
- Log.w(TAG, "WifiAwareDiscoverySessionCallbackProxy: handleMessage post GC");
- return;
- }
-
- switch (msg.what) {
- case CALLBACK_SESSION_STARTED:
- onProxySessionStarted(msg.arg1);
- break;
- case CALLBACK_SESSION_CONFIG_SUCCESS:
- mOriginalCallback.onSessionConfigUpdated();
- break;
- case CALLBACK_SESSION_CONFIG_FAIL:
- mOriginalCallback.onSessionConfigFailed();
- if (mSession == null) {
- /*
- * creation failed (as opposed to update
- * failing)
- */
- mAwareManager.clear();
- }
- break;
- case CALLBACK_SESSION_TERMINATED:
- onProxySessionTerminated(msg.arg1);
- break;
- case CALLBACK_MATCH:
- case CALLBACK_MATCH_WITH_DISTANCE:
- {
- List<byte[]> matchFilter = null;
- byte[] arg = msg.getData().getByteArray(MESSAGE_BUNDLE_KEY_MESSAGE2);
- try {
- matchFilter = new TlvBufferUtils.TlvIterable(0, 1, arg).toList();
- } catch (BufferOverflowException e) {
- matchFilter = null;
- Log.e(TAG, "onServiceDiscovered: invalid match filter byte array '"
- + new String(HexEncoding.encode(arg))
- + "' - cannot be parsed: e=" + e);
- }
- if (msg.what == CALLBACK_MATCH) {
- mOriginalCallback.onServiceDiscovered(new PeerHandle(msg.arg1),
- msg.getData().getByteArray(MESSAGE_BUNDLE_KEY_MESSAGE),
- matchFilter);
- } else {
- mOriginalCallback.onServiceDiscoveredWithinRange(
- new PeerHandle(msg.arg1),
- msg.getData().getByteArray(MESSAGE_BUNDLE_KEY_MESSAGE),
- matchFilter, msg.arg2);
- }
- break;
- }
- case CALLBACK_MESSAGE_SEND_SUCCESS:
- mOriginalCallback.onMessageSendSucceeded(msg.arg1);
- break;
- case CALLBACK_MESSAGE_SEND_FAIL:
- mOriginalCallback.onMessageSendFailed(msg.arg1);
- break;
- case CALLBACK_MESSAGE_RECEIVED:
- mOriginalCallback.onMessageReceived(new PeerHandle(msg.arg1),
- (byte[]) msg.obj);
- break;
- case CALLBACK_MATCH_EXPIRED:
- if (!SdkLevel.isAtLeastS()) {
- break;
- }
- mOriginalCallback
- .onServiceLost(new PeerHandle(msg.arg1),
- WIFI_AWARE_DISCOVERY_LOST_REASON_PEER_NOT_VISIBLE);
- break;
- }
- }
- };
- }
-
- @Override
- public void onSessionStarted(int sessionId) {
- if (VDBG) Log.v(TAG, "onSessionStarted: sessionId=" + sessionId);
-
- Message msg = mHandler.obtainMessage(CALLBACK_SESSION_STARTED);
- msg.arg1 = sessionId;
- mHandler.sendMessage(msg);
- }
-
- @Override
- public void onSessionConfigSuccess() {
- if (VDBG) Log.v(TAG, "onSessionConfigSuccess");
-
- Message msg = mHandler.obtainMessage(CALLBACK_SESSION_CONFIG_SUCCESS);
- mHandler.sendMessage(msg);
- }
-
- @Override
- public void onSessionConfigFail(int reason) {
- if (VDBG) Log.v(TAG, "onSessionConfigFail: reason=" + reason);
-
- Message msg = mHandler.obtainMessage(CALLBACK_SESSION_CONFIG_FAIL);
- msg.arg1 = reason;
- mHandler.sendMessage(msg);
- }
-
- @Override
- public void onSessionTerminated(int reason) {
- if (VDBG) Log.v(TAG, "onSessionTerminated: reason=" + reason);
-
- Message msg = mHandler.obtainMessage(CALLBACK_SESSION_TERMINATED);
- msg.arg1 = reason;
- mHandler.sendMessage(msg);
- }
-
- private void onMatchCommon(int messageType, int peerId, byte[] serviceSpecificInfo,
- byte[] matchFilter, int distanceMm) {
- Bundle data = new Bundle();
- data.putByteArray(MESSAGE_BUNDLE_KEY_MESSAGE, serviceSpecificInfo);
- data.putByteArray(MESSAGE_BUNDLE_KEY_MESSAGE2, matchFilter);
-
- Message msg = mHandler.obtainMessage(messageType);
- msg.arg1 = peerId;
- msg.arg2 = distanceMm;
- msg.setData(data);
- mHandler.sendMessage(msg);
- }
-
- @Override
- public void onMatch(int peerId, byte[] serviceSpecificInfo, byte[] matchFilter) {
- if (VDBG) Log.v(TAG, "onMatch: peerId=" + peerId);
-
- onMatchCommon(CALLBACK_MATCH, peerId, serviceSpecificInfo, matchFilter, 0);
- }
-
- @Override
- public void onMatchWithDistance(int peerId, byte[] serviceSpecificInfo, byte[] matchFilter,
- int distanceMm) {
- if (VDBG) {
- Log.v(TAG, "onMatchWithDistance: peerId=" + peerId + ", distanceMm=" + distanceMm);
- }
-
- onMatchCommon(CALLBACK_MATCH_WITH_DISTANCE, peerId, serviceSpecificInfo, matchFilter,
- distanceMm);
- }
- @Override
- public void onMatchExpired(int peerId) {
- if (VDBG) {
- Log.v(TAG, "onMatchExpired: peerId=" + peerId);
- }
- Message msg = mHandler.obtainMessage(CALLBACK_MATCH_EXPIRED);
- msg.arg1 = peerId;
- mHandler.sendMessage(msg);
- }
-
- @Override
- public void onMessageSendSuccess(int messageId) {
- if (VDBG) Log.v(TAG, "onMessageSendSuccess");
-
- Message msg = mHandler.obtainMessage(CALLBACK_MESSAGE_SEND_SUCCESS);
- msg.arg1 = messageId;
- mHandler.sendMessage(msg);
- }
-
- @Override
- public void onMessageSendFail(int messageId, int reason) {
- if (VDBG) Log.v(TAG, "onMessageSendFail: reason=" + reason);
-
- Message msg = mHandler.obtainMessage(CALLBACK_MESSAGE_SEND_FAIL);
- msg.arg1 = messageId;
- msg.arg2 = reason;
- mHandler.sendMessage(msg);
- }
-
- @Override
- public void onMessageReceived(int peerId, byte[] message) {
- if (VDBG) {
- Log.v(TAG, "onMessageReceived: peerId=" + peerId);
- }
-
- Message msg = mHandler.obtainMessage(CALLBACK_MESSAGE_RECEIVED);
- msg.arg1 = peerId;
- msg.obj = message;
- mHandler.sendMessage(msg);
- }
-
- /*
- * Proxied methods
- */
- public void onProxySessionStarted(int sessionId) {
- if (VDBG) Log.v(TAG, "Proxy: onSessionStarted: sessionId=" + sessionId);
- if (mSession != null) {
- Log.e(TAG,
- "onSessionStarted: sessionId=" + sessionId + ": session already created!?");
- throw new IllegalStateException(
- "onSessionStarted: sessionId=" + sessionId + ": session already created!?");
- }
-
- WifiAwareManager mgr = mAwareManager.get();
- if (mgr == null) {
- Log.w(TAG, "onProxySessionStarted: mgr GC'd");
- return;
- }
-
- if (mIsPublish) {
- PublishDiscoverySession session = new PublishDiscoverySession(mgr,
- mClientId, sessionId);
- mSession = session;
- mOriginalCallback.onPublishStarted(session);
- } else {
- SubscribeDiscoverySession
- session = new SubscribeDiscoverySession(mgr, mClientId, sessionId);
- mSession = session;
- mOriginalCallback.onSubscribeStarted(session);
- }
- }
-
- public void onProxySessionTerminated(int reason) {
- if (VDBG) Log.v(TAG, "Proxy: onSessionTerminated: reason=" + reason);
- if (mSession != null) {
- mSession.setTerminated();
- mSession = null;
- } else {
- Log.w(TAG, "Proxy: onSessionTerminated called but mSession is null!?");
- }
- mAwareManager.clear();
- mOriginalCallback.onSessionTerminated();
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareNetworkInfo.java b/wifi/java/android/net/wifi/aware/WifiAwareNetworkInfo.java
deleted file mode 100644
index 60fe60438ce7..000000000000
--- a/wifi/java/android/net/wifi/aware/WifiAwareNetworkInfo.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (C) 2018 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.aware;
-
-import android.annotation.Nullable;
-import android.net.NetworkCapabilities;
-import android.net.TransportInfo;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.net.Inet6Address;
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-import java.util.Objects;
-
-/**
- * Wi-Fi Aware-specific network information. The information can be extracted from the
- * {@link android.net.NetworkCapabilities} of the network using
- * {@link NetworkCapabilities#getTransportInfo()}.
- * The {@link NetworkCapabilities} is provided by the connectivity service to apps, e.g. received
- * through the
- * {@link android.net.ConnectivityManager.NetworkCallback#onCapabilitiesChanged(android.net.Network,
- * android.net.NetworkCapabilities)} callback.
- * <p>
- * The Wi-Fi Aware-specific network information include the peer's scoped link-local IPv6 address
- * for the Wi-Fi Aware link, as well as (optionally) the port and transport protocol specified by
- * the peer.
- * The scoped link-local IPv6, port, and transport protocol can then be used to create a
- * {@link java.net.Socket} connection to the peer.
- * <p>
- * Note: these are the peer's IPv6 and port information - not the local device's!
- */
-public final class WifiAwareNetworkInfo implements TransportInfo, Parcelable {
- private Inet6Address mIpv6Addr;
- private int mPort = 0; // a value of 0 is considered invalid
- private int mTransportProtocol = -1; // a value of -1 is considered invalid
-
- /** @hide */
- public WifiAwareNetworkInfo(Inet6Address ipv6Addr) {
- mIpv6Addr = ipv6Addr;
- }
-
- /** @hide */
- public WifiAwareNetworkInfo(Inet6Address ipv6Addr, int port, int transportProtocol) {
- mIpv6Addr = ipv6Addr;
- mPort = port;
- mTransportProtocol = transportProtocol;
- }
-
- /**
- * Get the scoped link-local IPv6 address of the Wi-Fi Aware peer (not of the local device!).
- *
- * @return An IPv6 address.
- */
- @Nullable
- public Inet6Address getPeerIpv6Addr() {
- return mIpv6Addr;
- }
-
- /**
- * Get the port number to be used to create a network connection to the Wi-Fi Aware peer.
- * The port information is provided by the app running on the peer which requested the
- * connection, using the {@link WifiAwareNetworkSpecifier.Builder#setPort(int)}.
- *
- * @return A port number on the peer. A value of 0 indicates that no port was specified by the
- * peer.
- */
- public int getPort() {
- return mPort;
- }
-
- /**
- * Get the transport protocol to be used to communicate over a network connection to the Wi-Fi
- * Aware peer. The transport protocol is provided by the app running on the peer which requested
- * the connection, using the
- * {@link WifiAwareNetworkSpecifier.Builder#setTransportProtocol(int)}.
- * <p>
- * The transport protocol number is assigned by the Internet Assigned Numbers Authority
- * (IANA) https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml.
- *
- * @return A transport protocol id. A value of -1 indicates that no transport protocol was
- * specified by the peer.
- */
- public int getTransportProtocol() {
- return mTransportProtocol;
- }
-
- // parcelable methods
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeByteArray(mIpv6Addr.getAddress());
- NetworkInterface ni = mIpv6Addr.getScopedInterface();
- dest.writeString(ni == null ? null : ni.getName());
- dest.writeInt(mPort);
- dest.writeInt(mTransportProtocol);
- }
-
- public static final @android.annotation.NonNull Creator<WifiAwareNetworkInfo> CREATOR =
- new Creator<WifiAwareNetworkInfo>() {
- @Override
- public WifiAwareNetworkInfo createFromParcel(Parcel in) {
- byte[] addr = in.createByteArray();
- String interfaceName = in.readString();
- int port = in.readInt();
- int transportProtocol = in.readInt();
- Inet6Address ipv6Addr;
- try {
- NetworkInterface ni = null;
- if (interfaceName != null) {
- try {
- ni = NetworkInterface.getByName(interfaceName);
- } catch (SocketException e) {
- e.printStackTrace();
- }
- }
- ipv6Addr = Inet6Address.getByAddress(null, addr, ni);
- } catch (UnknownHostException e) {
- e.printStackTrace();
- return new WifiAwareNetworkInfo(null);
- }
- return new WifiAwareNetworkInfo(ipv6Addr, port, transportProtocol);
- }
-
- @Override
- public WifiAwareNetworkInfo[] newArray(int size) {
- return new WifiAwareNetworkInfo[size];
- }
- };
-
-
- // object methods
-
- @Override
- public String toString() {
- return new StringBuilder("AwareNetworkInfo: IPv6=").append(mIpv6Addr).append(
- ", port=").append(mPort).append(", transportProtocol=").append(
- mTransportProtocol).toString();
- }
-
- /** @hide */
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!(obj instanceof WifiAwareNetworkInfo)) {
- return false;
- }
-
- WifiAwareNetworkInfo lhs = (WifiAwareNetworkInfo) obj;
- return Objects.equals(mIpv6Addr, lhs.mIpv6Addr) && mPort == lhs.mPort
- && mTransportProtocol == lhs.mTransportProtocol;
- }
-
- /** @hide */
- @Override
- public int hashCode() {
- return Objects.hash(mIpv6Addr, mPort, mTransportProtocol);
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareNetworkSpecifier.java b/wifi/java/android/net/wifi/aware/WifiAwareNetworkSpecifier.java
deleted file mode 100644
index 3547750896b3..000000000000
--- a/wifi/java/android/net/wifi/aware/WifiAwareNetworkSpecifier.java
+++ /dev/null
@@ -1,446 +0,0 @@
-/*
- * Copyright (C) 2017 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.aware;
-
-import static android.net.wifi.aware.WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR;
-
-import android.annotation.IntRange;
-import android.annotation.NonNull;
-import android.net.NetworkSpecifier;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-
-import java.util.Arrays;
-import java.util.Objects;
-
-/**
- * Network specifier object used to request a Wi-Fi Aware network. Apps should use the
- * {@link WifiAwareNetworkSpecifier.Builder} class to create an instance.
- */
-public final class WifiAwareNetworkSpecifier extends NetworkSpecifier implements Parcelable {
- /**
- * TYPE: in band, specific peer: role, client_id, session_id, peer_id, pmk/passphrase optional
- * @hide
- */
- public static final int NETWORK_SPECIFIER_TYPE_IB = 0;
-
- /**
- * TYPE: in band, any peer: role, client_id, session_id, pmk/passphrase optional
- * [only permitted for RESPONDER]
- * @hide
- */
- public static final int NETWORK_SPECIFIER_TYPE_IB_ANY_PEER = 1;
-
- /**
- * TYPE: out-of-band: role, client_id, peer_mac, pmk/passphrase optional
- * @hide
- */
- public static final int NETWORK_SPECIFIER_TYPE_OOB = 2;
-
- /**
- * TYPE: out-of-band, any peer: role, client_id, pmk/passphrase optional
- * [only permitted for RESPONDER]
- * @hide
- */
- public static final int NETWORK_SPECIFIER_TYPE_OOB_ANY_PEER = 3;
-
- /** @hide */
- public static final int NETWORK_SPECIFIER_TYPE_MAX_VALID = NETWORK_SPECIFIER_TYPE_OOB_ANY_PEER;
-
- /**
- * One of the NETWORK_SPECIFIER_TYPE_* constants. The type of the network specifier object.
- * @hide
- */
- public final int type;
-
- /**
- * The role of the device: WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_INITIATOR or
- * WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER.
- * @hide
- */
- public final int role;
-
- /**
- * The client ID of the device.
- * @hide
- */
- public final int clientId;
-
- /**
- * The session ID in which context to request a data-path. Only relevant for IB requests.
- * @hide
- */
- public final int sessionId;
-
- /**
- * The peer ID of the device which the data-path should be connected to. Only relevant for
- * IB requests (i.e. not IB_ANY_PEER or OOB*).
- * @hide
- */
- public final int peerId;
-
- /**
- * The peer MAC address of the device which the data-path should be connected to. Only relevant
- * for OB requests (i.e. not OOB_ANY_PEER or IB*).
- * @hide
- */
- public final byte[] peerMac;
-
- /**
- * The PMK of the requested data-path. Can be null. Only one or none of pmk or passphrase should
- * be specified.
- * @hide
- */
- public final byte[] pmk;
-
- /**
- * The Passphrase of the requested data-path. Can be null. Only one or none of the pmk or
- * passphrase should be specified.
- * @hide
- */
- public final String passphrase;
-
- /**
- * The port information to be used for this link. This information will be communicated to the
- * peer as part of the layer 2 link setup.
- *
- * Information only allowed on secure links since a single layer-2 link is set up for all
- * requestors. Therefore if multiple apps on a single device request links to the same peer
- * device they all get the same link. However, the link is only set up on the first request -
- * hence only the first can transmit the port information. But we don't want to expose that
- * information to other apps. Limiting to secure links would (usually) imply single app usage.
- *
- * @hide
- */
- public final int port;
-
- /**
- * The transport protocol information to be used for this link. This information will be
- * communicated to the peer as part of the layer 2 link setup.
- *
- * Information only allowed on secure links since a single layer-2 link is set up for all
- * requestors. Therefore if multiple apps on a single device request links to the same peer
- * device they all get the same link. However, the link is only set up on the first request -
- * hence only the first can transmit the port information. But we don't want to expose that
- * information to other apps. Limiting to secure links would (usually) imply single app usage.
- *
- * @hide
- */
- public final int transportProtocol;
-
- /** @hide */
- public WifiAwareNetworkSpecifier(int type, int role, int clientId, int sessionId, int peerId,
- byte[] peerMac, byte[] pmk, String passphrase, int port, int transportProtocol) {
- this.type = type;
- this.role = role;
- this.clientId = clientId;
- this.sessionId = sessionId;
- this.peerId = peerId;
- this.peerMac = peerMac;
- this.pmk = pmk;
- this.passphrase = passphrase;
- this.port = port;
- this.transportProtocol = transportProtocol;
- }
-
- public static final @android.annotation.NonNull Creator<WifiAwareNetworkSpecifier> CREATOR =
- new Creator<WifiAwareNetworkSpecifier>() {
- @Override
- public WifiAwareNetworkSpecifier createFromParcel(Parcel in) {
- return new WifiAwareNetworkSpecifier(
- in.readInt(), // type
- in.readInt(), // role
- in.readInt(), // clientId
- in.readInt(), // sessionId
- in.readInt(), // peerId
- in.createByteArray(), // peerMac
- in.createByteArray(), // pmk
- in.readString(), // passphrase
- in.readInt(), // port
- in.readInt()); // transportProtocol
- }
-
- @Override
- public WifiAwareNetworkSpecifier[] newArray(int size) {
- return new WifiAwareNetworkSpecifier[size];
- }
- };
-
- /**
- * Indicates whether the network specifier specifies an OOB (out-of-band) data-path - i.e. a
- * data-path created without a corresponding Aware discovery session.
- *
- * @hide
- */
- public boolean isOutOfBand() {
- return type == NETWORK_SPECIFIER_TYPE_OOB || type == NETWORK_SPECIFIER_TYPE_OOB_ANY_PEER;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(type);
- dest.writeInt(role);
- dest.writeInt(clientId);
- dest.writeInt(sessionId);
- dest.writeInt(peerId);
- dest.writeByteArray(peerMac);
- dest.writeByteArray(pmk);
- dest.writeString(passphrase);
- dest.writeInt(port);
- dest.writeInt(transportProtocol);
- }
-
- /** @hide */
- @Override
- public boolean canBeSatisfiedBy(NetworkSpecifier other) {
- // MatchAllNetworkSpecifier is taken care in NetworkCapabilities#satisfiedBySpecifier.
- if (other instanceof WifiAwareAgentNetworkSpecifier) {
- return ((WifiAwareAgentNetworkSpecifier) other).satisfiesAwareNetworkSpecifier(this);
- }
- return equals(other);
- }
-
- /** @hide */
- @Override
- public int hashCode() {
- return Objects.hash(type, role, clientId, sessionId, peerId, Arrays.hashCode(peerMac),
- Arrays.hashCode(pmk), passphrase, port, transportProtocol);
- }
-
- /** @hide */
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (!(obj instanceof WifiAwareNetworkSpecifier)) {
- return false;
- }
-
- WifiAwareNetworkSpecifier lhs = (WifiAwareNetworkSpecifier) obj;
-
- return type == lhs.type
- && role == lhs.role
- && clientId == lhs.clientId
- && sessionId == lhs.sessionId
- && peerId == lhs.peerId
- && Arrays.equals(peerMac, lhs.peerMac)
- && Arrays.equals(pmk, lhs.pmk)
- && Objects.equals(passphrase, lhs.passphrase)
- && port == lhs.port
- && transportProtocol == lhs.transportProtocol;
- }
-
- /** @hide */
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder("WifiAwareNetworkSpecifier [");
- sb.append("type=").append(type)
- .append(", role=").append(role)
- .append(", clientId=").append(clientId)
- .append(", sessionId=").append(sessionId)
- .append(", peerId=").append(peerId)
- // masking potential PII (although low impact information)
- .append(", peerMac=").append((peerMac == null) ? "<null>" : "<non-null>")
- // masking PII
- .append(", pmk=").append((pmk == null) ? "<null>" : "<non-null>")
- // masking PII
- .append(", passphrase=").append((passphrase == null) ? "<null>" : "<non-null>")
- .append(", port=").append(port).append(", transportProtocol=")
- .append(transportProtocol)
- .append("]");
- return sb.toString();
- }
-
- /**
- * A builder class for a Wi-Fi Aware network specifier to set up an Aware connection with a
- * peer.
- */
- public static final class Builder {
- private DiscoverySession mDiscoverySession;
- private PeerHandle mPeerHandle;
- private String mPskPassphrase;
- private byte[] mPmk;
- private int mPort = 0; // invalid value
- private int mTransportProtocol = -1; // invalid value
-
- /**
- * Create a builder for {@link WifiAwareNetworkSpecifier} used in requests to set up a
- * Wi-Fi Aware connection with a peer.
- *
- * @param discoverySession A Wi-Fi Aware discovery session in whose context the connection
- * is created.
- * @param peerHandle The handle of the peer to which the Wi-Fi Aware connection is
- * requested. The peer is discovered through Wi-Fi Aware discovery. The
- * handle can be obtained through
- * {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle, byte[], java.util.List)}
- * or
- * {@link DiscoverySessionCallback#onMessageReceived(PeerHandle, byte[])}.
- */
- public Builder(@NonNull DiscoverySession discoverySession, @NonNull PeerHandle peerHandle) {
- if (discoverySession == null) {
- throw new IllegalArgumentException("Non-null discoverySession required");
- }
- if (peerHandle == null) {
- throw new IllegalArgumentException("Non-null peerHandle required");
- }
- mDiscoverySession = discoverySession;
- mPeerHandle = peerHandle;
- }
-
- /**
- * Configure the PSK Passphrase for the Wi-Fi Aware connection being requested. This method
- * is optional - if not called, then an Open (unencrypted) connection will be created.
- *
- * @param pskPassphrase The (optional) passphrase to be used to encrypt the link. Use the
- * {@link #setPmk(byte[])} to specify a PMK.
- * @return the current {@link Builder} builder, enabling chaining of builder
- * methods.
- */
- public @NonNull Builder setPskPassphrase(@NonNull String pskPassphrase) {
- if (!WifiAwareUtils.validatePassphrase(pskPassphrase)) {
- throw new IllegalArgumentException("Passphrase must meet length requirements");
- }
- mPskPassphrase = pskPassphrase;
- return this;
- }
-
- /**
- * Configure the PMK for the Wi-Fi Aware connection being requested. This method
- * is optional - if not called, then an Open (unencrypted) connection will be created.
- *
- * @param pmk A PMK (pairwise master key, see IEEE 802.11i) specifying the key to use for
- * encrypting the data-path. Use the {@link #setPskPassphrase(String)} to
- * specify a Passphrase.
- * @return the current {@link Builder} builder, enabling chaining of builder
- * methods.
- */
- public @NonNull Builder setPmk(@NonNull byte[] pmk) {
- if (!WifiAwareUtils.validatePmk(pmk)) {
- throw new IllegalArgumentException("PMK must 32 bytes");
- }
- mPmk = pmk;
- return this;
- }
-
- /**
- * Configure the port number which will be used to create a connection over this link. This
- * configuration should only be done on the server device, e.g. the device creating the
- * {@link java.net.ServerSocket}.
- * <p>Notes:
- * <ul>
- * <li>The server device must be the Publisher device!
- * <li>The port information can only be specified on secure links, specified using
- * {@link #setPskPassphrase(String)} or {@link #setPmk(byte[])}.
- * </ul>
- *
- * @param port A positive integer indicating the port to be used for communication.
- * @return the current {@link Builder} builder, enabling chaining of builder
- * methods.
- */
- public @NonNull Builder setPort(@IntRange(from = 0, to = 65535) int port) {
- if (port <= 0 || port > 65535) {
- throw new IllegalArgumentException("The port must be a positive value (0, 65535]");
- }
- mPort = port;
- return this;
- }
-
- /**
- * Configure the transport protocol which will be used to create a connection over this
- * link. This configuration should only be done on the server device, e.g. the device
- * creating the {@link java.net.ServerSocket} for TCP.
- * <p>Notes:
- * <ul>
- * <li>The server device must be the Publisher device!
- * <li>The transport protocol information can only be specified on secure links,
- * specified using {@link #setPskPassphrase(String)} or {@link #setPmk(byte[])}.
- * </ul>
- * The transport protocol number is assigned by the Internet Assigned Numbers Authority
- * (IANA) https://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml.
- *
- * @param transportProtocol The transport protocol to be used for communication.
- * @return the current {@link Builder} builder, enabling chaining of builder
- * methods.
- */
- public @NonNull
- Builder setTransportProtocol(@IntRange(from = 0, to = 255) int transportProtocol) {
- if (transportProtocol < 0 || transportProtocol > 255) {
- throw new IllegalArgumentException(
- "The transport protocol must be in range [0, 255]");
- }
- mTransportProtocol = transportProtocol;
- return this;
- }
-
- /**
- * Create a {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)}
- * for a WiFi Aware connection (link) to the specified peer. The
- * {@link android.net.NetworkRequest.Builder#addTransportType(int)} should be set to
- * {@link android.net.NetworkCapabilities#TRANSPORT_WIFI_AWARE}.
- * <p> The default builder constructor will initialize a NetworkSpecifier which requests an
- * open (non-encrypted) link. To request an encrypted link use the
- * {@link #setPskPassphrase(String)} or {@link #setPmk(byte[])} builder methods.
- *
- * @return A {@link NetworkSpecifier} to be used to construct
- * {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} to pass
- * to {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest,
- * android.net.ConnectivityManager.NetworkCallback)}
- * [or other varieties of that API].
- */
- public @NonNull WifiAwareNetworkSpecifier build() {
- if (mDiscoverySession == null) {
- throw new IllegalStateException("Null discovery session!?");
- }
- if (mPeerHandle == null) {
- throw new IllegalStateException("Null peerHandle!?");
- }
- if (mPskPassphrase != null & mPmk != null) {
- throw new IllegalStateException(
- "Can only specify a Passphrase or a PMK - not both!");
- }
-
- int role = mDiscoverySession instanceof SubscribeDiscoverySession
- ? WIFI_AWARE_DATA_PATH_ROLE_INITIATOR
- : WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER;
-
- if (mPort != 0 || mTransportProtocol != -1) {
- if (role != WifiAwareManager.WIFI_AWARE_DATA_PATH_ROLE_RESPONDER) {
- throw new IllegalStateException(
- "Port and transport protocol information can only "
- + "be specified on the Publisher device (which is the server");
- }
- if (TextUtils.isEmpty(mPskPassphrase) && mPmk == null) {
- throw new IllegalStateException("Port and transport protocol information can "
- + "only be specified on a secure link");
- }
- }
-
- return new WifiAwareNetworkSpecifier(
- WifiAwareNetworkSpecifier.NETWORK_SPECIFIER_TYPE_IB, role,
- mDiscoverySession.mClientId, mDiscoverySession.mSessionId, mPeerHandle.peerId,
- null, mPmk, mPskPassphrase, mPort, mTransportProtocol);
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareSession.java b/wifi/java/android/net/wifi/aware/WifiAwareSession.java
deleted file mode 100644
index fe0872caf5f8..000000000000
--- a/wifi/java/android/net/wifi/aware/WifiAwareSession.java
+++ /dev/null
@@ -1,343 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.NetworkSpecifier;
-import android.os.Binder;
-import android.os.Handler;
-import android.os.Looper;
-import android.util.CloseGuard;
-import android.util.Log;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.lang.ref.Reference;
-import java.lang.ref.WeakReference;
-
-/**
- * This class represents a Wi-Fi Aware session - an attachment to the Wi-Fi Aware service through
- * which the app can execute discovery operations.
- */
-public class WifiAwareSession implements AutoCloseable {
- private static final String TAG = "WifiAwareSession";
- private static final boolean DBG = false;
- private static final boolean VDBG = false; // STOPSHIP if true
-
- private final WeakReference<WifiAwareManager> mMgr;
- private final Binder mBinder;
- private final int mClientId;
-
- private boolean mTerminated = true;
- private final CloseGuard mCloseGuard = new CloseGuard();
-
- /** @hide */
- public WifiAwareSession(WifiAwareManager manager, Binder binder, int clientId) {
- if (VDBG) Log.v(TAG, "New session created: manager=" + manager + ", clientId=" + clientId);
-
- mMgr = new WeakReference<>(manager);
- mBinder = binder;
- mClientId = clientId;
- mTerminated = false;
-
- mCloseGuard.open("close");
- }
-
- /**
- * Destroy the Wi-Fi Aware service session and, if no other applications are attached to Aware,
- * also disable Aware. This method destroys all outstanding operations - i.e. all publish and
- * subscribes are terminated, and any outstanding data-links are shut-down. However, it is
- * good practice to destroy these discovery sessions and connections explicitly before a
- * session-wide destroy.
- * <p>
- * An application may re-attach after a destroy using
- * {@link WifiAwareManager#attach(AttachCallback, Handler)} .
- */
- @Override
- public void close() {
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.w(TAG, "destroy: called post GC on WifiAwareManager");
- return;
- }
- mgr.disconnect(mClientId, mBinder);
- mTerminated = true;
- mMgr.clear();
- mCloseGuard.close();
- Reference.reachabilityFence(this);
- }
-
- /** @hide */
- @Override
- protected void finalize() throws Throwable {
- try {
- if (mCloseGuard != null) {
- mCloseGuard.warnIfOpen();
- }
-
- if (!mTerminated) {
- close();
- }
- } finally {
- super.finalize();
- }
- }
-
- /**
- * Access the client ID of the Aware session.
- *
- * Note: internal visibility for testing.
- *
- * @return The internal client ID.
- *
- * @hide
- */
- @VisibleForTesting
- public int getClientId() {
- return mClientId;
- }
-
- /**
- * Issue a request to the Aware service to create a new Aware publish discovery session, using
- * the specified {@code publishConfig} configuration. The results of the publish operation
- * are routed to the callbacks of {@link DiscoverySessionCallback}:
- * <ul>
- * <li>
- * {@link DiscoverySessionCallback#onPublishStarted(
- *PublishDiscoverySession)}
- * is called when the publish session is created and provides a handle to the session.
- * Further operations on the publish session can be executed on that object.
- * <li>{@link DiscoverySessionCallback#onSessionConfigFailed()} is called if the
- * publish operation failed.
- * </ul>
- * <p>
- * Other results of the publish session operations will also be routed to callbacks
- * on the {@code callback} object. The resulting publish session can be modified using
- * {@link PublishDiscoverySession#updatePublish(PublishConfig)}.
- * <p>
- * An application must use the {@link DiscoverySession#close()} to
- * terminate the publish discovery session once it isn't needed. This will free
- * resources as well terminate any on-air transmissions.
- * <p>The application must have the {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
- * permission to start a publish discovery session.
- *
- * @param publishConfig The {@link PublishConfig} specifying the
- * configuration of the requested publish session.
- * @param callback A {@link DiscoverySessionCallback} derived object to be used for
- * session event callbacks.
- * @param handler The Handler on whose thread to execute the callbacks of the {@code
- * callback} object. If a null is provided then the application's main thread will be used.
- */
- public void publish(@NonNull PublishConfig publishConfig,
- @NonNull DiscoverySessionCallback callback, @Nullable Handler handler) {
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.e(TAG, "publish: called post GC on WifiAwareManager");
- return;
- }
- if (mTerminated) {
- Log.e(TAG, "publish: called after termination");
- return;
- }
- mgr.publish(mClientId, (handler == null) ? Looper.getMainLooper() : handler.getLooper(),
- publishConfig, callback);
- }
-
- /**
- * Issue a request to the Aware service to create a new Aware subscribe discovery session, using
- * the specified {@code subscribeConfig} configuration. The results of the subscribe
- * operation are routed to the callbacks of {@link DiscoverySessionCallback}:
- * <ul>
- * <li>
- * {@link DiscoverySessionCallback#onSubscribeStarted(
- *SubscribeDiscoverySession)}
- * is called when the subscribe session is created and provides a handle to the session.
- * Further operations on the subscribe session can be executed on that object.
- * <li>{@link DiscoverySessionCallback#onSessionConfigFailed()} is called if the
- * subscribe operation failed.
- * </ul>
- * <p>
- * Other results of the subscribe session operations will also be routed to callbacks
- * on the {@code callback} object. The resulting subscribe session can be modified using
- * {@link SubscribeDiscoverySession#updateSubscribe(SubscribeConfig)}.
- * <p>
- * An application must use the {@link DiscoverySession#close()} to
- * terminate the subscribe discovery session once it isn't needed. This will free
- * resources as well terminate any on-air transmissions.
- * <p>The application must have the {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
- * permission to start a subscribe discovery session.
- *
- * @param subscribeConfig The {@link SubscribeConfig} specifying the
- * configuration of the requested subscribe session.
- * @param callback A {@link DiscoverySessionCallback} derived object to be used for
- * session event callbacks.
- * @param handler The Handler on whose thread to execute the callbacks of the {@code
- * callback} object. If a null is provided then the application's main thread will be used.
- */
- public void subscribe(@NonNull SubscribeConfig subscribeConfig,
- @NonNull DiscoverySessionCallback callback, @Nullable Handler handler) {
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.e(TAG, "publish: called post GC on WifiAwareManager");
- return;
- }
- if (mTerminated) {
- Log.e(TAG, "publish: called after termination");
- return;
- }
- mgr.subscribe(mClientId, (handler == null) ? Looper.getMainLooper() : handler.getLooper(),
- subscribeConfig, callback);
- }
-
- /**
- * Create a {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} for
- * an unencrypted WiFi Aware connection (link) to the specified peer. The
- * {@link android.net.NetworkRequest.Builder#addTransportType(int)} should be set to
- * {@link android.net.NetworkCapabilities#TRANSPORT_WIFI_AWARE}.
- * <p>
- * This API is targeted for applications which can obtain the peer MAC address using OOB
- * (out-of-band) discovery. Aware discovery does not provide the MAC address of the peer -
- * when using Aware discovery use the alternative network specifier method -
- * {@link android.net.wifi.aware.WifiAwareNetworkSpecifier.Builder}.
- * <p>
- * To set up an encrypted link use the
- * {@link #createNetworkSpecifierPassphrase(int, byte[], String)} API.
- *
- * @param role The role of this device:
- * {@link WifiAwareManager#WIFI_AWARE_DATA_PATH_ROLE_INITIATOR} or
- * {@link WifiAwareManager#WIFI_AWARE_DATA_PATH_ROLE_RESPONDER}
- * @param peer The MAC address of the peer's Aware discovery interface. On a RESPONDER this
- * value is used to gate the acceptance of a connection request from only that
- * peer.
- *
- * @return A {@link NetworkSpecifier} to be used to construct
- * {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} to pass to
- * {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest,
- * android.net.ConnectivityManager.NetworkCallback)}
- * [or other varieties of that API].
- */
- public NetworkSpecifier createNetworkSpecifierOpen(
- @WifiAwareManager.DataPathRole int role, @NonNull byte[] peer) {
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.e(TAG, "createNetworkSpecifierOpen: called post GC on WifiAwareManager");
- return null;
- }
- if (mTerminated) {
- Log.e(TAG, "createNetworkSpecifierOpen: called after termination");
- return null;
- }
- return mgr.createNetworkSpecifier(mClientId, role, peer, null, null);
- }
-
- /**
- * Create a {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} for
- * an encrypted WiFi Aware connection (link) to the specified peer. The
- * {@link android.net.NetworkRequest.Builder#addTransportType(int)} should be set to
- * {@link android.net.NetworkCapabilities#TRANSPORT_WIFI_AWARE}.
- * <p>
- * This API is targeted for applications which can obtain the peer MAC address using OOB
- * (out-of-band) discovery. Aware discovery does not provide the MAC address of the peer -
- * when using Aware discovery use the alternative network specifier method -
- * {@link android.net.wifi.aware.WifiAwareNetworkSpecifier.Builder}.
- *
- * @param role The role of this device:
- * {@link WifiAwareManager#WIFI_AWARE_DATA_PATH_ROLE_INITIATOR} or
- * {@link WifiAwareManager#WIFI_AWARE_DATA_PATH_ROLE_RESPONDER}
- * @param peer The MAC address of the peer's Aware discovery interface. On a RESPONDER this
- * value is used to gate the acceptance of a connection request from only that
- * peer.
- * @param passphrase The passphrase to be used to encrypt the link. The PMK is generated from
- * the passphrase. Use {@link #createNetworkSpecifierOpen(int, byte[])} to
- * specify an open (unencrypted) link.
- *
- * @return A {@link NetworkSpecifier} to be used to construct
- * {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} to pass to
- * {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest,
- * android.net.ConnectivityManager.NetworkCallback)}
- * [or other varieties of that API].
- */
- public NetworkSpecifier createNetworkSpecifierPassphrase(
- @WifiAwareManager.DataPathRole int role, @NonNull byte[] peer,
- @NonNull String passphrase) {
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.e(TAG, "createNetworkSpecifierPassphrase: called post GC on WifiAwareManager");
- return null;
- }
- if (mTerminated) {
- Log.e(TAG, "createNetworkSpecifierPassphrase: called after termination");
- return null;
- }
- if (!WifiAwareUtils.validatePassphrase(passphrase)) {
- throw new IllegalArgumentException("Passphrase must meet length requirements");
- }
-
- return mgr.createNetworkSpecifier(mClientId, role, peer, null, passphrase);
- }
-
- /**
- * Create a {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} for
- * an encrypted WiFi Aware connection (link) to the specified peer. The
- * {@link android.net.NetworkRequest.Builder#addTransportType(int)} should be set to
- * {@link android.net.NetworkCapabilities#TRANSPORT_WIFI_AWARE}.
- * <p>
- * This API is targeted for applications which can obtain the peer MAC address using OOB
- * (out-of-band) discovery. Aware discovery does not provide the MAC address of the peer -
- * when using Aware discovery use the alternative network specifier method -
- * {@link android.net.wifi.aware.WifiAwareNetworkSpecifier.Builder}.
- *
- * @param role The role of this device:
- * {@link WifiAwareManager#WIFI_AWARE_DATA_PATH_ROLE_INITIATOR} or
- * {@link WifiAwareManager#WIFI_AWARE_DATA_PATH_ROLE_RESPONDER}
- * @param peer The MAC address of the peer's Aware discovery interface. On a RESPONDER this
- * value is used to gate the acceptance of a connection request from only that
- * peer.
- * @param pmk A PMK (pairwise master key, see IEEE 802.11i) specifying the key to use for
- * encrypting the data-path. Use the
- * {@link #createNetworkSpecifierPassphrase(int, byte[], String)} to specify a
- * Passphrase or {@link #createNetworkSpecifierOpen(int, byte[])} to specify an
- * open (unencrypted) link.
- *
- * @return A {@link NetworkSpecifier} to be used to construct
- * {@link android.net.NetworkRequest.Builder#setNetworkSpecifier(NetworkSpecifier)} to pass to
- * {@link android.net.ConnectivityManager#requestNetwork(android.net.NetworkRequest,
- * android.net.ConnectivityManager.NetworkCallback)}
- * [or other varieties of that API].
- *
- * @hide
- */
- @SystemApi
- public NetworkSpecifier createNetworkSpecifierPmk(
- @WifiAwareManager.DataPathRole int role, @NonNull byte[] peer, @NonNull byte[] pmk) {
- WifiAwareManager mgr = mMgr.get();
- if (mgr == null) {
- Log.e(TAG, "createNetworkSpecifierPmk: called post GC on WifiAwareManager");
- return null;
- }
- if (mTerminated) {
- Log.e(TAG, "createNetworkSpecifierPmk: called after termination");
- return null;
- }
- if (!WifiAwareUtils.validatePmk(pmk)) {
- throw new IllegalArgumentException("PMK must 32 bytes");
- }
- return mgr.createNetworkSpecifier(mClientId, role, peer, pmk, null);
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/WifiAwareUtils.java b/wifi/java/android/net/wifi/aware/WifiAwareUtils.java
deleted file mode 100644
index 3ece93dfdf0a..000000000000
--- a/wifi/java/android/net/wifi/aware/WifiAwareUtils.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2016 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.aware;
-
-import android.content.Context;
-import android.content.pm.PackageManager;
-import android.hardware.wifi.V1_0.Constants;
-
-/**
- * Provides utilities for the Wifi Aware manager/service.
- *
- * @hide
- */
-public class WifiAwareUtils {
- /**
- * Per spec: The Service Name is a UTF-8 encoded string from 1 to 255 bytes in length. The
- * only acceptable single-byte UTF-8 symbols for a Service Name are alphanumeric values (A-Z,
- * a-z, 0-9), the hyphen ('-'), and the period ('.'). All valid multi-byte UTF-8 characters
- * are acceptable in a Service Name.
- */
- public static void validateServiceName(byte[] serviceNameData) throws IllegalArgumentException {
- if (serviceNameData == null) {
- throw new IllegalArgumentException("Invalid service name - null");
- }
-
- if (serviceNameData.length < 1 || serviceNameData.length > 255) {
- throw new IllegalArgumentException("Invalid service name length - must be between "
- + "1 and 255 bytes (UTF-8 encoding)");
- }
-
- int index = 0;
- while (index < serviceNameData.length) {
- byte b = serviceNameData[index];
- if ((b & 0x80) == 0x00) {
- if (!((b >= '0' && b <= '9') || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')
- || b == '-' || b == '.')) {
- throw new IllegalArgumentException("Invalid service name - illegal characters,"
- + " allowed = (0-9, a-z,A-Z, -, .)");
- }
- }
- ++index;
- }
- }
-
- /**
- * Validates that the passphrase is a non-null string of the right size (per the HAL min/max
- * length parameters).
- *
- * @param passphrase Passphrase to test
- * @return true if passphrase is valid, false if not
- */
- public static boolean validatePassphrase(String passphrase) {
- if (passphrase == null
- || passphrase.length() < Constants.NanParamSizeLimits.MIN_PASSPHRASE_LENGTH
- || passphrase.length() > Constants.NanParamSizeLimits.MAX_PASSPHRASE_LENGTH) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Validates that the PMK is a non-null byte array of the right size (32 bytes per spec).
- *
- * @param pmk PMK to test
- * @return true if PMK is valid, false if not
- */
- public static boolean validatePmk(byte[] pmk) {
- if (pmk == null || pmk.length != 32) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Returns true if the App version is older than minVersion.
- */
- public static boolean isLegacyVersion(Context context, int minVersion) {
- try {
- if (context.getPackageManager().getApplicationInfo(context.getOpPackageName(), 0)
- .targetSdkVersion < minVersion) {
- return true;
- }
- } catch (PackageManager.NameNotFoundException e) {
- // In case of exception, assume known app (more strict checking)
- // Note: This case will never happen since checkPackage is
- // called to verify valididity before checking App's version.
- }
- return false;
- }
-}
diff --git a/wifi/java/android/net/wifi/aware/package.html b/wifi/java/android/net/wifi/aware/package.html
deleted file mode 100644
index c4f2e1fec96b..000000000000
--- a/wifi/java/android/net/wifi/aware/package.html
+++ /dev/null
@@ -1,43 +0,0 @@
-<HTML>
-<BODY>
-<p>Provides classes which allow applications to use Wi-Fi Aware to discover peers and create
- connections to them.</p>
-<p>Using the Wi-Fi Aware APIs, applications can advertise services, discover peers which are
- advertising services, and connect to them.
- Wi-Fi Aware is independent of Wi-Fi infrastructure (i.e. a device may or may
- not be associated with an AP concurrent to using Wi-Fi Aware). </p>
-<p>The primary entry point to Wi-Fi Aware capabilities is the
- {@link android.net.wifi.aware.WifiAwareManager} class, which is acquired by calling
- {@link android.content.Context#getSystemService(String)
- Context.getSystemService(Context.WIFI_AWARE_SERVICE)}</p>
-
-<p>Some APIs may require the following user permissions:</p>
-<ul>
- <li>{@link android.Manifest.permission#ACCESS_WIFI_STATE}</li>
- <li>{@link android.Manifest.permission#CHANGE_WIFI_STATE}</li>
- <li>{@link android.Manifest.permission#ACCESS_FINE_LOCATION}</li>
-</ul>
-
-<p class="note"><strong>Note:</strong> Not all Android-powered devices support Wi-Fi Aware
- functionality.
- If your application only works with Wi-Fi Aware (i.e. it should only be installed on devices which
- support Wi-Fi Aware), declare so with a <a
- href="{@docRoot}guide/topics/manifest/uses-feature-element.html">
- {@code <uses-feature>}</a>
- element in the manifest file:</p>
-<pre>
-&lt;manifest ...>
- &lt;uses-feature android:name="android.hardware.wifi.aware" />
- ...
-&lt;/manifest>
-</pre>
-<p>Alternatively, if you application does not require Wi-Fi Aware but can take advantage of it if
- available, you can perform
- the check at run-time in your code using {@link
- android.content.pm.PackageManager#hasSystemFeature(String)} with {@link
- android.content.pm.PackageManager#FEATURE_WIFI_AWARE}:</p>
-<pre>
- getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_AWARE)
-</pre>
-</BODY>
-</HTML>
diff --git a/wifi/java/android/net/wifi/hotspot2/ConfigParser.java b/wifi/java/android/net/wifi/hotspot2/ConfigParser.java
deleted file mode 100644
index bb01365d6722..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/ConfigParser.java
+++ /dev/null
@@ -1,486 +0,0 @@
-/**
- * Copyright (c) 2016, 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.hotspot2;
-
-import android.net.wifi.hotspot2.omadm.PpsMoParser;
-import android.text.TextUtils;
-import android.util.Base64;
-import android.util.Log;
-import android.util.Pair;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.LineNumberReader;
-import java.nio.charset.StandardCharsets;
-import java.security.GeneralSecurityException;
-import java.security.KeyStore;
-import java.security.PrivateKey;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Utility class for building PasspointConfiguration from an installation file.
- */
-public final class ConfigParser {
- private static final String TAG = "ConfigParser";
-
- // Header names.
- private static final String CONTENT_TYPE = "Content-Type";
- private static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding";
-
- // MIME types.
- private static final String TYPE_MULTIPART_MIXED = "multipart/mixed";
- private static final String TYPE_WIFI_CONFIG = "application/x-wifi-config";
- private static final String TYPE_PASSPOINT_PROFILE = "application/x-passpoint-profile";
- private static final String TYPE_CA_CERT = "application/x-x509-ca-cert";
- private static final String TYPE_PKCS12 = "application/x-pkcs12";
-
- private static final String ENCODING_BASE64 = "base64";
- private static final String BOUNDARY = "boundary=";
-
- /**
- * Class represent a MIME (Multipurpose Internet Mail Extension) part.
- */
- private static class MimePart {
- /**
- * Content type of the part.
- */
- public String type = null;
-
- /**
- * Decoded data.
- */
- public byte[] data = null;
-
- /**
- * Flag indicating if this is the last part (ending with --{boundary}--).
- */
- public boolean isLast = false;
- }
-
- /**
- * Class represent the MIME (Multipurpose Internet Mail Extension) header.
- */
- private static class MimeHeader {
- /**
- * Content type.
- */
- public String contentType = null;
-
- /**
- * Boundary string (optional), only applies for the outter MIME header.
- */
- public String boundary = null;
-
- /**
- * Encoding type.
- */
- public String encodingType = null;
- }
-
- /**
- * @hide
- */
- public ConfigParser() {}
-
- /**
- * Parse the Hotspot 2.0 Release 1 configuration data into a {@link PasspointConfiguration}
- * object. The configuration data is a base64 encoded MIME multipart data. Below is
- * the format of the decoded message:
- *
- * Content-Type: multipart/mixed; boundary={boundary}
- * Content-Transfer-Encoding: base64
- * [Skip uninterested headers]
- *
- * --{boundary}
- * Content-Type: application/x-passpoint-profile
- * Content-Transfer-Encoding: base64
- *
- * [base64 encoded Passpoint profile data]
- * --{boundary}
- * Content-Type: application/x-x509-ca-cert
- * Content-Transfer-Encoding: base64
- *
- * [base64 encoded X509 CA certificate data]
- * --{boundary}
- * Content-Type: application/x-pkcs12
- * Content-Transfer-Encoding: base64
- *
- * [base64 encoded PKCS#12 ASN.1 structure containing client certificate chain]
- * --{boundary}
- *
- * @param mimeType MIME type of the encoded data.
- * @param data A base64 encoded MIME multipart message containing the Passpoint profile
- * (required), CA (Certificate Authority) certificate (optional), and client
- * certificate chain (optional).
- * @return {@link PasspointConfiguration}
- */
- public static PasspointConfiguration parsePasspointConfig(String mimeType, byte[] data) {
- // Verify MIME type.
- if (!TextUtils.equals(mimeType, TYPE_WIFI_CONFIG)) {
- Log.e(TAG, "Unexpected MIME type: " + mimeType);
- return null;
- }
-
- try {
- // Decode the data.
- byte[] decodedData = Base64.decode(new String(data, StandardCharsets.ISO_8859_1),
- Base64.DEFAULT);
- Map<String, byte[]> mimeParts = parseMimeMultipartMessage(new LineNumberReader(
- new InputStreamReader(new ByteArrayInputStream(decodedData),
- StandardCharsets.ISO_8859_1)));
- return createPasspointConfig(mimeParts);
- } catch (IOException | IllegalArgumentException e) {
- Log.e(TAG, "Failed to parse installation file: " + e.getMessage());
- return null;
- }
- }
-
- /**
- * Create a {@link PasspointConfiguration} object from list of MIME (Multipurpose Internet
- * Mail Extension) parts.
- *
- * @param mimeParts Map of content type and content data.
- * @return {@link PasspointConfiguration}
- * @throws IOException
- */
- private static PasspointConfiguration createPasspointConfig(Map<String, byte[]> mimeParts)
- throws IOException {
- byte[] profileData = mimeParts.get(TYPE_PASSPOINT_PROFILE);
- if (profileData == null) {
- throw new IOException("Missing Passpoint Profile");
- }
-
- PasspointConfiguration config = PpsMoParser.parseMoText(new String(profileData));
- if (config == null) {
- throw new IOException("Failed to parse Passpoint profile");
- }
-
- // Credential is needed for storing the certificates and private client key.
- if (config.getCredential() == null) {
- throw new IOException("Passpoint profile missing credential");
- }
-
- // Don't allow the installer to make changes to the update identifier. This is an
- // indicator of an R2 (or newer) network.
- if (config.getUpdateIdentifier() != Integer.MIN_VALUE) {
- config.setUpdateIdentifier(Integer.MIN_VALUE);
- }
-
- // Parse CA (Certificate Authority) certificate.
- byte[] caCertData = mimeParts.get(TYPE_CA_CERT);
- if (caCertData != null) {
- try {
- config.getCredential().setCaCertificate(parseCACert(caCertData));
- } catch (CertificateException e) {
- throw new IOException("Failed to parse CA Certificate");
- }
- }
-
- // Parse PKCS12 data for client private key and certificate chain.
- byte[] pkcs12Data = mimeParts.get(TYPE_PKCS12);
- if (pkcs12Data != null) {
- try {
- Pair<PrivateKey, List<X509Certificate>> clientKey = parsePkcs12(pkcs12Data);
- config.getCredential().setClientPrivateKey(clientKey.first);
- config.getCredential().setClientCertificateChain(
- clientKey.second.toArray(new X509Certificate[clientKey.second.size()]));
- } catch(GeneralSecurityException | IOException e) {
- throw new IOException("Failed to parse PCKS12 string");
- }
- }
- return config;
- }
-
- /**
- * Parse a MIME (Multipurpose Internet Mail Extension) multipart message from the given
- * input stream.
- *
- * @param in The input stream for reading the message data
- * @return A map of a content type and content data pair
- * @throws IOException
- */
- private static Map<String, byte[]> parseMimeMultipartMessage(LineNumberReader in)
- throws IOException {
- // Parse the outer MIME header.
- MimeHeader header = parseHeaders(in);
- if (!TextUtils.equals(header.contentType, TYPE_MULTIPART_MIXED)) {
- throw new IOException("Invalid content type: " + header.contentType);
- }
- if (TextUtils.isEmpty(header.boundary)) {
- throw new IOException("Missing boundary string");
- }
- if (!TextUtils.equals(header.encodingType, ENCODING_BASE64)) {
- throw new IOException("Unexpected encoding: " + header.encodingType);
- }
-
- // Read pass the first boundary string.
- for (;;) {
- String line = in.readLine();
- if (line == null) {
- throw new IOException("Unexpected EOF before first boundary @ " +
- in.getLineNumber());
- }
- if (line.equals("--" + header.boundary)) {
- break;
- }
- }
-
- // Parse each MIME part.
- Map<String, byte[]> mimeParts = new HashMap<>();
- boolean isLast = false;
- do {
- MimePart mimePart = parseMimePart(in, header.boundary);
- mimeParts.put(mimePart.type, mimePart.data);
- isLast = mimePart.isLast;
- } while(!isLast);
- return mimeParts;
- }
-
- /**
- * Parse a MIME (Multipurpose Internet Mail Extension) part. We expect the data to
- * be encoded in base64.
- *
- * @param in Input stream to read the data from
- * @param boundary Boundary string indicate the end of the part
- * @return {@link MimePart}
- * @throws IOException
- */
- private static MimePart parseMimePart(LineNumberReader in, String boundary)
- throws IOException {
- MimeHeader header = parseHeaders(in);
- // Expect encoding type to be base64.
- if (!TextUtils.equals(header.encodingType, ENCODING_BASE64)) {
- throw new IOException("Unexpected encoding type: " + header.encodingType);
- }
-
- // Check for a valid content type.
- if (!TextUtils.equals(header.contentType, TYPE_PASSPOINT_PROFILE) &&
- !TextUtils.equals(header.contentType, TYPE_CA_CERT) &&
- !TextUtils.equals(header.contentType, TYPE_PKCS12)) {
- throw new IOException("Unexpected content type: " + header.contentType);
- }
-
- StringBuilder text = new StringBuilder();
- boolean isLast = false;
- String partBoundary = "--" + boundary;
- String endBoundary = partBoundary + "--";
- for (;;) {
- String line = in.readLine();
- if (line == null) {
- throw new IOException("Unexpected EOF file in body @ " + in.getLineNumber());
- }
- // Check for boundary line.
- if (line.startsWith(partBoundary)) {
- if (line.equals(endBoundary)) {
- isLast = true;
- }
- break;
- }
- text.append(line);
- }
-
- MimePart part = new MimePart();
- part.type = header.contentType;
- part.data = Base64.decode(text.toString(), Base64.DEFAULT);
- part.isLast = isLast;
- return part;
- }
-
- /**
- * Parse a MIME (Multipurpose Internet Mail Extension) header from the input stream.
- * @param in Input stream to read from.
- * @return {@link MimeHeader}
- * @throws IOException
- */
- private static MimeHeader parseHeaders(LineNumberReader in)
- throws IOException {
- MimeHeader header = new MimeHeader();
-
- // Read the header from the input stream.
- Map<String, String> headers = readHeaders(in);
-
- // Parse each header.
- for (Map.Entry<String, String> entry : headers.entrySet()) {
- switch (entry.getKey()) {
- case CONTENT_TYPE:
- Pair<String, String> value = parseContentType(entry.getValue());
- header.contentType = value.first;
- header.boundary = value.second;
- break;
- case CONTENT_TRANSFER_ENCODING:
- header.encodingType = entry.getValue();
- break;
- default:
- Log.d(TAG, "Ignore header: " + entry.getKey());
- break;
- }
- }
- return header;
- }
-
- /**
- * Parse the Content-Type header value. The value will contain the content type string and
- * an optional boundary string separated by a ";". Below are examples of valid Content-Type
- * header value:
- * multipart/mixed; boundary={boundary}
- * application/x-passpoint-profile
- *
- * @param contentType The Content-Type value string
- * @return A pair of content type and boundary string
- * @throws IOException
- */
- private static Pair<String, String> parseContentType(String contentType) throws IOException {
- String[] attributes = contentType.split(";");
- String type = null;
- String boundary = null;
-
- if (attributes.length < 1) {
- throw new IOException("Invalid Content-Type: " + contentType);
- }
-
- // The type is always the first attribute.
- type = attributes[0].trim();
- // Look for boundary string from the rest of the attributes.
- for (int i = 1; i < attributes.length; i++) {
- String attribute = attributes[i].trim();
- if (!attribute.startsWith(BOUNDARY)) {
- Log.d(TAG, "Ignore Content-Type attribute: " + attributes[i]);
- continue;
- }
- boundary = attribute.substring(BOUNDARY.length());
- // Remove the leading and trailing quote if present.
- if (boundary.length() > 1 && boundary.startsWith("\"") && boundary.endsWith("\"")) {
- boundary = boundary.substring(1, boundary.length()-1);
- }
- }
-
- return new Pair<String, String>(type, boundary);
- }
-
- /**
- * Read the headers from the given input stream. The header section is terminated by
- * an empty line.
- *
- * @param in The input stream to read from
- * @return Map of key-value pairs.
- * @throws IOException
- */
- private static Map<String, String> readHeaders(LineNumberReader in)
- throws IOException {
- Map<String, String> headers = new HashMap<>();
- String line;
- String name = null;
- StringBuilder value = null;
- for (;;) {
- line = in.readLine();
- if (line == null) {
- throw new IOException("Missing line @ " + in.getLineNumber());
- }
-
- // End of headers section.
- if (line.length() == 0 || line.trim().length() == 0) {
- // Save the previous header line.
- if (name != null) {
- headers.put(name, value.toString());
- }
- break;
- }
-
- int nameEnd = line.indexOf(':');
- if (nameEnd < 0) {
- if (value != null) {
- // Continuation line for the header value.
- value.append(' ').append(line.trim());
- } else {
- throw new IOException("Bad header line: '" + line + "' @ " +
- in.getLineNumber());
- }
- } else {
- // New header line detected, make sure it doesn't start with a whitespace.
- if (Character.isWhitespace(line.charAt(0))) {
- throw new IOException("Illegal blank prefix in header line '" + line +
- "' @ " + in.getLineNumber());
- }
-
- if (name != null) {
- // Save the previous header line.
- headers.put(name, value.toString());
- }
-
- // Setup the current header line.
- name = line.substring(0, nameEnd).trim();
- value = new StringBuilder();
- value.append(line.substring(nameEnd+1).trim());
- }
- }
- return headers;
- }
-
- /**
- * Parse a CA (Certificate Authority) certificate data and convert it to a
- * X509Certificate object.
- *
- * @param octets Certificate data
- * @return X509Certificate
- * @throws CertificateException
- */
- private static X509Certificate parseCACert(byte[] octets) throws CertificateException {
- CertificateFactory factory = CertificateFactory.getInstance("X.509");
- return (X509Certificate) factory.generateCertificate(new ByteArrayInputStream(octets));
- }
-
- private static Pair<PrivateKey, List<X509Certificate>> parsePkcs12(byte[] octets)
- throws GeneralSecurityException, IOException {
- KeyStore ks = KeyStore.getInstance("PKCS12");
- ByteArrayInputStream in = new ByteArrayInputStream(octets);
- ks.load(in, new char[0]);
- in.close();
-
- // Only expects one set of key and certificate chain.
- if (ks.size() != 1) {
- throw new IOException("Unexpected key size: " + ks.size());
- }
-
- String alias = ks.aliases().nextElement();
- if (alias == null) {
- throw new IOException("No alias found");
- }
-
- PrivateKey clientKey = (PrivateKey) ks.getKey(alias, null);
- List<X509Certificate> clientCertificateChain = null;
- Certificate[] chain = ks.getCertificateChain(alias);
- if (chain != null) {
- clientCertificateChain = new ArrayList<>();
- for (Certificate certificate : chain) {
- if (!(certificate instanceof X509Certificate)) {
- throw new IOException("Unexpceted certificate type: " +
- certificate.getClass());
- }
- clientCertificateChain.add((X509Certificate) certificate);
- }
- }
- return new Pair<PrivateKey, List<X509Certificate>>(clientKey, clientCertificateChain);
- }
-}
diff --git a/wifi/java/android/net/wifi/hotspot2/IProvisioningCallback.aidl b/wifi/java/android/net/wifi/hotspot2/IProvisioningCallback.aidl
deleted file mode 100644
index a6bdd5b6bfff..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/IProvisioningCallback.aidl
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2017 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.hotspot2;
-
-/**
- * Interface for Provisioning callback.
- *
- * @hide
- */
-oneway interface IProvisioningCallback
-{
- /**
- * Service to manager callback providing failure notification
- */
- void onProvisioningFailure(int status);
-
- /**
- * Service to manager callback providing Provisioning status
- */
- void onProvisioningStatus(int status);
-
- /**
- * Service to manager callback providing completion of Provisioning/Remediation flow
- */
- void onProvisioningComplete();
-}
-
diff --git a/wifi/java/android/net/wifi/hotspot2/OsuProvider.java b/wifi/java/android/net/wifi/hotspot2/OsuProvider.java
deleted file mode 100644
index f0a06076961c..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/OsuProvider.java
+++ /dev/null
@@ -1,270 +0,0 @@
-/*
- * Copyright (C) 2017 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.hotspot2;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.Uri;
-import android.net.wifi.WifiSsid;
-import android.os.Bundle;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Objects;
-
-/**
- * Contained information for a Hotspot 2.0 OSU (Online Sign-Up provider).
- *
- * @hide
- */
-@SystemApi
-public final class OsuProvider implements Parcelable {
- /**
- * OSU (Online Sign-Up) method: OMA DM (Open Mobile Alliance Device Management).
- * For more info, refer to Section 8.3 of the Hotspot 2.0 Release 2 Technical Specification.
- * @hide
- */
- public static final int METHOD_OMA_DM = 0;
-
- /**
- * OSU (Online Sign-Up) method: SOAP XML SPP (Subscription Provisioning Protocol).
- * For more info, refer to Section 8.4 of the Hotspot 2.0 Release 2 Technical Specification.
- * @hide
- */
- public static final int METHOD_SOAP_XML_SPP = 1;
-
- /**
- * SSID of the network to connect for service sign-up.
- */
- private WifiSsid mOsuSsid;
-
- /**
- * Map of friendly names expressed as different language for the OSU provider.
- */
- private final Map<String, String> mFriendlyNames;
-
- /**
- * Description of the OSU provider.
- */
- private final String mServiceDescription;
-
- /**
- * URI to browse to for service sign-up.
- */
- private final Uri mServerUri;
-
- /**
- * Network Access Identifier used for authenticating with the OSU network when OSEN is used.
- */
- private final String mNetworkAccessIdentifier;
-
- /**
- * List of OSU (Online Sign-Up) method supported.
- */
- private final List<Integer> mMethodList;
-
- /** @hide */
- public OsuProvider(String osuSsid, Map<String, String> friendlyNames,
- String serviceDescription, Uri serverUri, String nai, List<Integer> methodList) {
- this(WifiSsid.createFromByteArray(osuSsid.getBytes(StandardCharsets.UTF_8)),
- friendlyNames, serviceDescription, serverUri, nai, methodList);
- }
-
- /** @hide */
- public OsuProvider(WifiSsid osuSsid, Map<String, String> friendlyNames,
- String serviceDescription, Uri serverUri, String nai, List<Integer> methodList) {
- mOsuSsid = osuSsid;
- mFriendlyNames = friendlyNames;
- mServiceDescription = serviceDescription;
- mServerUri = serverUri;
- mNetworkAccessIdentifier = nai;
- if (methodList == null) {
- mMethodList = new ArrayList<>();
- } else {
- mMethodList = new ArrayList<>(methodList);
- }
- }
-
- /**
- * Copy constructor.
- *
- * @param source The source to copy from
- * @hide
- */
- public OsuProvider(OsuProvider source) {
- if (source == null) {
- mOsuSsid = null;
- mFriendlyNames = null;
- mServiceDescription = null;
- mServerUri = null;
- mNetworkAccessIdentifier = null;
- mMethodList = new ArrayList<>();
- return;
- }
-
- mOsuSsid = source.mOsuSsid;
- mFriendlyNames = source.mFriendlyNames;
- mServiceDescription = source.mServiceDescription;
- mServerUri = source.mServerUri;
- mNetworkAccessIdentifier = source.mNetworkAccessIdentifier;
- if (source.mMethodList == null) {
- mMethodList = new ArrayList<>();
- } else {
- mMethodList = new ArrayList<>(source.mMethodList);
- }
- }
-
- /** @hide */
- public WifiSsid getOsuSsid() {
- return mOsuSsid;
- }
-
- /** @hide */
- public void setOsuSsid(WifiSsid osuSsid) {
- mOsuSsid = osuSsid;
- }
-
- /**
- * Return the friendly Name for current language from the list of friendly names of OSU
- * provider.
- *
- * The string matching the default locale will be returned if it is found, otherwise the string
- * in english or the first string in the list will be returned if english is not found.
- * A null will be returned if the list is empty.
- *
- * @return String matching the default locale, null otherwise
- */
- public @Nullable String getFriendlyName() {
- if (mFriendlyNames == null || mFriendlyNames.isEmpty()) return null;
- String lang = Locale.getDefault().getLanguage();
- String friendlyName = mFriendlyNames.get(lang);
- if (friendlyName != null) {
- return friendlyName;
- }
- friendlyName = mFriendlyNames.get("en");
- if (friendlyName != null) {
- return friendlyName;
- }
- return mFriendlyNames.get(mFriendlyNames.keySet().stream().findFirst().get());
- }
-
- /** @hide */
- public Map<String, String> getFriendlyNameList() {
- return mFriendlyNames;
- }
-
- /** @hide */
- public String getServiceDescription() {
- return mServiceDescription;
- }
-
- public @Nullable Uri getServerUri() {
- return mServerUri;
- }
-
- /** @hide */
- public String getNetworkAccessIdentifier() {
- return mNetworkAccessIdentifier;
- }
-
- /** @hide */
- public List<Integer> getMethodList() {
- return mMethodList;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeParcelable(mOsuSsid, flags);
- dest.writeString(mServiceDescription);
- dest.writeParcelable(mServerUri, flags);
- dest.writeString(mNetworkAccessIdentifier);
- dest.writeList(mMethodList);
- Bundle bundle = new Bundle();
- bundle.putSerializable("friendlyNameMap", (HashMap<String, String>) mFriendlyNames);
- dest.writeBundle(bundle);
- }
-
- @Override
- public boolean equals(@Nullable Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof OsuProvider)) {
- return false;
- }
- OsuProvider that = (OsuProvider) thatObject;
- return Objects.equals(mOsuSsid, that.mOsuSsid)
- && Objects.equals(mFriendlyNames, that.mFriendlyNames)
- && TextUtils.equals(mServiceDescription, that.mServiceDescription)
- && Objects.equals(mServerUri, that.mServerUri)
- && TextUtils.equals(mNetworkAccessIdentifier, that.mNetworkAccessIdentifier)
- && Objects.equals(mMethodList, that.mMethodList);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mOsuSsid, mServiceDescription, mFriendlyNames,
- mServerUri, mNetworkAccessIdentifier, mMethodList);
- }
-
- @NonNull
- @Override
- public String toString() {
- return "OsuProvider{mOsuSsid=" + mOsuSsid
- + " mFriendlyNames=" + mFriendlyNames
- + " mServiceDescription=" + mServiceDescription
- + " mServerUri=" + mServerUri
- + " mNetworkAccessIdentifier=" + mNetworkAccessIdentifier
- + " mMethodList=" + mMethodList;
- }
-
- public static final @android.annotation.NonNull Creator<OsuProvider> CREATOR =
- new Creator<OsuProvider>() {
- @Override
- public OsuProvider createFromParcel(Parcel in) {
- WifiSsid osuSsid = in.readParcelable(null);
- String serviceDescription = in.readString();
- Uri serverUri = in.readParcelable(null);
- String nai = in.readString();
- List<Integer> methodList = new ArrayList<>();
- in.readList(methodList, null);
- Bundle bundle = in.readBundle();
- Map<String, String> friendlyNamesMap = (HashMap) bundle.getSerializable(
- "friendlyNameMap");
- return new OsuProvider(osuSsid, friendlyNamesMap, serviceDescription,
- serverUri, nai, methodList);
- }
-
- @Override
- public OsuProvider[] newArray(int size) {
- return new OsuProvider[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java b/wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java
deleted file mode 100644
index 006fbaa028bd..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/PasspointConfiguration.java
+++ /dev/null
@@ -1,1075 +0,0 @@
-/**
- * Copyright (c) 2016, 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.hotspot2;
-
-import static android.net.wifi.WifiConfiguration.METERED_OVERRIDE_NONE;
-import static android.net.wifi.WifiConfiguration.MeteredOverride;
-
-import android.annotation.CurrentTimeMillisLong;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.wifi.hotspot2.pps.Credential;
-import android.net.wifi.hotspot2.pps.HomeSp;
-import android.net.wifi.hotspot2.pps.Policy;
-import android.net.wifi.hotspot2.pps.UpdateParameter;
-import android.os.Bundle;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.telephony.SubscriptionInfo;
-import android.telephony.SubscriptionManager;
-import android.telephony.TelephonyManager;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Objects;
-
-/**
- * Class representing Passpoint configuration. This contains configurations specified in
- * PerProviderSubscription (PPS) Management Object (MO) tree.
- *
- * For more info, refer to Hotspot 2.0 PPS MO defined in section 9.1 of the Hotspot 2.0
- * Release 2 Technical Specification.
- */
-public final class PasspointConfiguration implements Parcelable {
- private static final String TAG = "PasspointConfiguration";
-
- /**
- * Number of bytes for certificate SHA-256 fingerprint byte array.
- */
- private static final int CERTIFICATE_SHA256_BYTES = 32;
-
- /**
- * Maximum bytes for URL string.
- */
- private static final int MAX_URL_BYTES = 1023;
-
- /**
- * Integer value used for indicating null value in the Parcel.
- */
- private static final int NULL_VALUE = -1;
-
- /**
- * Configurations under HomeSp subtree.
- */
- private HomeSp mHomeSp = null;
-
- /**
- * Set the Home SP (Service Provider) information.
- *
- * @param homeSp The Home SP information to set to
- */
- public void setHomeSp(HomeSp homeSp) { mHomeSp = homeSp; }
- /**
- * Get the Home SP (Service Provider) information.
- *
- * @return Home SP information
- */
- public HomeSp getHomeSp() { return mHomeSp; }
-
- /**
- * Configurations under AAAServerTrustedNames subtree.
- */
- private String[] mAaaServerTrustedNames = null;
- /**
- * Set the AAA server trusted names information.
- *
- * @param aaaServerTrustedNames The AAA server trusted names information to set to
- * @hide
- */
- public void setAaaServerTrustedNames(@Nullable String[] aaaServerTrustedNames) {
- mAaaServerTrustedNames = aaaServerTrustedNames;
- }
- /**
- * Get the AAA server trusted names information.
- *
- * @return AAA server trusted names information
- * @hide
- */
- public @Nullable String[] getAaaServerTrustedNames() {
- return mAaaServerTrustedNames;
- }
-
- /**
- * Configurations under Credential subtree.
- */
- private Credential mCredential = null;
- /**
- * Set the credential information.
- *
- * @param credential The credential information to set to
- */
- public void setCredential(Credential credential) {
- mCredential = credential;
- }
- /**
- * Get the credential information.
- *
- * @return credential information
- */
- public Credential getCredential() {
- return mCredential;
- }
-
- /**
- * Configurations under Policy subtree.
- */
- private Policy mPolicy = null;
- /**
- * @hide
- */
- public void setPolicy(Policy policy) {
- mPolicy = policy;
- }
- /**
- * @hide
- */
- public Policy getPolicy() {
- return mPolicy;
- }
-
- /**
- * Meta data for performing subscription update.
- */
- private UpdateParameter mSubscriptionUpdate = null;
- /**
- * @hide
- */
- public void setSubscriptionUpdate(UpdateParameter subscriptionUpdate) {
- mSubscriptionUpdate = subscriptionUpdate;
- }
- /**
- * @hide
- */
- public UpdateParameter getSubscriptionUpdate() {
- return mSubscriptionUpdate;
- }
-
- /**
- * List of HTTPS URL for retrieving trust root certificate and the corresponding SHA-256
- * fingerprint of the certificate. The certificates are used for verifying AAA server's
- * identity during EAP authentication.
- */
- private Map<String, byte[]> mTrustRootCertList = null;
- /**
- * @hide
- */
- public void setTrustRootCertList(Map<String, byte[]> trustRootCertList) {
- mTrustRootCertList = trustRootCertList;
- }
- /**
- * @hide
- */
- public Map<String, byte[]> getTrustRootCertList() {
- return mTrustRootCertList;
- }
-
- /**
- * Set by the subscription server, updated every time the configuration is updated by
- * the subscription server.
- *
- * Use Integer.MIN_VALUE to indicate unset value.
- */
- private int mUpdateIdentifier = Integer.MIN_VALUE;
- /**
- * @hide
- */
- public void setUpdateIdentifier(int updateIdentifier) {
- mUpdateIdentifier = updateIdentifier;
- }
- /**
- * @hide
- */
- public int getUpdateIdentifier() {
- return mUpdateIdentifier;
- }
-
- /**
- * The priority of the credential.
- *
- * Use Integer.MIN_VALUE to indicate unset value.
- */
- private int mCredentialPriority = Integer.MIN_VALUE;
- /**
- * @hide
- */
- public void setCredentialPriority(int credentialPriority) {
- mCredentialPriority = credentialPriority;
- }
- /**
- * @hide
- */
- public int getCredentialPriority() {
- return mCredentialPriority;
- }
-
- /**
- * The time this subscription is created. It is in the format of number
- * of milliseconds since January 1, 1970, 00:00:00 GMT.
- *
- * Use Long.MIN_VALUE to indicate unset value.
- */
- private long mSubscriptionCreationTimeInMillis = Long.MIN_VALUE;
- /**
- * @hide
- */
- public void setSubscriptionCreationTimeInMillis(long subscriptionCreationTimeInMillis) {
- mSubscriptionCreationTimeInMillis = subscriptionCreationTimeInMillis;
- }
- /**
- * @hide
- */
- public long getSubscriptionCreationTimeInMillis() {
- return mSubscriptionCreationTimeInMillis;
- }
-
- /**
- * The time this subscription will expire. It is in the format of number
- * of milliseconds since January 1, 1970, 00:00:00 GMT.
- *
- * Use Long.MIN_VALUE to indicate unset value.
- */
- private long mSubscriptionExpirationTimeMillis = Long.MIN_VALUE;
- /**
- * @hide
- */
- public void setSubscriptionExpirationTimeInMillis(long subscriptionExpirationTimeInMillis) {
- mSubscriptionExpirationTimeMillis = subscriptionExpirationTimeInMillis;
- }
- /**
- * Utility method to get the time this subscription will expire. It is in the format of number
- * of milliseconds since January 1, 1970, 00:00:00 GMT.
- *
- * @return The time this subscription will expire, or Long.MIN_VALUE to indicate unset value
- */
- @CurrentTimeMillisLong
- public long getSubscriptionExpirationTimeMillis() {
- return mSubscriptionExpirationTimeMillis;
- }
-
- /**
- * The type of the subscription. This is defined by the provider and the value is provider
- * specific.
- */
- private String mSubscriptionType = null;
- /**
- * @hide
- */
- public void setSubscriptionType(String subscriptionType) {
- mSubscriptionType = subscriptionType;
- }
- /**
- * @hide
- */
- public String getSubscriptionType() {
- return mSubscriptionType;
- }
-
- /**
- * The time period for usage statistics accumulation. A value of zero means that usage
- * statistics are not accumulated on a periodic basis (e.g., a one-time limit for
- * “pay as you go” - PAYG service). A non-zero value specifies the usage interval in minutes.
- */
- private long mUsageLimitUsageTimePeriodInMinutes = Long.MIN_VALUE;
- /**
- * @hide
- */
- public void setUsageLimitUsageTimePeriodInMinutes(long usageLimitUsageTimePeriodInMinutes) {
- mUsageLimitUsageTimePeriodInMinutes = usageLimitUsageTimePeriodInMinutes;
- }
- /**
- * @hide
- */
- public long getUsageLimitUsageTimePeriodInMinutes() {
- return mUsageLimitUsageTimePeriodInMinutes;
- }
-
- /**
- * The time at which usage statistic accumulation begins. It is in the format of number
- * of milliseconds since January 1, 1970, 00:00:00 GMT.
- *
- * Use Long.MIN_VALUE to indicate unset value.
- */
- private long mUsageLimitStartTimeInMillis = Long.MIN_VALUE;
- /**
- * @hide
- */
- public void setUsageLimitStartTimeInMillis(long usageLimitStartTimeInMillis) {
- mUsageLimitStartTimeInMillis = usageLimitStartTimeInMillis;
- }
- /**
- * @hide
- */
- public long getUsageLimitStartTimeInMillis() {
- return mUsageLimitStartTimeInMillis;
- }
-
- /**
- * The cumulative data limit in megabytes for the {@link #usageLimitUsageTimePeriodInMinutes}.
- * A value of zero indicate unlimited data usage.
- *
- * Use Long.MIN_VALUE to indicate unset value.
- */
- private long mUsageLimitDataLimit = Long.MIN_VALUE;
- /**
- * @hide
- */
- public void setUsageLimitDataLimit(long usageLimitDataLimit) {
- mUsageLimitDataLimit = usageLimitDataLimit;
- }
- /**
- * @hide
- */
- public long getUsageLimitDataLimit() {
- return mUsageLimitDataLimit;
- }
-
- /**
- * The cumulative time limit in minutes for the {@link #usageLimitUsageTimePeriodInMinutes}.
- * A value of zero indicate unlimited time usage.
- */
- private long mUsageLimitTimeLimitInMinutes = Long.MIN_VALUE;
- /**
- * @hide
- */
- public void setUsageLimitTimeLimitInMinutes(long usageLimitTimeLimitInMinutes) {
- mUsageLimitTimeLimitInMinutes = usageLimitTimeLimitInMinutes;
- }
- /**
- * @hide
- */
- public long getUsageLimitTimeLimitInMinutes() {
- return mUsageLimitTimeLimitInMinutes;
- }
-
- /**
- * The map of OSU service provider names whose each element is presented in different
- * languages for the service provider, which is used for finding a matching
- * PasspointConfiguration with a given service provider name.
- */
- private Map<String, String> mServiceFriendlyNames = null;
-
- /**
- * @hide
- */
- public void setServiceFriendlyNames(Map<String, String> serviceFriendlyNames) {
- mServiceFriendlyNames = serviceFriendlyNames;
- }
-
- /**
- * @hide
- */
- public Map<String, String> getServiceFriendlyNames() {
- return mServiceFriendlyNames;
- }
-
- /**
- * Return the friendly Name for current language from the list of friendly names of OSU
- * provider.
- * The string matching the default locale will be returned if it is found, otherwise the
- * first string in the list will be returned. A null will be returned if the list is empty.
- *
- * @return String matching the default locale, null otherwise
- * @hide
- */
- public String getServiceFriendlyName() {
- if (mServiceFriendlyNames == null || mServiceFriendlyNames.isEmpty()) return null;
- String lang = Locale.getDefault().getLanguage();
- String friendlyName = mServiceFriendlyNames.get(lang);
- if (friendlyName != null) {
- return friendlyName;
- }
- friendlyName = mServiceFriendlyNames.get("en");
- if (friendlyName != null) {
- return friendlyName;
- }
- return mServiceFriendlyNames.get(mServiceFriendlyNames.keySet().stream().findFirst().get());
- }
-
- /**
- * The carrier ID identifies the operator who provides this network configuration.
- * see {@link TelephonyManager#getSimCarrierId()}
- */
- private int mCarrierId = TelephonyManager.UNKNOWN_CARRIER_ID;
-
- /**
- * The subscription ID identifies the SIM card who provides this network configuration.
- * See {@link SubscriptionInfo#getSubscriptionId()}
- */
- private int mSubscriptionId = SubscriptionManager.INVALID_SUBSCRIPTION_ID;
-
- /**
- * Set the carrier ID associated with current configuration.
- * @param carrierId {@code mCarrierId}
- * @hide
- */
- public void setCarrierId(int carrierId) {
- this.mCarrierId = carrierId;
- }
-
- /**
- * Get the carrier ID associated with current configuration.
- * @return {@code mCarrierId}
- * @hide
- */
- public int getCarrierId() {
- return mCarrierId;
- }
-
- /**
- * Set the subscription ID associated with current configuration.
- * @param subscriptionId {@code mSubscriptionId}
- * @hide
- */
- public void setSubscriptionId(int subscriptionId) {
- this.mSubscriptionId = subscriptionId;
- }
-
- /**
- * Get the carrier ID associated with current configuration.
- * @return {@code mSubscriptionId}
- * @hide
- */
- public int getSubscriptionId() {
- return mSubscriptionId;
- }
-
- /**
- * The auto-join configuration specifies whether or not the Passpoint Configuration is
- * considered for auto-connection. If true then yes, if false then it isn't considered as part
- * of auto-connection - but can still be manually connected to.
- */
- private boolean mIsAutojoinEnabled = true;
-
- /**
- * The mac randomization setting specifies whether a randomized or device MAC address will
- * be used to connect to the passpoint network. If true, a randomized MAC will be used.
- * Otherwise, the device MAC address will be used.
- */
- private boolean mIsMacRandomizationEnabled = true;
-
- /**
- * Whether this passpoint configuration should use enhanced MAC randomization.
- */
- private boolean mIsEnhancedMacRandomizationEnabled = false;
-
-
- /**
- * Indicate whether the network is oem paid or not. Networks are considered oem paid
- * if the corresponding connection is only available to system apps.
- * @hide
- */
- private boolean mIsOemPaid;
-
- /**
- * Indicate whether the network is oem private or not. Networks are considered oem private
- * if the corresponding connection is only available to system apps.
- * @hide
- */
- private boolean mIsOemPrivate;
-
- /**
- * Indicate whether or not the network is a carrier merged network.
- * @hide
- */
- private boolean mIsCarrierMerged;
-
- /**
- * Indicates if the end user has expressed an explicit opinion about the
- * meteredness of this network, such as through the Settings app.
- * This value is one of {@link #METERED_OVERRIDE_NONE}, {@link #METERED_OVERRIDE_METERED},
- * or {@link #METERED_OVERRIDE_NOT_METERED}.
- * <p>
- * This should always override any values from {@link WifiInfo#getMeteredHint()}.
- *
- * By default this field is set to {@link #METERED_OVERRIDE_NONE}.
- */
- private int mMeteredOverride = METERED_OVERRIDE_NONE;
-
- /**
- * Configures the auto-association status of this Passpoint configuration. A value of true
- * indicates that the configuration will be considered for auto-connection, a value of false
- * indicates that only manual connection will work - the framework will not auto-associate to
- * this Passpoint network.
- *
- * @param autojoinEnabled true to be considered for framework auto-connection, false otherwise.
- * @hide
- */
- public void setAutojoinEnabled(boolean autojoinEnabled) {
- mIsAutojoinEnabled = autojoinEnabled;
- }
-
- /**
- * Configures the MAC randomization setting for this Passpoint configuration.
- * If set to true, the framework will use a randomized MAC address to connect to this Passpoint
- * network. Otherwise, the framework will use the device MAC address.
- *
- * @param enabled true to use randomized MAC address, false to use device MAC address.
- * @hide
- */
- public void setMacRandomizationEnabled(boolean enabled) {
- mIsMacRandomizationEnabled = enabled;
- }
-
- /**
- * This setting is only applicable if MAC randomization is enabled.
- * If set to true, the framework will periodically generate new MAC addresses for new
- * connections.
- * If set to false (the default), the framework will use the same locally generated MAC address
- * for connections to this passpoint configuration.
- * @param enabled true to use enhanced MAC randomization, false to use persistent MAC
- * randomization.
- * @hide
- */
- public void setEnhancedMacRandomizationEnabled(boolean enabled) {
- mIsEnhancedMacRandomizationEnabled = enabled;
- }
-
- /**
- * Sets the metered override setting for this Passpoint configuration.
- *
- * @param meteredOverride One of the values in {@link MeteredOverride}
- * @hide
- */
- public void setMeteredOverride(@MeteredOverride int meteredOverride) {
- mMeteredOverride = meteredOverride;
- }
-
- /**
- * Indicates whether the Passpoint configuration may be auto-connected to by the framework. A
- * value of true indicates that auto-connection can happen, a value of false indicates that it
- * cannot. However, even when auto-connection is not possible manual connection by the user is
- * possible.
- *
- * @return the auto-join configuration: true for auto-connection (or join) enabled, false
- * otherwise.
- * @hide
- */
- @SystemApi
- public boolean isAutojoinEnabled() {
- return mIsAutojoinEnabled;
- }
-
- /**
- * Indicates whether the user chose this configuration to be treated as metered or not.
- *
- * @return One of the values in {@link MeteredOverride}
- * @hide
- */
- @SystemApi
- @MeteredOverride
- public int getMeteredOverride() {
- return mMeteredOverride;
- }
-
- /**
- * Indicates whether a randomized MAC address or device MAC address will be used for
- * connections to this Passpoint network. If true, a randomized MAC address will be used.
- * Otherwise, the device MAC address will be used.
- *
- * @return true for MAC randomization enabled. False for disabled.
- * @hide
- */
- @SystemApi
- public boolean isMacRandomizationEnabled() {
- return mIsMacRandomizationEnabled;
- }
-
- /**
- * When MAC randomization is enabled, this indicates whether enhanced MAC randomization or
- * persistent MAC randomization will be used for connections to this Passpoint network.
- * If true, the MAC address used for connections will periodically change. Otherwise, the same
- * locally generated MAC will be used for all connections to this passpoint configuration.
- *
- * @return true for enhanced MAC randomization enabled. False for disabled.
- * @hide
- */
- public boolean isEnhancedMacRandomizationEnabled() {
- return mIsEnhancedMacRandomizationEnabled;
- }
-
- /**
- * Set whether the network is oem paid or not.
- * @hide
- */
- public void setOemPaid(boolean isOemPaid) {
- mIsOemPaid = isOemPaid;
- }
-
- /**
- * Get whether the network is oem paid or not.
- * @hide
- */
- public boolean isOemPaid() {
- return mIsOemPaid;
- }
-
- /**
- * Set whether the network is oem private or not.
- * @hide
- */
- public void setOemPrivate(boolean isOemPrivate) {
- mIsOemPrivate = isOemPrivate;
- }
-
- /**
- * Get whether the network is oem private or not.
- * @hide
- */
- public boolean isOemPrivate() {
- return mIsOemPrivate;
- }
-
- /**
- * Set whether the network is carrier merged or not.
- * @hide
- */
- public void setCarrierMerged(boolean isCarrierMerged) {
- mIsCarrierMerged = isCarrierMerged;
- }
-
- /**
- * Get whether the network is carrier merged or not.
- * @hide
- */
- public boolean isCarrierMerged() {
- return mIsCarrierMerged;
- }
-
- /**
- * Constructor for creating PasspointConfiguration with default values.
- */
- public PasspointConfiguration() {}
-
- /**
- * Copy constructor.
- *
- * @param source The source to copy from
- */
- public PasspointConfiguration(PasspointConfiguration source) {
- if (source == null) {
- return;
- }
-
- if (source.mHomeSp != null) {
- mHomeSp = new HomeSp(source.mHomeSp);
- }
- if (source.mCredential != null) {
- mCredential = new Credential(source.mCredential);
- }
- if (source.mPolicy != null) {
- mPolicy = new Policy(source.mPolicy);
- }
- if (source.mTrustRootCertList != null) {
- mTrustRootCertList = Collections.unmodifiableMap(source.mTrustRootCertList);
- }
- if (source.mSubscriptionUpdate != null) {
- mSubscriptionUpdate = new UpdateParameter(source.mSubscriptionUpdate);
- }
- mUpdateIdentifier = source.mUpdateIdentifier;
- mCredentialPriority = source.mCredentialPriority;
- mSubscriptionCreationTimeInMillis = source.mSubscriptionCreationTimeInMillis;
- mSubscriptionExpirationTimeMillis = source.mSubscriptionExpirationTimeMillis;
- mSubscriptionType = source.mSubscriptionType;
- mUsageLimitDataLimit = source.mUsageLimitDataLimit;
- mUsageLimitStartTimeInMillis = source.mUsageLimitStartTimeInMillis;
- mUsageLimitTimeLimitInMinutes = source.mUsageLimitTimeLimitInMinutes;
- mUsageLimitUsageTimePeriodInMinutes = source.mUsageLimitUsageTimePeriodInMinutes;
- mServiceFriendlyNames = source.mServiceFriendlyNames;
- mAaaServerTrustedNames = source.mAaaServerTrustedNames;
- mCarrierId = source.mCarrierId;
- mSubscriptionId = source.mSubscriptionId;
- mIsAutojoinEnabled = source.mIsAutojoinEnabled;
- mIsMacRandomizationEnabled = source.mIsMacRandomizationEnabled;
- mIsEnhancedMacRandomizationEnabled = source.mIsEnhancedMacRandomizationEnabled;
- mMeteredOverride = source.mMeteredOverride;
- mIsCarrierMerged = source.mIsCarrierMerged;
- mIsOemPaid = source.mIsOemPaid;
- mIsOemPrivate = source.mIsOemPrivate;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeParcelable(mHomeSp, flags);
- dest.writeParcelable(mCredential, flags);
- dest.writeParcelable(mPolicy, flags);
- dest.writeParcelable(mSubscriptionUpdate, flags);
- writeTrustRootCerts(dest, mTrustRootCertList);
- dest.writeInt(mUpdateIdentifier);
- dest.writeInt(mCredentialPriority);
- dest.writeLong(mSubscriptionCreationTimeInMillis);
- dest.writeLong(mSubscriptionExpirationTimeMillis);
- dest.writeString(mSubscriptionType);
- dest.writeLong(mUsageLimitUsageTimePeriodInMinutes);
- dest.writeLong(mUsageLimitStartTimeInMillis);
- dest.writeLong(mUsageLimitDataLimit);
- dest.writeLong(mUsageLimitTimeLimitInMinutes);
- dest.writeStringArray(mAaaServerTrustedNames);
- Bundle bundle = new Bundle();
- bundle.putSerializable("serviceFriendlyNames",
- (HashMap<String, String>) mServiceFriendlyNames);
- dest.writeBundle(bundle);
- dest.writeInt(mCarrierId);
- dest.writeBoolean(mIsAutojoinEnabled);
- dest.writeBoolean(mIsMacRandomizationEnabled);
- dest.writeBoolean(mIsEnhancedMacRandomizationEnabled);
- dest.writeInt(mMeteredOverride);
- dest.writeInt(mSubscriptionId);
- dest.writeBoolean(mIsCarrierMerged);
- dest.writeBoolean(mIsOemPaid);
- dest.writeBoolean(mIsOemPrivate);
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof PasspointConfiguration)) {
- return false;
- }
- PasspointConfiguration that = (PasspointConfiguration) thatObject;
- return (mHomeSp == null ? that.mHomeSp == null : mHomeSp.equals(that.mHomeSp))
- && (mAaaServerTrustedNames == null ? that.mAaaServerTrustedNames == null
- : Arrays.equals(mAaaServerTrustedNames, that.mAaaServerTrustedNames))
- && (mCredential == null ? that.mCredential == null
- : mCredential.equals(that.mCredential))
- && (mPolicy == null ? that.mPolicy == null : mPolicy.equals(that.mPolicy))
- && (mSubscriptionUpdate == null ? that.mSubscriptionUpdate == null
- : mSubscriptionUpdate.equals(that.mSubscriptionUpdate))
- && isTrustRootCertListEquals(mTrustRootCertList, that.mTrustRootCertList)
- && mUpdateIdentifier == that.mUpdateIdentifier
- && mCredentialPriority == that.mCredentialPriority
- && mSubscriptionCreationTimeInMillis == that.mSubscriptionCreationTimeInMillis
- && mSubscriptionExpirationTimeMillis == that.mSubscriptionExpirationTimeMillis
- && TextUtils.equals(mSubscriptionType, that.mSubscriptionType)
- && mUsageLimitUsageTimePeriodInMinutes == that.mUsageLimitUsageTimePeriodInMinutes
- && mUsageLimitStartTimeInMillis == that.mUsageLimitStartTimeInMillis
- && mUsageLimitDataLimit == that.mUsageLimitDataLimit
- && mUsageLimitTimeLimitInMinutes == that.mUsageLimitTimeLimitInMinutes
- && mCarrierId == that.mCarrierId
- && mSubscriptionId == that.mSubscriptionId
- && mIsOemPrivate == that.mIsOemPrivate
- && mIsOemPaid == that.mIsOemPaid
- && mIsCarrierMerged == that.mIsCarrierMerged
- && mIsAutojoinEnabled == that.mIsAutojoinEnabled
- && mIsMacRandomizationEnabled == that.mIsMacRandomizationEnabled
- && mIsEnhancedMacRandomizationEnabled == that.mIsEnhancedMacRandomizationEnabled
- && mMeteredOverride == that.mMeteredOverride
- && (mServiceFriendlyNames == null ? that.mServiceFriendlyNames == null
- : mServiceFriendlyNames.equals(that.mServiceFriendlyNames));
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mHomeSp, mCredential, mPolicy, mSubscriptionUpdate, mTrustRootCertList,
- mUpdateIdentifier, mCredentialPriority, mSubscriptionCreationTimeInMillis,
- mSubscriptionExpirationTimeMillis, mUsageLimitUsageTimePeriodInMinutes,
- mUsageLimitStartTimeInMillis, mUsageLimitDataLimit, mUsageLimitTimeLimitInMinutes,
- mServiceFriendlyNames, mCarrierId, mIsAutojoinEnabled, mIsMacRandomizationEnabled,
- mIsEnhancedMacRandomizationEnabled, mMeteredOverride, mSubscriptionId,
- mIsCarrierMerged, mIsOemPaid, mIsOemPrivate);
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("UpdateIdentifier: ").append(mUpdateIdentifier).append("\n");
- builder.append("CredentialPriority: ").append(mCredentialPriority).append("\n");
- builder.append("SubscriptionCreationTime: ").append(
- mSubscriptionCreationTimeInMillis != Long.MIN_VALUE
- ? new Date(mSubscriptionCreationTimeInMillis) : "Not specified").append("\n");
- builder.append("SubscriptionExpirationTime: ").append(
- mSubscriptionExpirationTimeMillis != Long.MIN_VALUE
- ? new Date(mSubscriptionExpirationTimeMillis) : "Not specified").append("\n");
- builder.append("UsageLimitStartTime: ").append(mUsageLimitStartTimeInMillis != Long.MIN_VALUE
- ? new Date(mUsageLimitStartTimeInMillis) : "Not specified").append("\n");
- builder.append("UsageTimePeriod: ").append(mUsageLimitUsageTimePeriodInMinutes)
- .append("\n");
- builder.append("UsageLimitDataLimit: ").append(mUsageLimitDataLimit).append("\n");
- builder.append("UsageLimitTimeLimit: ").append(mUsageLimitTimeLimitInMinutes).append("\n");
- builder.append("Provisioned by a subscription server: ")
- .append(isOsuProvisioned() ? "Yes" : "No").append("\n");
- if (mHomeSp != null) {
- builder.append("HomeSP Begin ---\n");
- builder.append(mHomeSp);
- builder.append("HomeSP End ---\n");
- }
- if (mCredential != null) {
- builder.append("Credential Begin ---\n");
- builder.append(mCredential);
- builder.append("Credential End ---\n");
- }
- if (mPolicy != null) {
- builder.append("Policy Begin ---\n");
- builder.append(mPolicy);
- builder.append("Policy End ---\n");
- }
- if (mSubscriptionUpdate != null) {
- builder.append("SubscriptionUpdate Begin ---\n");
- builder.append(mSubscriptionUpdate);
- builder.append("SubscriptionUpdate End ---\n");
- }
- if (mTrustRootCertList != null) {
- builder.append("TrustRootCertServers: ").append(mTrustRootCertList.keySet())
- .append("\n");
- }
- if (mAaaServerTrustedNames != null) {
- builder.append("AAAServerTrustedNames: ")
- .append(String.join(";", mAaaServerTrustedNames)).append("\n");
- }
- if (mServiceFriendlyNames != null) {
- builder.append("ServiceFriendlyNames: ").append(mServiceFriendlyNames);
- }
- builder.append("CarrierId:" + mCarrierId);
- builder.append("SubscriptionId:" + mSubscriptionId);
- builder.append("IsAutojoinEnabled:" + mIsAutojoinEnabled);
- builder.append("mIsMacRandomizationEnabled:" + mIsMacRandomizationEnabled);
- builder.append("mIsEnhancedMacRandomizationEnabled:" + mIsEnhancedMacRandomizationEnabled);
- builder.append("mMeteredOverride:" + mMeteredOverride);
- builder.append("mIsCarrierMerged:" + mIsCarrierMerged);
- builder.append("mIsOemPaid:" + mIsOemPaid);
- builder.append("mIsOemPrivate" + mIsOemPrivate);
- return builder.toString();
- }
-
- /**
- * Validate the R1 configuration data.
- *
- * @return true on success or false on failure
- * @hide
- */
- public boolean validate() {
- // Optional: PerProviderSubscription/<X+>/SubscriptionUpdate
- if (mSubscriptionUpdate != null && !mSubscriptionUpdate.validate()) {
- return false;
- }
- return validateForCommonR1andR2();
- }
-
- /**
- * Validate the R2 configuration data.
- *
- * @return true on success or false on failure
- * @hide
- */
- public boolean validateForR2() {
- // Required: PerProviderSubscription/UpdateIdentifier
- if (mUpdateIdentifier == Integer.MIN_VALUE) {
- return false;
- }
-
- // Required: PerProviderSubscription/<X+>/SubscriptionUpdate
- if (mSubscriptionUpdate == null || !mSubscriptionUpdate.validate()) {
- return false;
- }
- return validateForCommonR1andR2();
- }
-
- private boolean validateForCommonR1andR2() {
- // Required: PerProviderSubscription/<X+>/HomeSP
- if (mHomeSp == null || !mHomeSp.validate()) {
- return false;
- }
-
- // Required: PerProviderSubscription/<X+>/Credential
- if (mCredential == null || !mCredential.validate()) {
- return false;
- }
-
- // Optional: PerProviderSubscription/<X+>/Policy
- if (mPolicy != null && !mPolicy.validate()) {
- return false;
- }
-
- if (mTrustRootCertList != null) {
- for (Map.Entry<String, byte[]> entry : mTrustRootCertList.entrySet()) {
- String url = entry.getKey();
- byte[] certFingerprint = entry.getValue();
- if (TextUtils.isEmpty(url)) {
- Log.d(TAG, "Empty URL");
- return false;
- }
- if (url.getBytes(StandardCharsets.UTF_8).length > MAX_URL_BYTES) {
- Log.d(TAG, "URL bytes exceeded the max: "
- + url.getBytes(StandardCharsets.UTF_8).length);
- return false;
- }
-
- if (certFingerprint == null) {
- Log.d(TAG, "Fingerprint not specified");
- return false;
- }
- if (certFingerprint.length != CERTIFICATE_SHA256_BYTES) {
- Log.d(TAG, "Incorrect size of trust root certificate SHA-256 fingerprint: "
- + certFingerprint.length);
- return false;
- }
- }
- }
- return true;
- }
-
- public static final @android.annotation.NonNull Creator<PasspointConfiguration> CREATOR =
- new Creator<PasspointConfiguration>() {
- @Override
- public PasspointConfiguration createFromParcel(Parcel in) {
- PasspointConfiguration config = new PasspointConfiguration();
- config.setHomeSp(in.readParcelable(null));
- config.setCredential(in.readParcelable(null));
- config.setPolicy(in.readParcelable(null));
- config.setSubscriptionUpdate(in.readParcelable(null));
- config.setTrustRootCertList(readTrustRootCerts(in));
- config.setUpdateIdentifier(in.readInt());
- config.setCredentialPriority(in.readInt());
- config.setSubscriptionCreationTimeInMillis(in.readLong());
- config.setSubscriptionExpirationTimeInMillis(in.readLong());
- config.setSubscriptionType(in.readString());
- config.setUsageLimitUsageTimePeriodInMinutes(in.readLong());
- config.setUsageLimitStartTimeInMillis(in.readLong());
- config.setUsageLimitDataLimit(in.readLong());
- config.setUsageLimitTimeLimitInMinutes(in.readLong());
- config.setAaaServerTrustedNames(in.createStringArray());
- Bundle bundle = in.readBundle();
- Map<String, String> friendlyNamesMap = (HashMap) bundle.getSerializable(
- "serviceFriendlyNames");
- config.setServiceFriendlyNames(friendlyNamesMap);
- config.mCarrierId = in.readInt();
- config.mIsAutojoinEnabled = in.readBoolean();
- config.mIsMacRandomizationEnabled = in.readBoolean();
- config.mIsEnhancedMacRandomizationEnabled = in.readBoolean();
- config.mMeteredOverride = in.readInt();
- config.mSubscriptionId = in.readInt();
- config.mIsCarrierMerged = in.readBoolean();
- config.mIsOemPaid = in.readBoolean();
- config.mIsOemPrivate = in.readBoolean();
-
- return config;
- }
-
- @Override
- public PasspointConfiguration[] newArray(int size) {
- return new PasspointConfiguration[size];
- }
-
- /**
- * Helper function for reading trust root certificate info list from a Parcel.
- *
- * @param in The Parcel to read from
- * @return The list of trust root certificate URL with the corresponding certificate
- * fingerprint
- */
- private Map<String, byte[]> readTrustRootCerts(Parcel in) {
- int size = in.readInt();
- if (size == NULL_VALUE) {
- return null;
- }
- Map<String, byte[]> trustRootCerts = new HashMap<>(size);
- for (int i = 0; i < size; i++) {
- String key = in.readString();
- byte[] value = in.createByteArray();
- trustRootCerts.put(key, value);
- }
- return trustRootCerts;
- }
- };
-
- /**
- * Helper function for writing trust root certificate information list.
- *
- * @param dest The Parcel to write to
- * @param trustRootCerts The list of trust root certificate URL with the corresponding
- * certificate fingerprint
- */
- private static void writeTrustRootCerts(Parcel dest, Map<String, byte[]> trustRootCerts) {
- if (trustRootCerts == null) {
- dest.writeInt(NULL_VALUE);
- return;
- }
- dest.writeInt(trustRootCerts.size());
- for (Map.Entry<String, byte[]> entry : trustRootCerts.entrySet()) {
- dest.writeString(entry.getKey());
- dest.writeByteArray(entry.getValue());
- }
- }
-
- /**
- * Helper function for comparing two trust root certificate list. Cannot use Map#equals
- * method since the value type (byte[]) doesn't override equals method.
- *
- * @param list1 The first trust root certificate list
- * @param list2 The second trust root certificate list
- * @return true if the two list are equal
- */
- private static boolean isTrustRootCertListEquals(Map<String, byte[]> list1,
- Map<String, byte[]> list2) {
- if (list1 == null || list2 == null) {
- return list1 == list2;
- }
- if (list1.size() != list2.size()) {
- return false;
- }
- for (Map.Entry<String, byte[]> entry : list1.entrySet()) {
- if (!Arrays.equals(entry.getValue(), list2.get(entry.getKey()))) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Indicates if the Passpoint Configuration was provisioned by a subscription (OSU) server,
- * which means that it's an R2 (or R3) profile.
- *
- * @return true if the Passpoint Configuration was provisioned by a subscription server.
- */
- public boolean isOsuProvisioned() {
- return getUpdateIdentifier() != Integer.MIN_VALUE;
- }
-
- /**
- * Get a unique identifier for a PasspointConfiguration object. The identifier depends on the
- * configuration that identify the service provider under the HomeSp subtree, and on the
- * credential configuration under the Credential subtree.
- * The method throws an {@link IllegalStateException} if the configuration under HomeSp subtree
- * or the configuration under Credential subtree are not initialized.
- *
- * @return A unique identifier
- */
- public @NonNull String getUniqueId() {
- if (mCredential == null || mHomeSp == null || TextUtils.isEmpty(mHomeSp.getFqdn())) {
- throw new IllegalStateException("Credential or HomeSP are not initialized");
- }
-
- StringBuilder sb = new StringBuilder();
- sb.append(String.format("%s_%x%x", mHomeSp.getFqdn(), mHomeSp.getUniqueId(),
- mCredential.getUniqueId()));
- return sb.toString();
- }
-}
diff --git a/wifi/java/android/net/wifi/hotspot2/ProvisioningCallback.java b/wifi/java/android/net/wifi/hotspot2/ProvisioningCallback.java
deleted file mode 100644
index 1d499b6654d0..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/ProvisioningCallback.java
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * Copyright (C) 2017 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.hotspot2;
-
-import android.annotation.SystemApi;
-import android.net.wifi.WifiManager;
-import android.os.Handler;
-
-/**
- * Base class for provisioning callbacks. Should be extended by applications and set when calling
- * {@link WifiManager#startSubscriptionProvisioning(OsuProvider, ProvisioningCallback, Handler)}.
- *
- * @hide
- */
-@SystemApi
-public abstract class ProvisioningCallback {
-
- /**
- * The reason code for Provisioning Failure due to connection failure to OSU AP.
- */
- public static final int OSU_FAILURE_AP_CONNECTION = 1;
-
- /**
- * The reason code for invalid server URL address.
- */
- public static final int OSU_FAILURE_SERVER_URL_INVALID = 2;
-
- /**
- * The reason code for provisioning failure due to connection failure to the server.
- */
- public static final int OSU_FAILURE_SERVER_CONNECTION = 3;
-
- /**
- * The reason code for provisioning failure due to invalid server certificate.
- */
- public static final int OSU_FAILURE_SERVER_VALIDATION = 4;
-
- /**
- * The reason code for provisioning failure due to invalid service provider.
- */
- public static final int OSU_FAILURE_SERVICE_PROVIDER_VERIFICATION = 5;
-
- /**
- * The reason code for provisioning failure when a provisioning flow is aborted.
- */
- public static final int OSU_FAILURE_PROVISIONING_ABORTED = 6;
-
- /**
- * The reason code for provisioning failure when a provisioning flow is not possible.
- */
- public static final int OSU_FAILURE_PROVISIONING_NOT_AVAILABLE = 7;
-
- /**
- * The reason code for provisioning failure due to invalid web url format for an OSU web page.
- */
- public static final int OSU_FAILURE_INVALID_URL_FORMAT_FOR_OSU = 8;
-
- /**
- * The reason code for provisioning failure when a command received is not the expected command
- * type.
- */
- public static final int OSU_FAILURE_UNEXPECTED_COMMAND_TYPE = 9;
-
- /**
- * The reason code for provisioning failure when a SOAP message is not the expected message
- * type.
- */
- public static final int OSU_FAILURE_UNEXPECTED_SOAP_MESSAGE_TYPE = 10;
-
- /**
- * The reason code for provisioning failure when a SOAP message exchange fails.
- */
- public static final int OSU_FAILURE_SOAP_MESSAGE_EXCHANGE = 11;
-
- /**
- * The reason code for provisioning failure when a redirect listener fails to start.
- */
- public static final int OSU_FAILURE_START_REDIRECT_LISTENER = 12;
-
- /**
- * The reason code for provisioning failure when a redirect listener timed out to receive a HTTP
- * redirect response.
- */
- public static final int OSU_FAILURE_TIMED_OUT_REDIRECT_LISTENER = 13;
-
- /**
- * The reason code for provisioning failure when there is no OSU activity to listen to
- * {@link WifiManager#ACTION_PASSPOINT_LAUNCH_OSU_VIEW} intent.
- */
- public static final int OSU_FAILURE_NO_OSU_ACTIVITY_FOUND = 14;
-
- /**
- * The reason code for provisioning failure when the status of a SOAP message is not the
- * expected message status.
- */
- public static final int OSU_FAILURE_UNEXPECTED_SOAP_MESSAGE_STATUS = 15;
-
- /**
- * The reason code for provisioning failure when there is no PPS MO.
- * MO.
- */
- public static final int OSU_FAILURE_NO_PPS_MO = 16;
-
- /**
- * The reason code for provisioning failure when there is no AAAServerTrustRoot node in a PPS
- * MO.
- */
- public static final int OSU_FAILURE_NO_AAA_SERVER_TRUST_ROOT_NODE = 17;
-
- /**
- * The reason code for provisioning failure when there is no TrustRoot node for remediation
- * server in a PPS MO.
- */
- public static final int OSU_FAILURE_NO_REMEDIATION_SERVER_TRUST_ROOT_NODE = 18;
-
- /**
- * The reason code for provisioning failure when there is no TrustRoot node for policy server in
- * a PPS MO.
- */
- public static final int OSU_FAILURE_NO_POLICY_SERVER_TRUST_ROOT_NODE = 19;
-
- /**
- * The reason code for provisioning failure when failing to retrieve trust root certificates
- * used for validating server certificate for AAA, Remediation and Policy server.
- */
- public static final int OSU_FAILURE_RETRIEVE_TRUST_ROOT_CERTIFICATES = 20;
-
- /**
- * The reason code for provisioning failure when there is no trust root certificate for AAA
- * server.
- */
- public static final int OSU_FAILURE_NO_AAA_TRUST_ROOT_CERTIFICATE = 21;
-
- /**
- * The reason code for provisioning failure when a {@link PasspointConfiguration} is failed to
- * install.
- */
- public static final int OSU_FAILURE_ADD_PASSPOINT_CONFIGURATION = 22;
-
- /**
- * The reason code for provisioning failure when an {@link OsuProvider} is not found for
- * provisioning.
- */
- public static final int OSU_FAILURE_OSU_PROVIDER_NOT_FOUND = 23;
-
- /**
- * The status code for provisioning flow to indicate connecting to OSU AP
- */
- public static final int OSU_STATUS_AP_CONNECTING = 1;
-
- /**
- * The status code for provisioning flow to indicate the OSU AP is connected.
- */
- public static final int OSU_STATUS_AP_CONNECTED = 2;
-
- /**
- * The status code for provisioning flow to indicate connecting to the server.
- */
- public static final int OSU_STATUS_SERVER_CONNECTING = 3;
-
- /**
- * The status code for provisioning flow to indicate the server certificate is validated.
- */
- public static final int OSU_STATUS_SERVER_VALIDATED = 4;
-
- /**
- * The status code for provisioning flow to indicate the server is connected
- */
- public static final int OSU_STATUS_SERVER_CONNECTED = 5;
-
- /**
- * The status code for provisioning flow to indicate starting the first SOAP exchange.
- */
- public static final int OSU_STATUS_INIT_SOAP_EXCHANGE = 6;
-
- /**
- * The status code for provisioning flow to indicate waiting for a HTTP redirect response.
- */
- public static final int OSU_STATUS_WAITING_FOR_REDIRECT_RESPONSE = 7;
-
- /**
- * The status code for provisioning flow to indicate a HTTP redirect response is received.
- */
- public static final int OSU_STATUS_REDIRECT_RESPONSE_RECEIVED = 8;
-
- /**
- * The status code for provisioning flow to indicate starting the second SOAP exchange.
- */
- public static final int OSU_STATUS_SECOND_SOAP_EXCHANGE = 9;
-
- /**
- * The status code for provisioning flow to indicate starting the third SOAP exchange.
- */
- public static final int OSU_STATUS_THIRD_SOAP_EXCHANGE = 10;
-
- /**
- * The status code for provisioning flow to indicate starting a step retrieving trust root
- * certs.
- */
- public static final int OSU_STATUS_RETRIEVING_TRUST_ROOT_CERTS = 11;
-
- /**
- * Provisioning status for OSU failure
- *
- * @param status indicates error condition
- */
- public abstract void onProvisioningFailure(int status);
-
- /**
- * Provisioning status when OSU is in progress
- *
- * @param status indicates status of OSU flow
- */
- public abstract void onProvisioningStatus(int status);
-
- /**
- * Provisioning complete when provisioning/remediation flow completes
- */
- public abstract void onProvisioningComplete();
-}
-
diff --git a/wifi/java/android/net/wifi/hotspot2/omadm/PpsMoParser.java b/wifi/java/android/net/wifi/hotspot2/omadm/PpsMoParser.java
deleted file mode 100644
index ae60ed47fd6a..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/omadm/PpsMoParser.java
+++ /dev/null
@@ -1,1787 +0,0 @@
-/**
- * Copyright (c) 2016, 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.hotspot2.omadm;
-
-import android.net.wifi.hotspot2.PasspointConfiguration;
-import android.net.wifi.hotspot2.pps.Credential;
-import android.net.wifi.hotspot2.pps.HomeSp;
-import android.net.wifi.hotspot2.pps.Policy;
-import android.net.wifi.hotspot2.pps.UpdateParameter;
-import android.text.TextUtils;
-import android.util.Log;
-import android.util.Pair;
-
-import org.xml.sax.SAXException;
-
-import java.io.IOException;
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Utility class for converting OMA-DM (Open Mobile Alliance's Device Management)
- * PPS-MO (PerProviderSubscription Management Object) XML tree to a
- * {@link PasspointConfiguration} object.
- *
- * Currently this only supports PerProviderSubscription/HomeSP and
- * PerProviderSubscription/Credential subtree for Hotspot 2.0 Release 1 support.
- *
- * For more info, refer to Hotspot 2.0 PPS MO defined in section 9.1 of the Hotspot 2.0
- * Release 2 Technical Specification.
- *
- * Below is a sample XML string for a Release 1 PPS MO tree:
- *
- * <MgmtTree xmlns="syncml:dmddf1.2">
- * <VerDTD>1.2</VerDTD>
- * <Node>
- * <NodeName>PerProviderSubscription</NodeName>
- * <RTProperties>
- * <Type>
- * <DDFName>urn:wfa:mo:hotspot2dot0­perprovidersubscription:1.0</DDFName>
- * </Type>
- * </RTProperties>
- * <Node>
- * <NodeName>i001</NodeName>
- * <Node>
- * <NodeName>HomeSP</NodeName>
- * <Node>
- * <NodeName>FriendlyName</NodeName>
- * <Value>Century House</Value>
- * </Node>
- * <Node>
- * <NodeName>FQDN</NodeName>
- * <Value>mi6.co.uk</Value>
- * </Node>
- * <Node>
- * <NodeName>RoamingConsortiumOI</NodeName>
- * <Value>112233,445566</Value>
- * </Node>
- * </Node>
- * <Node>
- * <NodeName>Credential</NodeName>
- * <Node>
- * <NodeName>Realm</NodeName>
- * <Value>shaken.stirred.com</Value>
- * </Node>
- * <Node>
- * <NodeName>UsernamePassword</NodeName>
- * <Node>
- * <NodeName>Username</NodeName>
- * <Value>james</Value>
- * </Node>
- * <Node>
- * <NodeName>Password</NodeName>
- * <Value>Ym9uZDAwNw==</Value>
- * </Node>
- * <Node>
- * <NodeName>EAPMethod</NodeName>
- * <Node>
- * <NodeName>EAPType</NodeName>
- * <Value>21</Value>
- * </Node>
- * <Node>
- * <NodeName>InnerMethod</NodeName>
- * <Value>MS-CHAP-V2</Value>
- * </Node>
- * </Node>
- * </Node>
- * </Node>
- * </Node>
- * </Node>
- * </MgmtTree>
- */
-public final class PpsMoParser {
- private static final String TAG = "PpsMoParser";
-
- /**
- * XML tags expected in the PPS MO (PerProviderSubscription Management Object) XML tree.
- */
- private static final String TAG_MANAGEMENT_TREE = "MgmtTree";
- private static final String TAG_VER_DTD = "VerDTD";
- private static final String TAG_NODE = "Node";
- private static final String TAG_NODE_NAME = "NodeName";
- private static final String TAG_RT_PROPERTIES = "RTProperties";
- private static final String TAG_TYPE = "Type";
- private static final String TAG_DDF_NAME = "DDFName";
- private static final String TAG_VALUE = "Value";
-
- /**
- * Name for PerProviderSubscription node.
- */
- private static final String NODE_PER_PROVIDER_SUBSCRIPTION = "PerProviderSubscription";
-
- /**
- * Fields under PerProviderSubscription.
- */
- private static final String NODE_UPDATE_IDENTIFIER = "UpdateIdentifier";
- private static final String NODE_AAA_SERVER_TRUST_ROOT = "AAAServerTrustRoot";
- private static final String NODE_SUBSCRIPTION_UPDATE = "SubscriptionUpdate";
- private static final String NODE_SUBSCRIPTION_PARAMETER = "SubscriptionParameters";
- private static final String NODE_TYPE_OF_SUBSCRIPTION = "TypeOfSubscription";
- private static final String NODE_USAGE_LIMITS = "UsageLimits";
- private static final String NODE_DATA_LIMIT = "DataLimit";
- private static final String NODE_START_DATE = "StartDate";
- private static final String NODE_TIME_LIMIT = "TimeLimit";
- private static final String NODE_USAGE_TIME_PERIOD = "UsageTimePeriod";
- private static final String NODE_CREDENTIAL_PRIORITY = "CredentialPriority";
- private static final String NODE_EXTENSION = "Extension";
-
- /**
- * Fields under Extension/Android subtree.
- */
- /*
- * This node is used to put Android specific extension nodes and must be put
- * under "Extension" node. Nodes with unknown names are allowed under this subtree.
- * If there is any new node added in later release, it won't break older release parsing.
- * <p>
- * Ex:
- * <Node>
- * <NodeName>Extension</NodeName>
- * <Node>
- * <NodeName>Android</NodeName>
- * <Node>
- * <NodeName>AndroidSpecificAttribute</NodeName>
- * <Value>AndroidSpecificValue</Value>
- * </Node>
- * <Node>
- * <NodeName>AndroidSpecificAttribute2</NodeName>
- * <Value>AndroidSpecificValue2</Value>
- * </Node>
- * </Node>
- * </Node>
- */
- private static final String NODE_VENDOR_ANDROID = "Android";
- /*
- * This node describes AAA server trusted names. The trusted name must be put in
- * a leaf named "FQDN". More than one trusted names can be provided by using
- * semicolons to separate the strings (e.g., example.org;example.com).
- * <p>
- * Ex:
- * <Node>
- * <NodeName>AAAServerTrustedNames</NodeName>
- * <Node>
- * <NodeName>FQDN</NodeName>
- * <Value>trusted.com;auth.net</Value>
- * </Node>
- * <Node>
- */
- private static final String NODE_AAA_SERVER_TRUSTED_NAMES = "AAAServerTrustedNames";
-
- /**
- * Fields under HomeSP subtree.
- */
- private static final String NODE_HOMESP = "HomeSP";
- private static final String NODE_FQDN = "FQDN";
- private static final String NODE_FRIENDLY_NAME = "FriendlyName";
- private static final String NODE_ROAMING_CONSORTIUM_OI = "RoamingConsortiumOI";
- private static final String NODE_NETWORK_ID = "NetworkID";
- private static final String NODE_SSID = "SSID";
- private static final String NODE_HESSID = "HESSID";
- private static final String NODE_ICON_URL = "IconURL";
- private static final String NODE_HOME_OI_LIST = "HomeOIList";
- private static final String NODE_HOME_OI = "HomeOI";
- private static final String NODE_HOME_OI_REQUIRED = "HomeOIRequired";
- private static final String NODE_OTHER_HOME_PARTNERS = "OtherHomePartners";
-
- /**
- * Fields under Credential subtree.
- */
- private static final String NODE_CREDENTIAL = "Credential";
- private static final String NODE_CREATION_DATE = "CreationDate";
- private static final String NODE_EXPIRATION_DATE = "ExpirationDate";
- private static final String NODE_USERNAME_PASSWORD = "UsernamePassword";
- private static final String NODE_USERNAME = "Username";
- private static final String NODE_PASSWORD = "Password";
- private static final String NODE_MACHINE_MANAGED = "MachineManaged";
- private static final String NODE_SOFT_TOKEN_APP = "SoftTokenApp";
- private static final String NODE_ABLE_TO_SHARE = "AbleToShare";
- private static final String NODE_EAP_METHOD = "EAPMethod";
- private static final String NODE_EAP_TYPE = "EAPType";
- private static final String NODE_VENDOR_ID = "VendorId";
- private static final String NODE_VENDOR_TYPE = "VendorType";
- private static final String NODE_INNER_EAP_TYPE = "InnerEAPType";
- private static final String NODE_INNER_VENDOR_ID = "InnerVendorID";
- private static final String NODE_INNER_VENDOR_TYPE = "InnerVendorType";
- private static final String NODE_INNER_METHOD = "InnerMethod";
- private static final String NODE_DIGITAL_CERTIFICATE = "DigitalCertificate";
- private static final String NODE_CERTIFICATE_TYPE = "CertificateType";
- private static final String NODE_CERT_SHA256_FINGERPRINT = "CertSHA256Fingerprint";
- private static final String NODE_REALM = "Realm";
- private static final String NODE_SIM = "SIM";
- private static final String NODE_SIM_IMSI = "IMSI";
- private static final String NODE_CHECK_AAA_SERVER_CERT_STATUS = "CheckAAAServerCertStatus";
-
- /**
- * Fields under Policy subtree.
- */
- private static final String NODE_POLICY = "Policy";
- private static final String NODE_PREFERRED_ROAMING_PARTNER_LIST =
- "PreferredRoamingPartnerList";
- private static final String NODE_FQDN_MATCH = "FQDN_Match";
- private static final String NODE_PRIORITY = "Priority";
- private static final String NODE_COUNTRY = "Country";
- private static final String NODE_MIN_BACKHAUL_THRESHOLD = "MinBackhaulThreshold";
- private static final String NODE_NETWORK_TYPE = "NetworkType";
- private static final String NODE_DOWNLINK_BANDWIDTH = "DLBandwidth";
- private static final String NODE_UPLINK_BANDWIDTH = "ULBandwidth";
- private static final String NODE_POLICY_UPDATE = "PolicyUpdate";
- private static final String NODE_UPDATE_INTERVAL = "UpdateInterval";
- private static final String NODE_UPDATE_METHOD = "UpdateMethod";
- private static final String NODE_RESTRICTION = "Restriction";
- private static final String NODE_URI = "URI";
- private static final String NODE_TRUST_ROOT = "TrustRoot";
- private static final String NODE_CERT_URL = "CertURL";
- private static final String NODE_SP_EXCLUSION_LIST = "SPExclusionList";
- private static final String NODE_REQUIRED_PROTO_PORT_TUPLE = "RequiredProtoPortTuple";
- private static final String NODE_IP_PROTOCOL = "IPProtocol";
- private static final String NODE_PORT_NUMBER = "PortNumber";
- private static final String NODE_MAXIMUM_BSS_LOAD_VALUE = "MaximumBSSLoadValue";
- private static final String NODE_OTHER = "Other";
-
- /**
- * URN (Unique Resource Name) for PerProviderSubscription Management Object Tree.
- */
- private static final String PPS_MO_URN =
- "urn:wfa:mo:hotspot2dot0-perprovidersubscription:1.0";
-
- /**
- * Exception for generic parsing errors.
- */
- private static class ParsingException extends Exception {
- public ParsingException(String message) {
- super(message);
- }
- }
-
- /**
- * Class representing a node within the PerProviderSubscription tree.
- * This is used to flatten out and eliminate the extra layering in the XMLNode tree,
- * to make the data parsing easier and cleaner.
- *
- * A PPSNode can be an internal or a leaf node, but not both.
- *
- */
- private static abstract class PPSNode {
- private final String mName;
- public PPSNode(String name) {
- mName = name;
- }
-
- /**
- * @return the name of the node
- */
- public String getName() {
- return mName;
- }
-
- /**
- * Applies for internal node only.
- *
- * @return the list of children nodes.
- */
- public abstract List<PPSNode> getChildren();
-
- /**
- * Applies for leaf node only.
- *
- * @return the string value of the node
- */
- public abstract String getValue();
-
- /**
- * @return a flag indicating if this is a leaf or an internal node
- */
- public abstract boolean isLeaf();
- }
-
- /**
- * Class representing a leaf node in a PPS (PerProviderSubscription) tree.
- */
- private static class LeafNode extends PPSNode {
- private final String mValue;
- public LeafNode(String nodeName, String value) {
- super(nodeName);
- mValue = value;
- }
-
- @Override
- public String getValue() {
- return mValue;
- }
-
- @Override
- public List<PPSNode> getChildren() {
- return null;
- }
-
- @Override
- public boolean isLeaf() {
- return true;
- }
- }
-
- /**
- * Class representing an internal node in a PPS (PerProviderSubscription) tree.
- */
- private static class InternalNode extends PPSNode {
- private final List<PPSNode> mChildren;
- public InternalNode(String nodeName, List<PPSNode> children) {
- super(nodeName);
- mChildren = children;
- }
-
- @Override
- public String getValue() {
- return null;
- }
-
- @Override
- public List<PPSNode> getChildren() {
- return mChildren;
- }
-
- @Override
- public boolean isLeaf() {
- return false;
- }
- }
-
- /**
- * @hide
- */
- public PpsMoParser() {}
-
- /**
- * Convert a XML string representation of a PPS MO (PerProviderSubscription
- * Management Object) tree to a {@link PasspointConfiguration} object.
- *
- * @param xmlString XML string representation of a PPS MO tree
- * @return {@link PasspointConfiguration} or null
- */
- public static PasspointConfiguration parseMoText(String xmlString) {
- // Convert the XML string to a XML tree.
- XMLParser xmlParser = new XMLParser();
- XMLNode root = null;
- try {
- root = xmlParser.parse(xmlString);
- } catch(IOException | SAXException e) {
- return null;
- }
- if (root == null) {
- return null;
- }
-
- // Verify root node is a "MgmtTree" node.
- if (root.getTag() != TAG_MANAGEMENT_TREE) {
- Log.e(TAG, "Root is not a MgmtTree");
- return null;
- }
-
- String verDtd = null; // Used for detecting duplicate VerDTD element.
- PasspointConfiguration config = null;
- for (XMLNode child : root.getChildren()) {
- switch(child.getTag()) {
- case TAG_VER_DTD:
- if (verDtd != null) {
- Log.e(TAG, "Duplicate VerDTD element");
- return null;
- }
- verDtd = child.getText();
- break;
- case TAG_NODE:
- if (config != null) {
- Log.e(TAG, "Unexpected multiple Node element under MgmtTree");
- return null;
- }
- try {
- config = parsePpsNode(child);
- } catch (ParsingException e) {
- Log.e(TAG, e.getMessage());
- return null;
- }
- break;
- default:
- Log.e(TAG, "Unknown node: " + child.getTag());
- return null;
- }
- }
- return config;
- }
-
- /**
- * Parse a PerProviderSubscription node. Below is the format of the XML tree (with
- * each XML element represent a node in the tree):
- *
- * <Node>
- * <NodeName>PerProviderSubscription</NodeName>
- * <RTProperties>
- * ...
- * </RTPProperties>
- * <Node>
- * <NodeName>UpdateIdentifier</NodeName>
- * <Value>...</Value>
- * </Node>
- * <Node>
- * ...
- * </Node>
- * </Node>
- *
- * @param node XMLNode that contains PerProviderSubscription node.
- * @return PasspointConfiguration or null
- * @throws ParsingException
- */
- private static PasspointConfiguration parsePpsNode(XMLNode node)
- throws ParsingException {
- PasspointConfiguration config = null;
- String nodeName = null;
- int updateIdentifier = Integer.MIN_VALUE;
- for (XMLNode child : node.getChildren()) {
- switch (child.getTag()) {
- case TAG_NODE_NAME:
- if (nodeName != null) {
- throw new ParsingException("Duplicate NodeName: " + child.getText());
- }
- nodeName = child.getText();
- if (!TextUtils.equals(nodeName, NODE_PER_PROVIDER_SUBSCRIPTION)) {
- throw new ParsingException("Unexpected NodeName: " + nodeName);
- }
- break;
- case TAG_NODE:
- // A node can be either an UpdateIdentifier node or a PerProviderSubscription
- // instance node. Flatten out the XML tree first by converting it to a PPS
- // tree to reduce the complexity of the parsing code.
- PPSNode ppsNodeRoot = buildPpsNode(child);
- if (TextUtils.equals(ppsNodeRoot.getName(), NODE_UPDATE_IDENTIFIER)) {
- if (updateIdentifier != Integer.MIN_VALUE) {
- throw new ParsingException("Multiple node for UpdateIdentifier");
- }
- updateIdentifier = parseInteger(getPpsNodeValue(ppsNodeRoot));
- } else {
- // Only one PerProviderSubscription instance is expected and allowed.
- if (config != null) {
- throw new ParsingException("Multiple PPS instance");
- }
- config = parsePpsInstance(ppsNodeRoot);
- }
- break;
- case TAG_RT_PROPERTIES:
- // Parse and verify URN stored in the RT (Run Time) Properties.
- String urn = parseUrn(child);
- if (!TextUtils.equals(urn, PPS_MO_URN)) {
- throw new ParsingException("Unknown URN: " + urn);
- }
- break;
- default:
- throw new ParsingException("Unknown tag under PPS node: " + child.getTag());
- }
- }
- if (config != null && updateIdentifier != Integer.MIN_VALUE) {
- config.setUpdateIdentifier(updateIdentifier);
- }
- return config;
- }
-
- /**
- * Parse the URN stored in the RTProperties. Below is the format of the RTPProperties node:
- *
- * <RTProperties>
- * <Type>
- * <DDFName>urn:...</DDFName>
- * </Type>
- * </RTProperties>
- *
- * @param node XMLNode that contains RTProperties node.
- * @return URN String of URN.
- * @throws ParsingException
- */
- private static String parseUrn(XMLNode node) throws ParsingException {
- if (node.getChildren().size() != 1)
- throw new ParsingException("Expect RTPProperties node to only have one child");
-
- XMLNode typeNode = node.getChildren().get(0);
- if (typeNode.getChildren().size() != 1) {
- throw new ParsingException("Expect Type node to only have one child");
- }
- if (!TextUtils.equals(typeNode.getTag(), TAG_TYPE)) {
- throw new ParsingException("Unexpected tag for Type: " + typeNode.getTag());
- }
-
- XMLNode ddfNameNode = typeNode.getChildren().get(0);
- if (!ddfNameNode.getChildren().isEmpty()) {
- throw new ParsingException("Expect DDFName node to have no child");
- }
- if (!TextUtils.equals(ddfNameNode.getTag(), TAG_DDF_NAME)) {
- throw new ParsingException("Unexpected tag for DDFName: " + ddfNameNode.getTag());
- }
-
- return ddfNameNode.getText();
- }
-
- /**
- * Convert a XML tree represented by XMLNode to a PPS (PerProviderSubscription) instance tree
- * represented by PPSNode. This flattens out the XML tree to allow easier and cleaner parsing
- * of the PPS configuration data. Only three types of XML tag are expected: "NodeName",
- * "Node", and "Value".
- *
- * The original XML tree (each XML element represent a node):
- *
- * <Node>
- * <NodeName>root</NodeName>
- * <Node>
- * <NodeName>child1</NodeName>
- * <Value>value1</Value>
- * </Node>
- * <Node>
- * <NodeName>child2</NodeName>
- * <Node>
- * <NodeName>grandchild1</NodeName>
- * ...
- * </Node>
- * </Node>
- * ...
- * </Node>
- *
- * The converted PPS tree:
- *
- * [root] --- [child1, value1]
- * |
- * ---------[child2] --------[grandchild1] --- ...
- *
- * @param node XMLNode pointed to the root of a XML tree
- * @return PPSNode pointing to the root of a PPS tree
- * @throws ParsingException
- */
- private static PPSNode buildPpsNode(XMLNode node) throws ParsingException {
- String nodeName = null;
- String nodeValue = null;
- List<PPSNode> childNodes = new ArrayList<PPSNode>();
- // Names of parsed child nodes, use for detecting multiple child nodes with the same name.
- Set<String> parsedNodes = new HashSet<String>();
-
- for (XMLNode child : node.getChildren()) {
- String tag = child.getTag();
- if (TextUtils.equals(tag, TAG_NODE_NAME)) {
- if (nodeName != null) {
- throw new ParsingException("Duplicate NodeName node");
- }
- nodeName = child.getText();
- } else if (TextUtils.equals(tag, TAG_NODE)) {
- PPSNode ppsNode = buildPpsNode(child);
- if (parsedNodes.contains(ppsNode.getName())) {
- throw new ParsingException("Duplicate node: " + ppsNode.getName());
- }
- parsedNodes.add(ppsNode.getName());
- childNodes.add(ppsNode);
- } else if (TextUtils.equals(tag, TAG_VALUE)) {
- if (nodeValue != null) {
- throw new ParsingException("Duplicate Value node");
- }
- nodeValue = child.getText();
- } else {
- throw new ParsingException("Unknown tag: " + tag);
- }
- }
-
- if (nodeName == null) {
- throw new ParsingException("Invalid node: missing NodeName");
- }
- if (nodeValue == null && childNodes.size() == 0) {
- throw new ParsingException("Invalid node: " + nodeName +
- " missing both value and children");
- }
- if (nodeValue != null && childNodes.size() > 0) {
- throw new ParsingException("Invalid node: " + nodeName +
- " contained both value and children");
- }
-
- if (nodeValue != null) {
- return new LeafNode(nodeName, nodeValue);
- }
- return new InternalNode(nodeName, childNodes);
- }
-
- /**
- * Return the value of a PPSNode. An exception will be thrown if the given node
- * is not a leaf node.
- *
- * @param node PPSNode to retrieve the value from
- * @return String representing the value of the node
- * @throws ParsingException
- */
- private static String getPpsNodeValue(PPSNode node) throws ParsingException {
- if (!node.isLeaf()) {
- throw new ParsingException("Cannot get value from a non-leaf node: " + node.getName());
- }
- return node.getValue();
- }
-
- /**
- * Parse a PPS (PerProviderSubscription) configurations from a PPS tree.
- *
- * @param root PPSNode representing the root of the PPS tree
- * @return PasspointConfiguration
- * @throws ParsingException
- */
- private static PasspointConfiguration parsePpsInstance(PPSNode root)
- throws ParsingException {
- if (root.isLeaf()) {
- throw new ParsingException("Leaf node not expected for PPS instance");
- }
-
- PasspointConfiguration config = new PasspointConfiguration();
- for (PPSNode child : root.getChildren()) {
- switch(child.getName()) {
- case NODE_HOMESP:
- config.setHomeSp(parseHomeSP(child));
- break;
- case NODE_CREDENTIAL:
- config.setCredential(parseCredential(child));
- break;
- case NODE_POLICY:
- config.setPolicy(parsePolicy(child));
- break;
- case NODE_AAA_SERVER_TRUST_ROOT:
- config.setTrustRootCertList(parseAAAServerTrustRootList(child));
- break;
- case NODE_SUBSCRIPTION_UPDATE:
- config.setSubscriptionUpdate(parseUpdateParameter(child));
- break;
- case NODE_SUBSCRIPTION_PARAMETER:
- parseSubscriptionParameter(child, config);
- break;
- case NODE_CREDENTIAL_PRIORITY:
- config.setCredentialPriority(parseInteger(getPpsNodeValue(child)));
- break;
- case NODE_EXTENSION:
- // All vendor specific information will be under this node.
- parseExtension(child, config);
- break;
- default:
- throw new ParsingException("Unknown node: " + child.getName());
- }
- }
- return config;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/HomeSP subtree.
- *
- * @param node PPSNode representing the root of the PerProviderSubscription/HomeSP subtree
- * @return HomeSP
- * @throws ParsingException
- */
- private static HomeSp parseHomeSP(PPSNode node) throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for HomeSP");
- }
-
- HomeSp homeSp = new HomeSp();
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_FQDN:
- homeSp.setFqdn(getPpsNodeValue(child));
- break;
- case NODE_FRIENDLY_NAME:
- homeSp.setFriendlyName(getPpsNodeValue(child));
- break;
- case NODE_ROAMING_CONSORTIUM_OI:
- homeSp.setRoamingConsortiumOis(
- parseRoamingConsortiumOI(getPpsNodeValue(child)));
- break;
- case NODE_ICON_URL:
- homeSp.setIconUrl(getPpsNodeValue(child));
- break;
- case NODE_NETWORK_ID:
- homeSp.setHomeNetworkIds(parseNetworkIds(child));
- break;
- case NODE_HOME_OI_LIST:
- Pair<List<Long>, List<Long>> homeOIs = parseHomeOIList(child);
- homeSp.setMatchAllOis(convertFromLongList(homeOIs.first));
- homeSp.setMatchAnyOis(convertFromLongList(homeOIs.second));
- break;
- case NODE_OTHER_HOME_PARTNERS:
- homeSp.setOtherHomePartners(parseOtherHomePartners(child));
- break;
- default:
- throw new ParsingException("Unknown node under HomeSP: " + child.getName());
- }
- }
- return homeSp;
- }
-
- /**
- * Parse the roaming consortium OI string, which contains a list of OIs separated by ",".
- *
- * @param oiStr string containing list of OIs (Organization Identifiers) separated by ","
- * @return long[]
- * @throws ParsingException
- */
- private static long[] parseRoamingConsortiumOI(String oiStr)
- throws ParsingException {
- String[] oiStrArray = oiStr.split(",");
- long[] oiArray = new long[oiStrArray.length];
- for (int i = 0; i < oiStrArray.length; i++) {
- oiArray[i] = parseLong(oiStrArray[i], 16);
- }
- return oiArray;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/HomeSP/NetworkID subtree.
- *
- * @param node PPSNode representing the root of the PerProviderSubscription/HomeSP/NetworkID
- * subtree
- * @return HashMap<String, Long> representing list of <SSID, HESSID> pair.
- * @throws ParsingException
- */
- static private Map<String, Long> parseNetworkIds(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for NetworkID");
- }
-
- Map<String, Long> networkIds = new HashMap<>();
- for (PPSNode child : node.getChildren()) {
- Pair<String, Long> networkId = parseNetworkIdInstance(child);
- networkIds.put(networkId.first, networkId.second);
- }
- return networkIds;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/HomeSP/NetworkID/<X+> subtree.
- * The instance name (<X+>) is irrelevant and must be unique for each instance, which
- * is verified when the PPS tree is constructed {@link #buildPpsNode}.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/HomeSP/NetworkID/<X+> subtree
- * @return Pair<String, Long> representing <SSID, HESSID> pair.
- * @throws ParsingException
- */
- static private Pair<String, Long> parseNetworkIdInstance(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for NetworkID instance");
- }
-
- String ssid = null;
- Long hessid = null;
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_SSID:
- ssid = getPpsNodeValue(child);
- break;
- case NODE_HESSID:
- hessid = parseLong(getPpsNodeValue(child), 16);
- break;
- default:
- throw new ParsingException("Unknown node under NetworkID instance: " +
- child.getName());
- }
- }
- if (ssid == null)
- throw new ParsingException("NetworkID instance missing SSID");
-
- return new Pair<String, Long>(ssid, hessid);
- }
-
- /**
- * Parse configurations under PerProviderSubscription/HomeSP/HomeOIList subtree.
- *
- * @param node PPSNode representing the root of the PerProviderSubscription/HomeSP/HomeOIList
- * subtree
- * @return Pair<List<Long>, List<Long>> containing both MatchAllOIs and MatchAnyOIs list.
- * @throws ParsingException
- */
- private static Pair<List<Long>, List<Long>> parseHomeOIList(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for HomeOIList");
- }
-
- List<Long> matchAllOIs = new ArrayList<Long>();
- List<Long> matchAnyOIs = new ArrayList<Long>();
- for (PPSNode child : node.getChildren()) {
- Pair<Long, Boolean> homeOI = parseHomeOIInstance(child);
- if (homeOI.second.booleanValue()) {
- matchAllOIs.add(homeOI.first);
- } else {
- matchAnyOIs.add(homeOI.first);
- }
- }
- return new Pair<List<Long>, List<Long>>(matchAllOIs, matchAnyOIs);
- }
-
- /**
- * Parse configurations under PerProviderSubscription/HomeSP/HomeOIList/<X+> subtree.
- * The instance name (<X+>) is irrelevant and must be unique for each instance, which
- * is verified when the PPS tree is constructed {@link #buildPpsNode}.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/HomeSP/HomeOIList/<X+> subtree
- * @return Pair<Long, Boolean> containing a HomeOI and a HomeOIRequired flag
- * @throws ParsingException
- */
- private static Pair<Long, Boolean> parseHomeOIInstance(PPSNode node) throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for HomeOI instance");
- }
-
- Long oi = null;
- Boolean required = null;
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_HOME_OI:
- try {
- oi = Long.valueOf(getPpsNodeValue(child), 16);
- } catch (NumberFormatException e) {
- throw new ParsingException("Invalid HomeOI: " + getPpsNodeValue(child));
- }
- break;
- case NODE_HOME_OI_REQUIRED:
- required = Boolean.valueOf(getPpsNodeValue(child));
- break;
- default:
- throw new ParsingException("Unknown node under NetworkID instance: " +
- child.getName());
- }
- }
- if (oi == null) {
- throw new ParsingException("HomeOI instance missing OI field");
- }
- if (required == null) {
- throw new ParsingException("HomeOI instance missing required field");
- }
- return new Pair<Long, Boolean>(oi, required);
- }
-
- /**
- * Parse configurations under PerProviderSubscription/HomeSP/OtherHomePartners subtree.
- * This contains a list of FQDN (Fully Qualified Domain Name) that are considered
- * home partners.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/HomeSP/OtherHomePartners subtree
- * @return String[] list of partner's FQDN
- * @throws ParsingException
- */
- private static String[] parseOtherHomePartners(PPSNode node) throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for OtherHomePartners");
- }
- List<String> otherHomePartners = new ArrayList<String>();
- for (PPSNode child : node.getChildren()) {
- String fqdn = parseOtherHomePartnerInstance(child);
- otherHomePartners.add(fqdn);
- }
- return otherHomePartners.toArray(new String[otherHomePartners.size()]);
- }
-
- /**
- * Parse configurations under PerProviderSubscription/HomeSP/OtherHomePartners/<X+> subtree.
- * The instance name (<X+>) is irrelevant and must be unique for each instance, which
- * is verified when the PPS tree is constructed {@link #buildPpsNode}.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/HomeSP/OtherHomePartners/<X+> subtree
- * @return String FQDN of the partner
- * @throws ParsingException
- */
- private static String parseOtherHomePartnerInstance(PPSNode node) throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for OtherHomePartner instance");
- }
- String fqdn = null;
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_FQDN:
- fqdn = getPpsNodeValue(child);
- break;
- default:
- throw new ParsingException(
- "Unknown node under OtherHomePartner instance: " + child.getName());
- }
- }
- if (fqdn == null) {
- throw new ParsingException("OtherHomePartner instance missing FQDN field");
- }
- return fqdn;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Credential subtree.
- *
- * @param node PPSNode representing the root of the PerProviderSubscription/Credential subtree
- * @return Credential
- * @throws ParsingException
- */
- private static Credential parseCredential(PPSNode node) throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for Credential");
- }
-
- Credential credential = new Credential();
- for (PPSNode child: node.getChildren()) {
- switch (child.getName()) {
- case NODE_CREATION_DATE:
- credential.setCreationTimeInMillis(parseDate(getPpsNodeValue(child)));
- break;
- case NODE_EXPIRATION_DATE:
- credential.setExpirationTimeInMillis(parseDate(getPpsNodeValue(child)));
- break;
- case NODE_USERNAME_PASSWORD:
- credential.setUserCredential(parseUserCredential(child));
- break;
- case NODE_DIGITAL_CERTIFICATE:
- credential.setCertCredential(parseCertificateCredential(child));
- break;
- case NODE_REALM:
- credential.setRealm(getPpsNodeValue(child));
- break;
- case NODE_CHECK_AAA_SERVER_CERT_STATUS:
- credential.setCheckAaaServerCertStatus(
- Boolean.parseBoolean(getPpsNodeValue(child)));
- break;
- case NODE_SIM:
- credential.setSimCredential(parseSimCredential(child));
- break;
- default:
- throw new ParsingException("Unknown node under Credential: " +
- child.getName());
- }
- }
- return credential;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Credential/UsernamePassword subtree.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Credential/UsernamePassword subtree
- * @return Credential.UserCredential
- * @throws ParsingException
- */
- private static Credential.UserCredential parseUserCredential(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for UsernamePassword");
- }
-
- Credential.UserCredential userCred = new Credential.UserCredential();
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_USERNAME:
- userCred.setUsername(getPpsNodeValue(child));
- break;
- case NODE_PASSWORD:
- userCred.setPassword(getPpsNodeValue(child));
- break;
- case NODE_MACHINE_MANAGED:
- userCred.setMachineManaged(Boolean.parseBoolean(getPpsNodeValue(child)));
- break;
- case NODE_SOFT_TOKEN_APP:
- userCred.setSoftTokenApp(getPpsNodeValue(child));
- break;
- case NODE_ABLE_TO_SHARE:
- userCred.setAbleToShare(Boolean.parseBoolean(getPpsNodeValue(child)));
- break;
- case NODE_EAP_METHOD:
- parseEAPMethod(child, userCred);
- break;
- default:
- throw new ParsingException("Unknown node under UsernamePassword: "
- + child.getName());
- }
- }
- return userCred;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Credential/UsernamePassword/EAPMethod
- * subtree.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Credential/UsernamePassword/EAPMethod subtree
- * @param userCred UserCredential to be updated with EAP method values.
- * @throws ParsingException
- */
- private static void parseEAPMethod(PPSNode node, Credential.UserCredential userCred)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for EAPMethod");
- }
-
- for (PPSNode child : node.getChildren()) {
- switch(child.getName()) {
- case NODE_EAP_TYPE:
- userCred.setEapType(parseInteger(getPpsNodeValue(child)));
- break;
- case NODE_INNER_METHOD:
- userCred.setNonEapInnerMethod(getPpsNodeValue(child));
- break;
- case NODE_VENDOR_ID:
- case NODE_VENDOR_TYPE:
- case NODE_INNER_EAP_TYPE:
- case NODE_INNER_VENDOR_ID:
- case NODE_INNER_VENDOR_TYPE:
- // Only EAP-TTLS is currently supported for user credential, which doesn't
- // use any of these parameters.
- Log.d(TAG, "Ignore unsupported EAP method parameter: " + child.getName());
- break;
- default:
- throw new ParsingException("Unknown node under EAPMethod: " + child.getName());
- }
- }
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Credential/DigitalCertificate subtree.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Credential/DigitalCertificate subtree
- * @return Credential.CertificateCredential
- * @throws ParsingException
- */
- private static Credential.CertificateCredential parseCertificateCredential(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for CertificateCredential");
- }
-
- Credential.CertificateCredential certCred = new Credential.CertificateCredential();
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_CERTIFICATE_TYPE:
- certCred.setCertType(getPpsNodeValue(child));
- break;
- case NODE_CERT_SHA256_FINGERPRINT:
- certCred.setCertSha256Fingerprint(parseHexString(getPpsNodeValue(child)));
- break;
- default:
- throw new ParsingException("Unknown node under CertificateCredential: "
- + child.getName());
- }
- }
- return certCred;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Credential/SIM subtree.
- *
- * @param node PPSNode representing the root of the PerProviderSubscription/Credential/SIM
- * subtree
- * @return Credential.SimCredential
- * @throws ParsingException
- */
- private static Credential.SimCredential parseSimCredential(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for SimCredential");
- }
-
- Credential.SimCredential simCred = new Credential.SimCredential();
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_SIM_IMSI:
- simCred.setImsi(getPpsNodeValue(child));
- break;
- case NODE_EAP_TYPE:
- simCred.setEapType(parseInteger(getPpsNodeValue(child)));
- break;
- default:
- throw new ParsingException("Unknown node under SimCredential: "
- + child.getName());
- }
- }
- return simCred;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Policy subtree.
- *
- * @param node PPSNode representing the root of the PerProviderSubscription/Policy subtree
- * @return {@link Policy}
- * @throws ParsingException
- */
- private static Policy parsePolicy(PPSNode node) throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for Policy");
- }
-
- Policy policy = new Policy();
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_PREFERRED_ROAMING_PARTNER_LIST:
- policy.setPreferredRoamingPartnerList(parsePreferredRoamingPartnerList(child));
- break;
- case NODE_MIN_BACKHAUL_THRESHOLD:
- parseMinBackhaulThreshold(child, policy);
- break;
- case NODE_POLICY_UPDATE:
- policy.setPolicyUpdate(parseUpdateParameter(child));
- break;
- case NODE_SP_EXCLUSION_LIST:
- policy.setExcludedSsidList(parseSpExclusionList(child));
- break;
- case NODE_REQUIRED_PROTO_PORT_TUPLE:
- policy.setRequiredProtoPortMap(parseRequiredProtoPortTuple(child));
- break;
- case NODE_MAXIMUM_BSS_LOAD_VALUE:
- policy.setMaximumBssLoadValue(parseInteger(getPpsNodeValue(child)));
- break;
- default:
- throw new ParsingException("Unknown node under Policy: " + child.getName());
- }
- }
- return policy;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Policy/PreferredRoamingPartnerList
- * subtree.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Policy/PreferredRoamingPartnerList subtree
- * @return List of {@link Policy#RoamingPartner}
- * @throws ParsingException
- */
- private static List<Policy.RoamingPartner> parsePreferredRoamingPartnerList(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for PreferredRoamingPartnerList");
- }
- List<Policy.RoamingPartner> partnerList = new ArrayList<>();
- for (PPSNode child : node.getChildren()) {
- partnerList.add(parsePreferredRoamingPartner(child));
- }
- return partnerList;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Policy/PreferredRoamingPartnerList/<X+>
- * subtree.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Policy/PreferredRoamingPartnerList/<X+> subtree
- * @return {@link Policy#RoamingPartner}
- * @throws ParsingException
- */
- private static Policy.RoamingPartner parsePreferredRoamingPartner(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for PreferredRoamingPartner "
- + "instance");
- }
-
- Policy.RoamingPartner roamingPartner = new Policy.RoamingPartner();
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_FQDN_MATCH:
- // FQDN_Match field is in the format of "[FQDN],[MatchInfo]", where [MatchInfo]
- // is either "exactMatch" for exact match of FQDN or "includeSubdomains" for
- // matching all FQDNs with the same sub-domain.
- String fqdnMatch = getPpsNodeValue(child);
- String[] fqdnMatchArray = fqdnMatch.split(",");
- if (fqdnMatchArray.length != 2) {
- throw new ParsingException("Invalid FQDN_Match: " + fqdnMatch);
- }
- roamingPartner.setFqdn(fqdnMatchArray[0]);
- if (TextUtils.equals(fqdnMatchArray[1], "exactMatch")) {
- roamingPartner.setFqdnExactMatch(true);
- } else if (TextUtils.equals(fqdnMatchArray[1], "includeSubdomains")) {
- roamingPartner.setFqdnExactMatch(false);
- } else {
- throw new ParsingException("Invalid FQDN_Match: " + fqdnMatch);
- }
- break;
- case NODE_PRIORITY:
- roamingPartner.setPriority(parseInteger(getPpsNodeValue(child)));
- break;
- case NODE_COUNTRY:
- roamingPartner.setCountries(getPpsNodeValue(child));
- break;
- default:
- throw new ParsingException("Unknown node under PreferredRoamingPartnerList "
- + "instance " + child.getName());
- }
- }
- return roamingPartner;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Policy/MinBackhaulThreshold subtree
- * into the given policy.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Policy/MinBackhaulThreshold subtree
- * @param policy The policy to store the MinBackhualThreshold configuration
- * @throws ParsingException
- */
- private static void parseMinBackhaulThreshold(PPSNode node, Policy policy)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for MinBackhaulThreshold");
- }
- for (PPSNode child : node.getChildren()) {
- parseMinBackhaulThresholdInstance(child, policy);
- }
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Policy/MinBackhaulThreshold/<X+> subtree
- * into the given policy.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Policy/MinBackhaulThreshold/<X+> subtree
- * @param policy The policy to store the MinBackhaulThreshold configuration
- * @throws ParsingException
- */
- private static void parseMinBackhaulThresholdInstance(PPSNode node, Policy policy)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for MinBackhaulThreshold instance");
- }
- String networkType = null;
- long downlinkBandwidth = Long.MIN_VALUE;
- long uplinkBandwidth = Long.MIN_VALUE;
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_NETWORK_TYPE:
- networkType = getPpsNodeValue(child);
- break;
- case NODE_DOWNLINK_BANDWIDTH:
- downlinkBandwidth = parseLong(getPpsNodeValue(child), 10);
- break;
- case NODE_UPLINK_BANDWIDTH:
- uplinkBandwidth = parseLong(getPpsNodeValue(child), 10);
- break;
- default:
- throw new ParsingException("Unknown node under MinBackhaulThreshold instance "
- + child.getName());
- }
- }
- if (networkType == null) {
- throw new ParsingException("Missing NetworkType field");
- }
-
- if (TextUtils.equals(networkType, "home")) {
- policy.setMinHomeDownlinkBandwidth(downlinkBandwidth);
- policy.setMinHomeUplinkBandwidth(uplinkBandwidth);
- } else if (TextUtils.equals(networkType, "roaming")) {
- policy.setMinRoamingDownlinkBandwidth(downlinkBandwidth);
- policy.setMinRoamingUplinkBandwidth(uplinkBandwidth);
- } else {
- throw new ParsingException("Invalid network type: " + networkType);
- }
- }
-
- /**
- * Parse update parameters. This contained configurations from either
- * PerProviderSubscription/Policy/PolicyUpdate or PerProviderSubscription/SubscriptionUpdate
- * subtree.
- *
- * @param node PPSNode representing the root of the PerProviderSubscription/Policy/PolicyUpdate
- * or PerProviderSubscription/SubscriptionUpdate subtree
- * @return {@link UpdateParameter}
- * @throws ParsingException
- */
- private static UpdateParameter parseUpdateParameter(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for Update Parameters");
- }
-
- UpdateParameter updateParam = new UpdateParameter();
- for (PPSNode child : node.getChildren()) {
- switch(child.getName()) {
- case NODE_UPDATE_INTERVAL:
- updateParam.setUpdateIntervalInMinutes(parseLong(getPpsNodeValue(child), 10));
- break;
- case NODE_UPDATE_METHOD:
- updateParam.setUpdateMethod(getPpsNodeValue(child));
- break;
- case NODE_RESTRICTION:
- updateParam.setRestriction(getPpsNodeValue(child));
- break;
- case NODE_URI:
- updateParam.setServerUri(getPpsNodeValue(child));
- break;
- case NODE_USERNAME_PASSWORD:
- Pair<String, String> usernamePassword = parseUpdateUserCredential(child);
- updateParam.setUsername(usernamePassword.first);
- updateParam.setBase64EncodedPassword(usernamePassword.second);
- break;
- case NODE_TRUST_ROOT:
- Pair<String, byte[]> trustRoot = parseTrustRoot(child);
- updateParam.setTrustRootCertUrl(trustRoot.first);
- updateParam.setTrustRootCertSha256Fingerprint(trustRoot.second);
- break;
- case NODE_OTHER:
- Log.d(TAG, "Ignore unsupported paramter: " + child.getName());
- break;
- default:
- throw new ParsingException("Unknown node under Update Parameters: "
- + child.getName());
- }
- }
- return updateParam;
- }
-
- /**
- * Parse username and password parameters associated with policy or subscription update.
- * This contained configurations under either
- * PerProviderSubscription/Policy/PolicyUpdate/UsernamePassword or
- * PerProviderSubscription/SubscriptionUpdate/UsernamePassword subtree.
- *
- * @param node PPSNode representing the root of the UsernamePassword subtree
- * @return Pair of username and password
- * @throws ParsingException
- */
- private static Pair<String, String> parseUpdateUserCredential(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for UsernamePassword");
- }
-
- String username = null;
- String password = null;
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_USERNAME:
- username = getPpsNodeValue(child);
- break;
- case NODE_PASSWORD:
- password = getPpsNodeValue(child);
- break;
- default:
- throw new ParsingException("Unknown node under UsernamePassword: "
- + child.getName());
- }
- }
- return Pair.create(username, password);
- }
-
- /**
- * Parse the trust root parameters associated with policy update, subscription update, or AAA
- * server trust root.
- *
- * This contained configurations under either
- * PerProviderSubscription/Policy/PolicyUpdate/TrustRoot or
- * PerProviderSubscription/SubscriptionUpdate/TrustRoot or
- * PerProviderSubscription/AAAServerTrustRoot/<X+> subtree.
- *
- * @param node PPSNode representing the root of the TrustRoot subtree
- * @return Pair of Certificate URL and fingerprint
- * @throws ParsingException
- */
- private static Pair<String, byte[]> parseTrustRoot(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for TrustRoot");
- }
-
- String certUrl = null;
- byte[] certFingerprint = null;
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_CERT_URL:
- certUrl = getPpsNodeValue(child);
- break;
- case NODE_CERT_SHA256_FINGERPRINT:
- certFingerprint = parseHexString(getPpsNodeValue(child));
- break;
- default:
- throw new ParsingException("Unknown node under TrustRoot: "
- + child.getName());
- }
- }
- return Pair.create(certUrl, certFingerprint);
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Policy/SPExclusionList subtree.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Policy/SPExclusionList subtree
- * @return Array of excluded SSIDs
- * @throws ParsingException
- */
- private static String[] parseSpExclusionList(PPSNode node) throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for SPExclusionList");
- }
- List<String> ssidList = new ArrayList<>();
- for (PPSNode child : node.getChildren()) {
- ssidList.add(parseSpExclusionInstance(child));
- }
- return ssidList.toArray(new String[ssidList.size()]);
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Policy/SPExclusionList/<X+> subtree.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Policy/SPExclusionList/<X+> subtree
- * @return String
- * @throws ParsingException
- */
- private static String parseSpExclusionInstance(PPSNode node) throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for SPExclusion instance");
- }
- String ssid = null;
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_SSID:
- ssid = getPpsNodeValue(child);
- break;
- default:
- throw new ParsingException("Unknown node under SPExclusion instance");
- }
- }
- return ssid;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Policy/RequiredProtoPortTuple subtree.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Policy/RequiredProtoPortTuple subtree
- * @return Map of IP Protocol to Port Number tuples
- * @throws ParsingException
- */
- private static Map<Integer, String> parseRequiredProtoPortTuple(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for RequiredProtoPortTuple");
- }
- Map<Integer, String> protoPortTupleMap = new HashMap<>();
- for (PPSNode child : node.getChildren()) {
- Pair<Integer, String> protoPortTuple = parseProtoPortTuple(child);
- protoPortTupleMap.put(protoPortTuple.first, protoPortTuple.second);
- }
- return protoPortTupleMap;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Policy/RequiredProtoPortTuple/<X+>
- * subtree.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Policy/RequiredProtoPortTuple/<X+> subtree
- * @return Pair of IP Protocol to Port Number tuple
- * @throws ParsingException
- */
- private static Pair<Integer, String> parseProtoPortTuple(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for RequiredProtoPortTuple "
- + "instance");
- }
- int proto = Integer.MIN_VALUE;
- String ports = null;
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_IP_PROTOCOL:
- proto = parseInteger(getPpsNodeValue(child));
- break;
- case NODE_PORT_NUMBER:
- ports = getPpsNodeValue(child);
- break;
- default:
- throw new ParsingException("Unknown node under RequiredProtoPortTuple instance"
- + child.getName());
- }
- }
- if (proto == Integer.MIN_VALUE) {
- throw new ParsingException("Missing IPProtocol field");
- }
- if (ports == null) {
- throw new ParsingException("Missing PortNumber field");
- }
- return Pair.create(proto, ports);
- }
-
- /**
- * Parse configurations under PerProviderSubscription/AAAServerTrustRoot subtree.
- *
- * @param node PPSNode representing the root of PerProviderSubscription/AAAServerTrustRoot
- * subtree
- * @return Map of certificate URL with the corresponding certificate fingerprint
- * @throws ParsingException
- */
- private static Map<String, byte[]> parseAAAServerTrustRootList(PPSNode node)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for AAAServerTrustRoot");
- }
- Map<String, byte[]> certList = new HashMap<>();
- for (PPSNode child : node.getChildren()) {
- Pair<String, byte[]> certTuple = parseTrustRoot(child);
- certList.put(certTuple.first, certTuple.second);
- }
- return certList;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/SubscriptionParameter subtree.
- *
- * @param node PPSNode representing the root of PerProviderSubscription/SubscriptionParameter
- * subtree
- * @param config Instance of {@link PasspointConfiguration}
- * @throws ParsingException
- */
- private static void parseSubscriptionParameter(PPSNode node, PasspointConfiguration config)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for SubscriptionParameter");
- }
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_CREATION_DATE:
- config.setSubscriptionCreationTimeInMillis(parseDate(getPpsNodeValue(child)));
- break;
- case NODE_EXPIRATION_DATE:
- config.setSubscriptionExpirationTimeInMillis(parseDate(getPpsNodeValue(child)));
- break;
- case NODE_TYPE_OF_SUBSCRIPTION:
- config.setSubscriptionType(getPpsNodeValue(child));
- break;
- case NODE_USAGE_LIMITS:
- parseUsageLimits(child, config);
- break;
- default:
- throw new ParsingException("Unknown node under SubscriptionParameter"
- + child.getName());
- }
- }
- }
-
- /**
- * Parse configurations under PerProviderSubscription/SubscriptionParameter/UsageLimits
- * subtree.
- *
- * @param node PPSNode representing the root of
- * PerProviderSubscription/SubscriptionParameter/UsageLimits subtree
- * @param config Instance of {@link PasspointConfiguration}
- * @throws ParsingException
- */
- private static void parseUsageLimits(PPSNode node, PasspointConfiguration config)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for UsageLimits");
- }
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_DATA_LIMIT:
- config.setUsageLimitDataLimit(parseLong(getPpsNodeValue(child), 10));
- break;
- case NODE_START_DATE:
- config.setUsageLimitStartTimeInMillis(parseDate(getPpsNodeValue(child)));
- break;
- case NODE_TIME_LIMIT:
- config.setUsageLimitTimeLimitInMinutes(parseLong(getPpsNodeValue(child), 10));
- break;
- case NODE_USAGE_TIME_PERIOD:
- config.setUsageLimitUsageTimePeriodInMinutes(
- parseLong(getPpsNodeValue(child), 10));
- break;
- default:
- throw new ParsingException("Unknown node under UsageLimits"
- + child.getName());
- }
- }
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Extension/Android/AAAServerTrustedNames
- * subtree.
- *
- * @param node PPSNode representing the root of the
- * PerProviderSubscription/Extension/Android/AAAServerTrustedNames subtree
- * @return String[] list of trusted name
- * @throws ParsingException
- */
- private static String[] parseAaaServerTrustedNames(PPSNode node) throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for AAAServerTrustedNames instance");
- }
- String fqdnListStr = null;
- String[] fqdnListArray = null;
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_FQDN:
- fqdnListStr = getPpsNodeValue(child);
- fqdnListArray = fqdnListStr.split(";");
- break;
- default:
- throw new ParsingException(
- "Unknown node under AAAServerTrustedNames instance: "
- + child.getName());
- }
- }
- if (fqdnListArray == null) {
- throw new ParsingException("AAAServerTrustedNames instance missing FQDN field");
- }
-
- return fqdnListArray;
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Extension/Android subtree.
- *
- * @param node PPSNode representing the root of PerProviderSubscription/Extension
- * subtree
- * @param config Instance of {@link PasspointConfiguration}
- * @throws ParsingException
- */
- private static void parseVendorAndroidExtension(PPSNode node, PasspointConfiguration config)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for AndroidExtension");
- }
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_AAA_SERVER_TRUSTED_NAMES:
- config.setAaaServerTrustedNames(parseAaaServerTrustedNames(child));
- break;
- default:
- // Don't raise an exception for unknown nodes to avoid breaking old release
- Log.w(TAG, "Unknown node under Android Extension: " + child.getName());
- }
- }
- }
-
- /**
- * Parse configurations under PerProviderSubscription/Extension subtree.
- *
- * @param node PPSNode representing the root of PerProviderSubscription/Extension
- * subtree
- * @param config Instance of {@link PasspointConfiguration}
- * @throws ParsingException
- */
- private static void parseExtension(PPSNode node, PasspointConfiguration config)
- throws ParsingException {
- if (node.isLeaf()) {
- throw new ParsingException("Leaf node not expected for Extension");
- }
- for (PPSNode child : node.getChildren()) {
- switch (child.getName()) {
- case NODE_VENDOR_ANDROID:
- parseVendorAndroidExtension(child, config);
- break;
- default:
- // Unknown nodes under Extension won't raise exception.
- // This allows adding new nodes in the future and
- // won't break older release.
- Log.w(TAG, "Unknown node under Extension: " + child.getName());
- }
- }
- }
-
- /**
- * Convert a hex string to a byte array.
- *
- * @param str String containing hex values
- * @return byte[]
- * @throws ParsingException
- */
- private static byte[] parseHexString(String str) throws ParsingException {
- if ((str.length() & 1) == 1) {
- throw new ParsingException("Odd length hex string: " + str + ", length: "
- + str.length());
- }
-
- byte[] result = new byte[str.length() / 2];
- for (int i = 0; i < result.length; i++) {
- int index = i * 2;
- try {
- result[i] = (byte) Integer.parseInt(str.substring(index, index + 2), 16);
- } catch (NumberFormatException e) {
- throw new ParsingException("Invalid hex string: " + str);
- }
- }
- return result;
- }
-
- /**
- * Convert a date string to the number of milliseconds since January 1, 1970, 00:00:00 GMT.
- *
- * @param dateStr String in the format of yyyy-MM-dd'T'HH:mm:ss'Z'
- * @return number of milliseconds
- * @throws ParsingException
- */
- private static long parseDate(String dateStr) throws ParsingException {
- try {
- DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
- return format.parse(dateStr).getTime();
- } catch (ParseException pe) {
- throw new ParsingException("Badly formatted time: " + dateStr);
- }
- }
-
- /**
- * Parse an integer string.
- *
- * @param value String of integer value
- * @return int
- * @throws ParsingException
- */
- private static int parseInteger(String value) throws ParsingException {
- try {
- return Integer.parseInt(value);
- } catch (NumberFormatException e) {
- throw new ParsingException("Invalid integer value: " + value);
- }
- }
-
- /**
- * Parse a string representing a long integer.
- *
- * @param value String of long integer value
- * @return long
- * @throws ParsingException
- */
- private static long parseLong(String value, int radix) throws ParsingException {
- try {
- return Long.parseLong(value, radix);
- } catch (NumberFormatException e) {
- throw new ParsingException("Invalid long integer value: " + value);
- }
- }
-
- /**
- * Convert a List<Long> to a primitive long array long[].
- *
- * @param list List to be converted
- * @return long[]
- */
- private static long[] convertFromLongList(List<Long> list) {
- Long[] objectArray = list.toArray(new Long[list.size()]);
- long[] primitiveArray = new long[objectArray.length];
- for (int i = 0; i < objectArray.length; i++) {
- primitiveArray[i] = objectArray[i].longValue();
- }
- return primitiveArray;
- }
-}
diff --git a/wifi/java/android/net/wifi/hotspot2/omadm/XMLNode.java b/wifi/java/android/net/wifi/hotspot2/omadm/XMLNode.java
deleted file mode 100644
index 959d5057e257..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/omadm/XMLNode.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * Copyright (c) 2016, 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.hotspot2.omadm;
-
-import android.text.TextUtils;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * A class represent a node in an XML tree. Each node is an XML element.
- * Used by {@link XMLParser} for parsing/converting each XML element to XMLNode.
- *
- * @hide
- */
-public class XMLNode {
- private final String mTag;
- private final List<XMLNode> mChildren;
- private final XMLNode mParent;
- private StringBuilder mTextBuilder;
- private String mText;
-
- public XMLNode(XMLNode parent, String tag) {
- mTag = tag;
- mParent = parent;
- mChildren = new ArrayList<>();
- mTextBuilder = new StringBuilder();
- mText = null;
- }
-
- /**
- * Adding a text to this node. Invoked by {@link XMLParser#characters}.
- *
- * @param text String to be added
- */
- public void addText(String text) {
- mTextBuilder.append(text);
- }
-
- /**
- * Adding a child node to this node. Invoked by {@link XMLParser#startElement}.
- *
- * @param child XMLNode to be added
- */
- public void addChild(XMLNode child) {
- mChildren.add(child);
- }
-
- /**
- * Invoked when the end of the XML element is detected. Used for further processing
- * of the text enclosed within this XML element. Invoked by {@link XMLParser#endElement}.
- */
- public void close() {
- // Remove the leading and the trailing whitespaces.
- mText = mTextBuilder.toString().trim();
- mTextBuilder = null;
- }
-
- public String getTag() {
- return mTag;
- }
-
- public XMLNode getParent() {
- return mParent;
- }
-
- public String getText() {
- return mText;
- }
-
- public List<XMLNode> getChildren() {
- return mChildren;
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof XMLNode)) {
- return false;
- }
- XMLNode that = (XMLNode) thatObject;
-
- return TextUtils.equals(mTag, that.mTag) &&
- TextUtils.equals(mText, that.mText) &&
- mChildren.equals(that.mChildren);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mTag, mText, mChildren);
- }
-}
diff --git a/wifi/java/android/net/wifi/hotspot2/omadm/XMLParser.java b/wifi/java/android/net/wifi/hotspot2/omadm/XMLParser.java
deleted file mode 100644
index 948052c9bf8a..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/omadm/XMLParser.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2016 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.hotspot2.omadm;
-
-import org.xml.sax.Attributes;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
-import android.text.TextUtils;
-
-import java.io.IOException;
-import java.io.StringReader;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-/**
- * Class for parsing an XML string to an XML tree represented by {@link XMLNode}.
- *
- * The original XML string:
- * <root>
- * <tag1>text1</tag1>
- * <tag2>
- * <tag3>text3</tag3>
- * </tag2>
- * </root>
- *
- * The XML tree representation:
- * [root]
- * |
- * |
- * [tag1, text1]-----|-----[tag2]
- * |
- * |
- * [tag3, text3]
- *
- * @hide
- */
-public class XMLParser extends DefaultHandler {
- private XMLNode mRoot = null;
- private XMLNode mCurrent = null;
-
- public XMLNode parse(String text) throws IOException, SAXException {
- if (TextUtils.isEmpty(text)) {
- throw new IOException("XML string not provided");
- }
-
- // Reset pointers.
- mRoot = null;
- mCurrent = null;
-
- try {
- SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
- parser.parse(new InputSource(new StringReader(text)), this);
- return mRoot;
- } catch (ParserConfigurationException pce) {
- throw new SAXException(pce);
- }
- }
-
- @Override
- public void startElement(String uri, String localName, String qName, Attributes attributes)
- throws SAXException {
- XMLNode parent = mCurrent;
-
- mCurrent = new XMLNode(parent, qName);
-
- if (mRoot == null) {
- mRoot = mCurrent;
- } else if (parent == null) {
- throw new SAXException("More than one root nodes");
- } else {
- parent.addChild(mCurrent);
- }
- }
-
- @Override
- public void endElement(String uri, String localName, String qName) throws SAXException {
- if (!qName.equals(mCurrent.getTag())) {
- throw new SAXException("End tag '" + qName + "' doesn't match current node: " +
- mCurrent);
- }
-
- mCurrent.close();
- mCurrent = mCurrent.getParent();
- }
-
- @Override
- public void characters(char[] ch, int start, int length) throws SAXException {
- mCurrent.addText(new String(ch, start, length));
- }
-}
diff --git a/wifi/java/android/net/wifi/hotspot2/pps/Credential.java b/wifi/java/android/net/wifi/hotspot2/pps/Credential.java
deleted file mode 100644
index 282757ac5a14..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/pps/Credential.java
+++ /dev/null
@@ -1,1313 +0,0 @@
-/**
- * Copyright (c) 2016, 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.hotspot2.pps;
-
-import android.net.wifi.EAPConstants;
-import android.net.wifi.ParcelUtil;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.nio.charset.StandardCharsets;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.Objects;
-import java.util.Set;
-
-/**
- * Class representing Credential subtree in the PerProviderSubscription (PPS)
- * Management Object (MO) tree.
- * For more info, refer to Hotspot 2.0 PPS MO defined in section 9.1 of the Hotspot 2.0
- * Release 2 Technical Specification.
- *
- * In addition to the fields in the Credential subtree, this will also maintain necessary
- * information for the private key and certificates associated with this credential.
- */
-public final class Credential implements Parcelable {
- private static final String TAG = "Credential";
-
- /**
- * Max string length for realm. Refer to Credential/Realm node in Hotspot 2.0 Release 2
- * Technical Specification Section 9.1 for more info.
- */
- private static final int MAX_REALM_BYTES = 253;
-
- /**
- * The time this credential is created. It is in the format of number
- * of milliseconds since January 1, 1970, 00:00:00 GMT.
- * Using Long.MIN_VALUE to indicate unset value.
- */
- private long mCreationTimeInMillis = Long.MIN_VALUE;
- /**
- * @hide
- */
- public void setCreationTimeInMillis(long creationTimeInMillis) {
- mCreationTimeInMillis = creationTimeInMillis;
- }
- /**
- * @hide
- */
- public long getCreationTimeInMillis() {
- return mCreationTimeInMillis;
- }
-
- /**
- * The time this credential will expire. It is in the format of number
- * of milliseconds since January 1, 1970, 00:00:00 GMT.
- * Using Long.MIN_VALUE to indicate unset value.
- */
- private long mExpirationTimeInMillis = Long.MIN_VALUE;
- /**
- * @hide
- */
- public void setExpirationTimeInMillis(long expirationTimeInMillis) {
- mExpirationTimeInMillis = expirationTimeInMillis;
- }
- /**
- * @hide
- */
- public long getExpirationTimeInMillis() {
- return mExpirationTimeInMillis;
- }
-
- /**
- * The realm associated with this credential. It will be used to determine
- * if this credential can be used to authenticate with a given hotspot by
- * comparing the realm specified in that hotspot's ANQP element.
- */
- private String mRealm = null;
- /**
- * Set the realm associated with this credential.
- *
- * @param realm The realm to set to
- */
- public void setRealm(String realm) {
- mRealm = realm;
- }
- /**
- * Get the realm associated with this credential.
- *
- * @return the realm associated with this credential
- */
- public String getRealm() {
- return mRealm;
- }
-
- /**
- * When set to true, the device should check AAA (Authentication, Authorization,
- * and Accounting) server's certificate during EAP (Extensible Authentication
- * Protocol) authentication.
- */
- private boolean mCheckAaaServerCertStatus = false;
- /**
- * @hide
- */
- public void setCheckAaaServerCertStatus(boolean checkAaaServerCertStatus) {
- mCheckAaaServerCertStatus = checkAaaServerCertStatus;
- }
- /**
- * @hide
- */
- public boolean getCheckAaaServerCertStatus() {
- return mCheckAaaServerCertStatus;
- }
-
- /**
- * Username-password based credential.
- * Contains the fields under PerProviderSubscription/Credential/UsernamePassword subtree.
- */
- public static final class UserCredential implements Parcelable {
- /**
- * Maximum string length for username. Refer to Credential/UsernamePassword/Username
- * node in Hotspot 2.0 Release 2 Technical Specification Section 9.1 for more info.
- */
- private static final int MAX_USERNAME_BYTES = 63;
-
- /**
- * Maximum string length for password. Refer to Credential/UsernamePassword/Password
- * in Hotspot 2.0 Release 2 Technical Specification Section 9.1 for more info.
- */
- private static final int MAX_PASSWORD_BYTES = 255;
-
- /**
- * Supported authentication methods.
- * @hide
- */
- public static final String AUTH_METHOD_PAP = "PAP";
- /** @hide */
- public static final String AUTH_METHOD_MSCHAP = "MS-CHAP";
- /** @hide */
- public static final String AUTH_METHOD_MSCHAPV2 = "MS-CHAP-V2";
-
- /**
- * Supported Non-EAP inner methods. Refer to
- * Credential/UsernamePassword/EAPMethod/InnerEAPType in Hotspot 2.0 Release 2 Technical
- * Specification Section 9.1 for more info.
- */
- private static final Set<String> SUPPORTED_AUTH = new HashSet<String>(
- Arrays.asList(AUTH_METHOD_PAP, AUTH_METHOD_MSCHAP, AUTH_METHOD_MSCHAPV2));
-
- /**
- * Username of the credential.
- */
- private String mUsername = null;
- /**
- * Set the username associated with this user credential.
- *
- * @param username The username to set to
- */
- public void setUsername(String username) {
- mUsername = username;
- }
- /**
- * Get the username associated with this user credential.
- *
- * @return the username associated with this user credential
- */
- public String getUsername() {
- return mUsername;
- }
-
- /**
- * Base64-encoded password.
- */
- private String mPassword = null;
- /**
- * Set the Base64-encoded password associated with this user credential.
- *
- * @param password The password to set to
- */
- public void setPassword(String password) {
- mPassword = password;
- }
- /**
- * Get the Base64-encoded password associated with this user credential.
- *
- * @return the Base64-encoded password associated with this user credential
- */
- public String getPassword() {
- return mPassword;
- }
-
- /**
- * Flag indicating if the password is machine managed.
- */
- private boolean mMachineManaged = false;
- /**
- * @hide
- */
- public void setMachineManaged(boolean machineManaged) {
- mMachineManaged = machineManaged;
- }
- /**
- * @hide
- */
- public boolean getMachineManaged() {
- return mMachineManaged;
- }
-
- /**
- * The name of the application used to generate the password.
- */
- private String mSoftTokenApp = null;
- /**
- * @hide
- */
- public void setSoftTokenApp(String softTokenApp) {
- mSoftTokenApp = softTokenApp;
- }
- /**
- * @hide
- */
- public String getSoftTokenApp() {
- return mSoftTokenApp;
- }
-
- /**
- * Flag indicating if this credential is usable on other mobile devices as well.
- */
- private boolean mAbleToShare = false;
- /**
- * @hide
- */
- public void setAbleToShare(boolean ableToShare) {
- mAbleToShare = ableToShare;
- }
- /**
- * @hide
- */
- public boolean getAbleToShare() {
- return mAbleToShare;
- }
-
- /**
- * EAP (Extensible Authentication Protocol) method type.
- * Refer to
- * <a href="http://www.iana.org/assignments/eap-numbers/eap-numbers.xml#eap-numbers-4">
- * EAP Numbers</a> for valid values.
- * Using Integer.MIN_VALUE to indicate unset value.
- */
- private int mEapType = Integer.MIN_VALUE;
- /**
- * Set the EAP (Extensible Authentication Protocol) method type associated with this
- * user credential.
- * Refer to
- * <a href="http://www.iana.org/assignments/eap-numbers/eap-numbers.xml#eap-numbers-4">
- * EAP Numbers</a> for valid values.
- *
- * @param eapType The EAP method type associated with this user credential
- */
- public void setEapType(int eapType) {
- mEapType = eapType;
- }
- /**
- * Get the EAP (Extensible Authentication Protocol) method type associated with this
- * user credential.
- *
- * @return EAP method type
- */
- public int getEapType() {
- return mEapType;
- }
-
- /**
- * Non-EAP inner authentication method.
- */
- private String mNonEapInnerMethod = null;
- /**
- * Set the inner non-EAP method associated with this user credential.
- *
- * @param nonEapInnerMethod The non-EAP inner method to set to
- */
- public void setNonEapInnerMethod(String nonEapInnerMethod) {
- mNonEapInnerMethod = nonEapInnerMethod;
- }
- /**
- * Get the inner non-EAP method associated with this user credential.
- *
- * @return Non-EAP inner method associated with this user credential
- */
- public String getNonEapInnerMethod() {
- return mNonEapInnerMethod;
- }
-
- /**
- * Constructor for creating UserCredential with default values.
- */
- public UserCredential() {}
-
- /**
- * Copy constructor.
- *
- * @param source The source to copy from
- */
- public UserCredential(UserCredential source) {
- if (source != null) {
- mUsername = source.mUsername;
- mPassword = source.mPassword;
- mMachineManaged = source.mMachineManaged;
- mSoftTokenApp = source.mSoftTokenApp;
- mAbleToShare = source.mAbleToShare;
- mEapType = source.mEapType;
- mNonEapInnerMethod = source.mNonEapInnerMethod;
- }
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(mUsername);
- dest.writeString(mPassword);
- dest.writeInt(mMachineManaged ? 1 : 0);
- dest.writeString(mSoftTokenApp);
- dest.writeInt(mAbleToShare ? 1 : 0);
- dest.writeInt(mEapType);
- dest.writeString(mNonEapInnerMethod);
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof UserCredential)) {
- return false;
- }
-
- UserCredential that = (UserCredential) thatObject;
- return TextUtils.equals(mUsername, that.mUsername)
- && TextUtils.equals(mPassword, that.mPassword)
- && mMachineManaged == that.mMachineManaged
- && TextUtils.equals(mSoftTokenApp, that.mSoftTokenApp)
- && mAbleToShare == that.mAbleToShare
- && mEapType == that.mEapType
- && TextUtils.equals(mNonEapInnerMethod, that.mNonEapInnerMethod);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mUsername, mPassword, mMachineManaged, mSoftTokenApp,
- mAbleToShare, mEapType, mNonEapInnerMethod);
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("Username: ").append(mUsername).append("\n");
- builder.append("MachineManaged: ").append(mMachineManaged).append("\n");
- builder.append("SoftTokenApp: ").append(mSoftTokenApp).append("\n");
- builder.append("AbleToShare: ").append(mAbleToShare).append("\n");
- builder.append("EAPType: ").append(mEapType).append("\n");
- builder.append("AuthMethod: ").append(mNonEapInnerMethod).append("\n");
- return builder.toString();
- }
-
- /**
- * Validate the configuration data.
- *
- * @return true on success or false on failure
- * @hide
- */
- public boolean validate() {
- if (TextUtils.isEmpty(mUsername)) {
- Log.d(TAG, "Missing username");
- return false;
- }
- if (mUsername.getBytes(StandardCharsets.UTF_8).length > MAX_USERNAME_BYTES) {
- Log.d(TAG, "username exceeding maximum length: "
- + mUsername.getBytes(StandardCharsets.UTF_8).length);
- return false;
- }
-
- if (TextUtils.isEmpty(mPassword)) {
- Log.d(TAG, "Missing password");
- return false;
- }
- if (mPassword.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) {
- Log.d(TAG, "password exceeding maximum length: "
- + mPassword.getBytes(StandardCharsets.UTF_8).length);
- return false;
- }
-
- // Only supports EAP-TTLS for user credential.
- if (mEapType != EAPConstants.EAP_TTLS) {
- Log.d(TAG, "Invalid EAP Type for user credential: " + mEapType);
- return false;
- }
-
- // Verify Non-EAP inner method for EAP-TTLS.
- if (!SUPPORTED_AUTH.contains(mNonEapInnerMethod)) {
- Log.d(TAG, "Invalid non-EAP inner method for EAP-TTLS: " + mNonEapInnerMethod);
- return false;
- }
- return true;
- }
-
- public static final @android.annotation.NonNull Creator<UserCredential> CREATOR =
- new Creator<UserCredential>() {
- @Override
- public UserCredential createFromParcel(Parcel in) {
- UserCredential userCredential = new UserCredential();
- userCredential.setUsername(in.readString());
- userCredential.setPassword(in.readString());
- userCredential.setMachineManaged(in.readInt() != 0);
- userCredential.setSoftTokenApp(in.readString());
- userCredential.setAbleToShare(in.readInt() != 0);
- userCredential.setEapType(in.readInt());
- userCredential.setNonEapInnerMethod(in.readString());
- return userCredential;
- }
-
- @Override
- public UserCredential[] newArray(int size) {
- return new UserCredential[size];
- }
- };
-
- /**
- * Get a unique identifier for UserCredential.
- *
- * @hide
- * @return a Unique identifier for a UserCredential object
- */
- public int getUniqueId() {
- return Objects.hash(mUsername);
- }
- }
- private UserCredential mUserCredential = null;
- /**
- * Set the user credential information.
- *
- * @param userCredential The user credential to set to
- */
- public void setUserCredential(UserCredential userCredential) {
- mUserCredential = userCredential;
- }
- /**
- * Get the user credential information.
- *
- * @return user credential information
- */
- public UserCredential getUserCredential() {
- return mUserCredential;
- }
-
- /**
- * Certificate based credential. This is used for EAP-TLS.
- * Contains fields under PerProviderSubscription/Credential/DigitalCertificate subtree.
- */
- public static final class CertificateCredential implements Parcelable {
- /**
- * Supported certificate types.
- * @hide
- */
- public static final String CERT_TYPE_X509V3 = "x509v3";
-
- /**
- * Certificate SHA-256 fingerprint length.
- */
- private static final int CERT_SHA256_FINGER_PRINT_LENGTH = 32;
-
- /**
- * Certificate type.
- */
- private String mCertType = null;
- /**
- * Set the certificate type associated with this certificate credential.
- *
- * @param certType The certificate type to set to
- */
- public void setCertType(String certType) {
- mCertType = certType;
- }
- /**
- * Get the certificate type associated with this certificate credential.
- *
- * @return certificate type
- */
- public String getCertType() {
- return mCertType;
- }
-
- /**
- * The SHA-256 fingerprint of the certificate.
- */
- private byte[] mCertSha256Fingerprint = null;
- /**
- * Set the certificate SHA-256 fingerprint associated with this certificate credential.
- *
- * @param certSha256Fingerprint The certificate fingerprint to set to
- */
- public void setCertSha256Fingerprint(byte[] certSha256Fingerprint) {
- mCertSha256Fingerprint = certSha256Fingerprint;
- }
- /**
- * Get the certificate SHA-256 fingerprint associated with this certificate credential.
- *
- * @return certificate SHA-256 fingerprint
- */
- public byte[] getCertSha256Fingerprint() {
- return mCertSha256Fingerprint;
- }
-
- /**
- * Constructor for creating CertificateCredential with default values.
- */
- public CertificateCredential() {}
-
- /**
- * Copy constructor.
- *
- * @param source The source to copy from
- */
- public CertificateCredential(CertificateCredential source) {
- if (source != null) {
- mCertType = source.mCertType;
- if (source.mCertSha256Fingerprint != null) {
- mCertSha256Fingerprint = Arrays.copyOf(source.mCertSha256Fingerprint,
- source.mCertSha256Fingerprint.length);
- }
- }
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(mCertType);
- dest.writeByteArray(mCertSha256Fingerprint);
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof CertificateCredential)) {
- return false;
- }
-
- CertificateCredential that = (CertificateCredential) thatObject;
- return TextUtils.equals(mCertType, that.mCertType)
- && Arrays.equals(mCertSha256Fingerprint, that.mCertSha256Fingerprint);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mCertType, Arrays.hashCode(mCertSha256Fingerprint));
- }
-
- @Override
- public String toString() {
- return "CertificateType: " + mCertType + "\n";
- }
-
- /**
- * Validate the configuration data.
- *
- * @return true on success or false on failure
- * @hide
- */
- public boolean validate() {
- if (!TextUtils.equals(CERT_TYPE_X509V3, mCertType)) {
- Log.d(TAG, "Unsupported certificate type: " + mCertType);
- return false;
- }
- if (mCertSha256Fingerprint == null
- || mCertSha256Fingerprint.length != CERT_SHA256_FINGER_PRINT_LENGTH) {
- Log.d(TAG, "Invalid SHA-256 fingerprint");
- return false;
- }
- return true;
- }
-
- public static final @android.annotation.NonNull Creator<CertificateCredential> CREATOR =
- new Creator<CertificateCredential>() {
- @Override
- public CertificateCredential createFromParcel(Parcel in) {
- CertificateCredential certCredential = new CertificateCredential();
- certCredential.setCertType(in.readString());
- certCredential.setCertSha256Fingerprint(in.createByteArray());
- return certCredential;
- }
-
- @Override
- public CertificateCredential[] newArray(int size) {
- return new CertificateCredential[size];
- }
- };
- }
- private CertificateCredential mCertCredential = null;
- /**
- * Set the certificate credential information.
- *
- * @param certCredential The certificate credential to set to
- */
- public void setCertCredential(CertificateCredential certCredential) {
- mCertCredential = certCredential;
- }
- /**
- * Get the certificate credential information.
- *
- * @return certificate credential information
- */
- public CertificateCredential getCertCredential() {
- return mCertCredential;
- }
-
- /**
- * SIM (Subscriber Identify Module) based credential.
- * Contains fields under PerProviderSubscription/Credential/SIM subtree.
- */
- public static final class SimCredential implements Parcelable {
- /**
- * Maximum string length for IMSI.
- */
- private static final int MAX_IMSI_LENGTH = 15;
-
- /**
- * International Mobile Subscriber Identity, is used to identify the user
- * of a cellular network and is a unique identification associated with all
- * cellular networks
- */
- private String mImsi = null;
- /**
- * Set the IMSI (International Mobile Subscriber Identity) associated with this SIM
- * credential.
- *
- * @param imsi The IMSI to set to
- */
- public void setImsi(String imsi) {
- mImsi = imsi;
- }
- /**
- * Get the IMSI (International Mobile Subscriber Identity) associated with this SIM
- * credential.
- *
- * @return IMSI associated with this SIM credential
- */
- public String getImsi() {
- return mImsi;
- }
-
- /**
- * EAP (Extensible Authentication Protocol) method type for using SIM credential.
- * Refer to http://www.iana.org/assignments/eap-numbers/eap-numbers.xml#eap-numbers-4
- * for valid values.
- * Using Integer.MIN_VALUE to indicate unset value.
- */
- private int mEapType = Integer.MIN_VALUE;
- /**
- * Set the EAP (Extensible Authentication Protocol) method type associated with this
- * SIM credential.
- *
- * @param eapType The EAP method type to set to
- */
- public void setEapType(int eapType) {
- mEapType = eapType;
- }
- /**
- * Get the EAP (Extensible Authentication Protocol) method type associated with this
- * SIM credential.
- *
- * @return EAP method type associated with this SIM credential
- */
- public int getEapType() {
- return mEapType;
- }
-
- /**
- * Constructor for creating SimCredential with default values.
- */
- public SimCredential() {}
-
- /**
- * Copy constructor
- *
- * @param source The source to copy from
- */
- public SimCredential(SimCredential source) {
- if (source != null) {
- mImsi = source.mImsi;
- mEapType = source.mEapType;
- }
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof SimCredential)) {
- return false;
- }
-
- SimCredential that = (SimCredential) thatObject;
- return TextUtils.equals(mImsi, that.mImsi)
- && mEapType == that.mEapType;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mImsi, mEapType);
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- String imsi;
- if (mImsi != null) {
- if (mImsi.length() > 6 && mImsi.charAt(6) != '*') {
- // Truncate the full IMSI from the log
- imsi = mImsi.substring(0, 6) + "****";
- } else {
- imsi = mImsi;
- }
- builder.append("IMSI: ").append(imsi).append("\n");
- }
- builder.append("EAPType: ").append(mEapType).append("\n");
- return builder.toString();
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(mImsi);
- dest.writeInt(mEapType);
- }
-
- /**
- * Validate the configuration data.
- *
- * @return true on success or false on failure
- * @hide
- */
- public boolean validate() {
- // Note: this only validate the format of IMSI string itself. Additional verification
- // will be done by WifiService at the time of provisioning to verify against the IMSI
- // of the SIM card installed in the device.
- if (!verifyImsi()) {
- return false;
- }
- if (mEapType != EAPConstants.EAP_SIM && mEapType != EAPConstants.EAP_AKA
- && mEapType != EAPConstants.EAP_AKA_PRIME) {
- Log.d(TAG, "Invalid EAP Type for SIM credential: " + mEapType);
- return false;
- }
- return true;
- }
-
- public static final @android.annotation.NonNull Creator<SimCredential> CREATOR =
- new Creator<SimCredential>() {
- @Override
- public SimCredential createFromParcel(Parcel in) {
- SimCredential simCredential = new SimCredential();
- simCredential.setImsi(in.readString());
- simCredential.setEapType(in.readInt());
- return simCredential;
- }
-
- @Override
- public SimCredential[] newArray(int size) {
- return new SimCredential[size];
- }
- };
-
- /**
- * Verify the IMSI (International Mobile Subscriber Identity) string. The string
- * should contain zero or more numeric digits, and might ends with a "*" for prefix
- * matching.
- *
- * @return true if IMSI is valid, false otherwise.
- */
- private boolean verifyImsi() {
- if (TextUtils.isEmpty(mImsi)) {
- Log.d(TAG, "Missing IMSI");
- return false;
- }
- if (mImsi.length() > MAX_IMSI_LENGTH) {
- Log.d(TAG, "IMSI exceeding maximum length: " + mImsi.length());
- return false;
- }
-
- // Locate the first non-digit character.
- int nonDigit;
- char stopChar = '\0';
- for (nonDigit = 0; nonDigit < mImsi.length(); nonDigit++) {
- stopChar = mImsi.charAt(nonDigit);
- if (stopChar < '0' || stopChar > '9') {
- break;
- }
- }
-
- if (nonDigit == mImsi.length()) {
- return true;
- }
- else if (nonDigit == mImsi.length()-1 && stopChar == '*') {
- // Prefix matching.
- return true;
- }
- return false;
- }
- }
- private SimCredential mSimCredential = null;
- /**
- * Set the SIM credential information.
- *
- * @param simCredential The SIM credential to set to
- */
- public void setSimCredential(SimCredential simCredential) {
- mSimCredential = simCredential;
- }
- /**
- * Get the SIM credential information.
- *
- * @return SIM credential information
- */
- public SimCredential getSimCredential() {
- return mSimCredential;
- }
-
- /**
- * CA (Certificate Authority) X509 certificates.
- */
- private X509Certificate[] mCaCertificates = null;
-
- /**
- * Set the CA (Certification Authority) certificate associated with this credential.
- *
- * @param caCertificate The CA certificate to set to
- */
- public void setCaCertificate(X509Certificate caCertificate) {
- mCaCertificates = null;
- if (caCertificate != null) {
- mCaCertificates = new X509Certificate[] {caCertificate};
- }
- }
-
- /**
- * Set the CA (Certification Authority) certificates associated with this credential.
- *
- * @param caCertificates The list of CA certificates to set to
- * @hide
- */
- public void setCaCertificates(X509Certificate[] caCertificates) {
- mCaCertificates = caCertificates;
- }
-
- /**
- * Get the CA (Certification Authority) certificate associated with this credential.
- *
- * @return CA certificate associated with this credential, {@code null} if certificate is not
- * set or certificate is more than one.
- */
- public X509Certificate getCaCertificate() {
- return mCaCertificates == null || mCaCertificates.length > 1 ? null : mCaCertificates[0];
- }
-
- /**
- * Get the CA (Certification Authority) certificates associated with this credential.
- *
- * @return The list of CA certificates associated with this credential
- * @hide
- */
- public X509Certificate[] getCaCertificates() {
- return mCaCertificates;
- }
-
- /**
- * Client side X509 certificate chain.
- */
- private X509Certificate[] mClientCertificateChain = null;
- /**
- * Set the client certificate chain associated with this credential.
- *
- * @param certificateChain The client certificate chain to set to
- */
- public void setClientCertificateChain(X509Certificate[] certificateChain) {
- mClientCertificateChain = certificateChain;
- }
- /**
- * Get the client certificate chain associated with this credential.
- *
- * @return client certificate chain associated with this credential
- */
- public X509Certificate[] getClientCertificateChain() {
- return mClientCertificateChain;
- }
-
- /**
- * Client side private key.
- */
- private PrivateKey mClientPrivateKey = null;
- /**
- * Set the client private key associated with this credential.
- *
- * @param clientPrivateKey the client private key to set to
- */
- public void setClientPrivateKey(PrivateKey clientPrivateKey) {
- mClientPrivateKey = clientPrivateKey;
- }
- /**
- * Get the client private key associated with this credential.
- *
- * @return client private key associated with this credential.
- */
- public PrivateKey getClientPrivateKey() {
- return mClientPrivateKey;
- }
-
- /**
- * Constructor for creating Credential with default values.
- */
- public Credential() {}
-
- /**
- * Copy constructor.
- *
- * @param source The source to copy from
- */
- public Credential(Credential source) {
- if (source != null) {
- mCreationTimeInMillis = source.mCreationTimeInMillis;
- mExpirationTimeInMillis = source.mExpirationTimeInMillis;
- mRealm = source.mRealm;
- mCheckAaaServerCertStatus = source.mCheckAaaServerCertStatus;
- if (source.mUserCredential != null) {
- mUserCredential = new UserCredential(source.mUserCredential);
- }
- if (source.mCertCredential != null) {
- mCertCredential = new CertificateCredential(source.mCertCredential);
- }
- if (source.mSimCredential != null) {
- mSimCredential = new SimCredential(source.mSimCredential);
- }
- if (source.mClientCertificateChain != null) {
- mClientCertificateChain = Arrays.copyOf(source.mClientCertificateChain,
- source.mClientCertificateChain.length);
- }
- if (source.mCaCertificates != null) {
- mCaCertificates = Arrays.copyOf(source.mCaCertificates,
- source.mCaCertificates.length);
- }
-
- mClientPrivateKey = source.mClientPrivateKey;
- }
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeLong(mCreationTimeInMillis);
- dest.writeLong(mExpirationTimeInMillis);
- dest.writeString(mRealm);
- dest.writeInt(mCheckAaaServerCertStatus ? 1 : 0);
- dest.writeParcelable(mUserCredential, flags);
- dest.writeParcelable(mCertCredential, flags);
- dest.writeParcelable(mSimCredential, flags);
- ParcelUtil.writeCertificates(dest, mCaCertificates);
- ParcelUtil.writeCertificates(dest, mClientCertificateChain);
- ParcelUtil.writePrivateKey(dest, mClientPrivateKey);
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof Credential)) {
- return false;
- }
-
- Credential that = (Credential) thatObject;
- return TextUtils.equals(mRealm, that.mRealm)
- && mCreationTimeInMillis == that.mCreationTimeInMillis
- && mExpirationTimeInMillis == that.mExpirationTimeInMillis
- && mCheckAaaServerCertStatus == that.mCheckAaaServerCertStatus
- && (mUserCredential == null ? that.mUserCredential == null
- : mUserCredential.equals(that.mUserCredential))
- && (mCertCredential == null ? that.mCertCredential == null
- : mCertCredential.equals(that.mCertCredential))
- && (mSimCredential == null ? that.mSimCredential == null
- : mSimCredential.equals(that.mSimCredential))
- && isX509CertificatesEquals(mCaCertificates, that.mCaCertificates)
- && isX509CertificatesEquals(mClientCertificateChain, that.mClientCertificateChain)
- && isPrivateKeyEquals(mClientPrivateKey, that.mClientPrivateKey);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mCreationTimeInMillis, mExpirationTimeInMillis, mRealm,
- mCheckAaaServerCertStatus, mUserCredential, mCertCredential, mSimCredential,
- mClientPrivateKey, Arrays.hashCode(mCaCertificates),
- Arrays.hashCode(mClientCertificateChain));
- }
-
- /**
- * Get a unique identifier for Credential. This identifier depends only on items that remain
- * constant throughout the lifetime of a subscription's credentials.
- *
- * @hide
- * @return a Unique identifier for a Credential object
- */
- public int getUniqueId() {
- return Objects.hash(mUserCredential != null ? mUserCredential.getUniqueId() : 0,
- mCertCredential, mSimCredential, mRealm);
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("Realm: ").append(mRealm).append("\n");
- builder.append("CreationTime: ").append(mCreationTimeInMillis != Long.MIN_VALUE
- ? new Date(mCreationTimeInMillis) : "Not specified").append("\n");
- builder.append("ExpirationTime: ").append(mExpirationTimeInMillis != Long.MIN_VALUE
- ? new Date(mExpirationTimeInMillis) : "Not specified").append("\n");
- builder.append("CheckAAAServerStatus: ").append(mCheckAaaServerCertStatus).append("\n");
- if (mUserCredential != null) {
- builder.append("UserCredential Begin ---\n");
- builder.append(mUserCredential);
- builder.append("UserCredential End ---\n");
- }
- if (mCertCredential != null) {
- builder.append("CertificateCredential Begin ---\n");
- builder.append(mCertCredential);
- builder.append("CertificateCredential End ---\n");
- }
- if (mSimCredential != null) {
- builder.append("SIMCredential Begin ---\n");
- builder.append(mSimCredential);
- builder.append("SIMCredential End ---\n");
- }
- return builder.toString();
- }
-
- /**
- * Validate the configuration data.
- *
- * @return true on success or false on failure
- * @hide
- */
- public boolean validate() {
- if (TextUtils.isEmpty(mRealm)) {
- Log.d(TAG, "Missing realm");
- return false;
- }
- if (mRealm.getBytes(StandardCharsets.UTF_8).length > MAX_REALM_BYTES) {
- Log.d(TAG, "realm exceeding maximum length: "
- + mRealm.getBytes(StandardCharsets.UTF_8).length);
- return false;
- }
-
- // Verify the credential.
- if (mUserCredential != null) {
- if (!verifyUserCredential()) {
- return false;
- }
- } else if (mCertCredential != null) {
- if (!verifyCertCredential()) {
- return false;
- }
- } else if (mSimCredential != null) {
- if (!verifySimCredential()) {
- return false;
- }
- } else {
- Log.d(TAG, "Missing required credential");
- return false;
- }
-
- return true;
- }
-
- public static final @android.annotation.NonNull Creator<Credential> CREATOR =
- new Creator<Credential>() {
- @Override
- public Credential createFromParcel(Parcel in) {
- Credential credential = new Credential();
- credential.setCreationTimeInMillis(in.readLong());
- credential.setExpirationTimeInMillis(in.readLong());
- credential.setRealm(in.readString());
- credential.setCheckAaaServerCertStatus(in.readInt() != 0);
- credential.setUserCredential(in.readParcelable(null));
- credential.setCertCredential(in.readParcelable(null));
- credential.setSimCredential(in.readParcelable(null));
- credential.setCaCertificates(ParcelUtil.readCertificates(in));
- credential.setClientCertificateChain(ParcelUtil.readCertificates(in));
- credential.setClientPrivateKey(ParcelUtil.readPrivateKey(in));
- return credential;
- }
-
- @Override
- public Credential[] newArray(int size) {
- return new Credential[size];
- }
- };
-
- /**
- * Verify user credential.
- * If no CA certificate is provided, then the system uses the CAs in the trust store.
- *
- * @return true if user credential is valid, false otherwise.
- */
- private boolean verifyUserCredential() {
- if (mUserCredential == null) {
- Log.d(TAG, "Missing user credential");
- return false;
- }
- if (mCertCredential != null || mSimCredential != null) {
- Log.d(TAG, "Contained more than one type of credential");
- return false;
- }
- if (!mUserCredential.validate()) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Verify certificate credential, which is used for EAP-TLS. This will verify
- * that the necessary client key and certificates are provided.
- * If no CA certificate is provided, then the system uses the CAs in the trust store.
- *
- * @return true if certificate credential is valid, false otherwise.
- */
- private boolean verifyCertCredential() {
- if (mCertCredential == null) {
- Log.d(TAG, "Missing certificate credential");
- return false;
- }
- if (mUserCredential != null || mSimCredential != null) {
- Log.d(TAG, "Contained more than one type of credential");
- return false;
- }
-
- if (!mCertCredential.validate()) {
- return false;
- }
-
- if (mClientPrivateKey == null) {
- Log.d(TAG, "Missing client private key for certificate credential");
- return false;
- }
- try {
- // Verify SHA-256 fingerprint for client certificate.
- if (!verifySha256Fingerprint(mClientCertificateChain,
- mCertCredential.getCertSha256Fingerprint())) {
- Log.d(TAG, "SHA-256 fingerprint mismatch");
- return false;
- }
- } catch (NoSuchAlgorithmException | CertificateEncodingException e) {
- Log.d(TAG, "Failed to verify SHA-256 fingerprint: " + e.getMessage());
- return false;
- }
-
- return true;
- }
-
- /**
- * Verify SIM credential.
- *
- * @return true if SIM credential is valid, false otherwise.
- */
- private boolean verifySimCredential() {
- if (mSimCredential == null) {
- Log.d(TAG, "Missing SIM credential");
- return false;
- }
- if (mUserCredential != null || mCertCredential != null) {
- Log.d(TAG, "Contained more than one type of credential");
- return false;
- }
- return mSimCredential.validate();
- }
-
- private static boolean isPrivateKeyEquals(PrivateKey key1, PrivateKey key2) {
- if (key1 == null && key2 == null) {
- return true;
- }
-
- /* Return false if only one of them is null */
- if (key1 == null || key2 == null) {
- return false;
- }
-
- return TextUtils.equals(key1.getAlgorithm(), key2.getAlgorithm()) &&
- Arrays.equals(key1.getEncoded(), key2.getEncoded());
- }
-
- /**
- * Verify two X.509 certificates are identical.
- *
- * @param cert1 a certificate to compare
- * @param cert2 a certificate to compare
- * @return {@code true} if given certificates are the same each other, {@code false} otherwise.
- * @hide
- */
- public static boolean isX509CertificateEquals(X509Certificate cert1, X509Certificate cert2) {
- if (cert1 == null && cert2 == null) {
- return true;
- }
-
- /* Return false if only one of them is null */
- if (cert1 == null || cert2 == null) {
- return false;
- }
-
- boolean result = false;
- try {
- result = Arrays.equals(cert1.getEncoded(), cert2.getEncoded());
- } catch (CertificateEncodingException e) {
- /* empty, return false. */
- }
- return result;
- }
-
- private static boolean isX509CertificatesEquals(X509Certificate[] certs1,
- X509Certificate[] certs2) {
- if (certs1 == null && certs2 == null) {
- return true;
- }
-
- /* Return false if only one of them is null */
- if (certs1 == null || certs2 == null) {
- return false;
- }
-
- if (certs1.length != certs2.length) {
- return false;
- }
-
- for (int i = 0; i < certs1.length; i++) {
- if (!isX509CertificateEquals(certs1[i], certs2[i])) {
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * Verify that the digest for a certificate in the certificate chain matches expected
- * fingerprint. The certificate that matches the fingerprint is the client certificate.
- *
- * @param certChain Chain of certificates
- * @param expectedFingerprint The expected SHA-256 digest of the client certificate
- * @return true if the certificate chain contains a matching certificate, false otherwise
- * @throws NoSuchAlgorithmException
- * @throws CertificateEncodingException
- */
- private static boolean verifySha256Fingerprint(X509Certificate[] certChain,
- byte[] expectedFingerprint)
- throws NoSuchAlgorithmException, CertificateEncodingException {
- if (certChain == null) {
- return false;
- }
- MessageDigest digester = MessageDigest.getInstance("SHA-256");
- for (X509Certificate certificate : certChain) {
- digester.reset();
- byte[] fingerprint = digester.digest(certificate.getEncoded());
- if (Arrays.equals(expectedFingerprint, fingerprint)) {
- return true;
- }
- }
- return false;
- }
-}
diff --git a/wifi/java/android/net/wifi/hotspot2/pps/HomeSp.java b/wifi/java/android/net/wifi/hotspot2/pps/HomeSp.java
deleted file mode 100644
index 64aad613c8b2..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/pps/HomeSp.java
+++ /dev/null
@@ -1,491 +0,0 @@
-/**
- * Copyright (c) 2016, 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.hotspot2.pps;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-
-/**
- * Class representing HomeSP subtree in PerProviderSubscription (PPS)
- * Management Object (MO) tree.
- *
- * For more info, refer to Hotspot 2.0 PPS MO defined in section 9.1 of the Hotspot 2.0
- * Release 2 Technical Specification.
- */
-public final class HomeSp implements Parcelable {
- private static final String TAG = "HomeSp";
-
- /**
- * Maximum number of bytes allowed for a SSID.
- */
- private static final int MAX_SSID_BYTES = 32;
-
- /**
- * Integer value used for indicating null value in the Parcel.
- */
- private static final int NULL_VALUE = -1;
-
- /**
- * FQDN (Fully Qualified Domain Name) of this home service provider.
- */
- private String mFqdn = null;
- /**
- * Set the FQDN (Fully Qualified Domain Name) associated with this home service provider.
- *
- * @param fqdn The FQDN to set to
- */
- public void setFqdn(String fqdn) {
- mFqdn = fqdn;
- }
- /**
- * Get the FQDN (Fully Qualified Domain Name) associated with this home service provider.
- *
- * @return the FQDN associated with this home service provider
- */
- public String getFqdn() {
- return mFqdn;
- }
-
- /**
- * Friendly name of this home service provider.
- */
- private String mFriendlyName = null;
- /**
- * Set the friendly name associated with this home service provider.
- *
- * @param friendlyName The friendly name to set to
- */
- public void setFriendlyName(String friendlyName) {
- mFriendlyName = friendlyName;
- }
- /**
- * Get the friendly name associated with this home service provider.
- *
- * @return the friendly name associated with this home service provider
- */
- public String getFriendlyName() {
- return mFriendlyName;
- }
-
- /**
- * Icon URL of this home service provider.
- */
- private String mIconUrl = null;
- /**
- * @hide
- */
- public void setIconUrl(String iconUrl) {
- mIconUrl = iconUrl;
- }
- /**
- * @hide
- */
- public String getIconUrl() {
- return mIconUrl;
- }
-
- /**
- * <SSID, HESSID> duple of the networks that are consider home networks.
- *
- * According to the Section 9.1.2 of the Hotspot 2.0 Release 2 Technical Specification,
- * all nodes in the PSS MO are encoded using UTF-8 unless stated otherwise. Thus, the SSID
- * string is assumed to be encoded using UTF-8.
- */
- private Map<String, Long> mHomeNetworkIds = null;
- /**
- * @hide
- */
- public void setHomeNetworkIds(Map<String, Long> homeNetworkIds) {
- mHomeNetworkIds = homeNetworkIds;
- }
- /**
- * @hide
- */
- public Map<String, Long> getHomeNetworkIds() {
- return mHomeNetworkIds;
- }
-
- /**
- * Used for determining if this provider is a member of a given Hotspot provider.
- * Every Organization Identifiers (OIs) in this list are required to match an OI in the
- * the Roaming Consortium advertised by a Hotspot, in order to consider this provider
- * as a member of that Hotspot provider (e.g. successful authentication with such Hotspot
- * is possible).
- *
- * Refer to HomeSP/HomeOIList subtree in PerProviderSubscription (PPS) Management Object
- * (MO) tree for more detail.
- */
- private long[] mMatchAllOis = null;
-
- /**
- * Set a list of HomeOIs such that all OIs in the list must match an OI in the Roaming
- * Consortium advertised by a hotspot operator. The list set by this API will have precedence
- * over {@link #setMatchAnyOis(long[])}, meaning the list set in {@link #setMatchAnyOis(long[])}
- * will only be used for matching if the list set by this API is null or empty.
- *
- * @param matchAllOis An array of longs containing the HomeOIs
- */
- public void setMatchAllOis(@Nullable long[] matchAllOis) {
- mMatchAllOis = matchAllOis;
- }
-
- /**
- * Get the list of HomeOIs such that all OIs in the list must match an OI in the Roaming
- * Consortium advertised by a hotspot operator.
- *
- * @return An array of longs containing the HomeOIs
- */
- public @Nullable long[] getMatchAllOis() {
- return mMatchAllOis;
- }
-
- /**
- * Used for determining if this provider is a member of a given Hotspot provider.
- * Matching of any Organization Identifiers (OIs) in this list with an OI in the
- * Roaming Consortium advertised by a Hotspot, will consider this provider as a member
- * of that Hotspot provider (e.g. successful authentication with such Hotspot
- * is possible).
- *
- * The list set by {@link #setMatchAllOis(long[])} will have precedence over this one, meaning
- * this list will only be used for matching if the list set by {@link #setMatchAllOis(long[])}
- * is null or empty.
- *
- * Refer to HomeSP/HomeOIList subtree in PerProviderSubscription (PPS) Management Object
- * (MO) tree for more detail.
- */
- private long[] mMatchAnyOis = null;
-
- /**
- * Set a list of HomeOIs such that any OI in the list matches an OI in the Roaming Consortium
- * advertised by a hotspot operator. The list set by {@link #setMatchAllOis(long[])}
- * will have precedence over this API, meaning this list will only be used for matching if the
- * list set by {@link #setMatchAllOis(long[])} is null or empty.
- *
- * @param matchAnyOis An array of longs containing the HomeOIs
- */
- public void setMatchAnyOis(@Nullable long[] matchAnyOis) {
- mMatchAnyOis = matchAnyOis;
- }
-
- /**
- * Get a list of HomeOIs such that any OI in the list matches an OI in the Roaming Consortium
- * advertised by a hotspot operator.
- *
- * @return An array of longs containing the HomeOIs
- */
- public @Nullable long[] getMatchAnyOis() {
- return mMatchAnyOis;
- }
-
- /**
- * List of FQDN (Fully Qualified Domain Name) of partner providers.
- * These providers should also be regarded as home Hotspot operators.
- * This relationship is most likely achieved via a commercial agreement or
- * operator merges between the providers.
- */
- private String[] mOtherHomePartners = null;
-
- /**
- * Set the list of FQDN (Fully Qualified Domain Name) of other Home partner providers.
- *
- * @param otherHomePartners Array of Strings containing the FQDNs of other Home partner
- * providers
- * @hide
- */
- public void setOtherHomePartners(@Nullable String[] otherHomePartners) {
- mOtherHomePartners = otherHomePartners;
- }
-
- /**
- * Set the list of FQDN (Fully Qualified Domain Name) of other Home partner providers.
- *
- * @param otherHomePartners Collection of Strings containing the FQDNs of other Home partner
- * providers
- */
- public void setOtherHomePartnersList(@NonNull Collection<String> otherHomePartners) {
- if (otherHomePartners == null) {
- return;
- }
- mOtherHomePartners = otherHomePartners.toArray(new String[otherHomePartners.size()]);
- }
-
- /**
- * Get the list of FQDN (Fully Qualified Domain Name) of other Home partner providers set in
- * the profile.
- *
- * @return Array of Strings containing the FQDNs of other Home partner providers set in the
- * profile
- * @hide
- */
- public @Nullable String[] getOtherHomePartners() {
- return mOtherHomePartners;
- }
-
- /**
- * Get the list of FQDN (Fully Qualified Domain Name) of other Home partner providers set in
- * the profile.
- *
- * @return Collection of Strings containing the FQDNs of other Home partner providers set in the
- * profile
- */
- public @NonNull Collection<String> getOtherHomePartnersList() {
- if (mOtherHomePartners == null) {
- return Collections.emptyList();
- }
- return Arrays.asList(mOtherHomePartners);
- }
-
- /**
- * List of Organization Identifiers (OIs) identifying a roaming consortium of
- * which this provider is a member.
- */
- private long[] mRoamingConsortiumOis = null;
- /**
- * Set the Organization Identifiers (OIs) identifying a roaming consortium of which this
- * provider is a member.
- *
- * @param roamingConsortiumOis Array of roaming consortium OIs
- */
- public void setRoamingConsortiumOis(long[] roamingConsortiumOis) {
- mRoamingConsortiumOis = roamingConsortiumOis;
- }
- /**
- * Get the Organization Identifiers (OIs) identifying a roaming consortium of which this
- * provider is a member.
- *
- * @return array of roaming consortium OIs
- */
- public long[] getRoamingConsortiumOis() {
- return mRoamingConsortiumOis;
- }
-
- /**
- * Constructor for creating HomeSp with default values.
- */
- public HomeSp() {}
-
- /**
- * Copy constructor.
- *
- * @param source The source to copy from
- */
- public HomeSp(HomeSp source) {
- if (source == null) {
- return;
- }
- mFqdn = source.mFqdn;
- mFriendlyName = source.mFriendlyName;
- mIconUrl = source.mIconUrl;
- if (source.mHomeNetworkIds != null) {
- mHomeNetworkIds = Collections.unmodifiableMap(source.mHomeNetworkIds);
- }
- if (source.mMatchAllOis != null) {
- mMatchAllOis = Arrays.copyOf(source.mMatchAllOis, source.mMatchAllOis.length);
- }
- if (source.mMatchAnyOis != null) {
- mMatchAnyOis = Arrays.copyOf(source.mMatchAnyOis, source.mMatchAnyOis.length);
- }
- if (source.mOtherHomePartners != null) {
- mOtherHomePartners = Arrays.copyOf(source.mOtherHomePartners,
- source.mOtherHomePartners.length);
- }
- if (source.mRoamingConsortiumOis != null) {
- mRoamingConsortiumOis = Arrays.copyOf(source.mRoamingConsortiumOis,
- source.mRoamingConsortiumOis.length);
- }
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(mFqdn);
- dest.writeString(mFriendlyName);
- dest.writeString(mIconUrl);
- writeHomeNetworkIds(dest, mHomeNetworkIds);
- dest.writeLongArray(mMatchAllOis);
- dest.writeLongArray(mMatchAnyOis);
- dest.writeStringArray(mOtherHomePartners);
- dest.writeLongArray(mRoamingConsortiumOis);
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof HomeSp)) {
- return false;
- }
- HomeSp that = (HomeSp) thatObject;
-
- return TextUtils.equals(mFqdn, that.mFqdn)
- && TextUtils.equals(mFriendlyName, that.mFriendlyName)
- && TextUtils.equals(mIconUrl, that.mIconUrl)
- && (mHomeNetworkIds == null ? that.mHomeNetworkIds == null
- : mHomeNetworkIds.equals(that.mHomeNetworkIds))
- && Arrays.equals(mMatchAllOis, that.mMatchAllOis)
- && Arrays.equals(mMatchAnyOis, that.mMatchAnyOis)
- && Arrays.equals(mOtherHomePartners, that.mOtherHomePartners)
- && Arrays.equals(mRoamingConsortiumOis, that.mRoamingConsortiumOis);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mFqdn, mFriendlyName, mIconUrl,
- mHomeNetworkIds, Arrays.hashCode(mMatchAllOis),
- Arrays.hashCode(mMatchAnyOis), Arrays.hashCode(mOtherHomePartners),
- Arrays.hashCode(mRoamingConsortiumOis));
- }
-
- /**
- * Get a unique identifier for HomeSp. This identifier depends only on items that remain
- * constant throughout the lifetime of a subscription.
- *
- * @hide
- * @return a Unique identifier for a HomeSp object
- */
- public int getUniqueId() {
- return Objects.hash(mFqdn);
- }
-
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("FQDN: ").append(mFqdn).append("\n");
- builder.append("FriendlyName: ").append(mFriendlyName).append("\n");
- builder.append("IconURL: ").append(mIconUrl).append("\n");
- builder.append("HomeNetworkIDs: ").append(mHomeNetworkIds).append("\n");
- builder.append("MatchAllOIs: ").append(mMatchAllOis).append("\n");
- builder.append("MatchAnyOIs: ").append(mMatchAnyOis).append("\n");
- builder.append("OtherHomePartners: ").append(mOtherHomePartners).append("\n");
- builder.append("RoamingConsortiumOIs: ").append(mRoamingConsortiumOis).append("\n");
- return builder.toString();
- }
-
- /**
- * Validate HomeSp data.
- *
- * @return true on success or false on failure
- * @hide
- */
- public boolean validate() {
- if (TextUtils.isEmpty(mFqdn)) {
- Log.d(TAG, "Missing FQDN");
- return false;
- }
- if (TextUtils.isEmpty(mFriendlyName)) {
- Log.d(TAG, "Missing friendly name");
- return false;
- }
- // Verify SSIDs specified in the NetworkID
- if (mHomeNetworkIds != null) {
- for (Map.Entry<String, Long> entry : mHomeNetworkIds.entrySet()) {
- if (entry.getKey() == null ||
- entry.getKey().getBytes(StandardCharsets.UTF_8).length > MAX_SSID_BYTES) {
- Log.d(TAG, "Invalid SSID in HomeNetworkIDs");
- return false;
- }
- }
- }
- return true;
- }
-
- public static final @android.annotation.NonNull Creator<HomeSp> CREATOR =
- new Creator<HomeSp>() {
- @Override
- public HomeSp createFromParcel(Parcel in) {
- HomeSp homeSp = new HomeSp();
- homeSp.setFqdn(in.readString());
- homeSp.setFriendlyName(in.readString());
- homeSp.setIconUrl(in.readString());
- homeSp.setHomeNetworkIds(readHomeNetworkIds(in));
- homeSp.setMatchAllOis(in.createLongArray());
- homeSp.setMatchAnyOis(in.createLongArray());
- homeSp.setOtherHomePartners(in.createStringArray());
- homeSp.setRoamingConsortiumOis(in.createLongArray());
- return homeSp;
- }
-
- @Override
- public HomeSp[] newArray(int size) {
- return new HomeSp[size];
- }
-
- /**
- * Helper function for reading a Home Network IDs map from a Parcel.
- *
- * @param in The Parcel to read from
- * @return Map of home network IDs
- */
- private Map<String, Long> readHomeNetworkIds(Parcel in) {
- int size = in.readInt();
- if (size == NULL_VALUE) {
- return null;
- }
- Map<String, Long> networkIds = new HashMap<>(size);
- for (int i = 0; i < size; i++) {
- String key = in.readString();
- Long value = null;
- long readValue = in.readLong();
- if (readValue != NULL_VALUE) {
- value = Long.valueOf(readValue);
- }
- networkIds.put(key, value);
- }
- return networkIds;
- }
- };
-
- /**
- * Helper function for writing Home Network IDs map to a Parcel.
- *
- * @param dest The Parcel to write to
- * @param networkIds The map of home network IDs
- */
- private static void writeHomeNetworkIds(Parcel dest, Map<String, Long> networkIds) {
- if (networkIds == null) {
- dest.writeInt(NULL_VALUE);
- return;
- }
- dest.writeInt(networkIds.size());
- for (Map.Entry<String, Long> entry : networkIds.entrySet()) {
- dest.writeString(entry.getKey());
- if (entry.getValue() == null) {
- dest.writeLong(NULL_VALUE);
- } else {
- dest.writeLong(entry.getValue());
- }
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/hotspot2/pps/Policy.java b/wifi/java/android/net/wifi/hotspot2/pps/Policy.java
deleted file mode 100644
index b0a2cc397c53..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/pps/Policy.java
+++ /dev/null
@@ -1,576 +0,0 @@
-/**
- * Copyright (c) 2017, 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.hotspot2.pps;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-import android.util.Log;
-
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-
-/**
- * Class representing Policy subtree in PerProviderSubscription (PPS)
- * Management Object (MO) tree.
- *
- * The Policy specifies additional criteria for Passpoint network selections, such as preferred
- * roaming partner, minimum backhaul bandwidth, and etc. It also provides the meta data for
- * updating the policy.
- *
- * For more info, refer to Hotspot 2.0 PPS MO defined in section 9.1 of the Hotspot 2.0
- * Release 2 Technical Specification.
- *
- * @hide
- */
-public final class Policy implements Parcelable {
- private static final String TAG = "Policy";
-
- /**
- * Maximum number of SSIDs in the exclusion list.
- */
- private static final int MAX_EXCLUSION_SSIDS = 128;
-
- /**
- * Maximum byte for SSID.
- */
- private static final int MAX_SSID_BYTES = 32;
-
- /**
- * Maximum bytes for port string in {@link #requiredProtoPortMap}.
- */
- private static final int MAX_PORT_STRING_BYTES = 64;
-
- /**
- * Integer value used for indicating null value in the Parcel.
- */
- private static final int NULL_VALUE = -1;
-
- /**
- * Minimum available downlink/uplink bandwidth (in kilobits per second) required when
- * selecting a network from home providers.
- *
- * The bandwidth is calculated as the LinkSpeed * (1 – LinkLoad/255), where LinkSpeed
- * and LinkLoad parameters are drawn from the WAN Metrics ANQP element at that hotspot.
- *
- * Using Long.MIN_VALUE to indicate unset value.
- */
- private long mMinHomeDownlinkBandwidth = Long.MIN_VALUE;
- public void setMinHomeDownlinkBandwidth(long minHomeDownlinkBandwidth) {
- mMinHomeDownlinkBandwidth = minHomeDownlinkBandwidth;
- }
- public long getMinHomeDownlinkBandwidth() {
- return mMinHomeDownlinkBandwidth;
- }
- private long mMinHomeUplinkBandwidth = Long.MIN_VALUE;
- public void setMinHomeUplinkBandwidth(long minHomeUplinkBandwidth) {
- mMinHomeUplinkBandwidth = minHomeUplinkBandwidth;
- }
- public long getMinHomeUplinkBandwidth() {
- return mMinHomeUplinkBandwidth;
- }
-
- /**
- * Minimum available downlink/uplink bandwidth (in kilobits per second) required when
- * selecting a network from roaming providers.
- *
- * The bandwidth is calculated as the LinkSpeed * (1 – LinkLoad/255), where LinkSpeed
- * and LinkLoad parameters are drawn from the WAN Metrics ANQP element at that hotspot.
- *
- * Using Long.MIN_VALUE to indicate unset value.
- */
- private long mMinRoamingDownlinkBandwidth = Long.MIN_VALUE;
- public void setMinRoamingDownlinkBandwidth(long minRoamingDownlinkBandwidth) {
- mMinRoamingDownlinkBandwidth = minRoamingDownlinkBandwidth;
- }
- public long getMinRoamingDownlinkBandwidth() {
- return mMinRoamingDownlinkBandwidth;
- }
- private long mMinRoamingUplinkBandwidth = Long.MIN_VALUE;
- public void setMinRoamingUplinkBandwidth(long minRoamingUplinkBandwidth) {
- mMinRoamingUplinkBandwidth = minRoamingUplinkBandwidth;
- }
- public long getMinRoamingUplinkBandwidth() {
- return mMinRoamingUplinkBandwidth;
- }
-
- /**
- * List of SSIDs that are not preferred by the Home SP.
- */
- private String[] mExcludedSsidList = null;
- public void setExcludedSsidList(String[] excludedSsidList) {
- mExcludedSsidList = excludedSsidList;
- }
- public String[] getExcludedSsidList() {
- return mExcludedSsidList;
- }
-
- /**
- * List of IP protocol and port number required by one or more operator supported application.
- * The port string contained one or more port numbers delimited by ",".
- */
- private Map<Integer, String> mRequiredProtoPortMap = null;
- public void setRequiredProtoPortMap(Map<Integer, String> requiredProtoPortMap) {
- mRequiredProtoPortMap = requiredProtoPortMap;
- }
- public Map<Integer, String> getRequiredProtoPortMap() {
- return mRequiredProtoPortMap;
- }
-
- /**
- * This specifies the maximum acceptable BSS load policy. This is used to prevent device
- * from joining an AP whose channel is overly congested with traffic.
- * Using Integer.MIN_VALUE to indicate unset value.
- */
- private int mMaximumBssLoadValue = Integer.MIN_VALUE;
- public void setMaximumBssLoadValue(int maximumBssLoadValue) {
- mMaximumBssLoadValue = maximumBssLoadValue;
- }
- public int getMaximumBssLoadValue() {
- return mMaximumBssLoadValue;
- }
-
- /**
- * Policy associated with a roaming provider. This specifies a priority associated
- * with a roaming provider for given list of countries.
- *
- * Contains field under PerProviderSubscription/Policy/PreferredRoamingPartnerList.
- */
- public static final class RoamingPartner implements Parcelable {
- /**
- * FQDN of the roaming partner.
- */
- private String mFqdn = null;
- public void setFqdn(String fqdn) {
- mFqdn = fqdn;
- }
- public String getFqdn() {
- return mFqdn;
- }
-
- /**
- * Flag indicating the exact match of FQDN is required for FQDN matching.
- *
- * When this flag is set to false, sub-domain matching is used. For example, when
- * {@link #fqdn} s set to "example.com", "host.example.com" would be a match.
- */
- private boolean mFqdnExactMatch = false;
- public void setFqdnExactMatch(boolean fqdnExactMatch) {
- mFqdnExactMatch = fqdnExactMatch;
- }
- public boolean getFqdnExactMatch() {
- return mFqdnExactMatch;
- }
-
- /**
- * Priority associated with this roaming partner policy.
- * Using Integer.MIN_VALUE to indicate unset value.
- */
- private int mPriority = Integer.MIN_VALUE;
- public void setPriority(int priority) {
- mPriority = priority;
- }
- public int getPriority() {
- return mPriority;
- }
-
- /**
- * A string contained One or more, comma delimited (i.e., ",") ISO/IEC 3166-1 two
- * character country strings or the country-independent value, "*".
- */
- private String mCountries = null;
- public void setCountries(String countries) {
- mCountries = countries;
- }
- public String getCountries() {
- return mCountries;
- }
-
- public RoamingPartner() {}
-
- public RoamingPartner(RoamingPartner source) {
- if (source != null) {
- mFqdn = source.mFqdn;
- mFqdnExactMatch = source.mFqdnExactMatch;
- mPriority = source.mPriority;
- mCountries = source.mCountries;
- }
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(mFqdn);
- dest.writeInt(mFqdnExactMatch ? 1 : 0);
- dest.writeInt(mPriority);
- dest.writeString(mCountries);
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof RoamingPartner)) {
- return false;
- }
-
- RoamingPartner that = (RoamingPartner) thatObject;
- return TextUtils.equals(mFqdn, that.mFqdn)
- && mFqdnExactMatch == that.mFqdnExactMatch
- && mPriority == that.mPriority
- && TextUtils.equals(mCountries, that.mCountries);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mFqdn, mFqdnExactMatch, mPriority, mCountries);
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("FQDN: ").append(mFqdn).append("\n");
- builder.append("ExactMatch: ").append("mFqdnExactMatch").append("\n");
- builder.append("Priority: ").append(mPriority).append("\n");
- builder.append("Countries: ").append(mCountries).append("\n");
- return builder.toString();
- }
-
- /**
- * Validate RoamingParnter data.
- *
- * @return true on success
- * @hide
- */
- public boolean validate() {
- if (TextUtils.isEmpty(mFqdn)) {
- Log.d(TAG, "Missing FQDN");
- return false;
- }
- if (TextUtils.isEmpty(mCountries)) {
- Log.d(TAG, "Missing countries");
- return false;
- }
- return true;
- }
-
- public static final @android.annotation.NonNull Creator<RoamingPartner> CREATOR =
- new Creator<RoamingPartner>() {
- @Override
- public RoamingPartner createFromParcel(Parcel in) {
- RoamingPartner roamingPartner = new RoamingPartner();
- roamingPartner.setFqdn(in.readString());
- roamingPartner.setFqdnExactMatch(in.readInt() != 0);
- roamingPartner.setPriority(in.readInt());
- roamingPartner.setCountries(in.readString());
- return roamingPartner;
- }
-
- @Override
- public RoamingPartner[] newArray(int size) {
- return new RoamingPartner[size];
- }
- };
- }
- private List<RoamingPartner> mPreferredRoamingPartnerList = null;
- public void setPreferredRoamingPartnerList(List<RoamingPartner> partnerList) {
- mPreferredRoamingPartnerList = partnerList;
- }
- public List<RoamingPartner> getPreferredRoamingPartnerList() {
- return mPreferredRoamingPartnerList;
- }
-
- /**
- * Meta data used for policy update.
- */
- private UpdateParameter mPolicyUpdate = null;
- public void setPolicyUpdate(UpdateParameter policyUpdate) {
- mPolicyUpdate = policyUpdate;
- }
- public UpdateParameter getPolicyUpdate() {
- return mPolicyUpdate;
- }
-
- /**
- * Constructor for creating Policy with default values.
- */
- public Policy() {}
-
- /**
- * Copy constructor.
- *
- * @param source The source to copy from
- */
- public Policy(Policy source) {
- if (source == null) {
- return;
- }
- mMinHomeDownlinkBandwidth = source.mMinHomeDownlinkBandwidth;
- mMinHomeUplinkBandwidth = source.mMinHomeUplinkBandwidth;
- mMinRoamingDownlinkBandwidth = source.mMinRoamingDownlinkBandwidth;
- mMinRoamingUplinkBandwidth = source.mMinRoamingUplinkBandwidth;
- mMaximumBssLoadValue = source.mMaximumBssLoadValue;
- if (source.mExcludedSsidList != null) {
- mExcludedSsidList = Arrays.copyOf(source.mExcludedSsidList,
- source.mExcludedSsidList.length);
- }
- if (source.mRequiredProtoPortMap != null) {
- mRequiredProtoPortMap = Collections.unmodifiableMap(source.mRequiredProtoPortMap);
- }
- if (source.mPreferredRoamingPartnerList != null) {
- mPreferredRoamingPartnerList = Collections.unmodifiableList(
- source.mPreferredRoamingPartnerList);
- }
- if (source.mPolicyUpdate != null) {
- mPolicyUpdate = new UpdateParameter(source.mPolicyUpdate);
- }
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeLong(mMinHomeDownlinkBandwidth);
- dest.writeLong(mMinHomeUplinkBandwidth);
- dest.writeLong(mMinRoamingDownlinkBandwidth);
- dest.writeLong(mMinRoamingUplinkBandwidth);
- dest.writeStringArray(mExcludedSsidList);
- writeProtoPortMap(dest, mRequiredProtoPortMap);
- dest.writeInt(mMaximumBssLoadValue);
- writeRoamingPartnerList(dest, flags, mPreferredRoamingPartnerList);
- dest.writeParcelable(mPolicyUpdate, flags);
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof Policy)) {
- return false;
- }
- Policy that = (Policy) thatObject;
-
- return mMinHomeDownlinkBandwidth == that.mMinHomeDownlinkBandwidth
- && mMinHomeUplinkBandwidth == that.mMinHomeUplinkBandwidth
- && mMinRoamingDownlinkBandwidth == that.mMinRoamingDownlinkBandwidth
- && mMinRoamingUplinkBandwidth == that.mMinRoamingUplinkBandwidth
- && Arrays.equals(mExcludedSsidList, that.mExcludedSsidList)
- && (mRequiredProtoPortMap == null ? that.mRequiredProtoPortMap == null
- : mRequiredProtoPortMap.equals(that.mRequiredProtoPortMap))
- && mMaximumBssLoadValue == that.mMaximumBssLoadValue
- && (mPreferredRoamingPartnerList == null
- ? that.mPreferredRoamingPartnerList == null
- : mPreferredRoamingPartnerList.equals(that.mPreferredRoamingPartnerList))
- && (mPolicyUpdate == null ? that.mPolicyUpdate == null
- : mPolicyUpdate.equals(that.mPolicyUpdate));
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mMinHomeDownlinkBandwidth, mMinHomeUplinkBandwidth,
- mMinRoamingDownlinkBandwidth, mMinRoamingUplinkBandwidth, mExcludedSsidList,
- mRequiredProtoPortMap, mMaximumBssLoadValue, mPreferredRoamingPartnerList,
- mPolicyUpdate);
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("MinHomeDownlinkBandwidth: ").append(mMinHomeDownlinkBandwidth)
- .append("\n");
- builder.append("MinHomeUplinkBandwidth: ").append(mMinHomeUplinkBandwidth).append("\n");
- builder.append("MinRoamingDownlinkBandwidth: ").append(mMinRoamingDownlinkBandwidth)
- .append("\n");
- builder.append("MinRoamingUplinkBandwidth: ").append(mMinRoamingUplinkBandwidth)
- .append("\n");
- builder.append("ExcludedSSIDList: ").append(mExcludedSsidList).append("\n");
- builder.append("RequiredProtoPortMap: ").append(mRequiredProtoPortMap).append("\n");
- builder.append("MaximumBSSLoadValue: ").append(mMaximumBssLoadValue).append("\n");
- builder.append("PreferredRoamingPartnerList: ").append(mPreferredRoamingPartnerList)
- .append("\n");
- if (mPolicyUpdate != null) {
- builder.append("PolicyUpdate Begin ---\n");
- builder.append(mPolicyUpdate);
- builder.append("PolicyUpdate End ---\n");
- }
- return builder.toString();
- }
-
- /**
- * Validate Policy data.
- *
- * @return true on success
- * @hide
- */
- public boolean validate() {
- if (mPolicyUpdate == null) {
- Log.d(TAG, "PolicyUpdate not specified");
- return false;
- }
- if (!mPolicyUpdate.validate()) {
- return false;
- }
-
- // Validate SSID exclusion list.
- if (mExcludedSsidList != null) {
- if (mExcludedSsidList.length > MAX_EXCLUSION_SSIDS) {
- Log.d(TAG, "SSID exclusion list size exceeded the max: "
- + mExcludedSsidList.length);
- return false;
- }
- for (String ssid : mExcludedSsidList) {
- if (ssid.getBytes(StandardCharsets.UTF_8).length > MAX_SSID_BYTES) {
- Log.d(TAG, "Invalid SSID: " + ssid);
- return false;
- }
- }
- }
- // Validate required protocol to port map.
- if (mRequiredProtoPortMap != null) {
- for (Map.Entry<Integer, String> entry : mRequiredProtoPortMap.entrySet()) {
- String portNumber = entry.getValue();
- if (portNumber.getBytes(StandardCharsets.UTF_8).length > MAX_PORT_STRING_BYTES) {
- Log.d(TAG, "PortNumber string bytes exceeded the max: " + portNumber);
- return false;
- }
- }
- }
- // Validate preferred roaming partner list.
- if (mPreferredRoamingPartnerList != null) {
- for (RoamingPartner partner : mPreferredRoamingPartnerList) {
- if (!partner.validate()) {
- return false;
- }
- }
- }
- return true;
- }
-
- public static final @android.annotation.NonNull Creator<Policy> CREATOR =
- new Creator<Policy>() {
- @Override
- public Policy createFromParcel(Parcel in) {
- Policy policy = new Policy();
- policy.setMinHomeDownlinkBandwidth(in.readLong());
- policy.setMinHomeUplinkBandwidth(in.readLong());
- policy.setMinRoamingDownlinkBandwidth(in.readLong());
- policy.setMinRoamingUplinkBandwidth(in.readLong());
- policy.setExcludedSsidList(in.createStringArray());
- policy.setRequiredProtoPortMap(readProtoPortMap(in));
- policy.setMaximumBssLoadValue(in.readInt());
- policy.setPreferredRoamingPartnerList(readRoamingPartnerList(in));
- policy.setPolicyUpdate(in.readParcelable(null));
- return policy;
- }
-
- @Override
- public Policy[] newArray(int size) {
- return new Policy[size];
- }
-
- /**
- * Helper function for reading IP Protocol to Port Number map from a Parcel.
- *
- * @param in The Parcel to read from
- * @return Map of IP protocol to port number
- */
- private Map<Integer, String> readProtoPortMap(Parcel in) {
- int size = in.readInt();
- if (size == NULL_VALUE) {
- return null;
- }
- Map<Integer, String> protoPortMap = new HashMap<>(size);
- for (int i = 0; i < size; i++) {
- int key = in.readInt();
- String value = in.readString();
- protoPortMap.put(key, value);
- }
- return protoPortMap;
- }
-
- /**
- * Helper function for reading roaming partner list from a Parcel.
- *
- * @param in The Parcel to read from
- * @return List of roaming partners
- */
- private List<RoamingPartner> readRoamingPartnerList(Parcel in) {
- int size = in.readInt();
- if (size == NULL_VALUE) {
- return null;
- }
- List<RoamingPartner> partnerList = new ArrayList<>();
- for (int i = 0; i < size; i++) {
- partnerList.add(in.readParcelable(null));
- }
- return partnerList;
- }
-
- };
-
- /**
- * Helper function for writing IP Protocol to Port Number map to a Parcel.
- *
- * @param dest The Parcel to write to
- * @param protoPortMap The map to write
- */
- private static void writeProtoPortMap(Parcel dest, Map<Integer, String> protoPortMap) {
- if (protoPortMap == null) {
- dest.writeInt(NULL_VALUE);
- return;
- }
- dest.writeInt(protoPortMap.size());
- for (Map.Entry<Integer, String> entry : protoPortMap.entrySet()) {
- dest.writeInt(entry.getKey());
- dest.writeString(entry.getValue());
- }
- }
-
- /**
- * Helper function for writing roaming partner list to a Parcel.
- *
- * @param dest The Parcel to write to
- * @param flags The flag about how the object should be written
- * @param partnerList The partner list to write
- */
- private static void writeRoamingPartnerList(Parcel dest, int flags,
- List<RoamingPartner> partnerList) {
- if (partnerList == null) {
- dest.writeInt(NULL_VALUE);
- return;
- }
- dest.writeInt(partnerList.size());
- for (RoamingPartner partner : partnerList) {
- dest.writeParcelable(partner, flags);
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java b/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java
deleted file mode 100644
index 4a8aa361a849..000000000000
--- a/wifi/java/android/net/wifi/hotspot2/pps/UpdateParameter.java
+++ /dev/null
@@ -1,403 +0,0 @@
-/**
- * Copyright (c) 2017, 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.hotspot2.pps;
-
-import android.net.wifi.ParcelUtil;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-import android.util.Base64;
-import android.util.Log;
-
-import java.nio.charset.StandardCharsets;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Objects;
-
-/**
- * Class representing configuration parameters for subscription or policy update in
- * PerProviderSubscription (PPS) Management Object (MO) tree. This is used by both
- * PerProviderSubscription/Policy/PolicyUpdate and PerProviderSubscription/SubscriptionUpdate
- * subtree.
- *
- * For more info, refer to Hotspot 2.0 PPS MO defined in section 9.1 of the Hotspot 2.0
- * Release 2 Technical Specification.
- *
- * @hide
- */
-public final class UpdateParameter implements Parcelable {
- private static final String TAG = "UpdateParameter";
-
- /**
- * Value indicating policy update is not applicable. Thus, never check with policy server
- * for updates.
- */
- public static final long UPDATE_CHECK_INTERVAL_NEVER = 0xFFFFFFFFL;
-
- /**
- * Valid string for UpdateMethod.
- */
- public static final String UPDATE_METHOD_OMADM = "OMA-DM-ClientInitiated";
- public static final String UPDATE_METHOD_SSP = "SSP-ClientInitiated";
-
- /**
- * Valid string for Restriction.
- */
- public static final String UPDATE_RESTRICTION_HOMESP = "HomeSP";
- public static final String UPDATE_RESTRICTION_ROAMING_PARTNER = "RoamingPartner";
- public static final String UPDATE_RESTRICTION_UNRESTRICTED = "Unrestricted";
-
- /**
- * Maximum bytes for URI string.
- */
- private static final int MAX_URI_BYTES = 1023;
-
- /**
- * Maximum bytes for URI string.
- */
- private static final int MAX_URL_BYTES = 1023;
-
- /**
- * Maximum bytes for username.
- */
- private static final int MAX_USERNAME_BYTES = 63;
-
- /**
- * Maximum bytes for password.
- */
- private static final int MAX_PASSWORD_BYTES = 255;
-
- /**
- * Number of bytes for certificate SHA-256 fingerprint byte array.
- */
- private static final int CERTIFICATE_SHA256_BYTES = 32;
-
- /**
- * This specifies how often the mobile device shall check with policy server for updates.
- *
- * Using Long.MIN_VALUE to indicate unset value.
- */
- private long mUpdateIntervalInMinutes = Long.MIN_VALUE;
- public void setUpdateIntervalInMinutes(long updateIntervalInMinutes) {
- mUpdateIntervalInMinutes = updateIntervalInMinutes;
- }
- public long getUpdateIntervalInMinutes() {
- return mUpdateIntervalInMinutes;
- }
-
- /**
- * The method used to update the policy. Permitted values are "OMA-DM-ClientInitiated"
- * and "SPP-ClientInitiated".
- */
- private String mUpdateMethod = null;
- public void setUpdateMethod(String updateMethod) {
- mUpdateMethod = updateMethod;
- }
- public String getUpdateMethod() {
- return mUpdateMethod;
- }
-
- /**
- * This specifies the hotspots at which the subscription update is permitted. Permitted
- * values are "HomeSP", "RoamingPartner", or "Unrestricted";
- */
- private String mRestriction = null;
- public void setRestriction(String restriction) {
- mRestriction = restriction;
- }
- public String getRestriction() {
- return mRestriction;
- }
-
- /**
- * The URI of the update server.
- */
- private String mServerUri = null;
- public void setServerUri(String serverUri) {
- mServerUri = serverUri;
- }
- public String getServerUri() {
- return mServerUri;
- }
-
- /**
- * Username used to authenticate with the policy server.
- */
- private String mUsername = null;
- public void setUsername(String username) {
- mUsername = username;
- }
- public String getUsername() {
- return mUsername;
- }
-
- /**
- * Base64 encoded password used to authenticate with the policy server.
- */
- private String mBase64EncodedPassword = null;
- public void setBase64EncodedPassword(String password) {
- mBase64EncodedPassword = password;
- }
- public String getBase64EncodedPassword() {
- return mBase64EncodedPassword;
- }
-
- /**
- * HTTPS URL for retrieving certificate for trust root. The trust root is used to validate
- * policy server's identity.
- */
- private String mTrustRootCertUrl = null;
- public void setTrustRootCertUrl(String trustRootCertUrl) {
- mTrustRootCertUrl = trustRootCertUrl;
- }
- public String getTrustRootCertUrl() {
- return mTrustRootCertUrl;
- }
-
- /**
- * SHA-256 fingerprint of the certificate located at {@code mTrustRootCertUrl}
- */
- private byte[] mTrustRootCertSha256Fingerprint = null;
- public void setTrustRootCertSha256Fingerprint(byte[] fingerprint) {
- mTrustRootCertSha256Fingerprint = fingerprint;
- }
- public byte[] getTrustRootCertSha256Fingerprint() {
- return mTrustRootCertSha256Fingerprint;
- }
-
- /**
- * CA (Certificate Authority) X509 certificates.
- */
- private X509Certificate mCaCertificate;
-
- /**
- * Set the CA (Certification Authority) certificate associated with Policy/Subscription update.
- *
- * @param caCertificate The CA certificate to set
- * @hide
- */
- public void setCaCertificate(X509Certificate caCertificate) {
- mCaCertificate = caCertificate;
- }
-
- /**
- * Get the CA (Certification Authority) certificate associated with Policy/Subscription update.
- *
- * @return CA certificate associated and {@code null} if certificate is not set.
- * @hide
- */
- public X509Certificate getCaCertificate() {
- return mCaCertificate;
- }
-
- /**
- * Constructor for creating Policy with default values.
- */
- public UpdateParameter() {}
-
- /**
- * Copy constructor.
- *
- * @param source The source to copy from
- */
- public UpdateParameter(UpdateParameter source) {
- if (source == null) {
- return;
- }
- mUpdateIntervalInMinutes = source.mUpdateIntervalInMinutes;
- mUpdateMethod = source.mUpdateMethod;
- mRestriction = source.mRestriction;
- mServerUri = source.mServerUri;
- mUsername = source.mUsername;
- mBase64EncodedPassword = source.mBase64EncodedPassword;
- mTrustRootCertUrl = source.mTrustRootCertUrl;
- if (source.mTrustRootCertSha256Fingerprint != null) {
- mTrustRootCertSha256Fingerprint = Arrays.copyOf(source.mTrustRootCertSha256Fingerprint,
- source.mTrustRootCertSha256Fingerprint.length);
- }
- mCaCertificate = source.mCaCertificate;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeLong(mUpdateIntervalInMinutes);
- dest.writeString(mUpdateMethod);
- dest.writeString(mRestriction);
- dest.writeString(mServerUri);
- dest.writeString(mUsername);
- dest.writeString(mBase64EncodedPassword);
- dest.writeString(mTrustRootCertUrl);
- dest.writeByteArray(mTrustRootCertSha256Fingerprint);
- ParcelUtil.writeCertificate(dest, mCaCertificate);
- }
-
- @Override
- public boolean equals(Object thatObject) {
- if (this == thatObject) {
- return true;
- }
- if (!(thatObject instanceof UpdateParameter)) {
- return false;
- }
- UpdateParameter that = (UpdateParameter) thatObject;
-
- return mUpdateIntervalInMinutes == that.mUpdateIntervalInMinutes
- && TextUtils.equals(mUpdateMethod, that.mUpdateMethod)
- && TextUtils.equals(mRestriction, that.mRestriction)
- && TextUtils.equals(mServerUri, that.mServerUri)
- && TextUtils.equals(mUsername, that.mUsername)
- && TextUtils.equals(mBase64EncodedPassword, that.mBase64EncodedPassword)
- && TextUtils.equals(mTrustRootCertUrl, that.mTrustRootCertUrl)
- && Arrays.equals(mTrustRootCertSha256Fingerprint,
- that.mTrustRootCertSha256Fingerprint)
- && Credential.isX509CertificateEquals(mCaCertificate, that.mCaCertificate);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mUpdateIntervalInMinutes, mUpdateMethod, mRestriction, mServerUri,
- mUsername, mBase64EncodedPassword, mTrustRootCertUrl,
- Arrays.hashCode(mTrustRootCertSha256Fingerprint), mCaCertificate);
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("UpdateInterval: ").append(mUpdateIntervalInMinutes).append("\n");
- builder.append("UpdateMethod: ").append(mUpdateMethod).append("\n");
- builder.append("Restriction: ").append(mRestriction).append("\n");
- builder.append("ServerURI: ").append(mServerUri).append("\n");
- builder.append("Username: ").append(mUsername).append("\n");
- builder.append("TrustRootCertURL: ").append(mTrustRootCertUrl).append("\n");
- return builder.toString();
- }
-
- /**
- * Validate UpdateParameter data.
- *
- * @return true on success
- * @hide
- */
- public boolean validate() {
- if (mUpdateIntervalInMinutes == Long.MIN_VALUE) {
- Log.d(TAG, "Update interval not specified");
- return false;
- }
- // Update not applicable.
- if (mUpdateIntervalInMinutes == UPDATE_CHECK_INTERVAL_NEVER) {
- return true;
- }
-
- if (!TextUtils.equals(mUpdateMethod, UPDATE_METHOD_OMADM)
- && !TextUtils.equals(mUpdateMethod, UPDATE_METHOD_SSP)) {
- Log.d(TAG, "Unknown update method: " + mUpdateMethod);
- return false;
- }
-
- if (!TextUtils.equals(mRestriction, UPDATE_RESTRICTION_HOMESP)
- && !TextUtils.equals(mRestriction, UPDATE_RESTRICTION_ROAMING_PARTNER)
- && !TextUtils.equals(mRestriction, UPDATE_RESTRICTION_UNRESTRICTED)) {
- Log.d(TAG, "Unknown restriction: " + mRestriction);
- return false;
- }
-
- if (TextUtils.isEmpty(mServerUri)) {
- Log.d(TAG, "Missing update server URI");
- return false;
- }
- if (mServerUri.getBytes(StandardCharsets.UTF_8).length > MAX_URI_BYTES) {
- Log.d(TAG, "URI bytes exceeded the max: "
- + mServerUri.getBytes(StandardCharsets.UTF_8).length);
- return false;
- }
-
- if (TextUtils.isEmpty(mUsername)) {
- Log.d(TAG, "Missing username");
- return false;
- }
- if (mUsername.getBytes(StandardCharsets.UTF_8).length > MAX_USERNAME_BYTES) {
- Log.d(TAG, "Username bytes exceeded the max: "
- + mUsername.getBytes(StandardCharsets.UTF_8).length);
- return false;
- }
-
- if (TextUtils.isEmpty(mBase64EncodedPassword)) {
- Log.d(TAG, "Missing username");
- return false;
- }
- if (mBase64EncodedPassword.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES) {
- Log.d(TAG, "Password bytes exceeded the max: "
- + mBase64EncodedPassword.getBytes(StandardCharsets.UTF_8).length);
- return false;
- }
- try {
- Base64.decode(mBase64EncodedPassword, Base64.DEFAULT);
- } catch (IllegalArgumentException e) {
- Log.d(TAG, "Invalid encoding for password: " + mBase64EncodedPassword);
- return false;
- }
-
- if (TextUtils.isEmpty(mTrustRootCertUrl)) {
- Log.d(TAG, "Missing trust root certificate URL");
- return false;
- }
- if (mTrustRootCertUrl.getBytes(StandardCharsets.UTF_8).length > MAX_URL_BYTES) {
- Log.d(TAG, "Trust root cert URL bytes exceeded the max: "
- + mTrustRootCertUrl.getBytes(StandardCharsets.UTF_8).length);
- return false;
- }
-
- if (mTrustRootCertSha256Fingerprint == null) {
- Log.d(TAG, "Missing trust root certificate SHA-256 fingerprint");
- return false;
- }
- if (mTrustRootCertSha256Fingerprint.length != CERTIFICATE_SHA256_BYTES) {
- Log.d(TAG, "Incorrect size of trust root certificate SHA-256 fingerprint: "
- + mTrustRootCertSha256Fingerprint.length);
- return false;
- }
- return true;
- }
-
- public static final @android.annotation.NonNull Creator<UpdateParameter> CREATOR =
- new Creator<UpdateParameter>() {
- @Override
- public UpdateParameter createFromParcel(Parcel in) {
- UpdateParameter updateParam = new UpdateParameter();
- updateParam.setUpdateIntervalInMinutes(in.readLong());
- updateParam.setUpdateMethod(in.readString());
- updateParam.setRestriction(in.readString());
- updateParam.setServerUri(in.readString());
- updateParam.setUsername(in.readString());
- updateParam.setBase64EncodedPassword(in.readString());
- updateParam.setTrustRootCertUrl(in.readString());
- updateParam.setTrustRootCertSha256Fingerprint(in.createByteArray());
- updateParam.setCaCertificate(ParcelUtil.readCertificate(in));
- return updateParam;
- }
-
- @Override
- public UpdateParameter[] newArray(int size) {
- return new UpdateParameter[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/migration_samples/README.txt b/wifi/java/android/net/wifi/migration_samples/README.txt
deleted file mode 100644
index 264debaa51f9..000000000000
--- a/wifi/java/android/net/wifi/migration_samples/README.txt
+++ /dev/null
@@ -1,35 +0,0 @@
-This folder contains sample files for each of the 4 XML Wi-Fi config store files in Android 11 AOSP.
-OEMs can use these files as reference for converting their previous customized
-formats into the AOSP format. The conversion logic needs to be written in
-WifiMigration.java class, i.e each OEM needs to modify
-WifiMigration.convertAndRetrieveSharedConfigStoreFile() and the
-WifiMigration.convertAndRetrieveUserConfigStoreFile() methods.
-
-The 4 files are:
-
-Shared files
-============
-1) WifiConfigStore.xml - General storage for shared configurations. Includes
-user's saved Wi-Fi networks.
-AOSP Path in Android 10: /data/misc/wifi/WifiConfigStore.xml
-AOSP Path in Android 11: /data/misc/apexdata/com.android/wifi/WifiConfigStore.xml
-Sample File (in this folder): Shared_WifiConfigStore.xml
-
-2) WifiConfigStoreSoftAp.xml - Storage for user's softap/tethering configuration.
-AOSP Path in Android 10: /data/misc/wifi/softap.conf.
-Note: Was key/value format in Android 10. Conversion to XML done in SoftApConfToXmlMigrationUtil.java.
-AOSP Path in Android 11: /data/misc/apexdata/com.android/wifi/WifiConfigStore.xml
-Sample File (in this folder): Shared_WifiConfigStoreSoftAp.xml
-
-User specific files
-==================
-3) WifiConfigStore.xml - General storage for user specific configurations. Includes
-user's saved passpoint networks, Wi-Fi network request approvals, etc.
-AOSP Path in Android 10: /data/misc_ce/<userId>/wifi/WifiConfigStore.xml
-AOSP Path in Android 11: /data/misc_ce/<userId>/apexdata/com.android/wifi/WifiConfigStore.xml
-Sample File (in this folder): User_WifiConfigStore.xml
-
-4) WifiConfigStoreNetworkSuggestions.xml - Storage for app installed network suggestions.
-AOSP Path in Android 10: /data/misc_ce/<userId>/wifi/WifiConfigStoreNetworkSuggestions.xml
-AOSP Path in Android 11: /data/misc_ce/<userId>/apexdata/com.android/wifi/WifiConfigStoreNetworkSuggestions.xml
-Sample File (in this folder): User_WifiConfigStoreNetworkSuggestions.xml
diff --git a/wifi/java/android/net/wifi/migration_samples/Shared_WifiConfigStore.xml b/wifi/java/android/net/wifi/migration_samples/Shared_WifiConfigStore.xml
deleted file mode 100644
index 3063276fae6a..000000000000
--- a/wifi/java/android/net/wifi/migration_samples/Shared_WifiConfigStore.xml
+++ /dev/null
@@ -1,200 +0,0 @@
-<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
-<WifiConfigStoreData>
-<int name="Version" value="3" />
-<NetworkList>
-<Network>
-<WifiConfiguration>
-<string name="ConfigKey">&quot;OPEN_SSID&quot;NONE</string>
-<string name="SSID">&quot;OPEN_SSID&quot;</string>
-<null name="PreSharedKey" />
-<null name="WEPKeys" />
-<int name="WEPTxKeyIndex" value="0" />
-<boolean name="HiddenSSID" value="false" />
-<boolean name="RequirePMF" value="false" />
-<byte-array name="AllowedKeyMgmt" num="1">01</byte-array>
-<byte-array name="AllowedProtocols" num="1">03</byte-array>
-<byte-array name="AllowedAuthAlgos" num="0"></byte-array>
-<byte-array name="AllowedGroupCiphers" num="1">2f</byte-array>
-<byte-array name="AllowedPairwiseCiphers" num="1">0e</byte-array>
-<byte-array name="AllowedGroupMgmtCiphers" num="1">04</byte-array>
-<byte-array name="AllowedSuiteBCiphers" num="0"></byte-array>
-<boolean name="Shared" value="true" />
-<boolean name="AutoJoinEnabled" value="true" />
-<boolean name="Trusted" value="true" />
-<null name="BSSID" />
-<int name="Status" value="2" />
-<null name="FQDN" />
-<null name="ProviderFriendlyName" />
-<null name="LinkedNetworksList" />
-<null name="DefaultGwMacAddress" />
-<boolean name="ValidatedInternetAccess" value="true" />
-<boolean name="NoInternetAccessExpected" value="false" />
-<boolean name="MeteredHint" value="false" />
-<int name="MeteredOverride" value="0" />
-<boolean name="UseExternalScores" value="false" />
-<int name="NumAssociation" value="3" />
-<int name="CreatorUid" value="1000" />
-<string name="CreatorName">android.uid.system:1000</string>
-<int name="LastUpdateUid" value="1000" />
-<string name="LastUpdateName">android.uid.system:1000</string>
-<int name="LastConnectUid" value="1000" />
-<boolean name="IsLegacyPasspointConfig" value="false" />
-<long-array name="RoamingConsortiumOIs" num="0" />
-<string name="RandomizedMacAddress">ce:b1:36:bb:71:ac</string>
-<int name="MacRandomizationSetting" value="1" />
-<int name="CarrierId" value="-1" />
-</WifiConfiguration>
-<NetworkStatus>
-<string name="SelectionStatus">NETWORK_SELECTION_ENABLED</string>
-<string name="DisableReason">NETWORK_SELECTION_ENABLE</string>
-<string name="ConnectChoice">&quot;ENTERPRISE_SSID&quot;WPA_EAP</string>
-<boolean name="HasEverConnected" value="true" />
-</NetworkStatus>
-<IpConfiguration>
-<string name="IpAssignment">DHCP</string>
-<string name="ProxySettings">NONE</string>
-</IpConfiguration>
-</Network>
-<Network>
-<WifiConfiguration>
-<string name="ConfigKey">&quot;ENTERPRISE_SSID&quot;WPA_EAP</string>
-<string name="SSID">&quot;ENTERPRISE_SSID&quot;</string>
-<null name="PreSharedKey" />
-<null name="WEPKeys" />
-<int name="WEPTxKeyIndex" value="0" />
-<boolean name="HiddenSSID" value="false" />
-<boolean name="RequirePMF" value="false" />
-<byte-array name="AllowedKeyMgmt" num="1">0c</byte-array>
-<byte-array name="AllowedProtocols" num="1">03</byte-array>
-<byte-array name="AllowedAuthAlgos" num="0"></byte-array>
-<byte-array name="AllowedGroupCiphers" num="1">2f</byte-array>
-<byte-array name="AllowedPairwiseCiphers" num="1">0e</byte-array>
-<byte-array name="AllowedGroupMgmtCiphers" num="1">04</byte-array>
-<byte-array name="AllowedSuiteBCiphers" num="0"></byte-array>
-<boolean name="Shared" value="true" />
-<boolean name="AutoJoinEnabled" value="true" />
-<boolean name="Trusted" value="true" />
-<null name="BSSID" />
-<int name="Status" value="2" />
-<null name="FQDN" />
-<null name="ProviderFriendlyName" />
-<null name="LinkedNetworksList" />
-<null name="DefaultGwMacAddress" />
-<boolean name="ValidatedInternetAccess" value="false" />
-<boolean name="NoInternetAccessExpected" value="false" />
-<boolean name="MeteredHint" value="false" />
-<int name="MeteredOverride" value="0" />
-<boolean name="UseExternalScores" value="false" />
-<int name="NumAssociation" value="0" />
-<int name="CreatorUid" value="1000" />
-<string name="CreatorName">android.uid.system:1000</string>
-<int name="LastUpdateUid" value="1000" />
-<string name="LastUpdateName">android.uid.system:1000</string>
-<int name="LastConnectUid" value="1000" />
-<boolean name="IsLegacyPasspointConfig" value="false" />
-<long-array name="RoamingConsortiumOIs" num="0" />
-<string name="RandomizedMacAddress">f6:b3:94:44:40:87</string>
-<int name="MacRandomizationSetting" value="1" />
-<int name="CarrierId" value="-1" />
-</WifiConfiguration>
-<NetworkStatus>
-<string name="SelectionStatus">NETWORK_SELECTION_TEMPORARY_DISABLED</string>
-<string name="DisableReason">NETWORK_SELECTION_DISABLED_AUTHENTICATION_FAILURE</string>
-<null name="ConnectChoice" />
-<boolean name="HasEverConnected" value="false" />
-</NetworkStatus>
-<IpConfiguration>
-<string name="IpAssignment">DHCP</string>
-<string name="ProxySettings">NONE</string>
-</IpConfiguration>
-<WifiEnterpriseConfiguration>
-<string name="Identity">adadadasdaddsa</string>
-<string name="AnonIdentity">asdadaddadasd</string>
-<string name="Password">adasdadadad</string>
-<string name="ClientCert"></string>
-<string name="CaCert"></string>
-<string name="SubjectMatch"></string>
-<string name="Engine">0</string>
-<string name="EngineId"></string>
-<string name="PrivateKeyId"></string>
-<string name="AltSubjectMatch"></string>
-<string name="DomSuffixMatch">adsad</string>
-<string name="CaPath">/system/etc/security/cacerts</string>
-<int name="EapMethod" value="0" />
-<int name="Phase2Method" value="3" />
-<string name="PLMN"></string>
-<string name="Realm"></string>
-<int name="Ocsp" value="0" />
-<string name="WapiCertSuite"></string>
-</WifiEnterpriseConfiguration>
-</Network>
-<Network>
-<WifiConfiguration>
-<string name="ConfigKey">&quot;WPA3_SSID&quot;SAE</string>
-<string name="SSID">&quot;WPA3_SSID&quot;</string>
-<string name="PreSharedKey">&quot;sfsdfsfdsfsdf&quot;</string>
-<null name="WEPKeys" />
-<int name="WEPTxKeyIndex" value="0" />
-<boolean name="HiddenSSID" value="false" />
-<boolean name="RequirePMF" value="true" />
-<byte-array name="AllowedKeyMgmt" num="2">0001</byte-array>
-<byte-array name="AllowedProtocols" num="1">02</byte-array>
-<byte-array name="AllowedAuthAlgos" num="0"></byte-array>
-<byte-array name="AllowedGroupCiphers" num="1">28</byte-array>
-<byte-array name="AllowedPairwiseCiphers" num="1">0c</byte-array>
-<byte-array name="AllowedGroupMgmtCiphers" num="1">04</byte-array>
-<byte-array name="AllowedSuiteBCiphers" num="0"></byte-array>
-<boolean name="Shared" value="true" />
-<boolean name="AutoJoinEnabled" value="true" />
-<boolean name="Trusted" value="true" />
-<null name="BSSID" />
-<int name="Status" value="1" />
-<null name="FQDN" />
-<null name="ProviderFriendlyName" />
-<null name="LinkedNetworksList" />
-<null name="DefaultGwMacAddress" />
-<boolean name="ValidatedInternetAccess" value="false" />
-<boolean name="NoInternetAccessExpected" value="false" />
-<boolean name="MeteredHint" value="false" />
-<int name="MeteredOverride" value="0" />
-<boolean name="UseExternalScores" value="false" />
-<int name="NumAssociation" value="0" />
-<int name="CreatorUid" value="1000" />
-<string name="CreatorName">android.uid.system:1000</string>
-<int name="LastUpdateUid" value="1000" />
-<string name="LastUpdateName">android.uid.system:1000</string>
-<int name="LastConnectUid" value="1000" />
-<boolean name="IsLegacyPasspointConfig" value="false" />
-<long-array name="RoamingConsortiumOIs" num="0" />
-<string name="RandomizedMacAddress">a6:3d:b0:13:ed:41</string>
-<int name="MacRandomizationSetting" value="1" />
-<int name="CarrierId" value="-1" />
-</WifiConfiguration>
-<NetworkStatus>
-<string name="SelectionStatus">NETWORK_SELECTION_PERMANENTLY_DISABLED</string>
-<string name="DisableReason">NETWORK_SELECTION_DISABLED_BY_WRONG_PASSWORD</string>
-<null name="ConnectChoice" />
-<boolean name="HasEverConnected" value="false" />
-</NetworkStatus>
-<IpConfiguration>
-<string name="IpAssignment">DHCP</string>
-<string name="ProxySettings">NONE</string>
-</IpConfiguration>
-</Network>
-</NetworkList>
-<MacAddressMap>
-<map name="MacMapEntry" />
-</MacAddressMap>
-<Settings>
-<map name="Values">
-<boolean name="wifi_p2p_pending_factory_reset" value="false" />
-<boolean name="wifi_scan_throttle_enabled" value="true" />
-<null name="wifi_p2p_device_name" />
-<boolean name="wifi_scan_always_enabled" value="false" />
-<boolean name="wifi_verbose_logging_enabled" value="true" />
-</map>
-</Settings>
-<PasspointConfigData>
-<long name="ProviderIndex" value="0" />
-</PasspointConfigData>
-</WifiConfigStoreData>
diff --git a/wifi/java/android/net/wifi/migration_samples/Shared_WifiConfigStoreSoftAp.xml b/wifi/java/android/net/wifi/migration_samples/Shared_WifiConfigStoreSoftAp.xml
deleted file mode 100644
index fd99dd3df8b2..000000000000
--- a/wifi/java/android/net/wifi/migration_samples/Shared_WifiConfigStoreSoftAp.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
-<WifiConfigStoreData>
-<int name="Version" value="3" />
-<SoftAp>
-<string name="SSID">HOTSPOT_SSID</string>
-<int name="ApBand" value="1" />
-<int name="Channel" value="0" />
-<boolean name="HiddenSSID" value="false" />
-<int name="SecurityType" value="1" />
-<string name="Passphrase">blahblahblah</string>
-<int name="MaxNumberOfClients" value="0" />
-<boolean name="ClientControlByUser" value="false" />
-<boolean name="AutoShutdownEnabled" value="true" />
-<long name="ShutdownTimeoutMillis" value="0" />
-<BlockedClientList>
-<string name="ClientMacAddress">00:11:22:33:44:55</string>
-</BlockedClientList>
-<AllowedClientList>
-<string name="ClientMacAddress">aa:bb:cc:dd:ee:ff</string>
-</AllowedClientList>
-</SoftAp>
-</WifiConfigStoreData>
diff --git a/wifi/java/android/net/wifi/migration_samples/User_WifiConfigStore.xml b/wifi/java/android/net/wifi/migration_samples/User_WifiConfigStore.xml
deleted file mode 100644
index 67d5aab215f2..000000000000
--- a/wifi/java/android/net/wifi/migration_samples/User_WifiConfigStore.xml
+++ /dev/null
@@ -1,81 +0,0 @@
-<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
-<WifiConfigStoreData>
-<int name="Version" value="3" />
-<NetworkList />
-<PasspointConfigData>
-<ProviderList>
-<Provider>
-<long name="ProviderID" value="0" />
-<int name="CreatorUID" value="10085" />
-<string name="PackageName">com.android.certinstaller</string>
-<list name="CaCertificateAliases">
-<string>HS2_0_0</string>
-</list>
-<null name="ClientPrivateKeyAlias" />
-<boolean name="HasEverConnected" value="false" />
-<boolean name="IsFromSuggestion" value="false" />
-<boolean name="IsTrusted" value="true" />
-<Configuration>
-<int name="UpdateIdentifier" value="-2147483648" />
-<int name="CredentialPriority" value="-2147483648" />
-<null name="TrustRootCertList" />
-<long name="SubscriptionCreationTime" value="-9223372036854775808" />
-<long name="SubscriptionExpirationTime" value="-9223372036854775808" />
-<null name="SubscriptionType" />
-<long name="UsageLimitTimePeriod" value="-9223372036854775808" />
-<long name="UsageLimitStartTime" value="-9223372036854775808" />
-<long name="UsageLimitDataLimit" value="-9223372036854775808" />
-<long name="UsageLimitTimeLimit" value="-9223372036854775808" />
-<HomeSP>
-<string name="FQDN">Passpoint.net</string>
-<string name="FriendlyName">Passpoint Friendly Name</string>
-<null name="IconURL" />
-<null name="HomeNetworkIDs" />
-<null name="MatchAllOIs" />
-<null name="MatchAnyOIs" />
-<null name="OtherHomePartners" />
-<null name="RoamingConsortiumOIs" />
-</HomeSP>
-<Credential>
-<long name="CreationTime" value="-9223372036854775808" />
-<long name="ExpirationTime" value="-9223372036854775808" />
-<string name="Realm">passpoint.com</string>
-<boolean name="CheckAAAServerCertStatus" value="false" />
-<UserCredential>
-<string name="Username">blahblahblah</string>
-<string name="Password">doubleblahlah</string>
-<boolean name="MachineManaged" value="true" />
-<null name="SoftTokenApp" />
-<boolean name="AbleToShare" value="false" />
-<int name="EAPType" value="21" />
-<string name="NonEAPInnerMethod">PAP</string>
-</UserCredential>
-</Credential>
-<int name="CarrierId" value="-1" />
-<boolean name="AutoJoinEnabled" value="true" />
-<boolean name="IsMacRandomizationEnabled" value="true" />
-<int name="MeteredOverride" value="0" />
-</Configuration>
-<null name="RemediationCaCertificateAlias" />
-</Provider>
-</ProviderList>
-</PasspointConfigData>
-<OpenNetworkNotifierBlacklistConfigData />
-<NetworkRequestMap>
-<ApprovedAccessPointsPerApp>
-<string name="RequestorPackageName">com.android.cts.verifier</string>
-<AccessPoint>
-<string name="SSID">OPEN_SSID</string>
-<string name="BSSID">00:11:22:33:44:55</string>
-<int name="NetworkType" value="0" />
-</AccessPoint>
-</ApprovedAccessPointsPerApp>
-</NetworkRequestMap>
-<WakeupConfigStoreData>
-<FeatureState>
-<boolean name="IsActive" value="false" />
-<boolean name="IsOnboarded" value="false" />
-<int name="NotificationsShown" value="1" />
-</FeatureState>
-</WakeupConfigStoreData>
-</WifiConfigStoreData>
diff --git a/wifi/java/android/net/wifi/migration_samples/User_WifiConfigStoreNetworkSuggestions.xml b/wifi/java/android/net/wifi/migration_samples/User_WifiConfigStoreNetworkSuggestions.xml
deleted file mode 100644
index 4ecdd29709b4..000000000000
--- a/wifi/java/android/net/wifi/migration_samples/User_WifiConfigStoreNetworkSuggestions.xml
+++ /dev/null
@@ -1,155 +0,0 @@
-<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
-<WifiConfigStoreData>
-<int name="Version" value="3" />
-<NetworkSuggestionMap>
-<NetworkSuggestionPerApp>
-<string name="SuggestorPackageName">com.android.cts.verifier</string>
-<null name="SuggestorFeatureId" />
-<boolean name="SuggestorHasUserApproved" value="true" />
-<int name="SuggestorMaxSize" value="1" />
-<int name="SuggestorUid" value="10228" />
-<int name="SuggestorCarrierId" value="-1" />
-<NetworkSuggestion>
-<WifiConfiguration>
-<string name="ConfigKey">&quot;OPEN_SSID&quot;NONE</string>
-<string name="SSID">&quot;OPEN_SSID&quot;</string>
-<null name="PreSharedKey" />
-<null name="WEPKeys" />
-<int name="WEPTxKeyIndex" value="0" />
-<boolean name="HiddenSSID" value="false" />
-<boolean name="RequirePMF" value="false" />
-<byte-array name="AllowedKeyMgmt" num="1">01</byte-array>
-<byte-array name="AllowedProtocols" num="0"></byte-array>
-<byte-array name="AllowedAuthAlgos" num="0"></byte-array>
-<byte-array name="AllowedGroupCiphers" num="0"></byte-array>
-<byte-array name="AllowedPairwiseCiphers" num="0"></byte-array>
-<byte-array name="AllowedGroupMgmtCiphers" num="0"></byte-array>
-<byte-array name="AllowedSuiteBCiphers" num="0"></byte-array>
-<boolean name="Shared" value="true" />
-<boolean name="AutoJoinEnabled" value="true" />
-<boolean name="Trusted" value="true" />
-<null name="BSSID" />
-<int name="Status" value="0" />
-<null name="FQDN" />
-<null name="ProviderFriendlyName" />
-<null name="LinkedNetworksList" />
-<null name="DefaultGwMacAddress" />
-<boolean name="ValidatedInternetAccess" value="false" />
-<boolean name="NoInternetAccessExpected" value="false" />
-<boolean name="MeteredHint" value="false" />
-<int name="MeteredOverride" value="1" />
-<boolean name="UseExternalScores" value="false" />
-<int name="NumAssociation" value="0" />
-<int name="CreatorUid" value="10228" />
-<string name="CreatorName">com.android.cts.verifier</string>
-<int name="LastUpdateUid" value="-1" />
-<null name="LastUpdateName" />
-<int name="LastConnectUid" value="0" />
-<boolean name="IsLegacyPasspointConfig" value="false" />
-<long-array name="RoamingConsortiumOIs" num="0" />
-<string name="RandomizedMacAddress">02:00:00:00:00:00</string>
-<int name="MacRandomizationSetting" value="1" />
-<int name="CarrierId" value="-1" />
-</WifiConfiguration>
-<boolean name="IsAppInteractionRequired" value="false" />
-<boolean name="IsUserInteractionRequired" value="false" />
-<boolean name="IsUserAllowedToManuallyConnect" value="false" />
-<boolean name="InitializedAutoJoinEnabled" value="true" />
-<boolean name="AutoJoinEnabled" value="true" />
-</NetworkSuggestion>
-<NetworkSuggestion>
-<WifiConfiguration>
-<string name="ConfigKey">passpoint.net</string>
-<null name="SSID" />
-<null name="PreSharedKey" />
-<null name="WEPKeys" />
-<int name="WEPTxKeyIndex" value="0" />
-<boolean name="HiddenSSID" value="false" />
-<boolean name="RequirePMF" value="false" />
-<byte-array name="AllowedKeyMgmt" num="0"></byte-array>
-<byte-array name="AllowedProtocols" num="0"></byte-array>
-<byte-array name="AllowedAuthAlgos" num="0"></byte-array>
-<byte-array name="AllowedGroupCiphers" num="0"></byte-array>
-<byte-array name="AllowedPairwiseCiphers" num="0"></byte-array>
-<byte-array name="AllowedGroupMgmtCiphers" num="0"></byte-array>
-<byte-array name="AllowedSuiteBCiphers" num="0"></byte-array>
-<boolean name="Shared" value="true" />
-<boolean name="AutoJoinEnabled" value="true" />
-<boolean name="Trusted" value="true" />
-<null name="BSSID" />
-<int name="Status" value="0" />
-<string name="FQDN">passpoint.net</string>
-<null name="ProviderFriendlyName" />
-<null name="LinkedNetworksList" />
-<null name="DefaultGwMacAddress" />
-<boolean name="ValidatedInternetAccess" value="false" />
-<boolean name="NoInternetAccessExpected" value="false" />
-<boolean name="MeteredHint" value="false" />
-<int name="MeteredOverride" value="0" />
-<boolean name="UseExternalScores" value="false" />
-<int name="NumAssociation" value="0" />
-<int name="CreatorUid" value="1000" />
-<string name="CreatorName">com.android.cts.verifier</string>
-<int name="LastUpdateUid" value="-1" />
-<null name="LastUpdateName" />
-<int name="LastConnectUid" value="0" />
-<boolean name="IsLegacyPasspointConfig" value="false" />
-<long-array name="RoamingConsortiumOIs" num="0" />
-<string name="RandomizedMacAddress">02:00:00:00:00:00</string>
-<int name="MacRandomizationSetting" value="1" />
-<int name="CarrierId" value="-1" />
-<boolean name="IsMostRecentlyConnected" value="false" />
-</WifiConfiguration>
-<PasspointConfiguration>
-<int name="UpdateIdentifier" value="-2147483648" />
-<int name="CredentialPriority" value="-2147483648" />
-<null name="TrustRootCertList" />
-<long name="SubscriptionCreationTime" value="-9223372036854775808" />
-<long name="SubscriptionExpirationTime" value="-9223372036854775808" />
-<null name="SubscriptionType" />
-<long name="UsageLimitTimePeriod" value="-9223372036854775808" />
-<long name="UsageLimitStartTime" value="-9223372036854775808" />
-<long name="UsageLimitDataLimit" value="-9223372036854775808" />
-<long name="UsageLimitTimeLimit" value="-9223372036854775808" />
-<HomeSP>
-<string name="FQDN">passpoint.net</string>
-<string name="FriendlyName">Passpoint Friendly Name</string>
-<null name="IconURL" />
-<null name="HomeNetworkIDs" />
-<null name="MatchAllOIs" />
-<null name="MatchAnyOIs" />
-<null name="OtherHomePartners" />
-<null name="RoamingConsortiumOIs" />
-</HomeSP>
-<Credential>
-<long name="CreationTime" value="-9223372036854775808" />
-<long name="ExpirationTime" value="-9223372036854775808" />
-<string name="Realm">passpoint.com</string>
-<boolean name="CheckAAAServerCertStatus" value="false" />
-<UserCredential>
-<string name="Username">blahblahblah</string>
-<string name="Password">doubleblahblah</string>
-<boolean name="MachineManaged" value="false" />
-<null name="SoftTokenApp" />
-<boolean name="AbleToShare" value="false" />
-<int name="EAPType" value="21" />
-<string name="NonEAPInnerMethod">PAP</string>
-</UserCredential>
-</Credential>
-<int name="CarrierId" value="-1" />
-<boolean name="AutoJoinEnabled" value="true" />
-<boolean name="IsMacRandomizationEnabled" value="true" />
-<int name="MeteredOverride" value="0" />
-</PasspointConfiguration>
-<boolean name="IsAppInteractionRequired" value="false" />
-<boolean name="IsUserInteractionRequired" value="false" />
-<boolean name="IsUserAllowedToManuallyConnect" value="true" />
-<boolean name="InitializedAutoJoinEnabled" value="true" />
-<boolean name="AutoJoinEnabled" value="true" />
-</NetworkSuggestion>
-</NetworkSuggestionPerApp>
-</NetworkSuggestionMap>
-<ImsiPrivacyProtectionExemptionMap>
-<map name="CarrierExemptionMap" />
-</ImsiPrivacyProtectionExemptionMap>
-</WifiConfigStoreData>
diff --git a/wifi/java/android/net/wifi/nl80211/ChannelSettings.java b/wifi/java/android/net/wifi/nl80211/ChannelSettings.java
deleted file mode 100644
index 4c14fd499c28..000000000000
--- a/wifi/java/android/net/wifi/nl80211/ChannelSettings.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2016 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.nl80211;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
-
-import java.util.Objects;
-
-/**
- * ChannelSettings for wificond
- *
- * @hide
- */
-public class ChannelSettings implements Parcelable {
- private static final String TAG = "ChannelSettings";
-
- public int frequency;
-
- /** public constructor */
- public ChannelSettings() { }
-
- /** override comparator */
- @Override
- public boolean equals(Object rhs) {
- if (this == rhs) return true;
- if (!(rhs instanceof ChannelSettings)) {
- return false;
- }
- ChannelSettings channel = (ChannelSettings) rhs;
- if (channel == null) {
- return false;
- }
- return frequency == channel.frequency;
- }
-
- /** override hash code */
- @Override
- public int hashCode() {
- return Objects.hash(frequency);
- }
-
- /** implement Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /**
- * implement Parcelable interface
- * |flags| is ignored.
- **/
- @Override
- public void writeToParcel(Parcel out, int flags) {
- out.writeInt(frequency);
- }
-
- /** implement Parcelable interface */
- public static final Parcelable.Creator<ChannelSettings> CREATOR =
- new Parcelable.Creator<ChannelSettings>() {
- /**
- * Caller is responsible for providing a valid parcel.
- */
- @Override
- public ChannelSettings createFromParcel(Parcel in) {
- ChannelSettings result = new ChannelSettings();
- result.frequency = in.readInt();
- if (in.dataAvail() != 0) {
- Log.e(TAG, "Found trailing data after parcel parsing.");
- }
-
- return result;
- }
-
- @Override
- public ChannelSettings[] newArray(int size) {
- return new ChannelSettings[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/nl80211/DeviceWiphyCapabilities.java b/wifi/java/android/net/wifi/nl80211/DeviceWiphyCapabilities.java
deleted file mode 100644
index bb0cc975a3db..000000000000
--- a/wifi/java/android/net/wifi/nl80211/DeviceWiphyCapabilities.java
+++ /dev/null
@@ -1,283 +0,0 @@
-/*
- * Copyright (C) 2020 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.nl80211;
-
-import android.annotation.NonNull;
-import android.annotation.SystemApi;
-import android.net.wifi.ScanResult;
-import android.net.wifi.WifiAnnotations.ChannelWidth;
-import android.net.wifi.WifiAnnotations.WifiStandard;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
-
-import java.util.Objects;
-
-/**
- * DeviceWiphyCapabilities for wificond
- *
- * Contains the WiFi physical layer attributes and capabilities of the device.
- * It is used to collect these attributes from the device driver via wificond.
- *
- * @hide
- */
-@SystemApi
-public final class DeviceWiphyCapabilities implements Parcelable {
- private static final String TAG = "DeviceWiphyCapabilities";
-
- private boolean m80211nSupported;
- private boolean m80211acSupported;
- private boolean m80211axSupported;
- private boolean mChannelWidth160MhzSupported;
- private boolean mChannelWidth80p80MhzSupported;
- private int mMaxNumberTxSpatialStreams;
- private int mMaxNumberRxSpatialStreams;
-
-
- /** public constructor */
- public DeviceWiphyCapabilities() {
- m80211nSupported = false;
- m80211acSupported = false;
- m80211axSupported = false;
- mChannelWidth160MhzSupported = false;
- mChannelWidth80p80MhzSupported = false;
- mMaxNumberTxSpatialStreams = 1;
- mMaxNumberRxSpatialStreams = 1;
- }
-
- /**
- * Get the IEEE 802.11 standard support
- *
- * @param standard the IEEE 802.11 standard to check on its support.
- * valid values from {@link ScanResult}'s {@code WIFI_STANDARD_}
- * @return {@code true} if supported, {@code false} otherwise.
- */
- public boolean isWifiStandardSupported(@WifiStandard int standard) {
- switch (standard) {
- case ScanResult.WIFI_STANDARD_LEGACY:
- return true;
- case ScanResult.WIFI_STANDARD_11N:
- return m80211nSupported;
- case ScanResult.WIFI_STANDARD_11AC:
- return m80211acSupported;
- case ScanResult.WIFI_STANDARD_11AX:
- return m80211axSupported;
- default:
- Log.e(TAG, "isWifiStandardSupported called with invalid standard: " + standard);
- return false;
- }
- }
-
- /**
- * Set the IEEE 802.11 standard support
- *
- * @param standard the IEEE 802.11 standard to set its support.
- * valid values from {@link ScanResult}'s {@code WIFI_STANDARD_}
- * @param support {@code true} if supported, {@code false} otherwise.
- */
- public void setWifiStandardSupport(@WifiStandard int standard, boolean support) {
- switch (standard) {
- case ScanResult.WIFI_STANDARD_11N:
- m80211nSupported = support;
- break;
- case ScanResult.WIFI_STANDARD_11AC:
- m80211acSupported = support;
- break;
- case ScanResult.WIFI_STANDARD_11AX:
- m80211axSupported = support;
- break;
- default:
- Log.e(TAG, "setWifiStandardSupport called with invalid standard: " + standard);
- }
- }
-
- /**
- * Get the support for channel bandwidth
- *
- * @param chWidth valid values from {@link ScanResult}'s {@code CHANNEL_WIDTH_}
- *
- * @return {@code true} if supported, {@code false} otherwise.
- */
- public boolean isChannelWidthSupported(@ChannelWidth int chWidth) {
- switch (chWidth) {
- case ScanResult.CHANNEL_WIDTH_20MHZ:
- return true;
- case ScanResult.CHANNEL_WIDTH_40MHZ:
- return (m80211nSupported || m80211acSupported || m80211axSupported);
- case ScanResult.CHANNEL_WIDTH_80MHZ:
- return (m80211acSupported || m80211axSupported);
- case ScanResult.CHANNEL_WIDTH_160MHZ:
- return mChannelWidth160MhzSupported;
- case ScanResult.CHANNEL_WIDTH_80MHZ_PLUS_MHZ:
- return mChannelWidth80p80MhzSupported;
- default:
- Log.e(TAG, "isChannelWidthSupported called with invalid channel width: " + chWidth);
- }
- return false;
- }
-
- /**
- * Set support for channel bandwidth
- *
- * @param chWidth valid values are {@link ScanResult#CHANNEL_WIDTH_160MHZ} and
- * {@link ScanResult#CHANNEL_WIDTH_80MHZ_PLUS_MHZ}
- * @param support {@code true} if supported, {@code false} otherwise.
- *
- * @hide
- */
- public void setChannelWidthSupported(@ChannelWidth int chWidth, boolean support) {
- switch (chWidth) {
- case ScanResult.CHANNEL_WIDTH_160MHZ:
- mChannelWidth160MhzSupported = support;
- break;
- case ScanResult.CHANNEL_WIDTH_80MHZ_PLUS_MHZ:
- mChannelWidth80p80MhzSupported = support;
- break;
- default:
- Log.e(TAG, "setChannelWidthSupported called with Invalid channel width: "
- + chWidth);
- }
- }
-
- /**
- * Get maximum number of transmit spatial streams
- *
- * @return number of spatial streams
- */
- public int getMaxNumberTxSpatialStreams() {
- return mMaxNumberTxSpatialStreams;
- }
-
- /**
- * Set maximum number of transmit spatial streams
- *
- * @param streams number of spatial streams
- *
- * @hide
- */
- public void setMaxNumberTxSpatialStreams(int streams) {
- mMaxNumberTxSpatialStreams = streams;
- }
-
- /**
- * Get maximum number of receive spatial streams
- *
- * @return number of streams
- */
- public int getMaxNumberRxSpatialStreams() {
- return mMaxNumberRxSpatialStreams;
- }
-
- /**
- * Set maximum number of receive spatial streams
- *
- * @param streams number of streams
- *
- * @hide
- */
- public void setMaxNumberRxSpatialStreams(int streams) {
- mMaxNumberRxSpatialStreams = streams;
- }
-
- /** override comparator */
- @Override
- public boolean equals(Object rhs) {
- if (this == rhs) return true;
- if (!(rhs instanceof DeviceWiphyCapabilities)) {
- return false;
- }
- DeviceWiphyCapabilities capa = (DeviceWiphyCapabilities) rhs;
-
- return m80211nSupported == capa.m80211nSupported
- && m80211acSupported == capa.m80211acSupported
- && m80211axSupported == capa.m80211axSupported
- && mChannelWidth160MhzSupported == capa.mChannelWidth160MhzSupported
- && mChannelWidth80p80MhzSupported == capa.mChannelWidth80p80MhzSupported
- && mMaxNumberTxSpatialStreams == capa.mMaxNumberTxSpatialStreams
- && mMaxNumberRxSpatialStreams == capa.mMaxNumberRxSpatialStreams;
- }
-
- /** override hash code */
- @Override
- public int hashCode() {
- return Objects.hash(m80211nSupported, m80211acSupported, m80211axSupported,
- mChannelWidth160MhzSupported, mChannelWidth80p80MhzSupported,
- mMaxNumberTxSpatialStreams, mMaxNumberRxSpatialStreams);
- }
-
- /** implement Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /**
- * implement Parcelable interface
- * |flags| is ignored.
- */
- @Override
- public void writeToParcel(@NonNull Parcel out, int flags) {
- out.writeBoolean(m80211nSupported);
- out.writeBoolean(m80211acSupported);
- out.writeBoolean(m80211axSupported);
- out.writeBoolean(mChannelWidth160MhzSupported);
- out.writeBoolean(mChannelWidth80p80MhzSupported);
- out.writeInt(mMaxNumberTxSpatialStreams);
- out.writeInt(mMaxNumberRxSpatialStreams);
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("m80211nSupported:").append(m80211nSupported ? "Yes" : "No");
- sb.append("m80211acSupported:").append(m80211acSupported ? "Yes" : "No");
- sb.append("m80211axSupported:").append(m80211axSupported ? "Yes" : "No");
- sb.append("mChannelWidth160MhzSupported: ")
- .append(mChannelWidth160MhzSupported ? "Yes" : "No");
- sb.append("mChannelWidth80p80MhzSupported: ")
- .append(mChannelWidth80p80MhzSupported ? "Yes" : "No");
- sb.append("mMaxNumberTxSpatialStreams: ").append(mMaxNumberTxSpatialStreams);
- sb.append("mMaxNumberRxSpatialStreams: ").append(mMaxNumberRxSpatialStreams);
-
- return sb.toString();
- }
-
- /** implement Parcelable interface */
- public static final @NonNull Parcelable.Creator<DeviceWiphyCapabilities> CREATOR =
- new Parcelable.Creator<DeviceWiphyCapabilities>() {
- /**
- * Caller is responsible for providing a valid parcel.
- */
- @Override
- public DeviceWiphyCapabilities createFromParcel(Parcel in) {
- DeviceWiphyCapabilities capabilities = new DeviceWiphyCapabilities();
- capabilities.m80211nSupported = in.readBoolean();
- capabilities.m80211acSupported = in.readBoolean();
- capabilities.m80211axSupported = in.readBoolean();
- capabilities.mChannelWidth160MhzSupported = in.readBoolean();
- capabilities.mChannelWidth80p80MhzSupported = in.readBoolean();
- capabilities.mMaxNumberTxSpatialStreams = in.readInt();
- capabilities.mMaxNumberRxSpatialStreams = in.readInt();
- return capabilities;
- }
-
- @Override
- public DeviceWiphyCapabilities[] newArray(int size) {
- return new DeviceWiphyCapabilities[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/nl80211/HiddenNetwork.java b/wifi/java/android/net/wifi/nl80211/HiddenNetwork.java
deleted file mode 100644
index b1475b2c7b43..000000000000
--- a/wifi/java/android/net/wifi/nl80211/HiddenNetwork.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2016 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.nl80211;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.Arrays;
-
-/**
- * HiddenNetwork for wificond
- *
- * @hide
- */
-public class HiddenNetwork implements Parcelable {
- private static final String TAG = "HiddenNetwork";
-
- public byte[] ssid;
-
- /** public constructor */
- public HiddenNetwork() { }
-
- /** override comparator */
- @Override
- public boolean equals(Object rhs) {
- if (this == rhs) return true;
- if (!(rhs instanceof HiddenNetwork)) {
- return false;
- }
- HiddenNetwork network = (HiddenNetwork) rhs;
- return Arrays.equals(ssid, network.ssid);
- }
-
- /** override hash code */
- @Override
- public int hashCode() {
- return Arrays.hashCode(ssid);
- }
-
- /** implement Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /**
- * implement Parcelable interface
- * |flags| is ignored.
- */
- @Override
- public void writeToParcel(Parcel out, int flags) {
- out.writeByteArray(ssid);
- }
-
- /** implement Parcelable interface */
- public static final Parcelable.Creator<HiddenNetwork> CREATOR =
- new Parcelable.Creator<HiddenNetwork>() {
- /**
- * Caller is responsible for providing a valid parcel.
- */
- @Override
- public HiddenNetwork createFromParcel(Parcel in) {
- HiddenNetwork result = new HiddenNetwork();
- result.ssid = in.createByteArray();
- return result;
- }
-
- @Override
- public HiddenNetwork[] newArray(int size) {
- return new HiddenNetwork[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/nl80211/NativeScanResult.java b/wifi/java/android/net/wifi/nl80211/NativeScanResult.java
deleted file mode 100644
index 7a9b34b16058..000000000000
--- a/wifi/java/android/net/wifi/nl80211/NativeScanResult.java
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
- * Copyright (C) 2016 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.nl80211;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Raw scan result data from the wificond daemon.
- *
- * @hide
- */
-@SystemApi
-public final class NativeScanResult implements Parcelable {
- private static final String TAG = "NativeScanResult";
-
- /** @hide */
- @VisibleForTesting
- public byte[] ssid;
- /** @hide */
- @VisibleForTesting
- public byte[] bssid;
- /** @hide */
- @VisibleForTesting
- public byte[] infoElement;
- /** @hide */
- @VisibleForTesting
- public int frequency;
- /** @hide */
- @VisibleForTesting
- public int signalMbm;
- /** @hide */
- @VisibleForTesting
- public long tsf;
- /** @hide */
- @VisibleForTesting
- @BssCapabilityBits public int capability;
- /** @hide */
- @VisibleForTesting
- public boolean associated;
- /** @hide */
- @VisibleForTesting
- public List<RadioChainInfo> radioChainInfos;
-
- /**
- * Returns the SSID raw byte array of the AP represented by this scan result.
- *
- * @return A byte array.
- */
- @NonNull public byte[] getSsid() {
- return ssid;
- }
-
- /**
- * Returns the MAC address (BSSID) of the AP represented by this scan result.
- *
- * @return a MacAddress or null on error.
- */
- @Nullable public MacAddress getBssid() {
- try {
- return MacAddress.fromBytes(bssid);
- } catch (IllegalArgumentException e) {
- Log.e(TAG, "Illegal argument " + Arrays.toString(bssid), e);
- return null;
- }
- }
-
- /**
- * Returns the raw bytes of the information element advertised by the AP represented by this
- * scan result.
- *
- * @return A byte array, possibly null or containing an invalid TLV configuration.
- */
- @NonNull public byte[] getInformationElements() {
- return infoElement;
- }
-
- /**
- * Returns the frequency (in MHz) on which the AP represented by this scan result was observed.
- *
- * @return The frequency in MHz.
- */
- public int getFrequencyMhz() {
- return frequency;
- }
-
- /**
- * Return the signal strength of probe response/beacon in (100 * dBm).
- *
- * @return Signal strenght in (100 * dBm).
- */
- public int getSignalMbm() {
- return signalMbm;
- }
-
- /**
- * Return the TSF (Timing Synchronization Function) of the received probe response/beacon.
- * @return
- */
- public long getTsf() {
- return tsf;
- }
-
- /**
- * Return a boolean indicating whether or not we're associated to the AP represented by this
- * scan result.
- *
- * @return A boolean indicating association.
- */
- public boolean isAssociated() {
- return associated;
- }
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(flag = true, prefix = {"BSS_CAPABILITY_"},
- value = {BSS_CAPABILITY_ESS,
- BSS_CAPABILITY_IBSS,
- BSS_CAPABILITY_CF_POLLABLE,
- BSS_CAPABILITY_CF_POLL_REQUEST,
- BSS_CAPABILITY_PRIVACY,
- BSS_CAPABILITY_SHORT_PREAMBLE,
- BSS_CAPABILITY_PBCC,
- BSS_CAPABILITY_CHANNEL_AGILITY,
- BSS_CAPABILITY_SPECTRUM_MANAGEMENT,
- BSS_CAPABILITY_QOS,
- BSS_CAPABILITY_SHORT_SLOT_TIME,
- BSS_CAPABILITY_APSD,
- BSS_CAPABILITY_RADIO_MANAGEMENT,
- BSS_CAPABILITY_DSSS_OFDM,
- BSS_CAPABILITY_DELAYED_BLOCK_ACK,
- BSS_CAPABILITY_IMMEDIATE_BLOCK_ACK,
- BSS_CAPABILITY_DMG_ESS,
- BSS_CAPABILITY_DMG_IBSS
- })
- public @interface BssCapabilityBits { }
-
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): ESS.
- */
- public static final int BSS_CAPABILITY_ESS = 0x1 << 0;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): IBSS.
- */
- public static final int BSS_CAPABILITY_IBSS = 0x1 << 1;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): CF Pollable.
- */
- public static final int BSS_CAPABILITY_CF_POLLABLE = 0x1 << 2;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): CF-Poll Request.
- */
- public static final int BSS_CAPABILITY_CF_POLL_REQUEST = 0x1 << 3;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): Privacy.
- */
- public static final int BSS_CAPABILITY_PRIVACY = 0x1 << 4;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): Short Preamble.
- */
- public static final int BSS_CAPABILITY_SHORT_PREAMBLE = 0x1 << 5;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): PBCC.
- */
- public static final int BSS_CAPABILITY_PBCC = 0x1 << 6;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): Channel Agility.
- */
- public static final int BSS_CAPABILITY_CHANNEL_AGILITY = 0x1 << 7;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): Spectrum Management.
- */
- public static final int BSS_CAPABILITY_SPECTRUM_MANAGEMENT = 0x1 << 8;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): QoS.
- */
- public static final int BSS_CAPABILITY_QOS = 0x1 << 9;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): Short Slot Time.
- */
- public static final int BSS_CAPABILITY_SHORT_SLOT_TIME = 0x1 << 10;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): APSD.
- */
- public static final int BSS_CAPABILITY_APSD = 0x1 << 11;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): Radio Management.
- */
- public static final int BSS_CAPABILITY_RADIO_MANAGEMENT = 0x1 << 12;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): DSSS-OFDM.
- */
- public static final int BSS_CAPABILITY_DSSS_OFDM = 0x1 << 13;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): Delayed Block Ack.
- */
- public static final int BSS_CAPABILITY_DELAYED_BLOCK_ACK = 0x1 << 14;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): Immediate Block Ack.
- */
- public static final int BSS_CAPABILITY_IMMEDIATE_BLOCK_ACK = 0x1 << 15;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): DMG ESS.
- * In DMG bits 0 and 1 are parsed together, where ESS=0x3 and IBSS=0x1
- */
- public static final int BSS_CAPABILITY_DMG_ESS = 0x3;
- /**
- * BSS capability bit (see IEEE Std 802.11: 9.4.1.4): DMG IBSS.
- */
- public static final int BSS_CAPABILITY_DMG_IBSS = 0x1;
-
- /**
- * Returns the capabilities of the AP repseresented by this scan result as advertised in the
- * received probe response or beacon.
- *
- * This is a bit mask describing the capabilities of a BSS. See IEEE Std 802.11: 9.4.1.4: one
- * of the {@code BSS_CAPABILITY_*} flags.
- *
- * @return a bit mask of capabilities.
- */
- @BssCapabilityBits public int getCapabilities() {
- return capability;
- }
-
- /**
- * Returns details of the signal received on each radio chain for the AP represented by this
- * scan result in a list of {@link RadioChainInfo} elements.
- *
- * @return A list of {@link RadioChainInfo} - possibly empty in case of error.
- */
- @NonNull public List<RadioChainInfo> getRadioChainInfos() {
- return radioChainInfos;
- }
-
- /**
- * Construct an empty native scan result.
- */
- public NativeScanResult() { }
-
- /** implement Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /** implement Parcelable interface */
- @Override
- public void writeToParcel(@NonNull Parcel out, int flags) {
- out.writeByteArray(ssid);
- out.writeByteArray(bssid);
- out.writeByteArray(infoElement);
- out.writeInt(frequency);
- out.writeInt(signalMbm);
- out.writeLong(tsf);
- out.writeInt(capability);
- out.writeInt(associated ? 1 : 0);
- out.writeTypedList(radioChainInfos);
- }
-
- /** implement Parcelable interface */
- @NonNull public static final Parcelable.Creator<NativeScanResult> CREATOR =
- new Parcelable.Creator<NativeScanResult>() {
- @Override
- public NativeScanResult createFromParcel(Parcel in) {
- NativeScanResult result = new NativeScanResult();
- result.ssid = in.createByteArray();
- if (result.ssid == null) {
- result.ssid = new byte[0];
- }
- result.bssid = in.createByteArray();
- if (result.bssid == null) {
- result.bssid = new byte[0];
- }
- result.infoElement = in.createByteArray();
- if (result.infoElement == null) {
- result.infoElement = new byte[0];
- }
- result.frequency = in.readInt();
- result.signalMbm = in.readInt();
- result.tsf = in.readLong();
- result.capability = in.readInt();
- result.associated = (in.readInt() != 0);
- result.radioChainInfos = new ArrayList<>();
- in.readTypedList(result.radioChainInfos, RadioChainInfo.CREATOR);
- return result;
- }
-
- @Override
- public NativeScanResult[] newArray(int size) {
- return new NativeScanResult[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/nl80211/NativeWifiClient.java b/wifi/java/android/net/wifi/nl80211/NativeWifiClient.java
deleted file mode 100644
index 984d7d034302..000000000000
--- a/wifi/java/android/net/wifi/nl80211/NativeWifiClient.java
+++ /dev/null
@@ -1,103 +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 android.net.wifi.nl80211;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.Objects;
-
-/**
- * Structure providing information about clients (STAs) associated with a SoftAp.
- *
- * @hide
- */
-@SystemApi
-public final class NativeWifiClient implements Parcelable {
- private final MacAddress mMacAddress;
-
- /**
- * The MAC address of the client (STA) represented by this object. The MAC address may be null
- * in case of an error.
- */
- @Nullable public MacAddress getMacAddress() {
- return mMacAddress;
- }
-
- /**
- * Construct a native Wi-Fi client.
- */
- public NativeWifiClient(@Nullable MacAddress macAddress) {
- this.mMacAddress = macAddress;
- }
-
- /** override comparator */
- @Override
- public boolean equals(Object rhs) {
- if (this == rhs) return true;
- if (!(rhs instanceof NativeWifiClient)) {
- return false;
- }
- NativeWifiClient other = (NativeWifiClient) rhs;
- return Objects.equals(mMacAddress, other.mMacAddress);
- }
-
- /** override hash code */
- @Override
- public int hashCode() {
- return mMacAddress.hashCode();
- }
-
- /** implement Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /**
- * implement Parcelable interface
- * |flag| is ignored.
- */
- @Override
- public void writeToParcel(@NonNull Parcel out, int flags) {
- out.writeByteArray(mMacAddress.toByteArray());
- }
-
- /** implement Parcelable interface */
- @NonNull public static final Parcelable.Creator<NativeWifiClient> CREATOR =
- new Parcelable.Creator<NativeWifiClient>() {
- @Override
- public NativeWifiClient createFromParcel(Parcel in) {
- MacAddress macAddress;
- try {
- macAddress = MacAddress.fromBytes(in.createByteArray());
- } catch (IllegalArgumentException e) {
- macAddress = null;
- }
- return new NativeWifiClient(macAddress);
- }
-
- @Override
- public NativeWifiClient[] newArray(int size) {
- return new NativeWifiClient[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/nl80211/PnoNetwork.java b/wifi/java/android/net/wifi/nl80211/PnoNetwork.java
deleted file mode 100644
index e8eff09583b9..000000000000
--- a/wifi/java/android/net/wifi/nl80211/PnoNetwork.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (C) 2016 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.nl80211;
-
-import android.annotation.NonNull;
-import android.annotation.SystemApi;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.Arrays;
-import java.util.Objects;
-
-/**
- * Configuration for a PNO (preferred network offload) network used in {@link PnoSettings}. A PNO
- * network allows configuration of a specific network to search for.
- *
- * @hide
- */
-@SystemApi
-public final class PnoNetwork implements Parcelable {
- private boolean mIsHidden;
- private byte[] mSsid;
- private int[] mFrequencies;
-
- /**
- * Indicates whether the PNO network configuration is for a hidden SSID - i.e. a network which
- * does not broadcast its SSID and must be queried explicitly.
- *
- * @return True if the configuration is for a hidden network, false otherwise.
- */
- public boolean isHidden() {
- return mIsHidden;
- }
-
- /**
- * Configure whether the PNO network configuration is for a hidden SSID - i.e. a network which
- * does not broadcast its SSID and must be queried explicitly.
- *
- * @param isHidden True if the configuration is for a hidden network, false otherwise.
- */
- public void setHidden(boolean isHidden) {
- mIsHidden = isHidden;
- }
-
- /**
- * Get the raw bytes for the SSID of the PNO network being scanned for.
- *
- * @return A byte array.
- */
- @NonNull public byte[] getSsid() {
- return mSsid;
- }
-
- /**
- * Set the raw bytes for the SSID of the PNO network being scanned for.
- *
- * @param ssid A byte array.
- */
- public void setSsid(@NonNull byte[] ssid) {
- if (ssid == null) {
- throw new IllegalArgumentException("null argument");
- }
- this.mSsid = ssid;
- }
-
- /**
- * Get the frequencies (in MHz) on which to PNO scan for the current network is being searched
- * for. A null return (i.e. no frequencies configured) indicates that the network is search for
- * on all supported frequencies.
- *
- * @return A array of frequencies (in MHz), a null indicates no configured frequencies.
- */
- @NonNull public int[] getFrequenciesMhz() {
- return mFrequencies;
- }
-
- /**
- * Set the frequencies (in MHz) on which to PNO scan for the current network is being searched
- * for. A null configuration (i.e. no frequencies configured) indicates that the network is
- * search for on all supported frequencies.
- *
- * @param frequenciesMhz an array of frequencies (in MHz), null indicating no configured
- * frequencies.
- */
- public void setFrequenciesMhz(@NonNull int[] frequenciesMhz) {
- if (frequenciesMhz == null) {
- throw new IllegalArgumentException("null argument");
- }
- this.mFrequencies = frequenciesMhz;
- }
-
- /** Construct an uninitialized PnoNetwork object */
- public PnoNetwork() { }
-
- /** override comparator */
- @Override
- public boolean equals(Object rhs) {
- if (this == rhs) return true;
- if (!(rhs instanceof PnoNetwork)) {
- return false;
- }
- PnoNetwork network = (PnoNetwork) rhs;
- return Arrays.equals(mSsid, network.mSsid)
- && Arrays.equals(mFrequencies, network.mFrequencies)
- && mIsHidden == network.mIsHidden;
- }
-
- /** override hash code */
- @Override
- public int hashCode() {
- return Objects.hash(
- mIsHidden,
- Arrays.hashCode(mSsid),
- Arrays.hashCode(mFrequencies));
- }
-
- /** implement Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /**
- * implement Parcelable interface
- * |flag| is ignored.
- */
- @Override
- public void writeToParcel(@NonNull Parcel out, int flags) {
- out.writeInt(mIsHidden ? 1 : 0);
- out.writeByteArray(mSsid);
- out.writeIntArray(mFrequencies);
- }
-
- /** implement Parcelable interface */
- @NonNull public static final Parcelable.Creator<PnoNetwork> CREATOR =
- new Parcelable.Creator<PnoNetwork>() {
- @Override
- public PnoNetwork createFromParcel(Parcel in) {
- PnoNetwork result = new PnoNetwork();
- result.mIsHidden = in.readInt() != 0 ? true : false;
- result.mSsid = in.createByteArray();
- if (result.mSsid == null) {
- result.mSsid = new byte[0];
- }
- result.mFrequencies = in.createIntArray();
- if (result.mFrequencies == null) {
- result.mFrequencies = new int[0];
- }
- return result;
- }
-
- @Override
- public PnoNetwork[] newArray(int size) {
- return new PnoNetwork[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/nl80211/PnoSettings.java b/wifi/java/android/net/wifi/nl80211/PnoSettings.java
deleted file mode 100644
index 00ebe624ba0d..000000000000
--- a/wifi/java/android/net/wifi/nl80211/PnoSettings.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/*
- * Copyright (C) 2016 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.nl80211;
-
-import android.annotation.DurationMillisLong;
-import android.annotation.NonNull;
-import android.annotation.SystemApi;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * Configuration for a PNO (preferred network offload). A mechanism by which scans are offloaded
- * from the host device to the Wi-Fi chip.
- *
- * @hide
- */
-@SystemApi
-public final class PnoSettings implements Parcelable {
- private long mIntervalMs;
- private int mMin2gRssi;
- private int mMin5gRssi;
- private int mMin6gRssi;
- private List<PnoNetwork> mPnoNetworks;
-
- /** Construct an uninitialized PnoSettings object */
- public PnoSettings() { }
-
- /**
- * Get the requested PNO scan interval in milliseconds.
- *
- * @return An interval in milliseconds.
- */
- public @DurationMillisLong long getIntervalMillis() {
- return mIntervalMs;
- }
-
- /**
- * Set the requested PNO scan interval in milliseconds.
- *
- * @param intervalMillis An interval in milliseconds.
- */
- public void setIntervalMillis(@DurationMillisLong long intervalMillis) {
- this.mIntervalMs = intervalMillis;
- }
-
- /**
- * Get the requested minimum RSSI threshold (in dBm) for APs to report in scan results in the
- * 2.4GHz band.
- *
- * @return An RSSI value in dBm.
- */
- public int getMin2gRssiDbm() {
- return mMin2gRssi;
- }
-
- /**
- * Set the requested minimum RSSI threshold (in dBm) for APs to report in scan scan results in
- * the 2.4GHz band.
- *
- * @param min2gRssiDbm An RSSI value in dBm.
- */
- public void setMin2gRssiDbm(int min2gRssiDbm) {
- this.mMin2gRssi = min2gRssiDbm;
- }
-
- /**
- * Get the requested minimum RSSI threshold (in dBm) for APs to report in scan results in the
- * 5GHz band.
- *
- * @return An RSSI value in dBm.
- */
- public int getMin5gRssiDbm() {
- return mMin5gRssi;
- }
-
- /**
- * Set the requested minimum RSSI threshold (in dBm) for APs to report in scan scan results in
- * the 5GHz band.
- *
- * @param min5gRssiDbm An RSSI value in dBm.
- */
- public void setMin5gRssiDbm(int min5gRssiDbm) {
- this.mMin5gRssi = min5gRssiDbm;
- }
-
- /**
- * Get the requested minimum RSSI threshold (in dBm) for APs to report in scan results in the
- * 6GHz band.
- *
- * @return An RSSI value in dBm.
- */
- public int getMin6gRssiDbm() {
- return mMin6gRssi;
- }
-
- /**
- * Set the requested minimum RSSI threshold (in dBm) for APs to report in scan scan results in
- * the 6GHz band.
- *
- * @param min6gRssiDbm An RSSI value in dBm.
- */
- public void setMin6gRssiDbm(int min6gRssiDbm) {
- this.mMin6gRssi = min6gRssiDbm;
- }
-
- /**
- * Return the configured list of specific networks to search for in a PNO scan.
- *
- * @return A list of {@link PnoNetwork} objects, possibly empty if non configured.
- */
- @NonNull public List<PnoNetwork> getPnoNetworks() {
- return mPnoNetworks;
- }
-
- /**
- * Set the list of specified networks to scan for in a PNO scan. The networks (APs) are
- * specified using {@link PnoNetwork}s. An empty list indicates that all networks are scanned
- * for.
- *
- * @param pnoNetworks A (possibly empty) list of {@link PnoNetwork} objects.
- */
- public void setPnoNetworks(@NonNull List<PnoNetwork> pnoNetworks) {
- this.mPnoNetworks = pnoNetworks;
- }
-
- /** override comparator */
- @Override
- public boolean equals(Object rhs) {
- if (this == rhs) return true;
- if (!(rhs instanceof PnoSettings)) {
- return false;
- }
- PnoSettings settings = (PnoSettings) rhs;
- if (settings == null) {
- return false;
- }
- return mIntervalMs == settings.mIntervalMs
- && mMin2gRssi == settings.mMin2gRssi
- && mMin5gRssi == settings.mMin5gRssi
- && mMin6gRssi == settings.mMin6gRssi
- && mPnoNetworks.equals(settings.mPnoNetworks);
- }
-
- /** override hash code */
- @Override
- public int hashCode() {
- return Objects.hash(mIntervalMs, mMin2gRssi, mMin5gRssi, mMin6gRssi, mPnoNetworks);
- }
-
- /** implement Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /**
- * implement Parcelable interface
- * |flag| is ignored.
- **/
- @Override
- public void writeToParcel(@NonNull Parcel out, int flags) {
- out.writeLong(mIntervalMs);
- out.writeInt(mMin2gRssi);
- out.writeInt(mMin5gRssi);
- out.writeInt(mMin6gRssi);
- out.writeTypedList(mPnoNetworks);
- }
-
- /** implement Parcelable interface */
- @NonNull public static final Parcelable.Creator<PnoSettings> CREATOR =
- new Parcelable.Creator<PnoSettings>() {
- @Override
- public PnoSettings createFromParcel(Parcel in) {
- PnoSettings result = new PnoSettings();
- result.mIntervalMs = in.readLong();
- result.mMin2gRssi = in.readInt();
- result.mMin5gRssi = in.readInt();
- result.mMin6gRssi = in.readInt();
-
- result.mPnoNetworks = new ArrayList<>();
- in.readTypedList(result.mPnoNetworks, PnoNetwork.CREATOR);
-
- return result;
- }
-
- @Override
- public PnoSettings[] newArray(int size) {
- return new PnoSettings[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/nl80211/RadioChainInfo.java b/wifi/java/android/net/wifi/nl80211/RadioChainInfo.java
deleted file mode 100644
index 2c12163dc9a1..000000000000
--- a/wifi/java/android/net/wifi/nl80211/RadioChainInfo.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2016 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.nl80211;
-
-import android.annotation.NonNull;
-import android.annotation.SystemApi;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.util.Objects;
-
-/**
- * A class representing the radio chains of the Wi-Fi modems. Use to provide raw information about
- * signals received on different radio chains.
- *
- * @hide
- */
-@SystemApi
-public final class RadioChainInfo implements Parcelable {
- private static final String TAG = "RadioChainInfo";
-
- /** @hide */
- @VisibleForTesting
- public int chainId;
- /** @hide */
- @VisibleForTesting
- public int level;
-
- /**
- * Return an identifier for this radio chain. This is an arbitrary ID which is consistent for
- * the same device.
- *
- * @return The radio chain ID.
- */
- public int getChainId() {
- return chainId;
- }
-
- /**
- * Returns the detected signal level on this radio chain in dBm (aka RSSI).
- *
- * @return A signal level in dBm.
- */
- public int getLevelDbm() {
- return level;
- }
-
- /**
- * Construct a RadioChainInfo.
- */
- public RadioChainInfo(int chainId, int level) {
- this.chainId = chainId;
- this.level = level;
- }
-
- /** override comparator */
- @Override
- public boolean equals(Object rhs) {
- if (this == rhs) return true;
- if (!(rhs instanceof RadioChainInfo)) {
- return false;
- }
- RadioChainInfo chainInfo = (RadioChainInfo) rhs;
- if (chainInfo == null) {
- return false;
- }
- return chainId == chainInfo.chainId && level == chainInfo.level;
- }
-
- /** override hash code */
- @Override
- public int hashCode() {
- return Objects.hash(chainId, level);
- }
-
-
- /** implement Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /**
- * implement Parcelable interface
- * |flags| is ignored.
- */
- @Override
- public void writeToParcel(@NonNull Parcel out, int flags) {
- out.writeInt(chainId);
- out.writeInt(level);
- }
-
- /** implement Parcelable interface */
- @NonNull public static final Parcelable.Creator<RadioChainInfo> CREATOR =
- new Parcelable.Creator<RadioChainInfo>() {
- /**
- * Caller is responsible for providing a valid parcel.
- */
- @Override
- public RadioChainInfo createFromParcel(Parcel in) {
- return new RadioChainInfo(in.readInt(), in.readInt());
- }
-
- @Override
- public RadioChainInfo[] newArray(int size) {
- return new RadioChainInfo[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/nl80211/SingleScanSettings.java b/wifi/java/android/net/wifi/nl80211/SingleScanSettings.java
deleted file mode 100644
index 24b1854fbf6c..000000000000
--- a/wifi/java/android/net/wifi/nl80211/SingleScanSettings.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2016 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.nl80211;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
-
-import java.util.ArrayList;
-import java.util.Objects;
-
-/**
- * SingleScanSettings for wificond
- *
- * @hide
- */
-public class SingleScanSettings implements Parcelable {
- private static final String TAG = "SingleScanSettings";
-
- public int scanType;
- public ArrayList<ChannelSettings> channelSettings;
- public ArrayList<HiddenNetwork> hiddenNetworks;
-
- /** public constructor */
- public SingleScanSettings() { }
-
- /** override comparator */
- @Override
- public boolean equals(Object rhs) {
- if (this == rhs) return true;
- if (!(rhs instanceof SingleScanSettings)) {
- return false;
- }
- SingleScanSettings settings = (SingleScanSettings) rhs;
- if (settings == null) {
- return false;
- }
- return scanType == settings.scanType
- && channelSettings.equals(settings.channelSettings)
- && hiddenNetworks.equals(settings.hiddenNetworks);
- }
-
- /** override hash code */
- @Override
- public int hashCode() {
- return Objects.hash(scanType, channelSettings, hiddenNetworks);
- }
-
-
- /** implement Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- private static boolean isValidScanType(int scanType) {
- return scanType == IWifiScannerImpl.SCAN_TYPE_LOW_SPAN
- || scanType == IWifiScannerImpl.SCAN_TYPE_LOW_POWER
- || scanType == IWifiScannerImpl.SCAN_TYPE_HIGH_ACCURACY;
- }
-
- /**
- * implement Parcelable interface
- * |flags| is ignored.
- */
- @Override
- public void writeToParcel(Parcel out, int flags) {
- if (!isValidScanType(scanType)) {
- Log.wtf(TAG, "Invalid scan type " + scanType);
- }
- out.writeInt(scanType);
- out.writeTypedList(channelSettings);
- out.writeTypedList(hiddenNetworks);
- }
-
- /** implement Parcelable interface */
- public static final Parcelable.Creator<SingleScanSettings> CREATOR =
- new Parcelable.Creator<SingleScanSettings>() {
- /**
- * Caller is responsible for providing a valid parcel.
- */
- @Override
- public SingleScanSettings createFromParcel(Parcel in) {
- SingleScanSettings result = new SingleScanSettings();
- result.scanType = in.readInt();
- if (!isValidScanType(result.scanType)) {
- Log.wtf(TAG, "Invalid scan type " + result.scanType);
- }
- result.channelSettings = new ArrayList<ChannelSettings>();
- in.readTypedList(result.channelSettings, ChannelSettings.CREATOR);
- result.hiddenNetworks = new ArrayList<HiddenNetwork>();
- in.readTypedList(result.hiddenNetworks, HiddenNetwork.CREATOR);
- if (in.dataAvail() != 0) {
- Log.e(TAG, "Found trailing data after parcel parsing.");
- }
- return result;
- }
-
- @Override
- public SingleScanSettings[] newArray(int size) {
- return new SingleScanSettings[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/nl80211/WifiNl80211Manager.java b/wifi/java/android/net/wifi/nl80211/WifiNl80211Manager.java
deleted file mode 100644
index 0b0862a7a277..000000000000
--- a/wifi/java/android/net/wifi/nl80211/WifiNl80211Manager.java
+++ /dev/null
@@ -1,1325 +0,0 @@
-/*
- * Copyright (C) 2017 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.nl80211;
-
-import android.annotation.CallbackExecutor;
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.annotation.SystemService;
-import android.app.AlarmManager;
-import android.content.Context;
-import android.net.wifi.SoftApInfo;
-import android.net.wifi.WifiAnnotations;
-import android.net.wifi.WifiScanner;
-import android.os.Binder;
-import android.os.Handler;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.os.SystemClock;
-import android.util.Log;
-
-import com.android.internal.annotations.VisibleForTesting;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.Executor;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * This class encapsulates the interface the wificond daemon presents to the Wi-Fi framework - used
- * to encapsulate the Wi-Fi 80211nl management interface. The
- * interface is only for use by the Wi-Fi framework and access is protected by SELinux permissions.
- *
- * @hide
- */
-@SystemApi
-@SystemService(Context.WIFI_NL80211_SERVICE)
-public class WifiNl80211Manager {
- private static final String TAG = "WifiNl80211Manager";
- private boolean mVerboseLoggingEnabled = false;
-
- /**
- * The {@link #sendMgmtFrame(String, byte[], int, Executor, SendMgmtFrameCallback)}
- * timeout, in milliseconds, after which
- * {@link SendMgmtFrameCallback#onFailure(int)} will be called with reason
- * {@link #SEND_MGMT_FRAME_ERROR_TIMEOUT}.
- */
- private static final int SEND_MGMT_FRAME_TIMEOUT_MS = 1000;
-
- private static final String TIMEOUT_ALARM_TAG = TAG + " Send Management Frame Timeout";
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"SCAN_TYPE_"},
- value = {SCAN_TYPE_SINGLE_SCAN,
- SCAN_TYPE_PNO_SCAN})
- public @interface ScanResultType {}
-
- /**
- * Specifies a scan type: single scan initiated by the framework. Can be used in
- * {@link #getScanResults(String, int)} to specify the type of scan result to fetch.
- */
- public static final int SCAN_TYPE_SINGLE_SCAN = 0;
-
- /**
- * Specifies a scan type: PNO scan. Can be used in {@link #getScanResults(String, int)} to
- * specify the type of scan result to fetch.
- */
- public static final int SCAN_TYPE_PNO_SCAN = 1;
-
- private AlarmManager mAlarmManager;
- private Handler mEventHandler;
-
- // Cached wificond binder handlers.
- private IWificond mWificond;
- private HashMap<String, IClientInterface> mClientInterfaces = new HashMap<>();
- private HashMap<String, IApInterface> mApInterfaces = new HashMap<>();
- private HashMap<String, IWifiScannerImpl> mWificondScanners = new HashMap<>();
- private HashMap<String, IScanEvent> mScanEventHandlers = new HashMap<>();
- private HashMap<String, IPnoScanEvent> mPnoScanEventHandlers = new HashMap<>();
- private HashMap<String, IApInterfaceEventCallback> mApInterfaceListeners = new HashMap<>();
- private Runnable mDeathEventHandler;
- /**
- * Ensures that no more than one sendMgmtFrame operation runs concurrently.
- */
- private AtomicBoolean mSendMgmtFrameInProgress = new AtomicBoolean(false);
-
- /**
- * Interface used when waiting for scans to be completed (with results).
- */
- public interface ScanEventCallback {
- /**
- * Called when scan results are available. Scans results should then be obtained from
- * {@link #getScanResults(String, int)}.
- */
- void onScanResultReady();
-
- /**
- * Called when a scan has failed.
- */
- void onScanFailed();
- }
-
- /**
- * Interface for a callback to provide information about PNO scan request requested with
- * {@link #startPnoScan(String, PnoSettings, Executor, PnoScanRequestCallback)}. Note that the
- * callback are for the status of the request - not the scan itself. The results of the scan
- * are returned with {@link ScanEventCallback}.
- */
- public interface PnoScanRequestCallback {
- /**
- * Called when a PNO scan request has been successfully submitted.
- */
- void onPnoRequestSucceeded();
-
- /**
- * Called when a PNO scan request fails.
- */
- void onPnoRequestFailed();
- }
-
- private class ScanEventHandler extends IScanEvent.Stub {
- private Executor mExecutor;
- private ScanEventCallback mCallback;
-
- ScanEventHandler(@NonNull Executor executor, @NonNull ScanEventCallback callback) {
- mExecutor = executor;
- mCallback = callback;
- }
-
- @Override
- public void OnScanResultReady() {
- Log.d(TAG, "Scan result ready event");
- final long token = Binder.clearCallingIdentity();
- try {
- mExecutor.execute(() -> mCallback.onScanResultReady());
- } finally {
- Binder.restoreCallingIdentity(token);
- }
- }
-
- @Override
- public void OnScanFailed() {
- Log.d(TAG, "Scan failed event");
- final long token = Binder.clearCallingIdentity();
- try {
- mExecutor.execute(() -> mCallback.onScanFailed());
- } finally {
- Binder.restoreCallingIdentity(token);
- }
- }
- }
-
- /**
- * Result of a signal poll requested using {@link #signalPoll(String)}.
- */
- public static class SignalPollResult {
- /** @hide */
- public SignalPollResult(int currentRssiDbm, int txBitrateMbps, int rxBitrateMbps,
- int associationFrequencyMHz) {
- this.currentRssiDbm = currentRssiDbm;
- this.txBitrateMbps = txBitrateMbps;
- this.rxBitrateMbps = rxBitrateMbps;
- this.associationFrequencyMHz = associationFrequencyMHz;
- }
-
- /**
- * RSSI value in dBM.
- */
- public final int currentRssiDbm;
-
- /**
- * Transmission bit rate in Mbps.
- */
- public final int txBitrateMbps;
-
- /**
- * Last received packet bit rate in Mbps.
- */
- public final int rxBitrateMbps;
-
- /**
- * Association frequency in MHz.
- */
- public final int associationFrequencyMHz;
- }
-
- /**
- * Transmission counters obtained using {@link #getTxPacketCounters(String)}.
- */
- public static class TxPacketCounters {
- /** @hide */
- public TxPacketCounters(int txPacketSucceeded, int txPacketFailed) {
- this.txPacketSucceeded = txPacketSucceeded;
- this.txPacketFailed = txPacketFailed;
- }
-
- /**
- * Number of successfully transmitted packets.
- */
- public final int txPacketSucceeded;
-
- /**
- * Number of packet transmission failures.
- */
- public final int txPacketFailed;
- }
-
- /**
- * Callbacks for SoftAp interface registered using
- * {@link #registerApCallback(String, Executor, SoftApCallback)}.
- *
- * @deprecated The usage is replaced by vendor HAL
- * {@code android.hardware.wifi.hostapd.V1_3.IHostapdCallback}.
- */
- @Deprecated
- public interface SoftApCallback {
- /**
- * Invoked when there is a fatal failure and the SoftAp is shutdown.
- */
- void onFailure();
-
- /**
- * Invoked when there is a change in the associated station (STA).
- * @param client Information about the client whose status has changed.
- * @param isConnected Indication as to whether the client is connected (true), or
- * disconnected (false).
- */
- void onConnectedClientsChanged(@NonNull NativeWifiClient client, boolean isConnected);
-
- /**
- * Invoked when a channel switch event happens - i.e. the SoftAp is moved to a different
- * channel. Also called on initial registration.
- * @param frequencyMhz The new frequency of the SoftAp. A value of 0 is invalid and is an
- * indication that the SoftAp is not enabled.
- * @param bandwidth The new bandwidth of the SoftAp.
- */
- void onSoftApChannelSwitched(int frequencyMhz, @WifiAnnotations.Bandwidth int bandwidth);
- }
-
- /**
- * Callback to notify the results of a
- * {@link #sendMgmtFrame(String, byte[], int, Executor, SendMgmtFrameCallback)} call.
- * Note: no callbacks will be triggered if the interface dies while sending a frame.
- */
- public interface SendMgmtFrameCallback {
- /**
- * Called when the management frame was successfully sent and ACKed by the recipient.
- * @param elapsedTimeMs The elapsed time between when the management frame was sent and when
- * the ACK was processed, in milliseconds, as measured by wificond.
- * This includes the time that the send frame spent queuing before it
- * was sent, any firmware retries, and the time the received ACK spent
- * queuing before it was processed.
- */
- void onAck(int elapsedTimeMs);
-
- /**
- * Called when the send failed.
- * @param reason The error code for the failure.
- */
- void onFailure(@SendMgmtFrameError int reason);
- }
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"SEND_MGMT_FRAME_ERROR_"},
- value = {SEND_MGMT_FRAME_ERROR_UNKNOWN,
- SEND_MGMT_FRAME_ERROR_MCS_UNSUPPORTED,
- SEND_MGMT_FRAME_ERROR_NO_ACK,
- SEND_MGMT_FRAME_ERROR_TIMEOUT,
- SEND_MGMT_FRAME_ERROR_ALREADY_STARTED})
- public @interface SendMgmtFrameError {}
-
- // Send management frame error codes
-
- /**
- * Unknown error occurred during call to
- * {@link #sendMgmtFrame(String, byte[], int, Executor, SendMgmtFrameCallback)}.
- */
- public static final int SEND_MGMT_FRAME_ERROR_UNKNOWN = 1;
-
- /**
- * Specifying the MCS rate in
- * {@link #sendMgmtFrame(String, byte[], int, Executor, SendMgmtFrameCallback)} is not
- * supported by this device.
- */
- public static final int SEND_MGMT_FRAME_ERROR_MCS_UNSUPPORTED = 2;
-
- /**
- * Driver reported that no ACK was received for the frame transmitted using
- * {@link #sendMgmtFrame(String, byte[], int, Executor, SendMgmtFrameCallback)}.
- */
- public static final int SEND_MGMT_FRAME_ERROR_NO_ACK = 3;
-
- /**
- * Error code for when the driver fails to report on the status of the frame sent by
- * {@link #sendMgmtFrame(String, byte[], int, Executor, SendMgmtFrameCallback)}
- * after {@link #SEND_MGMT_FRAME_TIMEOUT_MS} milliseconds.
- */
- public static final int SEND_MGMT_FRAME_ERROR_TIMEOUT = 4;
-
- /**
- * An existing call to
- * {@link #sendMgmtFrame(String, byte[], int, Executor, SendMgmtFrameCallback)}
- * is in progress. Another frame cannot be sent until the first call completes.
- */
- public static final int SEND_MGMT_FRAME_ERROR_ALREADY_STARTED = 5;
-
- /** @hide */
- public WifiNl80211Manager(Context context) {
- mAlarmManager = context.getSystemService(AlarmManager.class);
- mEventHandler = new Handler(context.getMainLooper());
- }
-
- /** @hide */
- @VisibleForTesting
- public WifiNl80211Manager(Context context, IWificond wificond) {
- this(context);
- mWificond = wificond;
- }
-
- private class PnoScanEventHandler extends IPnoScanEvent.Stub {
- private Executor mExecutor;
- private ScanEventCallback mCallback;
-
- PnoScanEventHandler(@NonNull Executor executor, @NonNull ScanEventCallback callback) {
- mExecutor = executor;
- mCallback = callback;
- }
-
- @Override
- public void OnPnoNetworkFound() {
- Log.d(TAG, "Pno scan result event");
- final long token = Binder.clearCallingIdentity();
- try {
- mExecutor.execute(() -> mCallback.onScanResultReady());
- } finally {
- Binder.restoreCallingIdentity(token);
- }
- }
-
- @Override
- public void OnPnoScanFailed() {
- Log.d(TAG, "Pno Scan failed event");
- final long token = Binder.clearCallingIdentity();
- try {
- mExecutor.execute(() -> mCallback.onScanFailed());
- } finally {
- Binder.restoreCallingIdentity(token);
- }
- }
- }
-
- /**
- * Listener for AP Interface events.
- */
- private class ApInterfaceEventCallback extends IApInterfaceEventCallback.Stub {
- private Executor mExecutor;
- private SoftApCallback mSoftApListener;
-
- ApInterfaceEventCallback(Executor executor, SoftApCallback listener) {
- mExecutor = executor;
- mSoftApListener = listener;
- }
-
- @Override
- public void onConnectedClientsChanged(NativeWifiClient client, boolean isConnected) {
- // Ignore event from wificond. This is handled from hostapd now.
- }
-
- @Override
- public void onSoftApChannelSwitched(int frequency, int bandwidth) {
- final long token = Binder.clearCallingIdentity();
- try {
- mExecutor.execute(() -> mSoftApListener.onSoftApChannelSwitched(frequency,
- toFrameworkBandwidth(bandwidth)));
- } finally {
- Binder.restoreCallingIdentity(token);
- }
- }
-
- private @WifiAnnotations.Bandwidth int toFrameworkBandwidth(int bandwidth) {
- switch(bandwidth) {
- case IApInterfaceEventCallback.BANDWIDTH_INVALID:
- return SoftApInfo.CHANNEL_WIDTH_INVALID;
- case IApInterfaceEventCallback.BANDWIDTH_20_NOHT:
- return SoftApInfo.CHANNEL_WIDTH_20MHZ_NOHT;
- case IApInterfaceEventCallback.BANDWIDTH_20:
- return SoftApInfo.CHANNEL_WIDTH_20MHZ;
- case IApInterfaceEventCallback.BANDWIDTH_40:
- return SoftApInfo.CHANNEL_WIDTH_40MHZ;
- case IApInterfaceEventCallback.BANDWIDTH_80:
- return SoftApInfo.CHANNEL_WIDTH_80MHZ;
- case IApInterfaceEventCallback.BANDWIDTH_80P80:
- return SoftApInfo.CHANNEL_WIDTH_80MHZ_PLUS_MHZ;
- case IApInterfaceEventCallback.BANDWIDTH_160:
- return SoftApInfo.CHANNEL_WIDTH_160MHZ;
- default:
- return SoftApInfo.CHANNEL_WIDTH_INVALID;
- }
- }
- }
-
- /**
- * Callback triggered by wificond.
- */
- private class SendMgmtFrameEvent extends ISendMgmtFrameEvent.Stub {
- private Executor mExecutor;
- private SendMgmtFrameCallback mCallback;
- private AlarmManager.OnAlarmListener mTimeoutCallback;
- /**
- * ensures that mCallback is only called once
- */
- private boolean mWasCalled;
-
- private void runIfFirstCall(Runnable r) {
- if (mWasCalled) return;
- mWasCalled = true;
-
- mSendMgmtFrameInProgress.set(false);
- r.run();
- }
-
- SendMgmtFrameEvent(@NonNull Executor executor, @NonNull SendMgmtFrameCallback callback) {
- mExecutor = executor;
- mCallback = callback;
- // called in main thread
- mTimeoutCallback = () -> runIfFirstCall(() -> {
- if (mVerboseLoggingEnabled) {
- Log.e(TAG, "Timed out waiting for ACK");
- }
- final long token = Binder.clearCallingIdentity();
- try {
- mExecutor.execute(() -> mCallback.onFailure(SEND_MGMT_FRAME_ERROR_TIMEOUT));
- } finally {
- Binder.restoreCallingIdentity(token);
- }
- });
- mWasCalled = false;
-
- mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
- SystemClock.elapsedRealtime() + SEND_MGMT_FRAME_TIMEOUT_MS,
- TIMEOUT_ALARM_TAG, mTimeoutCallback, mEventHandler);
- }
-
- // called in binder thread
- @Override
- public void OnAck(int elapsedTimeMs) {
- // post to main thread
- mEventHandler.post(() -> runIfFirstCall(() -> {
- mAlarmManager.cancel(mTimeoutCallback);
- final long token = Binder.clearCallingIdentity();
- try {
- mExecutor.execute(() -> mCallback.onAck(elapsedTimeMs));
- } finally {
- Binder.restoreCallingIdentity(token);
- }
- }));
- }
-
- // called in binder thread
- @Override
- public void OnFailure(int reason) {
- // post to main thread
- mEventHandler.post(() -> runIfFirstCall(() -> {
- mAlarmManager.cancel(mTimeoutCallback);
- final long token = Binder.clearCallingIdentity();
- try {
- mExecutor.execute(() -> mCallback.onFailure(reason));
- } finally {
- Binder.restoreCallingIdentity(token);
- }
- }));
- }
- }
-
- /**
- * Called by the binder subsystem upon remote object death.
- * Invoke all the register death handlers and clear state.
- * @hide
- */
- @VisibleForTesting
- public void binderDied() {
- mEventHandler.post(() -> {
- Log.e(TAG, "Wificond died!");
- clearState();
- // Invalidate the global wificond handle on death. Will be refreshed
- // on the next setup call.
- mWificond = null;
- if (mDeathEventHandler != null) {
- mDeathEventHandler.run();
- }
- });
- }
-
- /**
- * Enable or disable verbose logging of the WifiNl80211Manager module.
- * @param enable True to enable verbose logging. False to disable verbose logging.
- */
- public void enableVerboseLogging(boolean enable) {
- mVerboseLoggingEnabled = enable;
- }
-
- /**
- * Register a death notification for the WifiNl80211Manager which acts as a proxy for the
- * wificond daemon (i.e. the death listener will be called when and if the wificond daemon
- * dies).
- *
- * @param deathEventHandler A {@link Runnable} to be called whenever the wificond daemon dies.
- */
- public void setOnServiceDeadCallback(@NonNull Runnable deathEventHandler) {
- if (mDeathEventHandler != null) {
- Log.e(TAG, "Death handler already present");
- }
- mDeathEventHandler = deathEventHandler;
- }
-
- /**
- * Helper method to retrieve the global wificond handle and register for
- * death notifications.
- */
- private boolean retrieveWificondAndRegisterForDeath() {
- if (mWificond != null) {
- if (mVerboseLoggingEnabled) {
- Log.d(TAG, "Wificond handle already retrieved");
- }
- // We already have a wificond handle.
- return true;
- }
- IBinder binder = ServiceManager.getService(Context.WIFI_NL80211_SERVICE);
- mWificond = IWificond.Stub.asInterface(binder);
- if (mWificond == null) {
- Log.e(TAG, "Failed to get reference to wificond");
- return false;
- }
- try {
- mWificond.asBinder().linkToDeath(() -> binderDied(), 0);
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to register death notification for wificond");
- // The remote has already died.
- return false;
- }
- return true;
- }
-
- /**
- * Set up an interface for client (STA) mode.
- *
- * @param ifaceName Name of the interface to configure.
- * @param executor The Executor on which to execute the callbacks.
- * @param scanCallback A callback for framework initiated scans.
- * @param pnoScanCallback A callback for PNO (offloaded) scans.
- * @return true on success.
- */
- public boolean setupInterfaceForClientMode(@NonNull String ifaceName,
- @NonNull @CallbackExecutor Executor executor,
- @NonNull ScanEventCallback scanCallback, @NonNull ScanEventCallback pnoScanCallback) {
- Log.d(TAG, "Setting up interface for client mode");
- if (!retrieveWificondAndRegisterForDeath()) {
- return false;
- }
-
- if (scanCallback == null || pnoScanCallback == null || executor == null) {
- Log.e(TAG, "setupInterfaceForClientMode invoked with null callbacks");
- return false;
- }
-
- IClientInterface clientInterface = null;
- try {
- clientInterface = mWificond.createClientInterface(ifaceName);
- } catch (RemoteException e1) {
- Log.e(TAG, "Failed to get IClientInterface due to remote exception");
- return false;
- }
-
- if (clientInterface == null) {
- Log.e(TAG, "Could not get IClientInterface instance from wificond");
- return false;
- }
- Binder.allowBlocking(clientInterface.asBinder());
-
- // Refresh Handlers
- mClientInterfaces.put(ifaceName, clientInterface);
- try {
- IWifiScannerImpl wificondScanner = clientInterface.getWifiScannerImpl();
- if (wificondScanner == null) {
- Log.e(TAG, "Failed to get WificondScannerImpl");
- return false;
- }
- mWificondScanners.put(ifaceName, wificondScanner);
- Binder.allowBlocking(wificondScanner.asBinder());
- ScanEventHandler scanEventHandler = new ScanEventHandler(executor, scanCallback);
- mScanEventHandlers.put(ifaceName, scanEventHandler);
- wificondScanner.subscribeScanEvents(scanEventHandler);
- PnoScanEventHandler pnoScanEventHandler = new PnoScanEventHandler(executor,
- pnoScanCallback);
- mPnoScanEventHandlers.put(ifaceName, pnoScanEventHandler);
- wificondScanner.subscribePnoScanEvents(pnoScanEventHandler);
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to refresh wificond scanner due to remote exception");
- }
-
- return true;
- }
-
- /**
- * Tear down a specific client (STA) interface configured using
- * {@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}.
- *
- * @param ifaceName Name of the interface to tear down.
- * @return Returns true on success, false on failure (e.g. when called before an interface was
- * set up).
- */
- public boolean tearDownClientInterface(@NonNull String ifaceName) {
- if (getClientInterface(ifaceName) == null) {
- Log.e(TAG, "No valid wificond client interface handler");
- return false;
- }
- try {
- IWifiScannerImpl scannerImpl = mWificondScanners.get(ifaceName);
- if (scannerImpl != null) {
- scannerImpl.unsubscribeScanEvents();
- scannerImpl.unsubscribePnoScanEvents();
- }
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to unsubscribe wificond scanner due to remote exception");
- return false;
- }
-
- if (mWificond == null) {
- Log.e(TAG, "Reference to wifiCond is null");
- return false;
- }
-
- boolean success;
- try {
- success = mWificond.tearDownClientInterface(ifaceName);
- } catch (RemoteException e1) {
- Log.e(TAG, "Failed to teardown client interface due to remote exception");
- return false;
- }
- if (!success) {
- Log.e(TAG, "Failed to teardown client interface");
- return false;
- }
-
- mClientInterfaces.remove(ifaceName);
- mWificondScanners.remove(ifaceName);
- mScanEventHandlers.remove(ifaceName);
- mPnoScanEventHandlers.remove(ifaceName);
- return true;
- }
-
- /**
- * Set up interface as a Soft AP.
- *
- * @param ifaceName Name of the interface to configure.
- * @return true on success.
- */
- public boolean setupInterfaceForSoftApMode(@NonNull String ifaceName) {
- Log.d(TAG, "Setting up interface for soft ap mode");
- if (!retrieveWificondAndRegisterForDeath()) {
- return false;
- }
-
- IApInterface apInterface = null;
- try {
- apInterface = mWificond.createApInterface(ifaceName);
- } catch (RemoteException e1) {
- Log.e(TAG, "Failed to get IApInterface due to remote exception");
- return false;
- }
-
- if (apInterface == null) {
- Log.e(TAG, "Could not get IApInterface instance from wificond");
- return false;
- }
- Binder.allowBlocking(apInterface.asBinder());
-
- // Refresh Handlers
- mApInterfaces.put(ifaceName, apInterface);
- return true;
- }
-
- /**
- * Tear down a Soft AP interface configured using
- * {@link #setupInterfaceForSoftApMode(String)}.
- *
- * @param ifaceName Name of the interface to tear down.
- * @return Returns true on success, false on failure (e.g. when called before an interface was
- * set up).
- */
- public boolean tearDownSoftApInterface(@NonNull String ifaceName) {
- if (getApInterface(ifaceName) == null) {
- Log.e(TAG, "No valid wificond ap interface handler");
- return false;
- }
-
- if (mWificond == null) {
- Log.e(TAG, "Reference to wifiCond is null");
- return false;
- }
-
- boolean success;
- try {
- success = mWificond.tearDownApInterface(ifaceName);
- } catch (RemoteException e1) {
- Log.e(TAG, "Failed to teardown AP interface due to remote exception");
- return false;
- }
- if (!success) {
- Log.e(TAG, "Failed to teardown AP interface");
- return false;
- }
- mApInterfaces.remove(ifaceName);
- mApInterfaceListeners.remove(ifaceName);
- return true;
- }
-
- /**
- * Tear down all interfaces, whether clients (STA) or Soft AP.
- *
- * @return Returns true on success.
- */
- public boolean tearDownInterfaces() {
- Log.d(TAG, "tearing down interfaces in wificond");
- // Explicitly refresh the wificodn handler because |tearDownInterfaces()|
- // could be used to cleanup before we setup any interfaces.
- if (!retrieveWificondAndRegisterForDeath()) {
- return false;
- }
-
- try {
- for (Map.Entry<String, IWifiScannerImpl> entry : mWificondScanners.entrySet()) {
- entry.getValue().unsubscribeScanEvents();
- entry.getValue().unsubscribePnoScanEvents();
- }
- mWificond.tearDownInterfaces();
- clearState();
- return true;
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to tear down interfaces due to remote exception");
- }
-
- return false;
- }
-
- /** Helper function to look up the interface handle using name */
- private IClientInterface getClientInterface(@NonNull String ifaceName) {
- return mClientInterfaces.get(ifaceName);
- }
-
- /**
- * Request signal polling.
- *
- * @param ifaceName Name of the interface on which to poll. The interface must have been
- * already set up using
- *{@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}
- * or {@link #setupInterfaceForSoftApMode(String)}.
- *
- * @return A {@link SignalPollResult} object containing interface statistics, or a null on
- * error (e.g. the interface hasn't been set up yet).
- */
- @Nullable public SignalPollResult signalPoll(@NonNull String ifaceName) {
- IClientInterface iface = getClientInterface(ifaceName);
- if (iface == null) {
- Log.e(TAG, "No valid wificond client interface handler");
- return null;
- }
-
- int[] resultArray;
- try {
- resultArray = iface.signalPoll();
- if (resultArray == null || resultArray.length != 4) {
- Log.e(TAG, "Invalid signal poll result from wificond");
- return null;
- }
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to do signal polling due to remote exception");
- return null;
- }
- return new SignalPollResult(resultArray[0], resultArray[1], resultArray[3], resultArray[2]);
- }
-
- /**
- * Get current transmit (Tx) packet counters of the specified interface. The interface must
- * have been already set up using
- * {@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}
- * or {@link #setupInterfaceForSoftApMode(String)}.
- *
- * @param ifaceName Name of the interface.
- * @return {@link TxPacketCounters} of the current interface or null on error (e.g. when
- * called before the interface has been set up).
- */
- @Nullable public TxPacketCounters getTxPacketCounters(@NonNull String ifaceName) {
- IClientInterface iface = getClientInterface(ifaceName);
- if (iface == null) {
- Log.e(TAG, "No valid wificond client interface handler");
- return null;
- }
-
- int[] resultArray;
- try {
- resultArray = iface.getPacketCounters();
- if (resultArray == null || resultArray.length != 2) {
- Log.e(TAG, "Invalid signal poll result from wificond");
- return null;
- }
- } catch (RemoteException e) {
- Log.e(TAG, "Failed to do signal polling due to remote exception");
- return null;
- }
- return new TxPacketCounters(resultArray[0], resultArray[1]);
- }
-
- /** Helper function to look up the scanner impl handle using name */
- private IWifiScannerImpl getScannerImpl(@NonNull String ifaceName) {
- return mWificondScanners.get(ifaceName);
- }
-
- /**
- * Fetch the latest scan results of the indicated type for the specified interface. Note that
- * this method fetches the latest results - it does not initiate a scan. Initiating a scan can
- * be done using {@link #startScan(String, int, Set, List)} or
- * {@link #startPnoScan(String, PnoSettings, Executor, PnoScanRequestCallback)}.
- *
- * Note: The interface must have been already set up using
- * {@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}
- * or {@link #setupInterfaceForSoftApMode(String)}.
- *
- * @param ifaceName Name of the interface.
- * @param scanType The type of scan result to be returned, can be
- * {@link #SCAN_TYPE_SINGLE_SCAN} or {@link #SCAN_TYPE_PNO_SCAN}.
- * @return Returns an array of {@link NativeScanResult} or an empty array on failure (e.g. when
- * called before the interface has been set up).
- */
- @NonNull public List<NativeScanResult> getScanResults(@NonNull String ifaceName,
- @ScanResultType int scanType) {
- IWifiScannerImpl scannerImpl = getScannerImpl(ifaceName);
- if (scannerImpl == null) {
- Log.e(TAG, "No valid wificond scanner interface handler");
- return new ArrayList<>();
- }
- List<NativeScanResult> results = null;
- try {
- if (scanType == SCAN_TYPE_SINGLE_SCAN) {
- results = Arrays.asList(scannerImpl.getScanResults());
- } else {
- results = Arrays.asList(scannerImpl.getPnoScanResults());
- }
- } catch (RemoteException e1) {
- Log.e(TAG, "Failed to create ScanDetail ArrayList");
- }
- if (results == null) {
- results = new ArrayList<>();
- }
- if (mVerboseLoggingEnabled) {
- Log.d(TAG, "get " + results.size() + " scan results from wificond");
- }
-
- return results;
- }
-
- /**
- * Return scan type for the parcelable {@link SingleScanSettings}
- */
- private static int getScanType(@WifiAnnotations.ScanType int scanType) {
- switch (scanType) {
- case WifiScanner.SCAN_TYPE_LOW_LATENCY:
- return IWifiScannerImpl.SCAN_TYPE_LOW_SPAN;
- case WifiScanner.SCAN_TYPE_LOW_POWER:
- return IWifiScannerImpl.SCAN_TYPE_LOW_POWER;
- case WifiScanner.SCAN_TYPE_HIGH_ACCURACY:
- return IWifiScannerImpl.SCAN_TYPE_HIGH_ACCURACY;
- default:
- throw new IllegalArgumentException("Invalid scan type " + scanType);
- }
- }
-
- /**
- * Start a scan using the specified parameters. A scan is an asynchronous operation. The
- * result of the operation is returned in the {@link ScanEventCallback} registered when
- * setting up an interface using
- * {@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}.
- * The latest scans can be obtained using {@link #getScanResults(String, int)} and using a
- * {@link #SCAN_TYPE_SINGLE_SCAN} for the {@code scanType}.
- *
- * Note: The interface must have been already set up using
- * {@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}
- * or {@link #setupInterfaceForSoftApMode(String)}.
- *
- * @param ifaceName Name of the interface on which to initiate the scan.
- * @param scanType Type of scan to perform, can be any of
- * {@link WifiScanner#SCAN_TYPE_HIGH_ACCURACY}, {@link WifiScanner#SCAN_TYPE_LOW_POWER}, or
- * {@link WifiScanner#SCAN_TYPE_LOW_LATENCY}.
- * @param freqs list of frequencies to scan for, if null scan all supported channels.
- * @param hiddenNetworkSSIDs List of hidden networks to be scanned for, a null indicates that
- * no hidden frequencies will be scanned for.
- * @return Returns true on success, false on failure (e.g. when called before the interface
- * has been set up).
- */
- public boolean startScan(@NonNull String ifaceName, @WifiAnnotations.ScanType int scanType,
- @Nullable Set<Integer> freqs, @Nullable List<byte[]> hiddenNetworkSSIDs) {
- IWifiScannerImpl scannerImpl = getScannerImpl(ifaceName);
- if (scannerImpl == null) {
- Log.e(TAG, "No valid wificond scanner interface handler");
- return false;
- }
- SingleScanSettings settings = new SingleScanSettings();
- try {
- settings.scanType = getScanType(scanType);
- } catch (IllegalArgumentException e) {
- Log.e(TAG, "Invalid scan type ", e);
- return false;
- }
- settings.channelSettings = new ArrayList<>();
- settings.hiddenNetworks = new ArrayList<>();
-
- if (freqs != null) {
- for (Integer freq : freqs) {
- ChannelSettings channel = new ChannelSettings();
- channel.frequency = freq;
- settings.channelSettings.add(channel);
- }
- }
- if (hiddenNetworkSSIDs != null) {
- for (byte[] ssid : hiddenNetworkSSIDs) {
- HiddenNetwork network = new HiddenNetwork();
- network.ssid = ssid;
-
- // settings.hiddenNetworks is expected to be very small, so this shouldn't cause
- // any performance issues.
- if (!settings.hiddenNetworks.contains(network)) {
- settings.hiddenNetworks.add(network);
- }
- }
- }
-
- try {
- return scannerImpl.scan(settings);
- } catch (RemoteException e1) {
- Log.e(TAG, "Failed to request scan due to remote exception");
- }
- return false;
- }
-
- /**
- * Request a PNO (Preferred Network Offload). The offload request and the scans are asynchronous
- * operations. The result of the request are returned in the {@code callback} parameter which
- * is an {@link PnoScanRequestCallback}. The scan results are are return in the
- * {@link ScanEventCallback} which is registered when setting up an interface using
- * {@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}.
- * The latest PNO scans can be obtained using {@link #getScanResults(String, int)} with the
- * {@code scanType} set to {@link #SCAN_TYPE_PNO_SCAN}.
- *
- * Note: The interface must have been already set up using
- * {@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}
- * or {@link #setupInterfaceForSoftApMode(String)}.
- *
- * @param ifaceName Name of the interface on which to request a PNO.
- * @param pnoSettings PNO scan configuration.
- * @param executor The Executor on which to execute the callback.
- * @param callback Callback for the results of the offload request.
- * @return true on success, false on failure (e.g. when called before the interface has been set
- * up).
- */
- public boolean startPnoScan(@NonNull String ifaceName, @NonNull PnoSettings pnoSettings,
- @NonNull @CallbackExecutor Executor executor,
- @NonNull PnoScanRequestCallback callback) {
- IWifiScannerImpl scannerImpl = getScannerImpl(ifaceName);
- if (scannerImpl == null) {
- Log.e(TAG, "No valid wificond scanner interface handler");
- return false;
- }
-
- if (callback == null || executor == null) {
- Log.e(TAG, "startPnoScan called with a null callback");
- return false;
- }
-
- try {
- boolean success = scannerImpl.startPnoScan(pnoSettings);
- if (success) {
- executor.execute(callback::onPnoRequestSucceeded);
- } else {
- executor.execute(callback::onPnoRequestFailed);
- }
- return success;
- } catch (RemoteException e1) {
- Log.e(TAG, "Failed to start pno scan due to remote exception");
- }
- return false;
- }
-
- /**
- * Stop PNO scan configured with
- * {@link #startPnoScan(String, PnoSettings, Executor, PnoScanRequestCallback)}.
- *
- * Note: The interface must have been already set up using
- * {@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}
- * or {@link #setupInterfaceForSoftApMode(String)}.
- *
- * @param ifaceName Name of the interface on which the PNO scan was configured.
- * @return true on success, false on failure (e.g. when called before the interface has been
- * set up).
- */
- public boolean stopPnoScan(@NonNull String ifaceName) {
- IWifiScannerImpl scannerImpl = getScannerImpl(ifaceName);
- if (scannerImpl == null) {
- Log.e(TAG, "No valid wificond scanner interface handler");
- return false;
- }
- try {
- return scannerImpl.stopPnoScan();
- } catch (RemoteException e1) {
- Log.e(TAG, "Failed to stop pno scan due to remote exception");
- }
- return false;
- }
-
- /**
- * Abort ongoing single scan started with {@link #startScan(String, int, Set, List)}. No failure
- * callback, e.g. {@link ScanEventCallback#onScanFailed()}, is triggered by this operation.
- *
- * Note: The interface must have been already set up using
- * {@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}
- * or {@link #setupInterfaceForSoftApMode(String)}. If the interface has not been set up then
- * this method has no impact.
- *
- * @param ifaceName Name of the interface on which the scan was started.
- */
- public void abortScan(@NonNull String ifaceName) {
- IWifiScannerImpl scannerImpl = getScannerImpl(ifaceName);
- if (scannerImpl == null) {
- Log.e(TAG, "No valid wificond scanner interface handler");
- return;
- }
- try {
- scannerImpl.abortScan();
- } catch (RemoteException e1) {
- Log.e(TAG, "Failed to request abortScan due to remote exception");
- }
- }
-
- /**
- * Query the list of valid frequencies (in MHz) for the provided band.
- * The result depends on the on the country code that has been set.
- *
- * @param band as specified by one of the WifiScanner.WIFI_BAND_* constants.
- * The following bands are supported:
- * {@link WifiScanner#WIFI_BAND_24_GHZ},
- * {@link WifiScanner#WIFI_BAND_5_GHZ},
- * {@link WifiScanner#WIFI_BAND_5_GHZ_DFS_ONLY},
- * {@link WifiScanner#WIFI_BAND_6_GHZ}
- * {@link WifiScanner.WIFI_BAND_60_GHZ}
- * @return frequencies vector of valid frequencies (MHz), or an empty array for error.
- * @throws IllegalArgumentException if band is not recognized.
- */
- public @NonNull int[] getChannelsMhzForBand(@WifiAnnotations.WifiBandBasic int band) {
- if (mWificond == null) {
- Log.e(TAG, "No valid wificond scanner interface handler");
- return new int[0];
- }
- int[] result = null;
- try {
- switch (band) {
- case WifiScanner.WIFI_BAND_24_GHZ:
- result = mWificond.getAvailable2gChannels();
- break;
- case WifiScanner.WIFI_BAND_5_GHZ:
- result = mWificond.getAvailable5gNonDFSChannels();
- break;
- case WifiScanner.WIFI_BAND_5_GHZ_DFS_ONLY:
- result = mWificond.getAvailableDFSChannels();
- break;
- case WifiScanner.WIFI_BAND_6_GHZ:
- result = mWificond.getAvailable6gChannels();
- break;
- case WifiScanner.WIFI_BAND_60_GHZ:
- result = mWificond.getAvailable60gChannels();
- break;
- default:
- throw new IllegalArgumentException("unsupported band " + band);
- }
- } catch (RemoteException e1) {
- Log.e(TAG, "Failed to request getChannelsForBand due to remote exception");
- }
- if (result == null) {
- result = new int[0];
- }
- return result;
- }
-
- /** Helper function to look up the interface handle using name */
- private IApInterface getApInterface(@NonNull String ifaceName) {
- return mApInterfaces.get(ifaceName);
- }
-
- /**
- * Get the device phy capabilities for a given interface.
- *
- * Note: The interface must have been already set up using
- * {@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}
- * or {@link #setupInterfaceForSoftApMode(String)}.
- *
- * @return DeviceWiphyCapabilities or null on error (e.g. when called on an interface which has
- * not been set up).
- */
- @Nullable public DeviceWiphyCapabilities getDeviceWiphyCapabilities(@NonNull String ifaceName) {
- if (mWificond == null) {
- Log.e(TAG, "Can not query for device wiphy capabilities at this time");
- return null;
- }
-
- try {
- return mWificond.getDeviceWiphyCapabilities(ifaceName);
- } catch (RemoteException e) {
- return null;
- }
- }
-
- /**
- * Register the provided callback handler for SoftAp events. The interface must first be created
- * using {@link #setupInterfaceForSoftApMode(String)}. The callback registration is valid until
- * the interface is deleted using {@link #tearDownSoftApInterface(String)} (no deregistration
- * method is provided).
- * <p>
- * Note that only one callback can be registered at a time - any registration overrides previous
- * registrations.
- *
- * @param ifaceName Name of the interface on which to register the callback.
- * @param executor The Executor on which to execute the callbacks.
- * @param callback Callback for AP events.
- * @return true on success, false on failure (e.g. when called on an interface which has not
- * been set up).
- *
- * @deprecated The usage is replaced by vendor HAL
- * {@code android.hardware.wifi.hostapd.V1_3.IHostapdCallback}.
- */
- @Deprecated
- public boolean registerApCallback(@NonNull String ifaceName,
- @NonNull @CallbackExecutor Executor executor,
- @NonNull SoftApCallback callback) {
- IApInterface iface = getApInterface(ifaceName);
- if (iface == null) {
- Log.e(TAG, "No valid ap interface handler");
- return false;
- }
-
- if (callback == null || executor == null) {
- Log.e(TAG, "registerApCallback called with a null callback");
- return false;
- }
-
- try {
- IApInterfaceEventCallback wificondCallback = new ApInterfaceEventCallback(executor,
- callback);
- mApInterfaceListeners.put(ifaceName, wificondCallback);
- boolean success = iface.registerCallback(wificondCallback);
- if (!success) {
- Log.e(TAG, "Failed to register ap callback.");
- return false;
- }
- } catch (RemoteException e) {
- Log.e(TAG, "Exception in registering AP callback: " + e);
- return false;
- }
- return true;
- }
-
- /**
- * Send a management frame on the specified interface at the specified rate. Useful for probing
- * the link with arbitrary frames.
- *
- * Note: The interface must have been already set up using
- * {@link #setupInterfaceForClientMode(String, Executor, ScanEventCallback, ScanEventCallback)}
- * or {@link #setupInterfaceForSoftApMode(String)}.
- *
- * @param ifaceName The interface on which to send the frame.
- * @param frame The raw byte array of the management frame to tramit.
- * @param mcs The MCS (modulation and coding scheme), i.e. rate, at which to transmit the
- * frame. Specified per IEEE 802.11.
- * @param executor The Executor on which to execute the callbacks.
- * @param callback A {@link SendMgmtFrameCallback} callback for results of the operation.
- */
- public void sendMgmtFrame(@NonNull String ifaceName, @NonNull byte[] frame, int mcs,
- @NonNull @CallbackExecutor Executor executor,
- @NonNull SendMgmtFrameCallback callback) {
-
- if (callback == null || executor == null) {
- Log.e(TAG, "callback cannot be null!");
- return;
- }
-
- if (frame == null) {
- Log.e(TAG, "frame cannot be null!");
- executor.execute(() -> callback.onFailure(SEND_MGMT_FRAME_ERROR_UNKNOWN));
- return;
- }
-
- // TODO (b/112029045) validate mcs
- IClientInterface clientInterface = getClientInterface(ifaceName);
- if (clientInterface == null) {
- Log.e(TAG, "No valid wificond client interface handler");
- executor.execute(() -> callback.onFailure(SEND_MGMT_FRAME_ERROR_UNKNOWN));
- return;
- }
-
- if (!mSendMgmtFrameInProgress.compareAndSet(false, true)) {
- Log.e(TAG, "An existing management frame transmission is in progress!");
- executor.execute(() -> callback.onFailure(SEND_MGMT_FRAME_ERROR_ALREADY_STARTED));
- return;
- }
-
- SendMgmtFrameEvent sendMgmtFrameEvent = new SendMgmtFrameEvent(executor, callback);
- try {
- clientInterface.SendMgmtFrame(frame, sendMgmtFrameEvent, mcs);
- } catch (RemoteException e) {
- Log.e(TAG, "Exception while starting link probe: " + e);
- // Call sendMgmtFrameEvent.OnFailure() instead of callback.onFailure() so that
- // sendMgmtFrameEvent can clean up internal state, such as cancelling the timer.
- sendMgmtFrameEvent.OnFailure(SEND_MGMT_FRAME_ERROR_UNKNOWN);
- }
- }
-
- /**
- * Clear all internal handles.
- */
- private void clearState() {
- // Refresh handlers
- mClientInterfaces.clear();
- mWificondScanners.clear();
- mPnoScanEventHandlers.clear();
- mScanEventHandlers.clear();
- mApInterfaces.clear();
- mApInterfaceListeners.clear();
- mSendMgmtFrameInProgress.set(false);
- }
-
- /**
- * OEM parsed security type
- */
- public static class OemSecurityType {
- /** The protocol defined in {@link android.net.wifi.WifiAnnotations.Protocol}. */
- public final @WifiAnnotations.Protocol int protocol;
- /**
- * Supported key management types defined
- * in {@link android.net.wifi.WifiAnnotations.KeyMgmt}.
- */
- @NonNull public final List<Integer> keyManagement;
- /**
- * Supported pairwise cipher types defined
- * in {@link android.net.wifi.WifiAnnotations.Cipher}.
- */
- @NonNull public final List<Integer> pairwiseCipher;
- /** The group cipher type defined in {@link android.net.wifi.WifiAnnotations.Cipher}. */
- public final @WifiAnnotations.Cipher int groupCipher;
- /**
- * Default constructor for OemSecurityType
- *
- * @param protocol The protocol defined in
- * {@link android.net.wifi.WifiAnnotations.Protocol}.
- * @param keyManagement Supported key management types defined
- * in {@link android.net.wifi.WifiAnnotations.KeyMgmt}.
- * @param pairwiseCipher Supported pairwise cipher types defined
- * in {@link android.net.wifi.WifiAnnotations.Cipher}.
- * @param groupCipher The group cipher type defined
- * in {@link android.net.wifi.WifiAnnotations.Cipher}.
- */
- public OemSecurityType(
- @WifiAnnotations.Protocol int protocol,
- @NonNull List<Integer> keyManagement,
- @NonNull List<Integer> pairwiseCipher,
- @WifiAnnotations.Cipher int groupCipher) {
- this.protocol = protocol;
- this.keyManagement = (keyManagement != null)
- ? keyManagement : new ArrayList<Integer>();
- this.pairwiseCipher = (pairwiseCipher != null)
- ? pairwiseCipher : new ArrayList<Integer>();
- this.groupCipher = groupCipher;
- }
- }
-
- /**
- * OEM information element parser for security types not parsed by the framework.
- *
- * The OEM method should use the method inputs {@code id}, {@code idExt}, and {@code bytes}
- * to perform the parsing. The method should place the results in an OemSecurityType objct.
- *
- * @param id The information element id.
- * @param idExt The information element extension id. This is valid only when id is
- * the extension id, {@code 255}.
- * @param bytes The raw bytes of information element data, 'Element ID' and 'Length' are
- * stripped off already.
- * @return an OemSecurityType object if this IE is parsed successfully, null otherwise.
- */
- @Nullable public static OemSecurityType parseOemSecurityTypeElement(
- int id,
- int idExt,
- @NonNull byte[] bytes) {
- return null;
- }
-}
diff --git a/wifi/java/android/net/wifi/p2p/IWifiP2pManager.aidl b/wifi/java/android/net/wifi/p2p/IWifiP2pManager.aidl
deleted file mode 100644
index fd89d3b0486e..000000000000
--- a/wifi/java/android/net/wifi/p2p/IWifiP2pManager.aidl
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Copyright (c) 2008, 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.p2p;
-
-import android.os.Messenger;
-
-/**
- * Interface that WifiP2pService implements
- *
- * {@hide}
- */
-interface IWifiP2pManager
-{
- Messenger getMessenger(in IBinder binder, in String packageName);
- Messenger getP2pStateMachineMessenger();
- oneway void close(in IBinder binder);
- void setMiracastMode(int mode);
- void checkConfigureWifiDisplayPermission();
-}
-
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pConfig.java b/wifi/java/android/net/wifi/p2p/WifiP2pConfig.java
deleted file mode 100644
index d3a6bac2513f..000000000000
--- a/wifi/java/android/net/wifi/p2p/WifiP2pConfig.java
+++ /dev/null
@@ -1,506 +0,0 @@
-/*
- * Copyright (C) 2011 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.p2p;
-
-import android.annotation.IntDef;
-import android.annotation.IntRange;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.net.MacAddress;
-import android.net.wifi.WpsInfo;
-import android.os.Build;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.nio.charset.StandardCharsets;
-import java.util.regex.PatternSyntaxException;
-
-/**
- * A class representing a Wi-Fi P2p configuration for setting up a connection
- *
- * {@see WifiP2pManager}
- */
-public class WifiP2pConfig implements Parcelable {
-
- /**
- * The device MAC address uniquely identifies a Wi-Fi p2p device
- */
- public String deviceAddress = "";
-
- /**
- * Wi-Fi Protected Setup information
- */
- public WpsInfo wps;
-
- /** Get the network name of this P2P configuration, or null if unset. */
- @Nullable
- public String getNetworkName() {
- return networkName;
- }
-
- /** @hide */
- public String networkName = "";
-
- /** Get the passphrase of this P2P configuration, or null if unset. */
- @Nullable
- public String getPassphrase() {
- return passphrase;
- }
-
- /** @hide */
- public String passphrase = "";
-
- /**
- * Get the required band for the group owner.
- * The result will be one of the following:
- * {@link #GROUP_OWNER_BAND_AUTO},
- * {@link #GROUP_OWNER_BAND_2GHZ},
- * {@link #GROUP_OWNER_BAND_5GHZ}
- */
- @GroupOperatingBandType
- public int getGroupOwnerBand() {
- return groupOwnerBand;
- }
-
- /** @hide */
- @GroupOperatingBandType
- public int groupOwnerBand = GROUP_OWNER_BAND_AUTO;
-
- /** @hide */
- @IntDef(flag = false, prefix = { "GROUP_OWNER_BAND_" }, value = {
- GROUP_OWNER_BAND_AUTO,
- GROUP_OWNER_BAND_2GHZ,
- GROUP_OWNER_BAND_5GHZ
- })
- @Retention(RetentionPolicy.SOURCE)
- public @interface GroupOperatingBandType {}
-
- /**
- * Allow the system to pick the operating frequency from all supported bands.
- */
- public static final int GROUP_OWNER_BAND_AUTO = 0;
- /**
- * Allow the system to pick the operating frequency from the 2.4 GHz band.
- */
- public static final int GROUP_OWNER_BAND_2GHZ = 1;
- /**
- * Allow the system to pick the operating frequency from the 5 GHz band.
- */
- public static final int GROUP_OWNER_BAND_5GHZ = 2;
-
- /**
- * The least inclination to be a group owner, to be filled in the field
- * {@link #groupOwnerIntent}.
- */
- public static final int GROUP_OWNER_INTENT_MIN = 0;
-
- /**
- * The most inclination to be a group owner, to be filled in the field
- * {@link #groupOwnerIntent}.
- */
- public static final int GROUP_OWNER_INTENT_MAX = 15;
-
- /**
- * The system can choose an appropriate owner intent value, to be filled in the field
- * {@link #groupOwnerIntent}.
- */
- public static final int GROUP_OWNER_INTENT_AUTO = -1;
-
- /**
- * This is an integer value between {@link #GROUP_OWNER_INTENT_MIN} and
- * {@link #GROUP_OWNER_INTENT_MAX} where
- * {@link #GROUP_OWNER_INTENT_MIN} indicates the least inclination to be a group owner and
- * {@link #GROUP_OWNER_INTENT_MAX} indicates the highest inclination to be a group owner.
- *
- * A value of {@link #GROUP_OWNER_INTENT_AUTO} indicates the system can choose an appropriate
- * value.
- *
- * By default this field is set to {@link #GROUP_OWNER_INTENT_AUTO}.
- */
- @IntRange(from = 0, to = 15)
- public int groupOwnerIntent = GROUP_OWNER_INTENT_AUTO;
-
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public int netId = WifiP2pGroup.NETWORK_ID_PERSISTENT;
-
- /**
- * Get the network ID of this P2P configuration.
- * @return either a non-negative network ID, or one of
- * {@link WifiP2pGroup#NETWORK_ID_PERSISTENT} or {@link WifiP2pGroup#NETWORK_ID_TEMPORARY}.
- */
- public int getNetworkId() {
- return netId;
- }
-
- public WifiP2pConfig() {
- //set defaults
- wps = new WpsInfo();
- wps.setup = WpsInfo.PBC;
- }
-
- /** @hide */
- public void invalidate() {
- deviceAddress = "";
- }
-
- /** P2P-GO-NEG-REQUEST 42:fc:89:a8:96:09 dev_passwd_id=4 {@hide}*/
- @UnsupportedAppUsage
- public WifiP2pConfig(String supplicantEvent) throws IllegalArgumentException {
- String[] tokens = supplicantEvent.split(" ");
-
- if (tokens.length < 2 || !tokens[0].equals("P2P-GO-NEG-REQUEST")) {
- throw new IllegalArgumentException("Malformed supplicant event");
- }
-
- deviceAddress = tokens[1];
- wps = new WpsInfo();
-
- if (tokens.length > 2) {
- String[] nameVal = tokens[2].split("=");
- int devPasswdId;
- try {
- devPasswdId = Integer.parseInt(nameVal[1]);
- } catch (NumberFormatException e) {
- devPasswdId = 0;
- }
- //Based on definitions in wps/wps_defs.h
- switch (devPasswdId) {
- //DEV_PW_USER_SPECIFIED = 0x0001,
- case 0x01:
- wps.setup = WpsInfo.DISPLAY;
- break;
- //DEV_PW_PUSHBUTTON = 0x0004,
- case 0x04:
- wps.setup = WpsInfo.PBC;
- break;
- //DEV_PW_REGISTRAR_SPECIFIED = 0x0005
- case 0x05:
- wps.setup = WpsInfo.KEYPAD;
- break;
- default:
- wps.setup = WpsInfo.PBC;
- break;
- }
- }
- }
-
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
- sbuf.append("\n address: ").append(deviceAddress);
- sbuf.append("\n wps: ").append(wps);
- sbuf.append("\n groupOwnerIntent: ").append(groupOwnerIntent);
- sbuf.append("\n persist: ").append(netId);
- sbuf.append("\n networkName: ").append(networkName);
- sbuf.append("\n passphrase: ").append(
- TextUtils.isEmpty(passphrase) ? "<empty>" : "<non-empty>");
- sbuf.append("\n groupOwnerBand: ").append(groupOwnerBand);
- return sbuf.toString();
- }
-
- /** Implement the Parcelable interface */
- public int describeContents() {
- return 0;
- }
-
- /** copy constructor */
- public WifiP2pConfig(WifiP2pConfig source) {
- if (source != null) {
- deviceAddress = source.deviceAddress;
- wps = new WpsInfo(source.wps);
- groupOwnerIntent = source.groupOwnerIntent;
- netId = source.netId;
- networkName = source.networkName;
- passphrase = source.passphrase;
- groupOwnerBand = source.groupOwnerBand;
- }
- }
-
- /** Implement the Parcelable interface */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(deviceAddress);
- dest.writeParcelable(wps, flags);
- dest.writeInt(groupOwnerIntent);
- dest.writeInt(netId);
- dest.writeString(networkName);
- dest.writeString(passphrase);
- dest.writeInt(groupOwnerBand);
- }
-
- /** Implement the Parcelable interface */
- public static final @android.annotation.NonNull Creator<WifiP2pConfig> CREATOR =
- new Creator<WifiP2pConfig>() {
- public WifiP2pConfig createFromParcel(Parcel in) {
- WifiP2pConfig config = new WifiP2pConfig();
- config.deviceAddress = in.readString();
- config.wps = (WpsInfo) in.readParcelable(null);
- config.groupOwnerIntent = in.readInt();
- config.netId = in.readInt();
- config.networkName = in.readString();
- config.passphrase = in.readString();
- config.groupOwnerBand = in.readInt();
- return config;
- }
-
- public WifiP2pConfig[] newArray(int size) {
- return new WifiP2pConfig[size];
- }
- };
-
- /**
- * Builder used to build {@link WifiP2pConfig} objects for
- * creating or joining a group.
- */
- public static final class Builder {
-
- private static final MacAddress MAC_ANY_ADDRESS =
- MacAddress.fromString("02:00:00:00:00:00");
- /**
- * Maximum number of bytes allowed for a SSID.
- */
- private static final int MAX_SSID_BYTES = 32;
-
- private MacAddress mDeviceAddress = MAC_ANY_ADDRESS;
- private String mNetworkName = "";
- private String mPassphrase = "";
- private int mGroupOperatingBand = GROUP_OWNER_BAND_AUTO;
- private int mGroupOperatingFrequency = GROUP_OWNER_BAND_AUTO;
- private int mNetId = WifiP2pGroup.NETWORK_ID_TEMPORARY;
-
- /**
- * Specify the peer's MAC address. If not set, the device will
- * try to find a peer whose SSID matches the network name as
- * specified by {@link #setNetworkName(String)}. Specifying null will
- * reset the peer's MAC address to "02:00:00:00:00:00".
- * <p>
- * Optional. "02:00:00:00:00:00" by default.
- *
- * @param deviceAddress the peer's MAC address.
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public @NonNull Builder setDeviceAddress(@Nullable MacAddress deviceAddress) {
- if (deviceAddress == null) {
- mDeviceAddress = MAC_ANY_ADDRESS;
- } else {
- mDeviceAddress = deviceAddress;
- }
- return this;
- }
-
- /**
- * Specify the network name, a.k.a. group name,
- * for creating or joining a group.
- * <p>
- * A network name shall begin with "DIRECT-xy". x and y are selected
- * from the following character set: upper case letters, lower case
- * letters and numbers. Any byte values allowed for an SSID according to
- * IEEE802.11-2012 [1] may be included after the string "DIRECT-xy"
- * (including none).
- * <p>
- * Must be called - an empty network name or an network name
- * not conforming to the P2P Group ID naming rule is not valid.
- *
- * @param networkName network name of a group.
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public @NonNull Builder setNetworkName(@NonNull String networkName) {
- if (TextUtils.isEmpty(networkName)) {
- throw new IllegalArgumentException(
- "network name must be non-empty.");
- }
- if (networkName.getBytes(StandardCharsets.UTF_8).length > MAX_SSID_BYTES) {
- throw new IllegalArgumentException(
- "network name exceeds " + MAX_SSID_BYTES + " bytes.");
- }
- try {
- if (!networkName.matches("^DIRECT-[a-zA-Z0-9]{2}.*")) {
- throw new IllegalArgumentException(
- "network name must starts with the prefix DIRECT-xy.");
- }
- } catch (PatternSyntaxException e) {
- // can never happen (fixed pattern)
- }
- mNetworkName = networkName;
- return this;
- }
-
- /**
- * Specify the passphrase for creating or joining a group.
- * <p>
- * The passphrase must be an ASCII string whose length is between 8
- * and 63.
- * <p>
- * Must be called - an empty passphrase is not valid.
- *
- * @param passphrase the passphrase of a group.
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public @NonNull Builder setPassphrase(@NonNull String passphrase) {
- if (TextUtils.isEmpty(passphrase)) {
- throw new IllegalArgumentException(
- "passphrase must be non-empty.");
- }
- if (passphrase.length() < 8 || passphrase.length() > 63) {
- throw new IllegalArgumentException(
- "The length of a passphrase must be between 8 and 63.");
- }
- mPassphrase = passphrase;
- return this;
- }
-
- /**
- * Specify the band to use for creating the group or joining the group. The band should
- * be {@link #GROUP_OWNER_BAND_2GHZ}, {@link #GROUP_OWNER_BAND_5GHZ} or
- * {@link #GROUP_OWNER_BAND_AUTO}.
- * <p>
- * When creating a group as Group Owner using {@link
- * WifiP2pManager#createGroup(WifiP2pManager.Channel,
- * WifiP2pConfig, WifiP2pManager.ActionListener)},
- * specifying {@link #GROUP_OWNER_BAND_AUTO} allows the system to pick the operating
- * frequency from all supported bands.
- * Specifying {@link #GROUP_OWNER_BAND_2GHZ} or {@link #GROUP_OWNER_BAND_5GHZ}
- * only allows the system to pick the operating frequency in the specified band.
- * If the Group Owner cannot create a group in the specified band, the operation will fail.
- * <p>
- * When joining a group as Group Client using {@link
- * WifiP2pManager#connect(WifiP2pManager.Channel, WifiP2pConfig,
- * WifiP2pManager.ActionListener)},
- * specifying {@link #GROUP_OWNER_BAND_AUTO} allows the system to scan all supported
- * frequencies to find the desired group. Specifying {@link #GROUP_OWNER_BAND_2GHZ} or
- * {@link #GROUP_OWNER_BAND_5GHZ} only allows the system to scan the specified band.
- * <p>
- * {@link #setGroupOperatingBand(int)} and {@link #setGroupOperatingFrequency(int)} are
- * mutually exclusive. Setting operating band and frequency both is invalid.
- * <p>
- * Optional. {@link #GROUP_OWNER_BAND_AUTO} by default.
- *
- * @param band the operating band of the group.
- * This should be one of {@link #GROUP_OWNER_BAND_AUTO},
- * {@link #GROUP_OWNER_BAND_2GHZ}, {@link #GROUP_OWNER_BAND_5GHZ}.
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public @NonNull Builder setGroupOperatingBand(@GroupOperatingBandType int band) {
- switch (band) {
- case GROUP_OWNER_BAND_AUTO:
- case GROUP_OWNER_BAND_2GHZ:
- case GROUP_OWNER_BAND_5GHZ:
- mGroupOperatingBand = band;
- break;
- default:
- throw new IllegalArgumentException(
- "Invalid constant for the group operating band!");
- }
- return this;
- }
-
- /**
- * Specify the frequency, in MHz, to use for creating the group or joining the group.
- * <p>
- * When creating a group as Group Owner using {@link WifiP2pManager#createGroup(
- * WifiP2pManager.Channel, WifiP2pConfig, WifiP2pManager.ActionListener)},
- * specifying a frequency only allows the system to pick the specified frequency.
- * If the Group Owner cannot create a group at the specified frequency,
- * the operation will fail.
- * When not specifying a frequency, it allows the system to pick operating frequency
- * from all supported bands.
- * <p>
- * When joining a group as Group Client using {@link WifiP2pManager#connect(
- * WifiP2pManager.Channel, WifiP2pConfig, WifiP2pManager.ActionListener)},
- * specifying a frequency only allows the system to scan the specified frequency.
- * If the frequency is not supported or invalid, the operation will fail.
- * When not specifying a frequency, it allows the system to scan all supported
- * frequencies to find the desired group.
- * <p>
- * {@link #setGroupOperatingBand(int)} and {@link #setGroupOperatingFrequency(int)} are
- * mutually exclusive. Setting operating band and frequency both is invalid.
- * <p>
- * Optional. 0 by default.
- *
- * @param frequency the operating frequency of the group.
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public @NonNull Builder setGroupOperatingFrequency(int frequency) {
- if (frequency < 0) {
- throw new IllegalArgumentException(
- "Invalid group operating frequency!");
- }
- mGroupOperatingFrequency = frequency;
- return this;
- }
-
- /**
- * Specify that the group configuration be persisted (i.e. saved).
- * By default the group configuration will not be saved.
- * <p>
- * Optional. false by default.
- *
- * @param persistent is this group persistent group.
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public @NonNull Builder enablePersistentMode(boolean persistent) {
- if (persistent) {
- mNetId = WifiP2pGroup.NETWORK_ID_PERSISTENT;
- } else {
- mNetId = WifiP2pGroup.NETWORK_ID_TEMPORARY;
- }
- return this;
- }
-
- /**
- * Build {@link WifiP2pConfig} given the current requests made on the builder.
- * @return {@link WifiP2pConfig} constructed based on builder method calls.
- */
- public @NonNull WifiP2pConfig build() {
- if (TextUtils.isEmpty(mNetworkName)) {
- throw new IllegalStateException(
- "network name must be non-empty.");
- }
- if (TextUtils.isEmpty(mPassphrase)) {
- throw new IllegalStateException(
- "passphrase must be non-empty.");
- }
-
- if (mGroupOperatingFrequency > 0 && mGroupOperatingBand > 0) {
- throw new IllegalStateException(
- "Preferred frequency and band are mutually exclusive.");
- }
-
- WifiP2pConfig config = new WifiP2pConfig();
- config.deviceAddress = mDeviceAddress.toString();
- config.networkName = mNetworkName;
- config.passphrase = mPassphrase;
- config.groupOwnerBand = GROUP_OWNER_BAND_AUTO;
- if (mGroupOperatingFrequency > 0) {
- config.groupOwnerBand = mGroupOperatingFrequency;
- } else if (mGroupOperatingBand > 0) {
- config.groupOwnerBand = mGroupOperatingBand;
- }
- config.netId = mNetId;
- return config;
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pDevice.java b/wifi/java/android/net/wifi/p2p/WifiP2pDevice.java
deleted file mode 100644
index 685b6b32de44..000000000000
--- a/wifi/java/android/net/wifi/p2p/WifiP2pDevice.java
+++ /dev/null
@@ -1,440 +0,0 @@
-/*
- * Copyright (C) 2011 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.p2p;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Build;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
-
-import java.util.Objects;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * A class representing a Wi-Fi p2p device
- *
- * Note that the operations are not thread safe
- * {@see WifiP2pManager}
- */
-public class WifiP2pDevice implements Parcelable {
-
- private static final String TAG = "WifiP2pDevice";
-
- /**
- * The device name is a user friendly string to identify a Wi-Fi p2p device
- */
- public String deviceName = "";
-
- /**
- * The device MAC address uniquely identifies a Wi-Fi p2p device
- */
- public String deviceAddress = "";
-
- /**
- * Primary device type identifies the type of device. For example, an application
- * could filter the devices discovered to only display printers if the purpose is to
- * enable a printing action from the user. See the Wi-Fi Direct technical specification
- * for the full list of standard device types supported.
- */
- public String primaryDeviceType;
-
- /**
- * Secondary device type is an optional attribute that can be provided by a device in
- * addition to the primary device type.
- */
- public String secondaryDeviceType;
-
-
- // These definitions match the ones in wpa_supplicant
- /* WPS config methods supported */
- private static final int WPS_CONFIG_DISPLAY = 0x0008;
- private static final int WPS_CONFIG_PUSHBUTTON = 0x0080;
- private static final int WPS_CONFIG_KEYPAD = 0x0100;
-
- /* Device Capability bitmap */
- private static final int DEVICE_CAPAB_SERVICE_DISCOVERY = 1;
- @SuppressWarnings("unused")
- private static final int DEVICE_CAPAB_CLIENT_DISCOVERABILITY = 1<<1;
- @SuppressWarnings("unused")
- private static final int DEVICE_CAPAB_CONCURRENT_OPER = 1<<2;
- @SuppressWarnings("unused")
- private static final int DEVICE_CAPAB_INFRA_MANAGED = 1<<3;
- @SuppressWarnings("unused")
- private static final int DEVICE_CAPAB_DEVICE_LIMIT = 1<<4;
- private static final int DEVICE_CAPAB_INVITATION_PROCEDURE = 1<<5;
-
- /* Group Capability bitmap */
- private static final int GROUP_CAPAB_GROUP_OWNER = 1;
- @SuppressWarnings("unused")
- private static final int GROUP_CAPAB_PERSISTENT_GROUP = 1<<1;
- private static final int GROUP_CAPAB_GROUP_LIMIT = 1<<2;
- @SuppressWarnings("unused")
- private static final int GROUP_CAPAB_INTRA_BSS_DIST = 1<<3;
- @SuppressWarnings("unused")
- private static final int GROUP_CAPAB_CROSS_CONN = 1<<4;
- @SuppressWarnings("unused")
- private static final int GROUP_CAPAB_PERSISTENT_RECONN = 1<<5;
- @SuppressWarnings("unused")
- private static final int GROUP_CAPAB_GROUP_FORMATION = 1<<6;
-
- /**
- * WPS config methods supported
- * @hide
- */
- @UnsupportedAppUsage
- public int wpsConfigMethodsSupported;
-
- /**
- * Device capability
- * @hide
- */
- @UnsupportedAppUsage
- public int deviceCapability;
-
- /**
- * Group capability
- * @hide
- */
- @UnsupportedAppUsage
- public int groupCapability;
-
- public static final int CONNECTED = 0;
- public static final int INVITED = 1;
- public static final int FAILED = 2;
- public static final int AVAILABLE = 3;
- public static final int UNAVAILABLE = 4;
-
- /** Device connection status */
- public int status = UNAVAILABLE;
-
- /** @hide */
- @UnsupportedAppUsage
- public WifiP2pWfdInfo wfdInfo;
-
- /** Detailed device string pattern with WFD info
- * Example:
- * P2P-DEVICE-FOUND 00:18:6b:de:a3:6e p2p_dev_addr=00:18:6b:de:a3:6e
- * pri_dev_type=1-0050F204-1 name='DWD-300-DEA36E' config_methods=0x188
- * dev_capab=0x21 group_capab=0x9
- */
- private static final Pattern detailedDevicePattern = Pattern.compile(
- "((?:[0-9a-f]{2}:){5}[0-9a-f]{2}) " +
- "(\\d+ )?" +
- "p2p_dev_addr=((?:[0-9a-f]{2}:){5}[0-9a-f]{2}) " +
- "pri_dev_type=(\\d+-[0-9a-fA-F]+-\\d+) " +
- "name='(.*)' " +
- "config_methods=(0x[0-9a-fA-F]+) " +
- "dev_capab=(0x[0-9a-fA-F]+) " +
- "group_capab=(0x[0-9a-fA-F]+)" +
- "( wfd_dev_info=0x([0-9a-fA-F]{12}))?" +
- "( wfd_r2_dev_info=0x([0-9a-fA-F]{4}))?"
- );
-
- /** 2 token device address pattern
- * Example:
- * P2P-DEVICE-LOST p2p_dev_addr=fa:7b:7a:42:02:13
- * AP-STA-DISCONNECTED 42:fc:89:a8:96:09
- */
- private static final Pattern twoTokenPattern = Pattern.compile(
- "(p2p_dev_addr=)?((?:[0-9a-f]{2}:){5}[0-9a-f]{2})"
- );
-
- /** 3 token device address pattern
- * Example:
- * AP-STA-CONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=fa:7b:7a:42:02:13
- * AP-STA-DISCONNECTED 42:fc:89:a8:96:09 p2p_dev_addr=fa:7b:7a:42:02:13
- */
- private static final Pattern threeTokenPattern = Pattern.compile(
- "(?:[0-9a-f]{2}:){5}[0-9a-f]{2} p2p_dev_addr=((?:[0-9a-f]{2}:){5}[0-9a-f]{2})"
- );
-
-
- public WifiP2pDevice() {
- }
-
- /**
- * @param string formats supported include
- * P2P-DEVICE-FOUND fa:7b:7a:42:02:13 p2p_dev_addr=fa:7b:7a:42:02:13
- * pri_dev_type=1-0050F204-1 name='p2p-TEST1' config_methods=0x188 dev_capab=0x27
- * group_capab=0x0 wfd_dev_info=000006015d022a0032
- *
- * P2P-DEVICE-LOST p2p_dev_addr=fa:7b:7a:42:02:13
- *
- * AP-STA-CONNECTED 42:fc:89:a8:96:09 [p2p_dev_addr=02:90:4c:a0:92:54]
- *
- * AP-STA-DISCONNECTED 42:fc:89:a8:96:09 [p2p_dev_addr=02:90:4c:a0:92:54]
- *
- * fa:7b:7a:42:02:13
- *
- * Note: The events formats can be looked up in the wpa_supplicant code
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public WifiP2pDevice(String string) throws IllegalArgumentException {
- String[] tokens = string.split("[ \n]");
- Matcher match;
-
- if (tokens.length < 1) {
- throw new IllegalArgumentException("Malformed supplicant event");
- }
-
- switch (tokens.length) {
- case 1:
- /* Just a device address */
- deviceAddress = string;
- return;
- case 2:
- match = twoTokenPattern.matcher(string);
- if (!match.find()) {
- throw new IllegalArgumentException("Malformed supplicant event");
- }
- deviceAddress = match.group(2);
- return;
- case 3:
- match = threeTokenPattern.matcher(string);
- if (!match.find()) {
- throw new IllegalArgumentException("Malformed supplicant event");
- }
- deviceAddress = match.group(1);
- return;
- default:
- match = detailedDevicePattern.matcher(string);
- if (!match.find()) {
- throw new IllegalArgumentException("Malformed supplicant event");
- }
-
- deviceAddress = match.group(3);
- primaryDeviceType = match.group(4);
- deviceName = match.group(5);
- wpsConfigMethodsSupported = parseHex(match.group(6));
- deviceCapability = parseHex(match.group(7));
- groupCapability = parseHex(match.group(8));
- if (match.group(9) != null) {
- String str = match.group(10);
- wfdInfo = new WifiP2pWfdInfo(parseHex(str.substring(0,4)),
- parseHex(str.substring(4,8)),
- parseHex(str.substring(8,12)));
- if (match.group(11) != null) {
- String r2str = match.group(12);
- wfdInfo.setWfdR2Device(parseHex(r2str.substring(0,4)));
- }
- }
- break;
- }
-
- if (tokens[0].startsWith("P2P-DEVICE-FOUND")) {
- status = AVAILABLE;
- }
- }
-
- /** The Wifi Display information for this device, or null if unavailable. */
- @Nullable
- public WifiP2pWfdInfo getWfdInfo() {
- return wfdInfo;
- }
-
- /** Returns true if WPS push button configuration is supported */
- public boolean wpsPbcSupported() {
- return (wpsConfigMethodsSupported & WPS_CONFIG_PUSHBUTTON) != 0;
- }
-
- /** Returns true if WPS keypad configuration is supported */
- public boolean wpsKeypadSupported() {
- return (wpsConfigMethodsSupported & WPS_CONFIG_KEYPAD) != 0;
- }
-
- /** Returns true if WPS display configuration is supported */
- public boolean wpsDisplaySupported() {
- return (wpsConfigMethodsSupported & WPS_CONFIG_DISPLAY) != 0;
- }
-
- /** Returns true if the device is capable of service discovery */
- public boolean isServiceDiscoveryCapable() {
- return (deviceCapability & DEVICE_CAPAB_SERVICE_DISCOVERY) != 0;
- }
-
- /** Returns true if the device is capable of invitation {@hide}*/
- public boolean isInvitationCapable() {
- return (deviceCapability & DEVICE_CAPAB_INVITATION_PROCEDURE) != 0;
- }
-
- /** Returns true if the device reaches the limit. {@hide}*/
- public boolean isDeviceLimit() {
- return (deviceCapability & DEVICE_CAPAB_DEVICE_LIMIT) != 0;
- }
-
- /** Returns true if the device is a group owner */
- public boolean isGroupOwner() {
- return (groupCapability & GROUP_CAPAB_GROUP_OWNER) != 0;
- }
-
- /** Returns true if the group reaches the limit. {@hide}*/
- public boolean isGroupLimit() {
- return (groupCapability & GROUP_CAPAB_GROUP_LIMIT) != 0;
- }
-
- /**
- * Update this device's details using another {@link WifiP2pDevice} instance.
- * This will throw an exception if the device address does not match.
- *
- * @param device another instance of {@link WifiP2pDevice} used to update this instance.
- * @throws IllegalArgumentException if the device is null or the device address does not match
- */
- public void update(@NonNull WifiP2pDevice device) {
- updateSupplicantDetails(device);
- status = device.status;
- }
-
- /** Updates details obtained from supplicant @hide */
- public void updateSupplicantDetails(WifiP2pDevice device) {
- if (device == null) {
- throw new IllegalArgumentException("device is null");
- }
- if (device.deviceAddress == null) {
- throw new IllegalArgumentException("deviceAddress is null");
- }
- if (!deviceAddress.equals(device.deviceAddress)) {
- throw new IllegalArgumentException("deviceAddress does not match");
- }
- deviceName = device.deviceName;
- primaryDeviceType = device.primaryDeviceType;
- secondaryDeviceType = device.secondaryDeviceType;
- wpsConfigMethodsSupported = device.wpsConfigMethodsSupported;
- deviceCapability = device.deviceCapability;
- groupCapability = device.groupCapability;
- wfdInfo = device.wfdInfo;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) return true;
- if (!(obj instanceof WifiP2pDevice)) return false;
-
- WifiP2pDevice other = (WifiP2pDevice) obj;
- if (other == null || other.deviceAddress == null) {
- return (deviceAddress == null);
- }
- return other.deviceAddress.equals(deviceAddress);
- }
-
- @Override
- public int hashCode() {
- return Objects.hashCode(deviceAddress);
- }
-
- @Override
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
- sbuf.append("Device: ").append(deviceName);
- sbuf.append("\n deviceAddress: ").append(deviceAddress);
- sbuf.append("\n primary type: ").append(primaryDeviceType);
- sbuf.append("\n secondary type: ").append(secondaryDeviceType);
- sbuf.append("\n wps: ").append(wpsConfigMethodsSupported);
- sbuf.append("\n grpcapab: ").append(groupCapability);
- sbuf.append("\n devcapab: ").append(deviceCapability);
- sbuf.append("\n status: ").append(status);
- sbuf.append("\n wfdInfo: ").append(wfdInfo);
- return sbuf.toString();
- }
-
- /** Implement the Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /** copy constructor */
- public WifiP2pDevice(WifiP2pDevice source) {
- if (source != null) {
- deviceName = source.deviceName;
- deviceAddress = source.deviceAddress;
- primaryDeviceType = source.primaryDeviceType;
- secondaryDeviceType = source.secondaryDeviceType;
- wpsConfigMethodsSupported = source.wpsConfigMethodsSupported;
- deviceCapability = source.deviceCapability;
- groupCapability = source.groupCapability;
- status = source.status;
- if (source.wfdInfo != null) {
- wfdInfo = new WifiP2pWfdInfo(source.wfdInfo);
- }
- }
- }
-
- /** Implement the Parcelable interface */
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(deviceName);
- dest.writeString(deviceAddress);
- dest.writeString(primaryDeviceType);
- dest.writeString(secondaryDeviceType);
- dest.writeInt(wpsConfigMethodsSupported);
- dest.writeInt(deviceCapability);
- dest.writeInt(groupCapability);
- dest.writeInt(status);
- if (wfdInfo != null) {
- dest.writeInt(1);
- wfdInfo.writeToParcel(dest, flags);
- } else {
- dest.writeInt(0);
- }
- }
-
- /** Implement the Parcelable interface */
- public static final @android.annotation.NonNull Creator<WifiP2pDevice> CREATOR =
- new Creator<WifiP2pDevice>() {
- @Override
- public WifiP2pDevice createFromParcel(Parcel in) {
- WifiP2pDevice device = new WifiP2pDevice();
- device.deviceName = in.readString();
- device.deviceAddress = in.readString();
- device.primaryDeviceType = in.readString();
- device.secondaryDeviceType = in.readString();
- device.wpsConfigMethodsSupported = in.readInt();
- device.deviceCapability = in.readInt();
- device.groupCapability = in.readInt();
- device.status = in.readInt();
- if (in.readInt() == 1) {
- device.wfdInfo = WifiP2pWfdInfo.CREATOR.createFromParcel(in);
- }
- return device;
- }
-
- @Override
- public WifiP2pDevice[] newArray(int size) {
- return new WifiP2pDevice[size];
- }
- };
-
- //supported formats: 0x1abc, 0X1abc, 1abc
- private int parseHex(String hexString) {
- int num = 0;
- if (hexString.startsWith("0x") || hexString.startsWith("0X")) {
- hexString = hexString.substring(2);
- }
-
- try {
- num = Integer.parseInt(hexString, 16);
- } catch(NumberFormatException e) {
- Log.e(TAG, "Failed to parse hex string " + hexString);
- }
- return num;
- }
-}
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pDeviceList.java b/wifi/java/android/net/wifi/p2p/WifiP2pDeviceList.java
deleted file mode 100644
index e7866e618089..000000000000
--- a/wifi/java/android/net/wifi/p2p/WifiP2pDeviceList.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright (C) 2011 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.p2p;
-
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Build;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-
-/**
- * A class representing a Wi-Fi P2p device list.
- *
- * Note that the operations are not thread safe.
- * {@see WifiP2pManager}
- */
-public class WifiP2pDeviceList implements Parcelable {
-
- private final HashMap<String, WifiP2pDevice> mDevices = new HashMap<String, WifiP2pDevice>();
-
- public WifiP2pDeviceList() {
- }
-
- /** copy constructor */
- public WifiP2pDeviceList(WifiP2pDeviceList source) {
- if (source != null) {
- for (WifiP2pDevice d : source.getDeviceList()) {
- mDevices.put(d.deviceAddress, new WifiP2pDevice(d));
- }
- }
- }
-
- /** @hide */
- public WifiP2pDeviceList(ArrayList<WifiP2pDevice> devices) {
- for (WifiP2pDevice device : devices) {
- if (device.deviceAddress != null) {
- mDevices.put(device.deviceAddress, new WifiP2pDevice(device));
- }
- }
- }
-
- private void validateDevice(WifiP2pDevice device) {
- if (device == null) throw new IllegalArgumentException("Null device");
- if (TextUtils.isEmpty(device.deviceAddress)) {
- throw new IllegalArgumentException("Empty deviceAddress");
- }
- }
-
- private void validateDeviceAddress(String deviceAddress) {
- if (TextUtils.isEmpty(deviceAddress)) {
- throw new IllegalArgumentException("Empty deviceAddress");
- }
- }
-
- /** Clear the list @hide */
- public boolean clear() {
- if (mDevices.isEmpty()) return false;
- mDevices.clear();
- return true;
- }
-
- /**
- * Add/update a device to the list. If the device is not found, a new device entry
- * is created. If the device is already found, the device details are updated
- * @param device to be updated
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public void update(WifiP2pDevice device) {
- updateSupplicantDetails(device);
- mDevices.get(device.deviceAddress).status = device.status;
- }
-
- /** Only updates details fetched from the supplicant @hide */
- public void updateSupplicantDetails(WifiP2pDevice device) {
- validateDevice(device);
- WifiP2pDevice d = mDevices.get(device.deviceAddress);
- if (d != null) {
- d.deviceName = device.deviceName;
- d.primaryDeviceType = device.primaryDeviceType;
- d.secondaryDeviceType = device.secondaryDeviceType;
- d.wpsConfigMethodsSupported = device.wpsConfigMethodsSupported;
- d.deviceCapability = device.deviceCapability;
- d.groupCapability = device.groupCapability;
- d.wfdInfo = device.wfdInfo;
- return;
- }
- //Not found, add a new one
- mDevices.put(device.deviceAddress, device);
- }
-
- /** @hide */
- public void updateGroupCapability(String deviceAddress, int groupCapab) {
- validateDeviceAddress(deviceAddress);
- WifiP2pDevice d = mDevices.get(deviceAddress);
- if (d != null) {
- d.groupCapability = groupCapab;
- }
- }
-
- /** @hide */
- public void updateStatus(String deviceAddress, int status) {
- validateDeviceAddress(deviceAddress);
- WifiP2pDevice d = mDevices.get(deviceAddress);
- if (d != null) {
- d.status = status;
- }
- }
-
- /**
- * Fetch a device from the list
- * @param deviceAddress is the address of the device
- * @return WifiP2pDevice device found, or null if none found
- */
- public WifiP2pDevice get(String deviceAddress) {
- validateDeviceAddress(deviceAddress);
- return mDevices.get(deviceAddress);
- }
-
- /** @hide */
- public boolean remove(WifiP2pDevice device) {
- validateDevice(device);
- return mDevices.remove(device.deviceAddress) != null;
- }
-
- /**
- * Remove a device from the list
- * @param deviceAddress is the address of the device
- * @return WifiP2pDevice device removed, or null if none removed
- * @hide
- */
- @UnsupportedAppUsage
- public WifiP2pDevice remove(String deviceAddress) {
- validateDeviceAddress(deviceAddress);
- return mDevices.remove(deviceAddress);
- }
-
- /** Returns true if any device the list was removed @hide */
- public boolean remove(WifiP2pDeviceList list) {
- boolean ret = false;
- for (WifiP2pDevice d : list.mDevices.values()) {
- if (remove(d)) ret = true;
- }
- return ret;
- }
-
- /** Get the list of devices */
- public Collection<WifiP2pDevice> getDeviceList() {
- return Collections.unmodifiableCollection(mDevices.values());
- }
-
- /** @hide */
- public boolean isGroupOwner(String deviceAddress) {
- validateDeviceAddress(deviceAddress);
- WifiP2pDevice device = mDevices.get(deviceAddress);
- if (device == null) {
- throw new IllegalArgumentException("Device not found " + deviceAddress);
- }
- return device.isGroupOwner();
- }
-
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
- for (WifiP2pDevice device : mDevices.values()) {
- sbuf.append("\n").append(device);
- }
- return sbuf.toString();
- }
-
- /** Implement the Parcelable interface */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mDevices.size());
- for(WifiP2pDevice device : mDevices.values()) {
- dest.writeParcelable(device, flags);
- }
- }
-
- /** Implement the Parcelable interface */
- public static final @android.annotation.NonNull Creator<WifiP2pDeviceList> CREATOR =
- new Creator<WifiP2pDeviceList>() {
- public WifiP2pDeviceList createFromParcel(Parcel in) {
- WifiP2pDeviceList deviceList = new WifiP2pDeviceList();
-
- int deviceCount = in.readInt();
- for (int i = 0; i < deviceCount; i++) {
- deviceList.update((WifiP2pDevice)in.readParcelable(null));
- }
- return deviceList;
- }
-
- public WifiP2pDeviceList[] newArray(int size) {
- return new WifiP2pDeviceList[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pGroup.java b/wifi/java/android/net/wifi/p2p/WifiP2pGroup.java
deleted file mode 100644
index e497b22d7769..000000000000
--- a/wifi/java/android/net/wifi/p2p/WifiP2pGroup.java
+++ /dev/null
@@ -1,371 +0,0 @@
-/*
- * Copyright (C) 2011 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.p2p;
-
-import android.annotation.Nullable;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * A class representing a Wi-Fi P2p group. A p2p group consists of a single group
- * owner and one or more clients. In the case of a group with only two devices, one
- * will be the group owner and the other will be a group client.
- *
- * {@see WifiP2pManager}
- */
-public class WifiP2pGroup implements Parcelable {
-
- /**
- * The temporary network id.
- * @see #getNetworkId()
- */
- public static final int NETWORK_ID_TEMPORARY = -1;
-
- /**
- * The temporary network id.
- *
- * @hide
- */
- @UnsupportedAppUsage
- public static final int TEMPORARY_NET_ID = NETWORK_ID_TEMPORARY;
-
- /**
- * The persistent network id.
- * If a matching persistent profile is found, use it.
- * Otherwise, create a new persistent profile.
- * @see #getNetworkId()
- */
- public static final int NETWORK_ID_PERSISTENT = -2;
-
- /** The network name */
- private String mNetworkName;
-
- /** Group owner */
- private WifiP2pDevice mOwner;
-
- /** Device is group owner */
- private boolean mIsGroupOwner;
-
- /** Group clients */
- private List<WifiP2pDevice> mClients = new ArrayList<WifiP2pDevice>();
-
- /** The passphrase used for WPA2-PSK */
- private String mPassphrase;
-
- private String mInterface;
-
- /** The network ID in wpa_supplicant */
- private int mNetId;
-
- /** The frequency (in MHz) used by this group */
- private int mFrequency;
-
- /** P2P group started string pattern */
- private static final Pattern groupStartedPattern = Pattern.compile(
- "ssid=\"(.+)\" " +
- "freq=(\\d+) " +
- "(?:psk=)?([0-9a-fA-F]{64})?" +
- "(?:passphrase=)?(?:\"(.{0,63})\")? " +
- "go_dev_addr=((?:[0-9a-f]{2}:){5}[0-9a-f]{2})" +
- " ?(\\[PERSISTENT\\])?"
- );
-
- public WifiP2pGroup() {
- }
-
- /**
- * @param supplicantEvent formats supported include
- *
- * P2P-GROUP-STARTED p2p-wlan0-0 [client|GO] ssid="DIRECT-W8" freq=2437
- * [psk=2182b2e50e53f260d04f3c7b25ef33c965a3291b9b36b455a82d77fd82ca15bc|
- * passphrase="fKG4jMe3"] go_dev_addr=fa:7b:7a:42:02:13 [PERSISTENT]
- *
- * P2P-GROUP-REMOVED p2p-wlan0-0 [client|GO] reason=REQUESTED
- *
- * P2P-INVITATION-RECEIVED sa=fa:7b:7a:42:02:13 go_dev_addr=f8:7b:7a:42:02:13
- * bssid=fa:7b:7a:42:82:13 unknown-network
- *
- * P2P-INVITATION-RECEIVED sa=b8:f9:34:2a:c7:9d persistent=0
- *
- * Note: The events formats can be looked up in the wpa_supplicant code
- * @hide
- */
- @UnsupportedAppUsage
- public WifiP2pGroup(String supplicantEvent) throws IllegalArgumentException {
-
- String[] tokens = supplicantEvent.split(" ");
-
- if (tokens.length < 3) {
- throw new IllegalArgumentException("Malformed supplicant event");
- }
-
- if (tokens[0].startsWith("P2P-GROUP")) {
- mInterface = tokens[1];
- mIsGroupOwner = tokens[2].equals("GO");
-
- Matcher match = groupStartedPattern.matcher(supplicantEvent);
- if (!match.find()) {
- return;
- }
-
- mNetworkName = match.group(1);
- // It throws NumberFormatException if the string cannot be parsed as an integer.
- mFrequency = Integer.parseInt(match.group(2));
- // psk is unused right now
- //String psk = match.group(3);
- mPassphrase = match.group(4);
- mOwner = new WifiP2pDevice(match.group(5));
- if (match.group(6) != null) {
- mNetId = NETWORK_ID_PERSISTENT;
- } else {
- mNetId = NETWORK_ID_TEMPORARY;
- }
- } else if (tokens[0].equals("P2P-INVITATION-RECEIVED")) {
- String sa = null;
- mNetId = NETWORK_ID_PERSISTENT;
- for (String token : tokens) {
- String[] nameValue = token.split("=");
- if (nameValue.length != 2) continue;
-
- if (nameValue[0].equals("sa")) {
- sa = nameValue[1];
-
- // set source address into the client list.
- WifiP2pDevice dev = new WifiP2pDevice();
- dev.deviceAddress = nameValue[1];
- mClients.add(dev);
- continue;
- }
-
- if (nameValue[0].equals("go_dev_addr")) {
- mOwner = new WifiP2pDevice(nameValue[1]);
- continue;
- }
-
- if (nameValue[0].equals("persistent")) {
- mNetId = Integer.parseInt(nameValue[1]);
- continue;
- }
- }
- } else {
- throw new IllegalArgumentException("Malformed supplicant event");
- }
- }
-
- /** @hide */
- public void setNetworkName(String networkName) {
- mNetworkName = networkName;
- }
-
- /**
- * Get the network name (SSID) of the group. Legacy Wi-Fi clients will discover
- * the p2p group using the network name.
- */
- public String getNetworkName() {
- return mNetworkName;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setIsGroupOwner(boolean isGo) {
- mIsGroupOwner = isGo;
- }
-
- /** Check whether this device is the group owner of the created p2p group */
- public boolean isGroupOwner() {
- return mIsGroupOwner;
- }
-
- /** @hide */
- public void setOwner(WifiP2pDevice device) {
- mOwner = device;
- }
-
- /** Get the details of the group owner as a {@link WifiP2pDevice} object */
- public WifiP2pDevice getOwner() {
- return mOwner;
- }
-
- /** @hide */
- public void addClient(String address) {
- addClient(new WifiP2pDevice(address));
- }
-
- /** @hide */
- public void addClient(WifiP2pDevice device) {
- for (WifiP2pDevice client : mClients) {
- if (client.equals(device)) return;
- }
- mClients.add(device);
- }
-
- /** @hide */
- public boolean removeClient(String address) {
- return mClients.remove(new WifiP2pDevice(address));
- }
-
- /** @hide */
- public boolean removeClient(WifiP2pDevice device) {
- return mClients.remove(device);
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public boolean isClientListEmpty() {
- return mClients.size() == 0;
- }
-
- /**
- * Returns {@code true} if the device is part of the group, {@code false} otherwise.
- *
- * @hide
- */
- public boolean contains(@Nullable WifiP2pDevice device) {
- return mOwner.equals(device) || mClients.contains(device);
- }
-
- /** Get the list of clients currently part of the p2p group */
- public Collection<WifiP2pDevice> getClientList() {
- return Collections.unmodifiableCollection(mClients);
- }
-
- /** @hide */
- public void setPassphrase(String passphrase) {
- mPassphrase = passphrase;
- }
-
- /**
- * Get the passphrase of the group. This function will return a valid passphrase only
- * at the group owner. Legacy Wi-Fi clients will need this passphrase alongside
- * network name obtained from {@link #getNetworkName()} to join the group
- */
- public String getPassphrase() {
- return mPassphrase;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setInterface(String intf) {
- mInterface = intf;
- }
-
- /** Get the interface name on which the group is created */
- public String getInterface() {
- return mInterface;
- }
-
- /** The network ID of the P2P group in wpa_supplicant. */
- public int getNetworkId() {
- return mNetId;
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public void setNetworkId(int netId) {
- this.mNetId = netId;
- }
-
- /** Get the operating frequency (in MHz) of the p2p group */
- public int getFrequency() {
- return mFrequency;
- }
-
- /** @hide */
- public void setFrequency(int freq) {
- this.mFrequency = freq;
- }
-
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
- sbuf.append("network: ").append(mNetworkName);
- sbuf.append("\n isGO: ").append(mIsGroupOwner);
- sbuf.append("\n GO: ").append(mOwner);
- for (WifiP2pDevice client : mClients) {
- sbuf.append("\n Client: ").append(client);
- }
- sbuf.append("\n interface: ").append(mInterface);
- sbuf.append("\n networkId: ").append(mNetId);
- sbuf.append("\n frequency: ").append(mFrequency);
- return sbuf.toString();
- }
-
- /** Implement the Parcelable interface */
- public int describeContents() {
- return 0;
- }
-
- /** copy constructor */
- public WifiP2pGroup(WifiP2pGroup source) {
- if (source != null) {
- mNetworkName = source.getNetworkName();
- mOwner = new WifiP2pDevice(source.getOwner());
- mIsGroupOwner = source.mIsGroupOwner;
- for (WifiP2pDevice d : source.getClientList()) mClients.add(d);
- mPassphrase = source.getPassphrase();
- mInterface = source.getInterface();
- mNetId = source.getNetworkId();
- mFrequency = source.getFrequency();
- }
- }
-
- /** Implement the Parcelable interface */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(mNetworkName);
- dest.writeParcelable(mOwner, flags);
- dest.writeByte(mIsGroupOwner ? (byte) 1: (byte) 0);
- dest.writeInt(mClients.size());
- for (WifiP2pDevice client : mClients) {
- dest.writeParcelable(client, flags);
- }
- dest.writeString(mPassphrase);
- dest.writeString(mInterface);
- dest.writeInt(mNetId);
- dest.writeInt(mFrequency);
- }
-
- /** Implement the Parcelable interface */
- public static final @android.annotation.NonNull Creator<WifiP2pGroup> CREATOR =
- new Creator<WifiP2pGroup>() {
- public WifiP2pGroup createFromParcel(Parcel in) {
- WifiP2pGroup group = new WifiP2pGroup();
- group.setNetworkName(in.readString());
- group.setOwner((WifiP2pDevice)in.readParcelable(null));
- group.setIsGroupOwner(in.readByte() == (byte)1);
- int clientCount = in.readInt();
- for (int i=0; i<clientCount; i++) {
- group.addClient((WifiP2pDevice) in.readParcelable(null));
- }
- group.setPassphrase(in.readString());
- group.setInterface(in.readString());
- group.setNetworkId(in.readInt());
- group.setFrequency(in.readInt());
- return group;
- }
-
- public WifiP2pGroup[] newArray(int size) {
- return new WifiP2pGroup[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pGroupList.java b/wifi/java/android/net/wifi/p2p/WifiP2pGroupList.java
deleted file mode 100644
index 8a86311defca..000000000000
--- a/wifi/java/android/net/wifi/p2p/WifiP2pGroupList.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Copyright (C) 2012 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.p2p;
-
-import android.annotation.NonNull;
-import android.annotation.SystemApi;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.LruCache;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-
-/**
- * A class representing a Wi-Fi P2p group list
- *
- * {@see WifiP2pManager}
- * @hide
- */
-@SystemApi
-public final class WifiP2pGroupList implements Parcelable {
-
- private static final int CREDENTIAL_MAX_NUM = 32;
-
- @UnsupportedAppUsage
- private final LruCache<Integer, WifiP2pGroup> mGroups;
- private final GroupDeleteListener mListener;
-
- private boolean isClearCalled = false;
-
- /** @hide */
- public interface GroupDeleteListener {
- public void onDeleteGroup(int netId);
- }
-
- /** @hide */
- public WifiP2pGroupList() {
- this(null, null);
- }
-
- /** @hide */
- @UnsupportedAppUsage
- public WifiP2pGroupList(WifiP2pGroupList source, GroupDeleteListener listener) {
- mListener = listener;
- mGroups = new LruCache<Integer, WifiP2pGroup>(CREDENTIAL_MAX_NUM) {
- @Override
- protected void entryRemoved(boolean evicted, Integer netId,
- WifiP2pGroup oldValue, WifiP2pGroup newValue) {
- if (mListener != null && !isClearCalled) {
- mListener.onDeleteGroup(oldValue.getNetworkId());
- }
- }
- };
-
- if (source != null) {
- for (Map.Entry<Integer, WifiP2pGroup> item : source.mGroups.snapshot().entrySet()) {
- mGroups.put(item.getKey(), item.getValue());
- }
- }
- }
-
- /**
- * Get the list of P2P groups.
- */
- @NonNull
- public List<WifiP2pGroup> getGroupList() {
- return new ArrayList<>(mGroups.snapshot().values());
- }
-
- /**
- * Add the specified group to this group list.
- *
- * @param group
- * @hide
- */
- public void add(WifiP2pGroup group) {
- mGroups.put(group.getNetworkId(), group);
- }
-
- /**
- * Remove the group with the specified network id from this group list.
- *
- * @param netId
- * @hide
- */
- public void remove(int netId) {
- mGroups.remove(netId);
- }
-
- /**
- * Remove the group with the specified device address from this group list.
- *
- * @param deviceAddress
- */
- void remove(String deviceAddress) {
- remove(getNetworkId(deviceAddress));
- }
-
- /**
- * Clear the group.
- * @hide
- */
- public boolean clear() {
- if (mGroups.size() == 0) return false;
- isClearCalled = true;
- mGroups.evictAll();
- isClearCalled = false;
- return true;
- }
-
- /**
- * Return the network id of the group owner profile with the specified p2p device
- * address.
- * If more than one persistent group of the same address is present in the list,
- * return the first one.
- *
- * @param deviceAddress p2p device address.
- * @return the network id. if not found, return -1.
- * @hide
- */
- public int getNetworkId(String deviceAddress) {
- if (deviceAddress == null) return -1;
-
- final Collection<WifiP2pGroup> groups = mGroups.snapshot().values();
- for (WifiP2pGroup grp: groups) {
- if (deviceAddress.equalsIgnoreCase(grp.getOwner().deviceAddress)) {
- // update cache ordered.
- mGroups.get(grp.getNetworkId());
- return grp.getNetworkId();
- }
- }
- return -1;
- }
-
- /**
- * Return the network id of the group with the specified p2p device address
- * and the ssid.
- *
- * @param deviceAddress p2p device address.
- * @param ssid ssid.
- * @return the network id. if not found, return -1.
- * @hide
- */
- public int getNetworkId(String deviceAddress, String ssid) {
- if (deviceAddress == null || ssid == null) {
- return -1;
- }
-
- final Collection<WifiP2pGroup> groups = mGroups.snapshot().values();
- for (WifiP2pGroup grp: groups) {
- if (deviceAddress.equalsIgnoreCase(grp.getOwner().deviceAddress) &&
- ssid.equals(grp.getNetworkName())) {
- // update cache ordered.
- mGroups.get(grp.getNetworkId());
- return grp.getNetworkId();
- }
- }
-
- return -1;
- }
-
- /**
- * Return the group owner address of the group with the specified network id
- *
- * @param netId network id.
- * @return the address. if not found, return null.
- * @hide
- */
- public String getOwnerAddr(int netId) {
- WifiP2pGroup grp = mGroups.get(netId);
- if (grp != null) {
- return grp.getOwner().deviceAddress;
- }
- return null;
- }
-
- /**
- * Return true if this group list contains the specified network id.
- * This function does NOT update LRU information.
- * It means the internal queue is NOT reordered.
- *
- * @param netId network id.
- * @return true if the specified network id is present in this group list.
- * @hide
- */
- public boolean contains(int netId) {
- final Collection<WifiP2pGroup> groups = mGroups.snapshot().values();
- for (WifiP2pGroup grp: groups) {
- if (netId == grp.getNetworkId()) {
- return true;
- }
- }
- return false;
- }
-
- @Override
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
-
- final Collection<WifiP2pGroup> groups = mGroups.snapshot().values();
- for (WifiP2pGroup grp: groups) {
- sbuf.append(grp).append("\n");
- }
- return sbuf.toString();
- }
-
- /** Implement the Parcelable interface */
- @Override
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface */
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- final Collection<WifiP2pGroup> groups = mGroups.snapshot().values();
- dest.writeInt(groups.size());
- for(WifiP2pGroup group : groups) {
- dest.writeParcelable(group, flags);
- }
- }
-
- /** Implement the Parcelable interface */
- public static final @NonNull Creator<WifiP2pGroupList> CREATOR =
- new Creator<WifiP2pGroupList>() {
- public WifiP2pGroupList createFromParcel(Parcel in) {
- WifiP2pGroupList grpList = new WifiP2pGroupList();
-
- int deviceCount = in.readInt();
- for (int i = 0; i < deviceCount; i++) {
- grpList.add((WifiP2pGroup)in.readParcelable(null));
- }
- return grpList;
- }
-
- public WifiP2pGroupList[] newArray(int size) {
- return new WifiP2pGroupList[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pInfo.java b/wifi/java/android/net/wifi/p2p/WifiP2pInfo.java
deleted file mode 100644
index 33bc37e155b5..000000000000
--- a/wifi/java/android/net/wifi/p2p/WifiP2pInfo.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2011 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.p2p;
-
-import android.os.Parcelable;
-import android.os.Parcel;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-
-/**
- * A class representing connection information about a Wi-Fi p2p group
- *
- * {@see WifiP2pManager}
- */
-public class WifiP2pInfo implements Parcelable {
-
- /** Indicates if a p2p group has been successfully formed */
- public boolean groupFormed;
-
- /** Indicates if the current device is the group owner */
- public boolean isGroupOwner;
-
- /** Group owner address */
- public InetAddress groupOwnerAddress;
-
- public WifiP2pInfo() {
- }
-
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
- sbuf.append("groupFormed: ").append(groupFormed)
- .append(" isGroupOwner: ").append(isGroupOwner)
- .append(" groupOwnerAddress: ").append(groupOwnerAddress);
- return sbuf.toString();
- }
-
- /** Implement the Parcelable interface */
- public int describeContents() {
- return 0;
- }
-
- /** copy constructor */
- public WifiP2pInfo(WifiP2pInfo source) {
- if (source != null) {
- groupFormed = source.groupFormed;
- isGroupOwner = source.isGroupOwner;
- groupOwnerAddress = source.groupOwnerAddress;
- }
- }
-
- /** Implement the Parcelable interface */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeByte(groupFormed ? (byte)1 : (byte)0);
- dest.writeByte(isGroupOwner ? (byte)1 : (byte)0);
-
- if (groupOwnerAddress != null) {
- dest.writeByte((byte)1);
- dest.writeByteArray(groupOwnerAddress.getAddress());
- } else {
- dest.writeByte((byte)0);
- }
- }
-
- /** Implement the Parcelable interface */
- public static final @android.annotation.NonNull Creator<WifiP2pInfo> CREATOR =
- new Creator<WifiP2pInfo>() {
- public WifiP2pInfo createFromParcel(Parcel in) {
- WifiP2pInfo info = new WifiP2pInfo();
- info.groupFormed = (in.readByte() == 1);
- info.isGroupOwner = (in.readByte() == 1);
- if (in.readByte() == 1) {
- try {
- info.groupOwnerAddress = InetAddress.getByAddress(in.createByteArray());
- } catch (UnknownHostException e) {}
- }
- return info;
- }
-
- public WifiP2pInfo[] newArray(int size) {
- return new WifiP2pInfo[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pManager.java b/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
deleted file mode 100644
index cccbd86e52f6..000000000000
--- a/wifi/java/android/net/wifi/p2p/WifiP2pManager.java
+++ /dev/null
@@ -1,2059 +0,0 @@
-/*
- * Copyright (C) 2011 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.p2p;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
-import android.annotation.SdkConstant;
-import android.annotation.SdkConstant.SdkConstantType;
-import android.annotation.SystemApi;
-import android.annotation.SystemService;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.content.Context;
-import android.net.NetworkInfo;
-import android.net.wifi.WpsInfo;
-import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo;
-import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceResponse;
-import android.net.wifi.p2p.nsd.WifiP2pServiceInfo;
-import android.net.wifi.p2p.nsd.WifiP2pServiceRequest;
-import android.net.wifi.p2p.nsd.WifiP2pServiceResponse;
-import android.net.wifi.p2p.nsd.WifiP2pUpnpServiceInfo;
-import android.net.wifi.p2p.nsd.WifiP2pUpnpServiceResponse;
-import android.os.Binder;
-import android.os.Build;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.os.Message;
-import android.os.Messenger;
-import android.os.RemoteException;
-import android.text.TextUtils;
-import android.util.CloseGuard;
-import android.util.Log;
-
-import com.android.internal.util.AsyncChannel;
-import com.android.internal.util.Protocol;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.ref.Reference;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * This class provides the API for managing Wi-Fi peer-to-peer connectivity. This lets an
- * application discover available peers, setup connection to peers and query for the list of peers.
- * When a p2p connection is formed over wifi, the device continues to maintain the uplink
- * connection over mobile or any other available network for internet connectivity on the device.
- *
- * <p> The API is asynchronous and responses to requests from an application are on listener
- * callbacks provided by the application. The application needs to do an initialization with
- * {@link #initialize} before doing any p2p operation.
- *
- * <p> Most application calls need a {@link ActionListener} instance for receiving callbacks
- * {@link ActionListener#onSuccess} or {@link ActionListener#onFailure}. Action callbacks
- * indicate whether the initiation of the action was a success or a failure.
- * Upon failure, the reason of failure can be one of {@link #ERROR}, {@link #P2P_UNSUPPORTED}
- * or {@link #BUSY}.
- *
- * <p> An application can initiate discovery of peers with {@link #discoverPeers}. An initiated
- * discovery request from an application stays active until the device starts connecting to a peer
- * ,forms a p2p group or there is an explicit {@link #stopPeerDiscovery}.
- * Applications can listen to {@link #WIFI_P2P_DISCOVERY_CHANGED_ACTION} to know if a peer-to-peer
- * discovery is running or stopped. Additionally, {@link #WIFI_P2P_PEERS_CHANGED_ACTION} indicates
- * if the peer list has changed.
- *
- * <p> When an application needs to fetch the current list of peers, it can request the list
- * of peers with {@link #requestPeers}. When the peer list is available
- * {@link PeerListListener#onPeersAvailable} is called with the device list.
- *
- * <p> An application can initiate a connection request to a peer through {@link #connect}. See
- * {@link WifiP2pConfig} for details on setting up the configuration. For communication with legacy
- * Wi-Fi devices that do not support p2p, an app can create a group using {@link #createGroup}
- * which creates an access point whose details can be fetched with {@link #requestGroupInfo}.
- *
- * <p> After a successful group formation through {@link #createGroup} or through {@link #connect},
- * use {@link #requestConnectionInfo} to fetch the connection details. The connection info
- * {@link WifiP2pInfo} contains the address of the group owner
- * {@link WifiP2pInfo#groupOwnerAddress} and a flag {@link WifiP2pInfo#isGroupOwner} to indicate
- * if the current device is a p2p group owner. A p2p client can thus communicate with
- * the p2p group owner through a socket connection. If the current device is the p2p group owner,
- * {@link WifiP2pInfo#groupOwnerAddress} is anonymized unless the caller holds the
- * {@code android.Manifest.permission#LOCAL_MAC_ADDRESS} permission.
- *
- * <p> With peer discovery using {@link #discoverPeers}, an application discovers the neighboring
- * peers, but has no good way to figure out which peer to establish a connection with. For example,
- * if a game application is interested in finding all the neighboring peers that are also running
- * the same game, it has no way to find out until after the connection is setup. Pre-association
- * service discovery is meant to address this issue of filtering the peers based on the running
- * services.
- *
- * <p>With pre-association service discovery, an application can advertise a service for a
- * application on a peer device prior to a connection setup between the devices.
- * Currently, DNS based service discovery (Bonjour) and Upnp are the higher layer protocols
- * supported. Get Bonjour resources at dns-sd.org and Upnp resources at upnp.org
- * As an example, a video application can discover a Upnp capable media renderer
- * prior to setting up a Wi-fi p2p connection with the device.
- *
- * <p> An application can advertise a Upnp or a Bonjour service with a call to
- * {@link #addLocalService}. After a local service is added,
- * the framework automatically responds to a peer application discovering the service prior
- * to establishing a p2p connection. A call to {@link #removeLocalService} removes a local
- * service and {@link #clearLocalServices} can be used to clear all local services.
- *
- * <p> An application that is looking for peer devices that support certain services
- * can do so with a call to {@link #discoverServices}. Prior to initiating the discovery,
- * application can add service discovery request with a call to {@link #addServiceRequest},
- * remove a service discovery request with a call to {@link #removeServiceRequest} or clear
- * all requests with a call to {@link #clearServiceRequests}. When no service requests remain,
- * a previously running service discovery will stop.
- *
- * The application is notified of a result of service discovery request through listener callbacks
- * set through {@link #setDnsSdResponseListeners} for Bonjour or
- * {@link #setUpnpServiceResponseListener} for Upnp.
- *
- * <p class="note"><strong>Note:</strong>
- * Registering an application handler with {@link #initialize} requires the permissions
- * {@link android.Manifest.permission#ACCESS_WIFI_STATE} and
- * {@link android.Manifest.permission#CHANGE_WIFI_STATE} to perform any further peer-to-peer
- * operations.
- *
- * {@see WifiP2pConfig}
- * {@see WifiP2pInfo}
- * {@see WifiP2pGroup}
- * {@see WifiP2pDevice}
- * {@see WifiP2pDeviceList}
- * {@see android.net.wifi.WpsInfo}
- */
-@SystemService(Context.WIFI_P2P_SERVICE)
-public class WifiP2pManager {
- private static final String TAG = "WifiP2pManager";
- /**
- * Broadcast intent action to indicate whether Wi-Fi p2p is enabled or disabled. An
- * extra {@link #EXTRA_WIFI_STATE} provides the state information as int.
- *
- * @see #EXTRA_WIFI_STATE
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String WIFI_P2P_STATE_CHANGED_ACTION =
- "android.net.wifi.p2p.STATE_CHANGED";
-
- /**
- * The lookup key for an int that indicates whether Wi-Fi p2p is enabled or disabled.
- * Retrieve it with {@link android.content.Intent#getIntExtra(String,int)}.
- *
- * @see #WIFI_P2P_STATE_DISABLED
- * @see #WIFI_P2P_STATE_ENABLED
- */
- public static final String EXTRA_WIFI_STATE = "wifi_p2p_state";
-
- /** @hide */
- @IntDef({
- WIFI_P2P_STATE_DISABLED,
- WIFI_P2P_STATE_ENABLED})
- @Retention(RetentionPolicy.SOURCE)
- public @interface WifiP2pState {
- }
-
- /**
- * Wi-Fi p2p is disabled.
- *
- * @see #WIFI_P2P_STATE_CHANGED_ACTION
- */
- public static final int WIFI_P2P_STATE_DISABLED = 1;
-
- /**
- * Wi-Fi p2p is enabled.
- *
- * @see #WIFI_P2P_STATE_CHANGED_ACTION
- */
- public static final int WIFI_P2P_STATE_ENABLED = 2;
-
- /**
- * Broadcast intent action indicating that the state of Wi-Fi p2p connectivity
- * has changed. One extra {@link #EXTRA_WIFI_P2P_INFO} provides the p2p connection info in
- * the form of a {@link WifiP2pInfo} object. Another extra {@link #EXTRA_NETWORK_INFO} provides
- * the network info in the form of a {@link android.net.NetworkInfo}. A third extra provides
- * the details of the group and may contain a {@code null}.
- *
- * All of these permissions are required to receive this broadcast:
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and
- * {@link android.Manifest.permission#ACCESS_WIFI_STATE}
- *
- * @see #EXTRA_WIFI_P2P_INFO
- * @see #EXTRA_NETWORK_INFO
- * @see #EXTRA_WIFI_P2P_GROUP
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String WIFI_P2P_CONNECTION_CHANGED_ACTION =
- "android.net.wifi.p2p.CONNECTION_STATE_CHANGE";
-
- /**
- * The lookup key for a {@link android.net.wifi.p2p.WifiP2pInfo} object
- * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
- */
- public static final String EXTRA_WIFI_P2P_INFO = "wifiP2pInfo";
-
- /**
- * The lookup key for a {@link android.net.NetworkInfo} object associated with the
- * p2p network. Retrieve with
- * {@link android.content.Intent#getParcelableExtra(String)}.
- */
- public static final String EXTRA_NETWORK_INFO = "networkInfo";
-
- /**
- * The lookup key for a {@link android.net.wifi.p2p.WifiP2pGroup} object
- * associated with the p2p network. Retrieve with
- * {@link android.content.Intent#getParcelableExtra(String)}.
- */
- public static final String EXTRA_WIFI_P2P_GROUP = "p2pGroupInfo";
-
- /**
- * Broadcast intent action indicating that the available peer list has changed. This
- * can be sent as a result of peers being found, lost or updated.
- *
- * All of these permissions are required to receive this broadcast:
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and
- * {@link android.Manifest.permission#ACCESS_WIFI_STATE}
- *
- * <p> An extra {@link #EXTRA_P2P_DEVICE_LIST} provides the full list of
- * current peers. The full list of peers can also be obtained any time with
- * {@link #requestPeers}.
- *
- * @see #EXTRA_P2P_DEVICE_LIST
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String WIFI_P2P_PEERS_CHANGED_ACTION =
- "android.net.wifi.p2p.PEERS_CHANGED";
-
- /**
- * The lookup key for a {@link android.net.wifi.p2p.WifiP2pDeviceList} object representing
- * the new peer list when {@link #WIFI_P2P_PEERS_CHANGED_ACTION} broadcast is sent.
- *
- * <p>Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
- */
- public static final String EXTRA_P2P_DEVICE_LIST = "wifiP2pDeviceList";
-
- /**
- * Broadcast intent action indicating that peer discovery has either started or stopped.
- * One extra {@link #EXTRA_DISCOVERY_STATE} indicates whether discovery has started
- * or stopped.
- *
- * <p>Note that discovery will be stopped during a connection setup. If the application tries
- * to re-initiate discovery during this time, it can fail.
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String WIFI_P2P_DISCOVERY_CHANGED_ACTION =
- "android.net.wifi.p2p.DISCOVERY_STATE_CHANGE";
-
- /**
- * The lookup key for an int that indicates whether p2p discovery has started or stopped.
- * Retrieve it with {@link android.content.Intent#getIntExtra(String,int)}.
- *
- * @see #WIFI_P2P_DISCOVERY_STARTED
- * @see #WIFI_P2P_DISCOVERY_STOPPED
- */
- public static final String EXTRA_DISCOVERY_STATE = "discoveryState";
-
- /** @hide */
- @IntDef({
- WIFI_P2P_DISCOVERY_STOPPED,
- WIFI_P2P_DISCOVERY_STARTED})
- @Retention(RetentionPolicy.SOURCE)
- public @interface WifiP2pDiscoveryState {
- }
-
- /**
- * p2p discovery has stopped
- *
- * @see #WIFI_P2P_DISCOVERY_CHANGED_ACTION
- */
- public static final int WIFI_P2P_DISCOVERY_STOPPED = 1;
-
- /**
- * p2p discovery has started
- *
- * @see #WIFI_P2P_DISCOVERY_CHANGED_ACTION
- */
- public static final int WIFI_P2P_DISCOVERY_STARTED = 2;
-
- /**
- * Broadcast intent action indicating that this device details have changed.
- *
- * <p> An extra {@link #EXTRA_WIFI_P2P_DEVICE} provides this device details.
- * The valid device details can also be obtained with
- * {@link #requestDeviceInfo(Channel, DeviceInfoListener)} when p2p is enabled.
- * To get information notifications on P2P getting enabled refers
- * {@link #WIFI_P2P_STATE_ENABLED}.
- *
- * <p> The {@link #EXTRA_WIFI_P2P_DEVICE} extra contains an anonymized version of the device's
- * MAC address. Callers holding the {@code android.Manifest.permission#LOCAL_MAC_ADDRESS}
- * permission can use {@link #requestDeviceInfo} to obtain the actual MAC address of this
- * device.
- *
- * All of these permissions are required to receive this broadcast:
- * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} and
- * {@link android.Manifest.permission#ACCESS_WIFI_STATE}
- *
- * @see #EXTRA_WIFI_P2P_DEVICE
- */
- @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String WIFI_P2P_THIS_DEVICE_CHANGED_ACTION =
- "android.net.wifi.p2p.THIS_DEVICE_CHANGED";
-
- /**
- * The lookup key for a {@link android.net.wifi.p2p.WifiP2pDevice} object
- * Retrieve with {@link android.content.Intent#getParcelableExtra(String)}.
- */
- public static final String EXTRA_WIFI_P2P_DEVICE = "wifiP2pDevice";
-
- /**
- * Broadcast intent action indicating that remembered persistent groups have changed.
- *
- * You can <em>not</em> receive this through components declared
- * in manifests, only by explicitly registering for it with
- * {@link android.content.Context#registerReceiver(android.content.BroadcastReceiver,
- * android.content.IntentFilter) Context.registerReceiver()}.
- *
- * @hide
- */
- @SystemApi
- public static final String ACTION_WIFI_P2P_PERSISTENT_GROUPS_CHANGED =
- "android.net.wifi.p2p.action.WIFI_P2P_PERSISTENT_GROUPS_CHANGED";
-
- /**
- * The lookup key for a handover message returned by the WifiP2pService.
- * @hide
- */
- public static final String EXTRA_HANDOVER_MESSAGE =
- "android.net.wifi.p2p.EXTRA_HANDOVER_MESSAGE";
-
- /**
- * The lookup key for a calling package name from WifiP2pManager
- * @hide
- */
- public static final String CALLING_PACKAGE =
- "android.net.wifi.p2p.CALLING_PACKAGE";
-
- /**
- * The lookup key for a calling feature id from WifiP2pManager
- * @hide
- */
- public static final String CALLING_FEATURE_ID =
- "android.net.wifi.p2p.CALLING_FEATURE_ID";
-
- /**
- * The lookup key for a calling package binder from WifiP2pManager
- * @hide
- */
- public static final String CALLING_BINDER =
- "android.net.wifi.p2p.CALLING_BINDER";
-
- IWifiP2pManager mService;
-
- private static final int BASE = Protocol.BASE_WIFI_P2P_MANAGER;
-
- /** @hide */
- public static final int DISCOVER_PEERS = BASE + 1;
- /** @hide */
- public static final int DISCOVER_PEERS_FAILED = BASE + 2;
- /** @hide */
- public static final int DISCOVER_PEERS_SUCCEEDED = BASE + 3;
-
- /** @hide */
- public static final int STOP_DISCOVERY = BASE + 4;
- /** @hide */
- public static final int STOP_DISCOVERY_FAILED = BASE + 5;
- /** @hide */
- public static final int STOP_DISCOVERY_SUCCEEDED = BASE + 6;
-
- /** @hide */
- public static final int CONNECT = BASE + 7;
- /** @hide */
- public static final int CONNECT_FAILED = BASE + 8;
- /** @hide */
- public static final int CONNECT_SUCCEEDED = BASE + 9;
-
- /** @hide */
- public static final int CANCEL_CONNECT = BASE + 10;
- /** @hide */
- public static final int CANCEL_CONNECT_FAILED = BASE + 11;
- /** @hide */
- public static final int CANCEL_CONNECT_SUCCEEDED = BASE + 12;
-
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final int CREATE_GROUP = BASE + 13;
- /** @hide */
- public static final int CREATE_GROUP_FAILED = BASE + 14;
- /** @hide */
- public static final int CREATE_GROUP_SUCCEEDED = BASE + 15;
-
- /** @hide */
- public static final int REMOVE_GROUP = BASE + 16;
- /** @hide */
- public static final int REMOVE_GROUP_FAILED = BASE + 17;
- /** @hide */
- public static final int REMOVE_GROUP_SUCCEEDED = BASE + 18;
-
- /** @hide */
- public static final int REQUEST_PEERS = BASE + 19;
- /** @hide */
- public static final int RESPONSE_PEERS = BASE + 20;
-
- /** @hide */
- public static final int REQUEST_CONNECTION_INFO = BASE + 21;
- /** @hide */
- public static final int RESPONSE_CONNECTION_INFO = BASE + 22;
-
- /** @hide */
- public static final int REQUEST_GROUP_INFO = BASE + 23;
- /** @hide */
- public static final int RESPONSE_GROUP_INFO = BASE + 24;
-
- /** @hide */
- public static final int ADD_LOCAL_SERVICE = BASE + 28;
- /** @hide */
- public static final int ADD_LOCAL_SERVICE_FAILED = BASE + 29;
- /** @hide */
- public static final int ADD_LOCAL_SERVICE_SUCCEEDED = BASE + 30;
-
- /** @hide */
- public static final int REMOVE_LOCAL_SERVICE = BASE + 31;
- /** @hide */
- public static final int REMOVE_LOCAL_SERVICE_FAILED = BASE + 32;
- /** @hide */
- public static final int REMOVE_LOCAL_SERVICE_SUCCEEDED = BASE + 33;
-
- /** @hide */
- public static final int CLEAR_LOCAL_SERVICES = BASE + 34;
- /** @hide */
- public static final int CLEAR_LOCAL_SERVICES_FAILED = BASE + 35;
- /** @hide */
- public static final int CLEAR_LOCAL_SERVICES_SUCCEEDED = BASE + 36;
-
- /** @hide */
- public static final int ADD_SERVICE_REQUEST = BASE + 37;
- /** @hide */
- public static final int ADD_SERVICE_REQUEST_FAILED = BASE + 38;
- /** @hide */
- public static final int ADD_SERVICE_REQUEST_SUCCEEDED = BASE + 39;
-
- /** @hide */
- public static final int REMOVE_SERVICE_REQUEST = BASE + 40;
- /** @hide */
- public static final int REMOVE_SERVICE_REQUEST_FAILED = BASE + 41;
- /** @hide */
- public static final int REMOVE_SERVICE_REQUEST_SUCCEEDED = BASE + 42;
-
- /** @hide */
- public static final int CLEAR_SERVICE_REQUESTS = BASE + 43;
- /** @hide */
- public static final int CLEAR_SERVICE_REQUESTS_FAILED = BASE + 44;
- /** @hide */
- public static final int CLEAR_SERVICE_REQUESTS_SUCCEEDED = BASE + 45;
-
- /** @hide */
- public static final int DISCOVER_SERVICES = BASE + 46;
- /** @hide */
- public static final int DISCOVER_SERVICES_FAILED = BASE + 47;
- /** @hide */
- public static final int DISCOVER_SERVICES_SUCCEEDED = BASE + 48;
-
- /** @hide */
- public static final int PING = BASE + 49;
-
- /** @hide */
- public static final int RESPONSE_SERVICE = BASE + 50;
-
- /** @hide */
- public static final int SET_DEVICE_NAME = BASE + 51;
- /** @hide */
- public static final int SET_DEVICE_NAME_FAILED = BASE + 52;
- /** @hide */
- public static final int SET_DEVICE_NAME_SUCCEEDED = BASE + 53;
-
- /** @hide */
- public static final int DELETE_PERSISTENT_GROUP = BASE + 54;
- /** @hide */
- public static final int DELETE_PERSISTENT_GROUP_FAILED = BASE + 55;
- /** @hide */
- public static final int DELETE_PERSISTENT_GROUP_SUCCEEDED = BASE + 56;
-
- /** @hide */
- public static final int REQUEST_PERSISTENT_GROUP_INFO = BASE + 57;
- /** @hide */
- public static final int RESPONSE_PERSISTENT_GROUP_INFO = BASE + 58;
-
- /** @hide */
- public static final int SET_WFD_INFO = BASE + 59;
- /** @hide */
- public static final int SET_WFD_INFO_FAILED = BASE + 60;
- /** @hide */
- public static final int SET_WFD_INFO_SUCCEEDED = BASE + 61;
-
- /** @hide */
- public static final int START_WPS = BASE + 62;
- /** @hide */
- public static final int START_WPS_FAILED = BASE + 63;
- /** @hide */
- public static final int START_WPS_SUCCEEDED = BASE + 64;
-
- /** @hide */
- public static final int START_LISTEN = BASE + 65;
- /** @hide */
- public static final int START_LISTEN_FAILED = BASE + 66;
- /** @hide */
- public static final int START_LISTEN_SUCCEEDED = BASE + 67;
-
- /** @hide */
- public static final int STOP_LISTEN = BASE + 68;
- /** @hide */
- public static final int STOP_LISTEN_FAILED = BASE + 69;
- /** @hide */
- public static final int STOP_LISTEN_SUCCEEDED = BASE + 70;
-
- /** @hide */
- public static final int SET_CHANNEL = BASE + 71;
- /** @hide */
- public static final int SET_CHANNEL_FAILED = BASE + 72;
- /** @hide */
- public static final int SET_CHANNEL_SUCCEEDED = BASE + 73;
-
- /** @hide */
- public static final int GET_HANDOVER_REQUEST = BASE + 75;
- /** @hide */
- public static final int GET_HANDOVER_SELECT = BASE + 76;
- /** @hide */
- public static final int RESPONSE_GET_HANDOVER_MESSAGE = BASE + 77;
- /** @hide */
- public static final int INITIATOR_REPORT_NFC_HANDOVER = BASE + 78;
- /** @hide */
- public static final int RESPONDER_REPORT_NFC_HANDOVER = BASE + 79;
- /** @hide */
- public static final int REPORT_NFC_HANDOVER_SUCCEEDED = BASE + 80;
- /** @hide */
- public static final int REPORT_NFC_HANDOVER_FAILED = BASE + 81;
-
- /** @hide */
- public static final int FACTORY_RESET = BASE + 82;
- /** @hide */
- public static final int FACTORY_RESET_FAILED = BASE + 83;
- /** @hide */
- public static final int FACTORY_RESET_SUCCEEDED = BASE + 84;
-
- /** @hide */
- public static final int REQUEST_ONGOING_PEER_CONFIG = BASE + 85;
- /** @hide */
- public static final int RESPONSE_ONGOING_PEER_CONFIG = BASE + 86;
- /** @hide */
- public static final int SET_ONGOING_PEER_CONFIG = BASE + 87;
- /** @hide */
- public static final int SET_ONGOING_PEER_CONFIG_FAILED = BASE + 88;
- /** @hide */
- public static final int SET_ONGOING_PEER_CONFIG_SUCCEEDED = BASE + 89;
-
- /** @hide */
- public static final int SET_WFDR2_INFO = BASE + 90;
- /** @hide */
- public static final int SET_WFDR2_INFO_FAILED = BASE + 91;
- /** @hide */
- public static final int SET_WFDR2_INFO_SUCCEEDED = BASE + 92;
-
- /** @hide */
- public static final int REQUEST_P2P_STATE = BASE + 93;
- /** @hide */
- public static final int RESPONSE_P2P_STATE = BASE + 94;
-
- /** @hide */
- public static final int REQUEST_DISCOVERY_STATE = BASE + 95;
- /** @hide */
- public static final int RESPONSE_DISCOVERY_STATE = BASE + 96;
-
- /** @hide */
- public static final int REQUEST_NETWORK_INFO = BASE + 97;
- /** @hide */
- public static final int RESPONSE_NETWORK_INFO = BASE + 98;
-
- /** @hide */
- public static final int UPDATE_CHANNEL_INFO = BASE + 99;
-
- /** @hide */
- public static final int REQUEST_DEVICE_INFO = BASE + 100;
- /** @hide */
- public static final int RESPONSE_DEVICE_INFO = BASE + 101;
-
- /**
- * Create a new WifiP2pManager instance. Applications use
- * {@link android.content.Context#getSystemService Context.getSystemService()} to retrieve
- * the standard {@link android.content.Context#WIFI_P2P_SERVICE Context.WIFI_P2P_SERVICE}.
- * @param service the Binder interface
- * @hide - hide this because it takes in a parameter of type IWifiP2pManager, which
- * is a system private class.
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- public WifiP2pManager(IWifiP2pManager service) {
- mService = service;
- }
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation failed due to an internal error.
- */
- public static final int ERROR = 0;
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation failed because p2p is unsupported on the device.
- */
- public static final int P2P_UNSUPPORTED = 1;
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the operation failed because the framework is busy and
- * unable to service the request
- */
- public static final int BUSY = 2;
-
- /**
- * Passed with {@link ActionListener#onFailure}.
- * Indicates that the {@link #discoverServices} failed because no service
- * requests are added. Use {@link #addServiceRequest} to add a service
- * request.
- */
- public static final int NO_SERVICE_REQUESTS = 3;
-
- /** Interface for callback invocation when framework channel is lost */
- public interface ChannelListener {
- /**
- * The channel to the framework has been disconnected.
- * Application could try re-initializing using {@link #initialize}
- */
- public void onChannelDisconnected();
- }
-
- /** Interface for callback invocation on an application action */
- public interface ActionListener {
- /** The operation succeeded */
- public void onSuccess();
- /**
- * The operation failed
- * @param reason The reason for failure could be one of {@link #P2P_UNSUPPORTED},
- * {@link #ERROR} or {@link #BUSY}
- */
- public void onFailure(int reason);
- }
-
- /** Interface for callback invocation when peer list is available */
- public interface PeerListListener {
- /**
- * The requested peer list is available
- * @param peers List of available peers
- */
- public void onPeersAvailable(WifiP2pDeviceList peers);
- }
-
- /** Interface for callback invocation when connection info is available */
- public interface ConnectionInfoListener {
- /**
- * The requested connection info is available
- * @param info Wi-Fi p2p connection info
- */
- public void onConnectionInfoAvailable(WifiP2pInfo info);
- }
-
- /** Interface for callback invocation when group info is available */
- public interface GroupInfoListener {
- /**
- * The requested p2p group info is available
- * @param group Wi-Fi p2p group info
- */
- public void onGroupInfoAvailable(WifiP2pGroup group);
- }
-
- /**
- * Interface for callback invocation when service discovery response other than
- * Upnp or Bonjour is received
- */
- public interface ServiceResponseListener {
-
- /**
- * The requested service response is available.
- *
- * @param protocolType protocol type. currently only
- * {@link WifiP2pServiceInfo#SERVICE_TYPE_VENDOR_SPECIFIC}.
- * @param responseData service discovery response data based on the requested
- * service protocol type. The format depends on the service type.
- * @param srcDevice source device.
- */
- public void onServiceAvailable(int protocolType,
- byte[] responseData, WifiP2pDevice srcDevice);
- }
-
- /**
- * Interface for callback invocation when Bonjour service discovery response
- * is received
- */
- public interface DnsSdServiceResponseListener {
-
- /**
- * The requested Bonjour service response is available.
- *
- * <p>This function is invoked when the device with the specified Bonjour
- * registration type returned the instance name.
- * @param instanceName instance name.<br>
- * e.g) "MyPrinter".
- * @param registrationType <br>
- * e.g) "_ipp._tcp.local."
- * @param srcDevice source device.
- */
- public void onDnsSdServiceAvailable(String instanceName,
- String registrationType, WifiP2pDevice srcDevice);
-
- }
-
- /**
- * Interface for callback invocation when Bonjour TXT record is available
- * for a service
- */
- public interface DnsSdTxtRecordListener {
- /**
- * The requested Bonjour service response is available.
- *
- * <p>This function is invoked when the device with the specified full
- * service domain service returned TXT record.
- *
- * @param fullDomainName full domain name. <br>
- * e.g) "MyPrinter._ipp._tcp.local.".
- * @param txtRecordMap TXT record data as a map of key/value pairs
- * @param srcDevice source device.
- */
- public void onDnsSdTxtRecordAvailable(String fullDomainName,
- Map<String, String> txtRecordMap,
- WifiP2pDevice srcDevice);
- }
-
- /**
- * Interface for callback invocation when upnp service discovery response
- * is received
- * */
- public interface UpnpServiceResponseListener {
-
- /**
- * The requested upnp service response is available.
- *
- * <p>This function is invoked when the specified device or service is found.
- *
- * @param uniqueServiceNames The list of unique service names.<br>
- * e.g) uuid:6859dede-8574-59ab-9332-123456789012::urn:schemas-upnp-org:device:
- * MediaServer:1
- * @param srcDevice source device.
- */
- public void onUpnpServiceAvailable(List<String> uniqueServiceNames,
- WifiP2pDevice srcDevice);
- }
-
-
- /**
- * Interface for callback invocation when stored group info list is available
- *
- * @hide
- */
- @SystemApi
- public interface PersistentGroupInfoListener {
- /**
- * The requested stored p2p group info list is available
- * @param groups Wi-Fi p2p group info list
- */
- void onPersistentGroupInfoAvailable(@NonNull WifiP2pGroupList groups);
- }
-
- /**
- * Interface for callback invocation when Handover Request or Select Message is available
- * @hide
- */
- public interface HandoverMessageListener {
- public void onHandoverMessageAvailable(String handoverMessage);
- }
-
- /** Interface for callback invocation when p2p state is available
- * in response to {@link #requestP2pState}.
- */
- public interface P2pStateListener {
- /**
- * The requested p2p state is available.
- * @param state Wi-Fi p2p state
- * @see #WIFI_P2P_STATE_DISABLED
- * @see #WIFI_P2P_STATE_ENABLED
- */
- void onP2pStateAvailable(@WifiP2pState int state);
- }
-
- /** Interface for callback invocation when p2p state is available
- * in response to {@link #requestDiscoveryState}.
- */
- public interface DiscoveryStateListener {
- /**
- * The requested p2p discovery state is available.
- * @param state Wi-Fi p2p discovery state
- * @see #WIFI_P2P_DISCOVERY_STARTED
- * @see #WIFI_P2P_DISCOVERY_STOPPED
- */
- void onDiscoveryStateAvailable(@WifiP2pDiscoveryState int state);
- }
-
- /** Interface for callback invocation when {@link android.net.NetworkInfo} is available
- * in response to {@link #requestNetworkInfo}.
- */
- public interface NetworkInfoListener {
- /**
- * The requested {@link android.net.NetworkInfo} is available
- * @param networkInfo Wi-Fi p2p {@link android.net.NetworkInfo}
- */
- void onNetworkInfoAvailable(@NonNull NetworkInfo networkInfo);
- }
-
- /**
- * Interface for callback invocation when ongoing peer info is available
- * @hide
- */
- public interface OngoingPeerInfoListener {
- /**
- * The requested ongoing WifiP2pConfig is available
- * @param peerConfig WifiP2pConfig for current connecting session
- */
- void onOngoingPeerAvailable(WifiP2pConfig peerConfig);
- }
-
- /** Interface for callback invocation when {@link android.net.wifi.p2p.WifiP2pDevice}
- * is available in response to {@link #requestDeviceInfo(Channel, DeviceInfoListener)}.
- */
- public interface DeviceInfoListener {
- /**
- * The requested {@link android.net.wifi.p2p.WifiP2pDevice} is available.
- * @param wifiP2pDevice Wi-Fi p2p {@link android.net.wifi.p2p.WifiP2pDevice}
- */
- void onDeviceInfoAvailable(@Nullable WifiP2pDevice wifiP2pDevice);
- }
-
- /**
- * A channel that connects the application to the Wifi p2p framework.
- * Most p2p operations require a Channel as an argument. An instance of Channel is obtained
- * by doing a call on {@link #initialize}
- */
- public static class Channel implements AutoCloseable {
- /** @hide */
- public Channel(Context context, Looper looper, ChannelListener l, Binder binder,
- WifiP2pManager p2pManager) {
- mAsyncChannel = new AsyncChannel();
- mHandler = new P2pHandler(looper);
- mChannelListener = l;
- mContext = context;
- mBinder = binder;
- mP2pManager = p2pManager;
-
- mCloseGuard.open("close");
- }
- private final static int INVALID_LISTENER_KEY = 0;
- private final WifiP2pManager mP2pManager;
- private ChannelListener mChannelListener;
- private ServiceResponseListener mServRspListener;
- private DnsSdServiceResponseListener mDnsSdServRspListener;
- private DnsSdTxtRecordListener mDnsSdTxtListener;
- private UpnpServiceResponseListener mUpnpServRspListener;
- private HashMap<Integer, Object> mListenerMap = new HashMap<Integer, Object>();
- private final Object mListenerMapLock = new Object();
- private int mListenerKey = 0;
-
- private final CloseGuard mCloseGuard = new CloseGuard();
-
- /**
- * Close the current P2P connection and indicate to the P2P service that connections
- * created by the app can be removed.
- */
- public void close() {
- if (mP2pManager == null) {
- Log.w(TAG, "Channel.close(): Null mP2pManager!?");
- } else {
- try {
- mP2pManager.mService.close(mBinder);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- mAsyncChannel.disconnect();
- mCloseGuard.close();
- Reference.reachabilityFence(this);
- }
-
- /** @hide */
- @Override
- protected void finalize() throws Throwable {
- try {
- if (mCloseGuard != null) {
- mCloseGuard.warnIfOpen();
- }
-
- close();
- } finally {
- super.finalize();
- }
- }
-
- /* package */ final Binder mBinder;
-
- @UnsupportedAppUsage
- private AsyncChannel mAsyncChannel;
- private P2pHandler mHandler;
- Context mContext;
- class P2pHandler extends Handler {
- P2pHandler(Looper looper) {
- super(looper);
- }
-
- @Override
- public void handleMessage(Message message) {
- Object listener = getListener(message.arg2);
- switch (message.what) {
- case AsyncChannel.CMD_CHANNEL_DISCONNECTED:
- if (mChannelListener != null) {
- mChannelListener.onChannelDisconnected();
- mChannelListener = null;
- }
- break;
- /* ActionListeners grouped together */
- case DISCOVER_PEERS_FAILED:
- case STOP_DISCOVERY_FAILED:
- case DISCOVER_SERVICES_FAILED:
- case CONNECT_FAILED:
- case CANCEL_CONNECT_FAILED:
- case CREATE_GROUP_FAILED:
- case REMOVE_GROUP_FAILED:
- case ADD_LOCAL_SERVICE_FAILED:
- case REMOVE_LOCAL_SERVICE_FAILED:
- case CLEAR_LOCAL_SERVICES_FAILED:
- case ADD_SERVICE_REQUEST_FAILED:
- case REMOVE_SERVICE_REQUEST_FAILED:
- case CLEAR_SERVICE_REQUESTS_FAILED:
- case SET_DEVICE_NAME_FAILED:
- case DELETE_PERSISTENT_GROUP_FAILED:
- case SET_WFD_INFO_FAILED:
- case SET_WFDR2_INFO_FAILED:
- case START_WPS_FAILED:
- case START_LISTEN_FAILED:
- case STOP_LISTEN_FAILED:
- case SET_CHANNEL_FAILED:
- case REPORT_NFC_HANDOVER_FAILED:
- case FACTORY_RESET_FAILED:
- case SET_ONGOING_PEER_CONFIG_FAILED:
- if (listener != null) {
- ((ActionListener) listener).onFailure(message.arg1);
- }
- break;
- /* ActionListeners grouped together */
- case DISCOVER_PEERS_SUCCEEDED:
- case STOP_DISCOVERY_SUCCEEDED:
- case DISCOVER_SERVICES_SUCCEEDED:
- case CONNECT_SUCCEEDED:
- case CANCEL_CONNECT_SUCCEEDED:
- case CREATE_GROUP_SUCCEEDED:
- case REMOVE_GROUP_SUCCEEDED:
- case ADD_LOCAL_SERVICE_SUCCEEDED:
- case REMOVE_LOCAL_SERVICE_SUCCEEDED:
- case CLEAR_LOCAL_SERVICES_SUCCEEDED:
- case ADD_SERVICE_REQUEST_SUCCEEDED:
- case REMOVE_SERVICE_REQUEST_SUCCEEDED:
- case CLEAR_SERVICE_REQUESTS_SUCCEEDED:
- case SET_DEVICE_NAME_SUCCEEDED:
- case DELETE_PERSISTENT_GROUP_SUCCEEDED:
- case SET_WFD_INFO_SUCCEEDED:
- case SET_WFDR2_INFO_SUCCEEDED:
- case START_WPS_SUCCEEDED:
- case START_LISTEN_SUCCEEDED:
- case STOP_LISTEN_SUCCEEDED:
- case SET_CHANNEL_SUCCEEDED:
- case REPORT_NFC_HANDOVER_SUCCEEDED:
- case FACTORY_RESET_SUCCEEDED:
- case SET_ONGOING_PEER_CONFIG_SUCCEEDED:
- if (listener != null) {
- ((ActionListener) listener).onSuccess();
- }
- break;
- case RESPONSE_PEERS:
- WifiP2pDeviceList peers = (WifiP2pDeviceList) message.obj;
- if (listener != null) {
- ((PeerListListener) listener).onPeersAvailable(peers);
- }
- break;
- case RESPONSE_CONNECTION_INFO:
- WifiP2pInfo wifiP2pInfo = (WifiP2pInfo) message.obj;
- if (listener != null) {
- ((ConnectionInfoListener) listener).onConnectionInfoAvailable(wifiP2pInfo);
- }
- break;
- case RESPONSE_GROUP_INFO:
- WifiP2pGroup group = (WifiP2pGroup) message.obj;
- if (listener != null) {
- ((GroupInfoListener) listener).onGroupInfoAvailable(group);
- }
- break;
- case RESPONSE_SERVICE:
- WifiP2pServiceResponse resp = (WifiP2pServiceResponse) message.obj;
- handleServiceResponse(resp);
- break;
- case RESPONSE_PERSISTENT_GROUP_INFO:
- WifiP2pGroupList groups = (WifiP2pGroupList) message.obj;
- if (listener != null) {
- ((PersistentGroupInfoListener) listener).
- onPersistentGroupInfoAvailable(groups);
- }
- break;
- case RESPONSE_GET_HANDOVER_MESSAGE:
- Bundle handoverBundle = (Bundle) message.obj;
- if (listener != null) {
- String handoverMessage = handoverBundle != null
- ? handoverBundle.getString(EXTRA_HANDOVER_MESSAGE)
- : null;
- ((HandoverMessageListener) listener)
- .onHandoverMessageAvailable(handoverMessage);
- }
- break;
- case RESPONSE_ONGOING_PEER_CONFIG:
- WifiP2pConfig peerConfig = (WifiP2pConfig) message.obj;
- if (listener != null) {
- ((OngoingPeerInfoListener) listener)
- .onOngoingPeerAvailable(peerConfig);
- }
- break;
- case RESPONSE_P2P_STATE:
- if (listener != null) {
- ((P2pStateListener) listener)
- .onP2pStateAvailable(message.arg1);
- }
- break;
- case RESPONSE_DISCOVERY_STATE:
- if (listener != null) {
- ((DiscoveryStateListener) listener)
- .onDiscoveryStateAvailable(message.arg1);
- }
- break;
- case RESPONSE_NETWORK_INFO:
- if (listener != null) {
- ((NetworkInfoListener) listener)
- .onNetworkInfoAvailable((NetworkInfo) message.obj);
- }
- break;
- case RESPONSE_DEVICE_INFO:
- if (listener != null) {
- ((DeviceInfoListener) listener)
- .onDeviceInfoAvailable((WifiP2pDevice) message.obj);
- }
- break;
- default:
- Log.d(TAG, "Ignored " + message);
- break;
- }
- }
- }
-
- private void handleServiceResponse(WifiP2pServiceResponse resp) {
- if (resp instanceof WifiP2pDnsSdServiceResponse) {
- handleDnsSdServiceResponse((WifiP2pDnsSdServiceResponse)resp);
- } else if (resp instanceof WifiP2pUpnpServiceResponse) {
- if (mUpnpServRspListener != null) {
- handleUpnpServiceResponse((WifiP2pUpnpServiceResponse)resp);
- }
- } else {
- if (mServRspListener != null) {
- mServRspListener.onServiceAvailable(resp.getServiceType(),
- resp.getRawData(), resp.getSrcDevice());
- }
- }
- }
-
- private void handleUpnpServiceResponse(WifiP2pUpnpServiceResponse resp) {
- mUpnpServRspListener.onUpnpServiceAvailable(resp.getUniqueServiceNames(),
- resp.getSrcDevice());
- }
-
- private void handleDnsSdServiceResponse(WifiP2pDnsSdServiceResponse resp) {
- if (resp.getDnsType() == WifiP2pDnsSdServiceInfo.DNS_TYPE_PTR) {
- if (mDnsSdServRspListener != null) {
- mDnsSdServRspListener.onDnsSdServiceAvailable(
- resp.getInstanceName(),
- resp.getDnsQueryName(),
- resp.getSrcDevice());
- }
- } else if (resp.getDnsType() == WifiP2pDnsSdServiceInfo.DNS_TYPE_TXT) {
- if (mDnsSdTxtListener != null) {
- mDnsSdTxtListener.onDnsSdTxtRecordAvailable(
- resp.getDnsQueryName(),
- resp.getTxtRecord(),
- resp.getSrcDevice());
- }
- } else {
- Log.e(TAG, "Unhandled resp " + resp);
- }
- }
-
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- private int putListener(Object listener) {
- if (listener == null) return INVALID_LISTENER_KEY;
- int key;
- synchronized (mListenerMapLock) {
- do {
- key = mListenerKey++;
- } while (key == INVALID_LISTENER_KEY);
- mListenerMap.put(key, listener);
- }
- return key;
- }
-
- private Object getListener(int key) {
- if (key == INVALID_LISTENER_KEY) return null;
- synchronized (mListenerMapLock) {
- return mListenerMap.remove(key);
- }
- }
- }
-
- private static void checkChannel(Channel c) {
- if (c == null) throw new IllegalArgumentException("Channel needs to be initialized");
- }
-
- private static void checkServiceInfo(WifiP2pServiceInfo info) {
- if (info == null) throw new IllegalArgumentException("service info is null");
- }
-
- private static void checkServiceRequest(WifiP2pServiceRequest req) {
- if (req == null) throw new IllegalArgumentException("service request is null");
- }
-
- private static void checkP2pConfig(WifiP2pConfig c) {
- if (c == null) throw new IllegalArgumentException("config cannot be null");
- if (TextUtils.isEmpty(c.deviceAddress)) {
- throw new IllegalArgumentException("deviceAddress cannot be empty");
- }
- }
-
- /**
- * Registers the application with the Wi-Fi framework. This function
- * must be the first to be called before any p2p operations are performed.
- *
- * @param srcContext is the context of the source
- * @param srcLooper is the Looper on which the callbacks are receivied
- * @param listener for callback at loss of framework communication. Can be null.
- * @return Channel instance that is necessary for performing any further p2p operations
- */
- public Channel initialize(Context srcContext, Looper srcLooper, ChannelListener listener) {
- Binder binder = new Binder();
- Channel channel = initializeChannel(srcContext, srcLooper, listener,
- getMessenger(binder, srcContext.getOpPackageName()), binder);
- return channel;
- }
-
- /**
- * Registers the application with the Wi-Fi framework. Enables system-only functionality.
- * @hide
- */
- public Channel initializeInternal(Context srcContext, Looper srcLooper,
- ChannelListener listener) {
- return initializeChannel(srcContext, srcLooper, listener, getP2pStateMachineMessenger(),
- null);
- }
-
- private Channel initializeChannel(Context srcContext, Looper srcLooper,
- ChannelListener listener, Messenger messenger, Binder binder) {
- if (messenger == null) return null;
-
- Channel c = new Channel(srcContext, srcLooper, listener, binder, this);
- if (c.mAsyncChannel.connectSync(srcContext, c.mHandler, messenger)
- == AsyncChannel.STATUS_SUCCESSFUL) {
- Bundle bundle = new Bundle();
- bundle.putString(CALLING_PACKAGE, c.mContext.getOpPackageName());
- bundle.putString(CALLING_FEATURE_ID, c.mContext.getAttributionTag());
- bundle.putBinder(CALLING_BINDER, binder);
- c.mAsyncChannel.sendMessage(UPDATE_CHANNEL_INFO, 0,
- c.putListener(null), bundle);
- return c;
- } else {
- c.close();
- return null;
- }
- }
-
- /**
- * Initiate peer discovery. A discovery process involves scanning for available Wi-Fi peers
- * for the purpose of establishing a connection.
- *
- * <p> The function call immediately returns after sending a discovery request
- * to the framework. The application is notified of a success or failure to initiate
- * discovery through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * <p> The discovery remains active until a connection is initiated or
- * a p2p group is formed. Register for {@link #WIFI_P2P_PEERS_CHANGED_ACTION} intent to
- * determine when the framework notifies of a change as peers are discovered.
- *
- * <p> Upon receiving a {@link #WIFI_P2P_PEERS_CHANGED_ACTION} intent, an application
- * can request for the list of peers using {@link #requestPeers}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callbacks on success or failure. Can be null.
- */
- @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
- public void discoverPeers(Channel c, ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(DISCOVER_PEERS, 0, c.putListener(listener));
- }
-
- /**
- * Stop an ongoing peer discovery
- *
- * <p> The function call immediately returns after sending a stop request
- * to the framework. The application is notified of a success or failure to initiate
- * stop through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callbacks on success or failure. Can be null.
- */
- public void stopPeerDiscovery(Channel c, ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(STOP_DISCOVERY, 0, c.putListener(listener));
- }
-
- /**
- * Start a p2p connection to a device with the specified configuration.
- *
- * <p> The function call immediately returns after sending a connection request
- * to the framework. The application is notified of a success or failure to initiate
- * connect through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * <p> Register for {@link #WIFI_P2P_CONNECTION_CHANGED_ACTION} intent to
- * determine when the framework notifies of a change in connectivity.
- *
- * <p> If the current device is not part of a p2p group, a connect request initiates
- * a group negotiation with the peer.
- *
- * <p> If the current device is part of an existing p2p group or has created
- * a p2p group with {@link #createGroup}, an invitation to join the group is sent to
- * the peer device.
- *
- * @param c is the channel created at {@link #initialize}
- * @param config options as described in {@link WifiP2pConfig} class
- * @param listener for callbacks on success or failure. Can be null.
- */
- @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
- public void connect(Channel c, WifiP2pConfig config, ActionListener listener) {
- checkChannel(c);
- checkP2pConfig(config);
- c.mAsyncChannel.sendMessage(CONNECT, 0, c.putListener(listener), config);
- }
-
- /**
- * Cancel any ongoing p2p group negotiation
- *
- * <p> The function call immediately returns after sending a connection cancellation request
- * to the framework. The application is notified of a success or failure to initiate
- * cancellation through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callbacks on success or failure. Can be null.
- */
- public void cancelConnect(Channel c, ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(CANCEL_CONNECT, 0, c.putListener(listener));
- }
-
- /**
- * Create a p2p group with the current device as the group owner. This essentially creates
- * an access point that can accept connections from legacy clients as well as other p2p
- * devices.
- *
- * <p class="note"><strong>Note:</strong>
- * This function would normally not be used unless the current device needs
- * to form a p2p connection with a legacy client
- *
- * <p> The function call immediately returns after sending a group creation request
- * to the framework. The application is notified of a success or failure to initiate
- * group creation through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * <p> Application can request for the group details with {@link #requestGroupInfo}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callbacks on success or failure. Can be null.
- */
- @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
- public void createGroup(Channel c, ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(CREATE_GROUP, WifiP2pGroup.NETWORK_ID_PERSISTENT,
- c.putListener(listener));
- }
-
- /**
- * Create a p2p group with the current device as the group owner. This essentially creates
- * an access point that can accept connections from legacy clients as well as other p2p
- * devices.
- *
- * <p> An app should use {@link WifiP2pConfig.Builder} to build the configuration
- * for a group.
- *
- * <p class="note"><strong>Note:</strong>
- * This function would normally not be used unless the current device needs
- * to form a p2p group as a Group Owner and allow peers to join it as either
- * Group Clients or legacy Wi-Fi STAs.
- *
- * <p> The function call immediately returns after sending a group creation request
- * to the framework. The application is notified of a success or failure to initiate
- * group creation through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * <p> Application can request for the group details with {@link #requestGroupInfo}.
- *
- * @param c is the channel created at {@link #initialize}.
- * @param config the configuration of a p2p group.
- * @param listener for callbacks on success or failure. Can be null.
- */
- @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
- public void createGroup(@NonNull Channel c,
- @Nullable WifiP2pConfig config,
- @Nullable ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(CREATE_GROUP, 0,
- c.putListener(listener), config);
- }
-
- /**
- * Remove the current p2p group.
- *
- * <p> The function call immediately returns after sending a group removal request
- * to the framework. The application is notified of a success or failure to initiate
- * group removal through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callbacks on success or failure. Can be null.
- */
- public void removeGroup(Channel c, ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(REMOVE_GROUP, 0, c.putListener(listener));
- }
-
- /**
- * Force p2p to enter listen state
- *
- * @param c is the channel created at {@link #initialize(Context, Looper, ChannelListener)}
- * @param listener for callbacks on success or failure. Can be null.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void startListening(@NonNull Channel c, @Nullable ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(START_LISTEN, 0, c.putListener(listener));
- }
-
- /**
- * Force p2p to exit listen state
- *
- * @param c is the channel created at {@link #initialize(Context, Looper, ChannelListener)}
- * @param listener for callbacks on success or failure. Can be null.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void stopListening(@NonNull Channel c, @Nullable ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(STOP_LISTEN, 0, c.putListener(listener));
- }
-
- /**
- * Set P2P listening and operating channel.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listeningChannel the listening channel's Wifi channel number. e.g. 1, 6, 11.
- * @param operatingChannel the operating channel's Wifi channel number. e.g. 1, 6, 11.
- * @param listener for callbacks on success or failure. Can be null.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_STACK,
- android.Manifest.permission.OVERRIDE_WIFI_CONFIG
- })
- public void setWifiP2pChannels(@NonNull Channel c, int listeningChannel, int operatingChannel,
- @Nullable ActionListener listener) {
- checkChannel(c);
- Bundle p2pChannels = new Bundle();
- p2pChannels.putInt("lc", listeningChannel);
- p2pChannels.putInt("oc", operatingChannel);
- c.mAsyncChannel.sendMessage(SET_CHANNEL, 0, c.putListener(listener), p2pChannels);
- }
-
- /**
- * Start a Wi-Fi Protected Setup (WPS) session.
- *
- * <p> The function call immediately returns after sending a request to start a
- * WPS session. Currently, this is only valid if the current device is running
- * as a group owner to allow any new clients to join the group. The application
- * is notified of a success or failure to initiate WPS through listener callbacks
- * {@link ActionListener#onSuccess} or {@link ActionListener#onFailure}.
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public void startWps(Channel c, WpsInfo wps, ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(START_WPS, 0, c.putListener(listener), wps);
- }
-
- /**
- * Register a local service for service discovery. If a local service is registered,
- * the framework automatically responds to a service discovery request from a peer.
- *
- * <p> The function call immediately returns after sending a request to add a local
- * service to the framework. The application is notified of a success or failure to
- * add service through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * <p>The service information is set through {@link WifiP2pServiceInfo}.<br>
- * or its subclass calls {@link WifiP2pUpnpServiceInfo#newInstance} or
- * {@link WifiP2pDnsSdServiceInfo#newInstance} for a Upnp or Bonjour service
- * respectively
- *
- * <p>The service information can be cleared with calls to
- * {@link #removeLocalService} or {@link #clearLocalServices}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param servInfo is a local service information.
- * @param listener for callbacks on success or failure. Can be null.
- */
- @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
- public void addLocalService(Channel c, WifiP2pServiceInfo servInfo, ActionListener listener) {
- checkChannel(c);
- checkServiceInfo(servInfo);
- c.mAsyncChannel.sendMessage(ADD_LOCAL_SERVICE, 0, c.putListener(listener), servInfo);
- }
-
- /**
- * Remove a registered local service added with {@link #addLocalService}
- *
- * <p> The function call immediately returns after sending a request to remove a
- * local service to the framework. The application is notified of a success or failure to
- * add service through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param servInfo is the local service information.
- * @param listener for callbacks on success or failure. Can be null.
- */
- public void removeLocalService(Channel c, WifiP2pServiceInfo servInfo,
- ActionListener listener) {
- checkChannel(c);
- checkServiceInfo(servInfo);
- c.mAsyncChannel.sendMessage(REMOVE_LOCAL_SERVICE, 0, c.putListener(listener), servInfo);
- }
-
- /**
- * Clear all registered local services of service discovery.
- *
- * <p> The function call immediately returns after sending a request to clear all
- * local services to the framework. The application is notified of a success or failure to
- * add service through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callbacks on success or failure. Can be null.
- */
- public void clearLocalServices(Channel c, ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(CLEAR_LOCAL_SERVICES, 0, c.putListener(listener));
- }
-
- /**
- * Register a callback to be invoked on receiving service discovery response.
- * Used only for vendor specific protocol right now. For Bonjour or Upnp, use
- * {@link #setDnsSdResponseListeners} or {@link #setUpnpServiceResponseListener}
- * respectively.
- *
- * <p> see {@link #discoverServices} for the detail.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callbacks on receiving service discovery response.
- */
- public void setServiceResponseListener(Channel c,
- ServiceResponseListener listener) {
- checkChannel(c);
- c.mServRspListener = listener;
- }
-
- /**
- * Register a callback to be invoked on receiving Bonjour service discovery
- * response.
- *
- * <p> see {@link #discoverServices} for the detail.
- *
- * @param c
- * @param servListener is for listening to a Bonjour service response
- * @param txtListener is for listening to a Bonjour TXT record response
- */
- public void setDnsSdResponseListeners(Channel c,
- DnsSdServiceResponseListener servListener, DnsSdTxtRecordListener txtListener) {
- checkChannel(c);
- c.mDnsSdServRspListener = servListener;
- c.mDnsSdTxtListener = txtListener;
- }
-
- /**
- * Register a callback to be invoked on receiving upnp service discovery
- * response.
- *
- * <p> see {@link #discoverServices} for the detail.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callbacks on receiving service discovery response.
- */
- public void setUpnpServiceResponseListener(Channel c,
- UpnpServiceResponseListener listener) {
- checkChannel(c);
- c.mUpnpServRspListener = listener;
- }
-
- /**
- * Initiate service discovery. A discovery process involves scanning for
- * requested services for the purpose of establishing a connection to a peer
- * that supports an available service.
- *
- * <p> The function call immediately returns after sending a request to start service
- * discovery to the framework. The application is notified of a success or failure to initiate
- * discovery through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * <p> The services to be discovered are specified with calls to {@link #addServiceRequest}.
- *
- * <p>The application is notified of the response against the service discovery request
- * through listener callbacks registered by {@link #setServiceResponseListener} or
- * {@link #setDnsSdResponseListeners}, or {@link #setUpnpServiceResponseListener}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callbacks on success or failure. Can be null.
- */
- @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
- public void discoverServices(Channel c, ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(DISCOVER_SERVICES, 0, c.putListener(listener));
- }
-
- /**
- * Add a service discovery request.
- *
- * <p> The function call immediately returns after sending a request to add service
- * discovery request to the framework. The application is notified of a success or failure to
- * add service through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * <p>After service discovery request is added, you can initiate service discovery by
- * {@link #discoverServices}.
- *
- * <p>The added service requests can be cleared with calls to
- * {@link #removeServiceRequest(Channel, WifiP2pServiceRequest, ActionListener)} or
- * {@link #clearServiceRequests(Channel, ActionListener)}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param req is the service discovery request.
- * @param listener for callbacks on success or failure. Can be null.
- */
- public void addServiceRequest(Channel c,
- WifiP2pServiceRequest req, ActionListener listener) {
- checkChannel(c);
- checkServiceRequest(req);
- c.mAsyncChannel.sendMessage(ADD_SERVICE_REQUEST, 0,
- c.putListener(listener), req);
- }
-
- /**
- * Remove a specified service discovery request added with {@link #addServiceRequest}
- *
- * <p> The function call immediately returns after sending a request to remove service
- * discovery request to the framework. The application is notified of a success or failure to
- * add service through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param req is the service discovery request.
- * @param listener for callbacks on success or failure. Can be null.
- */
- public void removeServiceRequest(Channel c, WifiP2pServiceRequest req,
- ActionListener listener) {
- checkChannel(c);
- checkServiceRequest(req);
- c.mAsyncChannel.sendMessage(REMOVE_SERVICE_REQUEST, 0,
- c.putListener(listener), req);
- }
-
- /**
- * Clear all registered service discovery requests.
- *
- * <p> The function call immediately returns after sending a request to clear all
- * service discovery requests to the framework. The application is notified of a success
- * or failure to add service through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callbacks on success or failure. Can be null.
- */
- public void clearServiceRequests(Channel c, ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(CLEAR_SERVICE_REQUESTS,
- 0, c.putListener(listener));
- }
-
- /**
- * Request the current list of peers.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callback when peer list is available. Can be null.
- */
- @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
- public void requestPeers(Channel c, PeerListListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(REQUEST_PEERS, 0, c.putListener(listener));
- }
-
- /**
- * Request device connection info.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callback when connection info is available. Can be null.
- */
- public void requestConnectionInfo(Channel c, ConnectionInfoListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(REQUEST_CONNECTION_INFO, 0, c.putListener(listener));
- }
-
- /**
- * Request p2p group info.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callback when group info is available. Can be null.
- */
- @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
- public void requestGroupInfo(Channel c, GroupInfoListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(REQUEST_GROUP_INFO, 0, c.putListener(listener));
- }
-
- /**
- * Set p2p device name.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callback when group info is available. Can be null.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_STACK,
- android.Manifest.permission.OVERRIDE_WIFI_CONFIG
- })
- public void setDeviceName(@NonNull Channel c, @NonNull String devName,
- @Nullable ActionListener listener) {
- checkChannel(c);
- WifiP2pDevice d = new WifiP2pDevice();
- d.deviceName = devName;
- c.mAsyncChannel.sendMessage(SET_DEVICE_NAME, 0, c.putListener(listener), d);
- }
-
- /**
- * Set Wifi Display information.
- *
- * @param c is the channel created at {@link #initialize}
- * @param wfdInfo the Wifi Display information to set
- * @param listener for callbacks on success or failure. Can be null.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY)
- public void setWfdInfo(@NonNull Channel c, @NonNull WifiP2pWfdInfo wfdInfo,
- @Nullable ActionListener listener) {
- setWFDInfo(c, wfdInfo, listener);
- }
-
- /** @hide */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- @RequiresPermission(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY)
- public void setWFDInfo(@NonNull Channel c, @NonNull WifiP2pWfdInfo wfdInfo,
- @Nullable ActionListener listener) {
- checkChannel(c);
- try {
- mService.checkConfigureWifiDisplayPermission();
- } catch (RemoteException e) {
- e.rethrowFromSystemServer();
- }
- c.mAsyncChannel.sendMessage(SET_WFD_INFO, 0, c.putListener(listener), wfdInfo);
- }
-
- /** @hide */
- public void setWFDR2Info(
- @NonNull Channel c, @NonNull WifiP2pWfdInfo wfdInfo,
- @Nullable ActionListener listener) {
- checkChannel(c);
- try {
- mService.checkConfigureWifiDisplayPermission();
- } catch (RemoteException e) {
- e.rethrowFromSystemServer();
- }
- c.mAsyncChannel.sendMessage(SET_WFDR2_INFO, 0, c.putListener(listener), wfdInfo);
- }
- /**
- * Delete a stored persistent group from the system settings.
- *
- * <p> The function call immediately returns after sending a persistent group removal request
- * to the framework. The application is notified of a success or failure to initiate
- * group removal through listener callbacks {@link ActionListener#onSuccess} or
- * {@link ActionListener#onFailure}.
- *
- * <p>The persistent p2p group list stored in the system can be obtained by
- * {@link #requestPersistentGroupInfo(Channel, PersistentGroupInfoListener)} and
- * a network id can be obtained by {@link WifiP2pGroup#getNetworkId()}.
- *
- * @param c is the channel created at {@link #initialize}
- * @param netId the network id of the p2p group.
- * @param listener for callbacks on success or failure. Can be null.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_STACK,
- android.Manifest.permission.OVERRIDE_WIFI_CONFIG
- })
- public void deletePersistentGroup(@NonNull Channel c, int netId,
- @Nullable ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(DELETE_PERSISTENT_GROUP, netId, c.putListener(listener));
- }
-
- /**
- * Request a list of all the persistent p2p groups stored in system.
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callback when persistent group info list is available. Can be null.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(anyOf = {
- android.Manifest.permission.NETWORK_SETTINGS,
- android.Manifest.permission.NETWORK_STACK,
- android.Manifest.permission.READ_WIFI_CREDENTIAL
- })
- public void requestPersistentGroupInfo(@NonNull Channel c,
- @Nullable PersistentGroupInfoListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(REQUEST_PERSISTENT_GROUP_INFO, 0, c.putListener(listener));
- }
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = {"MIRACAST_"}, value = {
- MIRACAST_DISABLED,
- MIRACAST_SOURCE,
- MIRACAST_SINK})
- public @interface MiracastMode {}
-
- /**
- * Miracast is disabled.
- * @hide
- */
- @SystemApi
- public static final int MIRACAST_DISABLED = 0;
- /**
- * Device acts as a Miracast source.
- * @hide
- */
- @SystemApi
- public static final int MIRACAST_SOURCE = 1;
- /**
- * Device acts as a Miracast sink.
- * @hide
- */
- @SystemApi
- public static final int MIRACAST_SINK = 2;
-
- /**
- * This is used to provide information to drivers to optimize performance depending
- * on the current mode of operation.
- * {@link #MIRACAST_DISABLED} - disabled
- * {@link #MIRACAST_SOURCE} - source operation
- * {@link #MIRACAST_SINK} - sink operation
- *
- * As an example, the driver could reduce the channel dwell time during scanning
- * when acting as a source or sink to minimize impact on Miracast.
- *
- * @param mode mode of operation. One of {@link #MIRACAST_DISABLED}, {@link #MIRACAST_SOURCE},
- * or {@link #MIRACAST_SINK}
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.CONFIGURE_WIFI_DISPLAY)
- public void setMiracastMode(@MiracastMode int mode) {
- try {
- mService.setMiracastMode(mode);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- private Messenger getMessenger(@NonNull Binder binder, @Nullable String packageName) {
- try {
- return mService.getMessenger(binder, packageName);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get a reference to WifiP2pService handler. This is used to establish
- * an AsyncChannel communication with WifiService
- *
- * @param binder A binder for the service to associate with this client.
- *
- * @return Messenger pointing to the WifiP2pService handler
- * @hide
- */
- public Messenger getMessenger(Binder binder) {
- // No way to determine package name in this case.
- return getMessenger(binder, null);
- }
-
- /**
- * Get a reference to P2pStateMachine handler. This is used to establish
- * a priveleged AsyncChannel communication with WifiP2pService.
- *
- * @return Messenger pointing to the WifiP2pService handler
- * @hide
- */
- public Messenger getP2pStateMachineMessenger() {
- try {
- return mService.getP2pStateMachineMessenger();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Get a handover request message for use in WFA NFC Handover transfer.
- * @hide
- */
- public void getNfcHandoverRequest(Channel c, HandoverMessageListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(GET_HANDOVER_REQUEST, 0, c.putListener(listener));
- }
-
-
- /**
- * Get a handover select message for use in WFA NFC Handover transfer.
- * @hide
- */
- public void getNfcHandoverSelect(Channel c, HandoverMessageListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(GET_HANDOVER_SELECT, 0, c.putListener(listener));
- }
-
- /**
- * @hide
- */
- public void initiatorReportNfcHandover(Channel c, String handoverSelect,
- ActionListener listener) {
- checkChannel(c);
- Bundle bundle = new Bundle();
- bundle.putString(EXTRA_HANDOVER_MESSAGE, handoverSelect);
- c.mAsyncChannel.sendMessage(INITIATOR_REPORT_NFC_HANDOVER, 0,
- c.putListener(listener), bundle);
- }
-
-
- /**
- * @hide
- */
- public void responderReportNfcHandover(Channel c, String handoverRequest,
- ActionListener listener) {
- checkChannel(c);
- Bundle bundle = new Bundle();
- bundle.putString(EXTRA_HANDOVER_MESSAGE, handoverRequest);
- c.mAsyncChannel.sendMessage(RESPONDER_REPORT_NFC_HANDOVER, 0,
- c.putListener(listener), bundle);
- }
-
- /**
- * Removes all saved p2p groups.
- *
- * @param c is the channel created at {@link #initialize}.
- * @param listener for callback on success or failure. Can be null.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public void factoryReset(@NonNull Channel c, @Nullable ActionListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(FACTORY_RESET, 0, c.putListener(listener));
- }
-
- /**
- * Request saved WifiP2pConfig which used for an ongoing peer connection
- *
- * @param c is the channel created at {@link #initialize}
- * @param listener for callback when ongoing peer config updated. Can't be null.
- *
- * @hide
- */
- @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
- public void requestOngoingPeerConfig(@NonNull Channel c,
- @NonNull OngoingPeerInfoListener listener) {
- checkChannel(c);
- c.mAsyncChannel.sendMessage(REQUEST_ONGOING_PEER_CONFIG,
- Binder.getCallingUid(), c.putListener(listener));
- }
-
- /**
- * Set saved WifiP2pConfig which used for an ongoing peer connection
- *
- * @param c is the channel created at {@link #initialize}
- * @param config used for change an ongoing peer connection
- * @param listener for callback when ongoing peer config updated. Can be null.
- *
- * @hide
- */
- @RequiresPermission(android.Manifest.permission.NETWORK_STACK)
- public void setOngoingPeerConfig(@NonNull Channel c, @NonNull WifiP2pConfig config,
- @Nullable ActionListener listener) {
- checkChannel(c);
- checkP2pConfig(config);
- c.mAsyncChannel.sendMessage(SET_ONGOING_PEER_CONFIG, 0,
- c.putListener(listener), config);
- }
-
- /**
- * Request p2p enabled state.
- *
- * <p> This state indicates whether Wi-Fi p2p is enabled or disabled.
- * The valid value is one of {@link #WIFI_P2P_STATE_DISABLED} or
- * {@link #WIFI_P2P_STATE_ENABLED}. The state is returned using the
- * {@link P2pStateListener} listener.
- *
- * <p> This state is also included in the {@link #WIFI_P2P_STATE_CHANGED_ACTION}
- * broadcast event with extra {@link #EXTRA_WIFI_STATE}.
- *
- * @param c is the channel created at {@link #initialize}.
- * @param listener for callback when p2p state is available..
- */
- public void requestP2pState(@NonNull Channel c,
- @NonNull P2pStateListener listener) {
- checkChannel(c);
- if (listener == null) throw new IllegalArgumentException("This listener cannot be null.");
- c.mAsyncChannel.sendMessage(REQUEST_P2P_STATE, 0, c.putListener(listener));
- }
-
- /**
- * Request p2p discovery state.
- *
- * <p> This state indicates whether p2p discovery has started or stopped.
- * The valid value is one of {@link #WIFI_P2P_DISCOVERY_STARTED} or
- * {@link #WIFI_P2P_DISCOVERY_STOPPED}. The state is returned using the
- * {@link DiscoveryStateListener} listener.
- *
- * <p> This state is also included in the {@link #WIFI_P2P_DISCOVERY_CHANGED_ACTION}
- * broadcast event with extra {@link #EXTRA_DISCOVERY_STATE}.
- *
- * @param c is the channel created at {@link #initialize}.
- * @param listener for callback when discovery state is available..
- */
- public void requestDiscoveryState(@NonNull Channel c,
- @NonNull DiscoveryStateListener listener) {
- checkChannel(c);
- if (listener == null) throw new IllegalArgumentException("This listener cannot be null.");
- c.mAsyncChannel.sendMessage(REQUEST_DISCOVERY_STATE, 0, c.putListener(listener));
- }
-
- /**
- * Request network info.
- *
- * <p> This method provides the network info in the form of a {@link android.net.NetworkInfo}.
- * {@link android.net.NetworkInfo#isAvailable()} indicates the p2p availability and
- * {@link android.net.NetworkInfo#getDetailedState()} reports the current fine-grained state
- * of the network. This {@link android.net.NetworkInfo} is returned using the
- * {@link NetworkInfoListener} listener.
- *
- * <p> This information is also included in the {@link #WIFI_P2P_CONNECTION_CHANGED_ACTION}
- * broadcast event with extra {@link #EXTRA_NETWORK_INFO}.
- *
- * @param c is the channel created at {@link #initialize}.
- * @param listener for callback when network info is available..
- */
- public void requestNetworkInfo(@NonNull Channel c,
- @NonNull NetworkInfoListener listener) {
- checkChannel(c);
- if (listener == null) throw new IllegalArgumentException("This listener cannot be null.");
- c.mAsyncChannel.sendMessage(REQUEST_NETWORK_INFO, 0, c.putListener(listener));
- }
-
- /**
- * Request Device Info
- *
- * <p> This method provides the device info
- * in the form of a {@link android.net.wifi.p2p.WifiP2pDevice}.
- * Valid {@link android.net.wifi.p2p.WifiP2pDevice} is returned when p2p is enabled.
- * To get information notifications on P2P getting enabled refers
- * {@link #WIFI_P2P_STATE_ENABLED}.
- *
- * <p> This {@link android.net.wifi.p2p.WifiP2pDevice} is returned using the
- * {@link DeviceInfoListener} listener.
- *
- * <p> {@link android.net.wifi.p2p.WifiP2pDevice#deviceAddress} is only available if the caller
- * holds the {@code android.Manifest.permission#LOCAL_MAC_ADDRESS} permission, and holds the
- * anonymized MAC address (02:00:00:00:00:00) otherwise.
- *
- * <p> This information is also included in the {@link #WIFI_P2P_THIS_DEVICE_CHANGED_ACTION}
- * broadcast event with extra {@link #EXTRA_WIFI_P2P_DEVICE}.
- *
- * @param c is the channel created at {@link #initialize(Context, Looper, ChannelListener)}.
- * @param listener for callback when network info is available.
- */
- @RequiresPermission(android.Manifest.permission.ACCESS_FINE_LOCATION)
- public void requestDeviceInfo(@NonNull Channel c, @NonNull DeviceInfoListener listener) {
- checkChannel(c);
- if (listener == null) throw new IllegalArgumentException("This listener cannot be null.");
- c.mAsyncChannel.sendMessage(REQUEST_DEVICE_INFO, 0, c.putListener(listener));
- }
-}
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pProvDiscEvent.java b/wifi/java/android/net/wifi/p2p/WifiP2pProvDiscEvent.java
deleted file mode 100644
index d0fe92d5249d..000000000000
--- a/wifi/java/android/net/wifi/p2p/WifiP2pProvDiscEvent.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2011 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.p2p;
-
-import android.compat.annotation.UnsupportedAppUsage;
-
-/**
- * A class representing a Wi-Fi p2p provisional discovery request/response
- * See {@link #WifiP2pProvDiscEvent} for supported types
- *
- * @hide
- */
-public class WifiP2pProvDiscEvent {
-
- private static final String TAG = "WifiP2pProvDiscEvent";
-
- public static final int PBC_REQ = 1;
- public static final int PBC_RSP = 2;
- public static final int ENTER_PIN = 3;
- public static final int SHOW_PIN = 4;
-
- /* One of PBC_REQ, PBC_RSP, ENTER_PIN or SHOW_PIN */
- @UnsupportedAppUsage
- public int event;
-
- @UnsupportedAppUsage
- public WifiP2pDevice device;
-
- /* Valid when event = SHOW_PIN */
- @UnsupportedAppUsage
- public String pin;
-
- @UnsupportedAppUsage
- public WifiP2pProvDiscEvent() {
- device = new WifiP2pDevice();
- }
-
- /**
- * @param string formats supported include
- *
- * P2P-PROV-DISC-PBC-REQ 42:fc:89:e1:e2:27
- * P2P-PROV-DISC-PBC-RESP 02:12:47:f2:5a:36
- * P2P-PROV-DISC-ENTER-PIN 42:fc:89:e1:e2:27
- * P2P-PROV-DISC-SHOW-PIN 42:fc:89:e1:e2:27 44490607
- *
- * Note: The events formats can be looked up in the wpa_supplicant code
- * @hide
- */
- public WifiP2pProvDiscEvent(String string) throws IllegalArgumentException {
- String[] tokens = string.split(" ");
-
- if (tokens.length < 2) {
- throw new IllegalArgumentException("Malformed event " + string);
- }
-
- if (tokens[0].endsWith("PBC-REQ")) event = PBC_REQ;
- else if (tokens[0].endsWith("PBC-RESP")) event = PBC_RSP;
- else if (tokens[0].endsWith("ENTER-PIN")) event = ENTER_PIN;
- else if (tokens[0].endsWith("SHOW-PIN")) event = SHOW_PIN;
- else throw new IllegalArgumentException("Malformed event " + string);
-
-
- device = new WifiP2pDevice();
- device.deviceAddress = tokens[1];
-
- if (event == SHOW_PIN) {
- pin = tokens[2];
- }
- }
-
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
- sbuf.append(device);
- sbuf.append("\n event: ").append(event);
- sbuf.append("\n pin: ").append(pin);
- return sbuf.toString();
- }
-}
diff --git a/wifi/java/android/net/wifi/p2p/WifiP2pWfdInfo.java b/wifi/java/android/net/wifi/p2p/WifiP2pWfdInfo.java
deleted file mode 100644
index a7fe874a0504..000000000000
--- a/wifi/java/android/net/wifi/p2p/WifiP2pWfdInfo.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * Copyright (C) 2012 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.p2p;
-
-import android.annotation.IntDef;
-import android.annotation.IntRange;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Locale;
-
-/**
- * A class representing Wifi Display information for a device.
- *
- * See Wifi Display technical specification v1.0.0, section 5.1.2.
- */
-public final class WifiP2pWfdInfo implements Parcelable {
-
- private boolean mEnabled;
-
- /** Device information bitmap */
- private int mDeviceInfo;
-
- private int mR2DeviceInfo;
-
- /** @hide */
- @Retention(RetentionPolicy.SOURCE)
- @IntDef(prefix = { "DEVICE_TYPE_" }, value = {
- DEVICE_TYPE_WFD_SOURCE,
- DEVICE_TYPE_PRIMARY_SINK,
- DEVICE_TYPE_SECONDARY_SINK,
- DEVICE_TYPE_SOURCE_OR_PRIMARY_SINK})
- public @interface DeviceType {}
-
- /** The device is a Wifi Display Source. */
- public static final int DEVICE_TYPE_WFD_SOURCE = 0;
- /** The device is a primary sink. */
- public static final int DEVICE_TYPE_PRIMARY_SINK = 1;
- /** The device is a secondary sink. */
- public static final int DEVICE_TYPE_SECONDARY_SINK = 2;
- /** The device is dual-role capable i.e. either a WFD source or a primary sink. */
- public static final int DEVICE_TYPE_SOURCE_OR_PRIMARY_SINK = 3;
-
- /**
- * {@link #mDeviceInfo} & {@link #DEVICE_TYPE} is one of {@link #DEVICE_TYPE_WFD_SOURCE},
- * {@link #DEVICE_TYPE_PRIMARY_SINK}, {@link #DEVICE_TYPE_SECONDARY_SINK} or
- * {@link #DEVICE_TYPE_SOURCE_OR_PRIMARY_SINK}.
- *
- * The bit definition is listed in 5.1.2 WFD Device Information Subelement in
- * Wi-Fi Display Technical Specification.
- */
- private static final int DEVICE_TYPE = 1 << 1 | 1 << 0;
- private static final int COUPLED_SINK_SUPPORT_AT_SOURCE = 1 << 2;
- private static final int COUPLED_SINK_SUPPORT_AT_SINK = 1 << 3;
- private static final int SESSION_AVAILABLE_BIT1 = 1 << 4;
- private static final int SESSION_AVAILABLE_BIT2 = 1 << 5;
- private static final int SESSION_AVAILABLE =
- SESSION_AVAILABLE_BIT2 | SESSION_AVAILABLE_BIT1;
- /* The support of Content Protection using the HDCP system 2.0/2.1. */
- private static final int CONTENT_PROTECTION_SUPPORT = 1 << 8;
-
- private int mCtrlPort;
-
- private int mMaxThroughput;
-
- /** Default constructor. */
- public WifiP2pWfdInfo() {}
-
- /** @hide */
- @UnsupportedAppUsage
- public WifiP2pWfdInfo(int devInfo, int ctrlPort, int maxTput) {
- mEnabled = true;
- mDeviceInfo = devInfo;
- mCtrlPort = ctrlPort;
- mMaxThroughput = maxTput;
- mR2DeviceInfo = -1;
- }
-
- /** Returns true is Wifi Display is enabled, false otherwise. */
- public boolean isEnabled() {
- return mEnabled;
- }
-
- /** @hide */
- public boolean isWfdR2Supported() {
- return (mR2DeviceInfo<0?false:true);
- }
-
- /**
- * Sets whether Wifi Display should be enabled.
- *
- * @param enabled true to enable Wifi Display, false to disable
- */
- public void setEnabled(boolean enabled) {
- mEnabled = enabled;
- }
-
- /** @hide */
- public void setWfdR2Device(int r2DeviceInfo) {
- mR2DeviceInfo = r2DeviceInfo;
- }
-
- /**
- * Get the type of the device.
- * One of {@link #DEVICE_TYPE_WFD_SOURCE}, {@link #DEVICE_TYPE_PRIMARY_SINK},
- * {@link #DEVICE_TYPE_SECONDARY_SINK}, {@link #DEVICE_TYPE_SOURCE_OR_PRIMARY_SINK}
- */
- @DeviceType
- public int getDeviceType() {
- return mDeviceInfo & DEVICE_TYPE;
- }
-
- /**
- * Sets the type of the device.
- *
- * @param deviceType One of {@link #DEVICE_TYPE_WFD_SOURCE}, {@link #DEVICE_TYPE_PRIMARY_SINK},
- * {@link #DEVICE_TYPE_SECONDARY_SINK}, {@link #DEVICE_TYPE_SOURCE_OR_PRIMARY_SINK}
- * @return true if the device type was successfully set, false otherwise
- */
- public boolean setDeviceType(@DeviceType int deviceType) {
- if (DEVICE_TYPE_WFD_SOURCE <= deviceType
- && deviceType <= DEVICE_TYPE_SOURCE_OR_PRIMARY_SINK) {
- mDeviceInfo &= ~DEVICE_TYPE;
- mDeviceInfo |= deviceType;
- return true;
- }
- return false;
- }
-
- /** Returns true if a session is available, false otherwise. */
- public boolean isSessionAvailable() {
- return (mDeviceInfo & SESSION_AVAILABLE) != 0;
- }
-
- /**
- * Sets whether a session is available.
- *
- * @param enabled true to indicate that a session is available, false otherwise.
- */
- public void setSessionAvailable(boolean enabled) {
- if (enabled) {
- mDeviceInfo |= SESSION_AVAILABLE_BIT1;
- mDeviceInfo &= ~SESSION_AVAILABLE_BIT2;
- } else {
- mDeviceInfo &= ~SESSION_AVAILABLE;
- }
- }
-
- /**
- * @return true if Content Protection using the HDCP system 2.0/2.1 is supported.
- */
- public boolean isContentProtectionSupported() {
- return (mDeviceInfo & CONTENT_PROTECTION_SUPPORT) != 0;
- }
-
- /**
- * Sets whether Content Protection using the HDCP system 2.0/2.1 is supported.
- *
- * @param enabled true to indicate that Content Protection is supported, false otherwise.
- */
- public void setContentProtectionSupported(boolean enabled) {
- if (enabled) {
- mDeviceInfo |= CONTENT_PROTECTION_SUPPORT;
- } else {
- mDeviceInfo &= ~CONTENT_PROTECTION_SUPPORT;
- }
- }
-
- /** Returns the TCP port at which the WFD Device listens for RTSP messages. */
- public int getControlPort() {
- return mCtrlPort;
- }
-
- /** Sets the TCP port at which the WFD Device listens for RTSP messages. */
- public void setControlPort(@IntRange(from = 0) int port) {
- mCtrlPort = port;
- }
-
- /** Sets the maximum average throughput capability of the WFD Device, in megabits/second. */
- public void setMaxThroughput(@IntRange(from = 0) int maxThroughput) {
- mMaxThroughput = maxThroughput;
- }
-
- /** Returns the maximum average throughput capability of the WFD Device, in megabits/second. */
- public int getMaxThroughput() {
- return mMaxThroughput;
- }
-
- /** @hide */
- public String getDeviceInfoHex() {
- return String.format(
- Locale.US, "%04x%04x%04x", mDeviceInfo, mCtrlPort, mMaxThroughput);
- }
-
- /** @hide */
- public String getR2DeviceInfoHex() {
- return String.format(
- Locale.US, "%04x%04x", 2, mR2DeviceInfo);
- }
-
- @Override
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
- sbuf.append("WFD enabled: ").append(mEnabled);
- sbuf.append("WFD DeviceInfo: ").append(mDeviceInfo);
- sbuf.append("\n WFD CtrlPort: ").append(mCtrlPort);
- sbuf.append("\n WFD MaxThroughput: ").append(mMaxThroughput);
- sbuf.append("\n WFD R2 DeviceInfo: ").append(mR2DeviceInfo);
- return sbuf.toString();
- }
-
- /** Implement the Parcelable interface */
- public int describeContents() {
- return 0;
- }
-
- /** Copy constructor. */
- public WifiP2pWfdInfo(@Nullable WifiP2pWfdInfo source) {
- if (source != null) {
- mEnabled = source.mEnabled;
- mDeviceInfo = source.mDeviceInfo;
- mCtrlPort = source.mCtrlPort;
- mMaxThroughput = source.mMaxThroughput;
- mR2DeviceInfo = source.mR2DeviceInfo;
- }
- }
-
- /** Implement the Parcelable interface */
- @Override
- public void writeToParcel(@NonNull Parcel dest, int flags) {
- dest.writeInt(mEnabled ? 1 : 0);
- dest.writeInt(mDeviceInfo);
- dest.writeInt(mCtrlPort);
- dest.writeInt(mMaxThroughput);
- dest.writeInt(mR2DeviceInfo);
- }
-
- private void readFromParcel(Parcel in) {
- mEnabled = (in.readInt() == 1);
- mDeviceInfo = in.readInt();
- mCtrlPort = in.readInt();
- mMaxThroughput = in.readInt();
- mR2DeviceInfo = in.readInt();
- }
-
- /** Implement the Parcelable interface */
- public static final @NonNull Creator<WifiP2pWfdInfo> CREATOR =
- new Creator<WifiP2pWfdInfo>() {
- public WifiP2pWfdInfo createFromParcel(Parcel in) {
- WifiP2pWfdInfo device = new WifiP2pWfdInfo();
- device.readFromParcel(in);
- return device;
- }
-
- public WifiP2pWfdInfo[] newArray(int size) {
- return new WifiP2pWfdInfo[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceInfo.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceInfo.java
deleted file mode 100644
index e2f40cfa058c..000000000000
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceInfo.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * Copyright (C) 2012 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.p2p.nsd;
-
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Build;
-import android.text.TextUtils;
-
-import com.android.net.module.util.DnsSdTxtRecord;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * A class for storing Bonjour service information that is advertised
- * over a Wi-Fi peer-to-peer setup.
- *
- * {@see android.net.wifi.p2p.WifiP2pManager#addLocalService}
- * {@see android.net.wifi.p2p.WifiP2pManager#removeLocalService}
- * {@see WifiP2pServiceInfo}
- * {@see WifiP2pUpnpServiceInfo}
- */
-public class WifiP2pDnsSdServiceInfo extends WifiP2pServiceInfo {
-
- /**
- * Bonjour version 1.
- * @hide
- */
- public static final int VERSION_1 = 0x01;
-
- /**
- * Pointer record.
- * @hide
- */
- public static final int DNS_TYPE_PTR = 12;
-
- /**
- * Text record.
- * @hide
- */
- public static final int DNS_TYPE_TXT = 16;
-
- /**
- * virtual memory packet.
- * see E.3 of the Wi-Fi Direct technical specification for the detail.<br>
- * Key: domain name Value: pointer address.<br>
- */
- private final static Map<String, String> sVmPacket;
-
- static {
- sVmPacket = new HashMap<String, String>();
- sVmPacket.put("_tcp.local.", "c00c");
- sVmPacket.put("local.", "c011");
- sVmPacket.put("_udp.local.", "c01c");
- }
-
- /**
- * This constructor is only used in newInstance().
- *
- * @param queryList
- */
- private WifiP2pDnsSdServiceInfo(List<String> queryList) {
- super(queryList);
- }
-
- /**
- * Create a Bonjour service information object.
- *
- * @param instanceName instance name.<br>
- * e.g) "MyPrinter"
- * @param serviceType service type.<br>
- * e.g) "_ipp._tcp"
- * @param txtMap TXT record with key/value pair in a map confirming to format defined at
- * http://files.dns-sd.org/draft-cheshire-dnsext-dns-sd.txt
- * @return Bonjour service information object
- */
- public static WifiP2pDnsSdServiceInfo newInstance(String instanceName,
- String serviceType, Map<String, String> txtMap) {
- if (TextUtils.isEmpty(instanceName) || TextUtils.isEmpty(serviceType)) {
- throw new IllegalArgumentException(
- "instance name or service type cannot be empty");
- }
-
- DnsSdTxtRecord txtRecord = new DnsSdTxtRecord();
- if (txtMap != null) {
- for (String key : txtMap.keySet()) {
- txtRecord.set(key, txtMap.get(key));
- }
- }
-
- ArrayList<String> queries = new ArrayList<String>();
- queries.add(createPtrServiceQuery(instanceName, serviceType));
- queries.add(createTxtServiceQuery(instanceName, serviceType, txtRecord));
-
- return new WifiP2pDnsSdServiceInfo(queries);
- }
-
- /**
- * Create wpa_supplicant service query for PTR record.
- *
- * @param instanceName instance name.<br>
- * e.g) "MyPrinter"
- * @param serviceType service type.<br>
- * e.g) "_ipp._tcp"
- * @return wpa_supplicant service query.
- */
- private static String createPtrServiceQuery(String instanceName,
- String serviceType) {
-
- StringBuffer sb = new StringBuffer();
- sb.append("bonjour ");
- sb.append(createRequest(serviceType + ".local.", DNS_TYPE_PTR, VERSION_1));
- sb.append(" ");
-
- byte[] data = instanceName.getBytes();
- sb.append(String.format(Locale.US, "%02x", data.length));
- sb.append(WifiP2pServiceInfo.bin2HexStr(data));
- // This is the start point of this response.
- // Therefore, it indicates the request domain name.
- sb.append("c027");
- return sb.toString();
- }
-
- /**
- * Create wpa_supplicant service query for TXT record.
- *
- * @param instanceName instance name.<br>
- * e.g) "MyPrinter"
- * @param serviceType service type.<br>
- * e.g) "_ipp._tcp"
- * @param txtRecord TXT record.<br>
- * @return wpa_supplicant service query.
- */
- private static String createTxtServiceQuery(String instanceName,
- String serviceType,
- DnsSdTxtRecord txtRecord) {
-
-
- StringBuffer sb = new StringBuffer();
- sb.append("bonjour ");
-
- sb.append(createRequest((instanceName + "." + serviceType + ".local."),
- DNS_TYPE_TXT, VERSION_1));
- sb.append(" ");
- byte[] rawData = txtRecord.getRawData();
- if (rawData.length == 0) {
- sb.append("00");
- } else {
- sb.append(bin2HexStr(rawData));
- }
- return sb.toString();
- }
-
- /**
- * Create bonjour service discovery request.
- *
- * @param dnsName dns name
- * @param dnsType dns type
- * @param version version number
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- static String createRequest(String dnsName, int dnsType, int version) {
- StringBuffer sb = new StringBuffer();
-
- /*
- * The request format is as follows.
- * ________________________________________________
- * | Encoded and Compressed dns name (variable) |
- * ________________________________________________
- * | Type (2) | Version (1) |
- */
- if (dnsType == WifiP2pDnsSdServiceInfo.DNS_TYPE_TXT) {
- dnsName = dnsName.toLowerCase(Locale.ROOT); // TODO: is this right?
- }
- sb.append(compressDnsName(dnsName));
- sb.append(String.format(Locale.US, "%04x", dnsType));
- sb.append(String.format(Locale.US, "%02x", version));
-
- return sb.toString();
- }
-
- /**
- * Compress DNS data.
- *
- * see E.3 of the Wi-Fi Direct technical specification for the detail.
- *
- * @param dnsName dns name
- * @return compressed dns name
- */
- private static String compressDnsName(String dnsName) {
- StringBuffer sb = new StringBuffer();
-
- // The domain name is replaced with a pointer to a prior
- // occurrence of the same name in virtual memory packet.
- while (true) {
- String data = sVmPacket.get(dnsName);
- if (data != null) {
- sb.append(data);
- break;
- }
- int i = dnsName.indexOf('.');
- if (i == -1) {
- if (dnsName.length() > 0) {
- sb.append(String.format(Locale.US, "%02x", dnsName.length()));
- sb.append(WifiP2pServiceInfo.bin2HexStr(dnsName.getBytes()));
- }
- // for a sequence of labels ending in a zero octet
- sb.append("00");
- break;
- }
-
- String name = dnsName.substring(0, i);
- dnsName = dnsName.substring(i + 1);
- sb.append(String.format(Locale.US, "%02x", name.length()));
- sb.append(WifiP2pServiceInfo.bin2HexStr(name.getBytes()));
- }
- return sb.toString();
- }
-}
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceRequest.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceRequest.java
deleted file mode 100644
index d5415e055b21..000000000000
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceRequest.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2012 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.p2p.nsd;
-
-import android.net.wifi.p2p.WifiP2pManager;
-
-/**
- * A class for creating a Bonjour service discovery request for use with
- * {@link WifiP2pManager#addServiceRequest} and {@link WifiP2pManager#removeServiceRequest}
- *
- * {@see WifiP2pManager}
- * {@see WifiP2pServiceRequest}
- * {@see WifiP2pUpnpServiceRequest}
- */
-public class WifiP2pDnsSdServiceRequest extends WifiP2pServiceRequest {
-
- /**
- * This constructor is only used in newInstance().
- *
- * @param query The part of service specific query.
- * @hide
- */
- private WifiP2pDnsSdServiceRequest(String query) {
- super(WifiP2pServiceInfo.SERVICE_TYPE_BONJOUR, query);
- }
-
- /**
- * This constructor is only used in newInstance().
- * @hide
- */
- private WifiP2pDnsSdServiceRequest() {
- super(WifiP2pServiceInfo.SERVICE_TYPE_BONJOUR, null);
- }
-
- private WifiP2pDnsSdServiceRequest(String dnsQuery, int dnsType, int version) {
- super(WifiP2pServiceInfo.SERVICE_TYPE_BONJOUR, WifiP2pDnsSdServiceInfo.createRequest(
- dnsQuery,
- dnsType,
- version));
- }
-
- /**
- * Create a service discovery request to search all Bonjour services.
- *
- * @return service request for Bonjour.
- */
- public static WifiP2pDnsSdServiceRequest newInstance() {
- return new WifiP2pDnsSdServiceRequest();
- }
-
- /**
- * Create a service discovery to search for Bonjour services with the specified
- * service type.
- *
- * @param serviceType service type. Cannot be null <br>
- * "_afpovertcp._tcp."(Apple File Sharing over TCP)<br>
- * "_ipp._tcp" (IP Printing over TCP)<br>
- * "_http._tcp" (http service)
- * @return service request for DnsSd.
- */
- public static WifiP2pDnsSdServiceRequest newInstance(String serviceType) {
- if (serviceType == null) {
- throw new IllegalArgumentException("service type cannot be null");
- }
- return new WifiP2pDnsSdServiceRequest(serviceType + ".local.",
- WifiP2pDnsSdServiceInfo.DNS_TYPE_PTR,
- WifiP2pDnsSdServiceInfo.VERSION_1);
- }
-
- /**
- * Create a service discovery request to get the TXT data from the specified
- * Bonjour service.
- *
- * @param instanceName instance name. Cannot be null. <br>
- * "MyPrinter"
- * @param serviceType service type. Cannot be null. <br>
- * e.g) <br>
- * "_afpovertcp._tcp"(Apple File Sharing over TCP)<br>
- * "_ipp._tcp" (IP Printing over TCP)<br>
- * @return service request for Bonjour.
- */
- public static WifiP2pDnsSdServiceRequest newInstance(String instanceName,
- String serviceType) {
- if (instanceName == null || serviceType == null) {
- throw new IllegalArgumentException(
- "instance name or service type cannot be null");
- }
- String fullDomainName = instanceName + "." + serviceType + ".local.";
- return new WifiP2pDnsSdServiceRequest(fullDomainName,
- WifiP2pDnsSdServiceInfo.DNS_TYPE_TXT,
- WifiP2pDnsSdServiceInfo.VERSION_1);
- }
-}
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceResponse.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceResponse.java
deleted file mode 100644
index ed84a1a0803e..000000000000
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pDnsSdServiceResponse.java
+++ /dev/null
@@ -1,309 +0,0 @@
-/*
- * Copyright (C) 2012 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.p2p.nsd;
-
-import android.net.wifi.p2p.WifiP2pDevice;
-
-import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * A class for a response of bonjour service discovery.
- *
- * @hide
- */
-public class WifiP2pDnsSdServiceResponse extends WifiP2pServiceResponse {
-
- /**
- * DNS query name.
- * e.g)
- * for PTR
- * "_ipp._tcp.local."
- * for TXT
- * "MyPrinter._ipp._tcp.local."
- */
- private String mDnsQueryName;
-
- /**
- * Service instance name.
- * e.g) "MyPrinter"
- * This field is only used when the dns type equals to
- * {@link WifiP2pDnsSdServiceInfo#DNS_TYPE_PTR}.
- */
- private String mInstanceName;
-
- /**
- * DNS Type.
- * Should be {@link WifiP2pDnsSdServiceInfo#DNS_TYPE_PTR} or
- * {@link WifiP2pDnsSdServiceInfo#DNS_TYPE_TXT}.
- */
- private int mDnsType;
-
- /**
- * DnsSd version number.
- * Should be {@link WifiP2pDnsSdServiceInfo#VERSION_1}.
- */
- private int mVersion;
-
- /**
- * Txt record.
- * This field is only used when the dns type equals to
- * {@link WifiP2pDnsSdServiceInfo#DNS_TYPE_TXT}.
- */
- private final HashMap<String, String> mTxtRecord = new HashMap<String, String>();
-
- /**
- * Virtual memory packet.
- * see E.3 of the Wi-Fi Direct technical specification for the detail.<br>
- * The spec can be obtained from wi-fi.org
- * Key: pointer Value: domain name.<br>
- */
- private final static Map<Integer, String> sVmpack;
-
- static {
- sVmpack = new HashMap<Integer, String>();
- sVmpack.put(0x0c, "_tcp.local.");
- sVmpack.put(0x11, "local.");
- sVmpack.put(0x1c, "_udp.local.");
- }
-
- /**
- * Returns query DNS name.
- * @return DNS name.
- */
- public String getDnsQueryName() {
- return mDnsQueryName;
- }
-
- /**
- * Return query DNS type.
- * @return DNS type.
- */
- public int getDnsType() {
- return mDnsType;
- }
-
- /**
- * Return bonjour version number.
- * @return version number.
- */
- public int getVersion() {
- return mVersion;
- }
-
- /**
- * Return instance name.
- * @return
- */
- public String getInstanceName() {
- return mInstanceName;
- }
-
- /**
- * Return TXT record data.
- * @return TXT record data.
- */
- public Map<String, String> getTxtRecord() {
- return mTxtRecord;
- }
-
- @Override
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
- sbuf.append("serviceType:DnsSd(").append(mServiceType).append(")");
- sbuf.append(" status:").append(Status.toString(mStatus));
- sbuf.append(" srcAddr:").append(mDevice.deviceAddress);
- sbuf.append(" version:").append(String.format("%02x", mVersion));
- sbuf.append(" dnsName:").append(mDnsQueryName);
- sbuf.append(" TxtRecord:");
- for (String key : mTxtRecord.keySet()) {
- sbuf.append(" key:").append(key).append(" value:").append(mTxtRecord.get(key));
- }
- if (mInstanceName != null) {
- sbuf.append(" InsName:").append(mInstanceName);
- }
- return sbuf.toString();
- }
-
- /**
- * This is only used in framework.
- * @param status status code.
- * @param dev source device.
- * @param data RDATA.
- * @hide
- */
- protected WifiP2pDnsSdServiceResponse(int status,
- int tranId, WifiP2pDevice dev, byte[] data) {
- super(WifiP2pServiceInfo.SERVICE_TYPE_BONJOUR,
- status, tranId, dev, data);
- if (!parse()) {
- throw new IllegalArgumentException("Malformed bonjour service response");
- }
- }
-
- /**
- * Parse DnsSd service discovery response.
- *
- * @return {@code true} if the operation succeeded
- */
- private boolean parse() {
- /*
- * The data format from Wi-Fi Direct spec is as follows.
- * ________________________________________________
- * | encoded and compressed dns name (variable) |
- * ________________________________________________
- * | dnstype(2byte) | version(1byte) |
- * ________________________________________________
- * | RDATA (variable) |
- */
- if (mData == null) {
- // the empty is OK.
- return true;
- }
-
- DataInputStream dis = new DataInputStream(new ByteArrayInputStream(mData));
-
- mDnsQueryName = readDnsName(dis);
- if (mDnsQueryName == null) {
- return false;
- }
-
- try {
- mDnsType = dis.readUnsignedShort();
- mVersion = dis.readUnsignedByte();
- } catch (IOException e) {
- e.printStackTrace();
- return false;
- }
-
- if (mDnsType == WifiP2pDnsSdServiceInfo.DNS_TYPE_PTR) {
- String rData = readDnsName(dis);
- if (rData == null) {
- return false;
- }
- if (rData.length() <= mDnsQueryName.length()) {
- return false;
- }
-
- mInstanceName = rData.substring(0,
- rData.length() - mDnsQueryName.length() -1);
- } else if (mDnsType == WifiP2pDnsSdServiceInfo.DNS_TYPE_TXT) {
- return readTxtData(dis);
- } else {
- return false;
- }
-
- return true;
- }
-
- /**
- * Read dns name.
- *
- * @param dis data input stream.
- * @return dns name
- */
- private String readDnsName(DataInputStream dis) {
- StringBuffer sb = new StringBuffer();
-
- // copy virtual memory packet.
- HashMap<Integer, String> vmpack = new HashMap<Integer, String>(sVmpack);
- if (mDnsQueryName != null) {
- vmpack.put(0x27, mDnsQueryName);
- }
- try {
- while (true) {
- int i = dis.readUnsignedByte();
- if (i == 0x00) {
- return sb.toString();
- } else if (i == 0xc0) {
- // refer to pointer.
- String ref = vmpack.get(dis.readUnsignedByte());
- if (ref == null) {
- //invalid.
- return null;
- }
- sb.append(ref);
- return sb.toString();
- } else {
- byte[] data = new byte[i];
- dis.readFully(data);
- sb.append(new String(data));
- sb.append(".");
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- /**
- * Read TXT record data.
- *
- * @param dis
- * @return true if TXT data is valid
- */
- private boolean readTxtData(DataInputStream dis) {
- try {
- while (dis.available() > 0) {
- int len = dis.readUnsignedByte();
- if (len == 0) {
- break;
- }
- byte[] data = new byte[len];
- dis.readFully(data);
- String[] keyVal = new String(data).split("=");
- if (keyVal.length != 2) {
- return false;
- }
- mTxtRecord.put(keyVal[0], keyVal[1]);
- }
- return true;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return false;
- }
-
- /**
- * Creates DnsSd service response.
- * This is only called from WifiP2pServiceResponse
- *
- * @param status status code.
- * @param dev source device.
- * @param data DnsSd response data.
- * @return DnsSd service response data.
- * @hide
- */
- static WifiP2pDnsSdServiceResponse newInstance(int status,
- int transId, WifiP2pDevice dev, byte[] data) {
- if (status != WifiP2pServiceResponse.Status.SUCCESS) {
- return new WifiP2pDnsSdServiceResponse(status,
- transId, dev, null);
- }
- try {
- return new WifiP2pDnsSdServiceResponse(status,
- transId, dev, data);
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- }
- return null;
- }
-}
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceInfo.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceInfo.java
deleted file mode 100644
index 5d018e75488e..000000000000
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceInfo.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (C) 2012 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.p2p.nsd;
-
-import android.compat.annotation.UnsupportedAppUsage;
-import android.os.Build;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A class for storing service information that is advertised
- * over a Wi-Fi peer-to-peer setup
- *
- * @see WifiP2pUpnpServiceInfo
- * @see WifiP2pDnsSdServiceInfo
- */
-public class WifiP2pServiceInfo implements Parcelable {
-
- /**
- * All service protocol types.
- */
- public static final int SERVICE_TYPE_ALL = 0;
-
- /**
- * DNS based service discovery protocol.
- */
- public static final int SERVICE_TYPE_BONJOUR = 1;
-
- /**
- * UPnP protocol.
- */
- public static final int SERVICE_TYPE_UPNP = 2;
-
- /**
- * WS-Discovery protocol
- * @hide
- */
- public static final int SERVICE_TYPE_WS_DISCOVERY = 3;
-
- /**
- * Vendor Specific protocol
- */
- public static final int SERVICE_TYPE_VENDOR_SPECIFIC = 255;
-
- /**
- * the list of query string for wpa_supplicant
- *
- * e.g)
- * # IP Printing over TCP (PTR) (RDATA=MyPrinter._ipp._tcp.local.)
- * {"bonjour", "045f697070c00c000c01", "094d795072696e746572c027"
- *
- * # IP Printing over TCP (TXT) (RDATA=txtvers=1,pdl=application/postscript)
- * {"bonjour", "096d797072696e746572045f697070c00c001001",
- * "09747874766572733d311a70646c3d6170706c69636174696f6e2f706f7374736372797074"}
- *
- * [UPnP]
- * # UPnP uuid
- * {"upnp", "10", "uuid:6859dede-8574-59ab-9332-123456789012"}
- *
- * # UPnP rootdevice
- * {"upnp", "10", "uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice"}
- *
- * # UPnP device
- * {"upnp", "10", "uuid:6859dede-8574-59ab-9332-123456789012::urn:schemas-upnp
- * -org:device:InternetGatewayDevice:1"}
- *
- * # UPnP service
- * {"upnp", "10", "uuid:6859dede-8574-59ab-9322-123456789012::urn:schemas-upnp
- * -org:service:ContentDirectory:2"}
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- private List<String> mQueryList;
-
- /**
- * This is only used in subclass.
- *
- * @param queryList query string for wpa_supplicant
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- protected WifiP2pServiceInfo(List<String> queryList) {
- if (queryList == null) {
- throw new IllegalArgumentException("query list cannot be null");
- }
- mQueryList = queryList;
- }
-
- /**
- * Return the list of the query string for wpa_supplicant.
- *
- * @return the list of the query string for wpa_supplicant.
- * @hide
- */
- public List<String> getSupplicantQueryList() {
- return mQueryList;
- }
-
- /**
- * Converts byte array to hex string.
- *
- * @param data
- * @return hex string.
- * @hide
- */
- static String bin2HexStr(byte[] data) {
- StringBuffer sb = new StringBuffer();
-
- for (byte b: data) {
- String s = null;
- try {
- s = Integer.toHexString(b & 0xff);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- //add 0 padding
- if (s.length() == 1) {
- sb.append('0');
- }
- sb.append(s);
- }
- return sb.toString();
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (!(o instanceof WifiP2pServiceInfo)) {
- return false;
- }
-
- WifiP2pServiceInfo servInfo = (WifiP2pServiceInfo)o;
- return mQueryList.equals(servInfo.mQueryList);
- }
-
- @Override
- public int hashCode() {
- int result = 17;
- result = 31 * result + (mQueryList == null ? 0 : mQueryList.hashCode());
- return result;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeStringList(mQueryList);
- }
-
- /** Implement the Parcelable interface {@hide} */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final @android.annotation.NonNull Creator<WifiP2pServiceInfo> CREATOR =
- new Creator<WifiP2pServiceInfo>() {
- public WifiP2pServiceInfo createFromParcel(Parcel in) {
-
- List<String> data = new ArrayList<String>();
- in.readStringList(data);
- return new WifiP2pServiceInfo(data);
- }
-
- public WifiP2pServiceInfo[] newArray(int size) {
- return new WifiP2pServiceInfo[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceRequest.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceRequest.java
deleted file mode 100644
index dea0477cf09b..000000000000
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceRequest.java
+++ /dev/null
@@ -1,283 +0,0 @@
-/*
- * Copyright (C) 2012 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.p2p.nsd;
-
-import android.compat.annotation.UnsupportedAppUsage;
-import android.net.wifi.p2p.WifiP2pManager;
-import android.os.Build;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.Locale;
-
-/**
- * A class for creating a service discovery request for use with
- * {@link WifiP2pManager#addServiceRequest} and {@link WifiP2pManager#removeServiceRequest}
- *
- * <p>This class is used to create service discovery request for custom
- * vendor specific service discovery protocol {@link WifiP2pServiceInfo#SERVICE_TYPE_VENDOR_SPECIFIC}
- * or to search all service protocols {@link WifiP2pServiceInfo#SERVICE_TYPE_ALL}.
- *
- * <p>For the purpose of creating a UPnP or Bonjour service request, use
- * {@link WifiP2pUpnpServiceRequest} or {@link WifiP2pDnsSdServiceRequest} respectively.
- *
- * {@see WifiP2pManager}
- * {@see WifiP2pUpnpServiceRequest}
- * {@see WifiP2pDnsSdServiceRequest}
- */
-public class WifiP2pServiceRequest implements Parcelable {
-
- /**
- * Service discovery protocol. It's defined in table63 in Wi-Fi Direct specification.
- */
- private int mProtocolType;
-
- /**
- * The length of the service request TLV.
- * The value is equal to 2 plus the number of octets in the
- * query data field.
- */
- private int mLength;
-
- /**
- * Service transaction ID.
- * This is a nonzero value used to match the service request/response TLVs.
- */
- private int mTransId;
-
- /**
- * The hex dump string of query data for the requested service information.
- *
- * e.g) DnsSd apple file sharing over tcp (dns name=_afpovertcp._tcp.local.)
- * 0b5f6166706f766572746370c00c000c01
- */
- private String mQuery;
-
- /**
- * This constructor is only used in newInstance().
- *
- * @param protocolType service discovery protocol.
- * @param query The part of service specific query.
- * @hide
- */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- protected WifiP2pServiceRequest(int protocolType, String query) {
- validateQuery(query);
-
- mProtocolType = protocolType;
- mQuery = query;
- if (query != null) {
- mLength = query.length()/2 + 2;
- } else {
- mLength = 2;
- }
- }
-
- /**
- * This constructor is only used in Parcelable.
- *
- * @param serviceType service discovery type.
- * @param length the length of service discovery packet.
- * @param transId the transaction id
- * @param query The part of service specific query.
- */
- private WifiP2pServiceRequest(int serviceType, int length,
- int transId, String query) {
- mProtocolType = serviceType;
- mLength = length;
- mTransId = transId;
- mQuery = query;
- }
-
- /**
- * Return transaction id.
- *
- * @return transaction id
- * @hide
- */
- public int getTransactionId() {
- return mTransId;
- }
-
- /**
- * Set transaction id.
- *
- * @param id
- * @hide
- */
- public void setTransactionId(int id) {
- mTransId = id;
- }
-
- /**
- * Return wpa_supplicant request string.
- *
- * The format is the hex dump of the following frame.
- * <pre>
- * _______________________________________________________________
- * | Length (2) | Type (1) | Transaction ID (1) |
- * | Query Data (variable) |
- * </pre>
- *
- * @return wpa_supplicant request string.
- * @hide
- */
- public String getSupplicantQuery() {
- StringBuffer sb = new StringBuffer();
- // length is retained as little endian format.
- sb.append(String.format(Locale.US, "%02x", (mLength) & 0xff));
- sb.append(String.format(Locale.US, "%02x", (mLength >> 8) & 0xff));
- sb.append(String.format(Locale.US, "%02x", mProtocolType));
- sb.append(String.format(Locale.US, "%02x", mTransId));
- if (mQuery != null) {
- sb.append(mQuery);
- }
-
- return sb.toString();
- }
-
- /**
- * Validate query.
- *
- * <p>If invalid, throw IllegalArgumentException.
- * @param query The part of service specific query.
- */
- private void validateQuery(String query) {
- if (query == null) {
- return;
- }
-
- int UNSIGNED_SHORT_MAX = 0xffff;
- if (query.length()%2 == 1) {
- throw new IllegalArgumentException(
- "query size is invalid. query=" + query);
- }
- if (query.length()/2 > UNSIGNED_SHORT_MAX) {
- throw new IllegalArgumentException(
- "query size is too large. len=" + query.length());
- }
-
- // check whether query is hex string.
- query = query.toLowerCase(Locale.ROOT);
- char[] chars = query.toCharArray();
- for (char c: chars) {
- if (!((c >= '0' && c <= '9') ||
- (c >= 'a' && c <= 'f'))){
- throw new IllegalArgumentException(
- "query should be hex string. query=" + query);
- }
- }
- }
-
- /**
- * Create a service discovery request.
- *
- * @param protocolType can be {@link WifiP2pServiceInfo#SERVICE_TYPE_ALL}
- * or {@link WifiP2pServiceInfo#SERVICE_TYPE_VENDOR_SPECIFIC}.
- * In order to create a UPnP or Bonjour service request, use
- * {@link WifiP2pUpnpServiceRequest} or {@link WifiP2pDnsSdServiceRequest}
- * respectively
- *
- * @param queryData hex string that is vendor specific. Can be null.
- * @return service discovery request.
- */
- public static WifiP2pServiceRequest newInstance(int protocolType, String queryData) {
- return new WifiP2pServiceRequest(protocolType, queryData);
- }
-
- /**
- * Create a service discovery request.
- *
- * @param protocolType can be {@link WifiP2pServiceInfo#SERVICE_TYPE_ALL}
- * or {@link WifiP2pServiceInfo#SERVICE_TYPE_VENDOR_SPECIFIC}.
- * In order to create a UPnP or Bonjour service request, use
- * {@link WifiP2pUpnpServiceRequest} or {@link WifiP2pDnsSdServiceRequest}
- * respectively
- *
- * @return service discovery request.
- */
- public static WifiP2pServiceRequest newInstance(int protocolType ) {
- return new WifiP2pServiceRequest(protocolType, null);
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (!(o instanceof WifiP2pServiceRequest)) {
- return false;
- }
-
- WifiP2pServiceRequest req = (WifiP2pServiceRequest)o;
-
- /*
- * Not compare transaction id.
- * Transaction id may be changed on each service discovery operation.
- */
- if ((req.mProtocolType != mProtocolType) ||
- (req.mLength != mLength)) {
- return false;
- }
-
- if (req.mQuery == null && mQuery == null) {
- return true;
- } else if (req.mQuery != null) {
- return req.mQuery.equals(mQuery);
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- int result = 17;
- result = 31 * result + mProtocolType;
- result = 31 * result + mLength;
- result = 31 * result + (mQuery == null ? 0 : mQuery.hashCode());
- return result;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mProtocolType);
- dest.writeInt(mLength);
- dest.writeInt(mTransId);
- dest.writeString(mQuery);
- }
-
- /** Implement the Parcelable interface {@hide} */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final @android.annotation.NonNull Creator<WifiP2pServiceRequest> CREATOR =
- new Creator<WifiP2pServiceRequest>() {
- public WifiP2pServiceRequest createFromParcel(Parcel in) {
- int servType = in.readInt();
- int length = in.readInt();
- int transId = in.readInt();
- String query = in.readString();
- return new WifiP2pServiceRequest(servType, length, transId, query);
- }
-
- public WifiP2pServiceRequest[] newArray(int size) {
- return new WifiP2pServiceRequest[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceResponse.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceResponse.java
deleted file mode 100644
index 1b9c080993fa..000000000000
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pServiceResponse.java
+++ /dev/null
@@ -1,381 +0,0 @@
-/*
- * Copyright (C) 2012 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.p2p.nsd;
-
-import android.net.wifi.p2p.WifiP2pDevice;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.io.ByteArrayInputStream;
-import java.io.DataInputStream;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * The class for a response of service discovery.
- *
- * @hide
- */
-public class WifiP2pServiceResponse implements Parcelable {
-
- private static int MAX_BUF_SIZE = 1024;
-
- /**
- * Service type. It's defined in table63 in Wi-Fi Direct specification.
- */
- protected int mServiceType;
-
- /**
- * Status code of service discovery response.
- * It's defined in table65 in Wi-Fi Direct specification.
- * @see Status
- */
- protected int mStatus;
-
- /**
- * Service transaction ID.
- * This is a nonzero value used to match the service request/response TLVs.
- */
- protected int mTransId;
-
- /**
- * Source device.
- */
- protected WifiP2pDevice mDevice;
-
- /**
- * Service discovery response data based on the requested on
- * the service protocol type. The protocol format depends on the service type.
- */
- protected byte[] mData;
-
-
- /**
- * The status code of service discovery response.
- * Currently 4 status codes are defined and the status codes from 4 to 255
- * are reserved.
- *
- * See Wi-Fi Direct specification for the detail.
- */
- public static class Status {
- /** success */
- public static final int SUCCESS = 0;
-
- /** the service protocol type is not available */
- public static final int SERVICE_PROTOCOL_NOT_AVAILABLE = 1;
-
- /** the requested information is not available */
- public static final int REQUESTED_INFORMATION_NOT_AVAILABLE = 2;
-
- /** bad request */
- public static final int BAD_REQUEST = 3;
-
- /** @hide */
- public static String toString(int status) {
- switch(status) {
- case SUCCESS:
- return "SUCCESS";
- case SERVICE_PROTOCOL_NOT_AVAILABLE:
- return "SERVICE_PROTOCOL_NOT_AVAILABLE";
- case REQUESTED_INFORMATION_NOT_AVAILABLE:
- return "REQUESTED_INFORMATION_NOT_AVAILABLE";
- case BAD_REQUEST:
- return "BAD_REQUEST";
- default:
- return "UNKNOWN";
- }
- }
-
- /** not used */
- private Status() {}
- }
-
- /**
- * Hidden constructor. This is only used in framework.
- *
- * @param serviceType service discovery type.
- * @param status status code.
- * @param transId transaction id.
- * @param device source device.
- * @param data query data.
- */
- protected WifiP2pServiceResponse(int serviceType, int status, int transId,
- WifiP2pDevice device, byte[] data) {
- mServiceType = serviceType;
- mStatus = status;
- mTransId = transId;
- mDevice = device;
- mData = data;
- }
-
- /**
- * Return the service type of service discovery response.
- *
- * @return service discovery type.<br>
- * e.g) {@link WifiP2pServiceInfo#SERVICE_TYPE_BONJOUR}
- */
- public int getServiceType() {
- return mServiceType;
- }
-
- /**
- * Return the status code of service discovery response.
- *
- * @return status code.
- * @see Status
- */
- public int getStatus() {
- return mStatus;
- }
-
- /**
- * Return the transaction id of service discovery response.
- *
- * @return transaction id.
- * @hide
- */
- public int getTransactionId() {
- return mTransId;
- }
-
- /**
- * Return response data.
- *
- * <pre>Data format depends on service type
- *
- * @return a query or response data.
- */
- public byte[] getRawData() {
- return mData;
- }
-
- /**
- * Returns the source device of service discovery response.
- *
- * <pre>This is valid only when service discovery response.
- *
- * @return the source device of service discovery response.
- */
- public WifiP2pDevice getSrcDevice() {
- return mDevice;
- }
-
- /** @hide */
- public void setSrcDevice(WifiP2pDevice dev) {
- if (dev == null) return;
- this.mDevice = dev;
- }
-
-
- /**
- * Create the list of WifiP2pServiceResponse instance from supplicant event.
- *
- * @param srcAddr source address of the service response
- * @param tlvsBin byte array containing the binary tlvs data
- * @return if parse failed, return null
- * @hide
- */
- public static List<WifiP2pServiceResponse> newInstance(String srcAddr, byte[] tlvsBin) {
- //updateIndicator not used, and not passed up from supplicant
-
- List<WifiP2pServiceResponse> respList = new ArrayList<WifiP2pServiceResponse>();
- WifiP2pDevice dev = new WifiP2pDevice();
- dev.deviceAddress = srcAddr;
- if (tlvsBin == null) {
- return null;
- }
-
-
- DataInputStream dis = new DataInputStream(new ByteArrayInputStream(tlvsBin));
- try {
- while (dis.available() > 0) {
- /*
- * Service discovery header is as follows.
- * ______________________________________________________________
- * | Length(2byte) | Type(1byte) | TransId(1byte)}|
- * ______________________________________________________________
- * | status(1byte) | vendor specific(variable) |
- */
- // The length equals to 3 plus the number of octets in the vendor
- // specific content field. And this is little endian.
- int length = (dis.readUnsignedByte() +
- (dis.readUnsignedByte() << 8)) - 3;
- int type = dis.readUnsignedByte();
- int transId = dis.readUnsignedByte();
- int status = dis.readUnsignedByte();
- if (length < 0) {
- return null;
- }
- if (length == 0) {
- if (status == Status.SUCCESS) {
- respList.add(new WifiP2pServiceResponse(type, status,
- transId, dev, null));
- }
- continue;
- }
- if (length > MAX_BUF_SIZE) {
- dis.skip(length);
- continue;
- }
- byte[] data = new byte[length];
- dis.readFully(data);
-
- WifiP2pServiceResponse resp;
- if (type == WifiP2pServiceInfo.SERVICE_TYPE_BONJOUR) {
- resp = WifiP2pDnsSdServiceResponse.newInstance(status,
- transId, dev, data);
- } else if (type == WifiP2pServiceInfo.SERVICE_TYPE_UPNP) {
- resp = WifiP2pUpnpServiceResponse.newInstance(status,
- transId, dev, data);
- } else {
- resp = new WifiP2pServiceResponse(type, status, transId, dev, data);
- }
- if (resp != null && resp.getStatus() == Status.SUCCESS) {
- respList.add(resp);
- }
- }
- return respList;
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- if (respList.size() > 0) {
- return respList;
- }
- return null;
- }
-
- /**
- * Converts hex string to byte array.
- *
- * @param hex hex string. if invalid, return null.
- * @return binary data.
- */
- private static byte[] hexStr2Bin(String hex) {
- int sz = hex.length()/2;
- byte[] b = new byte[hex.length()/2];
-
- for (int i=0;i<sz;i++) {
- try {
- b[i] = (byte)Integer.parseInt(hex.substring(i*2, i*2+2), 16);
- } catch (Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- return b;
- }
-
- @Override
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
- sbuf.append("serviceType:").append(mServiceType);
- sbuf.append(" status:").append(Status.toString(mStatus));
- sbuf.append(" srcAddr:").append(mDevice.deviceAddress);
- sbuf.append(" data:").append(Arrays.toString(mData));
- return sbuf.toString();
- }
-
- @Override
- public boolean equals(Object o) {
- if (o == this) {
- return true;
- }
- if (!(o instanceof WifiP2pServiceResponse)) {
- return false;
- }
-
- WifiP2pServiceResponse req = (WifiP2pServiceResponse)o;
-
- return (req.mServiceType == mServiceType) &&
- (req.mStatus == mStatus) &&
- equals(req.mDevice.deviceAddress, mDevice.deviceAddress) &&
- Arrays.equals(req.mData, mData);
- }
-
- private boolean equals(Object a, Object b) {
- if (a == null && b == null) {
- return true;
- } else if (a != null) {
- return a.equals(b);
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- int result = 17;
- result = 31 * result + mServiceType;
- result = 31 * result + mStatus;
- result = 31 * result + mTransId;
- result = 31 * result + (mDevice.deviceAddress == null ?
- 0 : mDevice.deviceAddress.hashCode());
- result = 31 * result + (mData == null ? 0 : Arrays.hashCode(mData));
- return result;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public int describeContents() {
- return 0;
- }
-
- /** Implement the Parcelable interface {@hide} */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mServiceType);
- dest.writeInt(mStatus);
- dest.writeInt(mTransId);
- dest.writeParcelable(mDevice, flags);
- if (mData == null || mData.length == 0) {
- dest.writeInt(0);
- } else {
- dest.writeInt(mData.length);
- dest.writeByteArray(mData);
- }
- }
-
- /** Implement the Parcelable interface {@hide} */
- public static final @android.annotation.NonNull Creator<WifiP2pServiceResponse> CREATOR =
- new Creator<WifiP2pServiceResponse>() {
- public WifiP2pServiceResponse createFromParcel(Parcel in) {
-
- int type = in.readInt();
- int status = in.readInt();
- int transId = in.readInt();
- WifiP2pDevice dev = (WifiP2pDevice)in.readParcelable(null);
- int len = in.readInt();
- byte[] data = null;
- if (len > 0) {
- data = new byte[len];
- in.readByteArray(data);
- }
- if (type == WifiP2pServiceInfo.SERVICE_TYPE_BONJOUR) {
- return WifiP2pDnsSdServiceResponse.newInstance(status,
- transId, dev, data);
- } else if (type == WifiP2pServiceInfo.SERVICE_TYPE_UPNP) {
- return WifiP2pUpnpServiceResponse.newInstance(status,
- transId, dev, data);
- }
- return new WifiP2pServiceResponse(type, status, transId, dev, data);
- }
-
- public WifiP2pServiceResponse[] newArray(int size) {
- return new WifiP2pServiceResponse[size];
- }
- };
-}
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceInfo.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceInfo.java
deleted file mode 100644
index a4cdfd97f20d..000000000000
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceInfo.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2012 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.p2p.nsd;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-import java.util.UUID;
-
-/**
- * A class for storing Upnp service information that is advertised
- * over a Wi-Fi peer-to-peer setup.
- *
- * {@see android.net.wifi.p2p.WifiP2pManager#addLocalService}
- * {@see android.net.wifi.p2p.WifiP2pManager#removeLocalService}
- * {@see WifiP2pServiceInfo}
- * {@see WifiP2pDnsSdServiceInfo}
- */
-public class WifiP2pUpnpServiceInfo extends WifiP2pServiceInfo {
-
- /**
- * UPnP version 1.0.
- *
- * <pre>Query Version should always be set to 0x10 if the query values are
- * compatible with UPnP Device Architecture 1.0.
- * @hide
- */
- public static final int VERSION_1_0 = 0x10;
-
- /**
- * This constructor is only used in newInstance().
- *
- * @param queryList
- */
- private WifiP2pUpnpServiceInfo(List<String> queryList) {
- super(queryList);
- }
-
- /**
- * Create UPnP service information object.
- *
- * @param uuid a string representation of this UUID in the following format,
- * as per <a href="http://www.ietf.org/rfc/rfc4122.txt">RFC 4122</a>.<br>
- * e.g) 6859dede-8574-59ab-9332-123456789012
- * @param device a string representation of this device in the following format,
- * as per
- * <a href="http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf">
- * UPnP Device Architecture1.1</a><br>
- * e.g) urn:schemas-upnp-org:device:MediaServer:1
- * @param services a string representation of this service in the following format,
- * as per
- * <a href="http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf">
- * UPnP Device Architecture1.1</a><br>
- * e.g) urn:schemas-upnp-org:service:ContentDirectory:1
- * @return UPnP service information object.
- */
- public static WifiP2pUpnpServiceInfo newInstance(String uuid,
- String device, List<String> services) {
- if (uuid == null || device == null) {
- throw new IllegalArgumentException("uuid or device cannnot be null");
- }
- UUID.fromString(uuid);
-
- ArrayList<String> info = new ArrayList<String>();
-
- info.add(createSupplicantQuery(uuid, null));
- info.add(createSupplicantQuery(uuid, "upnp:rootdevice"));
- info.add(createSupplicantQuery(uuid, device));
- if (services != null) {
- for (String service:services) {
- info.add(createSupplicantQuery(uuid, service));
- }
- }
-
- return new WifiP2pUpnpServiceInfo(info);
- }
-
- /**
- * Create wpa_supplicant service query for upnp.
- *
- * @param uuid
- * @param data
- * @return wpa_supplicant service query for upnp
- */
- private static String createSupplicantQuery(String uuid, String data) {
- StringBuffer sb = new StringBuffer();
- sb.append("upnp ");
- sb.append(String.format(Locale.US, "%02x ", VERSION_1_0));
- sb.append("uuid:");
- sb.append(uuid);
- if (data != null) {
- sb.append("::");
- sb.append(data);
- }
- return sb.toString();
- }
-}
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceRequest.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceRequest.java
deleted file mode 100644
index 98e447e37bae..000000000000
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceRequest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2012 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.p2p.nsd;
-
-import android.net.wifi.p2p.WifiP2pManager;
-
-import java.util.Locale;
-
-/**
- * A class for creating a Upnp service discovery request for use with
- * {@link WifiP2pManager#addServiceRequest} and {@link WifiP2pManager#removeServiceRequest}
- *
- * {@see WifiP2pManager}
- * {@see WifiP2pServiceRequest}
- * {@see WifiP2pDnsSdServiceRequest}
- */
-public class WifiP2pUpnpServiceRequest extends WifiP2pServiceRequest {
-
- /**
- * This constructor is only used in newInstance().
- *
- * @param query The part of service specific query.
- * @hide
- */
- protected WifiP2pUpnpServiceRequest(String query) {
- super(WifiP2pServiceInfo.SERVICE_TYPE_UPNP, query);
- }
-
- /**
- * This constructor is only used in newInstance().
- * @hide
- */
- protected WifiP2pUpnpServiceRequest() {
- super(WifiP2pServiceInfo.SERVICE_TYPE_UPNP, null);
- }
-
- /**
- * Create a service discovery request to search all UPnP services.
- *
- * @return service request for UPnP.
- */
- public static WifiP2pUpnpServiceRequest newInstance() {
- return new WifiP2pUpnpServiceRequest();
- }
- /**
- * Create a service discovery request to search specified UPnP services.
- *
- * @param st ssdp search target. Cannot be null.<br>
- * e.g ) <br>
- * <ul>
- * <li>"ssdp:all"
- * <li>"upnp:rootdevice"
- * <li>"urn:schemas-upnp-org:device:MediaServer:2"
- * <li>"urn:schemas-upnp-org:service:ContentDirectory:2"
- * <li>"uuid:6859dede-8574-59ab-9332-123456789012"
- * </ul>
- * @return service request for UPnP.
- */
- public static WifiP2pUpnpServiceRequest newInstance(String st) {
- if (st == null) {
- throw new IllegalArgumentException("search target cannot be null");
- }
- StringBuffer sb = new StringBuffer();
- sb.append(String.format(Locale.US, "%02x", WifiP2pUpnpServiceInfo.VERSION_1_0));
- sb.append(WifiP2pServiceInfo.bin2HexStr(st.getBytes()));
- return new WifiP2pUpnpServiceRequest(sb.toString());
- }
-}
diff --git a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceResponse.java b/wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceResponse.java
deleted file mode 100644
index ab95af6f64b3..000000000000
--- a/wifi/java/android/net/wifi/p2p/nsd/WifiP2pUpnpServiceResponse.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2012 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.p2p.nsd;
-
-import android.net.wifi.p2p.WifiP2pDevice;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A class for a response of upnp service discovery.
- *
- * @hide
- */
-public class WifiP2pUpnpServiceResponse extends WifiP2pServiceResponse {
-
- /**
- * UPnP version. should be {@link WifiP2pUpnpServiceInfo#VERSION_1_0}
- */
- private int mVersion;
-
- /**
- * The list of Unique Service Name.
- * e.g)
- *{"uuid:6859dede-8574-59ab-9332-123456789012",
- *"uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice"}
- */
- private List<String> mUniqueServiceNames;
-
- /**
- * Return UPnP version number.
- *
- * @return version number.
- * @see WifiP2pUpnpServiceInfo#VERSION_1_0
- */
- public int getVersion() {
- return mVersion;
- }
-
- /**
- * Return Unique Service Name strings.
- *
- * @return Unique Service Name.<br>
- * e.g ) <br>
- * <ul>
- * <li>"uuid:6859dede-8574-59ab-9332-123456789012"
- * <li>"uuid:6859dede-8574-59ab-9332-123456789012::upnp:rootdevice"
- * <li>"uuid:6859dede-8574-59ab-9332-123456789012::urn:schemas-upnp-org:device:
- * MediaServer:2"
- * <li>"uuid:6859dede-8574-59ab-9332-123456789012::urn:schemas-upnp-org:service:
- * ContentDirectory:2"
- * </ul>
- */
- public List<String> getUniqueServiceNames() {
- return mUniqueServiceNames;
- }
-
- /**
- * hidden constructor.
- *
- * @param status status code
- * @param transId transaction id
- * @param dev source device
- * @param data UPnP response data.
- */
- protected WifiP2pUpnpServiceResponse(int status,
- int transId, WifiP2pDevice dev, byte[] data) {
- super(WifiP2pServiceInfo.SERVICE_TYPE_UPNP,
- status, transId, dev, data);
- if (!parse()) {
- throw new IllegalArgumentException("Malformed upnp service response");
- }
- }
-
- /**
- * Parse UPnP service discovery response
- *
- * @return {@code true} if the operation succeeded
- */
- private boolean parse() {
- /*
- * The data format is as follows.
- *
- * ______________________________________________________
- * | Version (1) | USN (Variable) |
- */
- if (mData == null) {
- // the empty is OK.
- return true;
- }
-
- if (mData.length < 1) {
- return false;
- }
-
- mVersion = mData[0] & 0xff;
- String[] names = new String(mData, 1, mData.length-1).split(",");
- mUniqueServiceNames = new ArrayList<String>();
- for (String name : names) {
- mUniqueServiceNames.add(name);
- }
- return true;
- }
-
- @Override
- public String toString() {
- StringBuffer sbuf = new StringBuffer();
- sbuf.append("serviceType:UPnP(").append(mServiceType).append(")");
- sbuf.append(" status:").append(Status.toString(mStatus));
- sbuf.append(" srcAddr:").append(mDevice.deviceAddress);
- sbuf.append(" version:").append(String.format("%02x", mVersion));
- if (mUniqueServiceNames != null) {
- for (String name : mUniqueServiceNames) {
- sbuf.append(" usn:").append(name);
- }
- }
- return sbuf.toString();
- }
-
- /**
- * Create upnp service response.
- *
- * <pre>This is only used in{@link WifiP2pServiceResponse}
- *
- * @param status status code.
- * @param transId transaction id.
- * @param device source device.
- * @param data UPnP response data.
- * @return UPnP service response data.
- * @hide
- */
- static WifiP2pUpnpServiceResponse newInstance(int status,
- int transId, WifiP2pDevice device, byte[] data) {
- if (status != WifiP2pServiceResponse.Status.SUCCESS) {
- return new WifiP2pUpnpServiceResponse(status, transId, device, null);
- }
-
- try {
- return new WifiP2pUpnpServiceResponse(status, transId, device, data);
- } catch (IllegalArgumentException e) {
- e.printStackTrace();
- }
- return null;
- }
-}
diff --git a/wifi/java/android/net/wifi/p2p/package.html b/wifi/java/android/net/wifi/p2p/package.html
deleted file mode 100644
index 6a5e8e6a79b6..000000000000
--- a/wifi/java/android/net/wifi/p2p/package.html
+++ /dev/null
@@ -1,68 +0,0 @@
-<HTML>
-<BODY>
-<p>Provides classes to create peer-to-peer (P2P) connections with Wi-Fi Direct.</p>
-
-<p>Using these APIs, you can discover and connect to other devices when each
-device supports Wi-Fi Direct, then communicate over a speedy connection across distances much longer
-than a Bluetooth connection. The primary class you need to work with is {@link
-android.net.wifi.p2p.WifiP2pManager}, which you can acquire by calling {@link
-android.app.Activity#getSystemService getSystemService(WIFI_P2P_SERVICE)}. The {@link
-android.net.wifi.p2p.WifiP2pManager} includes APIs that allow you to:</p>
-<ul>
-<li>Initialize your application for P2P connections by calling {@link
-android.net.wifi.p2p.WifiP2pManager#initialize initialize()}</li>
-
-<li>Discover nearby devices by calling {@link android.net.wifi.p2p.WifiP2pManager#discoverPeers
-discoverPeers()}</li>
-
-<li>Start a P2P connection by calling {@link android.net.wifi.p2p.WifiP2pManager#connect
-connect()}</li>
-<li>And more</li>
-</ul>
-
-<p>Several other interfaces and classes are necessary as well, such as:</p>
-<ul>
-<li>The {@link android.net.wifi.p2p.WifiP2pManager.ActionListener} interface allows you to receive
-callbacks when an operation such as discovering peers or connecting to them succeeds or fails.</li>
-
-<li>{@link android.net.wifi.p2p.WifiP2pManager.PeerListListener} interface allows you to receive
-information about discovered peers. The callback provides a {@link
-android.net.wifi.p2p.WifiP2pDeviceList}, from which you can retrieve a {@link
-android.net.wifi.p2p.WifiP2pDevice} object for each device within range and get information such as
-the device name, address, device type, the WPS configurations the device supports, and more.</li>
-
-<li>The {@link android.net.wifi.p2p.WifiP2pManager.GroupInfoListener} interface allows you to
-receive information about a P2P group. The callback provides a {@link
-android.net.wifi.p2p.WifiP2pGroup} object, which provides group information such as the owner, the
-network name, and passphrase.</li>
-
-<li>{@link android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener} interface allows you to
-receive information about the current connection. The callback provides a {@link
-android.net.wifi.p2p.WifiP2pInfo} object, which has information such as whether a group has been
-formed and who is the group owner.</li>
-</ul>
-
-<p>In order to use the Wi-Fi P2P APIs, your app must request the following user permissions:</p>
-<ul>
-<li>{@link android.Manifest.permission#ACCESS_WIFI_STATE}</li>
-<li>{@link android.Manifest.permission#CHANGE_WIFI_STATE}</li>
-<li>{@link android.Manifest.permission#INTERNET} (although your app doesn’t technically connect
-to the Internet, communicating to Wi-Fi Direct peers with standard java sockets requires Internet
-permission).</li>
-</ul>
-
-<p>For example code, see the <a href="{@docRoot}resources/samples/WiFiDirectDemo/index.html">Wi-Fi
-Direct Demo</a> sample application.</p>
-
-<p class="note"><strong>Note:</strong> Not all Android-powered devices support Wi-Fi
-Direct. If your application uses Wi-Fi Direct, declare so with a <a
-href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a>
-element in the manifest file:</p>
-<pre>
-&lt;manifest ...>
- &lt;uses-feature android:name="android.hardware.wifi.direct" />
- ...
-&lt;/manifest>
-</pre>
-</BODY>
-</HTML>
diff --git a/wifi/java/android/net/wifi/package.html b/wifi/java/android/net/wifi/package.html
deleted file mode 100644
index b21d39d065b5..000000000000
--- a/wifi/java/android/net/wifi/package.html
+++ /dev/null
@@ -1,29 +0,0 @@
-<HTML>
-<BODY>
-<p>Provides classes to manage Wi-Fi functionality on the device.</p>
-<p>The Wi-Fi APIs provide a means by which applications can communicate
-with the lower-level wireless stack that provides Wi-Fi network access. Almost all
-information from the device supplicant is available, including the connected network's
-link speed, IP address, negotiation state, and more, plus information about other
-networks that are available. Some other API features include the ability to
-scan, add, save, terminate and initiate Wi-Fi connections.</p>
-
-<p>Some APIs may require the following user permissions:</p>
-<ul>
- <li>{@link android.Manifest.permission#ACCESS_WIFI_STATE}</li>
- <li>{@link android.Manifest.permission#CHANGE_WIFI_STATE}</li>
- <li>{@link android.Manifest.permission#CHANGE_WIFI_MULTICAST_STATE}</li>
-</ul>
-
-<p class="note"><strong>Note:</strong> Not all Android-powered devices provide Wi-Fi functionality.
-If your application uses Wi-Fi, declare so with a <a
-href="{@docRoot}guide/topics/manifest/uses-feature-element.html">{@code <uses-feature>}</a>
-element in the manifest file:</p>
-<pre>
-&lt;manifest ...>
- &lt;uses-feature android:name="android.hardware.wifi" />
- ...
-&lt;/manifest>
-</pre>
-</BODY>
-</HTML>
diff --git a/wifi/java/android/net/wifi/rtt/CivicLocation.java b/wifi/java/android/net/wifi/rtt/CivicLocation.java
deleted file mode 100644
index 1d411779267d..000000000000
--- a/wifi/java/android/net/wifi/rtt/CivicLocation.java
+++ /dev/null
@@ -1,333 +0,0 @@
-/*
- * Copyright (C) 2018 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.rtt;
-
-import android.annotation.Nullable;
-import android.location.Address;
-import android.net.wifi.rtt.CivicLocationKeys.CivicLocationKeysType;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.os.Parcelable.Creator;
-import android.util.SparseArray;
-
-import java.nio.charset.StandardCharsets;
-import java.util.Locale;
-import java.util.Objects;
-
-/**
- * Decodes the Type Length Value (TLV) elements found in a Location Civic Record as defined by IEEE
- * P802.11-REVmc/D8.0 section 9.4.2.22.13 using the format described in IETF RFC 4776.
- *
- * <p>The TLVs each define a key, value pair for a civic address type such as apt, street, city,
- * county, and country. The class provides a general getter method to extract a value for an element
- * key, returning null if not set.
- *
- * @hide
- */
-public final class CivicLocation implements Parcelable {
- // Address (class) line indexes
- private static final int ADDRESS_LINE_0_ROOM_DESK_FLOOR = 0;
- private static final int ADDRESS_LINE_1_NUMBER_ROAD_SUFFIX_APT = 1;
- private static final int ADDRESS_LINE_2_CITY = 2;
- private static final int ADDRESS_LINE_3_STATE_POSTAL_CODE = 3;
- private static final int ADDRESS_LINE_4_COUNTRY = 4;
-
- // Buffer management
- private static final int MIN_CIVIC_BUFFER_SIZE = 3;
- private static final int MAX_CIVIC_BUFFER_SIZE = 256;
- private static final int COUNTRY_CODE_LENGTH = 2;
- private static final int BYTE_MASK = 0xFF;
- private static final int TLV_TYPE_INDEX = 0;
- private static final int TLV_LENGTH_INDEX = 1;
- private static final int TLV_VALUE_INDEX = 2;
-
- private final boolean mIsValid;
- private final String mCountryCode; // Two character country code (ISO 3166 standard).
- private SparseArray<String> mCivicAddressElements =
- new SparseArray<>(MIN_CIVIC_BUFFER_SIZE);
-
-
- /**
- * Constructor
- *
- * @param civicTLVs a byte buffer containing parameters in the form type, length, value
- * @param countryCode the two letter code defined by the ISO 3166 standard
- *
- * @hide
- */
- public CivicLocation(@Nullable byte[] civicTLVs, @Nullable String countryCode) {
- this.mCountryCode = countryCode;
- if (countryCode == null || countryCode.length() != COUNTRY_CODE_LENGTH) {
- this.mIsValid = false;
- return;
- }
- boolean isValid = false;
- if (civicTLVs != null
- && civicTLVs.length >= MIN_CIVIC_BUFFER_SIZE
- && civicTLVs.length < MAX_CIVIC_BUFFER_SIZE) {
- isValid = parseCivicTLVs(civicTLVs);
- }
-
- mIsValid = isValid;
- }
-
- private CivicLocation(Parcel in) {
- mIsValid = in.readByte() != 0;
- mCountryCode = in.readString();
- mCivicAddressElements = in.readSparseArray(this.getClass().getClassLoader());
- }
-
- public static final @android.annotation.NonNull Creator<CivicLocation> CREATOR = new Creator<CivicLocation>() {
- @Override
- public CivicLocation createFromParcel(Parcel in) {
- return new CivicLocation(in);
- }
-
- @Override
- public CivicLocation[] newArray(int size) {
- return new CivicLocation[size];
- }
- };
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel parcel, int flags) {
- parcel.writeByte((byte) (mIsValid ? 1 : 0));
- parcel.writeString(mCountryCode);
- parcel.writeSparseArray((android.util.SparseArray) mCivicAddressElements);
- }
-
- /**
- * Check TLV format and store TLV key/value pairs in this object so they can be queried by key.
- *
- * @param civicTLVs the buffer of TLV elements
- * @return a boolean indicating success of the parsing process
- */
- private boolean parseCivicTLVs(byte[] civicTLVs) {
- int bufferPtr = 0;
- int bufferLength = civicTLVs.length;
-
- // Iterate through the sub-elements contained in the LCI IE checking the accumulated
- // element lengths do not overflow the total buffer length
- while (bufferPtr < bufferLength) {
- int civicAddressType = civicTLVs[bufferPtr + TLV_TYPE_INDEX] & BYTE_MASK;
- int civicAddressTypeLength = civicTLVs[bufferPtr + TLV_LENGTH_INDEX];
- if (civicAddressTypeLength != 0) {
- if (bufferPtr + TLV_VALUE_INDEX + civicAddressTypeLength > bufferLength) {
- return false;
- }
- mCivicAddressElements.put(civicAddressType,
- new String(civicTLVs, bufferPtr + TLV_VALUE_INDEX,
- civicAddressTypeLength, StandardCharsets.UTF_8));
- }
- bufferPtr += civicAddressTypeLength + TLV_VALUE_INDEX;
- }
- return true;
- }
-
- /**
- * Getter for the value of a civic Address element type.
- *
- * @param key an integer code for the element type key
- * @return the string value associated with that element type
- */
- @Nullable
- public String getCivicElementValue(@CivicLocationKeysType int key) {
- return mCivicAddressElements.get(key);
- }
-
- /**
- * Converts a CivicLocation object to a SparseArray.
- *
- * @return the SparseArray<string> representation of the CivicLocation
- */
- @Nullable
- public SparseArray<String> toSparseArray() {
- return mCivicAddressElements;
- }
-
- /**
- * Generates a comma separated string of all the defined elements.
- *
- * @return a compiled string representing all elements
- */
- @Override
- public String toString() {
- return mCivicAddressElements.toString();
- }
-
- /**
- * Converts Civic Location to the best effort Address Object.
- *
- * @return the {@link Address} object based on the Civic Location data
- */
- @Nullable
- public Address toAddress() {
- if (!mIsValid) {
- return null;
- }
- Address address = new Address(Locale.US);
- String room = formatAddressElement("Room: ", getCivicElementValue(CivicLocationKeys.ROOM));
- String desk =
- formatAddressElement(" Desk: ", getCivicElementValue(CivicLocationKeys.DESK));
- String floor =
- formatAddressElement(", Flr: ", getCivicElementValue(CivicLocationKeys.FLOOR));
- String houseNumber = formatAddressElement("", getCivicElementValue(CivicLocationKeys.HNO));
- String houseNumberSuffix =
- formatAddressElement("", getCivicElementValue(CivicLocationKeys.HNS));
- String road =
- formatAddressElement(" ", getCivicElementValue(
- CivicLocationKeys.PRIMARY_ROAD_NAME));
- String roadSuffix = formatAddressElement(" ", getCivicElementValue(CivicLocationKeys.STS));
- String apt = formatAddressElement(", Apt: ", getCivicElementValue(CivicLocationKeys.APT));
- String city = formatAddressElement("", getCivicElementValue(CivicLocationKeys.CITY));
- String state = formatAddressElement("", getCivicElementValue(CivicLocationKeys.STATE));
- String postalCode =
- formatAddressElement(" ", getCivicElementValue(CivicLocationKeys.POSTAL_CODE));
-
- // Aggregation into common address format
- String addressLine0 =
- new StringBuilder().append(room).append(desk).append(floor).toString();
- String addressLine1 =
- new StringBuilder().append(houseNumber).append(houseNumberSuffix).append(road)
- .append(roadSuffix).append(apt).toString();
- String addressLine2 = city;
- String addressLine3 = new StringBuilder().append(state).append(postalCode).toString();
- String addressLine4 = mCountryCode;
-
- // Setting Address object line fields by common convention.
- address.setAddressLine(ADDRESS_LINE_0_ROOM_DESK_FLOOR, addressLine0);
- address.setAddressLine(ADDRESS_LINE_1_NUMBER_ROAD_SUFFIX_APT, addressLine1);
- address.setAddressLine(ADDRESS_LINE_2_CITY, addressLine2);
- address.setAddressLine(ADDRESS_LINE_3_STATE_POSTAL_CODE, addressLine3);
- address.setAddressLine(ADDRESS_LINE_4_COUNTRY, addressLine4);
-
- // Other compatible fields between the CIVIC_ADDRESS and the Address Class.
- address.setFeatureName(getCivicElementValue(CivicLocationKeys.NAM)); // Structure name
- address.setSubThoroughfare(getCivicElementValue(CivicLocationKeys.HNO));
- address.setThoroughfare(getCivicElementValue(CivicLocationKeys.PRIMARY_ROAD_NAME));
- address.setSubLocality(getCivicElementValue(CivicLocationKeys.NEIGHBORHOOD));
- address.setSubAdminArea(getCivicElementValue(CivicLocationKeys.COUNTY));
- address.setAdminArea(getCivicElementValue(CivicLocationKeys.STATE));
- address.setPostalCode(getCivicElementValue(CivicLocationKeys.POSTAL_CODE));
- address.setCountryCode(mCountryCode); // Country
- return address;
- }
-
- /**
- * Prepares an address element so that it can be integrated into an address line convention.
- *
- * <p>If an address element is null, the return string will be empty e.g. "".
- *
- * @param label a string defining the type of address element
- * @param value a string defining the elements value
- * @return the formatted version of the value, with null values converted to empty strings
- */
- private String formatAddressElement(String label, String value) {
- if (value != null) {
- return label + value;
- } else {
- return "";
- }
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (!(obj instanceof CivicLocation)) {
- return false;
- }
- CivicLocation other = (CivicLocation) obj;
- return mIsValid == other.mIsValid
- && Objects.equals(mCountryCode, other.mCountryCode)
- && isSparseArrayStringEqual(mCivicAddressElements, other.mCivicAddressElements);
- }
-
- @Override
- public int hashCode() {
- int[] civicAddressKeys = getSparseArrayKeys(mCivicAddressElements);
- String[] civicAddressValues = getSparseArrayValues(mCivicAddressElements);
- return Objects.hash(mIsValid, mCountryCode, civicAddressKeys, civicAddressValues);
- }
-
- /**
- * Tests if the Civic Location object is valid
- *
- * @return a boolean defining mIsValid
- */
- public boolean isValid() {
- return mIsValid;
- }
-
- /**
- * Tests if two sparse arrays are equal on a key for key basis
- *
- * @param sa1 the first sparse array
- * @param sa2 the second sparse array
- * @return the boolean result after comparing values key by key
- */
- private boolean isSparseArrayStringEqual(SparseArray<String> sa1, SparseArray<String> sa2) {
- int size = sa1.size();
- if (size != sa2.size()) {
- return false;
- }
- for (int i = 0; i < size; i++) {
- String sa1Value = sa1.valueAt(i);
- String sa2Value = sa2.valueAt(i);
- if (!sa1Value.equals(sa2Value)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Extract an array of all the keys in a SparseArray<String>
- *
- * @param sa the sparse array of Strings
- * @return an integer array of all keys in the SparseArray<String>
- */
- private int[] getSparseArrayKeys(SparseArray<String> sa) {
- int size = sa.size();
- int[] keys = new int[size];
- for (int i = 0; i < size; i++) {
- keys[i] = sa.keyAt(i);
- }
- return keys;
- }
-
- /**
- * Extract an array of all the String values in a SparseArray<String>
- *
- * @param sa the sparse array of Strings
- * @return a String array of all values in the SparseArray<String>
- */
- private String[] getSparseArrayValues(SparseArray<String> sa) {
- int size = sa.size();
- String[] values = new String[size];
- for (int i = 0; i < size; i++) {
- values[i] = sa.valueAt(i);
- }
- return values;
- }
-}
diff --git a/wifi/java/android/net/wifi/rtt/CivicLocationKeys.java b/wifi/java/android/net/wifi/rtt/CivicLocationKeys.java
deleted file mode 100644
index b03f4a93e962..000000000000
--- a/wifi/java/android/net/wifi/rtt/CivicLocationKeys.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (C) 2018 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.rtt;
-
-import static java.lang.annotation.RetentionPolicy.SOURCE;
-
-import android.annotation.IntDef;
-
-import java.lang.annotation.Retention;
-
-/**
- * Civic Address key types used to define address elements.
- *
- * <p>These keys can be used with {@code ResponderLocation.toCivicLocationSparseArray()}
- * to look-up the corresponding string values.</p>
- */
-public class CivicLocationKeys {
-
- /**
- * An enumeration of all civic location keys.
- *
- * @hide
- */
- @Retention(SOURCE)
- @IntDef({LANGUAGE, STATE, COUNTY, CITY, BOROUGH, NEIGHBORHOOD, GROUP_OF_STREETS, PRD, POD, STS,
- HNO, HNS, LMK, LOC, NAM, POSTAL_CODE, BUILDING, APT, FLOOR, ROOM, TYPE_OF_PLACE, PCN,
- PO_BOX, ADDITIONAL_CODE, DESK, PRIMARY_ROAD_NAME, ROAD_SECTION, BRANCH_ROAD_NAME,
- SUBBRANCH_ROAD_NAME, STREET_NAME_PRE_MODIFIER, STREET_NAME_POST_MODIFIER, SCRIPT})
- public @interface CivicLocationKeysType {
- }
-
- /** Language key e.g. i-default. */
- public static final int LANGUAGE = 0;
- /** Category label A1 key e.g. California. */
- public static final int STATE = 1;
- /** Category label A2 key e.g. Marin. */
- public static final int COUNTY = 2;
- /** Category label A3 key e.g. San Francisco. */
- public static final int CITY = 3;
- /** Category label A4 key e.g. Westminster. */
- public static final int BOROUGH = 4;
- /** Category label A5 key e.g. Pacific Heights. */
- public static final int NEIGHBORHOOD = 5;
- /** Category label A6 key e.g. University District. */
- public static final int GROUP_OF_STREETS = 6;
- // 7 - 15 not defined
- /** Leading Street direction key e.g. N. */
- public static final int PRD = 16;
- /** Trailing street suffix key e.g. SW. */
- public static final int POD = 17;
- /** Street suffix or Type key e.g Ave, Platz. */
- public static final int STS = 18;
- /** House Number key e.g. 123. */
- public static final int HNO = 19;
- /** House number suffix key e.g. A, 1/2. */
- public static final int HNS = 20;
- /** Landmark or vanity address key e.g. Golden Gate Bridge. */
- public static final int LMK = 21;
- /** Additional Location info key e.g. South Wing. */
- public static final int LOC = 22;
- /** Name of residence key e.g. Joe's Barbershop. */
- public static final int NAM = 23;
- /** Postal or ZIP code key e.g. 10027-1234. */
- public static final int POSTAL_CODE = 24;
- /** Building key e.g. Lincoln Library. */
- public static final int BUILDING = 25;
- /** Apartment or suite key e.g. Apt 42. */
- public static final int APT = 26;
- /** Floor key e.g. 4. */
- public static final int FLOOR = 27;
- /** Room key e.g. 450F. */
- public static final int ROOM = 28;
- /** Type of place key e.g. office. */
- public static final int TYPE_OF_PLACE = 29;
- /** Postal community name key e.g. Leonia. */
- public static final int PCN = 30;
- /** Post Office Box key e.g. 12345. */
- public static final int PO_BOX = 31;
- /** Additional Code key e.g. 13203000003. */
- public static final int ADDITIONAL_CODE = 32;
- /** Seat, desk, pole, or cubical key e.g. WS 181. */
- public static final int DESK = 33;
- /** Primary road name key e.g. Shoreline. */
- public static final int PRIMARY_ROAD_NAME = 34;
- /** Road Section key e.g. 14. */
- public static final int ROAD_SECTION = 35;
- /** Branch Rd Name key e.g. Lane 7. */
- public static final int BRANCH_ROAD_NAME = 36;
- /** Subbranch Rd Name key e.g. Alley 8. */
- public static final int SUBBRANCH_ROAD_NAME = 37;
- /** Premodifier key e.g. Old. */
- public static final int STREET_NAME_PRE_MODIFIER = 38;
- /** Postmodifier key e.g. Service. */
- public static final int STREET_NAME_POST_MODIFIER = 39;
- /** Script key e.g. Latn. */
- public static final int SCRIPT = 128;
-
- /** private constructor */
- private CivicLocationKeys() {}
-}
-
diff --git a/wifi/java/android/net/wifi/rtt/IRttCallback.aidl b/wifi/java/android/net/wifi/rtt/IRttCallback.aidl
deleted file mode 100644
index 578dd1e94997..000000000000
--- a/wifi/java/android/net/wifi/rtt/IRttCallback.aidl
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2017 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.rtt;
-
-import android.net.wifi.rtt.RangingResult;
-
-/**
- * Interface for RTT result callback.
- *
- * @hide
- */
-oneway interface IRttCallback
-{
- /**
- * Service to manager callback indicating failure.
- */
- void onRangingFailure(int status);
-
- /**
- * Service to manager callback indicating success and providing results.
- */
- void onRangingResults(in List<RangingResult> results);
-}
diff --git a/wifi/java/android/net/wifi/rtt/IWifiRttManager.aidl b/wifi/java/android/net/wifi/rtt/IWifiRttManager.aidl
deleted file mode 100644
index 7c92a6b6bdba..000000000000
--- a/wifi/java/android/net/wifi/rtt/IWifiRttManager.aidl
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2017 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.rtt;
-
-import android.os.WorkSource;
-
-import android.net.wifi.rtt.IRttCallback;
-import android.net.wifi.rtt.RangingRequest;
-
-/**
- * @hide
- */
-interface IWifiRttManager
-{
- boolean isAvailable();
- void startRanging(in IBinder binder, in String callingPackage, in String callingFeatureId,
- in WorkSource workSource, in RangingRequest request, in IRttCallback callback);
- void cancelRanging(in WorkSource workSource);
-}
diff --git a/wifi/java/android/net/wifi/rtt/RangingRequest.java b/wifi/java/android/net/wifi/rtt/RangingRequest.java
deleted file mode 100644
index 318efa61a110..000000000000
--- a/wifi/java/android/net/wifi/rtt/RangingRequest.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * Copyright (C) 2017 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.rtt;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.net.wifi.ScanResult;
-import android.net.wifi.aware.AttachCallback;
-import android.net.wifi.aware.DiscoverySessionCallback;
-import android.net.wifi.aware.IdentityChangedListener;
-import android.net.wifi.aware.PeerHandle;
-import android.net.wifi.aware.WifiAwareManager;
-import android.os.Handler;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.StringJoiner;
-
-/**
- * Defines the ranging request to other devices. The ranging request is built using
- * {@link RangingRequest.Builder}.
- * A ranging request is executed using
- * {@link WifiRttManager#startRanging(RangingRequest, java.util.concurrent.Executor, RangingResultCallback)}.
- * <p>
- * The ranging request is a batch request - specifying a set of devices (specified using
- * {@link RangingRequest.Builder#addAccessPoint(ScanResult)} and
- * {@link RangingRequest.Builder#addAccessPoints(List)}).
- */
-public final class RangingRequest implements Parcelable {
- private static final int MAX_PEERS = 10;
-
- /**
- * Returns the maximum number of peers to range which can be specified in a single {@code
- * RangingRequest}. The limit applies no matter how the peers are added to the request, e.g.
- * through {@link RangingRequest.Builder#addAccessPoint(ScanResult)} or
- * {@link RangingRequest.Builder#addAccessPoints(List)}.
- *
- * @return Maximum number of peers.
- */
- public static int getMaxPeers() {
- return MAX_PEERS;
- }
-
- /** @hide */
- public final List<ResponderConfig> mRttPeers;
-
- /** @hide */
- private RangingRequest(List<ResponderConfig> rttPeers) {
- mRttPeers = rttPeers;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeList(mRttPeers);
- }
-
- public static final @android.annotation.NonNull Creator<RangingRequest> CREATOR = new Creator<RangingRequest>() {
- @Override
- public RangingRequest[] newArray(int size) {
- return new RangingRequest[size];
- }
-
- @Override
- public RangingRequest createFromParcel(Parcel in) {
- return new RangingRequest(in.readArrayList(null));
- }
- };
-
- /** @hide */
- @Override
- public String toString() {
- StringJoiner sj = new StringJoiner(", ", "RangingRequest: mRttPeers=[", "]");
- for (ResponderConfig rc : mRttPeers) {
- sj.add(rc.toString());
- }
- return sj.toString();
- }
-
- /** @hide */
- public void enforceValidity(boolean awareSupported) {
- if (mRttPeers.size() > MAX_PEERS) {
- throw new IllegalArgumentException(
- "Ranging to too many peers requested. Use getMaxPeers() API to get limit.");
- }
-
- for (ResponderConfig peer: mRttPeers) {
- if (!peer.isValid(awareSupported)) {
- throw new IllegalArgumentException("Invalid Responder specification");
- }
- }
- }
-
- /**
- * Builder class used to construct {@link RangingRequest} objects.
- */
- public static final class Builder {
- private List<ResponderConfig> mRttPeers = new ArrayList<>();
-
- /**
- * Add the device specified by the {@link ScanResult} to the list of devices with
- * which to measure range. The total number of peers added to a request cannot exceed the
- * limit specified by {@link #getMaxPeers()}.
- * <p>
- * Ranging may not be supported if the Access Point does not support IEEE 802.11mc. Use
- * {@link ScanResult#is80211mcResponder()} to verify the Access Point's capabilities. If
- * not supported the result status will be
- * {@link RangingResult#STATUS_RESPONDER_DOES_NOT_SUPPORT_IEEE80211MC}.
- *
- * @param apInfo Information of an Access Point (AP) obtained in a Scan Result.
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder addAccessPoint(@NonNull ScanResult apInfo) {
- if (apInfo == null) {
- throw new IllegalArgumentException("Null ScanResult!");
- }
- return addResponder(ResponderConfig.fromScanResult(apInfo));
- }
-
- /**
- * Add the devices specified by the {@link ScanResult}s to the list of devices with
- * which to measure range. The total number of peers added to a request cannot exceed the
- * limit specified by {@link #getMaxPeers()}.
- * <p>
- * Ranging may not be supported if the Access Point does not support IEEE 802.11mc. Use
- * {@link ScanResult#is80211mcResponder()} to verify the Access Point's capabilities. If
- * not supported the result status will be
- * {@link RangingResult#STATUS_RESPONDER_DOES_NOT_SUPPORT_IEEE80211MC}.
- *
- * @param apInfos Information of an Access Points (APs) obtained in a Scan Result.
- * @return The builder to facilitate chaining
- * {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder addAccessPoints(@NonNull List<ScanResult> apInfos) {
- if (apInfos == null) {
- throw new IllegalArgumentException("Null list of ScanResults!");
- }
- for (ScanResult scanResult : apInfos) {
- addAccessPoint(scanResult);
- }
- return this;
- }
-
- /**
- * Add the device specified by the {@code peerMacAddress} to the list of devices with
- * which to measure range.
- * <p>
- * The MAC address may be obtained out-of-band from a peer Wi-Fi Aware device. A Wi-Fi
- * Aware device may obtain its MAC address using the {@link IdentityChangedListener}
- * provided to
- * {@link WifiAwareManager#attach(AttachCallback, IdentityChangedListener, Handler)}.
- * <p>
- * Note: in order to use this API the device must support Wi-Fi Aware
- * {@link android.net.wifi.aware}. The peer device which is being ranged to must be
- * configured to publish a service (with any name) with:
- * <li>Type {@link android.net.wifi.aware.PublishConfig#PUBLISH_TYPE_UNSOLICITED}.
- * <li>Ranging enabled
- * {@link android.net.wifi.aware.PublishConfig.Builder#setRangingEnabled(boolean)}.
- *
- * @param peerMacAddress The MAC address of the Wi-Fi Aware peer.
- * @return The builder, to facilitate chaining {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder addWifiAwarePeer(@NonNull MacAddress peerMacAddress) {
- if (peerMacAddress == null) {
- throw new IllegalArgumentException("Null peer MAC address");
- }
- return addResponder(
- ResponderConfig.fromWifiAwarePeerMacAddressWithDefaults(peerMacAddress));
- }
-
- /**
- * Add a device specified by a {@link PeerHandle} to the list of devices with which to
- * measure range.
- * <p>
- * The {@link PeerHandle} may be obtained as part of the Wi-Fi Aware discovery process. E.g.
- * using {@link DiscoverySessionCallback#onServiceDiscovered(PeerHandle, byte[], List)}.
- * <p>
- * Note: in order to use this API the device must support Wi-Fi Aware
- * {@link android.net.wifi.aware}. The peer device which is being ranged to must be
- * configured to publish a service (with any name) with:
- * <li>Type {@link android.net.wifi.aware.PublishConfig#PUBLISH_TYPE_UNSOLICITED}.
- * <li>Ranging enabled
- * {@link android.net.wifi.aware.PublishConfig.Builder#setRangingEnabled(boolean)}.
- *
- * @param peerHandle The peer handler of the peer Wi-Fi Aware device.
- * @return The builder, to facilitate chaining {@code builder.setXXX(..).setXXX(..)}.
- */
- public Builder addWifiAwarePeer(@NonNull PeerHandle peerHandle) {
- if (peerHandle == null) {
- throw new IllegalArgumentException("Null peer handler (identifier)");
- }
-
- return addResponder(ResponderConfig.fromWifiAwarePeerHandleWithDefaults(peerHandle));
- }
-
- /**
- * Add the Responder device specified by the {@link ResponderConfig} to the list of devices
- * with which to measure range. The total number of peers added to the request cannot exceed
- * the limit specified by {@link #getMaxPeers()}.
- *
- * @param responder Information on the RTT Responder.
- * @return The builder, to facilitate chaining {@code builder.setXXX(..).setXXX(..)}.
- *
- * @hide
- */
- @SystemApi
- public Builder addResponder(@NonNull ResponderConfig responder) {
- if (responder == null) {
- throw new IllegalArgumentException("Null Responder!");
- }
-
- mRttPeers.add(responder);
- return this;
- }
-
- /**
- * Build {@link RangingRequest} given the current configurations made on the
- * builder.
- */
- public RangingRequest build() {
- return new RangingRequest(mRttPeers);
- }
- }
-
- @Override
- public boolean equals(@Nullable Object o) {
- if (this == o) {
- return true;
- }
-
- if (!(o instanceof RangingRequest)) {
- return false;
- }
-
- RangingRequest lhs = (RangingRequest) o;
-
- return mRttPeers.size() == lhs.mRttPeers.size() && mRttPeers.containsAll(lhs.mRttPeers);
- }
-
- @Override
- public int hashCode() {
- return mRttPeers.hashCode();
- }
-}
diff --git a/wifi/java/android/net/wifi/rtt/RangingResult.java b/wifi/java/android/net/wifi/rtt/RangingResult.java
deleted file mode 100644
index a065bbc4b656..000000000000
--- a/wifi/java/android/net/wifi/rtt/RangingResult.java
+++ /dev/null
@@ -1,438 +0,0 @@
-/*
- * Copyright (C) 2017 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.rtt;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.net.wifi.aware.PeerHandle;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * Ranging result for a request started by
- * {@link WifiRttManager#startRanging(RangingRequest, java.util.concurrent.Executor, RangingResultCallback)}.
- * Results are returned in {@link RangingResultCallback#onRangingResults(List)}.
- * <p>
- * A ranging result is the distance measurement result for a single device specified in the
- * {@link RangingRequest}.
- */
-public final class RangingResult implements Parcelable {
- private static final String TAG = "RangingResult";
- private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
-
- /** @hide */
- @IntDef({STATUS_SUCCESS, STATUS_FAIL, STATUS_RESPONDER_DOES_NOT_SUPPORT_IEEE80211MC})
- @Retention(RetentionPolicy.SOURCE)
- public @interface RangeResultStatus {
- }
-
- /**
- * Individual range request status, {@link #getStatus()}. Indicates ranging operation was
- * successful and distance value is valid.
- */
- public static final int STATUS_SUCCESS = 0;
-
- /**
- * Individual range request status, {@link #getStatus()}. Indicates ranging operation failed
- * and the distance value is invalid.
- */
- public static final int STATUS_FAIL = 1;
-
- /**
- * Individual range request status, {@link #getStatus()}. Indicates that the ranging operation
- * failed because the specified peer does not support IEEE 802.11mc RTT operations. Support by
- * an Access Point can be confirmed using
- * {@link android.net.wifi.ScanResult#is80211mcResponder()}.
- * <p>
- * On such a failure, the individual result fields of {@link RangingResult} such as
- * {@link RangingResult#getDistanceMm()} are invalid.
- */
- public static final int STATUS_RESPONDER_DOES_NOT_SUPPORT_IEEE80211MC = 2;
-
- private final int mStatus;
- private final MacAddress mMac;
- private final PeerHandle mPeerHandle;
- private final int mDistanceMm;
- private final int mDistanceStdDevMm;
- private final int mRssi;
- private final int mNumAttemptedMeasurements;
- private final int mNumSuccessfulMeasurements;
- private final byte[] mLci;
- private final byte[] mLcr;
- private final ResponderLocation mResponderLocation;
- private final long mTimestamp;
-
- /** @hide */
- public RangingResult(@RangeResultStatus int status, @NonNull MacAddress mac, int distanceMm,
- int distanceStdDevMm, int rssi, int numAttemptedMeasurements,
- int numSuccessfulMeasurements, byte[] lci, byte[] lcr,
- ResponderLocation responderLocation, long timestamp) {
- mStatus = status;
- mMac = mac;
- mPeerHandle = null;
- mDistanceMm = distanceMm;
- mDistanceStdDevMm = distanceStdDevMm;
- mRssi = rssi;
- mNumAttemptedMeasurements = numAttemptedMeasurements;
- mNumSuccessfulMeasurements = numSuccessfulMeasurements;
- mLci = lci == null ? EMPTY_BYTE_ARRAY : lci;
- mLcr = lcr == null ? EMPTY_BYTE_ARRAY : lcr;
- mResponderLocation = responderLocation;
- mTimestamp = timestamp;
- }
-
- /** @hide */
- public RangingResult(@RangeResultStatus int status, PeerHandle peerHandle, int distanceMm,
- int distanceStdDevMm, int rssi, int numAttemptedMeasurements,
- int numSuccessfulMeasurements, byte[] lci, byte[] lcr,
- ResponderLocation responderLocation, long timestamp) {
- mStatus = status;
- mMac = null;
- mPeerHandle = peerHandle;
- mDistanceMm = distanceMm;
- mDistanceStdDevMm = distanceStdDevMm;
- mRssi = rssi;
- mNumAttemptedMeasurements = numAttemptedMeasurements;
- mNumSuccessfulMeasurements = numSuccessfulMeasurements;
- mLci = lci == null ? EMPTY_BYTE_ARRAY : lci;
- mLcr = lcr == null ? EMPTY_BYTE_ARRAY : lcr;
- mResponderLocation = responderLocation;
- mTimestamp = timestamp;
- }
-
- /**
- * @return The status of ranging measurement: {@link #STATUS_SUCCESS} in case of success, and
- * {@link #STATUS_FAIL} in case of failure.
- */
- @RangeResultStatus
- public int getStatus() {
- return mStatus;
- }
-
- /**
- * @return The MAC address of the device whose range measurement was requested. Will correspond
- * to the MAC address of the device in the {@link RangingRequest}.
- * <p>
- * Will return a {@code null} for results corresponding to requests issued using a {@code
- * PeerHandle}, i.e. using the {@link RangingRequest.Builder#addWifiAwarePeer(PeerHandle)} API.
- */
- @Nullable
- public MacAddress getMacAddress() {
- return mMac;
- }
-
- /**
- * @return The PeerHandle of the device whose reange measurement was requested. Will correspond
- * to the PeerHandle of the devices requested using
- * {@link RangingRequest.Builder#addWifiAwarePeer(PeerHandle)}.
- * <p>
- * Will return a {@code null} for results corresponding to requests issued using a MAC address.
- */
- @Nullable public PeerHandle getPeerHandle() {
- return mPeerHandle;
- }
-
- /**
- * @return The distance (in mm) to the device specified by {@link #getMacAddress()} or
- * {@link #getPeerHandle()}.
- * <p>
- * Note: the measured distance may be negative for very close devices.
- * <p>
- * Only valid if {@link #getStatus()} returns {@link #STATUS_SUCCESS}, otherwise will throw an
- * exception.
- */
- public int getDistanceMm() {
- if (mStatus != STATUS_SUCCESS) {
- throw new IllegalStateException(
- "getDistanceMm(): invoked on an invalid result: getStatus()=" + mStatus);
- }
- return mDistanceMm;
- }
-
- /**
- * @return The standard deviation of the measured distance (in mm) to the device specified by
- * {@link #getMacAddress()} or {@link #getPeerHandle()}. The standard deviation is calculated
- * over the measurements executed in a single RTT burst. The number of measurements is returned
- * by {@link #getNumSuccessfulMeasurements()} - 0 successful measurements indicate that the
- * standard deviation is not valid (a valid standard deviation requires at least 2 data points).
- * <p>
- * Only valid if {@link #getStatus()} returns {@link #STATUS_SUCCESS}, otherwise will throw an
- * exception.
- */
- public int getDistanceStdDevMm() {
- if (mStatus != STATUS_SUCCESS) {
- throw new IllegalStateException(
- "getDistanceStdDevMm(): invoked on an invalid result: getStatus()=" + mStatus);
- }
- return mDistanceStdDevMm;
- }
-
- /**
- * @return The average RSSI, in units of dBm, observed during the RTT measurement.
- * <p>
- * Only valid if {@link #getStatus()} returns {@link #STATUS_SUCCESS}, otherwise will throw an
- * exception.
- */
- public int getRssi() {
- if (mStatus != STATUS_SUCCESS) {
- throw new IllegalStateException(
- "getRssi(): invoked on an invalid result: getStatus()=" + mStatus);
- }
- return mRssi;
- }
-
- /**
- * @return The number of attempted measurements used in the RTT exchange resulting in this set
- * of results. The number of successful measurements is returned by
- * {@link #getNumSuccessfulMeasurements()} which at most, if there are no errors, will be 1 less
- * that the number of attempted measurements.
- * <p>
- * Only valid if {@link #getStatus()} returns {@link #STATUS_SUCCESS}, otherwise will throw an
- * exception.
- */
- public int getNumAttemptedMeasurements() {
- if (mStatus != STATUS_SUCCESS) {
- throw new IllegalStateException(
- "getNumAttemptedMeasurements(): invoked on an invalid result: getStatus()="
- + mStatus);
- }
- return mNumAttemptedMeasurements;
- }
-
- /**
- * @return The number of successful measurements used to calculate the distance and standard
- * deviation. If the number of successful measurements if 1 then then standard deviation,
- * returned by {@link #getDistanceStdDevMm()}, is not valid (a 0 is returned for the standard
- * deviation).
- * <p>
- * The total number of measurement attempts is returned by
- * {@link #getNumAttemptedMeasurements()}. The number of successful measurements will be at
- * most 1 less then the number of attempted measurements.
- * <p>
- * Only valid if {@link #getStatus()} returns {@link #STATUS_SUCCESS}, otherwise will throw an
- * exception.
- */
- public int getNumSuccessfulMeasurements() {
- if (mStatus != STATUS_SUCCESS) {
- throw new IllegalStateException(
- "getNumSuccessfulMeasurements(): invoked on an invalid result: getStatus()="
- + mStatus);
- }
- return mNumSuccessfulMeasurements;
- }
-
- /**
- * @return The unverified responder location represented as {@link ResponderLocation} which
- * captures location information the responder is programmed to broadcast. The responder
- * location is referred to as unverified, because we are relying on the device/site
- * administrator to correctly configure its location data.
- * <p>
- * Will return a {@code null} when the location information cannot be parsed.
- * <p>
- * Only valid if {@link #getStatus()} returns {@link #STATUS_SUCCESS}, otherwise will throw an
- * exception.
- */
- @Nullable
- public ResponderLocation getUnverifiedResponderLocation() {
- if (mStatus != STATUS_SUCCESS) {
- throw new IllegalStateException(
- "getUnverifiedResponderLocation(): invoked on an invalid result: getStatus()="
- + mStatus);
- }
- return mResponderLocation;
- }
-
- /**
- * @return The Location Configuration Information (LCI) as self-reported by the peer. The format
- * is specified in the IEEE 802.11-2016 specifications, section 9.4.2.22.10.
- * <p>
- * Note: the information is NOT validated - use with caution. Consider validating it with
- * other sources of information before using it.
- *
- * @hide
- */
- @SystemApi
- @NonNull
- public byte[] getLci() {
- if (mStatus != STATUS_SUCCESS) {
- throw new IllegalStateException(
- "getLci(): invoked on an invalid result: getStatus()=" + mStatus);
- }
- return mLci;
- }
-
- /**
- * @return The Location Civic report (LCR) as self-reported by the peer. The format
- * is specified in the IEEE 802.11-2016 specifications, section 9.4.2.22.13.
- * <p>
- * Note: the information is NOT validated - use with caution. Consider validating it with
- * other sources of information before using it.
- *
- * @hide
- */
- @SystemApi
- @NonNull
- public byte[] getLcr() {
- if (mStatus != STATUS_SUCCESS) {
- throw new IllegalStateException(
- "getReportedLocationCivic(): invoked on an invalid result: getStatus()="
- + mStatus);
- }
- return mLcr;
- }
-
- /**
- * @return The timestamp at which the ranging operation was performed. The timestamp is in
- * milliseconds since boot, including time spent in sleep, corresponding to values provided by
- * {@link android.os.SystemClock#elapsedRealtime()}.
- * <p>
- * Only valid if {@link #getStatus()} returns {@link #STATUS_SUCCESS}, otherwise will throw an
- * exception.
- */
- public long getRangingTimestampMillis() {
- if (mStatus != STATUS_SUCCESS) {
- throw new IllegalStateException(
- "getRangingTimestampMillis(): invoked on an invalid result: getStatus()="
- + mStatus);
- }
- return mTimestamp;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mStatus);
- if (mMac == null) {
- dest.writeBoolean(false);
- } else {
- dest.writeBoolean(true);
- mMac.writeToParcel(dest, flags);
- }
- if (mPeerHandle == null) {
- dest.writeBoolean(false);
- } else {
- dest.writeBoolean(true);
- dest.writeInt(mPeerHandle.peerId);
- }
- dest.writeInt(mDistanceMm);
- dest.writeInt(mDistanceStdDevMm);
- dest.writeInt(mRssi);
- dest.writeInt(mNumAttemptedMeasurements);
- dest.writeInt(mNumSuccessfulMeasurements);
- dest.writeByteArray(mLci);
- dest.writeByteArray(mLcr);
- dest.writeParcelable(mResponderLocation, flags);
- dest.writeLong(mTimestamp);
- }
-
- public static final @android.annotation.NonNull Creator<RangingResult> CREATOR = new Creator<RangingResult>() {
- @Override
- public RangingResult[] newArray(int size) {
- return new RangingResult[size];
- }
-
- @Override
- public RangingResult createFromParcel(Parcel in) {
- int status = in.readInt();
- boolean macAddressPresent = in.readBoolean();
- MacAddress mac = null;
- if (macAddressPresent) {
- mac = MacAddress.CREATOR.createFromParcel(in);
- }
- boolean peerHandlePresent = in.readBoolean();
- PeerHandle peerHandle = null;
- if (peerHandlePresent) {
- peerHandle = new PeerHandle(in.readInt());
- }
- int distanceMm = in.readInt();
- int distanceStdDevMm = in.readInt();
- int rssi = in.readInt();
- int numAttemptedMeasurements = in.readInt();
- int numSuccessfulMeasurements = in.readInt();
- byte[] lci = in.createByteArray();
- byte[] lcr = in.createByteArray();
- ResponderLocation responderLocation =
- in.readParcelable(this.getClass().getClassLoader());
- long timestamp = in.readLong();
- if (peerHandlePresent) {
- return new RangingResult(status, peerHandle, distanceMm, distanceStdDevMm, rssi,
- numAttemptedMeasurements, numSuccessfulMeasurements, lci, lcr,
- responderLocation, timestamp);
- } else {
- return new RangingResult(status, mac, distanceMm, distanceStdDevMm, rssi,
- numAttemptedMeasurements, numSuccessfulMeasurements, lci, lcr,
- responderLocation, timestamp);
- }
- }
- };
-
- /** @hide */
- @Override
- public String toString() {
- return new StringBuilder("RangingResult: [status=").append(mStatus).append(", mac=").append(
- mMac).append(", peerHandle=").append(
- mPeerHandle == null ? "<null>" : mPeerHandle.peerId).append(", distanceMm=").append(
- mDistanceMm).append(", distanceStdDevMm=").append(mDistanceStdDevMm).append(
- ", rssi=").append(mRssi).append(", numAttemptedMeasurements=").append(
- mNumAttemptedMeasurements).append(", numSuccessfulMeasurements=").append(
- mNumSuccessfulMeasurements).append(", lci=").append(mLci).append(", lcr=").append(
- mLcr).append(", responderLocation=").append(mResponderLocation)
- .append(", timestamp=").append(mTimestamp).append("]").toString();
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
-
- if (!(o instanceof RangingResult)) {
- return false;
- }
-
- RangingResult lhs = (RangingResult) o;
-
- return mStatus == lhs.mStatus && Objects.equals(mMac, lhs.mMac) && Objects.equals(
- mPeerHandle, lhs.mPeerHandle) && mDistanceMm == lhs.mDistanceMm
- && mDistanceStdDevMm == lhs.mDistanceStdDevMm && mRssi == lhs.mRssi
- && mNumAttemptedMeasurements == lhs.mNumAttemptedMeasurements
- && mNumSuccessfulMeasurements == lhs.mNumSuccessfulMeasurements
- && Arrays.equals(mLci, lhs.mLci) && Arrays.equals(mLcr, lhs.mLcr)
- && mTimestamp == lhs.mTimestamp
- && Objects.equals(mResponderLocation, lhs.mResponderLocation);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mStatus, mMac, mPeerHandle, mDistanceMm, mDistanceStdDevMm, mRssi,
- mNumAttemptedMeasurements, mNumSuccessfulMeasurements, mLci, mLcr,
- mResponderLocation, mTimestamp);
- }
-}
diff --git a/wifi/java/android/net/wifi/rtt/RangingResultCallback.java b/wifi/java/android/net/wifi/rtt/RangingResultCallback.java
deleted file mode 100644
index fa7d79ec0a8c..000000000000
--- a/wifi/java/android/net/wifi/rtt/RangingResultCallback.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2017 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.rtt;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.List;
-
-/**
- * Base class for ranging result callbacks. Should be extended by applications and set when calling
- * {@link WifiRttManager#startRanging(RangingRequest, java.util.concurrent.Executor, RangingResultCallback)}.
- * If the ranging operation fails in whole (not attempted) then {@link #onRangingFailure(int)}
- * will be called with a failure code. If the ranging operation is performed for each of the
- * requested peers then the {@link #onRangingResults(List)} will be called with the set of
- * results (@link {@link RangingResult}, each of which has its own success/failure code
- * {@link RangingResult#getStatus()}.
- */
-public abstract class RangingResultCallback {
- /** @hide */
- @IntDef({STATUS_CODE_FAIL, STATUS_CODE_FAIL_RTT_NOT_AVAILABLE})
- @Retention(RetentionPolicy.SOURCE)
- public @interface RangingOperationStatus {
- }
-
- /**
- * A failure code for the whole ranging request operation. Indicates a failure.
- */
- public static final int STATUS_CODE_FAIL = 1;
-
- /**
- * A failure code for the whole ranging request operation. Indicates that the request failed due
- * to RTT not being available - e.g. Wi-Fi was disabled. Use the
- * {@link WifiRttManager#isAvailable()} and {@link WifiRttManager#ACTION_WIFI_RTT_STATE_CHANGED}
- * to track RTT availability.
- */
- public static final int STATUS_CODE_FAIL_RTT_NOT_AVAILABLE = 2;
-
- /**
- * Called when a ranging operation failed in whole - i.e. no ranging operation to any of the
- * devices specified in the request was attempted.
- *
- * @param code A status code indicating the type of failure.
- */
- public abstract void onRangingFailure(@RangingOperationStatus int code);
-
- /**
- * Called when a ranging operation was executed. The list of results corresponds to devices
- * specified in the ranging request.
- *
- * @param results List of range measurements, one per requested device.
- */
- public abstract void onRangingResults(@NonNull List<RangingResult> results);
-}
diff --git a/wifi/java/android/net/wifi/rtt/ResponderConfig.java b/wifi/java/android/net/wifi/rtt/ResponderConfig.java
deleted file mode 100644
index be4eeccd0c31..000000000000
--- a/wifi/java/android/net/wifi/rtt/ResponderConfig.java
+++ /dev/null
@@ -1,514 +0,0 @@
-/*
- * Copyright (C) 2017 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.rtt;
-
-import static android.net.wifi.ScanResult.InformationElement.EID_EXTENSION_PRESENT;
-import static android.net.wifi.ScanResult.InformationElement.EID_EXT_HE_CAPABILITIES;
-import static android.net.wifi.ScanResult.InformationElement.EID_HT_CAPABILITIES;
-import static android.net.wifi.ScanResult.InformationElement.EID_VHT_CAPABILITIES;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SystemApi;
-import android.net.MacAddress;
-import android.net.wifi.ScanResult;
-import android.net.wifi.aware.PeerHandle;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
-
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.util.Objects;
-
-/**
- * Defines the configuration of an IEEE 802.11mc Responder. The Responder may be an Access Point
- * (AP), a Wi-Fi Aware device, or a manually configured Responder.
- * <p>
- * A Responder configuration may be constructed from a {@link ScanResult} or manually (with the
- * data obtained out-of-band from a peer).
- *
- * @hide
- */
-@SystemApi
-public final class ResponderConfig implements Parcelable {
- private static final String TAG = "ResponderConfig";
- private static final int AWARE_BAND_2_DISCOVERY_CHANNEL = 2437;
-
- /** @hide */
- @IntDef({RESPONDER_AP, RESPONDER_STA, RESPONDER_P2P_GO, RESPONDER_P2P_CLIENT, RESPONDER_AWARE})
- @Retention(RetentionPolicy.SOURCE)
- public @interface ResponderType {
- }
-
- /**
- * Responder is an AP.
- */
- public static final int RESPONDER_AP = 0;
- /**
- * Responder is a STA.
- */
- public static final int RESPONDER_STA = 1;
- /**
- * Responder is a Wi-Fi Direct Group Owner (GO).
- */
- public static final int RESPONDER_P2P_GO = 2;
- /**
- * Responder is a Wi-Fi Direct Group Client.
- */
- public static final int RESPONDER_P2P_CLIENT = 3;
- /**
- * Responder is a Wi-Fi Aware device.
- */
- public static final int RESPONDER_AWARE = 4;
-
-
- /** @hide */
- @IntDef({
- CHANNEL_WIDTH_20MHZ, CHANNEL_WIDTH_40MHZ, CHANNEL_WIDTH_80MHZ, CHANNEL_WIDTH_160MHZ,
- CHANNEL_WIDTH_80MHZ_PLUS_MHZ})
- @Retention(RetentionPolicy.SOURCE)
- public @interface ChannelWidth {
- }
-
- /**
- * Channel bandwidth is 20 MHZ
- */
- public static final int CHANNEL_WIDTH_20MHZ = 0;
- /**
- * Channel bandwidth is 40 MHZ
- */
- public static final int CHANNEL_WIDTH_40MHZ = 1;
- /**
- * Channel bandwidth is 80 MHZ
- */
- public static final int CHANNEL_WIDTH_80MHZ = 2;
- /**
- * Channel bandwidth is 160 MHZ
- */
- public static final int CHANNEL_WIDTH_160MHZ = 3;
- /**
- * Channel bandwidth is 160 MHZ, but 80MHZ + 80MHZ
- */
- public static final int CHANNEL_WIDTH_80MHZ_PLUS_MHZ = 4;
-
- /** @hide */
- @IntDef({PREAMBLE_LEGACY, PREAMBLE_HT, PREAMBLE_VHT, PREAMBLE_HE})
- @Retention(RetentionPolicy.SOURCE)
- public @interface PreambleType {
- }
-
- /**
- * Preamble type: Legacy.
- */
- public static final int PREAMBLE_LEGACY = 0;
-
- /**
- * Preamble type: HT.
- */
- public static final int PREAMBLE_HT = 1;
-
- /**
- * Preamble type: VHT.
- */
- public static final int PREAMBLE_VHT = 2;
-
- /**
- * Preamble type: HE.
- */
- public static final int PREAMBLE_HE = 3;
-
- /**
- * The MAC address of the Responder. Will be null if a Wi-Fi Aware peer identifier (the
- * peerHandle field) ise used to identify the Responder.
- */
- public final MacAddress macAddress;
-
- /**
- * The peer identifier of a Wi-Fi Aware Responder. Will be null if a MAC Address (the macAddress
- * field) is used to identify the Responder.
- */
- public final PeerHandle peerHandle;
-
- /**
- * The device type of the Responder.
- */
- public final int responderType;
-
- /**
- * Indicates whether the Responder device supports IEEE 802.11mc.
- */
- public final boolean supports80211mc;
-
- /**
- * Responder channel bandwidth, specified using {@link ChannelWidth}.
- */
- public final int channelWidth;
-
- /**
- * The primary 20 MHz frequency (in MHz) of the channel of the Responder.
- */
- public final int frequency;
-
- /**
- * Not used if the {@link #channelWidth} is 20 MHz. If the Responder uses 40, 80 or 160 MHz,
- * this is the center frequency (in MHz), if the Responder uses 80 + 80 MHz, this is the
- * center frequency of the first segment (in MHz).
- */
- public final int centerFreq0;
-
- /**
- * Only used if the {@link #channelWidth} is 80 + 80 MHz. If the Responder uses 80 + 80 MHz,
- * this is the center frequency of the second segment (in MHz).
- */
- public final int centerFreq1;
-
- /**
- * The preamble used by the Responder, specified using {@link PreambleType}.
- */
- public final int preamble;
-
- /**
- * Constructs Responder configuration, using a MAC address to identify the Responder.
- *
- * @param macAddress The MAC address of the Responder.
- * @param responderType The type of the responder device, specified using
- * {@link ResponderType}.
- * @param supports80211mc Indicates whether the responder supports IEEE 802.11mc.
- * @param channelWidth Responder channel bandwidth, specified using {@link ChannelWidth}.
- * @param frequency The primary 20 MHz frequency (in MHz) of the channel of the Responder.
- * @param centerFreq0 Not used if the {@code channelWidth} is 20 MHz. If the Responder uses
- * 40, 80 or 160 MHz, this is the center frequency (in MHz), if the
- * Responder uses 80 + 80 MHz, this is the center frequency of the first
- * segment (in MHz).
- * @param centerFreq1 Only used if the {@code channelWidth} is 80 + 80 MHz. If the
- * Responder
- * uses 80 + 80 MHz, this is the center frequency of the second segment
- * (in
- * MHz).
- * @param preamble The preamble used by the Responder, specified using
- * {@link PreambleType}.
- */
- public ResponderConfig(@NonNull MacAddress macAddress, @ResponderType int responderType,
- boolean supports80211mc, @ChannelWidth int channelWidth, int frequency, int centerFreq0,
- int centerFreq1, @PreambleType int preamble) {
- if (macAddress == null) {
- throw new IllegalArgumentException(
- "Invalid ResponderConfig - must specify a MAC address");
- }
- this.macAddress = macAddress;
- this.peerHandle = null;
- this.responderType = responderType;
- this.supports80211mc = supports80211mc;
- this.channelWidth = channelWidth;
- this.frequency = frequency;
- this.centerFreq0 = centerFreq0;
- this.centerFreq1 = centerFreq1;
- this.preamble = preamble;
- }
-
- /**
- * Constructs Responder configuration, using a Wi-Fi Aware PeerHandle to identify the Responder.
- *
- * @param peerHandle The Wi-Fi Aware peer identifier of the Responder.
- * @param responderType The type of the responder device, specified using
- * {@link ResponderType}.
- * @param supports80211mc Indicates whether the responder supports IEEE 802.11mc.
- * @param channelWidth Responder channel bandwidth, specified using {@link ChannelWidth}.
- * @param frequency The primary 20 MHz frequency (in MHz) of the channel of the Responder.
- * @param centerFreq0 Not used if the {@code channelWidth} is 20 MHz. If the Responder uses
- * 40, 80 or 160 MHz, this is the center frequency (in MHz), if the
- * Responder uses 80 + 80 MHz, this is the center frequency of the first
- * segment (in MHz).
- * @param centerFreq1 Only used if the {@code channelWidth} is 80 + 80 MHz. If the
- * Responder
- * uses 80 + 80 MHz, this is the center frequency of the second segment
- * (in
- * MHz).
- * @param preamble The preamble used by the Responder, specified using
- * {@link PreambleType}.
- */
- public ResponderConfig(@NonNull PeerHandle peerHandle, @ResponderType int responderType,
- boolean supports80211mc, @ChannelWidth int channelWidth, int frequency, int centerFreq0,
- int centerFreq1, @PreambleType int preamble) {
- this.macAddress = null;
- this.peerHandle = peerHandle;
- this.responderType = responderType;
- this.supports80211mc = supports80211mc;
- this.channelWidth = channelWidth;
- this.frequency = frequency;
- this.centerFreq0 = centerFreq0;
- this.centerFreq1 = centerFreq1;
- this.preamble = preamble;
- }
-
- /**
- * Constructs Responder configuration. This is an internal-only constructor which specifies both
- * a MAC address and a Wi-Fi PeerHandle to identify the Responder.
- *
- * @param macAddress The MAC address of the Responder.
- * @param peerHandle The Wi-Fi Aware peer identifier of the Responder.
- * @param responderType The type of the responder device, specified using
- * {@link ResponderType}.
- * @param supports80211mc Indicates whether the responder supports IEEE 802.11mc.
- * @param channelWidth Responder channel bandwidth, specified using {@link ChannelWidth}.
- * @param frequency The primary 20 MHz frequency (in MHz) of the channel of the Responder.
- * @param centerFreq0 Not used if the {@code channelWidth} is 20 MHz. If the Responder uses
- * 40, 80 or 160 MHz, this is the center frequency (in MHz), if the
- * Responder uses 80 + 80 MHz, this is the center frequency of the first
- * segment (in MHz).
- * @param centerFreq1 Only used if the {@code channelWidth} is 80 + 80 MHz. If the
- * Responder
- * uses 80 + 80 MHz, this is the center frequency of the second segment
- * (in
- * MHz).
- * @param preamble The preamble used by the Responder, specified using
- * {@link PreambleType}.
- * @hide
- */
- public ResponderConfig(@NonNull MacAddress macAddress, @NonNull PeerHandle peerHandle,
- @ResponderType int responderType, boolean supports80211mc,
- @ChannelWidth int channelWidth, int frequency, int centerFreq0, int centerFreq1,
- @PreambleType int preamble) {
- this.macAddress = macAddress;
- this.peerHandle = peerHandle;
- this.responderType = responderType;
- this.supports80211mc = supports80211mc;
- this.channelWidth = channelWidth;
- this.frequency = frequency;
- this.centerFreq0 = centerFreq0;
- this.centerFreq1 = centerFreq1;
- this.preamble = preamble;
- }
-
- /**
- * Creates a Responder configuration from a {@link ScanResult} corresponding to an Access
- * Point (AP), which can be obtained from {@link android.net.wifi.WifiManager#getScanResults()}.
- */
- public static ResponderConfig fromScanResult(ScanResult scanResult) {
- MacAddress macAddress = MacAddress.fromString(scanResult.BSSID);
- int responderType = RESPONDER_AP;
- boolean supports80211mc = scanResult.is80211mcResponder();
- int channelWidth = translateScanResultChannelWidth(scanResult.channelWidth);
- int frequency = scanResult.frequency;
- int centerFreq0 = scanResult.centerFreq0;
- int centerFreq1 = scanResult.centerFreq1;
-
- int preamble;
- if (scanResult.informationElements != null && scanResult.informationElements.length != 0) {
- boolean htCapabilitiesPresent = false;
- boolean vhtCapabilitiesPresent = false;
- boolean heCapabilitiesPresent = false;
-
- for (ScanResult.InformationElement ie : scanResult.informationElements) {
- if (ie.id == EID_HT_CAPABILITIES) {
- htCapabilitiesPresent = true;
- } else if (ie.id == EID_VHT_CAPABILITIES) {
- vhtCapabilitiesPresent = true;
- } else if (ie.id == EID_EXTENSION_PRESENT && ie.idExt == EID_EXT_HE_CAPABILITIES) {
- heCapabilitiesPresent = true;
- }
- }
-
- if (heCapabilitiesPresent) {
- preamble = PREAMBLE_HE;
- } else if (vhtCapabilitiesPresent) {
- preamble = PREAMBLE_VHT;
- } else if (htCapabilitiesPresent) {
- preamble = PREAMBLE_HT;
- } else {
- preamble = PREAMBLE_LEGACY;
- }
- } else {
- Log.e(TAG, "Scan Results do not contain IEs - using backup method to select preamble");
- if (channelWidth == CHANNEL_WIDTH_80MHZ || channelWidth == CHANNEL_WIDTH_160MHZ) {
- preamble = PREAMBLE_VHT;
- } else {
- preamble = PREAMBLE_HT;
- }
- }
-
- return new ResponderConfig(macAddress, responderType, supports80211mc, channelWidth,
- frequency, centerFreq0, centerFreq1, preamble);
- }
-
- /**
- * Creates a Responder configuration from a MAC address corresponding to a Wi-Fi Aware
- * Responder. The Responder parameters are set to defaults.
- */
- public static ResponderConfig fromWifiAwarePeerMacAddressWithDefaults(MacAddress macAddress) {
- /* Note: the parameters are those of the Aware discovery channel (channel 6). A Responder
- * is expected to be brought up and available to negotiate a maximum accuracy channel
- * (i.e. Band 5 @ 80MHz). A Responder is brought up on the peer by starting an Aware
- * Unsolicited Publisher with Ranging enabled.
- */
- return new ResponderConfig(macAddress, RESPONDER_AWARE, true, CHANNEL_WIDTH_20MHZ,
- AWARE_BAND_2_DISCOVERY_CHANNEL, 0, 0, PREAMBLE_HT);
- }
-
- /**
- * Creates a Responder configuration from a {@link PeerHandle} corresponding to a Wi-Fi Aware
- * Responder. The Responder parameters are set to defaults.
- */
- public static ResponderConfig fromWifiAwarePeerHandleWithDefaults(PeerHandle peerHandle) {
- /* Note: the parameters are those of the Aware discovery channel (channel 6). A Responder
- * is expected to be brought up and available to negotiate a maximum accuracy channel
- * (i.e. Band 5 @ 80MHz). A Responder is brought up on the peer by starting an Aware
- * Unsolicited Publisher with Ranging enabled.
- */
- return new ResponderConfig(peerHandle, RESPONDER_AWARE, true, CHANNEL_WIDTH_20MHZ,
- AWARE_BAND_2_DISCOVERY_CHANNEL, 0, 0, PREAMBLE_HT);
- }
-
- /**
- * Check whether the Responder configuration is valid.
- *
- * @return true if valid, false otherwise.
- * @hide
- */
- public boolean isValid(boolean awareSupported) {
- if (macAddress == null && peerHandle == null || macAddress != null && peerHandle != null) {
- return false;
- }
- if (!awareSupported && responderType == RESPONDER_AWARE) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- if (macAddress == null) {
- dest.writeBoolean(false);
- } else {
- dest.writeBoolean(true);
- macAddress.writeToParcel(dest, flags);
- }
- if (peerHandle == null) {
- dest.writeBoolean(false);
- } else {
- dest.writeBoolean(true);
- dest.writeInt(peerHandle.peerId);
- }
- dest.writeInt(responderType);
- dest.writeInt(supports80211mc ? 1 : 0);
- dest.writeInt(channelWidth);
- dest.writeInt(frequency);
- dest.writeInt(centerFreq0);
- dest.writeInt(centerFreq1);
- dest.writeInt(preamble);
- }
-
- public static final @android.annotation.NonNull Creator<ResponderConfig> CREATOR = new Creator<ResponderConfig>() {
- @Override
- public ResponderConfig[] newArray(int size) {
- return new ResponderConfig[size];
- }
-
- @Override
- public ResponderConfig createFromParcel(Parcel in) {
- boolean macAddressPresent = in.readBoolean();
- MacAddress macAddress = null;
- if (macAddressPresent) {
- macAddress = MacAddress.CREATOR.createFromParcel(in);
- }
- boolean peerHandlePresent = in.readBoolean();
- PeerHandle peerHandle = null;
- if (peerHandlePresent) {
- peerHandle = new PeerHandle(in.readInt());
- }
- int responderType = in.readInt();
- boolean supports80211mc = in.readInt() == 1;
- int channelWidth = in.readInt();
- int frequency = in.readInt();
- int centerFreq0 = in.readInt();
- int centerFreq1 = in.readInt();
- int preamble = in.readInt();
-
- if (peerHandle == null) {
- return new ResponderConfig(macAddress, responderType, supports80211mc, channelWidth,
- frequency, centerFreq0, centerFreq1, preamble);
- } else {
- return new ResponderConfig(peerHandle, responderType, supports80211mc, channelWidth,
- frequency, centerFreq0, centerFreq1, preamble);
- }
- }
- };
-
- @Override
- public boolean equals(@Nullable Object o) {
- if (this == o) {
- return true;
- }
-
- if (!(o instanceof ResponderConfig)) {
- return false;
- }
-
- ResponderConfig lhs = (ResponderConfig) o;
-
- return Objects.equals(macAddress, lhs.macAddress) && Objects.equals(peerHandle,
- lhs.peerHandle) && responderType == lhs.responderType
- && supports80211mc == lhs.supports80211mc && channelWidth == lhs.channelWidth
- && frequency == lhs.frequency && centerFreq0 == lhs.centerFreq0
- && centerFreq1 == lhs.centerFreq1 && preamble == lhs.preamble;
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(macAddress, peerHandle, responderType, supports80211mc, channelWidth,
- frequency, centerFreq0, centerFreq1, preamble);
- }
-
- /** @hide */
- @Override
- public String toString() {
- return new StringBuffer("ResponderConfig: macAddress=").append(macAddress).append(
- ", peerHandle=").append(peerHandle == null ? "<null>" : peerHandle.peerId).append(
- ", responderType=").append(responderType).append(", supports80211mc=").append(
- supports80211mc).append(", channelWidth=").append(channelWidth).append(
- ", frequency=").append(frequency).append(", centerFreq0=").append(
- centerFreq0).append(", centerFreq1=").append(centerFreq1).append(
- ", preamble=").append(preamble).toString();
- }
-
- /** @hide */
- static int translateScanResultChannelWidth(int scanResultChannelWidth) {
- switch (scanResultChannelWidth) {
- case ScanResult.CHANNEL_WIDTH_20MHZ:
- return CHANNEL_WIDTH_20MHZ;
- case ScanResult.CHANNEL_WIDTH_40MHZ:
- return CHANNEL_WIDTH_40MHZ;
- case ScanResult.CHANNEL_WIDTH_80MHZ:
- return CHANNEL_WIDTH_80MHZ;
- case ScanResult.CHANNEL_WIDTH_160MHZ:
- return CHANNEL_WIDTH_160MHZ;
- case ScanResult.CHANNEL_WIDTH_80MHZ_PLUS_MHZ:
- return CHANNEL_WIDTH_80MHZ_PLUS_MHZ;
- default:
- throw new IllegalArgumentException(
- "translateScanResultChannelWidth: bad " + scanResultChannelWidth);
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/rtt/ResponderLocation.java b/wifi/java/android/net/wifi/rtt/ResponderLocation.java
deleted file mode 100644
index 218b2dcae71d..000000000000
--- a/wifi/java/android/net/wifi/rtt/ResponderLocation.java
+++ /dev/null
@@ -1,1427 +0,0 @@
-/*
- * Copyright (C) 2018 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.rtt;
-
-import static java.lang.annotation.RetentionPolicy.SOURCE;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.SuppressLint;
-import android.annotation.SystemApi;
-import android.location.Address;
-import android.location.Location;
-import android.net.MacAddress;
-import android.net.Uri;
-import android.net.wifi.rtt.CivicLocationKeys.CivicLocationKeysType;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.text.TextUtils;
-import android.util.SparseArray;
-import android.webkit.MimeTypeMap;
-
-import java.lang.annotation.Retention;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Objects;
-
-/**
- * ResponderLocation is both a Location Configuration Information (LCI) decoder and a Location Civic
- * Report (LCR) decoder for information received from a Wi-Fi Access Point (AP) during Wi-Fi RTT
- * ranging process.
- *
- * <p>This is based on the IEEE P802.11-REVmc/D8.0 spec section 9.4.2.22, under Measurement Report
- * Element. Subelement location data-fields parsed from separate input LCI and LCR Information
- * Elements are unified in this class.</p>
- *
- * <p>Note: The information provided by this class is broadcast by a responder (usually an Access
- * Point), and passed on as-is. There is no guarantee this information is accurate or correct, and
- * as a result developers should carefully consider how this information should be used and provide
- * corresponding advice to users.</p>
- */
-public final class ResponderLocation implements Parcelable {
- private static final int BYTE_MASK = 0xFF;
- private static final int LSB_IN_BYTE = 0x01;
- private static final int MSB_IN_BYTE = 0x80;
- private static final int MIN_BUFFER_SIZE = 3; // length of LEAD_LCI_ELEMENT_BYTES
- private static final int MAX_BUFFER_SIZE = 256;
-
- // Information Element (IE) fields
- private static final byte MEASUREMENT_TOKEN_AUTONOMOUS = 0x01;
- private static final byte MEASUREMENT_REPORT_MODE = 0x00;
- private static final byte MEASUREMENT_TYPE_LCI = 0x08;
- private static final byte MEASUREMENT_TYPE_LCR = 0x0b;
-
- // LCI Subelement IDs
- private static final byte SUBELEMENT_LCI = 0x00;
- private static final byte SUBELEMENT_Z = 0x04;
- private static final byte SUBELEMENT_USAGE = 0x06;
- private static final byte SUBELEMENT_BSSID_LIST = 0x07;
-
- // LCI Subelement Lengths
- private static final int SUBELEMENT_LCI_LENGTH = 16;
- private static final int SUBELEMENT_Z_LENGTH = 6;
- private static final int SUBELEMENT_USAGE_LENGTH1 = 1;
- private static final int SUBELEMENT_USAGE_LENGTH3 = 3;
- private static final int SUBELEMENT_BSSID_LIST_MIN_BUFFER_LENGTH = 1;
-
- private static final byte[] LEAD_LCI_ELEMENT_BYTES = {
- MEASUREMENT_TOKEN_AUTONOMOUS, MEASUREMENT_REPORT_MODE, MEASUREMENT_TYPE_LCI
- };
-
- // Subelement LCI constants
-
- /* The LCI subelement bit-field lengths are described in Figure 9-214 of the REVmc spec and
- represented here as a an array of integers */
- private static final int[] SUBELEMENT_LCI_BIT_FIELD_LENGTHS = {
- 6, 34, 6, 34, 4, 6, 30, 3, 1, 1, 1, 2
- };
- private static final int LATLNG_FRACTION_BITS = 25;
- private static final int LATLNG_UNCERTAINTY_BASE = 8;
- private static final int ALTITUDE_FRACTION_BITS = 8;
- private static final int ALTITUDE_UNCERTAINTY_BASE = 21;
- private static final double LAT_ABS_LIMIT = 90.0;
- private static final double LNG_ABS_LIMIT = 180.0;
- private static final int UNCERTAINTY_UNDEFINED = 0;
-
- // Subelement LCI fields indices
- private static final int SUBELEMENT_LCI_LAT_UNCERTAINTY_INDEX = 0;
- private static final int SUBELEMENT_LCI_LAT_INDEX = 1;
- private static final int SUBELEMENT_LCI_LNG_UNCERTAINTY_INDEX = 2;
- private static final int SUBELEMENT_LCI_LNG_INDEX = 3;
- private static final int SUBELEMENT_LCI_ALT_TYPE_INDEX = 4;
- private static final int SUBELEMENT_LCI_ALT_UNCERTAINTY_INDEX = 5;
- private static final int SUBELEMENT_LCI_ALT_INDEX = 6;
- private static final int SUBELEMENT_LCI_DATUM_INDEX = 7;
- private static final int SUBELEMENT_LCI_REGLOC_AGREEMENT_INDEX = 8;
- private static final int SUBELEMENT_LCI_REGLOC_DSE_INDEX = 9;
- private static final int SUBELEMENT_LCI_DEPENDENT_STA_INDEX = 10;
- private static final int SUBELEMENT_LCI_VERSION_INDEX = 11;
-
- /**
- * The Altitude value is interpreted based on the Altitude Type, and the selected mDatum.
- *
- * @hide
- */
- @Retention(SOURCE)
- @IntDef({ALTITUDE_UNDEFINED, ALTITUDE_METERS, ALTITUDE_FLOORS})
- public @interface AltitudeType {
- }
-
- /**
- * Altitude is not defined for the Responder.
- * The altitude and altitude uncertainty should not be used: see section 2.4 of IETF RFC 6225.
- */
- public static final int ALTITUDE_UNDEFINED = 0;
- /** Responder Altitude is measured in meters. */
- public static final int ALTITUDE_METERS = 1;
- /** Responder Altitude is measured in floors. */
- public static final int ALTITUDE_FLOORS = 2;
-
- /**
- * The Datum value determines how coordinates are organized in relation to the real world.
- *
- * @hide
- */
- @Retention(SOURCE)
- @IntDef({DATUM_UNDEFINED, DATUM_WGS84, DATUM_NAD83_NAV88, DATUM_NAD83_MLLW})
- public @interface DatumType {
- }
-
- /** Datum is not defined. */
- public static final int DATUM_UNDEFINED = 0;
- /** Datum used is WGS84. */
- public static final int DATUM_WGS84 = 1;
- /** Datum used is NAD83 NAV88. */
- public static final int DATUM_NAD83_NAV88 = 2;
- /** Datum used is NAD83 MLLW. */
- public static final int DATUM_NAD83_MLLW = 3;
-
-
- /** Version of the LCI protocol is 1.0, the only defined protocol at this time. */
- public static final int LCI_VERSION_1 = 1;
-
- /** Provider/Source of the location */
- private static final String LOCATION_PROVIDER = "WiFi Access Point";
-
- // LCI Subelement Z constants
- private static final int[] SUBELEMENT_Z_BIT_FIELD_LENGTHS = {2, 14, 24, 8};
- private static final int Z_FLOOR_NUMBER_FRACTION_BITS = 4;
- private static final int Z_FLOOR_HEIGHT_FRACTION_BITS = 12;
- private static final int Z_MAX_HEIGHT_UNCERTAINTY_FACTOR = 25;
-
- // LCI Subelement Z fields indices
- private static final int SUBELEMENT_Z_LAT_EXPECTED_TO_MOVE_INDEX = 0;
- private static final int SUBELEMENT_Z_FLOOR_NUMBER_INDEX = 1;
- private static final int SUBELEMENT_Z_HEIGHT_ABOVE_FLOOR_INDEX = 2;
- private static final int SUBELEMENT_Z_HEIGHT_ABOVE_FLOOR_UNCERTAINTY_INDEX = 3;
-
- // LCI Subelement Usage Rules constants
- private static final int SUBELEMENT_USAGE_MASK_RETRANSMIT = 0x01;
- private static final int SUBELEMENT_USAGE_MASK_RETENTION_EXPIRES = 0x02;
- private static final int SUBELEMENT_USAGE_MASK_STA_LOCATION_POLICY = 0x04;
-
- // LCI Subelement Usage Rules field indices
- private static final int SUBELEMENT_USAGE_PARAMS_INDEX = 0; // 8 bits
-
- // LCI Subelement BSSID List
- private static final int SUBELEMENT_BSSID_MAX_INDICATOR_INDEX = 0;
- private static final int SUBELEMENT_BSSID_LIST_INDEX = 1;
- private static final int BYTES_IN_A_BSSID = 6;
-
- /**
- * The Expected-To-Move value determines how mobile we expect the STA to be.
- *
- * @hide
- */
- @Retention(SOURCE)
- @IntDef({LOCATION_FIXED, LOCATION_VARIABLE, LOCATION_MOVEMENT_UNKNOWN, LOCATION_RESERVED})
- public @interface ExpectedToMoveType {
- }
-
- /** Location of responder is fixed (does not move) */
- public static final int LOCATION_FIXED = 0;
- /** Location of the responder is variable, and may move */
- public static final int LOCATION_VARIABLE = 1;
- /** Location of the responder is not known to be either fixed or variable. */
- public static final int LOCATION_MOVEMENT_UNKNOWN = 2;
- /** Location of the responder status is a reserved value */
- public static final int LOCATION_RESERVED = 3;
-
- // LCR Subelement IDs
- private static final byte SUBELEMENT_LOCATION_CIVIC = 0x00;
- private static final byte SUBELEMENT_MAP_IMAGE = 0x05;
-
- // LCR Subelement Lengths
- private static final int SUBELEMENT_LOCATION_CIVIC_MIN_LENGTH = 2;
- private static final int SUBELEMENT_LOCATION_CIVIC_MAX_LENGTH = 256;
- private static final int SUBELEMENT_MAP_IMAGE_URL_MAX_LENGTH = 256;
-
- private static final byte[] LEAD_LCR_ELEMENT_BYTES = {
- MEASUREMENT_TOKEN_AUTONOMOUS, MEASUREMENT_REPORT_MODE, MEASUREMENT_TYPE_LCR
- };
-
- // LCR Location Civic Subelement
- private static final int CIVIC_COUNTRY_CODE_INDEX = 0;
- private static final int CIVIC_TLV_LIST_INDEX = 2;
-
- // LCR Map Image Subelement field indexes.
- private static final int SUBELEMENT_IMAGE_MAP_TYPE_INDEX = 0;
- private static final int MAP_TYPE_URL_DEFINED = 0;
- private static final String[] SUPPORTED_IMAGE_FILE_EXTENSIONS = {
- "",
- "png",
- "gif",
- "jpg",
- "svg",
- "dxf",
- "dwg",
- "dwf",
- "cad",
- "tif",
- "gml",
- "kml",
- "bmp",
- "pgm",
- "ppm",
- "xbm",
- "xpm",
- "ico"
- };
-
- // General LCI and LCR state
- private final boolean mIsValid;
-
- /*
- These members are not final because we are not sure if the corresponding subelement will be
- present until after the parsing process. However, the default value should be set as listed.
- */
- private boolean mIsLciValid = false;
- private boolean mIsZValid = false;
- private boolean mIsUsageValid = true; // By default this is assumed true
- private boolean mIsBssidListValid = false;
- private boolean mIsLocationCivicValid = false;
- private boolean mIsMapImageValid = false;
-
- // LCI Subelement LCI state
- private double mLatitudeUncertainty;
- private double mLatitude;
- private double mLongitudeUncertainty;
- private double mLongitude;
- private int mAltitudeType;
- private double mAltitudeUncertainty;
- private double mAltitude;
- private int mDatum;
- private boolean mLciRegisteredLocationAgreement;
- private boolean mLciRegisteredLocationDse;
- private boolean mLciDependentStation;
- private int mLciVersion;
-
- // LCI Subelement Z state
- private int mExpectedToMove;
- private double mFloorNumber;
- private double mHeightAboveFloorMeters;
- private double mHeightAboveFloorUncertaintyMeters;
-
- // LCI Subelement Usage Rights state
- private boolean mUsageRetransmit;
- private boolean mUsageRetentionExpires;
- private boolean mUsageExtraInfoOnAssociation;
-
- // LCI Subelement BSSID List state
- private ArrayList<MacAddress> mBssidList;
-
- // LCR Subelement Location Civic state
- private String mCivicLocationCountryCode;
- private String mCivicLocationString;
- private CivicLocation mCivicLocation;
-
- // LCR Subelement Map Image state
- private int mMapImageType;
- private Uri mMapImageUri;
-
- /**
- * Constructor
- *
- * @param lciBuffer the bytes received in the LCI Measurement Report Information Element
- * @param lcrBuffer the bytes received in the LCR Measurement Report Information Element
- *
- * @hide
- */
- public ResponderLocation(byte[] lciBuffer, byte[] lcrBuffer) {
- boolean isLciIeValid = false;
- boolean isLcrIeValid = false;
- setLciSubelementDefaults();
- setZaxisSubelementDefaults();
- setUsageSubelementDefaults();
- setBssidListSubelementDefaults();
- setCivicLocationSubelementDefaults();
- setMapImageSubelementDefaults();
- if (lciBuffer != null && lciBuffer.length > LEAD_LCI_ELEMENT_BYTES.length) {
- isLciIeValid = parseInformationElementBuffer(
- MEASUREMENT_TYPE_LCI, lciBuffer, LEAD_LCI_ELEMENT_BYTES);
- }
- if (lcrBuffer != null && lcrBuffer.length > LEAD_LCR_ELEMENT_BYTES.length) {
- isLcrIeValid = parseInformationElementBuffer(
- MEASUREMENT_TYPE_LCR, lcrBuffer, LEAD_LCR_ELEMENT_BYTES);
- }
-
- boolean isLciValid = isLciIeValid && mIsUsageValid
- && (mIsLciValid || mIsZValid || mIsBssidListValid);
-
- boolean isLcrValid = isLcrIeValid && mIsUsageValid
- && (mIsLocationCivicValid || mIsMapImageValid);
-
- mIsValid = isLciValid || isLcrValid;
-
- if (!mIsValid) {
- setLciSubelementDefaults();
- setZaxisSubelementDefaults();
- setCivicLocationSubelementDefaults();
- setMapImageSubelementDefaults();
- }
- }
-
- private ResponderLocation(Parcel in) {
- // Object Validation
- mIsValid = in.readByte() != 0;
- mIsLciValid = in.readByte() != 0;
- mIsZValid = in.readByte() != 0;
- mIsUsageValid = in.readByte() != 0;
- mIsBssidListValid = in.readByte() != 0;
- mIsLocationCivicValid = in.readByte() != 0;
- mIsMapImageValid = in.readByte() != 0;
-
- // LCI Subelement LCI state
- mLatitudeUncertainty = in.readDouble();
- mLatitude = in.readDouble();
- mLongitudeUncertainty = in.readDouble();
- mLongitude = in.readDouble();
- mAltitudeType = in.readInt();
- mAltitudeUncertainty = in.readDouble();
- mAltitude = in.readDouble();
- mDatum = in.readInt();
- mLciRegisteredLocationAgreement = in.readByte() != 0;
- mLciRegisteredLocationDse = in.readByte() != 0;
- mLciDependentStation = in.readByte() != 0;
- mLciVersion = in.readInt();
-
- // LCI Subelement Z state
- mExpectedToMove = in.readInt();
- mFloorNumber = in.readDouble();
- mHeightAboveFloorMeters = in.readDouble();
- mHeightAboveFloorUncertaintyMeters = in.readDouble();
-
- // LCI Usage Rights
- mUsageRetransmit = in.readByte() != 0;
- mUsageRetentionExpires = in.readByte() != 0;
- mUsageExtraInfoOnAssociation = in.readByte() != 0;
-
- // LCI Subelement BSSID List
- mBssidList = in.readArrayList(MacAddress.class.getClassLoader());
-
- // LCR Subelement Location Civic
- mCivicLocationCountryCode = in.readString();
- mCivicLocationString = in.readString();
- mCivicLocation = in.readParcelable(this.getClass().getClassLoader());
-
- // LCR Subelement Map Image
- mMapImageType = in.readInt();
- String urlString = in.readString();
- if (TextUtils.isEmpty(urlString)) {
- mMapImageUri = null;
- } else {
- mMapImageUri = Uri.parse(urlString);
- }
- }
-
- public static final @android.annotation.NonNull Creator<ResponderLocation> CREATOR = new Creator<ResponderLocation>() {
- @Override
- public ResponderLocation createFromParcel(Parcel in) {
- return new ResponderLocation(in);
- }
-
- @Override
- public ResponderLocation[] newArray(int size) {
- return new ResponderLocation[size];
- }
- };
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel parcel, int flags) {
- // Object
- parcel.writeByte((byte) (mIsValid ? 1 : 0));
- parcel.writeByte((byte) (mIsLciValid ? 1 : 0));
- parcel.writeByte((byte) (mIsZValid ? 1 : 0));
- parcel.writeByte((byte) (mIsUsageValid ? 1 : 0));
- parcel.writeByte((byte) (mIsBssidListValid ? 1 : 0));
- parcel.writeByte((byte) (mIsLocationCivicValid ? 1 : 0));
- parcel.writeByte((byte) (mIsMapImageValid ? 1 : 0));
-
- // LCI Subelement LCI state
- parcel.writeDouble(mLatitudeUncertainty);
- parcel.writeDouble(mLatitude);
- parcel.writeDouble(mLongitudeUncertainty);
- parcel.writeDouble(mLongitude);
- parcel.writeInt(mAltitudeType);
- parcel.writeDouble(mAltitudeUncertainty);
- parcel.writeDouble(mAltitude);
- parcel.writeInt(mDatum);
- parcel.writeByte((byte) (mLciRegisteredLocationAgreement ? 1 : 0));
- parcel.writeByte((byte) (mLciRegisteredLocationDse ? 1 : 0));
- parcel.writeByte((byte) (mLciDependentStation ? 1 : 0));
- parcel.writeInt(mLciVersion);
-
- // LCI Subelement Z state
- parcel.writeInt(mExpectedToMove);
- parcel.writeDouble(mFloorNumber);
- parcel.writeDouble(mHeightAboveFloorMeters);
- parcel.writeDouble(mHeightAboveFloorUncertaintyMeters);
-
- // LCI Usage Rights
- parcel.writeByte((byte) (mUsageRetransmit ? 1 : 0));
- parcel.writeByte((byte) (mUsageRetentionExpires ? 1 : 0));
- parcel.writeByte((byte) (mUsageExtraInfoOnAssociation ? 1 : 0));
-
- // LCI Subelement BSSID List
- parcel.writeList(mBssidList);
-
- // LCR Subelement Location Civic
- parcel.writeString(mCivicLocationCountryCode);
- parcel.writeString(mCivicLocationString);
- parcel.writeParcelable(mCivicLocation, flags);
-
- // LCR Subelement Map Image
- parcel.writeInt(mMapImageType);
- if (mMapImageUri != null) {
- parcel.writeString(mMapImageUri.toString());
- } else {
- parcel.writeString("");
- }
- }
-
- /**
- * Test if the Information Element (IE) is in the correct format, and then parse its Subelements
- * based on their type, and setting state in this object when present.
- *
- * @return a boolean indicating the success of the parsing function
- */
- private boolean parseInformationElementBuffer(
- int ieType, byte[] buffer, byte[] expectedLeadBytes) {
- int bufferPtr = 0;
- int bufferLength = buffer.length;
-
- // Ensure the buffer size is within expected limits
- if (bufferLength < MIN_BUFFER_SIZE || bufferLength > MAX_BUFFER_SIZE) {
- return false;
- }
-
- // Ensure the IE contains the correct leading bytes
- byte[] leadBufferBytes = Arrays.copyOfRange(buffer, bufferPtr, expectedLeadBytes.length);
- if (!Arrays.equals(leadBufferBytes, expectedLeadBytes)) {
- return false;
- }
-
- // Iterate through the sub-elements contained in the Information Element (IE)
- bufferPtr += expectedLeadBytes.length;
- // Loop over the buffer ensuring there are 2-bytes available for each new subelement tested.
- while (bufferPtr + 1 < bufferLength) {
- byte subelement = buffer[bufferPtr++];
- int subelementLength = buffer[bufferPtr++];
- // Check there is enough data for the next subelement
- if ((bufferPtr + subelementLength) > bufferLength || subelementLength <= 0) {
- return false;
- }
-
- byte[] subelementData =
- Arrays.copyOfRange(buffer, bufferPtr, bufferPtr + subelementLength);
-
- if (ieType == MEASUREMENT_TYPE_LCI) {
- switch (subelement) {
- case SUBELEMENT_LCI:
- mIsLciValid = parseSubelementLci(subelementData);
- if (!mIsLciValid || mLciVersion != LCI_VERSION_1) {
- setLciSubelementDefaults();
- }
- break;
- case SUBELEMENT_Z:
- mIsZValid = parseSubelementZ(subelementData);
- if (!mIsZValid) {
- setZaxisSubelementDefaults();
- }
- break;
- case SUBELEMENT_USAGE:
- mIsUsageValid = parseSubelementUsage(subelementData);
- // Note: if the Usage Subelement is not valid, don't reset the state, as
- // it is now indicating the whole ResponderLocation is invalid.
- break;
- case SUBELEMENT_BSSID_LIST:
- mIsBssidListValid = parseSubelementBssidList(subelementData);
- if (!mIsBssidListValid) {
- setBssidListSubelementDefaults();
- }
- break;
- default:
- break; // skip over unused or vendor specific subelements
- }
- } else if (ieType == MEASUREMENT_TYPE_LCR) {
- switch (subelement) {
- case SUBELEMENT_LOCATION_CIVIC:
- mIsLocationCivicValid = parseSubelementLocationCivic(subelementData);
- if (!mIsLocationCivicValid) {
- setCivicLocationSubelementDefaults();
- }
- break;
- case SUBELEMENT_MAP_IMAGE:
- mIsMapImageValid = parseSubelementMapImage(subelementData);
- if (!mIsMapImageValid) {
- setMapImageSubelementDefaults();
- }
- break;
- default:
- break; // skip over unused or other vendor specific subelements
- }
- }
-
- bufferPtr += subelementLength;
- }
- return true;
- }
-
- /**
- * Parse the LCI Sub-Element in the LCI Information Element (IE).
- *
- * @param buffer a buffer containing the subelement
- * @return boolean true indicates success
- */
- private boolean parseSubelementLci(byte[] buffer) {
- if (buffer.length > SUBELEMENT_LCI_LENGTH) {
- return false;
- }
- swapEndianByteByByte(buffer);
- long[] subelementLciFields = getFieldData(buffer, SUBELEMENT_LCI_BIT_FIELD_LENGTHS);
- if (subelementLciFields == null) {
- return false;
- }
- // Set member state based on parsed buffer data
- mLatitudeUncertainty = decodeLciLatLngUncertainty(
- subelementLciFields[SUBELEMENT_LCI_LAT_UNCERTAINTY_INDEX]);
- mLatitude = decodeLciLatLng(subelementLciFields, SUBELEMENT_LCI_BIT_FIELD_LENGTHS,
- SUBELEMENT_LCI_LAT_INDEX, LAT_ABS_LIMIT);
- mLongitudeUncertainty = decodeLciLatLngUncertainty(
- subelementLciFields[SUBELEMENT_LCI_LNG_UNCERTAINTY_INDEX]);
- mLongitude =
- decodeLciLatLng(subelementLciFields, SUBELEMENT_LCI_BIT_FIELD_LENGTHS,
- SUBELEMENT_LCI_LNG_INDEX, LNG_ABS_LIMIT);
- mAltitudeType = (int) subelementLciFields[SUBELEMENT_LCI_ALT_TYPE_INDEX] & BYTE_MASK;
- mAltitudeUncertainty =
- decodeLciAltUncertainty(subelementLciFields[SUBELEMENT_LCI_ALT_UNCERTAINTY_INDEX]);
- mAltitude =
- Math.scalb(subelementLciFields[SUBELEMENT_LCI_ALT_INDEX], -ALTITUDE_FRACTION_BITS);
- mDatum = (int) subelementLciFields[SUBELEMENT_LCI_DATUM_INDEX] & BYTE_MASK;
- mLciRegisteredLocationAgreement =
- (subelementLciFields[SUBELEMENT_LCI_REGLOC_AGREEMENT_INDEX] == 1);
- mLciRegisteredLocationDse =
- (subelementLciFields[SUBELEMENT_LCI_REGLOC_DSE_INDEX] == 1);
- mLciDependentStation =
- (subelementLciFields[SUBELEMENT_LCI_DEPENDENT_STA_INDEX] == 1);
- mLciVersion = (int) subelementLciFields[SUBELEMENT_LCI_VERSION_INDEX];
- return true;
- }
-
- /**
- * Decode the floating point value of an encoded lat or lng in the LCI subelement field.
- *
- * @param fields the array of field data represented as longs
- * @param bitFieldSizes the lengths of each field
- * @param offset the offset of the field being decoded
- * @param limit the maximum absolute value (note: different for lat vs lng)
- * @return the floating point value of the lat or lng
- */
- private double decodeLciLatLng(long[] fields, int[] bitFieldSizes, int offset, double limit) {
- double angle;
- if ((fields[offset] & (long) Math.pow(2, bitFieldSizes[offset] - 1)) != 0) {
- // Negative 2's complement value
- // Note: The Math.pow(...) method cannot return a NaN value because the bitFieldSize
- // for Lat or Lng is limited to exactly 34 bits.
- angle = Math.scalb((double) fields[offset] - Math.pow(2, bitFieldSizes[offset]),
- -LATLNG_FRACTION_BITS);
- } else {
- // Positive 2's complement value
- angle = Math.scalb((double) fields[offset], -LATLNG_FRACTION_BITS);
- }
- if (angle > limit) {
- angle = limit;
- } else if (angle < -limit) {
- angle = -limit;
- }
- return angle;
- }
-
- /**
- * Coverts an encoded Lat/Lng uncertainty into a number of degrees.
- *
- * @param encodedValue the encoded uncertainty
- * @return the value in degrees
- */
- private double decodeLciLatLngUncertainty(long encodedValue) {
- return Math.pow(2, LATLNG_UNCERTAINTY_BASE - encodedValue);
- }
-
- /**
- * Converts an encoded Alt uncertainty into a number of degrees.
- *
- * @param encodedValue the encoded uncertainty
- * @return the value in degrees
- */
- private double decodeLciAltUncertainty(long encodedValue) {
- return Math.pow(2, ALTITUDE_UNCERTAINTY_BASE - encodedValue);
- }
-
- /**
- * Parse the Z subelement of the LCI IE.
- *
- * @param buffer a buffer containing the subelement
- * @return boolean true indicates success
- */
- private boolean parseSubelementZ(byte[] buffer) {
- if (buffer.length != SUBELEMENT_Z_LENGTH) {
- return false;
- }
- swapEndianByteByByte(buffer);
- long[] subelementZFields = getFieldData(buffer, SUBELEMENT_Z_BIT_FIELD_LENGTHS);
- if (subelementZFields == null) {
- return false;
- }
-
- mExpectedToMove =
- (int) subelementZFields[SUBELEMENT_Z_LAT_EXPECTED_TO_MOVE_INDEX] & BYTE_MASK;
- mFloorNumber = decodeZUnsignedToSignedValue(subelementZFields,
- SUBELEMENT_Z_BIT_FIELD_LENGTHS, SUBELEMENT_Z_FLOOR_NUMBER_INDEX,
- Z_FLOOR_NUMBER_FRACTION_BITS);
-
- mHeightAboveFloorMeters = decodeZUnsignedToSignedValue(subelementZFields,
- SUBELEMENT_Z_BIT_FIELD_LENGTHS, SUBELEMENT_Z_HEIGHT_ABOVE_FLOOR_INDEX,
- Z_FLOOR_HEIGHT_FRACTION_BITS);
-
- 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);
- } else {
- return false;
- }
- return true;
- }
-
- /**
- * Decode a two's complement encoded value, to a signed double based on the field length.
- *
- * @param fieldValues the array of field values reprented as longs
- * @param fieldLengths the array of field lengths
- * @param index the index of the field being decoded
- * @param fraction the number of fractional bits in the value
- * @return the signed value represented as a double
- */
- private double decodeZUnsignedToSignedValue(long[] fieldValues, int[] fieldLengths, int index,
- int fraction) {
- int value = (int) fieldValues[index];
- int maxPositiveValue = (int) Math.pow(2, fieldLengths[index] - 1) - 1;
- if (value > maxPositiveValue) {
- value -= Math.pow(2, fieldLengths[index]);
- }
- return Math.scalb(value, -fraction);
- }
-
- /**
- * Parse Subelement Usage Rights
- */
- private boolean parseSubelementUsage(byte[] buffer) {
- if (buffer.length != SUBELEMENT_USAGE_LENGTH1
- && buffer.length != SUBELEMENT_USAGE_LENGTH3) {
- return false;
- }
- mUsageRetransmit =
- (buffer[SUBELEMENT_USAGE_PARAMS_INDEX] & SUBELEMENT_USAGE_MASK_RETRANSMIT) != 0;
- mUsageRetentionExpires =
- (buffer[SUBELEMENT_USAGE_PARAMS_INDEX] & SUBELEMENT_USAGE_MASK_RETENTION_EXPIRES)
- != 0;
- mUsageExtraInfoOnAssociation =
- (buffer[SUBELEMENT_USAGE_PARAMS_INDEX] & SUBELEMENT_USAGE_MASK_STA_LOCATION_POLICY)
- != 0;
- // Note: the Retransmit flag must be true, and RetentionExpires, false for the
- // ResponderLocation object to be usable by public applications.
- return (mUsageRetransmit && !mUsageRetentionExpires);
- }
-
- /**
- * Parse the BSSID List Subelement of the LCI IE.
- *
- * @param buffer a buffer containing the subelement
- * @return boolean true indicates success
- */
- private boolean parseSubelementBssidList(byte[] buffer) {
- if (buffer.length < SUBELEMENT_BSSID_LIST_MIN_BUFFER_LENGTH) {
- return false;
- }
- if ((buffer.length - 1) % BYTES_IN_A_BSSID != 0) {
- return false;
- }
-
- int maxBssidIndicator = (int) buffer[SUBELEMENT_BSSID_MAX_INDICATOR_INDEX] & BYTE_MASK;
- int bssidListLength = (buffer.length - 1) / BYTES_IN_A_BSSID;
- // The maxBSSIDIndicator is ignored. Its use is still being clarified in 802.11REVmd,
- // which is not published at this time. This field will be used in a future
- // release of Android after 802.11REVmd is public. Here, we interpret the following
- // params as an explicit list of BSSIDs.
-
-
- int bssidOffset = SUBELEMENT_BSSID_LIST_INDEX;
- for (int i = 0; i < bssidListLength; i++) {
- byte[] bssid = Arrays.copyOfRange(buffer, bssidOffset, bssidOffset + BYTES_IN_A_BSSID);
- MacAddress macAddress = MacAddress.fromBytes(bssid);
- mBssidList.add(macAddress);
- bssidOffset += BYTES_IN_A_BSSID;
- }
- return true;
- }
-
- /**
- * Parse the Location Civic subelement in the LCR IE.
- *
- * @param buffer a buffer containing the subelement
- * @return boolean true indicates success
- */
- private boolean parseSubelementLocationCivic(byte[] buffer) {
- if (buffer.length < SUBELEMENT_LOCATION_CIVIC_MIN_LENGTH
- || buffer.length > SUBELEMENT_LOCATION_CIVIC_MAX_LENGTH) {
- return false;
- }
- mCivicLocationCountryCode =
- new String(Arrays.copyOfRange(buffer, CIVIC_COUNTRY_CODE_INDEX,
- CIVIC_TLV_LIST_INDEX)).toUpperCase();
- CivicLocation civicLocation =
- new CivicLocation(
- Arrays.copyOfRange(buffer, CIVIC_TLV_LIST_INDEX, buffer.length),
- mCivicLocationCountryCode);
- if (!civicLocation.isValid()) {
- return false;
- }
- this.mCivicLocation = civicLocation;
- mCivicLocationString = civicLocation.toString();
- return true;
- }
-
- /**
- * Parse the Map Image subelement in the LCR IE.
- *
- * @param buffer a buffer containing the subelement
- * @return boolean true indicates success
- */
- private boolean parseSubelementMapImage(byte[] buffer) {
- if (buffer.length > SUBELEMENT_MAP_IMAGE_URL_MAX_LENGTH) {
- return false;
- }
- int mapImageType = buffer[SUBELEMENT_IMAGE_MAP_TYPE_INDEX];
- int supportedTypesMax = SUPPORTED_IMAGE_FILE_EXTENSIONS.length - 1;
- if (mapImageType < MAP_TYPE_URL_DEFINED || mapImageType > supportedTypesMax) {
- return false;
- }
- this.mMapImageType = mapImageType;
- byte[] urlBytes = Arrays.copyOfRange(buffer, 1, buffer.length);
- mMapImageUri = Uri.parse(new String(urlBytes, StandardCharsets.UTF_8));
- return true;
- }
-
- /**
- * Convert an image type code to a Mime type
- *
- * @param imageTypeCode encoded as an integer
- * @return the mime type of the image file
- */
- private String imageTypeToMime(int imageTypeCode, String imageUrl) {
- int supportedExtensionsMax = SUPPORTED_IMAGE_FILE_EXTENSIONS.length - 1;
- if ((imageTypeCode == 0 && imageUrl == null) || imageTypeCode > supportedExtensionsMax) {
- return null;
- }
- MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
- if (imageTypeCode == 0) {
- return mimeTypeMap.getMimeTypeFromExtension(
- MimeTypeMap.getFileExtensionFromUrl(imageUrl));
- } else {
- return mimeTypeMap.getMimeTypeFromExtension(
- SUPPORTED_IMAGE_FILE_EXTENSIONS[imageTypeCode]);
- }
- }
-
- /**
- * Converts a byte array containing fields of variable size, into an array of longs where the
- * field boundaries are defined in a constant int array passed as an argument.
- *
- * @param buffer the byte array containing all the fields
- * @param bitFieldSizes the int array defining the size of each field
- */
- private long[] getFieldData(byte[] buffer, int[] bitFieldSizes) {
- int bufferLengthBits = buffer.length * Byte.SIZE;
- int sumBitFieldSizes = 0;
- for (int i : bitFieldSizes) {
- if (i > Long.SIZE) {
- return null;
- }
- sumBitFieldSizes += i;
- }
- if (bufferLengthBits != sumBitFieldSizes) {
- return null;
- }
- long[] fieldData = new long[bitFieldSizes.length];
- int bufferBitPos = 0;
- for (int fieldIndex = 0; fieldIndex < bitFieldSizes.length; fieldIndex++) {
- int bitFieldSize = bitFieldSizes[fieldIndex];
- long field = 0;
- for (int n = 0; n < bitFieldSize; n++) {
- field |= ((long) getBitAtBitOffsetInByteArray(buffer, bufferBitPos + n) << n);
- }
- fieldData[fieldIndex] = field;
- bufferBitPos += bitFieldSize;
- }
- return fieldData;
- }
-
- /**
- * Retrieves state of a bit at the bit-offset in a byte array, where the offset represents the
- * bytes in contiguous data with each value in big endian order.
- *
- * @param buffer the data buffer of bytes containing all the fields
- * @param bufferBitOffset the bit offset into the entire buffer
- * @return a zero or one value, representing the state of that bit.
- */
- private int getBitAtBitOffsetInByteArray(byte[] buffer, int bufferBitOffset) {
- int bufferIndex = bufferBitOffset / Byte.SIZE; // The byte index that contains the bit
- int bitOffsetInByte = bufferBitOffset % Byte.SIZE; // The bit offset within that byte
- int result = (buffer[bufferIndex] & (MSB_IN_BYTE >> bitOffsetInByte)) == 0 ? 0 : 1;
- return result;
- }
-
- /**
- * Reverses the order of the bits in each byte of a byte array.
- *
- * @param buffer the array containing each byte that will be reversed
- */
- private void swapEndianByteByByte(byte[] buffer) {
- for (int n = 0; n < buffer.length; n++) {
- byte currentByte = buffer[n];
- byte reversedByte = 0; // Cleared value
- byte bitSelectorMask = LSB_IN_BYTE;
- for (int i = 0; i < Byte.SIZE; i++) {
- reversedByte = (byte) (reversedByte << 1);
- if ((currentByte & bitSelectorMask) != 0) {
- reversedByte = (byte) (reversedByte | LSB_IN_BYTE);
- }
- bitSelectorMask = (byte) (bitSelectorMask << 1);
- }
- buffer[n] = reversedByte;
- }
- }
-
- /**
- * Sets the LCI subelement fields to the default undefined values.
- */
- private void setLciSubelementDefaults() {
- mIsLciValid = false;
- mLatitudeUncertainty = UNCERTAINTY_UNDEFINED;
- mLatitude = 0;
- mLongitudeUncertainty = UNCERTAINTY_UNDEFINED;
- mLongitude = 0;
- mAltitudeType = ALTITUDE_UNDEFINED;
- mAltitudeUncertainty = UNCERTAINTY_UNDEFINED;
- mAltitude = 0;
- mDatum = DATUM_UNDEFINED;
- mLciRegisteredLocationAgreement = false;
- mLciRegisteredLocationDse = false;
- mLciDependentStation = false;
- mLciVersion = 0;
- }
-
- /**
- * Sets the Z subelement fields to the default values when undefined.
- */
- private void setZaxisSubelementDefaults() {
- mIsZValid = false;
- mExpectedToMove = 0;
- mFloorNumber = 0;
- mHeightAboveFloorMeters = 0;
- mHeightAboveFloorUncertaintyMeters = 0;
- }
-
- /**
- * Sets the Usage Policy subelement fields to the default undefined values.
- */
- private void setUsageSubelementDefaults() {
- mUsageRetransmit = true;
- mUsageRetentionExpires = false;
- mUsageExtraInfoOnAssociation = false;
- }
-
- /**
- * Sets the BSSID List subelement fields to the default values when undefined.
- */
- private void setBssidListSubelementDefaults() {
- mIsBssidListValid = false;
- mBssidList = new ArrayList<>();
- }
-
- /**
- * Sets the LCR Civic Location subelement field to the default undefined value.
- *
- * @hide
- */
- public void setCivicLocationSubelementDefaults() {
- mIsLocationCivicValid = false;
- mCivicLocationCountryCode = "";
- mCivicLocationString = "";
- mCivicLocation = null;
- }
-
- /**
- * Sets the LCR Map Image subelement field to the default values when undefined.
- */
- private void setMapImageSubelementDefaults() {
- mIsMapImageValid = false;
- mMapImageType = MAP_TYPE_URL_DEFINED;
- mMapImageUri = null;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null || getClass() != obj.getClass()) {
- return false;
- }
- ResponderLocation other = (ResponderLocation) obj;
- return mIsValid == other.mIsValid
- && mIsLciValid == other.mIsLciValid
- && mIsZValid == other.mIsZValid
- && mIsUsageValid == other.mIsUsageValid
- && mIsBssidListValid == other.mIsBssidListValid
- && mIsLocationCivicValid == other.mIsLocationCivicValid
- && mIsMapImageValid == other.mIsMapImageValid
- && mLatitudeUncertainty == other.mLatitudeUncertainty
- && mLatitude == other.mLatitude
- && mLongitudeUncertainty == other.mLongitudeUncertainty
- && mLongitude == other.mLongitude
- && mAltitudeType == other.mAltitudeType
- && mAltitudeUncertainty == other.mAltitudeUncertainty
- && mAltitude == other.mAltitude
- && mDatum == other.mDatum
- && mLciRegisteredLocationAgreement == other.mLciRegisteredLocationAgreement
- && mLciRegisteredLocationDse == other.mLciRegisteredLocationDse
- && mLciDependentStation == other.mLciDependentStation
- && mLciVersion == other.mLciVersion
- && mExpectedToMove == other.mExpectedToMove
- && mFloorNumber == other.mFloorNumber
- && mHeightAboveFloorMeters == other.mHeightAboveFloorMeters
- && mHeightAboveFloorUncertaintyMeters
- == other.mHeightAboveFloorUncertaintyMeters
- && mUsageRetransmit == other.mUsageRetransmit
- && mUsageRetentionExpires == other.mUsageRetentionExpires
- && mUsageExtraInfoOnAssociation == other.mUsageExtraInfoOnAssociation
- && mBssidList.equals(other.mBssidList)
- && mCivicLocationCountryCode.equals(other.mCivicLocationCountryCode)
- && mCivicLocationString.equals(other.mCivicLocationString)
- && Objects.equals(mCivicLocation, other.mCivicLocation)
- && mMapImageType == other.mMapImageType
- && Objects.equals(mMapImageUri, other.mMapImageUri);
- }
-
- @Override
- public int hashCode() {
- return Objects.hash(mIsValid, mIsLciValid, mIsZValid, mIsUsageValid, mIsBssidListValid,
- mIsLocationCivicValid, mIsMapImageValid, mLatitudeUncertainty, mLatitude,
- mLongitudeUncertainty, mLongitude, mAltitudeType, mAltitudeUncertainty, mAltitude,
- mDatum, mLciRegisteredLocationAgreement,
- mLciRegisteredLocationDse, mLciDependentStation, mLciVersion,
- mExpectedToMove, mFloorNumber, mHeightAboveFloorMeters,
- mHeightAboveFloorUncertaintyMeters, mUsageRetransmit, mUsageRetentionExpires,
- mUsageExtraInfoOnAssociation, mBssidList, mCivicLocationCountryCode,
- mCivicLocationString, mCivicLocation, mMapImageType, mMapImageUri);
- }
-
- /**
- * @return true if the ResponderLocation object is valid and contains useful information
- * relevant to the location of the Responder. If this is ever false, this object will not be
- * available to developers, and have a null value.
- *
- * @hide
- */
- public boolean isValid() {
- return mIsValid;
- }
-
- /**
- * @return true if the LCI subelement (containing Latitude, Longitude and Altitude) is valid.
- *
- * <p> This method tells us if the responder has provided its Location Configuration
- * Information (LCI) directly, and is useful when an external database of responder locations
- * is not available</p>
- *
- * <p>If isLciSubelementValid() returns true, all the LCI values provided by the corresponding
- * getter methods will have been set as described by the responder, or else if false, they
- * should not be used and will throw an IllegalStateException.</p>
- */
- public boolean isLciSubelementValid() {
- return mIsLciValid;
- }
-
- /**
- * @return the latitude uncertainty in degrees.
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- * </p>
- * <p> An unknown uncertainty is indicated by 0.</p>
- */
- public double getLatitudeUncertainty() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getLatitudeUncertainty(): invoked on an invalid result: mIsLciValid = false.");
- }
- return mLatitudeUncertainty;
- }
-
- /**
- * @return the latitude in degrees
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- */
- public double getLatitude() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getLatitude(): invoked on an invalid result: mIsLciValid = false.");
- }
- return mLatitude;
- }
-
- /**
- * @return the Longitude uncertainty in degrees.
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- * </p>
- * <p> An unknown uncertainty is indicated by 0.</p>
- */
- public double getLongitudeUncertainty() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getLongitudeUncertainty(): invoked on an invalid result: mIsLciValid = false.");
- }
- return mLongitudeUncertainty;
- }
-
- /**
- * @return the Longitude in degrees..
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- */
- public double getLongitude() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getLatitudeUncertainty(): invoked on an invalid result: mIsLciValid = false.");
- }
- return mLongitude;
- }
-
- /**
- * @return the Altitude type.
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- */
- @AltitudeType
- public int getAltitudeType() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getLatitudeUncertainty(): invoked on an invalid result: mIsLciValid = false.");
- }
- return mAltitudeType;
- }
-
- /**
- * @return the Altitude uncertainty in meters.
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- * </p>
- * <p>An unknown uncertainty is indicated by 0.</p>
- */
- public double getAltitudeUncertainty() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getLatitudeUncertainty(): invoked on an invalid result: mIsLciValid = false.");
- }
- return mAltitudeUncertainty;
- }
-
- /**
- * @return the Altitude in units defined by the altitude type.
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- */
- public double getAltitude() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getAltitude(): invoked on an invalid result: mIsLciValid = false.");
- }
- return mAltitude;
- }
-
- /**
- * @return the Datum used for the LCI positioning information.
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- */
- @DatumType
- public int getDatum() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getDatum(): invoked on an invalid result: mIsLciValid = false.");
- }
- return mDatum;
- }
-
- /**
- * @return true if the station is operating within a national policy area or an international
- * agreement area near a national border, otherwise false
- * (see 802.11REVmc Section 11.12.3 - Registered STA Operation).
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- */
- public boolean getRegisteredLocationAgreementIndication() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getRegisteredLocationAgreementIndication(): "
- + "invoked on an invalid result: mIsLciValid = false.");
- }
- return mLciRegisteredLocationAgreement;
- }
-
- /**
- * @return true indicating this is an enabling station, enabling the operation of nearby STAs
- * with Dynamic Station Enablement (DSE), otherwise false.
- * (see 802.11REVmc Section 11.12.3 - Registered STA Operation).
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- *
- * @hide
- */
- public boolean getRegisteredLocationDseIndication() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getRegisteredLocationDseIndication(): "
- + "invoked on an invalid result: mIsLciValid = false.");
- }
- return mLciRegisteredLocationDse;
- }
-
- /**
- * @return true indicating this is a dependent station that is operating with the enablement of
- * an enabling station whose LCI is being reported, otherwise false.
- * (see 802.11REVmc Section 11.12.3 - Registered STA Operation).
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- *
- * @hide
- */
- public boolean getDependentStationIndication() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getDependentStationIndication(): "
- + "invoked on an invalid result: mIsLciValid = false.");
- }
- return mLciDependentStation;
- }
-
- /**
- * @return a value greater or equal to 1, indicating the current version number
- * of the LCI protocol.
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- */
- public int getLciVersion() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "getLciVersion(): "
- + "invoked on an invalid result: mIsLciValid = false.");
- }
- return mLciVersion;
- }
-
- /**
- * @return the LCI location represented as a {@link Location} object (best effort).
- * <p>
- * Only valid if {@link #isLciSubelementValid()} returns true, or will throw an exception.
- */
- @NonNull
- public Location toLocation() {
- if (!mIsLciValid) {
- throw new IllegalStateException(
- "toLocation(): "
- + "invoked on an invalid result: mIsLciValid = false.");
- }
- Location location = new Location(LOCATION_PROVIDER);
- location.setLatitude(mLatitude);
- location.setLongitude(mLongitude);
- location.setAccuracy((float) (mLatitudeUncertainty + mLongitudeUncertainty) / 2);
- location.setAltitude(mAltitude);
- location.setVerticalAccuracyMeters((float) mAltitudeUncertainty);
- location.setTime(System.currentTimeMillis());
- return location;
- }
-
- /**
- * @return if the Z subelement (containing mobility, Floor, Height above floor) is valid.
- */
- public boolean isZaxisSubelementValid() {
- return mIsZValid;
- }
-
- /**
- * @return an integer representing the mobility of the responder.
- * <p>
- * Only valid if {@link #isZaxisSubelementValid()} returns true, or will throw an exception.
- */
- @ExpectedToMoveType
- public int getExpectedToMove() {
- if (!mIsZValid) {
- throw new IllegalStateException(
- "getExpectedToMove(): invoked on an invalid result: mIsZValid = false.");
- }
- return mExpectedToMove;
- }
-
- /**
- * @return the Z sub element Floor Number.
- * <p>
- * Only valid if {@link #isZaxisSubelementValid()} returns true, or will throw an exception.
- * </p>
- * <p>Note: this number can be positive or negative, with value increments of +/- 1/16 of a
- * floor.</p>.
- */
- public double getFloorNumber() {
- if (!mIsZValid) {
- throw new IllegalStateException(
- "getFloorNumber(): invoked on an invalid result: mIsZValid = false)");
- }
- return mFloorNumber;
- }
-
- /**
- * @return the Z subelement Height above the floor in meters.
- * <p>
- * Only valid if {@link #isZaxisSubelementValid()} returns true, or will throw an exception.
- * </p>
- * <p>This value can be positive or negative. </p>
- */
- public double getHeightAboveFloorMeters() {
- if (!mIsZValid) {
- throw new IllegalStateException(
- "getHeightAboveFloorMeters(): invoked on an invalid result: mIsZValid = false)");
- }
- return mHeightAboveFloorMeters;
- }
-
- /**
- * @return the Z subelement Height above the floor uncertainty in meters.
- * <p>
- * Only valid if {@link #isZaxisSubelementValid()} returns true, or will throw an exception.
- * </p>
- * <p>An unknown uncertainty is indicated by 0.</p>
- */
- public double getHeightAboveFloorUncertaintyMeters() {
- if (!mIsZValid) {
- throw new IllegalStateException(
- "getHeightAboveFloorUncertaintyMeters():"
- + "invoked on an invalid result: mIsZValid = false)");
- }
- return mHeightAboveFloorUncertaintyMeters;
- }
-
- /**
- * @return true if the location information received from the responder can be
- * retransmitted to another device, physically separate from the one that received it.
- *
- * @hide
- */
- public boolean getRetransmitPolicyIndication() {
- return mUsageRetransmit;
- }
-
- /**
- * @return true if location-data received should expire (and be deleted)
- * by the time provided in the getRelativeExpirationTimeHours() method.
- *
- * @hide
- */
- public boolean getRetentionExpiresIndication() {
- return mUsageRetentionExpires;
- }
-
- /**
- * @return true if there is extra location info available on association.
- *
- * @hide
- */
- @SystemApi
- public boolean getExtraInfoOnAssociationIndication() {
- return mUsageExtraInfoOnAssociation;
- }
-
- /**
- * @return the Immutable list of colocated BSSIDs at the responder.
- *
- * <p> Will return an empty list when there are no bssids listed.
- */
- public List<MacAddress> getColocatedBssids() {
- return Collections.unmodifiableList(mBssidList);
- }
-
- /**
- * @return the civic location represented as an {@link Address} object (best effort).
- *
- * <p> Will return a {@code null} when there is no Civic Location defined.
- */
- @Nullable
- public Address toCivicLocationAddress() {
- if (mCivicLocation != null && mCivicLocation.isValid()) {
- return mCivicLocation.toAddress();
- } else {
- return null;
- }
- }
-
- /**
- * @return the civic location represented as a {@link SparseArray}
- * <p>
- * Valid keys to access the SparseArray can be found in {@code CivicLocationKeys}.
- * </p>
- * <p> Will return a {@code null} when there is no Civic Location defined.
- *
- */
- @Nullable
- @SuppressLint("ChangedType")
- public SparseArray<String> toCivicLocationSparseArray() {
- if (mCivicLocation != null && mCivicLocation.isValid()) {
- return mCivicLocation.toSparseArray();
- } else {
- return null;
- }
- }
-
- /**
- * @return the civic location two upper-case ASCII character country code defined in ISO 3166.
- *
- * <p> Will return a {@code null} when there is no country code defined.
- *
- * @hide
- */
- @Nullable
- public String getCivicLocationCountryCode() {
- return mCivicLocationCountryCode;
- }
-
- /**
- * @return the value of the Civic Location String associated with a key.
- *
- * <p> Will return a {@code null} when there is no value associated with the key provided.
- *
- * @param key used to find a corresponding value in the Civic Location Tuple list
- *
- * @hide
- */
- @Nullable
- public String getCivicLocationElementValue(@CivicLocationKeysType int key) {
- return mCivicLocation.getCivicElementValue(key);
- }
-
- /**
- * @return the Map Image file Mime type, referred to by getMapImageUrl().
- */
- @Nullable
- public String getMapImageMimeType() {
- if (mMapImageUri == null) {
- return null;
- } else {
- return imageTypeToMime(mMapImageType, mMapImageUri.toString());
- }
- }
-
- /**
- * @return a URI referencing a map-file showing the local floor plan.
- *
- * <p> Will return a {@code null} when there is no URI defined.
- */
- @Nullable
- public Uri getMapImageUri() {
- return mMapImageUri;
- }
-}
diff --git a/wifi/java/android/net/wifi/rtt/WifiRttManager.java b/wifi/java/android/net/wifi/rtt/WifiRttManager.java
deleted file mode 100644
index 865702af695c..000000000000
--- a/wifi/java/android/net/wifi/rtt/WifiRttManager.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * Copyright (C) 2018 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.rtt;
-
-import static android.Manifest.permission.ACCESS_FINE_LOCATION;
-import static android.Manifest.permission.ACCESS_WIFI_STATE;
-import static android.Manifest.permission.CHANGE_WIFI_STATE;
-import static android.Manifest.permission.LOCATION_HARDWARE;
-
-import android.annotation.CallbackExecutor;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
-import android.annotation.SdkConstant;
-import android.annotation.SystemApi;
-import android.annotation.SystemService;
-import android.content.Context;
-import android.os.Binder;
-import android.os.RemoteException;
-import android.os.WorkSource;
-import android.util.Log;
-
-import java.util.List;
-import java.util.concurrent.Executor;
-
-/**
- * This class provides the primary API for measuring distance (range) to other devices using the
- * IEEE 802.11mc Wi-Fi Round Trip Time (RTT) technology.
- * <p>
- * The devices which can be ranged include:
- * <li>Access Points (APs)
- * <li>Wi-Fi Aware peers
- * <p>
- * Ranging requests are triggered using
- * {@link #startRanging(RangingRequest, Executor, RangingResultCallback)}. Results (in case of
- * successful operation) are returned in the {@link RangingResultCallback#onRangingResults(List)}
- * callback.
- * <p>
- * Wi-Fi RTT may not be usable at some points, e.g. when Wi-Fi is disabled. To validate that
- * the functionality is available use the {@link #isAvailable()} function. To track
- * changes in RTT usability register for the {@link #ACTION_WIFI_RTT_STATE_CHANGED}
- * broadcast. Note that this broadcast is not sticky - you should register for it and then
- * check the above API to avoid a race condition.
- */
-@SystemService(Context.WIFI_RTT_RANGING_SERVICE)
-public class WifiRttManager {
- private static final String TAG = "WifiRttManager";
- private static final boolean VDBG = false;
-
- private final Context mContext;
- private final IWifiRttManager mService;
-
- /**
- * Broadcast intent action to indicate that the state of Wi-Fi RTT availability has changed.
- * Use the {@link #isAvailable()} to query the current status.
- * This broadcast is <b>not</b> sticky, use the {@link #isAvailable()} API after registering
- * the broadcast to check the current state of Wi-Fi RTT.
- * <p>Note: The broadcast is only delivered to registered receivers - no manifest registered
- * components will be launched.
- */
- @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
- public static final String ACTION_WIFI_RTT_STATE_CHANGED =
- "android.net.wifi.rtt.action.WIFI_RTT_STATE_CHANGED";
-
- /** @hide */
- public WifiRttManager(@NonNull Context context, @NonNull IWifiRttManager service) {
- mContext = context;
- mService = service;
- }
-
- /**
- * Returns the current status of RTT API: whether or not RTT is available. To track
- * changes in the state of RTT API register for the
- * {@link #ACTION_WIFI_RTT_STATE_CHANGED} broadcast.
- * <p>Note: availability of RTT does not mean that the app can use the API. The app's
- * permissions and platform Location Mode are validated at run-time.
- *
- * @return A boolean indicating whether the app can use the RTT API at this time (true) or
- * not (false).
- */
- public boolean isAvailable() {
- try {
- return mService.isAvailable();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Initiate a request to range to a set of devices specified in the {@link RangingRequest}.
- * Results will be returned in the {@link RangingResultCallback} set of callbacks.
- *
- * @param request A request specifying a set of devices whose distance measurements are
- * requested.
- * @param executor The Executor on which to run the callback.
- * @param callback A callback for the result of the ranging request.
- */
- @RequiresPermission(allOf = {ACCESS_FINE_LOCATION, CHANGE_WIFI_STATE, ACCESS_WIFI_STATE})
- public void startRanging(@NonNull RangingRequest request,
- @NonNull @CallbackExecutor Executor executor, @NonNull RangingResultCallback callback) {
- startRanging(null, request, executor, callback);
- }
-
- /**
- * Initiate a request to range to a set of devices specified in the {@link RangingRequest}.
- * Results will be returned in the {@link RangingResultCallback} set of callbacks.
- *
- * @param workSource A mechanism to specify an alternative work-source for the request.
- * @param request A request specifying a set of devices whose distance measurements are
- * requested.
- * @param executor The Executor on which to run the callback.
- * @param callback A callback for the result of the ranging request.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(allOf = {LOCATION_HARDWARE, ACCESS_FINE_LOCATION, CHANGE_WIFI_STATE,
- ACCESS_WIFI_STATE})
- public void startRanging(@Nullable WorkSource workSource, @NonNull RangingRequest request,
- @NonNull @CallbackExecutor Executor executor, @NonNull RangingResultCallback callback) {
- if (VDBG) {
- Log.v(TAG, "startRanging: workSource=" + workSource + ", request=" + request
- + ", callback=" + callback + ", executor=" + executor);
- }
-
- if (executor == null) {
- throw new IllegalArgumentException("Null executor provided");
- }
- if (callback == null) {
- throw new IllegalArgumentException("Null callback provided");
- }
-
- Binder binder = new Binder();
- try {
- mService.startRanging(binder, mContext.getOpPackageName(),
- mContext.getAttributionTag(), workSource, request, new IRttCallback.Stub() {
- @Override
- public void onRangingFailure(int status) throws RemoteException {
- clearCallingIdentity();
- executor.execute(() -> callback.onRangingFailure(status));
- }
-
- @Override
- public void onRangingResults(List<RangingResult> results)
- throws RemoteException {
- clearCallingIdentity();
- executor.execute(() -> callback.onRangingResults(results));
- }
- });
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Cancel all ranging requests for the specified work sources. The requests have been requested
- * using {@link #startRanging(WorkSource, RangingRequest, Executor, RangingResultCallback)}.
- *
- * @param workSource The work-sources of the requesters.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(allOf = {LOCATION_HARDWARE})
- public void cancelRanging(@Nullable WorkSource workSource) {
- if (VDBG) {
- Log.v(TAG, "cancelRanging: workSource=" + workSource);
- }
-
- try {
- mService.cancelRanging(workSource);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-}
diff --git a/wifi/java/android/net/wifi/rtt/package.html b/wifi/java/android/net/wifi/rtt/package.html
deleted file mode 100644
index 4a32f5206fde..000000000000
--- a/wifi/java/android/net/wifi/rtt/package.html
+++ /dev/null
@@ -1,45 +0,0 @@
-<HTML>
-<BODY>
-<p>Provides classes which allow applications to use Wi-Fi RTT (IEEE 802.11mc) to measure distance
- to supporting Access Points and peer devices.</p>
-<p>The primary entry point to Wi-Fi RTT capabilities is the
- {@link android.net.wifi.rtt.WifiRttManager} class, which is acquired by calling
- {@link android.content.Context#getSystemService(String)
- Context.getSystemService(Context.WIFI_RTT_RANGING_SERVICE)}</p>
-
-<p>Some APIs may require the following user permissions:</p>
-<ul>
- <li>{@link android.Manifest.permission#ACCESS_WIFI_STATE}</li>
- <li>{@link android.Manifest.permission#CHANGE_WIFI_STATE}</li>
- <li>{@link android.Manifest.permission#ACCESS_FINE_LOCATION}</li>
-</ul>
-<p>Usage of the API is also gated by the device's Location Mode: whether it permits Wi-Fi based
-location to be queried.</p>
-
-<p class="note"><strong>Note:</strong> Not all Android-powered devices support Wi-Fi RTT
- functionality.
- If your application only works with Wi-Fi RTT (i.e. it should only be installed on devices which
- support Wi-Fi RTT), declare so with a <a
- href="{@docRoot}guide/topics/manifest/uses-feature-element.html">
- {@code <uses-feature>}</a>
- element in the manifest file:</p>
-<pre>
-&lt;manifest ...>
- &lt;uses-feature android:name="android.hardware.wifi.rtt" />
- ...
-&lt;/manifest>
-</pre>
-<p>Alternatively, if your application does not require Wi-Fi RTT but can take advantage of it if
- available, you can perform
- the check at run-time in your code using {@link
- android.content.pm.PackageManager#hasSystemFeature(String)} with {@link
- android.content.pm.PackageManager#FEATURE_WIFI_RTT}:</p>
-<pre>
- getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_RTT)
-</pre>
-
-<p>For an example of this functionality, see
-<a href="{@docRoot}guide/topics/connectivity/wifi-rtt" class="external">Wi-Fi location: ranging
-with RTT</a>.</p>
-</BODY>
-</HTML>
diff --git a/wifi/java/android/net/wifi/util/HexEncoding.java b/wifi/java/android/net/wifi/util/HexEncoding.java
deleted file mode 100644
index 9ebf947e2dc3..000000000000
--- a/wifi/java/android/net/wifi/util/HexEncoding.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (C) 2014 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;
-
-/**
- * Hexadecimal encoding where each byte is represented by two hexadecimal digits.
- *
- * Note: this is copied from {@link libcore.util.HexEncoding}.
- *
- * @hide
- */
-public class HexEncoding {
-
- private static final char[] LOWER_CASE_DIGITS = {
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
- };
-
- private static final char[] UPPER_CASE_DIGITS = {
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
- };
-
- /** Hidden constructor to prevent instantiation. */
- private HexEncoding() {}
-
- /**
- * Encodes the provided byte as a two-digit hexadecimal String value.
- */
- public static String encodeToString(byte b, boolean upperCase) {
- char[] digits = upperCase ? UPPER_CASE_DIGITS : LOWER_CASE_DIGITS;
- char[] buf = new char[2]; // We always want two digits.
- buf[0] = digits[(b >> 4) & 0xf];
- buf[1] = digits[b & 0xf];
- return new String(buf, 0, 2);
- }
-
- /**
- * Encodes the provided data as a sequence of hexadecimal characters.
- */
- public static char[] encode(byte[] data) {
- return encode(data, 0, data.length, true /* upperCase */);
- }
-
- /**
- * Encodes the provided data as a sequence of hexadecimal characters.
- */
- public static char[] encode(byte[] data, boolean upperCase) {
- return encode(data, 0, data.length, upperCase);
- }
-
- /**
- * Encodes the provided data as a sequence of hexadecimal characters.
- */
- public static char[] encode(byte[] data, int offset, int len) {
- return encode(data, offset, len, true /* upperCase */);
- }
-
- /**
- * Encodes the provided data as a sequence of hexadecimal characters.
- */
- private static char[] encode(byte[] data, int offset, int len, boolean upperCase) {
- char[] digits = upperCase ? UPPER_CASE_DIGITS : LOWER_CASE_DIGITS;
- char[] result = new char[len * 2];
- for (int i = 0; i < len; i++) {
- byte b = data[offset + i];
- int resultIndex = 2 * i;
- result[resultIndex] = (digits[(b >> 4) & 0x0f]);
- result[resultIndex + 1] = (digits[b & 0x0f]);
- }
-
- return result;
- }
-
- /**
- * Encodes the provided data as a sequence of hexadecimal characters.
- */
- public static String encodeToString(byte[] data) {
- return encodeToString(data, true /* upperCase */);
- }
-
- /**
- * Encodes the provided data as a sequence of hexadecimal characters.
- */
- public static String encodeToString(byte[] data, boolean upperCase) {
- return new String(encode(data, upperCase));
- }
-
- /**
- * Decodes the provided hexadecimal string into a byte array. Odd-length inputs
- * are not allowed.
- *
- * Throws an {@code IllegalArgumentException} if the input is malformed.
- */
- public static byte[] decode(String encoded) throws IllegalArgumentException {
- return decode(encoded.toCharArray());
- }
-
- /**
- * Decodes the provided hexadecimal string into a byte array. If {@code allowSingleChar}
- * is {@code true} odd-length inputs are allowed and the first character is interpreted
- * as the lower bits of the first result byte.
- *
- * Throws an {@code IllegalArgumentException} if the input is malformed.
- */
- public static byte[] decode(String encoded, boolean allowSingleChar)
- throws IllegalArgumentException {
- return decode(encoded.toCharArray(), allowSingleChar);
- }
-
- /**
- * Decodes the provided hexadecimal string into a byte array. Odd-length inputs
- * are not allowed.
- *
- * Throws an {@code IllegalArgumentException} if the input is malformed.
- */
- public static byte[] decode(char[] encoded) throws IllegalArgumentException {
- return decode(encoded, false);
- }
-
- /**
- * Decodes the provided hexadecimal string into a byte array. If {@code allowSingleChar}
- * is {@code true} odd-length inputs are allowed and the first character is interpreted
- * as the lower bits of the first result byte.
- *
- * Throws an {@code IllegalArgumentException} if the input is malformed.
- */
- public static byte[] decode(char[] encoded, boolean allowSingleChar)
- throws IllegalArgumentException {
- int encodedLength = encoded.length;
- int resultLengthBytes = (encodedLength + 1) / 2;
- byte[] result = new byte[resultLengthBytes];
-
- int resultOffset = 0;
- int i = 0;
- if (allowSingleChar) {
- if ((encodedLength % 2) != 0) {
- // Odd number of digits -- the first digit is the lower 4 bits of the first result
- // byte.
- result[resultOffset++] = (byte) toDigit(encoded, i);
- i++;
- }
- } else {
- if ((encodedLength % 2) != 0) {
- throw new IllegalArgumentException("Invalid input length: " + encodedLength);
- }
- }
-
- for (; i < encodedLength; i += 2) {
- result[resultOffset++] = (byte) ((toDigit(encoded, i) << 4) | toDigit(encoded, i + 1));
- }
-
- return result;
- }
-
- private static int toDigit(char[] str, int offset) throws IllegalArgumentException {
- // NOTE: that this isn't really a code point in the traditional sense, since we're
- // just rejecting surrogate pairs outright.
- int pseudoCodePoint = str[offset];
-
- if ('0' <= pseudoCodePoint && pseudoCodePoint <= '9') {
- return pseudoCodePoint - '0';
- } else if ('a' <= pseudoCodePoint && pseudoCodePoint <= 'f') {
- return 10 + (pseudoCodePoint - 'a');
- } else if ('A' <= pseudoCodePoint && pseudoCodePoint <= 'F') {
- return 10 + (pseudoCodePoint - 'A');
- }
-
- throw new IllegalArgumentException("Illegal char: " + str[offset] + " at offset " + offset);
- }
-}