Merge changes from topic "set-thread-enabled" into main
* changes:
Add service implementation for ThreadNetworkController#setEnabled
Add setEnabled API
diff --git a/framework-t/api/current.txt b/framework-t/api/current.txt
index 60a88c0..7cd3d4f 100644
--- a/framework-t/api/current.txt
+++ b/framework-t/api/current.txt
@@ -210,9 +210,26 @@
package android.net.nsd {
+ @FlaggedApi("com.android.net.flags.nsd_subtypes_support_enabled") public final class DiscoveryRequest implements android.os.Parcelable {
+ method public int describeContents();
+ method @Nullable public android.net.Network getNetwork();
+ method @NonNull public String getServiceType();
+ method @Nullable public String getSubtype();
+ method public void writeToParcel(@NonNull android.os.Parcel, int);
+ field @NonNull public static final android.os.Parcelable.Creator<android.net.nsd.DiscoveryRequest> CREATOR;
+ }
+
+ public static final class DiscoveryRequest.Builder {
+ ctor public DiscoveryRequest.Builder(@NonNull String);
+ method @NonNull public android.net.nsd.DiscoveryRequest build();
+ method @NonNull public android.net.nsd.DiscoveryRequest.Builder setNetwork(@Nullable android.net.Network);
+ method @NonNull public android.net.nsd.DiscoveryRequest.Builder setSubtype(@Nullable String);
+ }
+
public final class NsdManager {
method public void discoverServices(String, int, android.net.nsd.NsdManager.DiscoveryListener);
method public void discoverServices(@NonNull String, int, @Nullable android.net.Network, @NonNull java.util.concurrent.Executor, @NonNull android.net.nsd.NsdManager.DiscoveryListener);
+ method @FlaggedApi("com.android.net.flags.nsd_subtypes_support_enabled") public void discoverServices(@NonNull android.net.nsd.DiscoveryRequest, @NonNull java.util.concurrent.Executor, @NonNull android.net.nsd.NsdManager.DiscoveryListener);
method @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public void discoverServices(@NonNull String, int, @NonNull android.net.NetworkRequest, @NonNull java.util.concurrent.Executor, @NonNull android.net.nsd.NsdManager.DiscoveryListener);
method public void registerService(android.net.nsd.NsdServiceInfo, int, android.net.nsd.NsdManager.RegistrationListener);
method public void registerService(@NonNull android.net.nsd.NsdServiceInfo, int, @NonNull java.util.concurrent.Executor, @NonNull android.net.nsd.NsdManager.RegistrationListener);
diff --git a/framework-t/src/android/net/nsd/DiscoveryRequest.java b/framework-t/src/android/net/nsd/DiscoveryRequest.java
new file mode 100644
index 0000000..b0b71ea
--- /dev/null
+++ b/framework-t/src/android/net/nsd/DiscoveryRequest.java
@@ -0,0 +1,247 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.nsd;
+
+import android.annotation.FlaggedApi;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.net.Network;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.text.TextUtils;
+
+import java.util.Objects;
+
+/**
+ * Encapsulates parameters for {@link NsdManager#discoverServices}.
+ */
+@FlaggedApi(NsdManager.Flags.NSD_SUBTYPES_SUPPORT_ENABLED)
+public final class DiscoveryRequest implements Parcelable {
+ private final int mProtocolType;
+
+ @NonNull
+ private final String mServiceType;
+
+ @Nullable
+ private final String mSubtype;
+
+ @Nullable
+ private final Network mNetwork;
+
+ // TODO: add mDiscoveryConfig for more fine-grained discovery behavior control
+
+ @NonNull
+ public static final Creator<DiscoveryRequest> CREATOR =
+ new Creator<>() {
+ @Override
+ public DiscoveryRequest createFromParcel(Parcel in) {
+ int protocolType = in.readInt();
+ String serviceType = in.readString();
+ String subtype = in.readString();
+ Network network =
+ in.readParcelable(Network.class.getClassLoader(), Network.class);
+ return new DiscoveryRequest(protocolType, serviceType, subtype, network);
+ }
+
+ @Override
+ public DiscoveryRequest[] newArray(int size) {
+ return new DiscoveryRequest[size];
+ }
+ };
+
+ private DiscoveryRequest(int protocolType, @NonNull String serviceType,
+ @Nullable String subtype, @Nullable Network network) {
+ mProtocolType = protocolType;
+ mServiceType = serviceType;
+ mSubtype = subtype;
+ mNetwork = network;
+ }
+
+ /**
+ * Returns the service type in format of dot-joint string of two labels.
+ *
+ * For example, "_ipp._tcp" for internet printer and "_matter._tcp" for <a
+ * href="https://csa-iot.org/all-solutions/matter">Matter</a> operational device.
+ */
+ @NonNull
+ public String getServiceType() {
+ return mServiceType;
+ }
+
+ /**
+ * Returns the subtype without the trailing "._sub" label or {@code null} if no subtype is
+ * specified.
+ *
+ * For example, the return value will be "_printer" for subtype "_printer._sub".
+ */
+ @Nullable
+ public String getSubtype() {
+ return mSubtype;
+ }
+
+ /**
+ * Returns the service discovery protocol.
+ *
+ * @hide
+ */
+ public int getProtocolType() {
+ return mProtocolType;
+ }
+
+ /**
+ * Returns the {@link Network} on which the query should be sent or {@code null} if no
+ * network is specified.
+ */
+ @Nullable
+ public Network getNetwork() {
+ return mNetwork;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(", protocolType: ").append(mProtocolType)
+ .append(", serviceType: ").append(mServiceType)
+ .append(", subtype: ").append(mSubtype)
+ .append(", network: ").append(mNetwork);
+ return sb.toString();
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (this == other) {
+ return true;
+ } else if (!(other instanceof DiscoveryRequest)) {
+ return false;
+ } else {
+ DiscoveryRequest otherRequest = (DiscoveryRequest) other;
+ return mProtocolType == otherRequest.mProtocolType
+ && Objects.equals(mServiceType, otherRequest.mServiceType)
+ && Objects.equals(mSubtype, otherRequest.mSubtype)
+ && Objects.equals(mNetwork, otherRequest.mNetwork);
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(mProtocolType, mServiceType, mSubtype, mNetwork);
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeInt(mProtocolType);
+ dest.writeString(mServiceType);
+ dest.writeString(mSubtype);
+ dest.writeParcelable(mNetwork, flags);
+ }
+
+ /** The builder for creating new {@link DiscoveryRequest} objects. */
+ public static final class Builder {
+ private final int mProtocolType;
+
+ @NonNull
+ private String mServiceType;
+
+ @Nullable
+ private String mSubtype;
+
+ @Nullable
+ private Network mNetwork;
+
+ /**
+ * Creates a new default {@link Builder} object with given service type.
+ *
+ * @throws IllegalArgumentException if {@code serviceType} is {@code null} or an empty
+ * string
+ */
+ public Builder(@NonNull String serviceType) {
+ this(NsdManager.PROTOCOL_DNS_SD, serviceType);
+ }
+
+ /** @hide */
+ public Builder(int protocolType, @NonNull String serviceType) {
+ NsdManager.checkProtocol(protocolType);
+ mProtocolType = protocolType;
+ setServiceType(serviceType);
+ }
+
+ /**
+ * Sets the service type to be discovered or {@code null} if no services should be queried.
+ *
+ * The {@code serviceType} must be a dot-joint string of two labels. For example,
+ * "_ipp._tcp" for internet printer. Additionally, the first label must start with
+ * underscore ('_') and the second label must be either "_udp" or "_tcp". Otherwise, {@link
+ * NsdManager#discoverServices} will fail with {@link NsdManager#FAILURE_BAD_PARAMETER}.
+ *
+ * @throws IllegalArgumentException if {@code serviceType} is {@code null} or an empty
+ * string
+ *
+ * @hide
+ */
+ @NonNull
+ public Builder setServiceType(@NonNull String serviceType) {
+ if (TextUtils.isEmpty(serviceType)) {
+ throw new IllegalArgumentException("Service type cannot be empty");
+ }
+ mServiceType = serviceType;
+ return this;
+ }
+
+ /**
+ * Sets the optional subtype of the services to be discovered.
+ *
+ * If a non-empty {@code subtype} is specified, it must start with underscore ('_') and
+ * have the trailing "._sub" removed. Otherwise, {@link NsdManager#discoverServices} will
+ * fail with {@link NsdManager#FAILURE_BAD_PARAMETER}. For example, {@code subtype} should
+ * be "_printer" for DNS name "_printer._sub._http._tcp". In this case, only services with
+ * this {@code subtype} will be queried, rather than all services of the base service type.
+ *
+ * Note that a non-empty service type must be specified with {@link #setServiceType} if a
+ * non-empty subtype is specified by this method.
+ */
+ @NonNull
+ public Builder setSubtype(@Nullable String subtype) {
+ mSubtype = subtype;
+ return this;
+ }
+
+ /**
+ * Sets the {@link Network} on which the discovery queries should be sent.
+ *
+ * @param network the discovery network or {@code null} if the query should be sent on
+ * all supported networks
+ */
+ @NonNull
+ public Builder setNetwork(@Nullable Network network) {
+ mNetwork = network;
+ return this;
+ }
+
+ /**
+ * Creates a new {@link DiscoveryRequest} object.
+ */
+ @NonNull
+ public DiscoveryRequest build() {
+ return new DiscoveryRequest(mProtocolType, mServiceType, mSubtype, mNetwork);
+ }
+ }
+}
diff --git a/framework-t/src/android/net/nsd/INsdManagerCallback.aidl b/framework-t/src/android/net/nsd/INsdManagerCallback.aidl
index d89bfa9..55820ec 100644
--- a/framework-t/src/android/net/nsd/INsdManagerCallback.aidl
+++ b/framework-t/src/android/net/nsd/INsdManagerCallback.aidl
@@ -17,6 +17,7 @@
package android.net.nsd;
import android.os.Messenger;
+import android.net.nsd.DiscoveryRequest;
import android.net.nsd.NsdServiceInfo;
/**
@@ -24,7 +25,7 @@
* @hide
*/
oneway interface INsdManagerCallback {
- void onDiscoverServicesStarted(int listenerKey, in NsdServiceInfo info);
+ void onDiscoverServicesStarted(int listenerKey, in DiscoveryRequest discoveryRequest);
void onDiscoverServicesFailed(int listenerKey, int error);
void onServiceFound(int listenerKey, in NsdServiceInfo info);
void onServiceLost(int listenerKey, in NsdServiceInfo info);
diff --git a/framework-t/src/android/net/nsd/INsdServiceConnector.aidl b/framework-t/src/android/net/nsd/INsdServiceConnector.aidl
index b03eb29..9a31278 100644
--- a/framework-t/src/android/net/nsd/INsdServiceConnector.aidl
+++ b/framework-t/src/android/net/nsd/INsdServiceConnector.aidl
@@ -17,6 +17,7 @@
package android.net.nsd;
import android.net.nsd.AdvertisingRequest;
+import android.net.nsd.DiscoveryRequest;
import android.net.nsd.INsdManagerCallback;
import android.net.nsd.IOffloadEngine;
import android.net.nsd.NsdServiceInfo;
@@ -30,7 +31,7 @@
interface INsdServiceConnector {
void registerService(int listenerKey, in AdvertisingRequest advertisingRequest);
void unregisterService(int listenerKey);
- void discoverServices(int listenerKey, in NsdServiceInfo serviceInfo);
+ void discoverServices(int listenerKey, in DiscoveryRequest discoveryRequest);
void stopDiscovery(int listenerKey);
void resolveService(int listenerKey, in NsdServiceInfo serviceInfo);
void startDaemon();
@@ -39,4 +40,4 @@
void unregisterServiceInfoCallback(int listenerKey);
void registerOffloadEngine(String ifaceName, in IOffloadEngine cb, long offloadCapabilities, long offloadType);
void unregisterOffloadEngine(in IOffloadEngine cb);
-}
\ No newline at end of file
+}
diff --git a/framework-t/src/android/net/nsd/NsdManager.java b/framework-t/src/android/net/nsd/NsdManager.java
index b4f2be9..263acf2 100644
--- a/framework-t/src/android/net/nsd/NsdManager.java
+++ b/framework-t/src/android/net/nsd/NsdManager.java
@@ -57,6 +57,7 @@
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
+import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.regex.Matcher;
@@ -360,6 +361,8 @@
@GuardedBy("mMapLock")
private final SparseArray<NsdServiceInfo> mServiceMap = new SparseArray<>();
@GuardedBy("mMapLock")
+ private final SparseArray<DiscoveryRequest> mDiscoveryMap = new SparseArray<>();
+ @GuardedBy("mMapLock")
private final SparseArray<Executor> mExecutorMap = new SparseArray<>();
private final Object mMapLock = new Object();
// Map of listener key sent by client -> per-network discovery tracker
@@ -715,6 +718,12 @@
mServHandler.sendMessage(mServHandler.obtainMessage(message, 0, listenerKey, info));
}
+ private void sendDiscoveryRequest(
+ int message, int listenerKey, DiscoveryRequest discoveryRequest) {
+ mServHandler.sendMessage(
+ mServHandler.obtainMessage(message, 0, listenerKey, discoveryRequest));
+ }
+
private void sendError(int message, int listenerKey, int error) {
mServHandler.sendMessage(mServHandler.obtainMessage(message, error, listenerKey));
}
@@ -724,8 +733,8 @@
}
@Override
- public void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info) {
- sendInfo(DISCOVER_SERVICES_STARTED, listenerKey, info);
+ public void onDiscoverServicesStarted(int listenerKey, DiscoveryRequest discoveryRequest) {
+ sendDiscoveryRequest(DISCOVER_SERVICES_STARTED, listenerKey, discoveryRequest);
}
@Override
@@ -1003,10 +1012,12 @@
final Object obj = message.obj;
final Object listener;
final NsdServiceInfo ns;
+ final DiscoveryRequest discoveryRequest;
final Executor executor;
synchronized (mMapLock) {
listener = mListenerMap.get(key);
ns = mServiceMap.get(key);
+ discoveryRequest = mDiscoveryMap.get(key);
executor = mExecutorMap.get(key);
}
if (listener == null) {
@@ -1014,17 +1025,22 @@
return;
}
if (DBG) {
- Log.d(TAG, "received " + nameOf(what) + " for key " + key + ", service " + ns);
+ if (discoveryRequest != null) {
+ Log.d(TAG, "received " + nameOf(what) + " for key " + key + ", discovery "
+ + discoveryRequest);
+ } else {
+ Log.d(TAG, "received " + nameOf(what) + " for key " + key + ", service " + ns);
+ }
}
switch (what) {
case DISCOVER_SERVICES_STARTED:
- final String s = getNsdServiceInfoType((NsdServiceInfo) obj);
+ final String s = getNsdServiceInfoType((DiscoveryRequest) obj);
executor.execute(() -> ((DiscoveryListener) listener).onDiscoveryStarted(s));
break;
case DISCOVER_SERVICES_FAILED:
removeListener(key);
executor.execute(() -> ((DiscoveryListener) listener).onStartDiscoveryFailed(
- getNsdServiceInfoType(ns), errorCode));
+ getNsdServiceInfoType(discoveryRequest), errorCode));
break;
case SERVICE_FOUND:
executor.execute(() -> ((DiscoveryListener) listener).onServiceFound(
@@ -1039,12 +1055,12 @@
// the effect for the client is indistinguishable from STOP_DISCOVERY_SUCCEEDED
removeListener(key);
executor.execute(() -> ((DiscoveryListener) listener).onStopDiscoveryFailed(
- getNsdServiceInfoType(ns), errorCode));
+ getNsdServiceInfoType(discoveryRequest), errorCode));
break;
case STOP_DISCOVERY_SUCCEEDED:
removeListener(key);
executor.execute(() -> ((DiscoveryListener) listener).onDiscoveryStopped(
- getNsdServiceInfoType(ns)));
+ getNsdServiceInfoType(discoveryRequest)));
break;
case REGISTER_SERVICE_FAILED:
removeListener(key);
@@ -1117,21 +1133,33 @@
return mListenerKey;
}
- // Assert that the listener is not in the map, then add it and returns its key
- private int putListener(Object listener, Executor e, NsdServiceInfo s) {
- checkListener(listener);
- final int key;
+ private int putListener(Object listener, Executor e, NsdServiceInfo serviceInfo) {
synchronized (mMapLock) {
- int valueIndex = mListenerMap.indexOfValue(listener);
+ return putListener(listener, e, mServiceMap, serviceInfo);
+ }
+ }
+
+ private int putListener(Object listener, Executor e, DiscoveryRequest discoveryRequest) {
+ synchronized (mMapLock) {
+ return putListener(listener, e, mDiscoveryMap, discoveryRequest);
+ }
+ }
+
+ // Assert that the listener is not in the map, then add it and returns its key
+ private <T> int putListener(Object listener, Executor e, SparseArray<T> map, T value) {
+ synchronized (mMapLock) {
+ checkListener(listener);
+ final int key;
+ final int valueIndex = mListenerMap.indexOfValue(listener);
if (valueIndex != -1) {
throw new IllegalArgumentException("listener already in use");
}
key = nextListenerKey();
mListenerMap.put(key, listener);
- mServiceMap.put(key, s);
+ map.put(key, value);
mExecutorMap.put(key, e);
+ return key;
}
- return key;
}
private int updateRegisteredListener(Object listener, Executor e, NsdServiceInfo s) {
@@ -1148,6 +1176,7 @@
synchronized (mMapLock) {
mListenerMap.remove(key);
mServiceMap.remove(key);
+ mDiscoveryMap.remove(key);
mExecutorMap.remove(key);
}
}
@@ -1163,9 +1192,9 @@
}
}
- private static String getNsdServiceInfoType(NsdServiceInfo s) {
- if (s == null) return "?";
- return s.getServiceType();
+ private static String getNsdServiceInfoType(DiscoveryRequest r) {
+ if (r == null) return "?";
+ return r.getServiceType();
}
/**
@@ -1406,15 +1435,44 @@
if (TextUtils.isEmpty(serviceType)) {
throw new IllegalArgumentException("Service type cannot be empty");
}
- checkProtocol(protocolType);
+ DiscoveryRequest request = new DiscoveryRequest.Builder(protocolType, serviceType)
+ .setNetwork(network).build();
+ discoverServices(request, executor, listener);
+ }
- NsdServiceInfo s = new NsdServiceInfo();
- s.setServiceType(serviceType);
- s.setNetwork(network);
-
- int key = putListener(listener, executor, s);
+ /**
+ * Initiates service discovery to browse for instances of a service type. Service discovery
+ * consumes network bandwidth and will continue until the application calls
+ * {@link #stopServiceDiscovery}.
+ *
+ * <p> The function call immediately returns after sending a request to start service
+ * discovery to the framework. The application is notified of a success to initiate
+ * discovery through the callback {@link DiscoveryListener#onDiscoveryStarted} or a failure
+ * through {@link DiscoveryListener#onStartDiscoveryFailed}.
+ *
+ * <p> Upon successful start, application is notified when a service is found with
+ * {@link DiscoveryListener#onServiceFound} or when a service is lost with
+ * {@link DiscoveryListener#onServiceLost}.
+ *
+ * <p> Upon failure to start, service discovery is not active and application does
+ * not need to invoke {@link #stopServiceDiscovery}
+ *
+ * <p> The application should call {@link #stopServiceDiscovery} when discovery of this
+ * service type is no longer required, and/or whenever the application is paused or
+ * stopped.
+ *
+ * @param discoveryRequest the {@link DiscoveryRequest} object which specifies the discovery
+ * parameters such as service type, subtype and network
+ * @param executor Executor to run listener callbacks with
+ * @param listener The listener notifies of a successful discovery and is used
+ * to stop discovery on this serviceType through a call on {@link #stopServiceDiscovery}.
+ */
+ @FlaggedApi(Flags.NSD_SUBTYPES_SUPPORT_ENABLED)
+ public void discoverServices(@NonNull DiscoveryRequest discoveryRequest,
+ @NonNull Executor executor, @NonNull DiscoveryListener listener) {
+ int key = putListener(listener, executor, discoveryRequest);
try {
- mService.discoverServices(key, s);
+ mService.discoverServices(key, discoveryRequest);
} catch (RemoteException e) {
e.rethrowFromSystemServer();
}
@@ -1465,12 +1523,10 @@
throw new IllegalArgumentException("Service type cannot be empty");
}
Objects.requireNonNull(networkRequest, "NetworkRequest cannot be null");
- checkProtocol(protocolType);
+ DiscoveryRequest discoveryRequest =
+ new DiscoveryRequest.Builder(protocolType, serviceType).build();
- NsdServiceInfo s = new NsdServiceInfo();
- s.setServiceType(serviceType);
-
- final int baseListenerKey = putListener(listener, executor, s);
+ final int baseListenerKey = putListener(listener, executor, discoveryRequest);
final PerNetworkDiscoveryTracker discoveryInfo = new PerNetworkDiscoveryTracker(
serviceType, protocolType, executor, listener);
@@ -1602,6 +1658,7 @@
* @param executor Executor to run callbacks with
* @param listener to receive callback upon service update
*/
+ // TODO: use {@link DiscoveryRequest} to specify the service to be subscribed
public void registerServiceInfoCallback(@NonNull NsdServiceInfo serviceInfo,
@NonNull Executor executor, @NonNull ServiceInfoCallback listener) {
checkServiceInfo(serviceInfo);
@@ -1643,7 +1700,7 @@
Objects.requireNonNull(listener, "listener cannot be null");
}
- private static void checkProtocol(int protocolType) {
+ static void checkProtocol(int protocolType) {
if (protocolType != PROTOCOL_DNS_SD) {
throw new IllegalArgumentException("Unsupported protocol");
}
diff --git a/framework/aidl-export/android/net/nsd/DiscoveryRequest.aidl b/framework/aidl-export/android/net/nsd/DiscoveryRequest.aidl
new file mode 100644
index 0000000..481a066
--- /dev/null
+++ b/framework/aidl-export/android/net/nsd/DiscoveryRequest.aidl
@@ -0,0 +1,19 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.nsd;
+
+@JavaOnlyStableParcelable parcelable DiscoveryRequest;
diff --git a/framework/src/android/net/BpfNetMapsUtils.java b/framework/src/android/net/BpfNetMapsUtils.java
index 11d610c..0be30bb 100644
--- a/framework/src/android/net/BpfNetMapsUtils.java
+++ b/framework/src/android/net/BpfNetMapsUtils.java
@@ -125,13 +125,11 @@
return sj.toString();
}
- public static final boolean PRE_T = !SdkLevel.isAtLeastT();
-
/**
* Throw UnsupportedOperationException if SdkLevel is before T.
*/
public static void throwIfPreT(final String msg) {
- if (PRE_T) {
+ if (!SdkLevel.isAtLeastT()) {
throw new UnsupportedOperationException(msg);
}
}
diff --git a/service-t/lint-baseline.xml b/service-t/lint-baseline.xml
index 7f05b8c..e4b92d6 100644
--- a/service-t/lint-baseline.xml
+++ b/service-t/lint-baseline.xml
@@ -3,17 +3,6 @@
<issue
id="NewApi"
- message="Call requires API level 31 (current min is 30): `BpfMap`"
- errorLine1=" return new BpfMap<>(IFACE_INDEX_NAME_MAP_PATH, BpfMap.BPF_F_RDWR,"
- errorLine2=" ~~~~~~~~~~~~">
- <location
- file="packages/modules/Connectivity/service-t/src/com/android/server/net/BpfInterfaceMapUpdater.java"
- line="69"
- column="24"/>
- </issue>
-
- <issue
- id="NewApi"
message="Call requires API level 31 (current min is 30): `new android.net.EthernetNetworkSpecifier`"
errorLine1=" .setNetworkSpecifier(new EthernetNetworkSpecifier(ifaceName))"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
diff --git a/service-t/native/libs/libnetworkstats/BpfNetworkStats.cpp b/service-t/native/libs/libnetworkstats/BpfNetworkStats.cpp
index 8a58e56..def5f88 100644
--- a/service-t/native/libs/libnetworkstats/BpfNetworkStats.cpp
+++ b/service-t/native/libs/libnetworkstats/BpfNetworkStats.cpp
@@ -85,12 +85,12 @@
[iface, stats, &ifaceNameMap, &unknownIfaceBytesTotal](
const uint32_t& key,
const BpfMapRO<uint32_t, StatsValue>& ifaceStatsMap) -> Result<void> {
- IfaceValue ifname;
- if (getIfaceNameFromMap(ifaceNameMap, ifaceStatsMap, key, ifname, key,
- &unknownIfaceBytesTotal)) {
+ Result<IfaceValue> ifname = ifaceNameMap.readValue(key);
+ if (!ifname.ok()) {
+ maybeLogUnknownIface(key, ifaceStatsMap, key, &unknownIfaceBytesTotal);
return Result<void>();
}
- if (!iface || !strcmp(iface, ifname.name)) {
+ if (!iface || !strcmp(iface, ifname.value().name)) {
Result<StatsValue> statsEntry = ifaceStatsMap.readValue(key);
if (!statsEntry.ok()) {
return statsEntry.error();
@@ -144,16 +144,16 @@
[&lines, &unknownIfaceBytesTotal, &ifaceMap](
const StatsKey& key,
const BpfMapRO<StatsKey, StatsValue>& statsMap) -> Result<void> {
- IfaceValue ifname;
- if (getIfaceNameFromMap(ifaceMap, statsMap, key.ifaceIndex, ifname, key,
- &unknownIfaceBytesTotal)) {
+ Result<IfaceValue> ifname = ifaceMap.readValue(key.ifaceIndex);
+ if (!ifname.ok()) {
+ maybeLogUnknownIface(key.ifaceIndex, statsMap, key, &unknownIfaceBytesTotal);
return Result<void>();
}
Result<StatsValue> statsEntry = statsMap.readValue(key);
if (!statsEntry.ok()) {
return base::ResultError(statsEntry.error().message(), statsEntry.error().code());
}
- stats_line newLine = populateStatsEntry(key, statsEntry.value(), ifname);
+ stats_line newLine = populateStatsEntry(key, statsEntry.value(), ifname.value());
lines.push_back(newLine);
if (newLine.tag) {
// account tagged traffic in the untagged stats (for historical reasons?)
@@ -234,8 +234,9 @@
const auto processDetailIfaceStats = [&lines, &unknownIfaceBytesTotal, &ifaceMap, &statsMap](
const uint32_t& key, const StatsValue& value,
const BpfMapRO<uint32_t, StatsValue>&) {
- IfaceValue ifname;
- if (getIfaceNameFromMap(ifaceMap, statsMap, key, ifname, key, &unknownIfaceBytesTotal)) {
+ Result<IfaceValue> ifname = ifaceMap.readValue(key);
+ if (!ifname.ok()) {
+ maybeLogUnknownIface(key, statsMap, key, &unknownIfaceBytesTotal);
return Result<void>();
}
StatsKey fakeKey = {
@@ -243,7 +244,7 @@
.tag = (uint32_t)TAG_NONE,
.counterSet = (uint32_t)SET_ALL,
};
- lines.push_back(populateStatsEntry(fakeKey, value, ifname));
+ lines.push_back(populateStatsEntry(fakeKey, value, ifname.value()));
return Result<void>();
};
Result<void> res = statsMap.iterateWithValue(processDetailIfaceStats);
diff --git a/service-t/native/libs/libnetworkstats/BpfNetworkStatsTest.cpp b/service-t/native/libs/libnetworkstats/BpfNetworkStatsTest.cpp
index 2c01904..57822fc 100644
--- a/service-t/native/libs/libnetworkstats/BpfNetworkStatsTest.cpp
+++ b/service-t/native/libs/libnetworkstats/BpfNetworkStatsTest.cpp
@@ -352,14 +352,16 @@
.counterSet = TEST_COUNTERSET0,
.ifaceIndex = ifaceIndex,
};
- IfaceValue ifname;
int64_t unknownIfaceBytesTotal = 0;
- ASSERT_EQ(-ENODEV, getIfaceNameFromMap(mFakeIfaceIndexNameMap, mFakeStatsMap, ifaceIndex,
- ifname, curKey, &unknownIfaceBytesTotal));
+ ASSERT_EQ(false, mFakeIfaceIndexNameMap.readValue(ifaceIndex).ok());
+ maybeLogUnknownIface(ifaceIndex, mFakeStatsMap, curKey, &unknownIfaceBytesTotal);
+
ASSERT_EQ(((int64_t)(TEST_BYTES0 * 20 + TEST_BYTES1 * 20)), unknownIfaceBytesTotal);
curKey.ifaceIndex = IFACE_INDEX2;
- ASSERT_EQ(-ENODEV, getIfaceNameFromMap(mFakeIfaceIndexNameMap, mFakeStatsMap, ifaceIndex,
- ifname, curKey, &unknownIfaceBytesTotal));
+
+ ASSERT_EQ(false, mFakeIfaceIndexNameMap.readValue(ifaceIndex).ok());
+ maybeLogUnknownIface(ifaceIndex, mFakeStatsMap, curKey, &unknownIfaceBytesTotal);
+
ASSERT_EQ(-1, unknownIfaceBytesTotal);
std::vector<stats_line> lines;
// TODO: find a way to test the total of unknown Iface Bytes go above limit.
diff --git a/service-t/native/libs/libnetworkstats/include/netdbpf/BpfNetworkStats.h b/service-t/native/libs/libnetworkstats/include/netdbpf/BpfNetworkStats.h
index 0f28c1d..173dee4 100644
--- a/service-t/native/libs/libnetworkstats/include/netdbpf/BpfNetworkStats.h
+++ b/service-t/native/libs/libnetworkstats/include/netdbpf/BpfNetworkStats.h
@@ -71,20 +71,6 @@
const BpfMapRO<uint32_t, IfaceValue>& ifaceMap);
// For test only
int cleanStatsMapInternal(const base::unique_fd& cookieTagMap, const base::unique_fd& tagStatsMap);
-// For test only
-template <class Key>
-int getIfaceNameFromMap(const BpfMapRO<uint32_t, IfaceValue>& ifaceMap,
- const BpfMapRO<Key, StatsValue>& statsMap,
- uint32_t ifaceIndex, IfaceValue& ifname,
- const Key& curKey, int64_t* unknownIfaceBytesTotal) {
- auto iface = ifaceMap.readValue(ifaceIndex);
- if (!iface.ok()) {
- maybeLogUnknownIface(ifaceIndex, statsMap, curKey, unknownIfaceBytesTotal);
- return -ENODEV;
- }
- ifname = iface.value();
- return 0;
-}
template <class Key>
void maybeLogUnknownIface(int ifaceIndex, const BpfMapRO<Key, StatsValue>& statsMap,
diff --git a/service-t/src/com/android/server/NsdService.java b/service-t/src/com/android/server/NsdService.java
index 62a2ae5..0feda6e 100644
--- a/service-t/src/com/android/server/NsdService.java
+++ b/service-t/src/com/android/server/NsdService.java
@@ -54,6 +54,7 @@
import android.net.mdns.aidl.RegistrationInfo;
import android.net.mdns.aidl.ResolutionInfo;
import android.net.nsd.AdvertisingRequest;
+import android.net.nsd.DiscoveryRequest;
import android.net.nsd.INsdManager;
import android.net.nsd.INsdManagerCallback;
import android.net.nsd.INsdServiceConnector;
@@ -742,8 +743,8 @@
switch (msg.what) {
case NsdManager.DISCOVER_SERVICES: {
if (DBG) Log.d(TAG, "Discover services");
- final ListenerArgs args = (ListenerArgs) msg.obj;
- clientInfo = mClients.get(args.connector);
+ final DiscoveryArgs discoveryArgs = (DiscoveryArgs) msg.obj;
+ clientInfo = mClients.get(discoveryArgs.connector);
// If the binder death notification for a INsdManagerCallback was received
// before any calls are received by NsdService, the clientInfo would be
// cleared and cause NPE. Add a null check here to prevent this corner case.
@@ -758,10 +759,10 @@
break;
}
- final NsdServiceInfo info = args.serviceInfo;
+ final DiscoveryRequest discoveryRequest = discoveryArgs.discoveryRequest;
transactionId = getUniqueId();
final Pair<String, List<String>> typeAndSubtype =
- parseTypeAndSubtype(info.getServiceType());
+ parseTypeAndSubtype(discoveryRequest.getServiceType());
final String serviceType = typeAndSubtype == null
? null : typeAndSubtype.first;
if (clientInfo.mUseJavaBackend
@@ -773,41 +774,53 @@
break;
}
+ String subtype = discoveryRequest.getSubtype();
+ if (subtype == null && !typeAndSubtype.second.isEmpty()) {
+ subtype = typeAndSubtype.second.get(0);
+ }
+
+ if (subtype != null && !checkSubtypeLabel(subtype)) {
+ clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
+ NsdManager.FAILURE_BAD_PARAMETERS, false /* isLegacy */);
+ break;
+ }
+
final String listenServiceType = serviceType + ".local";
maybeStartMonitoringSockets();
final MdnsListener listener = new DiscoveryListener(clientRequestId,
transactionId, listenServiceType);
final MdnsSearchOptions.Builder optionsBuilder =
MdnsSearchOptions.newBuilder()
- .setNetwork(info.getNetwork())
+ .setNetwork(discoveryRequest.getNetwork())
.setRemoveExpiredService(true)
.setIsPassiveMode(true);
- if (!typeAndSubtype.second.isEmpty()) {
- // The parsing ensures subtype starts with an underscore.
+
+ if (subtype != null) {
+ // checkSubtypeLabels() ensures that subtypes start with '_' but
// MdnsSearchOptions expects the underscore to not be present.
- optionsBuilder.addSubtype(
- typeAndSubtype.second.get(0).substring(1));
+ optionsBuilder.addSubtype(subtype.substring(1));
}
mMdnsDiscoveryManager.registerListener(
listenServiceType, listener, optionsBuilder.build());
final ClientRequest request = storeDiscoveryManagerRequestMap(
clientRequestId, transactionId, listener, clientInfo,
- info.getNetwork());
- clientInfo.onDiscoverServicesStarted(clientRequestId, info, request);
+ discoveryRequest.getNetwork());
+ clientInfo.onDiscoverServicesStarted(
+ clientRequestId, discoveryRequest, request);
clientInfo.log("Register a DiscoveryListener " + transactionId
+ " for service type:" + listenServiceType);
} else {
maybeStartDaemon();
- if (discoverServices(transactionId, info)) {
+ if (discoverServices(transactionId, discoveryRequest)) {
if (DBG) {
Log.d(TAG, "Discover " + msg.arg2 + " " + transactionId
- + info.getServiceType());
+ + discoveryRequest.getServiceType());
}
final ClientRequest request = storeLegacyRequestMap(clientRequestId,
transactionId, clientInfo, msg.what,
mClock.elapsedRealtime());
clientInfo.onDiscoverServicesStarted(
- clientRequestId, info, request);
+ clientRequestId, discoveryRequest, request);
} else {
stopServiceDiscovery(transactionId);
clientInfo.onDiscoverServicesFailedImmediately(clientRequestId,
@@ -2115,6 +2128,15 @@
}
}
+ private static final class DiscoveryArgs {
+ public final NsdServiceConnector connector;
+ public final DiscoveryRequest discoveryRequest;
+ DiscoveryArgs(NsdServiceConnector connector, DiscoveryRequest discoveryRequest) {
+ this.connector = connector;
+ this.discoveryRequest = discoveryRequest;
+ }
+ }
+
private class NsdServiceConnector extends INsdServiceConnector.Stub
implements IBinder.DeathRecipient {
@@ -2135,10 +2157,10 @@
}
@Override
- public void discoverServices(int listenerKey, NsdServiceInfo serviceInfo) {
+ public void discoverServices(int listenerKey, DiscoveryRequest discoveryRequest) {
mNsdStateMachine.sendMessage(mNsdStateMachine.obtainMessage(
NsdManager.DISCOVER_SERVICES, 0, listenerKey,
- new ListenerArgs(this, serviceInfo)));
+ new DiscoveryArgs(this, discoveryRequest)));
}
@Override
@@ -2277,15 +2299,15 @@
return mMDnsManager.stopOperation(transactionId);
}
- private boolean discoverServices(int transactionId, NsdServiceInfo serviceInfo) {
+ private boolean discoverServices(int transactionId, DiscoveryRequest discoveryRequest) {
if (mMDnsManager == null) {
Log.wtf(TAG, "discoverServices: mMDnsManager is null");
return false;
}
- final String type = serviceInfo.getServiceType();
- final int discoverInterface = getNetworkInterfaceIndex(serviceInfo);
- if (serviceInfo.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
+ final String type = discoveryRequest.getServiceType();
+ final int discoverInterface = getNetworkInterfaceIndex(discoveryRequest);
+ if (discoveryRequest.getNetwork() != null && discoverInterface == IFACE_IDX_ANY) {
Log.e(TAG, "Interface to discover service on not found");
return false;
}
@@ -2335,7 +2357,26 @@
}
return IFACE_IDX_ANY;
}
+ return getNetworkInterfaceIndex(network);
+ }
+ /**
+ * Returns the interface to use to discover a service on a specific network, or {@link
+ * IFACE_IDX_ANY} if no network is specified.
+ */
+ private int getNetworkInterfaceIndex(DiscoveryRequest discoveryRequest) {
+ final Network network = discoveryRequest.getNetwork();
+ if (network == null) {
+ return IFACE_IDX_ANY;
+ }
+ return getNetworkInterfaceIndex(network);
+ }
+
+ /**
+ * Returns the interface of a specific network, or {@link IFACE_IDX_ANY} if no interface is
+ * associated with {@code network}.
+ */
+ private int getNetworkInterfaceIndex(@NonNull Network network) {
String interfaceName = getNetworkInterfaceName(network);
if (interfaceName == null) {
return IFACE_IDX_ANY;
@@ -2710,12 +2751,12 @@
&& !(request instanceof AdvertiserClientRequest);
}
- void onDiscoverServicesStarted(int listenerKey, NsdServiceInfo info,
+ void onDiscoverServicesStarted(int listenerKey, DiscoveryRequest discoveryRequest,
ClientRequest request) {
mMetrics.reportServiceDiscoveryStarted(
isLegacyClientRequest(request), request.mTransactionId);
try {
- mCb.onDiscoverServicesStarted(listenerKey, info);
+ mCb.onDiscoverServicesStarted(listenerKey, discoveryRequest);
} catch (RemoteException e) {
Log.e(TAG, "Error calling onDiscoverServicesStarted", e);
}
diff --git a/service/lint-baseline.xml b/service/lint-baseline.xml
index a091a2b..b09589c 100644
--- a/service/lint-baseline.xml
+++ b/service/lint-baseline.xml
@@ -3,72 +3,6 @@
<issue
id="NewApi"
- message="Call requires API level 31 (current min is 30): `BpfMap`"
- errorLine1=" return new BpfMap<>("
- errorLine2=" ~~~~~~~~~~~~">
- <location
- file="packages/modules/Connectivity/service/src/com/android/server/BpfNetMaps.java"
- line="189"
- column="20"/>
- </issue>
-
- <issue
- id="NewApi"
- message="Call requires API level 31 (current min is 30): `BpfMap`"
- errorLine1=" return new BpfMap<>("
- errorLine2=" ~~~~~~~~~~~~">
- <location
- file="packages/modules/Connectivity/service/src/com/android/server/BpfNetMaps.java"
- line="198"
- column="20"/>
- </issue>
-
- <issue
- id="NewApi"
- message="Call requires API level 31 (current min is 30): `BpfMap`"
- errorLine1=" return new BpfMap<>("
- errorLine2=" ~~~~~~~~~~~~">
- <location
- file="packages/modules/Connectivity/service/src/com/android/server/BpfNetMaps.java"
- line="207"
- column="20"/>
- </issue>
-
- <issue
- id="NewApi"
- message="Call requires API level 31 (current min is 30): `BpfMap`"
- errorLine1=" return new BpfMap<>(COOKIE_TAG_MAP_PATH, BpfMap.BPF_F_RDWR,"
- errorLine2=" ~~~~~~~~~~~~">
- <location
- file="packages/modules/Connectivity/service/src/com/android/server/BpfNetMaps.java"
- line="216"
- column="20"/>
- </issue>
-
- <issue
- id="NewApi"
- message="Call requires API level 31 (current min is 30): `BpfMap`"
- errorLine1=" return new BpfMap<>("
- errorLine2=" ~~~~~~~~~~~~">
- <location
- file="packages/modules/Connectivity/service/src/com/android/server/BpfNetMaps.java"
- line="225"
- column="20"/>
- </issue>
-
- <issue
- id="NewApi"
- message="Call requires API level 31 (current min is 30): `BpfMap`"
- errorLine1=" return new BpfMap<>(INGRESS_DISCARD_MAP_PATH, BpfMap.BPF_F_RDWR,"
- errorLine2=" ~~~~~~~~~~~~">
- <location
- file="packages/modules/Connectivity/service/src/com/android/server/BpfNetMaps.java"
- line="234"
- column="20"/>
- </issue>
-
- <issue
- id="NewApi"
message="Call requires API level 31 (current min is 30): `BpfBitmap`"
errorLine1=" return new BpfBitmap(BLOCKED_PORTS_MAP_PATH);"
errorLine2=" ~~~~~~~~~~~~~">
diff --git a/service/src/com/android/server/BpfNetMaps.java b/service/src/com/android/server/BpfNetMaps.java
index aa40285..a7fddd0 100644
--- a/service/src/com/android/server/BpfNetMaps.java
+++ b/service/src/com/android/server/BpfNetMaps.java
@@ -31,7 +31,6 @@
import static android.net.BpfNetMapsConstants.UID_OWNER_MAP_PATH;
import static android.net.BpfNetMapsConstants.UID_PERMISSION_MAP_PATH;
import static android.net.BpfNetMapsConstants.UID_RULES_CONFIGURATION_KEY;
-import static android.net.BpfNetMapsUtils.PRE_T;
import static android.net.BpfNetMapsUtils.getMatchByFirewallChain;
import static android.net.BpfNetMapsUtils.isFirewallAllowList;
import static android.net.BpfNetMapsUtils.matchToString;
@@ -68,6 +67,7 @@
import com.android.internal.annotations.VisibleForTesting;
import com.android.modules.utils.BackgroundThread;
+import com.android.modules.utils.build.SdkLevel;
import com.android.net.module.util.BpfDump;
import com.android.net.module.util.BpfMap;
import com.android.net.module.util.IBpfMap;
@@ -95,7 +95,7 @@
*/
public class BpfNetMaps {
static {
- if (!PRE_T) {
+ if (SdkLevel.isAtLeastT()) {
System.loadLibrary("service-connectivity");
}
}
@@ -184,6 +184,7 @@
sIngressDiscardMap = ingressDiscardMap;
}
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
private static IBpfMap<S32, U32> getConfigurationMap() {
try {
return new BpfMap<>(
@@ -193,6 +194,7 @@
}
}
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
private static IBpfMap<S32, UidOwnerValue> getUidOwnerMap() {
try {
return new BpfMap<>(
@@ -202,6 +204,7 @@
}
}
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
private static IBpfMap<S32, U8> getUidPermissionMap() {
try {
return new BpfMap<>(
@@ -211,6 +214,7 @@
}
}
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
private static IBpfMap<CookieTagMapKey, CookieTagMapValue> getCookieTagMap() {
try {
return new BpfMap<>(COOKIE_TAG_MAP_PATH,
@@ -220,6 +224,7 @@
}
}
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
private static IBpfMap<S32, U8> getDataSaverEnabledMap() {
try {
return new BpfMap<>(
@@ -229,6 +234,7 @@
}
}
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
private static IBpfMap<IngressDiscardKey, IngressDiscardValue> getIngressDiscardMap() {
try {
return new BpfMap<>(INGRESS_DISCARD_MAP_PATH,
@@ -238,6 +244,7 @@
}
}
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
private static void initBpfMaps() {
if (sConfigurationMap == null) {
sConfigurationMap = getConfigurationMap();
@@ -295,6 +302,7 @@
* Initializes the class if it is not already initialized. This method will open maps but not
* cause any other effects. This method may be called multiple times on any thread.
*/
+ @RequiresApi(Build.VERSION_CODES.TIRAMISU)
private static synchronized void ensureInitialized(final Context context) {
if (sInitialized) return;
initBpfMaps();
@@ -348,7 +356,7 @@
public BpfNetMaps(final Context context) {
this(context, null);
- if (PRE_T) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
+ if (!SdkLevel.isAtLeastT()) throw new IllegalArgumentException("BpfNetMaps need to use netd before T");
}
public BpfNetMaps(final Context context, final INetd netd) {
@@ -357,7 +365,7 @@
@VisibleForTesting
public BpfNetMaps(final Context context, final INetd netd, final Dependencies deps) {
- if (!PRE_T) {
+ if (SdkLevel.isAtLeastT()) {
ensureInitialized(context);
}
mNetd = netd;
@@ -371,7 +379,7 @@
}
private void throwIfPreT(final String msg) {
- if (PRE_T) {
+ if (!SdkLevel.isAtLeastT()) {
throw new UnsupportedOperationException(msg);
}
}
@@ -712,7 +720,7 @@
* cause of the failure.
*/
public void addUidInterfaceRules(final String ifName, final int[] uids) throws RemoteException {
- if (PRE_T) {
+ if (!SdkLevel.isAtLeastT()) {
mNetd.firewallAddUidInterfaceRules(ifName, uids);
return;
}
@@ -750,7 +758,7 @@
* cause of the failure.
*/
public void removeUidInterfaceRules(final int[] uids) throws RemoteException {
- if (PRE_T) {
+ if (!SdkLevel.isAtLeastT()) {
mNetd.firewallRemoveUidInterfaceRules(uids);
return;
}
@@ -829,7 +837,7 @@
* @throws RemoteException when netd has crashed.
*/
public void setNetPermForUids(final int permissions, final int[] uids) throws RemoteException {
- if (PRE_T) {
+ if (!SdkLevel.isAtLeastT()) {
mNetd.trafficSetNetPermForUids(permissions, uids);
return;
}
@@ -1019,7 +1027,7 @@
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
throws IOException, ServiceSpecificException {
- if (PRE_T) {
+ if (!SdkLevel.isAtLeastT()) {
throw new ServiceSpecificException(
EOPNOTSUPP, "dumpsys connectivity trafficcontroller dump not available on pre-T"
+ " devices, use dumpsys netd trafficcontroller instead.");
diff --git a/staticlibs/testutils/devicetests/com/android/testutils/DevSdkIgnoreRunner.kt b/staticlibs/testutils/devicetests/com/android/testutils/DevSdkIgnoreRunner.kt
index 10accd4..69fdbf8 100644
--- a/staticlibs/testutils/devicetests/com/android/testutils/DevSdkIgnoreRunner.kt
+++ b/staticlibs/testutils/devicetests/com/android/testutils/DevSdkIgnoreRunner.kt
@@ -31,6 +31,7 @@
import org.junit.runner.notification.Failure
import org.junit.runner.notification.RunNotifier
import org.junit.runners.Parameterized
+import org.mockito.Mockito
/**
* A runner that can skip tests based on the development SDK as defined in [DevSdkIgnoreRule].
@@ -124,6 +125,9 @@
notifier.fireTestFailure(Failure(leakMonitorDesc,
IllegalStateException("Unexpected thread changes: $threadsDiff")))
}
+ // Clears up internal state of all inline mocks.
+ // TODO: Call clearInlineMocks() at the end of each test.
+ Mockito.framework().clearInlineMocks()
notifier.fireTestFinished(leakMonitorDesc)
}
diff --git a/tests/cts/net/Android.bp b/tests/cts/net/Android.bp
index 3d53d6c..f0e0ae8 100644
--- a/tests/cts/net/Android.bp
+++ b/tests/cts/net/Android.bp
@@ -54,6 +54,7 @@
"junit",
"junit-params",
"modules-utils-build",
+ "net-tests-utils",
"net-utils-framework-common",
"truth",
"TetheringIntegrationTestsBaseLib",
diff --git a/tests/cts/net/src/android/net/cts/DiscoveryRequestTest.kt b/tests/cts/net/src/android/net/cts/DiscoveryRequestTest.kt
new file mode 100644
index 0000000..909a5bc
--- /dev/null
+++ b/tests/cts/net/src/android/net/cts/DiscoveryRequestTest.kt
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net.cts
+
+import android.net.Network
+import android.net.nsd.DiscoveryRequest
+import android.os.Build
+import androidx.test.filters.SmallTest
+import com.android.testutils.ConnectivityModuleTest
+import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
+import com.android.testutils.DevSdkIgnoreRunner
+import com.android.testutils.assertParcelingIsLossless
+import com.android.testutils.assertThrows
+import kotlin.test.assertEquals
+import kotlin.test.assertNotEquals
+import org.junit.Test
+import org.junit.runner.RunWith
+
+/** CTS tests for {@link DiscoveryRequest}. */
+@IgnoreUpTo(Build.VERSION_CODES.S_V2)
+@RunWith(DevSdkIgnoreRunner::class)
+@SmallTest
+@ConnectivityModuleTest
+class DiscoveryRequestTest {
+ @Test
+ fun testParcelingIsLossLess() {
+ val requestWithNullFields =
+ DiscoveryRequest.Builder("_ipps._tcp").build()
+ val requestWithAllFields =
+ DiscoveryRequest.Builder("_ipps._tcp")
+ .setSubtype("_xyz")
+ .setNetwork(Network(1))
+ .build()
+
+ assertParcelingIsLossless(requestWithNullFields)
+ assertParcelingIsLossless(requestWithAllFields)
+ }
+
+ @Test
+ fun testBuilder_success() {
+ val request = DiscoveryRequest.Builder("_ipps._tcp")
+ .setSubtype("_xyz")
+ .setNetwork(Network(1))
+ .build()
+
+ assertEquals("_ipps._tcp", request.serviceType)
+ assertEquals("_xyz", request.subtype)
+ assertEquals(Network(1), request.network)
+ }
+
+ @Test
+ fun testBuilderConstructor_emptyServiceType_throwsIllegalArgument() {
+ assertThrows(IllegalArgumentException::class.java) {
+ DiscoveryRequest.Builder("")
+ }
+ }
+
+ @Test
+ fun testEquality() {
+ val request1 = DiscoveryRequest.Builder("_ipps._tcp").build()
+ val request2 = DiscoveryRequest.Builder("_ipps._tcp").build()
+ val request3 = DiscoveryRequest.Builder("_ipps._tcp")
+ .setSubtype("_xyz")
+ .setNetwork(Network(1))
+ .build()
+ val request4 = DiscoveryRequest.Builder("_ipps._tcp")
+ .setSubtype("_xyz")
+ .setNetwork(Network(1))
+ .build()
+
+ assertEquals(request1, request2)
+ assertEquals(request3, request4)
+ assertNotEquals(request1, request3)
+ assertNotEquals(request2, request4)
+ }
+}
diff --git a/tests/cts/net/src/android/net/cts/NsdManagerTest.kt b/tests/cts/net/src/android/net/cts/NsdManagerTest.kt
index e433442..8f9f8c7 100644
--- a/tests/cts/net/src/android/net/cts/NsdManagerTest.kt
+++ b/tests/cts/net/src/android/net/cts/NsdManagerTest.kt
@@ -53,6 +53,7 @@
import android.net.cts.NsdServiceInfoCallbackRecord.ServiceInfoCallbackEvent.ServiceUpdatedLost
import android.net.cts.NsdServiceInfoCallbackRecord.ServiceInfoCallbackEvent.UnregisterCallbackSucceeded
import android.net.cts.util.CtsNetUtils
+import android.net.nsd.DiscoveryRequest
import android.net.nsd.NsdManager
import android.net.nsd.NsdServiceInfo
import android.net.nsd.OffloadEngine
@@ -113,6 +114,7 @@
import kotlin.math.min
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
+import kotlin.test.assertNotEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.fail
@@ -1042,9 +1044,11 @@
nsdManager.discoverServices("_subtype1.$serviceType",
NsdManager.PROTOCOL_DNS_SD,
testNetwork1.network, Executor { it.run() }, subtype1DiscoveryRecord)
- nsdManager.discoverServices("_subtype2.$serviceType",
- NsdManager.PROTOCOL_DNS_SD,
- testNetwork1.network, Executor { it.run() }, subtype2DiscoveryRecord)
+
+ nsdManager.discoverServices(
+ DiscoveryRequest.Builder(serviceType).setSubtype("_subtype2")
+ .setNetwork(testNetwork1.network).build(),
+ Executor { it.run() }, subtype2DiscoveryRecord)
val info1 = subtype1DiscoveryRecord.waitForServiceDiscovered(
serviceName, serviceType, testNetwork1.network)
@@ -1099,6 +1103,28 @@
}
@Test
+ fun testSubtypeDiscovery_typeMatchButSubtypeNotMatch_notDiscovered() {
+ val si1 = makeTestServiceInfo(network = testNetwork1.network).apply {
+ serviceType += ",_subtype1"
+ }
+ val registrationRecord = NsdRegistrationRecord()
+ val subtype2DiscoveryRecord = NsdDiscoveryRecord()
+ tryTest {
+ registerService(registrationRecord, si1)
+ val request = DiscoveryRequest.Builder(serviceType)
+ .setSubtype("_subtype2").setNetwork(testNetwork1.network).build()
+ nsdManager.discoverServices(request, { it.run() }, subtype2DiscoveryRecord)
+ subtype2DiscoveryRecord.expectCallback<DiscoveryStarted>()
+ subtype2DiscoveryRecord.assertNoCallback(timeoutMs = 2000)
+ } cleanupStep {
+ nsdManager.stopServiceDiscovery(subtype2DiscoveryRecord)
+ subtype2DiscoveryRecord.expectCallback<DiscoveryStopped>()
+ } cleanup {
+ nsdManager.unregisterService(registrationRecord)
+ }
+ }
+
+ @Test
fun testSubtypeAdvertising_tooManySubtypes_returnsFailureBadParameters() {
val si = makeTestServiceInfo(network = testNetwork1.network)
// Sets 101 subtypes in total
diff --git a/tests/unit/java/android/net/nsd/NsdManagerTest.java b/tests/unit/java/android/net/nsd/NsdManagerTest.java
index 461ead8..aabe8d3 100644
--- a/tests/unit/java/android/net/nsd/NsdManagerTest.java
+++ b/tests/unit/java/android/net/nsd/NsdManagerTest.java
@@ -285,6 +285,7 @@
private void doTestDiscoverService() throws Exception {
NsdManager manager = mManager;
+ DiscoveryRequest request1 = new DiscoveryRequest.Builder("a_type").build();
NsdServiceInfo reply1 = new NsdServiceInfo("a_name", "a_type");
NsdServiceInfo reply2 = new NsdServiceInfo("another_name", "a_type");
NsdServiceInfo reply3 = new NsdServiceInfo("a_third_name", "a_type");
@@ -305,7 +306,7 @@
int key2 = getRequestKey(req ->
verify(mServiceConn, times(2)).discoverServices(req.capture(), any()));
- mCallback.onDiscoverServicesStarted(key2, reply1);
+ mCallback.onDiscoverServicesStarted(key2, request1);
verify(listener, timeout(mTimeoutMs).times(1)).onDiscoveryStarted("a_type");
@@ -345,7 +346,7 @@
int key3 = getRequestKey(req ->
verify(mServiceConn, times(3)).discoverServices(req.capture(), any()));
- mCallback.onDiscoverServicesStarted(key3, reply1);
+ mCallback.onDiscoverServicesStarted(key3, request1);
verify(listener, timeout(mTimeoutMs).times(1)).onDiscoveryStarted("a_type");
// Client unregisters immediately, it fails
diff --git a/thread/service/java/com/android/server/thread/ThreadNetworkCountryCode.java b/thread/service/java/com/android/server/thread/ThreadNetworkCountryCode.java
index 23aeb93..a1484a4 100644
--- a/thread/service/java/com/android/server/thread/ThreadNetworkCountryCode.java
+++ b/thread/service/java/com/android/server/thread/ThreadNetworkCountryCode.java
@@ -310,7 +310,14 @@
public void onActiveCountryCodeChanged(String countryCode) {
Log.d(TAG, "Wifi country code is changed to " + countryCode);
synchronized ("ThreadNetworkCountryCode.this") {
- mWifiCountryCodeInfo = new CountryCodeInfo(countryCode, COUNTRY_CODE_SOURCE_WIFI);
+ if (isValidCountryCode(countryCode)) {
+ mWifiCountryCodeInfo =
+ new CountryCodeInfo(countryCode, COUNTRY_CODE_SOURCE_WIFI);
+ } else {
+ Log.w(TAG, "WiFi country code " + countryCode + " is invalid");
+ mWifiCountryCodeInfo = null;
+ }
+
updateCountryCode(false /* forceUpdate */);
}
}
diff --git a/thread/tests/unit/src/com/android/server/thread/ThreadNetworkCountryCodeTest.java b/thread/tests/unit/src/com/android/server/thread/ThreadNetworkCountryCodeTest.java
index 670449d..5ca6511 100644
--- a/thread/tests/unit/src/com/android/server/thread/ThreadNetworkCountryCodeTest.java
+++ b/thread/tests/unit/src/com/android/server/thread/ThreadNetworkCountryCodeTest.java
@@ -86,6 +86,7 @@
private static final String TEST_COUNTRY_CODE_US = "US";
private static final String TEST_COUNTRY_CODE_CN = "CN";
private static final String TEST_COUNTRY_CODE_INVALID = "INVALID";
+ private static final String TEST_WIFI_DEFAULT_COUNTRY_CODE = "00";
private static final int TEST_SIM_SLOT_INDEX_0 = 0;
private static final int TEST_SIM_SLOT_INDEX_1 = 1;
@@ -259,6 +260,21 @@
}
@Test
+ public void wifiCountryCode_wifiDefaultCountryCodeIsActive_wifiCountryCodeIsNotUsed() {
+ mThreadNetworkCountryCode.initialize();
+
+ verify(mWifiManager)
+ .registerActiveCountryCodeChangedCallback(
+ any(), mWifiCountryCodeReceiverCaptor.capture());
+ mWifiCountryCodeReceiverCaptor
+ .getValue()
+ .onActiveCountryCodeChanged(TEST_WIFI_DEFAULT_COUNTRY_CODE);
+
+ assertThat(mThreadNetworkCountryCode.getCountryCode())
+ .isNotEqualTo(TEST_WIFI_DEFAULT_COUNTRY_CODE);
+ }
+
+ @Test
public void wifiCountryCode_wifiCountryCodeIsInactive_defaultCountryCodeIsUsed() {
mThreadNetworkCountryCode.initialize();
verify(mWifiManager)