Merge "Add getters to UnderlyingNetworkInfo" into sc-dev
diff --git a/framework/Android.bp b/framework/Android.bp
index c62402d..bb93af9 100644
--- a/framework/Android.bp
+++ b/framework/Android.bp
@@ -100,6 +100,7 @@
"//frameworks/base",
// Tests using hidden APIs
+ "//cts/tests/netlegacy22.api",
"//external/sl4a:__subpackages__",
"//frameworks/base/tests/net:__subpackages__",
"//frameworks/libs/net/common/testutils",
diff --git a/framework/api/module-lib-current.txt b/framework/api/module-lib-current.txt
index 9e2cd3e..c8b04a3 100644
--- a/framework/api/module-lib-current.txt
+++ b/framework/api/module-lib-current.txt
@@ -7,7 +7,7 @@
public class ConnectivityManager {
method @RequiresPermission(anyOf={android.Manifest.permission.NETWORK_SETTINGS, android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) public void factoryReset();
- method @NonNull @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK, android.Manifest.permission.NETWORK_SETTINGS}) public java.util.List<android.net.NetworkStateSnapshot> getAllNetworkStateSnapshot();
+ method @NonNull @RequiresPermission(anyOf={android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK, android.Manifest.permission.NETWORK_SETTINGS}) public java.util.List<android.net.NetworkStateSnapshot> getAllNetworkStateSnapshots();
method @Nullable public android.net.ProxyInfo getGlobalProxy();
method @NonNull public static android.util.Range<java.lang.Integer> getIpSecNetIdRange();
method @NonNull public static String getPrivateDnsMode(@NonNull android.content.Context);
diff --git a/framework/api/system-current.txt b/framework/api/system-current.txt
index 2194575..3ca7475 100644
--- a/framework/api/system-current.txt
+++ b/framework/api/system-current.txt
@@ -277,7 +277,7 @@
method @NonNull public int[] getAdministratorUids();
method @Nullable public static String getCapabilityCarrierName(int);
method @Nullable public String getSsid();
- method @NonNull public java.util.Set<java.lang.Integer> getSubIds();
+ method @NonNull public java.util.Set<java.lang.Integer> getSubscriptionIds();
method @NonNull public int[] getTransportTypes();
method public boolean isPrivateDnsBroken();
method public boolean satisfiedByNetworkCapabilities(@Nullable android.net.NetworkCapabilities);
@@ -308,7 +308,7 @@
method @NonNull @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) public android.net.NetworkCapabilities.Builder setRequestorUid(int);
method @NonNull @RequiresPermission(android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP) public android.net.NetworkCapabilities.Builder setSignalStrength(int);
method @NonNull @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY) public android.net.NetworkCapabilities.Builder setSsid(@Nullable String);
- method @NonNull public android.net.NetworkCapabilities.Builder setSubIds(@NonNull java.util.Set<java.lang.Integer>);
+ method @NonNull public android.net.NetworkCapabilities.Builder setSubscriptionIds(@NonNull java.util.Set<java.lang.Integer>);
method @NonNull public android.net.NetworkCapabilities.Builder setTransportInfo(@Nullable android.net.TransportInfo);
}
@@ -338,7 +338,7 @@
public static class NetworkRequest.Builder {
method @NonNull @RequiresPermission(android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP) public android.net.NetworkRequest.Builder setSignalStrength(int);
- method @NonNull public android.net.NetworkRequest.Builder setSubIds(@NonNull java.util.Set<java.lang.Integer>);
+ method @NonNull public android.net.NetworkRequest.Builder setSubscriptionIds(@NonNull java.util.Set<java.lang.Integer>);
}
public final class NetworkScore implements android.os.Parcelable {
diff --git a/framework/src/android/net/ConnectivityFrameworkInitializer.java b/framework/src/android/net/ConnectivityFrameworkInitializer.java
index 92a792b..a2e218d 100644
--- a/framework/src/android/net/ConnectivityFrameworkInitializer.java
+++ b/framework/src/android/net/ConnectivityFrameworkInitializer.java
@@ -68,5 +68,11 @@
return cm.startOrGetTestNetworkManager();
}
);
+
+ SystemServiceRegistry.registerContextAwareService(
+ DnsResolverServiceManager.DNS_RESOLVER_SERVICE,
+ DnsResolverServiceManager.class,
+ (context, serviceBinder) -> new DnsResolverServiceManager(serviceBinder)
+ );
}
}
diff --git a/framework/src/android/net/ConnectivityManager.java b/framework/src/android/net/ConnectivityManager.java
index 96f2de6..5dfa932 100644
--- a/framework/src/android/net/ConnectivityManager.java
+++ b/framework/src/android/net/ConnectivityManager.java
@@ -424,6 +424,9 @@
* Action used to display a dialog that asks the user whether to connect to a network that is
* not validated. This intent is used to start the dialog in settings via startActivity.
*
+ * This action includes a {@link Network} typed extra which is called
+ * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is unvalidated.
+ *
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
@@ -433,6 +436,10 @@
* Action used to display a dialog that asks the user whether to avoid a network that is no
* longer validated. This intent is used to start the dialog in settings via startActivity.
*
+ * This action includes a {@link Network} typed extra which is called
+ * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which is no longer
+ * validated.
+ *
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
@@ -444,6 +451,10 @@
* that has not validated. This intent is used to start the dialog in settings via
* startActivity.
*
+ * This action includes a {@link Network} typed extra which is called
+ * {@link ConnectivityManager#EXTRA_NETWORK} that represents the network which has partial
+ * connectivity.
+ *
* @hide
*/
@SystemApi(client = MODULE_LIBRARIES)
@@ -1425,9 +1436,9 @@
android.Manifest.permission.NETWORK_STACK,
android.Manifest.permission.NETWORK_SETTINGS})
@NonNull
- public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
+ public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
try {
- return mService.getAllNetworkStateSnapshot();
+ return mService.getAllNetworkStateSnapshots();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
diff --git a/framework/src/android/net/DnsResolverServiceManager.java b/framework/src/android/net/DnsResolverServiceManager.java
new file mode 100644
index 0000000..79009e8
--- /dev/null
+++ b/framework/src/android/net/DnsResolverServiceManager.java
@@ -0,0 +1,45 @@
+/*
+ * 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;
+
+import android.annotation.NonNull;
+import android.os.IBinder;
+
+/**
+ * Provides a way to obtain the DnsResolver binder objects.
+ *
+ * @hide
+ */
+public class DnsResolverServiceManager {
+ /** Service name for the DNS resolver. Keep in sync with DnsResolverService.h */
+ public static final String DNS_RESOLVER_SERVICE = "dnsresolver";
+
+ private final IBinder mResolver;
+
+ DnsResolverServiceManager(IBinder resolver) {
+ mResolver = resolver;
+ }
+
+ /**
+ * Get an {@link IBinder} representing the DnsResolver stable AIDL interface
+ *
+ * @return {@link android.net.IDnsResolver} IBinder.
+ */
+ @NonNull
+ public IBinder getService() {
+ return mResolver;
+ }
+}
diff --git a/framework/src/android/net/IConnectivityManager.aidl b/framework/src/android/net/IConnectivityManager.aidl
index 728f375..c434bbc 100644
--- a/framework/src/android/net/IConnectivityManager.aidl
+++ b/framework/src/android/net/IConnectivityManager.aidl
@@ -82,7 +82,7 @@
@UnsupportedAppUsage(maxTargetSdk = 30, trackingBug = 170729553)
NetworkState[] getAllNetworkState();
- List<NetworkStateSnapshot> getAllNetworkStateSnapshot();
+ List<NetworkStateSnapshot> getAllNetworkStateSnapshots();
boolean isActiveNetworkMetered();
diff --git a/framework/src/android/net/NetworkCapabilities.java b/framework/src/android/net/NetworkCapabilities.java
index c4277c3..775c88f 100644
--- a/framework/src/android/net/NetworkCapabilities.java
+++ b/framework/src/android/net/NetworkCapabilities.java
@@ -1749,7 +1749,7 @@
combineSSIDs(nc);
combineRequestor(nc);
combineAdministratorUids(nc);
- combineSubIds(nc);
+ combineSubscriptionIds(nc);
}
/**
@@ -1771,7 +1771,7 @@
&& (onlyImmutable || satisfiedByUids(nc))
&& (onlyImmutable || satisfiedBySSID(nc))
&& (onlyImmutable || satisfiedByRequestor(nc))
- && (onlyImmutable || satisfiedBySubIds(nc)));
+ && (onlyImmutable || satisfiedBySubscriptionIds(nc)));
}
/**
@@ -1868,7 +1868,7 @@
&& equalsPrivateDnsBroken(that)
&& equalsRequestor(that)
&& equalsAdministratorUids(that)
- && equalsSubIds(that);
+ && equalsSubscriptionIds(that);
}
@Override
@@ -2346,7 +2346,7 @@
* @hide
*/
@NonNull
- public NetworkCapabilities setSubIds(@NonNull Set<Integer> subIds) {
+ public NetworkCapabilities setSubscriptionIds(@NonNull Set<Integer> subIds) {
mSubIds = new ArraySet(Objects.requireNonNull(subIds));
return this;
}
@@ -2362,14 +2362,14 @@
*/
@NonNull
@SystemApi
- public Set<Integer> getSubIds() {
+ public Set<Integer> getSubscriptionIds() {
return new ArraySet<>(mSubIds);
}
/**
* Tests if the subscription ID set of this network is the same as that of the passed one.
*/
- private boolean equalsSubIds(@NonNull NetworkCapabilities nc) {
+ private boolean equalsSubscriptionIds(@NonNull NetworkCapabilities nc) {
return Objects.equals(mSubIds, nc.mSubIds);
}
@@ -2378,7 +2378,7 @@
* If specified in the request, the passed one need to have at least one subId and at least
* one of them needs to be in the request set.
*/
- private boolean satisfiedBySubIds(@NonNull NetworkCapabilities nc) {
+ private boolean satisfiedBySubscriptionIds(@NonNull NetworkCapabilities nc) {
if (mSubIds.isEmpty()) return true;
if (nc.mSubIds.isEmpty()) return false;
for (final Integer subId : nc.mSubIds) {
@@ -2395,7 +2395,7 @@
* <p>If both subscription IDs are not equal, they belong to different subscription
* (or no subscription). In this case, it would not make sense to add them together.
*/
- private void combineSubIds(@NonNull NetworkCapabilities nc) {
+ private void combineSubscriptionIds(@NonNull NetworkCapabilities nc) {
if (!Objects.equals(mSubIds, nc.mSubIds)) {
throw new IllegalStateException("Can't combine two subscription ID sets");
}
@@ -2737,8 +2737,8 @@
*/
@NonNull
@SystemApi
- public Builder setSubIds(@NonNull final Set<Integer> subIds) {
- mCaps.setSubIds(subIds);
+ public Builder setSubscriptionIds(@NonNull final Set<Integer> subIds) {
+ mCaps.setSubscriptionIds(subIds);
return this;
}
diff --git a/framework/src/android/net/NetworkRequest.java b/framework/src/android/net/NetworkRequest.java
index 78e1011..194b8ff 100644
--- a/framework/src/android/net/NetworkRequest.java
+++ b/framework/src/android/net/NetworkRequest.java
@@ -220,6 +220,10 @@
public Builder(@NonNull final NetworkRequest request) {
Objects.requireNonNull(request);
mNetworkCapabilities = request.networkCapabilities;
+ // If the caller constructed the builder from a request, it means the user
+ // might explicitly want the capabilities from the request. Thus, the NOT_VCN_MANAGED
+ // capabilities should not be touched later.
+ mModifiedNotVcnManaged = true;
}
/**
@@ -508,8 +512,8 @@
*/
@NonNull
@SystemApi
- public Builder setSubIds(@NonNull Set<Integer> subIds) {
- mNetworkCapabilities.setSubIds(subIds);
+ public Builder setSubscriptionIds(@NonNull Set<Integer> subIds) {
+ mNetworkCapabilities.setSubscriptionIds(subIds);
return this;
}
}
diff --git a/service/ServiceConnectivityResources/Android.bp b/service/ServiceConnectivityResources/Android.bp
index d783738..515498e 100644
--- a/service/ServiceConnectivityResources/Android.bp
+++ b/service/ServiceConnectivityResources/Android.bp
@@ -21,7 +21,7 @@
android_app {
name: "ServiceConnectivityResources",
- sdk_version: "module_current",
+ sdk_version: "module_30",
min_sdk_version: "30",
resource_dirs: [
"res",
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 4d96162..ecac1f2 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -321,7 +321,8 @@
private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
// The maximum number of network request allowed for system UIDs before an exception is thrown.
- private static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
+ @VisibleForTesting
+ static final int MAX_NETWORK_REQUESTS_PER_SYSTEM_UID = 250;
@VisibleForTesting
protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
@@ -338,7 +339,8 @@
protected final PermissionMonitor mPermissionMonitor;
private final PerUidCounter mNetworkRequestCounter;
- private final PerUidCounter mSystemNetworkRequestCounter;
+ @VisibleForTesting
+ final PerUidCounter mSystemNetworkRequestCounter;
private volatile boolean mLockdownEnabled;
@@ -630,7 +632,9 @@
}
private static IDnsResolver getDnsResolver(Context context) {
- return IDnsResolver.Stub.asInterface(DnsResolverServiceManager.getService(context));
+ final DnsResolverServiceManager dsm = context.getSystemService(
+ DnsResolverServiceManager.class);
+ return IDnsResolver.Stub.asInterface(dsm.getService());
}
/** Handler thread used for all of the handlers below. */
@@ -1058,8 +1062,9 @@
private final int mMaxCountPerUid;
// Map from UID to number of NetworkRequests that UID has filed.
+ @VisibleForTesting
@GuardedBy("mUidToNetworkRequestCount")
- private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
+ final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
/**
* Constructor
@@ -1083,15 +1088,20 @@
*/
public void incrementCountOrThrow(final int uid) {
synchronized (mUidToNetworkRequestCount) {
- final int networkRequests = mUidToNetworkRequestCount.get(uid, 0) + 1;
- if (networkRequests >= mMaxCountPerUid) {
- throw new ServiceSpecificException(
- ConnectivityManager.Errors.TOO_MANY_REQUESTS);
- }
- mUidToNetworkRequestCount.put(uid, networkRequests);
+ incrementCountOrThrow(uid, 1 /* numToIncrement */);
}
}
+ private void incrementCountOrThrow(final int uid, final int numToIncrement) {
+ final int newRequestCount =
+ mUidToNetworkRequestCount.get(uid, 0) + numToIncrement;
+ if (newRequestCount >= mMaxCountPerUid) {
+ throw new ServiceSpecificException(
+ ConnectivityManager.Errors.TOO_MANY_REQUESTS);
+ }
+ mUidToNetworkRequestCount.put(uid, newRequestCount);
+ }
+
/**
* Decrements the request count of the given uid.
*
@@ -1099,16 +1109,50 @@
*/
public void decrementCount(final int uid) {
synchronized (mUidToNetworkRequestCount) {
- final int requests = mUidToNetworkRequestCount.get(uid, 0);
- if (requests < 1) {
- logwtf("BUG: too small request count " + requests + " for UID " + uid);
- } else if (requests == 1) {
- mUidToNetworkRequestCount.delete(uid);
- } else {
- mUidToNetworkRequestCount.put(uid, requests - 1);
- }
+ decrementCount(uid, 1 /* numToDecrement */);
}
}
+
+ private void decrementCount(final int uid, final int numToDecrement) {
+ final int newRequestCount =
+ mUidToNetworkRequestCount.get(uid, 0) - numToDecrement;
+ if (newRequestCount < 0) {
+ logwtf("BUG: too small request count " + newRequestCount + " for UID " + uid);
+ } else if (newRequestCount == 0) {
+ mUidToNetworkRequestCount.delete(uid);
+ } else {
+ mUidToNetworkRequestCount.put(uid, newRequestCount);
+ }
+ }
+
+ /**
+ * Used to adjust the request counter for the per-app API flows. Directly adjusting the
+ * counter is not ideal however in the per-app flows, the nris can't be removed until they
+ * are used to create the new nris upon set. Therefore the request count limit can be
+ * artificially hit. This method is used as a workaround for this particular case so that
+ * the request counts are accounted for correctly.
+ * @param uid the uid to adjust counts for
+ * @param numOfNewRequests the new request count to account for
+ * @param r the runnable to execute
+ */
+ public void transact(final int uid, final int numOfNewRequests, @NonNull final Runnable r) {
+ // This should only be used on the handler thread as per all current and foreseen
+ // use-cases. ensureRunningOnConnectivityServiceThread() can't be used because there is
+ // no ref to the outer ConnectivityService.
+ synchronized (mUidToNetworkRequestCount) {
+ final int reqCountOverage = getCallingUidRequestCountOverage(uid, numOfNewRequests);
+ decrementCount(uid, reqCountOverage);
+ r.run();
+ incrementCountOrThrow(uid, reqCountOverage);
+ }
+ }
+
+ private int getCallingUidRequestCountOverage(final int uid, final int numOfNewRequests) {
+ final int newUidRequestCount = mUidToNetworkRequestCount.get(uid, 0)
+ + numOfNewRequests;
+ return newUidRequestCount >= MAX_NETWORK_REQUESTS_PER_SYSTEM_UID
+ ? newUidRequestCount - (MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - 1) : 0;
+ }
}
/**
@@ -1924,7 +1968,7 @@
newNc.setAdministratorUids(new int[0]);
if (!checkAnyPermissionOf(
callerPid, callerUid, android.Manifest.permission.NETWORK_FACTORY)) {
- newNc.setSubIds(Collections.emptySet());
+ newNc.setSubscriptionIds(Collections.emptySet());
}
return newNc;
@@ -2147,14 +2191,14 @@
PermissionUtils.enforceNetworkStackPermission(mContext);
final ArrayList<NetworkState> result = new ArrayList<>();
- for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshot()) {
+ for (NetworkStateSnapshot snapshot : getAllNetworkStateSnapshots()) {
// NetworkStateSnapshot doesn't contain NetworkInfo, so need to fetch it from the
// NetworkAgentInfo.
- final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.network);
+ final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(snapshot.getNetwork());
if (nai != null && nai.networkInfo.isConnected()) {
result.add(new NetworkState(new NetworkInfo(nai.networkInfo),
- snapshot.linkProperties, snapshot.networkCapabilities, snapshot.network,
- snapshot.subscriberId));
+ snapshot.getLinkProperties(), snapshot.getNetworkCapabilities(),
+ snapshot.getNetwork(), snapshot.getSubscriberId()));
}
}
return result.toArray(new NetworkState[result.size()]);
@@ -2162,7 +2206,7 @@
@Override
@NonNull
- public List<NetworkStateSnapshot> getAllNetworkStateSnapshot() {
+ public List<NetworkStateSnapshot> getAllNetworkStateSnapshots() {
// This contains IMSI details, so make sure the caller is privileged.
PermissionUtils.enforceNetworkStackPermission(mContext);
@@ -2808,6 +2852,8 @@
@Override
protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer,
@Nullable String[] args) {
+ if (!checkDumpPermission(mContext, TAG, writer)) return;
+
mPriorityDumper.dump(fd, writer, args);
}
@@ -2825,7 +2871,6 @@
private void doDump(FileDescriptor fd, PrintWriter writer, String[] args) {
final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
- if (!checkDumpPermission(mContext, TAG, pw)) return;
if (CollectionUtils.contains(args, DIAG_ARG)) {
dumpNetworkDiagnostics(pw);
@@ -3969,17 +4014,16 @@
// multilayer requests, returning as soon as a NetworkAgentInfo satisfies a request
// is important so as to not evaluate lower priority requests further in
// nri.mRequests.
- final boolean isNetworkNeeded = candidate.isSatisfyingRequest(req.requestId)
- // Note that this catches two important cases:
- // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
- // is currently satisfying the request. This is desirable when
- // cellular ends up validating but WiFi does not.
- // 2. Unvalidated WiFi will not be reaped when validated cellular
- // is currently satisfying the request. This is desirable when
- // WiFi ends up validating and out scoring cellular.
- || nri.getSatisfier().getCurrentScore()
- < candidate.getCurrentScoreAsValidated();
- return isNetworkNeeded;
+ final NetworkAgentInfo champion = req.equals(nri.getActiveRequest())
+ ? nri.getSatisfier() : null;
+ // Note that this catches two important cases:
+ // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
+ // is currently satisfying the request. This is desirable when
+ // cellular ends up validating but WiFi does not.
+ // 2. Unvalidated WiFi will not be reaped when validated cellular
+ // is currently satisfying the request. This is desirable when
+ // WiFi ends up validating and out scoring cellular.
+ return mNetworkRanker.mightBeat(req, champion, candidate.getValidatedScoreable());
}
}
@@ -5726,7 +5770,7 @@
}
mAppOpsManager.checkPackage(callerUid, callerPackageName);
- if (!nc.getSubIds().isEmpty()) {
+ if (!nc.getSubscriptionIds().isEmpty()) {
enforceNetworkFactoryPermission();
}
}
@@ -6148,6 +6192,7 @@
@Override
public int registerNetworkProvider(Messenger messenger, String name) {
enforceNetworkFactoryOrSettingsPermission();
+ Objects.requireNonNull(messenger, "messenger must be non-null");
NetworkProviderInfo npi = new NetworkProviderInfo(name, messenger,
nextNetworkProviderId(), () -> unregisterNetworkProvider(messenger));
mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_PROVIDER, npi));
@@ -7811,7 +7856,7 @@
@NonNull final Collection<NetworkRequestInfo> networkRequests) {
final NetworkReassignment changes = new NetworkReassignment();
- // Gather the list of all relevant agents and sort them by score.
+ // Gather the list of all relevant agents.
final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
if (!nai.everConnected) {
@@ -9186,6 +9231,7 @@
@Override
public void unregisterConnectivityDiagnosticsCallback(
@NonNull IConnectivityDiagnosticsCallback callback) {
+ Objects.requireNonNull(callback, "callback must be non-null");
mConnectivityDiagnosticsHandler.sendMessage(
mConnectivityDiagnosticsHandler.obtainMessage(
ConnectivityDiagnosticsHandler
@@ -9556,6 +9602,7 @@
*/
@Override
public void unregisterQosCallback(@NonNull final IQosCallback callback) {
+ Objects.requireNonNull(callback, "callback must be non-null");
mQosCallbackTracker.unregisterCallback(callback);
}
@@ -9675,9 +9722,13 @@
validateNetworkCapabilitiesOfProfileNetworkPreference(preference.capabilities);
mProfileNetworkPreferences = mProfileNetworkPreferences.plus(preference);
- final ArraySet<NetworkRequestInfo> nris =
- createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
- replaceDefaultNetworkRequestsForPreference(nris);
+ mSystemNetworkRequestCounter.transact(
+ mDeps.getCallingUid(), mProfileNetworkPreferences.preferences.size(),
+ () -> {
+ final ArraySet<NetworkRequestInfo> nris =
+ createNrisFromProfileNetworkPreferences(mProfileNetworkPreferences);
+ replaceDefaultNetworkRequestsForPreference(nris);
+ });
// Finally, rematch.
rematchAllNetworksAndRequests();
@@ -9763,9 +9814,16 @@
}
mOemNetworkPreferencesLogs.log("UPDATE INITIATED: " + preference);
- final ArraySet<NetworkRequestInfo> nris =
- new OemNetworkRequestFactory().createNrisFromOemNetworkPreferences(preference);
- replaceDefaultNetworkRequestsForPreference(nris);
+ final int uniquePreferenceCount = new ArraySet<>(
+ preference.getNetworkPreferences().values()).size();
+ mSystemNetworkRequestCounter.transact(
+ mDeps.getCallingUid(), uniquePreferenceCount,
+ () -> {
+ final ArraySet<NetworkRequestInfo> nris =
+ new OemNetworkRequestFactory()
+ .createNrisFromOemNetworkPreferences(preference);
+ replaceDefaultNetworkRequestsForPreference(nris);
+ });
mOemNetworkPreferences = preference;
if (null != listener) {
@@ -9790,10 +9848,14 @@
final ArraySet<NetworkRequestInfo> perAppCallbackRequestsToUpdate =
getPerAppCallbackRequestsToUpdate();
final ArraySet<NetworkRequestInfo> nrisToRegister = new ArraySet<>(nris);
- nrisToRegister.addAll(
- createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
- handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
- handleRegisterNetworkRequests(nrisToRegister);
+ mSystemNetworkRequestCounter.transact(
+ mDeps.getCallingUid(), perAppCallbackRequestsToUpdate.size(),
+ () -> {
+ nrisToRegister.addAll(
+ createPerAppCallbackRequestsToRegister(perAppCallbackRequestsToUpdate));
+ handleRemoveNetworkRequests(perAppCallbackRequestsToUpdate);
+ handleRegisterNetworkRequests(nrisToRegister);
+ });
}
/**
diff --git a/services/core/java/com/android/server/connectivity/FullScore.java b/services/core/java/com/android/server/connectivity/FullScore.java
index 52da566..14cec09 100644
--- a/services/core/java/com/android/server/connectivity/FullScore.java
+++ b/services/core/java/com/android/server/connectivity/FullScore.java
@@ -259,6 +259,14 @@
}
/**
+ * Returns this score but validated.
+ */
+ public FullScore asValidated() {
+ return new FullScore(mLegacyInt, mPolicies | (1L << POLICY_IS_VALIDATED),
+ mKeepConnectedReason);
+ }
+
+ /**
* For backward compatibility, get the legacy int.
* This will be removed before S is published.
*/
diff --git a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
index 584174e..18becd4 100644
--- a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
+++ b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
@@ -950,6 +950,26 @@
}
/**
+ * Returns a Scoreable identical to this NAI, but validated.
+ *
+ * This is useful to probe what scoring would be if this network validated, to know
+ * whether to provisionally keep a network that may or may not validate.
+ *
+ * @return a Scoreable identical to this NAI, but validated.
+ */
+ public NetworkRanker.Scoreable getValidatedScoreable() {
+ return new NetworkRanker.Scoreable() {
+ @Override public FullScore getScore() {
+ return mScore.asValidated();
+ }
+
+ @Override public NetworkCapabilities getCapsNoCopy() {
+ return networkCapabilities;
+ }
+ };
+ }
+
+ /**
* Return a {@link NetworkStateSnapshot} for this network.
*/
@NonNull
diff --git a/services/core/java/com/android/server/connectivity/NetworkRanker.java b/services/core/java/com/android/server/connectivity/NetworkRanker.java
index 2b345e5..346af44 100644
--- a/services/core/java/com/android/server/connectivity/NetworkRanker.java
+++ b/services/core/java/com/android/server/connectivity/NetworkRanker.java
@@ -234,16 +234,17 @@
NetworkAgentInfo bestNetwork = null;
int bestScore = Integer.MIN_VALUE;
for (final NetworkAgentInfo nai : nais) {
- if (nai.getCurrentScore() > bestScore) {
+ final int naiScore = nai.getCurrentScore();
+ if (naiScore > bestScore) {
bestNetwork = nai;
- bestScore = nai.getCurrentScore();
+ bestScore = naiScore;
}
}
return bestNetwork;
}
/**
- * Returns whether an offer has a chance to beat a champion network for a request.
+ * Returns whether a {@link Scoreable} has a chance to beat a champion network for a request.
*
* Offers are sent by network providers when they think they might be able to make a network
* with the characteristics contained in the offer. If the offer has no chance to beat
@@ -257,15 +258,15 @@
*
* @param request The request to evaluate against.
* @param champion The currently best network for this request.
- * @param offer The offer.
+ * @param contestant The offer.
* @return Whether the offer stands a chance to beat the champion.
*/
public boolean mightBeat(@NonNull final NetworkRequest request,
@Nullable final NetworkAgentInfo champion,
- @NonNull final NetworkOffer offer) {
+ @NonNull final Scoreable contestant) {
// If this network can't even satisfy the request then it can't beat anything, not
// even an absence of network. It can't satisfy it anyway.
- if (!request.canBeSatisfiedBy(offer.caps)) return false;
+ if (!request.canBeSatisfiedBy(contestant.getCapsNoCopy())) return false;
// If there is no satisfying network, then this network can beat, because some network
// is always better than no network.
if (null == champion) return true;
@@ -274,25 +275,24 @@
// Otherwise rank them.
final ArrayList<Scoreable> candidates = new ArrayList<>();
candidates.add(champion);
- candidates.add(offer);
- return offer == getBestNetworkByPolicy(candidates, champion);
+ candidates.add(contestant);
+ return contestant == getBestNetworkByPolicy(candidates, champion);
} else {
- return mightBeatByLegacyInt(request, champion.getScore(), offer);
+ return mightBeatByLegacyInt(champion.getScore(), contestant);
}
}
/**
- * Returns whether an offer might beat a champion according to the legacy int.
+ * Returns whether a contestant might beat a champion according to the legacy int.
*/
- public boolean mightBeatByLegacyInt(@NonNull final NetworkRequest request,
- @Nullable final FullScore championScore,
- @NonNull final NetworkOffer offer) {
+ private boolean mightBeatByLegacyInt(@Nullable final FullScore championScore,
+ @NonNull final Scoreable contestant) {
final int offerIntScore;
- if (offer.caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
+ if (contestant.getCapsNoCopy().hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
// If the offer might have Internet access, then it might validate.
- offerIntScore = offer.score.getLegacyIntAsValidated();
+ offerIntScore = contestant.getScore().getLegacyIntAsValidated();
} else {
- offerIntScore = offer.score.getLegacyInt();
+ offerIntScore = contestant.getScore().getLegacyInt();
}
return championScore.getLegacyInt() < offerIntScore;
}
diff --git a/tests/net/TEST_MAPPING b/tests/net/TEST_MAPPING
index d659688..502f885 100644
--- a/tests/net/TEST_MAPPING
+++ b/tests/net/TEST_MAPPING
@@ -28,7 +28,7 @@
],
"imports": [
{
- "path": "cts/tests/tests/net"
+ "path": "packages/modules/Connectivity"
}
]
}
\ No newline at end of file
diff --git a/tests/net/common/java/ParseExceptionTest.kt b/tests/net/common/java/ParseExceptionTest.kt
new file mode 100644
index 0000000..b702d61
--- /dev/null
+++ b/tests/net/common/java/ParseExceptionTest.kt
@@ -0,0 +1,52 @@
+/*
+ * Copyright (C) 2021 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.
+ */
+
+import android.net.ParseException
+import android.os.Build
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.testutils.DevSdkIgnoreRule
+import junit.framework.Assert.assertEquals
+import junit.framework.Assert.assertNull
+import org.junit.Rule
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@SmallTest
+@RunWith(AndroidJUnit4::class)
+class ParseExceptionTest {
+ @get:Rule
+ val ignoreRule = DevSdkIgnoreRule(ignoreClassUpTo = Build.VERSION_CODES.R)
+
+ @Test
+ fun testConstructor_WithCause() {
+ val testMessage = "Test message"
+ val base = Exception("Test")
+ val exception = ParseException(testMessage, base)
+
+ assertEquals(testMessage, exception.response)
+ assertEquals(base, exception.cause)
+ }
+
+ @Test
+ fun testConstructor_NoCause() {
+ val testMessage = "Test message"
+ val exception = ParseException(testMessage)
+
+ assertEquals(testMessage, exception.response)
+ assertNull(exception.cause)
+ }
+}
\ No newline at end of file
diff --git a/tests/net/common/java/android/net/NetworkCapabilitiesTest.java b/tests/net/common/java/android/net/NetworkCapabilitiesTest.java
index 6d852bf..9b74583 100644
--- a/tests/net/common/java/android/net/NetworkCapabilitiesTest.java
+++ b/tests/net/common/java/android/net/NetworkCapabilitiesTest.java
@@ -312,7 +312,7 @@
.addCapability(NET_CAPABILITY_EIMS)
.addCapability(NET_CAPABILITY_NOT_METERED);
if (isAtLeastS()) {
- netCap.setSubIds(Set.of(TEST_SUBID1, TEST_SUBID2));
+ netCap.setSubscriptionIds(Set.of(TEST_SUBID1, TEST_SUBID2));
netCap.setUids(uids);
}
if (isAtLeastR()) {
@@ -642,16 +642,16 @@
assertTrue(nc2.appliesToUid(22));
// Verify the subscription id list can be combined only when they are equal.
- nc1.setSubIds(Set.of(TEST_SUBID1, TEST_SUBID2));
- nc2.setSubIds(Set.of(TEST_SUBID2));
+ nc1.setSubscriptionIds(Set.of(TEST_SUBID1, TEST_SUBID2));
+ nc2.setSubscriptionIds(Set.of(TEST_SUBID2));
assertThrows(IllegalStateException.class, () -> nc2.combineCapabilities(nc1));
- nc2.setSubIds(Set.of());
+ nc2.setSubscriptionIds(Set.of());
assertThrows(IllegalStateException.class, () -> nc2.combineCapabilities(nc1));
- nc2.setSubIds(Set.of(TEST_SUBID2, TEST_SUBID1));
+ nc2.setSubscriptionIds(Set.of(TEST_SUBID2, TEST_SUBID1));
nc2.combineCapabilities(nc1);
- assertEquals(Set.of(TEST_SUBID2, TEST_SUBID1), nc2.getSubIds());
+ assertEquals(Set.of(TEST_SUBID2, TEST_SUBID1), nc2.getSubscriptionIds());
}
}
@@ -806,20 +806,20 @@
assertEquals(nc1, nc2);
if (isAtLeastS()) {
- assertThrows(NullPointerException.class, () -> nc1.setSubIds(null));
- nc1.setSubIds(Set.of());
+ assertThrows(NullPointerException.class, () -> nc1.setSubscriptionIds(null));
+ nc1.setSubscriptionIds(Set.of());
nc2.set(nc1);
assertEquals(nc1, nc2);
- nc1.setSubIds(Set.of(TEST_SUBID1));
+ nc1.setSubscriptionIds(Set.of(TEST_SUBID1));
nc2.set(nc1);
assertEquals(nc1, nc2);
- nc2.setSubIds(Set.of(TEST_SUBID2, TEST_SUBID1));
+ nc2.setSubscriptionIds(Set.of(TEST_SUBID2, TEST_SUBID1));
nc2.set(nc1);
assertEquals(nc1, nc2);
- nc2.setSubIds(Set.of(TEST_SUBID3, TEST_SUBID2));
+ nc2.setSubscriptionIds(Set.of(TEST_SUBID3, TEST_SUBID2));
assertNotEquals(nc1, nc2);
}
}
@@ -908,8 +908,8 @@
// satisfy these requests.
final NetworkCapabilities nc = new NetworkCapabilities.Builder()
.addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
- .setSubIds(new ArraySet<>(subIds)).build();
- assertEquals(new ArraySet<>(subIds), nc.getSubIds());
+ .setSubscriptionIds(new ArraySet<>(subIds)).build();
+ assertEquals(new ArraySet<>(subIds), nc.getSubscriptionIds());
return nc;
}
@@ -921,11 +921,11 @@
final NetworkCapabilities ncWithoutRequestedIds = capsWithSubIds(TEST_SUBID3);
final NetworkRequest requestWithoutId = new NetworkRequest.Builder().build();
- assertEmpty(requestWithoutId.networkCapabilities.getSubIds());
+ assertEmpty(requestWithoutId.networkCapabilities.getSubscriptionIds());
final NetworkRequest requestWithIds = new NetworkRequest.Builder()
- .setSubIds(Set.of(TEST_SUBID1, TEST_SUBID2)).build();
+ .setSubscriptionIds(Set.of(TEST_SUBID1, TEST_SUBID2)).build();
assertEquals(Set.of(TEST_SUBID1, TEST_SUBID2),
- requestWithIds.networkCapabilities.getSubIds());
+ requestWithIds.networkCapabilities.getSubscriptionIds());
assertFalse(requestWithIds.canBeSatisfiedBy(ncWithoutId));
assertTrue(requestWithIds.canBeSatisfiedBy(ncWithOtherIds));
@@ -1138,8 +1138,8 @@
if (isAtLeastS()) {
final NetworkCapabilities nc2 = new NetworkCapabilities.Builder()
- .setSubIds(Set.of(TEST_SUBID1)).build();
- assertEquals(Set.of(TEST_SUBID1), nc2.getSubIds());
+ .setSubscriptionIds(Set.of(TEST_SUBID1)).build();
+ assertEquals(Set.of(TEST_SUBID1), nc2.getSubscriptionIds());
}
}
}
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index 9582e66..2624a1b 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -1791,7 +1791,7 @@
assertNull(mCm.getActiveNetworkForUid(Process.myUid()));
// Test getAllNetworks()
assertEmpty(mCm.getAllNetworks());
- assertEmpty(mCm.getAllNetworkStateSnapshot());
+ assertEmpty(mCm.getAllNetworkStateSnapshots());
}
/**
@@ -2668,25 +2668,6 @@
assertEquals(mCellNetworkAgent.getNetwork(), mCm.getActiveNetwork());
assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
- // Bring up wifi with a score of 70.
- // Cell is lingered because it would not satisfy any request, even if it validated.
- mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
- mWiFiNetworkAgent.adjustScore(50);
- mWiFiNetworkAgent.connect(false); // Score: 70
- callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
- callback.expectCallback(CallbackEntry.LOSING, mCellNetworkAgent);
- defaultCallback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent);
- assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
- assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
-
- // Tear down wifi.
- mWiFiNetworkAgent.disconnect();
- callback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
- defaultCallback.expectCallback(CallbackEntry.LOST, mWiFiNetworkAgent);
- defaultCallback.expectAvailableCallbacksUnvalidated(mCellNetworkAgent);
- assertEquals(mCellNetworkAgent.getNetwork(), mCm.getActiveNetwork());
- assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
-
// Bring up wifi, then validate it. Previous versions would immediately tear down cell, but
// it's arguably correct to linger it, since it was the default network before it validated.
mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
@@ -2991,11 +2972,17 @@
callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent);
assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
- // BUG: the network will no longer linger, even though it's validated and outscored.
- // TODO: fix this.
mEthernetNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_ETHERNET);
mEthernetNetworkAgent.connect(true);
+ // BUG: with the legacy int-based scoring code, the network will no longer linger, even
+ // though it's validated and outscored.
+ // The new policy-based scoring code fixes this.
+ // TODO: remove the line below and replace with the three commented lines when
+ // the policy-based scoring code is turned on.
callback.expectAvailableThenValidatedCallbacks(mEthernetNetworkAgent);
+ // callback.expectAvailableCallbacksUnvalidated(mEthernetNetworkAgent);
+ // callback.expectCallback(CallbackEntry.LOSING, mWiFiNetworkAgent);
+ // callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mEthernetNetworkAgent);
assertEquals(mEthernetNetworkAgent.getNetwork(), mCm.getActiveNetwork());
callback.assertNoCallback();
@@ -10422,12 +10409,15 @@
return UidRange.createForUser(UserHandle.of(userId));
}
- private void mockGetApplicationInfo(@NonNull final String packageName, @NonNull final int uid)
- throws Exception {
+ private void mockGetApplicationInfo(@NonNull final String packageName, @NonNull final int uid) {
final ApplicationInfo applicationInfo = new ApplicationInfo();
applicationInfo.uid = uid;
- when(mPackageManager.getApplicationInfo(eq(packageName), anyInt()))
- .thenReturn(applicationInfo);
+ try {
+ when(mPackageManager.getApplicationInfo(eq(packageName), anyInt()))
+ .thenReturn(applicationInfo);
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
}
private void mockGetApplicationInfoThrowsNameNotFound(@NonNull final String packageName)
@@ -10448,8 +10438,7 @@
}
private OemNetworkPreferences createDefaultOemNetworkPreferences(
- @OemNetworkPreferences.OemNetworkPreference final int preference)
- throws Exception {
+ @OemNetworkPreferences.OemNetworkPreference final int preference) {
// Arrange PackageManager mocks
mockGetApplicationInfo(TEST_PACKAGE_NAME, TEST_PACKAGE_UID);
@@ -10926,11 +10915,13 @@
mDone.complete(new Object());
}
- void expectOnComplete() throws Exception {
+ void expectOnComplete() {
try {
mDone.get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
fail("Expected onComplete() not received after " + TIMEOUT_MS + " ms");
+ } catch (Exception e) {
+ fail(e.getMessage());
}
}
@@ -12029,7 +12020,7 @@
}
@Test
- public void testGetAllNetworkStateSnapshot() throws Exception {
+ public void testGetAllNetworkStateSnapshots() throws Exception {
verifyNoNetwork();
// Setup test cellular network with specified LinkProperties and NetworkCapabilities,
@@ -12053,7 +12044,7 @@
mCellNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_CELLULAR, cellLp, cellNcTemplate);
mCellNetworkAgent.connect(true);
cellCb.expectAvailableCallbacksUnvalidated(mCellNetworkAgent);
- List<NetworkStateSnapshot> snapshots = mCm.getAllNetworkStateSnapshot();
+ List<NetworkStateSnapshot> snapshots = mCm.getAllNetworkStateSnapshots();
assertLength(1, snapshots);
// Compose the expected cellular snapshot for verification.
@@ -12075,7 +12066,7 @@
mWiFiNetworkAgent.getNetwork(), wifiNc, new LinkProperties(), null,
ConnectivityManager.TYPE_WIFI);
- snapshots = mCm.getAllNetworkStateSnapshot();
+ snapshots = mCm.getAllNetworkStateSnapshots();
assertLength(2, snapshots);
assertContainsAll(snapshots, cellSnapshot, wifiSnapshot);
@@ -12084,20 +12075,20 @@
// temporary shortage of connectivity of a connected network.
mCellNetworkAgent.suspend();
waitForIdle();
- snapshots = mCm.getAllNetworkStateSnapshot();
+ snapshots = mCm.getAllNetworkStateSnapshots();
assertLength(1, snapshots);
assertEquals(wifiSnapshot, snapshots.get(0));
// Disconnect wifi, verify the snapshots contain nothing.
mWiFiNetworkAgent.disconnect();
waitForIdle();
- snapshots = mCm.getAllNetworkStateSnapshot();
+ snapshots = mCm.getAllNetworkStateSnapshots();
assertEquals(mCellNetworkAgent.getNetwork(), mCm.getActiveNetwork());
assertLength(0, snapshots);
mCellNetworkAgent.resume();
waitForIdle();
- snapshots = mCm.getAllNetworkStateSnapshot();
+ snapshots = mCm.getAllNetworkStateSnapshots();
assertLength(1, snapshots);
assertEquals(cellSnapshot, snapshots.get(0));
@@ -12602,12 +12593,12 @@
public void testSubIdsClearedWithoutNetworkFactoryPermission() throws Exception {
mServiceContext.setPermission(NETWORK_FACTORY, PERMISSION_DENIED);
final NetworkCapabilities nc = new NetworkCapabilities();
- nc.setSubIds(Collections.singleton(Process.myUid()));
+ nc.setSubscriptionIds(Collections.singleton(Process.myUid()));
final NetworkCapabilities result =
mService.networkCapabilitiesRestrictedForCallerPermissions(
nc, Process.myPid(), Process.myUid());
- assertTrue(result.getSubIds().isEmpty());
+ assertTrue(result.getSubscriptionIds().isEmpty());
}
@Test
@@ -12616,17 +12607,17 @@
final Set<Integer> subIds = Collections.singleton(Process.myUid());
final NetworkCapabilities nc = new NetworkCapabilities();
- nc.setSubIds(subIds);
+ nc.setSubscriptionIds(subIds);
final NetworkCapabilities result =
mService.networkCapabilitiesRestrictedForCallerPermissions(
nc, Process.myPid(), Process.myUid());
- assertEquals(subIds, result.getSubIds());
+ assertEquals(subIds, result.getSubscriptionIds());
}
private NetworkRequest getRequestWithSubIds() {
return new NetworkRequest.Builder()
- .setSubIds(Collections.singleton(Process.myUid()))
+ .setSubscriptionIds(Collections.singleton(Process.myUid()))
.build();
}
@@ -12661,4 +12652,72 @@
expected,
() -> mCm.registerNetworkCallback(getRequestWithSubIds(), new NetworkCallback()));
}
+
+ /**
+ * Validate request counts are counted accurately on setProfileNetworkPreference on set/replace.
+ */
+ @Test
+ public void testProfileNetworkPrefCountsRequestsCorrectlyOnSet() throws Exception {
+ final UserHandle testHandle = setupEnterpriseNetwork();
+ testRequestCountLimits(() -> {
+ // Set initially to test the limit prior to having existing requests.
+ final TestOnCompleteListener listener = new TestOnCompleteListener();
+ mCm.setProfileNetworkPreference(testHandle, PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
+ Runnable::run, listener);
+ listener.expectOnComplete();
+
+ // re-set so as to test the limit as part of replacing existing requests.
+ mCm.setProfileNetworkPreference(testHandle, PROFILE_NETWORK_PREFERENCE_ENTERPRISE,
+ Runnable::run, listener);
+ listener.expectOnComplete();
+ });
+ }
+
+ /**
+ * Validate request counts are counted accurately on setOemNetworkPreference on set/replace.
+ */
+ @Test
+ public void testSetOemNetworkPreferenceCountsRequestsCorrectlyOnSet() throws Exception {
+ mockHasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE, true);
+ @OemNetworkPreferences.OemNetworkPreference final int networkPref =
+ OEM_NETWORK_PREFERENCE_OEM_PRIVATE_ONLY;
+ testRequestCountLimits(() -> {
+ // Set initially to test the limit prior to having existing requests.
+ final TestOemListenerCallback listener = new TestOemListenerCallback();
+ mService.setOemNetworkPreference(
+ createDefaultOemNetworkPreferences(networkPref), listener);
+ listener.expectOnComplete();
+
+ // re-set so as to test the limit as part of replacing existing requests.
+ mService.setOemNetworkPreference(
+ createDefaultOemNetworkPreferences(networkPref), listener);
+ listener.expectOnComplete();
+ });
+ }
+
+ private void testRequestCountLimits(@NonNull final Runnable r) throws Exception {
+ final ArraySet<TestNetworkCallback> callbacks = new ArraySet<>();
+ try {
+ final int requestCount = mService.mSystemNetworkRequestCounter
+ .mUidToNetworkRequestCount.get(Process.myUid());
+ // The limit is hit when total requests <= limit.
+ final int maxCount =
+ ConnectivityService.MAX_NETWORK_REQUESTS_PER_SYSTEM_UID - requestCount;
+ // Need permission so registerDefaultNetworkCallback uses mSystemNetworkRequestCounter
+ withPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, () -> {
+ for (int i = 1; i < maxCount - 1; i++) {
+ final TestNetworkCallback cb = new TestNetworkCallback();
+ mCm.registerDefaultNetworkCallback(cb);
+ callbacks.add(cb);
+ }
+
+ // Code to run to check if it triggers a max request count limit error.
+ r.run();
+ });
+ } finally {
+ for (final TestNetworkCallback cb : callbacks) {
+ mCm.unregisterNetworkCallback(cb);
+ }
+ }
+ }
}
diff --git a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
index eeeb4fb..42441c2 100644
--- a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
+++ b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
@@ -67,6 +67,7 @@
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -88,8 +89,8 @@
import android.net.NetworkStats;
import android.net.NetworkStatsHistory;
import android.net.NetworkTemplate;
-import android.net.UnderlyingNetworkInfo;
import android.net.TelephonyNetworkSpecifier;
+import android.net.UnderlyingNetworkInfo;
import android.net.netstats.provider.INetworkStatsProviderCallback;
import android.os.ConditionVariable;
import android.os.Handler;
@@ -165,9 +166,9 @@
private long mElapsedRealtime;
- private BroadcastInterceptingContext mServiceContext;
private File mStatsDir;
-
+ private MockContext mServiceContext;
+ private @Mock TelephonyManager mTelephonyManager;
private @Mock INetworkManagementService mNetManager;
private @Mock NetworkStatsFactory mStatsFactory;
private @Mock NetworkStatsSettings mSettings;
@@ -183,19 +184,32 @@
private ContentObserver mContentObserver;
private Handler mHandler;
+ private class MockContext extends BroadcastInterceptingContext {
+ private final Context mBaseContext;
+
+ MockContext(Context base) {
+ super(base);
+ mBaseContext = base;
+ }
+
+ @Override
+ public Object getSystemService(String name) {
+ if (Context.TELEPHONY_SERVICE.equals(name)) return mTelephonyManager;
+ return mBaseContext.getSystemService(name);
+ }
+ }
+
private final Clock mClock = new SimpleClock(ZoneOffset.UTC) {
@Override
public long millis() {
return currentTimeMillis();
}
};
-
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
final Context context = InstrumentationRegistry.getContext();
-
- mServiceContext = new BroadcastInterceptingContext(context);
+ mServiceContext = new MockContext(context);
mStatsDir = context.getFilesDir();
if (mStatsDir.exists()) {
IoUtils.deleteContents(mStatsDir);
@@ -217,7 +231,6 @@
expectDefaultSettings();
expectNetworkStatsUidDetail(buildEmptyStats());
expectSystemReady();
-
mService.systemReady();
// Verify that system ready fetches realtime stats
verify(mStatsFactory).readNetworkStatsDetail(UID_ALL, INTERFACES_ALL, TAG_ALL);
@@ -228,6 +241,9 @@
verify(mNetworkStatsSubscriptionsMonitor).start();
reset(mNetworkStatsSubscriptionsMonitor);
+ doReturn(TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS).when(mTelephonyManager)
+ .checkCarrierPrivilegesForPackageAnyPhone(anyString());
+
mSession = mService.openSession();
assertNotNull("openSession() failed", mSession);
@@ -873,7 +889,7 @@
final LinkProperties stackedProp = new LinkProperties();
stackedProp.setInterfaceName(stackedIface);
final NetworkStateSnapshot wifiState = buildWifiState();
- wifiState.linkProperties.addStackedLink(stackedProp);
+ wifiState.getLinkProperties().addStackedLink(stackedProp);
NetworkStateSnapshot[] states = new NetworkStateSnapshot[] {wifiState};
expectNetworkStatsSummary(buildEmptyStats());
@@ -1564,10 +1580,10 @@
}
private String getActiveIface(NetworkStateSnapshot... states) throws Exception {
- if (states == null || states.length == 0 || states[0].linkProperties == null) {
+ if (states == null || states.length == 0 || states[0].getLinkProperties() == null) {
return null;
}
- return states[0].linkProperties.getInterfaceName();
+ return states[0].getLinkProperties().getInterfaceName();
}
private void expectNetworkStatsSummary(NetworkStats summary) throws Exception {