Merge changes Ifb7305be,I74d9d074,Ia0f6b67c,Ib14f444b
* changes:
ethernet: fix interface state callbacks ignoring restricted permission
ethernet: cleanup ethernet state listener interaction
ethernet: fix IpClient restart when link is down
ethernet: ignore NUD failures for static ip configurations
diff --git a/OWNERS_core_networking_xts b/OWNERS_core_networking_xts
index 8083cbf..1844334 100644
--- a/OWNERS_core_networking_xts
+++ b/OWNERS_core_networking_xts
@@ -1,7 +1,7 @@
lorenzo@google.com
satk@google.com #{LAST_RESORT_SUGGESTION}
-# For cherry-picks of CLs that are already merged in aosp/master.
+# For cherry-picks of CLs that are already merged in aosp/master, or flaky test fixes.
jchalard@google.com #{LAST_RESORT_SUGGESTION}
maze@google.com #{LAST_RESORT_SUGGESTION}
reminv@google.com #{LAST_RESORT_SUGGESTION}
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 6e30fd1..700a085 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -135,6 +135,37 @@
}
]
},
+ // Test with APK modules only, in cases where APEX is not supported, or the other modules
+ // were simply not updated
+ {
+ "name": "CtsNetTestCasesLatestSdk[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk]",
+ "options": [
+ {
+ "exclude-annotation": "com.android.testutils.SkipPresubmit"
+ },
+ {
+ "exclude-annotation": "androidx.test.filters.RequiresDevice"
+ },
+ {
+ "exclude-annotation": "com.android.testutils.ConnectivityModuleTest"
+ }
+ ]
+ },
+ // Test with connectivity/tethering module only, to catch integration issues with older versions
+ // of other modules. "new tethering + old NetworkStack" is not a configuration that should
+ // really exist in the field, but there is no strong guarantee, and it is required by MTS
+ // testing for module qualification, where modules are tested independently.
+ {
+ "name": "CtsNetTestCasesLatestSdk[com.google.android.tethering.apex]",
+ "options": [
+ {
+ "exclude-annotation": "com.android.testutils.SkipPresubmit"
+ },
+ {
+ "exclude-annotation": "androidx.test.filters.RequiresDevice"
+ }
+ ]
+ },
{
"name": "bpf_existence_test[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk+com.google.android.resolv.apex+com.google.android.tethering.apex]"
},
@@ -159,38 +190,6 @@
{
"name": "CtsNetTestCasesLatestSdk[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk+com.google.android.resolv.apex+com.google.android.tethering.apex]",
"keywords": ["sim"]
- },
- // TODO: move to mainline-presubmit when known green.
- // Test with APK modules only, in cases where APEX is not supported, or the other modules were simply not updated
- {
- "name": "CtsNetTestCasesLatestSdk[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk]",
- "options": [
- {
- "exclude-annotation": "com.android.testutils.SkipPresubmit"
- },
- {
- "exclude-annotation": "androidx.test.filters.RequiresDevice"
- },
- {
- "exclude-annotation": "com.android.testutils.ConnectivityModuleTest"
- }
- ]
- },
- // TODO: move to mainline-presubmit when known green.
- // Test with connectivity/tethering module only, to catch integration issues with older versions of other modules.
- // "new tethering + old NetworkStack" is not a configuration that should really exist in the field, but
- // there is no strong guarantee, and it is required by MTS testing for module qualification, where modules
- // are tested independently.
- {
- "name": "CtsNetTestCasesLatestSdk[com.google.android.tethering.apex]",
- "options": [
- {
- "exclude-annotation": "com.android.testutils.SkipPresubmit"
- },
- {
- "exclude-annotation": "androidx.test.filters.RequiresDevice"
- }
- ]
}
],
"imports": [
diff --git a/framework/src/android/net/NetworkCapabilities.java b/framework/src/android/net/NetworkCapabilities.java
index ea8a3df..d0cbbe5 100644
--- a/framework/src/android/net/NetworkCapabilities.java
+++ b/framework/src/android/net/NetworkCapabilities.java
@@ -185,10 +185,18 @@
NET_ENTERPRISE_ID_4,
NET_ENTERPRISE_ID_5,
})
-
public @interface EnterpriseId {
}
+ private static final int ALL_VALID_ENTERPRISE_IDS;
+ static {
+ int enterpriseIds = 0;
+ for (int i = NET_ENTERPRISE_ID_1; i <= NET_ENTERPRISE_ID_5; ++i) {
+ enterpriseIds |= 1 << i;
+ }
+ ALL_VALID_ENTERPRISE_IDS = enterpriseIds;
+ }
+
/**
* Bitfield representing the network's enterprise capability identifier. If any are specified
* they will be satisfied by any Network that matches all of them.
@@ -622,6 +630,15 @@
private static final int MIN_NET_CAPABILITY = NET_CAPABILITY_MMS;
private static final int MAX_NET_CAPABILITY = NET_CAPABILITY_PRIORITIZE_BANDWIDTH;
+ private static final int ALL_VALID_CAPABILITIES;
+ static {
+ int caps = 0;
+ for (int i = MIN_NET_CAPABILITY; i <= MAX_NET_CAPABILITY; ++i) {
+ caps |= 1 << i;
+ }
+ ALL_VALID_CAPABILITIES = caps;
+ }
+
/**
* Network capabilities that are expected to be mutable, i.e., can change while a particular
* network is connected.
@@ -1146,6 +1163,15 @@
/** @hide */
public static final int MAX_TRANSPORT = TRANSPORT_USB;
+ private static final int ALL_VALID_TRANSPORTS;
+ static {
+ int transports = 0;
+ for (int i = MIN_TRANSPORT; i <= MAX_TRANSPORT; ++i) {
+ transports |= 1 << i;
+ }
+ ALL_VALID_TRANSPORTS = transports;
+ }
+
/** @hide */
public static boolean isValidTransport(@Transport int transportType) {
return (MIN_TRANSPORT <= transportType) && (transportType <= MAX_TRANSPORT);
@@ -2114,9 +2140,9 @@
@Override
public void writeToParcel(Parcel dest, int flags) {
- dest.writeLong(mNetworkCapabilities);
- dest.writeLong(mForbiddenNetworkCapabilities);
- dest.writeLong(mTransportTypes);
+ dest.writeLong(mNetworkCapabilities & ALL_VALID_CAPABILITIES);
+ dest.writeLong(mForbiddenNetworkCapabilities & ALL_VALID_CAPABILITIES);
+ dest.writeLong(mTransportTypes & ALL_VALID_TRANSPORTS);
dest.writeInt(mLinkUpBandwidthKbps);
dest.writeInt(mLinkDownBandwidthKbps);
dest.writeParcelable((Parcelable) mNetworkSpecifier, flags);
@@ -2132,7 +2158,7 @@
dest.writeString(mRequestorPackageName);
dest.writeIntArray(CollectionUtils.toIntArray(mSubIds));
dest.writeTypedList(mUnderlyingNetworks);
- dest.writeInt(mEnterpriseId);
+ dest.writeInt(mEnterpriseId & ALL_VALID_ENTERPRISE_IDS);
}
public static final @android.annotation.NonNull Creator<NetworkCapabilities> CREATOR =
@@ -2140,10 +2166,10 @@
@Override
public NetworkCapabilities createFromParcel(Parcel in) {
NetworkCapabilities netCap = new NetworkCapabilities();
-
- netCap.mNetworkCapabilities = in.readLong();
- netCap.mForbiddenNetworkCapabilities = in.readLong();
- netCap.mTransportTypes = in.readLong();
+ // Validate the unparceled data, in case the parceling party was malicious.
+ netCap.mNetworkCapabilities = in.readLong() & ALL_VALID_CAPABILITIES;
+ netCap.mForbiddenNetworkCapabilities = in.readLong() & ALL_VALID_CAPABILITIES;
+ netCap.mTransportTypes = in.readLong() & ALL_VALID_TRANSPORTS;
netCap.mLinkUpBandwidthKbps = in.readInt();
netCap.mLinkDownBandwidthKbps = in.readInt();
netCap.mNetworkSpecifier = in.readParcelable(null);
@@ -2167,7 +2193,7 @@
netCap.mSubIds.add(subIdInts[i]);
}
netCap.setUnderlyingNetworks(in.createTypedArrayList(Network.CREATOR));
- netCap.mEnterpriseId = in.readInt();
+ netCap.mEnterpriseId = in.readInt() & ALL_VALID_ENTERPRISE_IDS;
return netCap;
}
@Override
diff --git a/service-t/src/com/android/server/net/NetworkStatsService.java b/service-t/src/com/android/server/net/NetworkStatsService.java
index 0da7b6f..629bf73 100644
--- a/service-t/src/com/android/server/net/NetworkStatsService.java
+++ b/service-t/src/com/android/server/net/NetworkStatsService.java
@@ -56,7 +56,6 @@
import static android.net.netstats.NetworkStatsDataMigrationUtils.PREFIX_XT;
import static android.os.Trace.TRACE_TAG_NETWORK;
import static android.system.OsConstants.ENOENT;
-import static android.system.OsConstants.R_OK;
import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
import static android.text.format.DateUtils.DAY_IN_MILLIS;
import static android.text.format.DateUtils.HOUR_IN_MILLIS;
@@ -134,7 +133,6 @@
import android.service.NetworkInterfaceProto;
import android.service.NetworkStatsServiceDumpProto;
import android.system.ErrnoException;
-import android.system.Os;
import android.telephony.PhoneStateListener;
import android.telephony.SubscriptionPlan;
import android.text.TextUtils;
@@ -254,6 +252,8 @@
"/sys/fs/bpf/netd_shared/map_netd_stats_map_A";
private static final String STATS_MAP_B_PATH =
"/sys/fs/bpf/netd_shared/map_netd_stats_map_B";
+ private static final String IFACE_STATS_MAP_PATH =
+ "/sys/fs/bpf/netd_shared/map_netd_iface_stats_map";
/**
* DeviceConfig flag used to indicate whether the files should be stored in the apex data
@@ -413,6 +413,7 @@
private final IBpfMap<StatsMapKey, StatsMapValue> mStatsMapA;
private final IBpfMap<StatsMapKey, StatsMapValue> mStatsMapB;
private final IBpfMap<UidStatsMapKey, StatsMapValue> mAppUidStatsMap;
+ private final IBpfMap<S32, StatsMapValue> mIfaceStatsMap;
/** Data layer operation counters for splicing into other structures. */
private NetworkStats mUidOperations = new NetworkStats(0L, 10);
@@ -592,6 +593,7 @@
mStatsMapA = mDeps.getStatsMapA();
mStatsMapB = mDeps.getStatsMapB();
mAppUidStatsMap = mDeps.getAppUidStatsMap();
+ mIfaceStatsMap = mDeps.getIfaceStatsMap();
// TODO: Remove bpfNetMaps creation and always start SkDestroyListener
// Following code is for the experiment to verify the SkDestroyListener refactoring. Based
@@ -795,6 +797,16 @@
}
}
+ /** Gets interface stats map */
+ public IBpfMap<S32, StatsMapValue> getIfaceStatsMap() {
+ try {
+ return new BpfMap<S32, StatsMapValue>(IFACE_STATS_MAP_PATH,
+ BpfMap.BPF_F_RDWR, S32.class, StatsMapValue.class);
+ } catch (ErrnoException e) {
+ throw new IllegalStateException("Failed to open interface stats map", e);
+ }
+ }
+
/** Gets whether the build is userdebug. */
public boolean isDebuggable() {
return Build.isDebuggable();
@@ -2763,6 +2775,7 @@
dumpAppUidStatsMapLocked(pw);
dumpStatsMapLocked(mStatsMapA, pw, "mStatsMapA");
dumpStatsMapLocked(mStatsMapB, pw, "mStatsMapB");
+ dumpIfaceStatsMapLocked(pw);
pw.decreaseIndent();
}
}
@@ -2830,26 +2843,14 @@
}
}
- private <K extends Struct, V extends Struct> String getMapStatus(
- final IBpfMap<K, V> map, final String path) {
- if (map != null) {
- return "OK";
- }
- try {
- Os.access(path, R_OK);
- return "NULL(map is pinned to " + path + ")";
- } catch (ErrnoException e) {
- return "NULL(map is not pinned to " + path + ": " + Os.strerror(e.errno) + ")";
- }
- }
-
private void dumpMapStatus(final IndentingPrintWriter pw) {
- pw.println("mCookieTagMap: " + getMapStatus(mCookieTagMap, COOKIE_TAG_MAP_PATH));
- pw.println("mUidCounterSetMap: "
- + getMapStatus(mUidCounterSetMap, UID_COUNTERSET_MAP_PATH));
- pw.println("mAppUidStatsMap: " + getMapStatus(mAppUidStatsMap, APP_UID_STATS_MAP_PATH));
- pw.println("mStatsMapA: " + getMapStatus(mStatsMapA, STATS_MAP_A_PATH));
- pw.println("mStatsMapB: " + getMapStatus(mStatsMapB, STATS_MAP_B_PATH));
+ BpfDump.dumpMapStatus(mCookieTagMap, pw, "mCookieTagMap", COOKIE_TAG_MAP_PATH);
+ BpfDump.dumpMapStatus(mUidCounterSetMap, pw, "mUidCounterSetMap", UID_COUNTERSET_MAP_PATH);
+ BpfDump.dumpMapStatus(mAppUidStatsMap, pw, "mAppUidStatsMap", APP_UID_STATS_MAP_PATH);
+ BpfDump.dumpMapStatus(mStatsMapA, pw, "mStatsMapA", STATS_MAP_A_PATH);
+ BpfDump.dumpMapStatus(mStatsMapB, pw, "mStatsMapB", STATS_MAP_B_PATH);
+ // mIfaceStatsMap is always not null but dump status to be consistent with other maps.
+ BpfDump.dumpMapStatus(mIfaceStatsMap, pw, "mIfaceStatsMap", IFACE_STATS_MAP_PATH);
}
@GuardedBy("mStatsLock")
@@ -2909,6 +2910,21 @@
});
}
+ @GuardedBy("mStatsLock")
+ private void dumpIfaceStatsMapLocked(final IndentingPrintWriter pw) {
+ BpfDump.dumpMap(mIfaceStatsMap, pw, "mIfaceStatsMap",
+ "ifaceIndex ifaceName rxBytes rxPackets txBytes txPackets",
+ (key, value) -> {
+ final String ifName = mInterfaceMapUpdater.getIfNameByIndex(key.val);
+ return key.val + " "
+ + (ifName != null ? ifName : "unknown") + " "
+ + value.rxBytes + " "
+ + value.rxPackets + " "
+ + value.txBytes + " "
+ + value.txPackets;
+ });
+ }
+
private NetworkStats readNetworkStatsSummaryDev() {
try {
return mStatsFactory.readNetworkStatsSummaryDev();
diff --git a/service/native/TrafficController.cpp b/service/native/TrafficController.cpp
index 49b23c9..fc76ae5 100644
--- a/service/native/TrafficController.cpp
+++ b/service/native/TrafficController.cpp
@@ -647,91 +647,7 @@
dw.println("mCookieTagMap print end with error: %s", res.error().message().c_str());
}
- // Print ifaceStatsMap content
- std::string ifaceStatsHeader = StringPrintf("ifaceIndex ifaceName rxBytes rxPackets txBytes"
- " txPackets");
- dumpBpfMap("mIfaceStatsMap:", dw, ifaceStatsHeader);
- const auto printIfaceStatsInfo = [&dw, this](const uint32_t& key, const StatsValue& value,
- const BpfMap<uint32_t, StatsValue>&) {
- auto ifname = mIfaceIndexNameMap.readValue(key);
- if (!ifname.ok()) {
- ifname = IfaceValue{"unknown"};
- }
- dw.println("%u %s %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64, key, ifname.value().name,
- value.rxBytes, value.rxPackets, value.txBytes, value.txPackets);
- return base::Result<void>();
- };
- res = mIfaceStatsMap.iterateWithValue(printIfaceStatsInfo);
- if (!res.ok()) {
- dw.println("mIfaceStatsMap print end with error: %s", res.error().message().c_str());
- }
-
dw.blankline();
-
- uint32_t key = UID_RULES_CONFIGURATION_KEY;
- auto configuration = mConfigurationMap.readValue(key);
- if (configuration.ok()) {
- dw.println("current ownerMatch configuration: %d%s", configuration.value(),
- uidMatchTypeToString(configuration.value()).c_str());
- } else {
- dw.println("mConfigurationMap read ownerMatch configure failed with error: %s",
- configuration.error().message().c_str());
- }
-
- key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
- configuration = mConfigurationMap.readValue(key);
- if (configuration.ok()) {
- const char* statsMapDescription = "???";
- switch (configuration.value()) {
- case SELECT_MAP_A:
- statsMapDescription = "SELECT_MAP_A";
- break;
- case SELECT_MAP_B:
- statsMapDescription = "SELECT_MAP_B";
- break;
- // No default clause, so if we ever add a third map, this code will fail to build.
- }
- dw.println("current statsMap configuration: %d %s", configuration.value(),
- statsMapDescription);
- } else {
- dw.println("mConfigurationMap read stats map configure failed with error: %s",
- configuration.error().message().c_str());
- }
- dumpBpfMap("mUidOwnerMap", dw, "");
- const auto printUidMatchInfo = [&dw, this](const uint32_t& key, const UidOwnerValue& value,
- const BpfMap<uint32_t, UidOwnerValue>&) {
- if (value.rule & IIF_MATCH) {
- auto ifname = mIfaceIndexNameMap.readValue(value.iif);
- if (ifname.ok()) {
- dw.println("%u %s %s", key, uidMatchTypeToString(value.rule).c_str(),
- ifname.value().name);
- } else {
- dw.println("%u %s %u", key, uidMatchTypeToString(value.rule).c_str(), value.iif);
- }
- } else {
- dw.println("%u %s", key, uidMatchTypeToString(value.rule).c_str());
- }
- return base::Result<void>();
- };
- res = mUidOwnerMap.iterateWithValue(printUidMatchInfo);
- if (!res.ok()) {
- dw.println("mUidOwnerMap print end with error: %s", res.error().message().c_str());
- }
- dumpBpfMap("mUidPermissionMap", dw, "");
- const auto printUidPermissionInfo = [&dw](const uint32_t& key, const int& value,
- const BpfMap<uint32_t, uint8_t>&) {
- dw.println("%u %s", key, UidPermissionTypeToString(value).c_str());
- return base::Result<void>();
- };
- res = mUidPermissionMap.iterateWithValue(printUidPermissionInfo);
- if (!res.ok()) {
- dw.println("mUidPermissionMap print end with error: %s", res.error().message().c_str());
- }
-
- dumpBpfMap("mPrivilegedUser", dw, "");
- for (uid_t uid : mPrivilegedUser) {
- dw.println("%u ALLOW_UPDATE_DEVICE_STATS", (uint32_t)uid);
- }
}
} // namespace net
diff --git a/service/native/TrafficControllerTest.cpp b/service/native/TrafficControllerTest.cpp
index 8525738..6cb0940 100644
--- a/service/native/TrafficControllerTest.cpp
+++ b/service/native/TrafficControllerTest.cpp
@@ -793,16 +793,6 @@
"mCookieTagMap:",
fmt::format("cookie={} tag={:#x} uid={}", TEST_COOKIE, TEST_TAG, TEST_UID)};
- ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, HAPPY_BOX_MATCH,
- TrafficController::IptOpInsert)));
- expectedLines.emplace_back("mUidOwnerMap:");
- expectedLines.emplace_back(fmt::format("{} HAPPY_BOX_MATCH", TEST_UID));
-
- mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, {TEST_UID2});
- expectedLines.emplace_back("mUidPermissionMap:");
- expectedLines.emplace_back(fmt::format("{} BPF_PERMISSION_UPDATE_DEVICE_STATS", TEST_UID2));
- expectedLines.emplace_back("mPrivilegedUser:");
- expectedLines.emplace_back(fmt::format("{} ALLOW_UPDATE_DEVICE_STATS", TEST_UID2));
EXPECT_TRUE(expectDumpsysContains(expectedLines));
}
@@ -813,59 +803,12 @@
"Bad file descriptor";
const std::string kErrReadRulesConfig = "read ownerMatch configure failed with error: "
"Read value of map -1 failed: Bad file descriptor";
- const std::string kErrReadStatsMapConfig = "read stats map configure failed with error: "
- "Read value of map -1 failed: Bad file descriptor";
std::vector<std::string> expectedLines = {
- fmt::format("mCookieTagMap {}", kErrIterate),
- fmt::format("mIfaceStatsMap {}", kErrIterate),
- fmt::format("mConfigurationMap {}", kErrReadRulesConfig),
- fmt::format("mConfigurationMap {}", kErrReadStatsMapConfig),
- fmt::format("mUidOwnerMap {}", kErrIterate),
- fmt::format("mUidPermissionMap {}", kErrIterate)};
+ fmt::format("mCookieTagMap {}", kErrIterate)};
EXPECT_TRUE(expectDumpsysContains(expectedLines));
}
-TEST_F(TrafficControllerTest, uidMatchTypeToString) {
- // NO_MATCH(0) can't be verified because match type flag is added by OR operator.
- // See TrafficController::addRule()
- static const struct TestConfig {
- UidOwnerMatchType uidOwnerMatchType;
- std::string expected;
- } testConfigs[] = {
- // clang-format off
- {HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH"},
- {DOZABLE_MATCH, "DOZABLE_MATCH"},
- {STANDBY_MATCH, "STANDBY_MATCH"},
- {POWERSAVE_MATCH, "POWERSAVE_MATCH"},
- {HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH"},
- {RESTRICTED_MATCH, "RESTRICTED_MATCH"},
- {LOW_POWER_STANDBY_MATCH, "LOW_POWER_STANDBY_MATCH"},
- {IIF_MATCH, "IIF_MATCH"},
- {LOCKDOWN_VPN_MATCH, "LOCKDOWN_VPN_MATCH"},
- {OEM_DENY_1_MATCH, "OEM_DENY_1_MATCH"},
- {OEM_DENY_2_MATCH, "OEM_DENY_2_MATCH"},
- {OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH"},
- // clang-format on
- };
-
- for (const auto& config : testConfigs) {
- SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.uidOwnerMatchType,
- config.expected));
-
- // Test private function uidMatchTypeToString() via dumpsys.
- ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, config.uidOwnerMatchType,
- TrafficController::IptOpInsert)));
- std::vector<std::string> expectedLines;
- expectedLines.emplace_back(fmt::format("{} {}", TEST_UID, config.expected));
- EXPECT_TRUE(expectDumpsysContains(expectedLines));
-
- // Clean up the stubs.
- ASSERT_TRUE(isOk(updateUidOwnerMaps({TEST_UID}, config.uidOwnerMatchType,
- TrafficController::IptOpDelete)));
- }
-}
-
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 dbfc383..d560747 100644
--- a/service/src/com/android/server/BpfNetMaps.java
+++ b/service/src/com/android/server/BpfNetMaps.java
@@ -27,7 +27,9 @@
import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
import static android.net.INetd.PERMISSION_INTERNET;
+import static android.net.INetd.PERMISSION_NONE;
import static android.net.INetd.PERMISSION_UNINSTALLED;
+import static android.net.INetd.PERMISSION_UPDATE_DEVICE_STATS;
import static android.system.OsConstants.EINVAL;
import static android.system.OsConstants.ENODEV;
import static android.system.OsConstants.ENOENT;
@@ -44,12 +46,15 @@
import android.system.ErrnoException;
import android.system.Os;
import android.util.ArraySet;
+import android.util.IndentingPrintWriter;
import android.util.Log;
+import android.util.Pair;
import android.util.StatsEvent;
import com.android.internal.annotations.VisibleForTesting;
import com.android.modules.utils.BackgroundThread;
import com.android.modules.utils.build.SdkLevel;
+import com.android.net.module.util.BpfDump;
import com.android.net.module.util.BpfMap;
import com.android.net.module.util.DeviceConfigUtils;
import com.android.net.module.util.IBpfMap;
@@ -62,8 +67,10 @@
import java.io.FileDescriptor;
import java.io.IOException;
+import java.util.Arrays;
import java.util.List;
import java.util.Set;
+import java.util.StringJoiner;
/**
* BpfNetMaps is responsible for providing traffic controller relevant functionality.
@@ -134,6 +141,25 @@
@VisibleForTesting public static final long OEM_DENY_3_MATCH = (1 << 11);
// LINT.ThenChange(packages/modules/Connectivity/bpf_progs/bpf_shared.h)
+ private static final List<Pair<Integer, String>> PERMISSION_LIST = Arrays.asList(
+ Pair.create(PERMISSION_INTERNET, "PERMISSION_INTERNET"),
+ Pair.create(PERMISSION_UPDATE_DEVICE_STATS, "PERMISSION_UPDATE_DEVICE_STATS")
+ );
+ private static final List<Pair<Long, String>> MATCH_LIST = Arrays.asList(
+ Pair.create(HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH"),
+ Pair.create(PENALTY_BOX_MATCH, "PENALTY_BOX_MATCH"),
+ Pair.create(DOZABLE_MATCH, "DOZABLE_MATCH"),
+ Pair.create(STANDBY_MATCH, "STANDBY_MATCH"),
+ Pair.create(POWERSAVE_MATCH, "POWERSAVE_MATCH"),
+ Pair.create(RESTRICTED_MATCH, "RESTRICTED_MATCH"),
+ Pair.create(LOW_POWER_STANDBY_MATCH, "LOW_POWER_STANDBY_MATCH"),
+ Pair.create(IIF_MATCH, "IIF_MATCH"),
+ Pair.create(LOCKDOWN_VPN_MATCH, "LOCKDOWN_VPN_MATCH"),
+ Pair.create(OEM_DENY_1_MATCH, "OEM_DENY_1_MATCH"),
+ Pair.create(OEM_DENY_2_MATCH, "OEM_DENY_2_MATCH"),
+ Pair.create(OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH")
+ );
+
/**
* Set sEnableJavaBpfMap for test.
*/
@@ -914,14 +940,80 @@
return StatsManager.PULL_SUCCESS;
}
+ private String permissionToString(int permissionMask) {
+ if (permissionMask == PERMISSION_NONE) {
+ return "PERMISSION_NONE";
+ }
+ if (permissionMask == PERMISSION_UNINSTALLED) {
+ // PERMISSION_UNINSTALLED should never appear in the map
+ return "PERMISSION_UNINSTALLED error!";
+ }
+
+ final StringJoiner sj = new StringJoiner(" ");
+ for (Pair<Integer, String> permission: PERMISSION_LIST) {
+ final int permissionFlag = permission.first;
+ final String permissionName = permission.second;
+ if ((permissionMask & permissionFlag) != 0) {
+ sj.add(permissionName);
+ permissionMask &= ~permissionFlag;
+ }
+ }
+ if (permissionMask != 0) {
+ sj.add("PERMISSION_UNKNOWN(" + permissionMask + ")");
+ }
+ return sj.toString();
+ }
+
+ private String matchToString(long matchMask) {
+ if (matchMask == NO_MATCH) {
+ return "NO_MATCH";
+ }
+
+ final StringJoiner sj = new StringJoiner(" ");
+ for (Pair<Long, String> match: MATCH_LIST) {
+ final long matchFlag = match.first;
+ final String matchName = match.second;
+ if ((matchMask & matchFlag) != 0) {
+ sj.add(matchName);
+ matchMask &= ~matchFlag;
+ }
+ }
+ if (matchMask != 0) {
+ sj.add("UNKNOWN_MATCH(" + matchMask + ")");
+ }
+ return sj.toString();
+ }
+
+ private void dumpOwnerMatchConfig(final IndentingPrintWriter pw) {
+ try {
+ final long match = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY).val;
+ pw.println("current ownerMatch configuration: " + match + " " + matchToString(match));
+ } catch (ErrnoException e) {
+ pw.println("Failed to read ownerMatch configuration: " + e);
+ }
+ }
+
+ private void dumpCurrentStatsMapConfig(final IndentingPrintWriter pw) {
+ try {
+ final long config = sConfigurationMap.getValue(CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
+ final String currentStatsMap =
+ (config == STATS_SELECT_MAP_A) ? "SELECT_MAP_A" : "SELECT_MAP_B";
+ pw.println("current statsMap configuration: " + config + " " + currentStatsMap);
+ } catch (ErrnoException e) {
+ pw.println("Falied to read current statsMap configuration: " + e);
+ }
+ }
+
/**
* Dump BPF maps
*
+ * @param pw print writer
* @param fd file descriptor to output
+ * @param verbose verbose dump flag, if true dump the BpfMap contents
* @throws IOException when file descriptor is invalid.
* @throws ServiceSpecificException when the method is called on an unsupported device.
*/
- public void dump(final FileDescriptor fd, boolean verbose)
+ public void dump(final IndentingPrintWriter pw, final FileDescriptor fd, boolean verbose)
throws IOException, ServiceSpecificException {
if (PRE_T) {
throw new ServiceSpecificException(
@@ -929,6 +1021,24 @@
+ " devices, use dumpsys netd trafficcontroller instead.");
}
mDeps.nativeDump(fd, verbose);
+
+ if (verbose) {
+ dumpOwnerMatchConfig(pw);
+ dumpCurrentStatsMapConfig(pw);
+ pw.println();
+
+ BpfDump.dumpMap(sUidOwnerMap, pw, "sUidOwnerMap",
+ (uid, match) -> {
+ if ((match.rule & IIF_MATCH) != 0) {
+ // TODO: convert interface index to interface name by IfaceIndexNameMap
+ return uid.val + " " + matchToString(match.rule) + " " + match.iif;
+ } else {
+ return uid.val + " " + matchToString(match.rule);
+ }
+ });
+ BpfDump.dumpMap(sUidPermissionMap, pw, "sUidPermissionMap",
+ (uid, permission) -> uid.val + " " + permissionToString(permission.val));
+ }
}
private static native void native_init(boolean startSkDestroyListener);
diff --git a/service/src/com/android/server/ConnectivityService.java b/service/src/com/android/server/ConnectivityService.java
index 84cf561..10b3dc8 100755
--- a/service/src/com/android/server/ConnectivityService.java
+++ b/service/src/com/android/server/ConnectivityService.java
@@ -1982,6 +1982,9 @@
@Nullable
public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
enforceAccessPermission();
+ if (uid != mDeps.getCallingUid()) {
+ enforceNetworkStackPermission(mContext);
+ }
final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
if (nai == null) return null;
return getFilteredNetworkInfo(nai, uid, ignoreBlocked);
@@ -3457,7 +3460,7 @@
private void dumpTrafficController(IndentingPrintWriter pw, final FileDescriptor fd,
boolean verbose) {
try {
- mBpfNetMaps.dump(fd, verbose);
+ mBpfNetMaps.dump(pw, fd, verbose);
} catch (ServiceSpecificException e) {
pw.println(e.getMessage());
} catch (IOException e) {
diff --git a/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
index 8dbcc00..310d7bf 100644
--- a/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -2751,6 +2751,27 @@
mCm.getActiveNetwork(), false /* accept */ , false /* always */));
}
+ private void ensureCellIsValidatedBeforeMockingValidationUrls() {
+ // Verify that current supported network is validated so that the mock http server will not
+ // apply to unexpected networks. Also see aosp/2208680.
+ //
+ // This may also apply to wifi in principle, but in practice methods that mock validation
+ // URL all disconnect wifi forcefully anyway, so don't wait for wifi to validate.
+ if (mPackageManager.hasSystemFeature(FEATURE_TELEPHONY)) {
+ ensureValidatedNetwork(makeCellNetworkRequest());
+ }
+ }
+
+ private void ensureValidatedNetwork(NetworkRequest request) {
+ final TestableNetworkCallback cb = new TestableNetworkCallback();
+ mCm.registerNetworkCallback(request, cb);
+ cb.eventuallyExpect(CallbackEntry.NETWORK_CAPS_UPDATED,
+ NETWORK_CALLBACK_TIMEOUT_MS,
+ entry -> ((CallbackEntry.CapabilitiesChanged) entry).getCaps()
+ .hasCapability(NET_CAPABILITY_VALIDATED));
+ mCm.unregisterNetworkCallback(cb);
+ }
+
@AppModeFull(reason = "WRITE_DEVICE_CONFIG permission can't be granted to instant apps")
@Test
public void testAcceptPartialConnectivity_validatedNetwork() throws Exception {
@@ -2882,7 +2903,8 @@
assertTrue(mCm.getNetworkCapabilities(wifiNetwork).hasCapability(
NET_CAPABILITY_VALIDATED));
- // Configure response code for unvalidated network
+ // The cell network has already been checked to be validated.
+ // Configure response code for unvalidated network.
configTestServer(Status.INTERNAL_ERROR, Status.INTERNAL_ERROR);
mCm.reportNetworkConnectivity(wifiNetwork, false);
// Default network should stay on unvalidated wifi because avoid bad wifi is disabled.
@@ -2970,6 +2992,8 @@
}
private Network prepareValidatedNetwork() throws Exception {
+ ensureCellIsValidatedBeforeMockingValidationUrls();
+
prepareHttpServer();
configTestServer(Status.NO_CONTENT, Status.NO_CONTENT);
// Disconnect wifi first then start wifi network with configuration.
@@ -2980,6 +3004,8 @@
}
private Network preparePartialConnectivity() throws Exception {
+ ensureCellIsValidatedBeforeMockingValidationUrls();
+
prepareHttpServer();
// Configure response code for partial connectivity
configTestServer(Status.INTERNAL_ERROR /* httpsStatusCode */,
@@ -2993,6 +3019,8 @@
}
private Network prepareUnvalidatedNetwork() throws Exception {
+ ensureCellIsValidatedBeforeMockingValidationUrls();
+
prepareHttpServer();
// Configure response code for unvalidated network
configTestServer(Status.INTERNAL_ERROR /* httpsStatusCode */,
diff --git a/tests/cts/net/src/android/net/cts/QosCallbackExceptionTest.java b/tests/cts/net/src/android/net/cts/QosCallbackExceptionTest.java
index ffb34e6..04abd72 100644
--- a/tests/cts/net/src/android/net/cts/QosCallbackExceptionTest.java
+++ b/tests/cts/net/src/android/net/cts/QosCallbackExceptionTest.java
@@ -29,6 +29,7 @@
import android.net.SocketRemoteAddressChangedException;
import android.os.Build;
+import com.android.testutils.ConnectivityModuleTest;
import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
import com.android.testutils.DevSdkIgnoreRunner;
@@ -37,6 +38,7 @@
@RunWith(DevSdkIgnoreRunner.class)
@IgnoreUpTo(Build.VERSION_CODES.R)
+@ConnectivityModuleTest
public class QosCallbackExceptionTest {
private static final String ERROR_MESSAGE = "Test Error Message";
diff --git a/tests/unit/java/com/android/server/BpfNetMapsTest.java b/tests/unit/java/com/android/server/BpfNetMapsTest.java
index 4966aed..0c00bc0 100644
--- a/tests/unit/java/com/android/server/BpfNetMapsTest.java
+++ b/tests/unit/java/com/android/server/BpfNetMapsTest.java
@@ -37,10 +37,15 @@
import static com.android.server.BpfNetMaps.HAPPY_BOX_MATCH;
import static com.android.server.BpfNetMaps.IIF_MATCH;
import static com.android.server.BpfNetMaps.LOCKDOWN_VPN_MATCH;
+import static com.android.server.BpfNetMaps.LOW_POWER_STANDBY_MATCH;
import static com.android.server.BpfNetMaps.NO_MATCH;
+import static com.android.server.BpfNetMaps.OEM_DENY_1_MATCH;
+import static com.android.server.BpfNetMaps.OEM_DENY_2_MATCH;
+import static com.android.server.BpfNetMaps.OEM_DENY_3_MATCH;
import static com.android.server.BpfNetMaps.PENALTY_BOX_MATCH;
import static com.android.server.BpfNetMaps.POWERSAVE_MATCH;
import static com.android.server.BpfNetMaps.RESTRICTED_MATCH;
+import static com.android.server.BpfNetMaps.STANDBY_MATCH;
import static com.android.server.ConnectivityStatsLog.NETWORK_BPF_MAP_INFO;
import static org.junit.Assert.assertEquals;
@@ -61,6 +66,7 @@
import android.os.Build;
import android.os.ServiceSpecificException;
import android.system.ErrnoException;
+import android.util.IndentingPrintWriter;
import androidx.test.filters.SmallTest;
@@ -84,6 +90,8 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import java.io.FileDescriptor;
+import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
@@ -138,6 +146,9 @@
doReturn(0).when(mDeps).synchronizeKernelRCU();
BpfNetMaps.setEnableJavaBpfMapForTest(true /* enable */);
BpfNetMaps.setConfigurationMapForTest(mConfigurationMap);
+ mConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(0));
+ mConfigurationMap.updateEntry(
+ CURRENT_STATS_MAP_CONFIGURATION_KEY, new U32(STATS_SELECT_MAP_A));
BpfNetMaps.setUidOwnerMapForTest(mUidOwnerMap);
BpfNetMaps.setUidPermissionMapForTest(mUidPermissionMap);
BpfNetMaps.setCookieTagMapForTest(mCookieTagMap);
@@ -927,4 +938,136 @@
final int ret = mBpfNetMaps.pullBpfMapInfoAtom(-1 /* atomTag */, new ArrayList<>());
assertEquals(StatsManager.PULL_SKIP, ret);
}
+
+ private void assertDumpContains(final String dump, final String message) {
+ assertTrue(String.format("dump(%s) does not contain '%s'", dump, message),
+ dump.contains(message));
+ }
+
+ private String getDump() throws Exception {
+ final StringWriter sw = new StringWriter();
+ mBpfNetMaps.dump(new IndentingPrintWriter(sw), new FileDescriptor(), true /* verbose */);
+ return sw.toString();
+ }
+
+ private void doTestDumpUidPermissionMap(final int permission, final String permissionString)
+ throws Exception {
+ mUidPermissionMap.updateEntry(new S32(TEST_UID), new U8((short) permission));
+ assertDumpContains(getDump(), TEST_UID + " " + permissionString);
+ }
+
+ @Test
+ @IgnoreUpTo(Build.VERSION_CODES.S_V2)
+ public void testDumpUidPermissionMap() throws Exception {
+ doTestDumpUidPermissionMap(PERMISSION_NONE, "PERMISSION_NONE");
+ doTestDumpUidPermissionMap(PERMISSION_INTERNET | PERMISSION_UPDATE_DEVICE_STATS,
+ "PERMISSION_INTERNET PERMISSION_UPDATE_DEVICE_STATS");
+ }
+
+ @Test
+ @IgnoreUpTo(Build.VERSION_CODES.S_V2)
+ public void testDumpUidPermissionMapInvalidPermission() throws Exception {
+ doTestDumpUidPermissionMap(PERMISSION_UNINSTALLED, "PERMISSION_UNINSTALLED error!");
+ doTestDumpUidPermissionMap(PERMISSION_INTERNET | 1 << 6,
+ "PERMISSION_INTERNET PERMISSION_UNKNOWN(64)");
+ }
+
+ void doTestDumpUidOwnerMap(final int iif, final long match, final String matchString)
+ throws Exception {
+ mUidOwnerMap.updateEntry(new S32(TEST_UID), new UidOwnerValue(iif, match));
+ assertDumpContains(getDump(), TEST_UID + " " + matchString);
+ }
+
+ void doTestDumpUidOwnerMap(final long match, final String matchString) throws Exception {
+ doTestDumpUidOwnerMap(0 /* iif */, match, matchString);
+ }
+
+ @Test
+ @IgnoreUpTo(Build.VERSION_CODES.S_V2)
+ public void testDumpUidOwnerMap() throws Exception {
+ doTestDumpUidOwnerMap(HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH");
+ doTestDumpUidOwnerMap(PENALTY_BOX_MATCH, "PENALTY_BOX_MATCH");
+ doTestDumpUidOwnerMap(DOZABLE_MATCH, "DOZABLE_MATCH");
+ doTestDumpUidOwnerMap(STANDBY_MATCH, "STANDBY_MATCH");
+ doTestDumpUidOwnerMap(POWERSAVE_MATCH, "POWERSAVE_MATCH");
+ doTestDumpUidOwnerMap(RESTRICTED_MATCH, "RESTRICTED_MATCH");
+ doTestDumpUidOwnerMap(LOW_POWER_STANDBY_MATCH, "LOW_POWER_STANDBY_MATCH");
+ doTestDumpUidOwnerMap(LOCKDOWN_VPN_MATCH, "LOCKDOWN_VPN_MATCH");
+ doTestDumpUidOwnerMap(OEM_DENY_1_MATCH, "OEM_DENY_1_MATCH");
+ doTestDumpUidOwnerMap(OEM_DENY_2_MATCH, "OEM_DENY_2_MATCH");
+ doTestDumpUidOwnerMap(OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH");
+
+ doTestDumpUidOwnerMap(HAPPY_BOX_MATCH | POWERSAVE_MATCH,
+ "HAPPY_BOX_MATCH POWERSAVE_MATCH");
+ doTestDumpUidOwnerMap(DOZABLE_MATCH | LOCKDOWN_VPN_MATCH | OEM_DENY_1_MATCH,
+ "DOZABLE_MATCH LOCKDOWN_VPN_MATCH OEM_DENY_1_MATCH");
+ }
+
+ @Test
+ @IgnoreUpTo(Build.VERSION_CODES.S_V2)
+ public void testDumpUidOwnerMapWithIifMatch() throws Exception {
+ doTestDumpUidOwnerMap(TEST_IF_INDEX, IIF_MATCH, "IIF_MATCH " + TEST_IF_INDEX);
+ doTestDumpUidOwnerMap(TEST_IF_INDEX,
+ IIF_MATCH | DOZABLE_MATCH | LOCKDOWN_VPN_MATCH | OEM_DENY_1_MATCH,
+ "DOZABLE_MATCH IIF_MATCH LOCKDOWN_VPN_MATCH OEM_DENY_1_MATCH " + TEST_IF_INDEX);
+ }
+
+ @Test
+ @IgnoreUpTo(Build.VERSION_CODES.S_V2)
+ public void testDumpUidOwnerMapWithInvalidMatch() throws Exception {
+ final long invalid_match = 1L << 31;
+ doTestDumpUidOwnerMap(invalid_match, "UNKNOWN_MATCH(" + invalid_match + ")");
+ doTestDumpUidOwnerMap(DOZABLE_MATCH | invalid_match,
+ "DOZABLE_MATCH UNKNOWN_MATCH(" + invalid_match + ")");
+ }
+
+ @Test
+ @IgnoreUpTo(Build.VERSION_CODES.S_V2)
+ public void testDumpCurrentStatsMapConfig() throws Exception {
+ mConfigurationMap.updateEntry(
+ CURRENT_STATS_MAP_CONFIGURATION_KEY, new U32(STATS_SELECT_MAP_A));
+ assertDumpContains(getDump(), "current statsMap configuration: 0 SELECT_MAP_A");
+
+ mConfigurationMap.updateEntry(
+ CURRENT_STATS_MAP_CONFIGURATION_KEY, new U32(STATS_SELECT_MAP_B));
+ assertDumpContains(getDump(), "current statsMap configuration: 1 SELECT_MAP_B");
+ }
+
+ private void doTestDumpOwnerMatchConfig(final long match, final String matchString)
+ throws Exception {
+ mConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(match));
+ assertDumpContains(getDump(),
+ "current ownerMatch configuration: " + match + " " + matchString);
+ }
+
+ @Test
+ @IgnoreUpTo(Build.VERSION_CODES.S_V2)
+ public void testDumpUidOwnerMapConfig() throws Exception {
+ doTestDumpOwnerMatchConfig(HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH");
+ doTestDumpOwnerMatchConfig(PENALTY_BOX_MATCH, "PENALTY_BOX_MATCH");
+ doTestDumpOwnerMatchConfig(DOZABLE_MATCH, "DOZABLE_MATCH");
+ doTestDumpOwnerMatchConfig(STANDBY_MATCH, "STANDBY_MATCH");
+ doTestDumpOwnerMatchConfig(POWERSAVE_MATCH, "POWERSAVE_MATCH");
+ doTestDumpOwnerMatchConfig(RESTRICTED_MATCH, "RESTRICTED_MATCH");
+ doTestDumpOwnerMatchConfig(LOW_POWER_STANDBY_MATCH, "LOW_POWER_STANDBY_MATCH");
+ doTestDumpOwnerMatchConfig(IIF_MATCH, "IIF_MATCH");
+ doTestDumpOwnerMatchConfig(LOCKDOWN_VPN_MATCH, "LOCKDOWN_VPN_MATCH");
+ doTestDumpOwnerMatchConfig(OEM_DENY_1_MATCH, "OEM_DENY_1_MATCH");
+ doTestDumpOwnerMatchConfig(OEM_DENY_2_MATCH, "OEM_DENY_2_MATCH");
+ doTestDumpOwnerMatchConfig(OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH");
+
+ doTestDumpOwnerMatchConfig(HAPPY_BOX_MATCH | POWERSAVE_MATCH,
+ "HAPPY_BOX_MATCH POWERSAVE_MATCH");
+ doTestDumpOwnerMatchConfig(DOZABLE_MATCH | LOCKDOWN_VPN_MATCH | OEM_DENY_1_MATCH,
+ "DOZABLE_MATCH LOCKDOWN_VPN_MATCH OEM_DENY_1_MATCH");
+ }
+
+ @Test
+ @IgnoreUpTo(Build.VERSION_CODES.S_V2)
+ public void testDumpUidOwnerMapConfigWithInvalidMatch() throws Exception {
+ final long invalid_match = 1L << 31;
+ doTestDumpOwnerMatchConfig(invalid_match, "UNKNOWN_MATCH(" + invalid_match + ")");
+ doTestDumpOwnerMatchConfig(DOZABLE_MATCH | invalid_match,
+ "DOZABLE_MATCH UNKNOWN_MATCH(" + invalid_match + ")");
+ }
}
diff --git a/tests/unit/java/com/android/server/ConnectivityServiceTest.java b/tests/unit/java/com/android/server/ConnectivityServiceTest.java
index 7993a5c..c8aa59b 100755
--- a/tests/unit/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/unit/java/com/android/server/ConnectivityServiceTest.java
@@ -1068,38 +1068,41 @@
* @param hasInternet Indicate if network should pretend to have NET_CAPABILITY_INTERNET.
*/
public void connect(boolean validated, boolean hasInternet, boolean isStrictMode) {
- ConnectivityManager.NetworkCallback callback = null;
final ConditionVariable validatedCv = new ConditionVariable();
+ final ConditionVariable capsChangedCv = new ConditionVariable();
+ final NetworkRequest request = new NetworkRequest.Builder()
+ .addTransportType(getNetworkCapabilities().getTransportTypes()[0])
+ .clearCapabilities()
+ .build();
if (validated) {
setNetworkValid(isStrictMode);
- NetworkRequest request = new NetworkRequest.Builder()
- .addTransportType(getNetworkCapabilities().getTransportTypes()[0])
- .clearCapabilities()
- .build();
- callback = new ConnectivityManager.NetworkCallback() {
- public void onCapabilitiesChanged(Network network,
- NetworkCapabilities networkCapabilities) {
- if (network.equals(getNetwork()) &&
- networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
+ }
+ final NetworkCallback callback = new NetworkCallback() {
+ public void onCapabilitiesChanged(Network network,
+ NetworkCapabilities networkCapabilities) {
+ if (network.equals(getNetwork())) {
+ capsChangedCv.open();
+ if (networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
validatedCv.open();
}
}
- };
- mCm.registerNetworkCallback(request, callback);
- }
+ }
+ };
+ mCm.registerNetworkCallback(request, callback);
+
if (hasInternet) {
addCapability(NET_CAPABILITY_INTERNET);
}
connectWithoutInternet();
+ waitFor(capsChangedCv);
if (validated) {
// Wait for network to validate.
waitFor(validatedCv);
setNetworkInvalid(isStrictMode);
}
-
- if (callback != null) mCm.unregisterNetworkCallback(callback);
+ mCm.unregisterNetworkCallback(callback);
}
public void connectWithCaptivePortal(String redirectUrl, boolean isStrictMode) {
@@ -1605,9 +1608,9 @@
mMockVpn = new MockVpn(userId);
}
- private void mockUidNetworkingBlocked() {
+ private void mockUidNetworkingBlocked(int uid) {
doAnswer(i -> isUidBlocked(mBlockedReasons, i.getArgument(1))
- ).when(mNetworkPolicyManager).isUidNetworkingBlocked(anyInt(), anyBoolean());
+ ).when(mNetworkPolicyManager).isUidNetworkingBlocked(eq(uid), anyBoolean());
}
private boolean isUidBlocked(int blockedReasons, boolean meteredNetwork) {
@@ -8994,7 +8997,7 @@
final DetailedBlockedStatusCallback detailedCallback = new DetailedBlockedStatusCallback();
mCm.registerNetworkCallback(cellRequest, detailedCallback);
- mockUidNetworkingBlocked();
+ mockUidNetworkingBlocked(Process.myUid());
mCellNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_CELLULAR);
mCellNetworkAgent.connect(true);
@@ -9109,7 +9112,7 @@
public void testNetworkBlockedStatusBeforeAndAfterConnect() throws Exception {
final TestNetworkCallback defaultCallback = new TestNetworkCallback();
mCm.registerDefaultNetworkCallback(defaultCallback);
- mockUidNetworkingBlocked();
+ mockUidNetworkingBlocked(Process.myUid());
// No Networkcallbacks invoked before any network is active.
setBlockedReasonChanged(BLOCKED_REASON_BATTERY_SAVER);
@@ -16878,4 +16881,43 @@
verify(mTetheringManager).getTetherableWifiRegexs();
});
}
+
+ @Test
+ public void testGetNetworkInfoForUid() throws Exception {
+ // Setup and verify getNetworkInfoForUid cannot be called without Network Stack permission,
+ // when querying NetworkInfo for other uid.
+ verifyNoNetwork();
+ mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
+ mServiceContext.setPermission(NETWORK_STACK, PERMISSION_DENIED);
+ mServiceContext.setPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ PERMISSION_DENIED);
+
+ final int otherUid = Process.myUid() + 1;
+ assertNull(mCm.getActiveNetwork());
+ assertNull(mCm.getNetworkInfoForUid(mCm.getActiveNetwork(),
+ Process.myUid(), false /* ignoreBlocked */));
+ assertThrows(SecurityException.class, () -> mCm.getNetworkInfoForUid(
+ mCm.getActiveNetwork(), otherUid, false /* ignoreBlocked */));
+ withPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, () ->
+ assertNull(mCm.getNetworkInfoForUid(mCm.getActiveNetwork(),
+ otherUid, false /* ignoreBlocked */)));
+
+ // Bringing up validated wifi and verify again. Make the other uid be blocked,
+ // verify the method returns result accordingly.
+ mWiFiNetworkAgent.connect(true);
+ setBlockedReasonChanged(BLOCKED_REASON_BATTERY_SAVER);
+ mockUidNetworkingBlocked(otherUid);
+ withPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, () ->
+ verifyActiveNetwork(TRANSPORT_WIFI));
+ checkNetworkInfo(mCm.getNetworkInfoForUid(mCm.getActiveNetwork(),
+ Process.myUid(), false /* ignoreBlocked */), TYPE_WIFI, DetailedState.CONNECTED);
+ assertThrows(SecurityException.class, () -> mCm.getNetworkInfoForUid(
+ mCm.getActiveNetwork(), otherUid, false /* ignoreBlocked */));
+ withPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, () ->
+ checkNetworkInfo(mCm.getNetworkInfoForUid(mCm.getActiveNetwork(),
+ otherUid, false /* ignoreBlocked */), TYPE_WIFI, DetailedState.BLOCKED));
+ withPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, () ->
+ checkNetworkInfo(mCm.getNetworkInfoForUid(mCm.getActiveNetwork(),
+ otherUid, true /* ignoreBlocked */), TYPE_WIFI, DetailedState.CONNECTED));
+ }
}
diff --git a/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java b/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
index 6448819..2ceb00a 100644
--- a/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
+++ b/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
@@ -263,7 +263,8 @@
StatsMapValue.class);
private TestBpfMap<UidStatsMapKey, StatsMapValue> mAppUidStatsMap = new TestBpfMap<>(
UidStatsMapKey.class, StatsMapValue.class);
-
+ private TestBpfMap<S32, StatsMapValue> mIfaceStatsMap = new TestBpfMap<>(
+ S32.class, StatsMapValue.class);
private NetworkStatsService mService;
private INetworkStatsSession mSession;
private AlertObserver mAlertObserver;
@@ -503,6 +504,11 @@
}
@Override
+ public IBpfMap<S32, StatsMapValue> getIfaceStatsMap() {
+ return mIfaceStatsMap;
+ }
+
+ @Override
public boolean isDebuggable() {
return mIsDebuggable == Boolean.TRUE;
}
@@ -2552,4 +2558,25 @@
doReturn(null).when(mBpfInterfaceMapUpdater).getIfNameByIndex(10 /* index */);
doTestDumpStatsMap("unknown");
}
+
+ void doTestDumpIfaceStatsMap(final String expectedIfaceName) throws Exception {
+ mIfaceStatsMap.insertEntry(new S32(10), new StatsMapValue(3, 3000, 3, 3000));
+
+ final String dump = getDump();
+ assertDumpContains(dump, "mIfaceStatsMap: OK");
+ assertDumpContains(dump, "ifaceIndex ifaceName rxBytes rxPackets txBytes txPackets");
+ assertDumpContains(dump, "10 " + expectedIfaceName + " 3000 3 3000 3");
+ }
+
+ @Test
+ public void testDumpIfaceStatsMap() throws Exception {
+ doReturn("wlan0").when(mBpfInterfaceMapUpdater).getIfNameByIndex(10 /* index */);
+ doTestDumpIfaceStatsMap("wlan0");
+ }
+
+ @Test
+ public void testDumpIfaceStatsMapUnknownInterface() throws Exception {
+ doReturn(null).when(mBpfInterfaceMapUpdater).getIfNameByIndex(10 /* index */);
+ doTestDumpIfaceStatsMap("unknown");
+ }
}