Merge "[VCN19] Rename get/setSubIds to get/setSubscriptionIds"
diff --git a/framework/src/android/net/ConnectivityManager.java b/framework/src/android/net/ConnectivityManager.java
index 043ff38..4dd0984 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)
diff --git a/framework/src/android/net/NetworkRequest.java b/framework/src/android/net/NetworkRequest.java
index e8bd640..8c4f419 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;
}
/**
diff --git a/service/ServiceConnectivityResources/Android.bp b/service/ServiceConnectivityResources/Android.bp
index fa4501a..7de1c6e 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",
resource_dirs: [
"res",
],
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 6b9a606..142169e 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -78,7 +78,6 @@
import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
import static android.net.NetworkCapabilities.TRANSPORT_TEST;
import static android.net.NetworkCapabilities.TRANSPORT_VPN;
-import static android.net.NetworkPolicyManager.blockedReasonsToString;
import static android.net.NetworkRequest.Type.LISTEN_FOR_BEST;
import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
import static android.os.Process.INVALID_UID;
@@ -319,7 +318,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.
@@ -336,7 +336,8 @@
protected final PermissionMonitor mPermissionMonitor;
private final PerUidCounter mNetworkRequestCounter;
- private final PerUidCounter mSystemNetworkRequestCounter;
+ @VisibleForTesting
+ final PerUidCounter mSystemNetworkRequestCounter;
private volatile boolean mLockdownEnabled;
@@ -1047,8 +1048,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
@@ -1072,15 +1074,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.
*
@@ -1088,16 +1095,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;
+ }
}
/**
@@ -1575,7 +1616,7 @@
? nri.getActiveRequest().requestId : nri.mRequests.get(0).requestId;
mNetworkInfoBlockingLogs.log(String.format(
"%s %d(%d) on netId %d: %s", action, nri.mAsUid, requestId, net.getNetId(),
- blockedReasonsToString(blocked)));
+ Integer.toHexString(blocked)));
}
/**
@@ -2859,7 +2900,7 @@
final int uid = mUidBlockedReasons.keyAt(i);
final int blockedReasons = mUidBlockedReasons.valueAt(i);
pw.println("UID=" + uid + " blockedReasons="
- + blockedReasonsToString(blockedReasons));
+ + Integer.toHexString(blockedReasons));
} catch (ArrayIndexOutOfBoundsException e) {
pw.println(" ArrayIndexOutOfBoundsException");
} catch (ConcurrentModificationException e) {
@@ -9569,9 +9610,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();
@@ -9657,9 +9702,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) {
@@ -9684,10 +9736,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/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
index f17715a..b702d61 100644
--- a/tests/net/common/java/ParseExceptionTest.kt
+++ b/tests/net/common/java/ParseExceptionTest.kt
@@ -15,16 +15,22 @@
*/
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"
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index c2acab8..9c797e4 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -10246,12 +10246,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)
@@ -10272,8 +10275,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);
@@ -10750,11 +10752,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());
}
}
@@ -12369,4 +12373,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..0ab4d2b 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);