Merge "Address API review feedback"
diff --git a/framework/api/system-current.txt b/framework/api/system-current.txt
index fc65fec..5750845 100644
--- a/framework/api/system-current.txt
+++ b/framework/api/system-current.txt
@@ -275,7 +275,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);
@@ -306,7 +306,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);
}
@@ -329,7 +329,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/ConnectivityManager.java b/framework/src/android/net/ConnectivityManager.java
index c042395..4636abb 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/NetworkCapabilities.java b/framework/src/android/net/NetworkCapabilities.java
index a43dd15..937a9d2 100644
--- a/framework/src/android/net/NetworkCapabilities.java
+++ b/framework/src/android/net/NetworkCapabilities.java
@@ -1733,7 +1733,7 @@
combineSSIDs(nc);
combineRequestor(nc);
combineAdministratorUids(nc);
- combineSubIds(nc);
+ combineSubscriptionIds(nc);
}
/**
@@ -1755,7 +1755,7 @@
&& (onlyImmutable || satisfiedByUids(nc))
&& (onlyImmutable || satisfiedBySSID(nc))
&& (onlyImmutable || satisfiedByRequestor(nc))
- && (onlyImmutable || satisfiedBySubIds(nc)));
+ && (onlyImmutable || satisfiedBySubscriptionIds(nc)));
}
/**
@@ -1852,7 +1852,7 @@
&& equalsPrivateDnsBroken(that)
&& equalsRequestor(that)
&& equalsAdministratorUids(that)
- && equalsSubIds(that);
+ && equalsSubscriptionIds(that);
}
@Override
@@ -2329,7 +2329,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;
}
@@ -2345,14 +2345,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);
}
@@ -2361,7 +2361,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) {
@@ -2378,7 +2378,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");
}
@@ -2720,8 +2720,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 3a8a07a..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;
}
/**
@@ -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 fa4501a..912d99f 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",
],
@@ -30,6 +30,10 @@
apex_available: [
"com.android.tethering",
],
- // TODO: use a dedicated cert once generated
- certificate: "platform",
+ certificate: ":com.android.connectivity.resources.certificate",
+}
+
+android_app_certificate {
+ name: "com.android.connectivity.resources.certificate",
+ certificate: "resources-certs/com.android.connectivity.resources",
}
diff --git a/service/ServiceConnectivityResources/res/values/config.xml b/service/ServiceConnectivityResources/res/values/config.xml
index 71674e4..9ff2a22 100644
--- a/service/ServiceConnectivityResources/res/values/config.xml
+++ b/service/ServiceConnectivityResources/res/values/config.xml
@@ -78,6 +78,11 @@
<item>1,3</item>
</string-array>
+ <!-- Reserved privileged keepalive slots per transport. -->
+ <integer translatable="false" name="config_reservedPrivilegedKeepaliveSlots">2</integer>
+
+ <!-- Allowed unprivileged keepalive slots per uid. -->
+ <integer translatable="false" name="config_allowedUnprivilegedKeepalivePerUid">2</integer>
<!-- Default value for ConnectivityManager.getMultipathPreference() on metered networks. Actual
device behaviour is controlled by the metered multipath preference in
@@ -89,4 +94,33 @@
Settings.Global.NETWORK_AVOID_BAD_WIFI. This is the default value of that setting. -->
<integer translatable="false" name="config_networkAvoidBadWifi">1</integer>
+ <!-- Array of ConnectivityManager.TYPE_xxxx constants for networks that may only
+ be controlled by systemOrSignature apps. -->
+ <integer-array translatable="false" name="config_protectedNetworks">
+ <item>10</item>
+ <item>11</item>
+ <item>12</item>
+ <item>14</item>
+ <item>15</item>
+ </integer-array>
+
+ <!-- Whether the internal vehicle network should remain active even when no
+ apps requested it. -->
+ <bool name="config_vehicleInternalNetworkAlwaysRequested">false</bool>
+
+
+ <!-- If the hardware supports specially marking packets that caused a wakeup of the
+ main CPU, set this value to the mark used. -->
+ <integer name="config_networkWakeupPacketMark">0</integer>
+
+ <!-- Mask to use when checking skb mark defined in config_networkWakeupPacketMark above. -->
+ <integer name="config_networkWakeupPacketMask">0</integer>
+
+ <!-- Whether/how to notify the user on network switches. See LingerMonitor.java. -->
+ <integer translatable="false" name="config_networkNotifySwitchType">0</integer>
+
+ <!-- What types of network switches to notify. See LingerMonitor.java. -->
+ <string-array translatable="false" name="config_networkNotifySwitches">
+ </string-array>
+
</resources>
diff --git a/service/ServiceConnectivityResources/res/values/overlayable.xml b/service/ServiceConnectivityResources/res/values/overlayable.xml
index 25e19ce..717d08e 100644
--- a/service/ServiceConnectivityResources/res/values/overlayable.xml
+++ b/service/ServiceConnectivityResources/res/values/overlayable.xml
@@ -26,6 +26,12 @@
<item type="integer" name="config_networkMeteredMultipathPreference"/>
<item type="array" name="config_networkSupportedKeepaliveCount"/>
<item type="integer" name="config_networkAvoidBadWifi"/>
+ <item type="array" name="config_protectedNetworks"/>
+ <item type="bool" name="config_vehicleInternalNetworkAlwaysRequested"/>
+ <item type="integer" name="config_networkWakeupPacketMark"/>
+ <item type="integer" name="config_networkWakeupPacketMask"/>
+ <item type="integer" name="config_networkNotifySwitchType"/>
+ <item type="array" name="config_networkNotifySwitches"/>
</policy>
</overlayable>
diff --git a/service/ServiceConnectivityResources/resources-certs/com.android.connectivity.resources.pk8 b/service/ServiceConnectivityResources/resources-certs/com.android.connectivity.resources.pk8
new file mode 100644
index 0000000..bfdc28b
--- /dev/null
+++ b/service/ServiceConnectivityResources/resources-certs/com.android.connectivity.resources.pk8
Binary files differ
diff --git a/service/ServiceConnectivityResources/resources-certs/com.android.connectivity.resources.x509.pem b/service/ServiceConnectivityResources/resources-certs/com.android.connectivity.resources.x509.pem
new file mode 100644
index 0000000..70eca1c
--- /dev/null
+++ b/service/ServiceConnectivityResources/resources-certs/com.android.connectivity.resources.x509.pem
@@ -0,0 +1,36 @@
+-----BEGIN CERTIFICATE-----
+MIIGQzCCBCugAwIBAgIUZY8nxBMINp/79sziXU77MLPpEXowDQYJKoZIhvcNAQEL
+BQAwga8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQH
+DA1Nb3VudGFpbiBWaWV3MRAwDgYDVQQKDAdBbmRyb2lkMRAwDgYDVQQLDAdBbmRy
+b2lkMSswKQYDVQQDDCJjb20uYW5kcm9pZC5jb25uZWN0aXZpdHkucmVzb3VyY2Vz
+MSIwIAYJKoZIhvcNAQkBFhNhbmRyb2lkQGFuZHJvaWQuY29tMCAXDTIxMDQyMjA3
+MjkxMFoYDzQ3NTkwMzE5MDcyOTEwWjCBrzELMAkGA1UEBhMCVVMxEzARBgNVBAgM
+CkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxEDAOBgNVBAoMB0Fu
+ZHJvaWQxEDAOBgNVBAsMB0FuZHJvaWQxKzApBgNVBAMMImNvbS5hbmRyb2lkLmNv
+bm5lY3Rpdml0eS5yZXNvdXJjZXMxIjAgBgkqhkiG9w0BCQEWE2FuZHJvaWRAYW5k
+cm9pZC5jb20wggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC361NT9qSz
+h3uLcLBD67HNE1QX3ykwGyw8u7ExzqpsqLCzZsOCFRJQJY+CnrgNaAz0NXeNtx7D
+Lpr9OCWWbG1KTQ/ANlR8g6xCqlAk4xdixsAnIlBUJB90+RlkcWrliE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49Qvq+
+5L6JjHFVSSOEbIjboNib26zNackjbiefF74meSUbGVGfcJ1OdkZsXZWphmER8V7X
+Wz3Z8JwOXW1RLPgcbjilHUR5g8pEmWBv4KrTCSg5IvOJr4w3pyyMBiiVI9NI5sB7
+g5Mi9v3ifPD1OHA4Y3wYCb26mMEpRb8ogOhMHcGNbdnL3QtIUg4cmXGqGSY/LbpU
+np0sIQDSjc46o79F0boPsLlaN3US5WZIu0nc9SHkjoNhd0CJQ5r9aEn4/wNrZgxs
+s8OEKsqcS7OsWiIE6nG51TMDsCuyRBrGedtSUyFFSVSpivpYIrPVNKKlHsJ/o+Nv
+Udb6dBjCraPvJB8binB1aojwya3MwRs=
+-----END CERTIFICATE-----
diff --git a/service/ServiceConnectivityResources/resources-certs/key.pem b/service/ServiceConnectivityResources/resources-certs/key.pem
new file mode 100644
index 0000000..38771c2
--- /dev/null
+++ b/service/ServiceConnectivityResources/resources-certs/key.pem
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQC361NT9qSzh3uL
+cLBD67HNE1QX3ykwGyw8u7ExzqpsqLCzZsOCFRJQJY+CnrgNaAz0NXeNtx7DLpr9
+OCWWbG1KTQ/ANlR8g6xCqlAk4xdixsAnIlBUJB90+RlkcWrliEY7OwcqIu3x/qe+
+5UR3irIFZOApNHOm760PjRl7VWAnYZC/PhkW0iKwnBuE96ddPIJc+KuiqCcPKflg
+F4/jmbHTZ+5uvVV4qkfovc744HnQtQoCDoYR8WpsJv3YL5xrAv78o3WCRzx6xxB+
+eUlJpuyyfIee2lUCG4Ly4jgOsWaupnUglLDORnz/L8fhhnpv83wLal7E0Shxsqvz
+ZZbb1QLuwMWy++gfzdDvGWewES3BdSFp5NwYWXQGZWSkEEFbIiorKSurU1On9OwB
+0jT/H2B/CAFKYJQ2V+hQ4I7PG+z9p7ZFNR6GZbZuhEr+Dpq1CwtI3W45izr3RJgc
+c2I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4K5eJCY8OuMYUL+if6ymFmLc4dkYSiOQ
+Vaob4+qKvfQEoIcv1EvXEBhFlTCKmQaDShWeBHqxmqqWbUr0M3qt/1U95bGsxlPr
+AEp+aG+uTDyB+ryvd/U53wHhcPnFJ5gGbC3KL7J3+tTngoD/gq7vOhmTfC8BDehH
+sy61GMmy6R0KaX1IgVuC+j0PaC14qYB5jfZD675930/asWqDmqpOmsVn2n+L888T
+zRkCggEBAIMuNhhfGGY6E4PLUcPM0LZA4tI/wTpeYEahunU1hWIYo/iZB9od2biz
+EeYY4BtkzCoE5ZWYXqTgiMxN4hJ4ufB+5umZ4BO0Gyx4p2/Ik2uv1BXu++GbM+TI
+eeFmaBh00dTtjccpeZEDgNkjAO7Rh9GV2ifl3uhqg0MnFXywPUX2Vm2bmwQXnfV9
+wY2TXgOmBN2epFBOArJwiA5IfV+bSqXCFCx8fgyOWpMNq9+zDRd6KCeHyge54ahm
+jMhCncp1OPDPaV+gnUdgWDGcywYg0KQvu5dLuCFfvucnsWoH2txsVZrXFha5XSM4
+/4Pif3Aj5E9dm1zkUtZJYQbII5SKQ94=
+-----END PRIVATE KEY-----
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index cbafaa2..9494c4c 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;
@@ -217,6 +216,7 @@
import android.util.SparseArray;
import android.util.SparseIntArray;
+import com.android.connectivity.resources.R;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.IndentingPrintWriter;
@@ -319,7 +319,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 +337,8 @@
protected final PermissionMonitor mPermissionMonitor;
private final PerUidCounter mNetworkRequestCounter;
- private final PerUidCounter mSystemNetworkRequestCounter;
+ @VisibleForTesting
+ final PerUidCounter mSystemNetworkRequestCounter;
private volatile boolean mLockdownEnabled;
@@ -829,8 +831,7 @@
private ArrayMap<Integer, Integer> loadRestoreTimers() {
final String[] configs = mService.mResources.get().getStringArray(
- com.android.connectivity.resources.R.array
- .config_legacy_networktype_restore_timers);
+ R.array.config_legacy_networktype_restore_timers);
final ArrayMap<Integer, Integer> ret = new ArrayMap<>(configs.length);
for (final String config : configs) {
final String[] splits = TextUtils.split(config, ",");
@@ -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;
+ }
}
/**
@@ -1269,8 +1310,7 @@
mLegacyTypeTracker.loadSupportedTypes(mContext, mTelephonyManager);
mProtectedNetworks = new ArrayList<>();
- int[] protectedNetworks = context.getResources().getIntArray(
- com.android.internal.R.array.config_protectedNetworks);
+ int[] protectedNetworks = mResources.get().getIntArray(R.array.config_protectedNetworks);
for (int p : protectedNetworks) {
if (mLegacyTypeTracker.isTypeSupported(p) && !mProtectedNetworks.contains(p)) {
mProtectedNetworks.add(p);
@@ -1442,8 +1482,14 @@
ConnectivitySettingsManager.MOBILE_DATA_ALWAYS_ON, true /* defaultValue */);
handleAlwaysOnNetworkRequest(mDefaultWifiRequest,
ConnectivitySettingsManager.WIFI_ALWAYS_REQUESTED, false /* defaultValue */);
+ final boolean vehicleAlwaysRequested = mResources.get().getBoolean(
+ R.bool.config_vehicleInternalNetworkAlwaysRequested);
+ // TODO (b/183076074): remove legacy fallback after migrating overlays
+ final boolean legacyAlwaysRequested = mContext.getResources().getBoolean(
+ mContext.getResources().getIdentifier(
+ "config_vehicleInternalNetworkAlwaysRequested", "bool", "android"));
handleAlwaysOnNetworkRequest(mDefaultVehicleRequest,
- com.android.internal.R.bool.config_vehicleInternalNetworkAlwaysRequested);
+ vehicleAlwaysRequested || legacyAlwaysRequested);
}
private void registerSettingsCallbacks() {
@@ -1575,7 +1621,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)));
}
/**
@@ -1907,7 +1953,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;
@@ -2859,7 +2905,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) {
@@ -4798,7 +4844,7 @@
mWakelockLogs.log("ACQUIRE for " + forWhom);
Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
final int lockTimeout = mResources.get().getInteger(
- com.android.connectivity.resources.R.integer.config_networkTransitionTimeout);
+ R.integer.config_networkTransitionTimeout);
mHandler.sendMessageDelayed(msg, lockTimeout);
}
@@ -5722,7 +5768,7 @@
}
mAppOpsManager.checkPackage(callerUid, callerPackageName);
- if (!nc.getSubIds().isEmpty()) {
+ if (!nc.getSubscriptionIds().isEmpty()) {
enforceNetworkFactoryPermission();
}
}
@@ -6659,10 +6705,16 @@
return;
}
- int mark = mContext.getResources().getInteger(
- com.android.internal.R.integer.config_networkWakeupPacketMark);
- int mask = mContext.getResources().getInteger(
- com.android.internal.R.integer.config_networkWakeupPacketMask);
+ int mark = mResources.get().getInteger(R.integer.config_networkWakeupPacketMark);
+ int mask = mResources.get().getInteger(R.integer.config_networkWakeupPacketMask);
+
+ // TODO (b/183076074): remove legacy fallback after migrating overlays
+ final int legacyMark = mContext.getResources().getInteger(mContext.getResources()
+ .getIdentifier("config_networkWakeupPacketMark", "integer", "android"));
+ final int legacyMask = mContext.getResources().getInteger(mContext.getResources()
+ .getIdentifier("config_networkWakeupPacketMask", "integer", "android"));
+ mark = mark == 0 ? legacyMark : mark;
+ mask = mask == 0 ? legacyMask : mask;
// Mask/mark of zero will not detect anything interesting.
// Don't install rules unless both values are nonzero.
@@ -6855,8 +6907,7 @@
private void updateWakeOnLan(@NonNull LinkProperties lp) {
if (mWolSupportedInterfaces == null) {
mWolSupportedInterfaces = new ArraySet<>(mResources.get().getStringArray(
- com.android.connectivity.resources.R.array
- .config_wakeonlan_supported_interfaces));
+ R.array.config_wakeonlan_supported_interfaces));
}
lp.setWakeOnLanSupported(mWolSupportedInterfaces.contains(lp.getInterfaceName()));
}
@@ -8432,7 +8483,7 @@
public String getCaptivePortalServerUrl() {
enforceNetworkStackOrSettingsPermission();
String settingUrl = mResources.get().getString(
- com.android.connectivity.resources.R.string.config_networkCaptivePortalServerUrl);
+ R.string.config_networkCaptivePortalServerUrl);
if (!TextUtils.isEmpty(settingUrl)) {
return settingUrl;
@@ -9569,9 +9620,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 +9712,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 +9746,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/KeepaliveTracker.java b/services/core/java/com/android/server/connectivity/KeepaliveTracker.java
index 058dac8..acf39f0 100644
--- a/services/core/java/com/android/server/connectivity/KeepaliveTracker.java
+++ b/services/core/java/com/android/server/connectivity/KeepaliveTracker.java
@@ -37,6 +37,7 @@
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.content.Context;
+import android.net.ConnectivityResources;
import android.net.ISocketKeepaliveCallback;
import android.net.InetAddresses;
import android.net.InvalidPacketException;
@@ -57,7 +58,7 @@
import android.util.Log;
import android.util.Pair;
-import com.android.internal.R;
+import com.android.connectivity.resources.R;
import com.android.internal.util.IndentingPrintWriter;
import com.android.net.module.util.HexDump;
import com.android.net.module.util.IpUtils;
@@ -112,10 +113,19 @@
mTcpController = new TcpKeepaliveController(handler);
mContext = context;
mSupportedKeepalives = KeepaliveUtils.getSupportedKeepalives(mContext);
- mReservedPrivilegedSlots = mContext.getResources().getInteger(
- R.integer.config_reservedPrivilegedKeepaliveSlots);
- mAllowedUnprivilegedSlotsForUid = mContext.getResources().getInteger(
- R.integer.config_allowedUnprivilegedKeepalivePerUid);
+
+ // TODO (b/183076074): stop reading legacy resources after migrating overlays
+ final int legacyReservedSlots = mContext.getResources().getInteger(
+ mContext.getResources().getIdentifier(
+ "config_reservedPrivilegedKeepaliveSlots", "integer", "android"));
+ final int legacyAllowedSlots = mContext.getResources().getInteger(
+ mContext.getResources().getIdentifier(
+ "config_allowedUnprivilegedKeepalivePerUid", "integer", "android"));
+ final ConnectivityResources res = new ConnectivityResources(mContext);
+ mReservedPrivilegedSlots = Math.min(legacyReservedSlots, res.get().getInteger(
+ R.integer.config_reservedPrivilegedKeepaliveSlots));
+ mAllowedUnprivilegedSlotsForUid = Math.min(legacyAllowedSlots, res.get().getInteger(
+ R.integer.config_allowedUnprivilegedKeepalivePerUid));
}
/**
diff --git a/services/core/java/com/android/server/connectivity/LingerMonitor.java b/services/core/java/com/android/server/connectivity/LingerMonitor.java
index adec7ad..032612c 100644
--- a/services/core/java/com/android/server/connectivity/LingerMonitor.java
+++ b/services/core/java/com/android/server/connectivity/LingerMonitor.java
@@ -24,6 +24,8 @@
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
+import android.content.res.Resources;
+import android.net.ConnectivityResources;
import android.net.NetworkCapabilities;
import android.os.SystemClock;
import android.os.UserHandle;
@@ -34,7 +36,7 @@
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
-import com.android.internal.R;
+import com.android.connectivity.resources.R;
import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.MessageUtils;
import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
@@ -72,6 +74,7 @@
new Class[] { LingerMonitor.class }, new String[]{ "NOTIFY_TYPE_" });
private final Context mContext;
+ final Resources mResources;
private final NetworkNotificationManager mNotifier;
private final int mDailyLimit;
private final long mRateLimitMillis;
@@ -89,6 +92,7 @@
public LingerMonitor(Context context, NetworkNotificationManager notifier,
int dailyLimit, long rateLimitMillis) {
mContext = context;
+ mResources = new ConnectivityResources(mContext).get();
mNotifier = notifier;
mDailyLimit = dailyLimit;
mRateLimitMillis = rateLimitMillis;
@@ -128,8 +132,7 @@
@VisibleForTesting
public boolean isNotificationEnabled(NetworkAgentInfo fromNai, NetworkAgentInfo toNai) {
// TODO: Evaluate moving to CarrierConfigManager.
- String[] notifySwitches =
- mContext.getResources().getStringArray(R.array.config_networkNotifySwitches);
+ String[] notifySwitches = mResources.getStringArray(R.array.config_networkNotifySwitches);
if (VDBG) {
Log.d(TAG, "Notify on network switches: " + Arrays.toString(notifySwitches));
@@ -178,8 +181,7 @@
// Notify the user of a network switch using a notification or a toast.
private void notify(NetworkAgentInfo fromNai, NetworkAgentInfo toNai, boolean forceToast) {
- int notifyType =
- mContext.getResources().getInteger(R.integer.config_networkNotifySwitchType);
+ int notifyType = mResources.getInteger(R.integer.config_networkNotifySwitchType);
if (notifyType == NOTIFY_TYPE_NOTIFICATION && forceToast) {
notifyType = NOTIFY_TYPE_TOAST;
}
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/common/java/android/net/NetworkCapabilitiesTest.java b/tests/net/common/java/android/net/NetworkCapabilitiesTest.java
index e7718b5..33f2c67 100644
--- a/tests/net/common/java/android/net/NetworkCapabilitiesTest.java
+++ b/tests/net/common/java/android/net/NetworkCapabilitiesTest.java
@@ -311,7 +311,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()) {
@@ -641,16 +641,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());
}
}
@@ -805,20 +805,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);
}
}
@@ -907,8 +907,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;
}
@@ -920,11 +920,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));
@@ -1132,8 +1132,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/integration/AndroidManifest.xml b/tests/net/integration/AndroidManifest.xml
index db18500..2e13689 100644
--- a/tests/net/integration/AndroidManifest.xml
+++ b/tests/net/integration/AndroidManifest.xml
@@ -38,6 +38,8 @@
<!-- Reading DeviceConfig flags -->
<uses-permission android:name="android.permission.READ_DEVICE_CONFIG"/>
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM"/>
+ <!-- Querying the resources package -->
+ <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
<application android:debuggable="true">
<uses-library android:name="android.test.runner"/>
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index 13c8ec5..20d9b94 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -1637,25 +1637,26 @@
}).when(deps).makeMultinetworkPolicyTracker(any(), any(), any());
doReturn(true).when(deps).getCellular464XlatEnabled();
- doReturn(60000).when(mResources).getInteger(
- com.android.connectivity.resources.R.integer.config_networkTransitionTimeout);
- doReturn("").when(mResources).getString(
- com.android.connectivity.resources.R.string.config_networkCaptivePortalServerUrl);
+ doReturn(60000).when(mResources).getInteger(R.integer.config_networkTransitionTimeout);
+ doReturn("").when(mResources).getString(R.string.config_networkCaptivePortalServerUrl);
doReturn(new String[]{ WIFI_WOL_IFNAME }).when(mResources).getStringArray(
- com.android.connectivity.resources.R.array.config_wakeonlan_supported_interfaces);
+ R.array.config_wakeonlan_supported_interfaces);
doReturn(new String[] { "0,1", "1,3" }).when(mResources).getStringArray(
- com.android.connectivity.resources.R.array.config_networkSupportedKeepaliveCount);
- doReturn(com.android.connectivity.resources.R.array.config_networkSupportedKeepaliveCount)
- .when(mResources).getIdentifier(eq("config_networkSupportedKeepaliveCount"),
- eq("array"), any());
- doReturn(com.android.connectivity.resources.R.array.network_switch_type_name)
- .when(mResources).getIdentifier(eq("network_switch_type_name"),
- eq("array"), any());
-
+ R.array.config_networkSupportedKeepaliveCount);
+ doReturn(new String[0]).when(mResources).getStringArray(
+ R.array.config_networkNotifySwitches);
+ doReturn(new int[]{10, 11, 12, 14, 15}).when(mResources).getIntArray(
+ R.array.config_protectedNetworks);
// We don't test the actual notification value strings, so just return an empty array.
// It doesn't matter what the values are as long as it's not null.
doReturn(new String[0]).when(mResources).getStringArray(R.array.network_switch_type_name);
+ doReturn(R.array.config_networkSupportedKeepaliveCount).when(mResources)
+ .getIdentifier(eq("config_networkSupportedKeepaliveCount"), eq("array"), any());
+ doReturn(R.array.network_switch_type_name).when(mResources)
+ .getIdentifier(eq("network_switch_type_name"), eq("array"), any());
+
+
final ConnectivityResources connRes = mock(ConnectivityResources.class);
doReturn(mResources).when(connRes).get();
doReturn(connRes).when(deps).getResources(any());
@@ -10246,12 +10247,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 +10276,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 +10753,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());
}
}
@@ -12310,12 +12315,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
@@ -12324,17 +12329,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();
}
@@ -12369,4 +12374,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/connectivity/LingerMonitorTest.java b/tests/net/java/com/android/server/connectivity/LingerMonitorTest.java
index 9ab60a4..116d755 100644
--- a/tests/net/java/com/android/server/connectivity/LingerMonitorTest.java
+++ b/tests/net/java/com/android/server/connectivity/LingerMonitorTest.java
@@ -32,6 +32,7 @@
import android.content.Context;
import android.content.res.Resources;
import android.net.ConnectivityManager;
+import android.net.ConnectivityResources;
import android.net.IDnsResolver;
import android.net.INetd;
import android.net.LinkProperties;
@@ -47,10 +48,11 @@
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
-import com.android.internal.R;
+import com.android.connectivity.resources.R;
import com.android.server.ConnectivityService;
import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
+import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -84,10 +86,16 @@
MockitoAnnotations.initMocks(this);
when(mCtx.getResources()).thenReturn(mResources);
when(mCtx.getPackageName()).thenReturn("com.android.server.connectivity");
+ ConnectivityResources.setResourcesContextForTest(mCtx);
mMonitor = new TestableLingerMonitor(mCtx, mNotifier, HIGH_DAILY_LIMIT, HIGH_RATE_LIMIT);
}
+ @After
+ public void tearDown() {
+ ConnectivityResources.setResourcesContextForTest(null);
+ }
+
@Test
public void testTransitions() {
setNotificationSwitch(transition(WIFI, CELLULAR));
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);