Merge "Filter ifaces for uid operations value before combine"
diff --git a/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java b/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
index 74ba209..ebc9d26 100644
--- a/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
+++ b/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
@@ -1473,6 +1473,15 @@
// to Objects.hash() to avoid autoboxing overhead.
return Objects.hash(upstreamIfindex, downstreamIfindex, address, srcMac, dstMac);
}
+
+ @Override
+ public String toString() {
+ return "upstreamIfindex: " + upstreamIfindex
+ + ", downstreamIfindex: " + downstreamIfindex
+ + ", address: " + address.getHostAddress()
+ + ", srcMac: " + srcMac
+ + ", dstMac: " + dstMac;
+ }
}
/** Tethering client information class. */
diff --git a/Tethering/src/com/android/networkstack/tethering/metrics/TetheringMetrics.java b/Tethering/src/com/android/networkstack/tethering/metrics/TetheringMetrics.java
index d8e631e..2c6054d 100644
--- a/Tethering/src/com/android/networkstack/tethering/metrics/TetheringMetrics.java
+++ b/Tethering/src/com/android/networkstack/tethering/metrics/TetheringMetrics.java
@@ -75,6 +75,8 @@
.setUserType(userTypeToEnum(callerPkg))
.setUpstreamType(UpstreamType.UT_UNKNOWN)
.setErrorCode(ErrorCode.EC_NO_ERROR)
+ .setUpstreamEvents(UpstreamEvents.newBuilder())
+ .setDurationMillis(0)
.build();
mBuilderMap.put(downstreamType, statsBuilder);
}
@@ -110,7 +112,8 @@
reported.getErrorCode().getNumber(),
reported.getDownstreamType().getNumber(),
reported.getUpstreamType().getNumber(),
- reported.getUserType().getNumber());
+ reported.getUserType().getNumber(),
+ null, 0);
if (DBG) {
Log.d(TAG, "Write errorCode: " + reported.getErrorCode().getNumber()
+ ", downstreamType: " + reported.getDownstreamType().getNumber()
diff --git a/Tethering/src/com/android/networkstack/tethering/metrics/stats.proto b/Tethering/src/com/android/networkstack/tethering/metrics/stats.proto
index 46a47af..27f2126 100644
--- a/Tethering/src/com/android/networkstack/tethering/metrics/stats.proto
+++ b/Tethering/src/com/android/networkstack/tethering/metrics/stats.proto
@@ -21,12 +21,38 @@
import "frameworks/proto_logging/stats/enums/stats/connectivity/tethering.proto";
+// Logs each upstream for a successful switch over
+message UpstreamEvent {
+ // Transport type of upstream network
+ optional .android.stats.connectivity.UpstreamType upstream_type = 1;
+
+ // A time period that an upstream continued
+ optional int64 duration_millis = 2;
+}
+
+message UpstreamEvents {
+ repeated UpstreamEvent upstream_event = 1;
+}
+
/**
* Logs Tethering events
*/
message NetworkTetheringReported {
- optional .android.stats.connectivity.ErrorCode error_code = 1;
- optional .android.stats.connectivity.DownstreamType downstream_type = 2;
- optional .android.stats.connectivity.UpstreamType upstream_type = 3;
- optional .android.stats.connectivity.UserType user_type = 4;
+ // Tethering error code
+ optional .android.stats.connectivity.ErrorCode error_code = 1;
+
+ // Tethering downstream type
+ optional .android.stats.connectivity.DownstreamType downstream_type = 2;
+
+ // Transport type of upstream network
+ optional .android.stats.connectivity.UpstreamType upstream_type = 3 [deprecated = true];
+
+ // The user type of switching tethering
+ optional .android.stats.connectivity.UserType user_type = 4;
+
+ // Log each transport type of upstream network event
+ optional UpstreamEvents upstream_events = 5;
+
+ // A time period that a downstreams exists
+ optional int64 duration_millis = 6;
}
diff --git a/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java b/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java
index ac92b43..bbca565 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java
@@ -2092,4 +2092,11 @@
assertNull(mBpfUpstream4Map.getValue(upstream4KeyB));
assertNull(mBpfDownstream4Map.getValue(downstream4KeyB));
}
+
+ @Test
+ public void testIpv6ForwardingRuleToString() throws Exception {
+ final Ipv6ForwardingRule rule = buildTestForwardingRule(UPSTREAM_IFINDEX, NEIGH_A, MAC_A);
+ assertEquals("upstreamIfindex: 1001, downstreamIfindex: 1003, address: 2001:db8::1, "
+ + "srcMac: 12:34:56:78:90:ab, dstMac: 00:00:00:00:00:0a", rule.toString());
+ }
}
diff --git a/Tethering/tests/unit/src/com/android/networkstack/tethering/metrics/TetheringMetricsTest.java b/Tethering/tests/unit/src/com/android/networkstack/tethering/metrics/TetheringMetricsTest.java
index 6a85718..7fdde97 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/metrics/TetheringMetricsTest.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/metrics/TetheringMetricsTest.java
@@ -88,6 +88,8 @@
.setUserType(user)
.setUpstreamType(UpstreamType.UT_UNKNOWN)
.setErrorCode(error)
+ .setUpstreamEvents(UpstreamEvents.newBuilder())
+ .setDurationMillis(0)
.build();
verify(mTetheringMetrics).write(expectedReport);
}
diff --git a/framework-t/src/android/net/NetworkIdentity.java b/framework-t/src/android/net/NetworkIdentity.java
index 350ed86..48e5092 100644
--- a/framework-t/src/android/net/NetworkIdentity.java
+++ b/framework-t/src/android/net/NetworkIdentity.java
@@ -34,8 +34,8 @@
import android.telephony.TelephonyManager;
import android.util.proto.ProtoOutputStream;
+import com.android.net.module.util.BitUtils;
import com.android.net.module.util.CollectionUtils;
-import com.android.net.module.util.NetworkCapabilitiesUtils;
import com.android.net.module.util.NetworkIdentityUtils;
import java.lang.annotation.Retention;
@@ -172,7 +172,7 @@
if (oemManaged == OEM_NONE) {
return "OEM_NONE";
}
- final int[] bitPositions = NetworkCapabilitiesUtils.unpackBits(oemManaged);
+ final int[] bitPositions = BitUtils.unpackBits(oemManaged);
final ArrayList<String> oemManagedNames = new ArrayList<String>();
for (int position : bitPositions) {
oemManagedNames.add(nameOfOemManaged(1 << position));
diff --git a/framework/src/android/net/NetworkCapabilities.java b/framework/src/android/net/NetworkCapabilities.java
index d0cbbe5..e07601f 100644
--- a/framework/src/android/net/NetworkCapabilities.java
+++ b/framework/src/android/net/NetworkCapabilities.java
@@ -17,6 +17,7 @@
package android.net;
import static com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE;
+import static com.android.net.module.util.BitUtils.appendStringRepresentationOfBitMaskToStringBuilder;
import android.annotation.IntDef;
import android.annotation.LongDef;
@@ -36,6 +37,7 @@
import android.util.Range;
import com.android.internal.annotations.VisibleForTesting;
+import com.android.net.module.util.BitUtils;
import com.android.net.module.util.CollectionUtils;
import com.android.net.module.util.NetworkCapabilitiesUtils;
@@ -217,7 +219,7 @@
if (hasCapability(NET_CAPABILITY_ENTERPRISE) && mEnterpriseId == 0) {
return new int[]{NET_ENTERPRISE_ID_1};
}
- return NetworkCapabilitiesUtils.unpackBits(mEnterpriseId);
+ return BitUtils.unpackBits(mEnterpriseId);
}
/**
@@ -643,7 +645,7 @@
* Network capabilities that are expected to be mutable, i.e., can change while a particular
* network is connected.
*/
- private static final long MUTABLE_CAPABILITIES = NetworkCapabilitiesUtils.packBitList(
+ private static final long MUTABLE_CAPABILITIES = BitUtils.packBitList(
// TRUSTED can change when user explicitly connects to an untrusted network in Settings.
// http://b/18206275
NET_CAPABILITY_TRUSTED,
@@ -678,7 +680,7 @@
/**
* Capabilities that are set by default when the object is constructed.
*/
- private static final long DEFAULT_CAPABILITIES = NetworkCapabilitiesUtils.packBitList(
+ private static final long DEFAULT_CAPABILITIES = BitUtils.packBitList(
NET_CAPABILITY_NOT_RESTRICTED,
NET_CAPABILITY_TRUSTED,
NET_CAPABILITY_NOT_VPN);
@@ -687,7 +689,7 @@
* Capabilities that are managed by ConnectivityService.
*/
private static final long CONNECTIVITY_MANAGED_CAPABILITIES =
- NetworkCapabilitiesUtils.packBitList(
+ BitUtils.packBitList(
NET_CAPABILITY_VALIDATED,
NET_CAPABILITY_CAPTIVE_PORTAL,
NET_CAPABILITY_FOREGROUND,
@@ -700,7 +702,7 @@
* INTERNET, IMS, SUPL, etc.
*/
private static final long TEST_NETWORKS_ALLOWED_CAPABILITIES =
- NetworkCapabilitiesUtils.packBitList(
+ BitUtils.packBitList(
NET_CAPABILITY_NOT_METERED,
NET_CAPABILITY_TEMPORARILY_NOT_METERED,
NET_CAPABILITY_NOT_RESTRICTED,
@@ -800,7 +802,7 @@
* @return an array of capability values for this instance.
*/
public @NonNull @NetCapability int[] getCapabilities() {
- return NetworkCapabilitiesUtils.unpackBits(mNetworkCapabilities);
+ return BitUtils.unpackBits(mNetworkCapabilities);
}
/**
@@ -810,7 +812,7 @@
* @hide
*/
public @NetCapability int[] getForbiddenCapabilities() {
- return NetworkCapabilitiesUtils.unpackBits(mForbiddenNetworkCapabilities);
+ return BitUtils.unpackBits(mForbiddenNetworkCapabilities);
}
@@ -822,8 +824,8 @@
*/
public void setCapabilities(@NetCapability int[] capabilities,
@NetCapability int[] forbiddenCapabilities) {
- mNetworkCapabilities = NetworkCapabilitiesUtils.packBits(capabilities);
- mForbiddenNetworkCapabilities = NetworkCapabilitiesUtils.packBits(forbiddenCapabilities);
+ mNetworkCapabilities = BitUtils.packBits(capabilities);
+ mForbiddenNetworkCapabilities = BitUtils.packBits(forbiddenCapabilities);
}
/**
@@ -960,7 +962,7 @@
& NON_REQUESTABLE_CAPABILITIES;
if (nonRequestable != 0) {
- return capabilityNameOf(NetworkCapabilitiesUtils.unpackBits(nonRequestable)[0]);
+ return capabilityNameOf(BitUtils.unpackBits(nonRequestable)[0]);
}
if (mLinkUpBandwidthKbps != 0 || mLinkDownBandwidthKbps != 0) return "link bandwidth";
if (hasSignalStrength()) return "signalStrength";
@@ -1193,7 +1195,7 @@
* Allowed transports on an unrestricted test network (in addition to TRANSPORT_TEST).
*/
private static final long UNRESTRICTED_TEST_NETWORKS_ALLOWED_TRANSPORTS =
- NetworkCapabilitiesUtils.packBitList(
+ BitUtils.packBitList(
TRANSPORT_TEST,
// Test eth networks are created with EthernetManager#setIncludeTestInterfaces
TRANSPORT_ETHERNET,
@@ -1258,7 +1260,7 @@
*/
@SystemApi
@NonNull public @Transport int[] getTransportTypes() {
- return NetworkCapabilitiesUtils.unpackBits(mTransportTypes);
+ return BitUtils.unpackBits(mTransportTypes);
}
/**
@@ -1268,7 +1270,7 @@
* @hide
*/
public void setTransportTypes(@Transport int[] transportTypes) {
- mTransportTypes = NetworkCapabilitiesUtils.packBits(transportTypes);
+ mTransportTypes = BitUtils.packBits(transportTypes);
}
/**
@@ -2041,9 +2043,9 @@
long oldImmutableCapabilities = this.mNetworkCapabilities & mask;
long newImmutableCapabilities = that.mNetworkCapabilities & mask;
if (oldImmutableCapabilities != newImmutableCapabilities) {
- String before = capabilityNamesOf(NetworkCapabilitiesUtils.unpackBits(
+ String before = capabilityNamesOf(BitUtils.unpackBits(
oldImmutableCapabilities));
- String after = capabilityNamesOf(NetworkCapabilitiesUtils.unpackBits(
+ String after = capabilityNamesOf(BitUtils.unpackBits(
newImmutableCapabilities));
joiner.add(String.format("immutable capabilities changed: %s -> %s", before, after));
}
@@ -2064,6 +2066,36 @@
}
/**
+ * Returns a short but human-readable string of updates from an older set of capabilities.
+ * @param old the old capabilities to diff from
+ * @return a string fit for logging differences, or null if no differences.
+ * this never returns the empty string.
+ * @hide
+ */
+ @Nullable
+ public String describeCapsDifferencesFrom(@Nullable final NetworkCapabilities old) {
+ final long oldCaps = null == old ? 0 : old.mNetworkCapabilities;
+ final long changed = oldCaps ^ mNetworkCapabilities;
+ if (0 == changed) return null;
+ // If the control reaches here, there are changes (additions, removals, or both) so
+ // the code below is guaranteed to add something to the string and can't return "".
+ final long removed = oldCaps & changed;
+ final long added = mNetworkCapabilities & changed;
+ final StringBuilder sb = new StringBuilder();
+ if (0 != removed) {
+ sb.append("-");
+ appendStringRepresentationOfBitMaskToStringBuilder(sb, removed,
+ NetworkCapabilities::capabilityNameOf, "-");
+ }
+ if (0 != added) {
+ sb.append("+");
+ appendStringRepresentationOfBitMaskToStringBuilder(sb, added,
+ NetworkCapabilities::capabilityNameOf, "+");
+ }
+ return sb.toString();
+ }
+
+ /**
* Checks that our requestable capabilities are the same as those of the given
* {@code NetworkCapabilities}.
*
@@ -2313,32 +2345,6 @@
return sb.toString();
}
-
- private interface NameOf {
- String nameOf(int value);
- }
-
- /**
- * @hide
- */
- public static void appendStringRepresentationOfBitMaskToStringBuilder(@NonNull StringBuilder sb,
- long bitMask, @NonNull NameOf nameFetcher, @NonNull String separator) {
- int bitPos = 0;
- boolean firstElementAdded = false;
- while (bitMask != 0) {
- if ((bitMask & 1) != 0) {
- if (firstElementAdded) {
- sb.append(separator);
- } else {
- firstElementAdded = true;
- }
- sb.append(nameFetcher.nameOf(bitPos));
- }
- bitMask >>= 1;
- ++bitPos;
- }
- }
-
/**
* @hide
*/
diff --git a/service/native/TrafficController.cpp b/service/native/TrafficController.cpp
index fc76ae5..8f6df21 100644
--- a/service/native/TrafficController.cpp
+++ b/service/native/TrafficController.cpp
@@ -595,7 +595,7 @@
}
}
-void TrafficController::dump(int fd, bool verbose) {
+void TrafficController::dump(int fd, bool verbose __unused) {
std::lock_guard guard(mMutex);
DumpWriter dw(fd);
@@ -623,31 +623,6 @@
getMapStatus(mConfigurationMap.getMap(), CONFIGURATION_MAP_PATH).c_str());
dw.println("mUidOwnerMap status: %s",
getMapStatus(mUidOwnerMap.getMap(), UID_OWNER_MAP_PATH).c_str());
-
- if (!verbose) {
- return;
- }
-
- dw.blankline();
- dw.println("BPF map content:");
-
- ScopedIndent indentForMapContent(dw);
-
- // Print CookieTagMap content.
- // TagSocketTest in CTS was using the output of mCookieTagMap dump.
- // So, mCookieTagMap dump can not be removed until the previous CTS support period is over.
- dumpBpfMap("mCookieTagMap", dw, "");
- const auto printCookieTagInfo = [&dw](const uint64_t& key, const UidTagValue& value,
- const BpfMap<uint64_t, UidTagValue>&) {
- dw.println("cookie=%" PRIu64 " tag=0x%x uid=%u", key, value.tag, value.uid);
- return base::Result<void>();
- };
- base::Result<void> res = mCookieTagMap.iterateWithValue(printCookieTagInfo);
- if (!res.ok()) {
- dw.println("mCookieTagMap print end with error: %s", res.error().message().c_str());
- }
-
- dw.blankline();
}
} // namespace net
diff --git a/service/native/TrafficControllerTest.cpp b/service/native/TrafficControllerTest.cpp
index 6cb0940..57f32af 100644
--- a/service/native/TrafficControllerTest.cpp
+++ b/service/native/TrafficControllerTest.cpp
@@ -59,7 +59,6 @@
constexpr uid_t TEST_UID3 = 98765;
constexpr uint32_t TEST_TAG = 42;
constexpr uint32_t TEST_COUNTERSET = 1;
-constexpr int TEST_COOKIE = 1;
constexpr int TEST_IFINDEX = 999;
constexpr int RXPACKETS = 1;
constexpr int RXBYTES = 100;
@@ -769,46 +768,6 @@
expectPrivilegedUserSetEmpty();
}
-TEST_F(TrafficControllerTest, TestDumpsys) {
- StatsKey tagStatsMapKey;
- populateFakeStats(TEST_COOKIE, TEST_UID, TEST_TAG, &tagStatsMapKey);
- populateFakeCounterSet(TEST_UID3, TEST_COUNTERSET);
-
- // Expect: (part of this depends on hard-code values in populateFakeStats())
- //
- // mCookieTagMap:
- // cookie=1 tag=0x2a uid=10086
- //
- // mUidCounterSetMap:
- // 98765 1
- //
- // mAppUidStatsMap::
- // uid rxBytes rxPackets txBytes txPackets
- // 10086 100 1 0 0
- //
- // mStatsMapA:
- // ifaceIndex ifaceName tag_hex uid_int cnt_set rxBytes rxPackets txBytes txPackets
- // 999 test0 0x2a 10086 1 100 1 0 0
- std::vector<std::string> expectedLines = {
- "mCookieTagMap:",
- fmt::format("cookie={} tag={:#x} uid={}", TEST_COOKIE, TEST_TAG, TEST_UID)};
-
- EXPECT_TRUE(expectDumpsysContains(expectedLines));
-}
-
-TEST_F(TrafficControllerTest, dumpsysInvalidMaps) {
- makeTrafficControllerMapsInvalid();
-
- const std::string kErrIterate = "print end with error: Get firstKey map -1 failed: "
- "Bad file descriptor";
- const std::string kErrReadRulesConfig = "read ownerMatch configure failed with error: "
- "Read value of map -1 failed: Bad file descriptor";
-
- std::vector<std::string> expectedLines = {
- fmt::format("mCookieTagMap {}", kErrIterate)};
- EXPECT_TRUE(expectDumpsysContains(expectedLines));
-}
-
TEST_F(TrafficControllerTest, getFirewallType) {
static const struct TestConfig {
ChildChain childChain;
diff --git a/service/src/com/android/server/BpfNetMaps.java b/service/src/com/android/server/BpfNetMaps.java
index d560747..aea2103 100644
--- a/service/src/com/android/server/BpfNetMaps.java
+++ b/service/src/com/android/server/BpfNetMaps.java
@@ -1022,11 +1022,25 @@
}
mDeps.nativeDump(fd, verbose);
+ pw.println();
+ pw.println("sEnableJavaBpfMap: " + sEnableJavaBpfMap);
if (verbose) {
+ pw.println();
+ pw.println("BPF map content:");
+ pw.increaseIndent();
+
dumpOwnerMatchConfig(pw);
dumpCurrentStatsMapConfig(pw);
pw.println();
+ // TODO: Remove CookieTagMap content dump
+ // NetworkStatsService also dumps CookieTagMap and NetworkStatsService is a right place
+ // to dump CookieTagMap. But the TagSocketTest in CTS depends on this dump so the tests
+ // need to be updated before remove the dump from BpfNetMaps.
+ BpfDump.dumpMap(sCookieTagMap, pw, "sCookieTagMap",
+ (key, value) -> "cookie=" + key.socketCookie
+ + " tag=0x" + Long.toHexString(value.tag)
+ + " uid=" + value.uid);
BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
(uid, match) -> {
if ((match.rule & IIF_MATCH) != 0) {
@@ -1038,6 +1052,7 @@
});
BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
(uid, permission) -> uid.val + " " + permissionToString(permission.val));
+ pw.decreaseIndent();
}
}
diff --git a/service/src/com/android/server/ConnectivityService.java b/service/src/com/android/server/ConnectivityService.java
index f8b47d2..e732001 100755
--- a/service/src/com/android/server/ConnectivityService.java
+++ b/service/src/com/android/server/ConnectivityService.java
@@ -249,13 +249,13 @@
import com.android.modules.utils.BasicShellCommandHandler;
import com.android.modules.utils.build.SdkLevel;
import com.android.net.module.util.BaseNetdUnsolicitedEventListener;
+import com.android.net.module.util.BitUtils;
import com.android.net.module.util.CollectionUtils;
import com.android.net.module.util.DeviceConfigUtils;
import com.android.net.module.util.InterfaceParams;
import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
import com.android.net.module.util.LocationPermissionChecker;
-import com.android.net.module.util.NetworkCapabilitiesUtils;
import com.android.net.module.util.PerUidCounter;
import com.android.net.module.util.PermissionUtils;
import com.android.net.module.util.TcUtils;
@@ -7843,7 +7843,7 @@
@NonNull NetworkCapabilities agentCaps, @NonNull NetworkCapabilities newNc) {
underlyingNetworks = underlyingNetworksOrDefault(
agentCaps.getOwnerUid(), underlyingNetworks);
- long transportTypes = NetworkCapabilitiesUtils.packBits(agentCaps.getTransportTypes());
+ long transportTypes = BitUtils.packBits(agentCaps.getTransportTypes());
int downKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
int upKbps = NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
// metered if any underlying is metered, or originally declared metered by the agent.
@@ -7896,7 +7896,7 @@
suspended = false;
}
- newNc.setTransportTypes(NetworkCapabilitiesUtils.unpackBits(transportTypes));
+ newNc.setTransportTypes(BitUtils.unpackBits(transportTypes));
newNc.setLinkDownstreamBandwidthKbps(downKbps);
newNc.setLinkUpstreamBandwidthKbps(upKbps);
newNc.setCapability(NET_CAPABILITY_NOT_METERED, !metered);
@@ -8008,6 +8008,10 @@
@NonNull final NetworkCapabilities nc) {
NetworkCapabilities newNc = mixInCapabilities(nai, nc);
if (Objects.equals(nai.networkCapabilities, newNc)) return;
+ final String differences = newNc.describeCapsDifferencesFrom(nai.networkCapabilities);
+ if (null != differences) {
+ Log.i(TAG, "Update capabilities for net " + nai.network + " : " + differences);
+ }
updateNetworkPermissions(nai, newNc);
final NetworkCapabilities prevNc = nai.getAndSetNetworkCapabilities(newNc);
diff --git a/service/src/com/android/server/connectivity/FullScore.java b/service/src/com/android/server/connectivity/FullScore.java
index aec4a71..2303894 100644
--- a/service/src/com/android/server/connectivity/FullScore.java
+++ b/service/src/com/android/server/connectivity/FullScore.java
@@ -23,7 +23,10 @@
import static android.net.NetworkScore.KEEP_CONNECTED_NONE;
import static android.net.NetworkScore.POLICY_YIELD_TO_BAD_WIFI;
+import static com.android.net.module.util.BitUtils.appendStringRepresentationOfBitMaskToStringBuilder;
+
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.net.NetworkAgentConfig;
import android.net.NetworkCapabilities;
import android.net.NetworkScore;
@@ -333,6 +336,35 @@
+ 5 * mKeepConnectedReason;
}
+ /**
+ * Returns a short but human-readable string of updates from an older score.
+ * @param old the old capabilities to diff from
+ * @return a string fit for logging differences, or null if no differences.
+ * this method cannot return the empty string.
+ */
+ @Nullable
+ public String describeDifferencesFrom(@Nullable final FullScore old) {
+ final long oldPolicies = null == old ? 0 : old.mPolicies;
+ final long changed = oldPolicies ^ mPolicies;
+ if (0 == changed) return null;
+ // If the control reaches here, there are changes (additions, removals, or both) so
+ // the code below is guaranteed to add something to the string and can't return "".
+ final long removed = oldPolicies & changed;
+ final long added = mPolicies & changed;
+ final StringBuilder sb = new StringBuilder();
+ if (0 != removed) {
+ sb.append("-");
+ appendStringRepresentationOfBitMaskToStringBuilder(sb, removed,
+ FullScore::policyNameOf, "-");
+ }
+ if (0 != added) {
+ sb.append("+");
+ appendStringRepresentationOfBitMaskToStringBuilder(sb, added,
+ FullScore::policyNameOf, "+");
+ }
+ return sb.toString();
+ }
+
// Example output :
// Score(Policies : EVER_USER_SELECTED&IS_VALIDATED ; KeepConnected : )
@Override
diff --git a/service/src/com/android/server/connectivity/NetworkAgentInfo.java b/service/src/com/android/server/connectivity/NetworkAgentInfo.java
index 2e92d43..85282cb 100644
--- a/service/src/com/android/server/connectivity/NetworkAgentInfo.java
+++ b/service/src/com/android/server/connectivity/NetworkAgentInfo.java
@@ -1003,9 +1003,7 @@
@NonNull final NetworkCapabilities nc) {
final NetworkCapabilities oldNc = networkCapabilities;
networkCapabilities = nc;
- mScore = mScore.mixInScore(networkCapabilities, networkAgentConfig, everValidated(),
- 0L != getAvoidUnvalidated(), yieldToBadWiFi(),
- 0L != mFirstEvaluationConcludedTime, isDestroyed());
+ updateScoreForNetworkAgentUpdate();
final NetworkMonitorManager nm = mNetworkMonitor;
if (nm != null) {
nm.notifyNetworkCapabilitiesChanged(nc);
@@ -1207,9 +1205,11 @@
* Mix-in the ConnectivityService-managed bits in the score.
*/
public void setScore(final NetworkScore score) {
+ final FullScore oldScore = mScore;
mScore = FullScore.fromNetworkScore(score, networkCapabilities, networkAgentConfig,
everValidated(), 0L != getAvoidUnvalidated(), yieldToBadWiFi(),
0L != mFirstEvaluationConcludedTime, isDestroyed());
+ maybeLogDifferences(oldScore);
}
/**
@@ -1218,9 +1218,22 @@
* Call this after changing any data that might affect the score (e.g., agent config).
*/
public void updateScoreForNetworkAgentUpdate() {
+ final FullScore oldScore = mScore;
mScore = mScore.mixInScore(networkCapabilities, networkAgentConfig,
everValidated(), 0L != getAvoidUnvalidated(), yieldToBadWiFi(),
0L != mFirstEvaluationConcludedTime, isDestroyed());
+ maybeLogDifferences(oldScore);
+ }
+
+ /**
+ * Prints score differences to logcat, if any.
+ * @param oldScore the old score. Differences from |oldScore| to |this| are logged, if any.
+ */
+ public void maybeLogDifferences(final FullScore oldScore) {
+ final String differences = mScore.describeDifferencesFrom(oldScore);
+ if (null != differences) {
+ Log.i(TAG, "Update score for net " + network + " : " + differences);
+ }
}
/**
diff --git a/tests/common/java/android/net/NetworkCapabilitiesTest.java b/tests/common/java/android/net/NetworkCapabilitiesTest.java
index c30e1d3..7b374d2 100644
--- a/tests/common/java/android/net/NetworkCapabilitiesTest.java
+++ b/tests/common/java/android/net/NetworkCapabilitiesTest.java
@@ -36,6 +36,7 @@
import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
import static android.net.NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH;
import static android.net.NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY;
+import static android.net.NetworkCapabilities.NET_CAPABILITY_SUPL;
import static android.net.NetworkCapabilities.NET_CAPABILITY_TRUSTED;
import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
import static android.net.NetworkCapabilities.NET_CAPABILITY_WIFI_P2P;
@@ -1370,4 +1371,23 @@
assertEquals(expectedNcBuilder.build(), restrictedNc);
}
+
+ @Test
+ public void testDescribeCapsDifferences() throws Exception {
+ final NetworkCapabilities nc1 = new NetworkCapabilities.Builder()
+ .addCapability(NET_CAPABILITY_MMS)
+ .addCapability(NET_CAPABILITY_OEM_PAID)
+ .addCapability(NET_CAPABILITY_INTERNET)
+ .build();
+ final NetworkCapabilities nc2 = new NetworkCapabilities.Builder()
+ .addCapability(NET_CAPABILITY_CAPTIVE_PORTAL)
+ .addCapability(NET_CAPABILITY_SUPL)
+ .addCapability(NET_CAPABILITY_VALIDATED)
+ .addCapability(NET_CAPABILITY_INTERNET)
+ .build();
+ assertEquals("-MMS-OEM_PAID+SUPL+VALIDATED+CAPTIVE_PORTAL",
+ nc2.describeCapsDifferencesFrom(nc1));
+ assertEquals("-SUPL-VALIDATED-CAPTIVE_PORTAL+MMS+OEM_PAID",
+ nc1.describeCapsDifferencesFrom(nc2));
+ }
}
diff --git a/tests/common/java/android/net/metrics/IpConnectivityLogTest.java b/tests/common/java/android/net/metrics/IpConnectivityLogTest.java
index 93cf748..b6e9b95 100644
--- a/tests/common/java/android/net/metrics/IpConnectivityLogTest.java
+++ b/tests/common/java/android/net/metrics/IpConnectivityLogTest.java
@@ -19,7 +19,7 @@
import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
-import static com.android.net.module.util.NetworkCapabilitiesUtils.unpackBits;
+import static com.android.net.module.util.BitUtils.unpackBits;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
diff --git a/tests/cts/net/src/android/net/cts/EthernetManagerTest.kt b/tests/cts/net/src/android/net/cts/EthernetManagerTest.kt
index 122eb15..776e49f 100644
--- a/tests/cts/net/src/android/net/cts/EthernetManagerTest.kt
+++ b/tests/cts/net/src/android/net/cts/EthernetManagerTest.kt
@@ -103,7 +103,10 @@
import kotlin.test.fail
private const val TAG = "EthernetManagerTest"
-private const val TIMEOUT_MS = 2000L
+// This timeout does not affect the test duration for passing tests. It needs to be long enough to
+// account for RS delay (and potentially the first retry interval (4s)). There have been failures
+// where the interface did not gain provisioning within the allotted timeout.
+private const val TIMEOUT_MS = 10_000L
// Timeout used to confirm no callbacks matching given criteria are received. Must be long enough to
// process all callbacks including ip provisioning when using the updateConfiguration API.
// Note that increasing this timeout increases the test duration.
@@ -303,8 +306,8 @@
available.completeExceptionally(IllegalStateException("onUnavailable was called"))
}
- fun expectOnAvailable(): String {
- return available.get(TIMEOUT_MS, TimeUnit.MILLISECONDS)
+ fun expectOnAvailable(timeout: Long = TIMEOUT_MS): String {
+ return available.get(timeout, TimeUnit.MILLISECONDS)
}
fun expectOnUnavailable() {
@@ -447,14 +450,18 @@
}
private fun requestNetwork(request: NetworkRequest): TestableNetworkCallback {
- return TestableNetworkCallback().also {
+ return TestableNetworkCallback(
+ timeoutMs = TIMEOUT_MS,
+ noCallbackTimeoutMs = NO_CALLBACK_TIMEOUT_MS).also {
cm.requestNetwork(request, it)
registeredCallbacks.add(it)
}
}
private fun registerNetworkListener(request: NetworkRequest): TestableNetworkCallback {
- return TestableNetworkCallback().also {
+ return TestableNetworkCallback(
+ timeoutMs = TIMEOUT_MS,
+ noCallbackTimeoutMs = NO_CALLBACK_TIMEOUT_MS).also {
cm.registerNetworkCallback(request, it)
registeredCallbacks.add(it)
}
@@ -523,18 +530,18 @@
// It can take multiple seconds for the network to become available.
private fun TestableNetworkCallback.expectAvailable() =
- expectCallback<Available>(anyNetwork(), 5000 /* ms timeout */).network
+ expectCallback<Available>().network
private fun TestableNetworkCallback.expectLost(n: Network = anyNetwork()) =
- expectCallback<Lost>(n, 5000 /* ms timeout */)
+ expectCallback<Lost>(n)
// b/233534110: eventuallyExpect<Lost>() does not advance ReadHead, use
// eventuallyExpect(Lost::class) instead.
private fun TestableNetworkCallback.eventuallyExpectLost(n: Network? = null) =
- eventuallyExpect(Lost::class, TIMEOUT_MS) { n?.equals(it.network) ?: true }
+ eventuallyExpect(Lost::class) { n?.equals(it.network) ?: true }
private fun TestableNetworkCallback.assertNeverLost(n: Network? = null) =
- assertNoCallbackThat(NO_CALLBACK_TIMEOUT_MS) {
+ assertNoCallbackThat() {
it is Lost && (n?.equals(it.network) ?: true)
}
@@ -548,7 +555,7 @@
private fun TestableNetworkCallback.eventuallyExpectCapabilities(nc: NetworkCapabilities) {
// b/233534110: eventuallyExpect<CapabilitiesChanged>() does not advance ReadHead.
- eventuallyExpect(CapabilitiesChanged::class, TIMEOUT_MS) {
+ eventuallyExpect(CapabilitiesChanged::class) {
// CS may mix in additional capabilities, so NetworkCapabilities#equals cannot be used.
// Check if all expected capabilities are present instead.
it is CapabilitiesChanged && nc.capabilities.all { c -> it.caps.hasCapability(c) }
@@ -559,7 +566,7 @@
config: StaticIpConfiguration
) {
// b/233534110: eventuallyExpect<LinkPropertiesChanged>() does not advance ReadHead.
- eventuallyExpect(LinkPropertiesChanged::class, TIMEOUT_MS) {
+ eventuallyExpect(LinkPropertiesChanged::class) {
it is LinkPropertiesChanged && it.lp.linkAddresses.any { la ->
la.isSameAddressAs(config.ipAddress)
}
@@ -623,7 +630,7 @@
// see aosp/2123900.
try {
// assumeException does not exist.
- requestTetheredInterface().expectOnAvailable()
+ requestTetheredInterface().expectOnAvailable(NO_CALLBACK_TIMEOUT_MS)
// interface used for tethering is available, throw an assumption error.
assumeTrue(false)
} catch (e: TimeoutException) {
@@ -836,7 +843,7 @@
val iface = createInterface()
val cb = requestNetwork(ETH_REQUEST)
// b/233534110: eventuallyExpect<LinkPropertiesChanged>() does not advance ReadHead
- cb.eventuallyExpect(LinkPropertiesChanged::class, TIMEOUT_MS) {
+ cb.eventuallyExpect(LinkPropertiesChanged::class) {
it is LinkPropertiesChanged && it.lp.addresses.any {
address -> iface.onLinkPrefix.contains(address)
}
diff --git a/tests/unit/java/android/app/usage/NetworkStatsManagerTest.java b/tests/unit/java/android/app/usage/NetworkStatsManagerTest.java
index 8a537be..679427a 100644
--- a/tests/unit/java/android/app/usage/NetworkStatsManagerTest.java
+++ b/tests/unit/java/android/app/usage/NetworkStatsManagerTest.java
@@ -16,7 +16,16 @@
package android.app.usage;
+import static android.net.ConnectivityManager.TYPE_MOBILE;
+import static android.net.ConnectivityManager.TYPE_WIFI;
+import static android.net.NetworkStats.DEFAULT_NETWORK_NO;
+import static android.net.NetworkStats.METERED_NO;
import static android.net.NetworkStats.METERED_YES;
+import static android.net.NetworkStats.ROAMING_NO;
+import static android.net.NetworkStats.SET_ALL;
+import static android.net.NetworkStats.SET_DEFAULT;
+import static android.net.NetworkStats.TAG_NONE;
+import static android.net.NetworkStatsHistory.FIELD_ALL;
import static android.net.NetworkTemplate.MATCH_MOBILE;
import static android.net.NetworkTemplate.MATCH_WIFI;
@@ -34,7 +43,6 @@
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
-import android.net.ConnectivityManager;
import android.net.INetworkStatsService;
import android.net.INetworkStatsSession;
import android.net.NetworkStats.Entry;
@@ -86,31 +94,17 @@
final int uid2 = 10002;
final int uid3 = 10003;
- Entry uid1Entry1 = new Entry("if1", uid1,
- android.net.NetworkStats.SET_DEFAULT, android.net.NetworkStats.TAG_NONE,
- android.net.NetworkStats.METERED_NO, android.net.NetworkStats.ROAMING_NO,
- android.net.NetworkStats.DEFAULT_NETWORK_NO,
- 100, 10, 200, 20, 0);
+ Entry uid1Entry1 = new Entry("if1", uid1, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 100, 10, 200, 20, 0);
- Entry uid1Entry2 = new Entry(
- "if2", uid1,
- android.net.NetworkStats.SET_DEFAULT, android.net.NetworkStats.TAG_NONE,
- android.net.NetworkStats.METERED_NO, android.net.NetworkStats.ROAMING_NO,
- android.net.NetworkStats.DEFAULT_NETWORK_NO,
- 100, 10, 200, 20, 0);
+ Entry uid1Entry2 = new Entry("if2", uid1, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 100, 10, 200, 20, 0);
- Entry uid2Entry1 = new Entry("if1", uid2,
- android.net.NetworkStats.SET_DEFAULT, android.net.NetworkStats.TAG_NONE,
- android.net.NetworkStats.METERED_NO, android.net.NetworkStats.ROAMING_NO,
- android.net.NetworkStats.DEFAULT_NETWORK_NO,
- 150, 10, 250, 20, 0);
+ Entry uid2Entry1 = new Entry("if1", uid2, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 150, 10, 250, 20, 0);
- Entry uid2Entry2 = new Entry(
- "if2", uid2,
- android.net.NetworkStats.SET_DEFAULT, android.net.NetworkStats.TAG_NONE,
- android.net.NetworkStats.METERED_NO, android.net.NetworkStats.ROAMING_NO,
- android.net.NetworkStats.DEFAULT_NETWORK_NO,
- 150, 10, 250, 20, 0);
+ Entry uid2Entry2 = new Entry("if2", uid2, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 150, 10, 250, 20, 0);
NetworkStatsHistory history1 = new NetworkStatsHistory(10, 2);
history1.recordData(10, 20, uid1Entry1);
@@ -125,9 +119,8 @@
when(mStatsSession.getRelevantUids()).thenReturn(new int[] { uid1, uid2, uid3 });
when(mStatsSession.getHistoryIntervalForUid(any(NetworkTemplate.class),
- eq(uid1), eq(android.net.NetworkStats.SET_ALL),
- eq(android.net.NetworkStats.TAG_NONE),
- eq(NetworkStatsHistory.FIELD_ALL), eq(startTime), eq(endTime)))
+ eq(uid1), eq(SET_ALL), eq(TAG_NONE),
+ eq(FIELD_ALL), eq(startTime), eq(endTime)))
.then((InvocationOnMock inv) -> {
NetworkTemplate template = inv.getArgument(0);
assertEquals(MATCH_MOBILE_ALL, template.getMatchRule());
@@ -136,9 +129,8 @@
});
when(mStatsSession.getHistoryIntervalForUid(any(NetworkTemplate.class),
- eq(uid2), eq(android.net.NetworkStats.SET_ALL),
- eq(android.net.NetworkStats.TAG_NONE),
- eq(NetworkStatsHistory.FIELD_ALL), eq(startTime), eq(endTime)))
+ eq(uid2), eq(SET_ALL), eq(TAG_NONE),
+ eq(FIELD_ALL), eq(startTime), eq(endTime)))
.then((InvocationOnMock inv) -> {
NetworkTemplate template = inv.getArgument(0);
assertEquals(MATCH_MOBILE_ALL, template.getMatchRule());
@@ -148,7 +140,7 @@
NetworkStats stats = mManager.queryDetails(
- ConnectivityManager.TYPE_MOBILE, TEST_SUBSCRIBER_ID, startTime, endTime);
+ TYPE_MOBILE, TEST_SUBSCRIBER_ID, startTime, endTime);
NetworkStats.Bucket bucket = new NetworkStats.Bucket();
@@ -202,35 +194,34 @@
verify(mStatsSession, times(1)).getHistoryIntervalForUid(
eq(expectedTemplate),
- eq(uid1), eq(android.net.NetworkStats.SET_ALL),
- eq(android.net.NetworkStats.TAG_NONE),
- eq(NetworkStatsHistory.FIELD_ALL), eq(startTime), eq(endTime));
+ eq(uid1), eq(SET_ALL),
+ eq(TAG_NONE),
+ eq(FIELD_ALL), eq(startTime), eq(endTime));
verify(mStatsSession, times(1)).getHistoryIntervalForUid(
eq(expectedTemplate),
- eq(uid2), eq(android.net.NetworkStats.SET_ALL),
- eq(android.net.NetworkStats.TAG_NONE),
- eq(NetworkStatsHistory.FIELD_ALL), eq(startTime), eq(endTime));
+ eq(uid2), eq(SET_ALL),
+ eq(TAG_NONE),
+ eq(FIELD_ALL), eq(startTime), eq(endTime));
assertFalse(stats.hasNextBucket());
}
@Test
public void testNetworkTemplateWhenRunningQueryDetails_NoSubscriberId() throws RemoteException {
- runQueryDetailsAndCheckTemplate(ConnectivityManager.TYPE_MOBILE,
- null /* subscriberId */, new NetworkTemplate.Builder(MATCH_MOBILE)
- .setMeteredness(METERED_YES).build());
- runQueryDetailsAndCheckTemplate(ConnectivityManager.TYPE_WIFI,
- "" /* subscriberId */, new NetworkTemplate.Builder(MATCH_WIFI).build());
- runQueryDetailsAndCheckTemplate(ConnectivityManager.TYPE_WIFI,
- null /* subscriberId */, new NetworkTemplate.Builder(MATCH_WIFI).build());
+ runQueryDetailsAndCheckTemplate(TYPE_MOBILE, null /* subscriberId */,
+ new NetworkTemplate.Builder(MATCH_MOBILE).setMeteredness(METERED_YES).build());
+ runQueryDetailsAndCheckTemplate(TYPE_WIFI, "" /* subscriberId */,
+ new NetworkTemplate.Builder(MATCH_WIFI).build());
+ runQueryDetailsAndCheckTemplate(TYPE_WIFI, null /* subscriberId */,
+ new NetworkTemplate.Builder(MATCH_WIFI).build());
}
@Test
public void testNetworkTemplateWhenRunningQueryDetails_MergedCarrierWifi()
throws RemoteException {
- runQueryDetailsAndCheckTemplate(ConnectivityManager.TYPE_WIFI,
- TEST_SUBSCRIBER_ID, new NetworkTemplate.Builder(MATCH_WIFI)
+ runQueryDetailsAndCheckTemplate(TYPE_WIFI, TEST_SUBSCRIBER_ID,
+ new NetworkTemplate.Builder(MATCH_WIFI)
.setSubscriberIds(Set.of(TEST_SUBSCRIBER_ID)).build());
}
@@ -244,7 +235,7 @@
when(mStatsSession.getTaggedSummaryForAllUid(any(NetworkTemplate.class),
anyLong(), anyLong()))
.thenReturn(new android.net.NetworkStats(0, 0));
- final NetworkTemplate template = new NetworkTemplate.Builder(NetworkTemplate.MATCH_MOBILE)
+ final NetworkTemplate template = new NetworkTemplate.Builder(MATCH_MOBILE)
.setMeteredness(NetworkStats.Bucket.METERED_YES).build();
NetworkStats stats = mManager.queryTaggedSummary(template, startTime, endTime);
@@ -265,12 +256,12 @@
when(mStatsSession.getHistoryIntervalForNetwork(any(NetworkTemplate.class),
anyInt(), anyLong(), anyLong()))
.thenReturn(new NetworkStatsHistory(10, 0));
- final NetworkTemplate template = new NetworkTemplate.Builder(NetworkTemplate.MATCH_MOBILE)
+ final NetworkTemplate template = new NetworkTemplate.Builder(MATCH_MOBILE)
.setMeteredness(NetworkStats.Bucket.METERED_YES).build();
NetworkStats stats = mManager.queryDetailsForDevice(template, startTime, endTime);
verify(mStatsSession, times(1)).getHistoryIntervalForNetwork(
- eq(template), eq(NetworkStatsHistory.FIELD_ALL), eq(startTime), eq(endTime));
+ eq(template), eq(FIELD_ALL), eq(startTime), eq(endTime));
assertFalse(stats.hasNextBucket());
}
diff --git a/tests/unit/java/com/android/server/BpfNetMapsTest.java b/tests/unit/java/com/android/server/BpfNetMapsTest.java
index 0c00bc0..0e17cd7 100644
--- a/tests/unit/java/com/android/server/BpfNetMapsTest.java
+++ b/tests/unit/java/com/android/server/BpfNetMapsTest.java
@@ -1070,4 +1070,11 @@
doTestDumpOwnerMatchConfig(DOZABLE_MATCH | invalid_match,
"DOZABLE_MATCH UNKNOWN_MATCH(" + invalid_match + ")");
}
+
+ @Test
+ @IgnoreUpTo(Build.VERSION_CODES.S_V2)
+ public void testDumpCookieTagMap() throws Exception {
+ mCookieTagMap.updateEntry(new CookieTagMapKey(123), new CookieTagMapValue(456, 0x789));
+ assertDumpContains(getDump(), "cookie=123 tag=0x789 uid=456");
+ }
}
diff --git a/tests/unit/java/com/android/server/connectivity/FullScoreTest.kt b/tests/unit/java/com/android/server/connectivity/FullScoreTest.kt
index b39e960..3520c5b 100644
--- a/tests/unit/java/com/android/server/connectivity/FullScoreTest.kt
+++ b/tests/unit/java/com/android/server/connectivity/FullScoreTest.kt
@@ -152,4 +152,16 @@
assertNotEquals(ns3, ns1)
assertFalse(ns1.equals(ns4))
}
+
+ @Test
+ fun testDescribeDifferences() {
+ val ns1 = FullScore((1L shl POLICY_EVER_EVALUATED) or (1L shl POLICY_IS_VALIDATED),
+ KEEP_CONNECTED_NONE)
+ val ns2 = FullScore((1L shl POLICY_IS_VALIDATED) or (1L shl POLICY_IS_VPN) or
+ (1L shl POLICY_IS_DESTROYED), KEEP_CONNECTED_NONE)
+ assertEquals("-EVER_EVALUATED+IS_DESTROYED+IS_VPN",
+ ns2.describeDifferencesFrom(ns1))
+ assertEquals("-IS_DESTROYED-IS_VPN+EVER_EVALUATED",
+ ns1.describeDifferencesFrom(ns2))
+ }
}