Merge "Remove unnecessary dropShellPermissionIdentity" into main
diff --git a/TEST_MAPPING b/TEST_MAPPING
index 520124d..ab3ed66 100644
--- a/TEST_MAPPING
+++ b/TEST_MAPPING
@@ -100,9 +100,6 @@
"name": "TetheringIntegrationTests"
},
{
- "name": "traffic_controller_unit_test"
- },
- {
"name": "libnetworkstats_test"
},
{
@@ -134,10 +131,6 @@
"name": "dns_helper_unit_test"
},
{
- "name": "traffic_controller_unit_test",
- "keywords": ["netd-device-kernel-4.9", "netd-device-kernel-4.14"]
- },
- {
"name": "FrameworksNetDeflakeTest"
},
// Postsubmit on virtual devices to monitor flakiness of @SkipPresubmit methods
@@ -274,9 +267,6 @@
]
},
{
- "name": "traffic_controller_unit_test[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk+com.google.android.resolv.apex+com.google.android.tethering.apex]"
- },
- {
"name": "libnetworkstats_test[CaptivePortalLoginGoogle.apk+NetworkStackGoogle.apk+com.google.android.resolv.apex+com.google.android.tethering.apex]"
},
{
diff --git a/Tethering/src/com/android/networkstack/tethering/TetheringDependencies.java b/Tethering/src/com/android/networkstack/tethering/TetheringDependencies.java
index c6468a0..c274165 100644
--- a/Tethering/src/com/android/networkstack/tethering/TetheringDependencies.java
+++ b/Tethering/src/com/android/networkstack/tethering/TetheringDependencies.java
@@ -23,7 +23,7 @@
import android.content.Context;
import android.net.INetd;
import android.net.RoutingCoordinatorManager;
-import android.net.connectivity.TiramisuConnectivityInternalApiUtil;
+import android.net.connectivity.ConnectivityInternalApiUtil;
import android.net.ip.IpServer;
import android.os.Build;
import android.os.Handler;
@@ -133,7 +133,7 @@
public LateSdk<RoutingCoordinatorManager> getRoutingCoordinator(Context context) {
if (!SdkLevel.isAtLeastS()) return new LateSdk<>(null);
return new LateSdk<>(
- TiramisuConnectivityInternalApiUtil.getRoutingCoordinatorManager(context));
+ ConnectivityInternalApiUtil.getRoutingCoordinatorManager(context));
}
/**
diff --git a/Tethering/src/com/android/networkstack/tethering/wear/CompanionDeviceManagerProxy.java b/Tethering/src/com/android/networkstack/tethering/wear/CompanionDeviceManagerProxy.java
index e94febb..e845f3f 100644
--- a/Tethering/src/com/android/networkstack/tethering/wear/CompanionDeviceManagerProxy.java
+++ b/Tethering/src/com/android/networkstack/tethering/wear/CompanionDeviceManagerProxy.java
@@ -19,7 +19,7 @@
import android.companion.AssociationInfo;
import android.companion.CompanionDeviceManager;
import android.content.Context;
-import android.net.connectivity.TiramisuConnectivityInternalApiUtil;
+import android.net.connectivity.ConnectivityInternalApiUtil;
import android.net.wear.ICompanionDeviceManagerProxy;
import android.os.Build;
import android.os.RemoteException;
@@ -39,7 +39,7 @@
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
public CompanionDeviceManagerProxy(Context context) {
mService = ICompanionDeviceManagerProxy.Stub.asInterface(
- TiramisuConnectivityInternalApiUtil.getCompanionDeviceManagerProxyService(context));
+ ConnectivityInternalApiUtil.getCompanionDeviceManagerProxyService(context));
}
/**
diff --git a/Tethering/tests/unit/src/android/net/ip/IpServerTest.java b/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
index 98b624b..a7064e8 100644
--- a/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
+++ b/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
@@ -35,15 +35,9 @@
import static android.net.ip.IpServer.STATE_TETHERED;
import static android.net.ip.IpServer.STATE_UNAVAILABLE;
import static android.net.ip.IpServer.getTetherableIpv6Prefixes;
-import static android.system.OsConstants.ETH_P_IPV6;
import static com.android.modules.utils.build.SdkLevel.isAtLeastT;
import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
-import static com.android.net.module.util.netlink.NetlinkConstants.RTM_DELNEIGH;
-import static com.android.net.module.util.netlink.NetlinkConstants.RTM_NEWNEIGH;
-import static com.android.net.module.util.netlink.StructNdMsg.NUD_FAILED;
-import static com.android.net.module.util.netlink.StructNdMsg.NUD_REACHABLE;
-import static com.android.net.module.util.netlink.StructNdMsg.NUD_STALE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -57,7 +51,6 @@
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
@@ -66,7 +59,6 @@
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -83,8 +75,6 @@
import android.net.MacAddress;
import android.net.RouteInfo;
import android.net.RoutingCoordinatorManager;
-import android.net.TetherOffloadRuleParcel;
-import android.net.TetherStatsParcel;
import android.net.dhcp.DhcpServerCallbacks;
import android.net.dhcp.DhcpServingParamsParcel;
import android.net.dhcp.IDhcpEventCallbacks;
@@ -96,40 +86,17 @@
import android.os.RemoteException;
import android.os.test.TestLooper;
import android.text.TextUtils;
-import android.util.ArrayMap;
-import android.util.ArraySet;
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
import com.android.modules.utils.build.SdkLevel;
-import com.android.net.module.util.BpfMap;
import com.android.net.module.util.InterfaceParams;
-import com.android.net.module.util.NetworkStackConstants;
import com.android.net.module.util.SdkUtil.LateSdk;
import com.android.net.module.util.SharedLog;
-import com.android.net.module.util.Struct.S32;
-import com.android.net.module.util.bpf.Tether4Key;
-import com.android.net.module.util.bpf.Tether4Value;
-import com.android.net.module.util.bpf.TetherStatsKey;
-import com.android.net.module.util.bpf.TetherStatsValue;
-import com.android.net.module.util.ip.ConntrackMonitor;
import com.android.net.module.util.ip.IpNeighborMonitor;
-import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEvent;
-import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEventConsumer;
import com.android.networkstack.tethering.BpfCoordinator;
-import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
-import com.android.networkstack.tethering.BpfCoordinator.Ipv6DownstreamRule;
import com.android.networkstack.tethering.PrivateAddressCoordinator;
-import com.android.networkstack.tethering.Tether6Value;
-import com.android.networkstack.tethering.TetherDevKey;
-import com.android.networkstack.tethering.TetherDevValue;
-import com.android.networkstack.tethering.TetherDownstream6Key;
-import com.android.networkstack.tethering.TetherLimitKey;
-import com.android.networkstack.tethering.TetherLimitValue;
-import com.android.networkstack.tethering.TetherUpstream6Key;
import com.android.networkstack.tethering.TetheringConfiguration;
import com.android.networkstack.tethering.metrics.TetheringMetrics;
import com.android.networkstack.tethering.util.InterfaceSet;
@@ -143,18 +110,13 @@
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
-import org.mockito.ArgumentMatcher;
import org.mockito.Captor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
-import org.mockito.verification.VerificationMode;
import java.net.Inet4Address;
-import java.net.Inet6Address;
import java.net.InetAddress;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
import java.util.List;
import java.util.Set;
@@ -219,16 +181,8 @@
new LateSdk<>(SdkLevel.isAtLeastS() ? mock(RoutingCoordinatorManager.class) : null);
@Mock private NetworkStatsManager mStatsManager;
@Mock private TetheringConfiguration mTetherConfig;
- @Mock private ConntrackMonitor mConntrackMonitor;
@Mock private TetheringMetrics mTetheringMetrics;
- @Mock private BpfMap<Tether4Key, Tether4Value> mBpfDownstream4Map;
- @Mock private BpfMap<Tether4Key, Tether4Value> mBpfUpstream4Map;
- @Mock private BpfMap<TetherDownstream6Key, Tether6Value> mBpfDownstream6Map;
- @Mock private BpfMap<TetherUpstream6Key, Tether6Value> mBpfUpstream6Map;
- @Mock private BpfMap<TetherStatsKey, TetherStatsValue> mBpfStatsMap;
- @Mock private BpfMap<TetherLimitKey, TetherLimitValue> mBpfLimitMap;
- @Mock private BpfMap<TetherDevKey, TetherDevValue> mBpfDevMap;
- @Mock private BpfMap<S32, S32> mBpfErrorMap;
+ @Mock private BpfCoordinator mBpfCoordinator;
@Captor private ArgumentCaptor<DhcpServingParamsParcel> mDhcpParamsCaptor;
@@ -238,9 +192,6 @@
ArgumentCaptor.forClass(LinkProperties.class);
private IpServer mIpServer;
private InterfaceConfigurationParcel mInterfaceConfiguration;
- private NeighborEventConsumer mNeighborEventConsumer;
- private BpfCoordinator mBpfCoordinator;
- private BpfCoordinator.Dependencies mBpfDeps;
private void initStateMachine(int interfaceType) throws Exception {
initStateMachine(interfaceType, false /* usingLegacyDhcp */, DEFAULT_USING_BPF_OFFLOAD);
@@ -262,22 +213,20 @@
mInterfaceConfiguration.prefixLength = BLUETOOTH_DHCP_PREFIX_LENGTH;
}
- ArgumentCaptor<NeighborEventConsumer> neighborCaptor =
- ArgumentCaptor.forClass(NeighborEventConsumer.class);
- doReturn(mIpNeighborMonitor).when(mDependencies).getIpNeighborMonitor(any(), any(),
- neighborCaptor.capture());
+ doReturn(mIpNeighborMonitor).when(mDependencies).getIpNeighborMonitor(any(), any(), any());
when(mTetherConfig.isBpfOffloadEnabled()).thenReturn(usingBpfOffload);
when(mTetherConfig.useLegacyDhcpServer()).thenReturn(usingLegacyDhcp);
when(mTetherConfig.getP2pLeasesSubnetPrefixLength()).thenReturn(P2P_SUBNET_PREFIX_LENGTH);
+ when(mBpfCoordinator.isUsingBpfOffload()).thenReturn(usingBpfOffload);
mIpServer = createIpServer(interfaceType);
+ verify(mIpNeighborMonitor).start();
mIpServer.start();
- mNeighborEventConsumer = neighborCaptor.getValue();
// Starting the state machine always puts us in a consistent state and notifies
// the rest of the world that we've changed from an unknown to available state.
mLooper.dispatchAll();
- reset(mNetd, mCallback);
+ reset(mNetd, mCallback, mIpNeighborMonitor);
when(mRaDaemon.start()).thenReturn(true);
}
@@ -294,23 +243,17 @@
initStateMachine(interfaceType, usingLegacyDhcp, usingBpfOffload);
dispatchCommand(IpServer.CMD_TETHER_REQUESTED, STATE_TETHERED);
if (upstreamIface != null) {
+ InterfaceParams interfaceParams = mDependencies.getInterfaceParams(upstreamIface);
+ assertNotNull("missing upstream interface: " + upstreamIface, interfaceParams);
LinkProperties lp = new LinkProperties();
lp.setInterfaceName(upstreamIface);
lp.setLinkAddresses(upstreamAddresses);
dispatchTetherConnectionChanged(upstreamIface, lp, 0);
- if (usingBpfOffload && !lp.getLinkAddresses().isEmpty()) {
- Set<IpPrefix> upstreamPrefixes = getTetherableIpv6Prefixes(lp.getLinkAddresses());
- InterfaceParams interfaceParams = mDependencies.getInterfaceParams(upstreamIface);
- assertNotNull("missing upstream interface: " + upstreamIface, interfaceParams);
- verify(mBpfCoordinator).updateAllIpv6Rules(
- mIpServer, TEST_IFACE_PARAMS, interfaceParams.index, upstreamPrefixes);
- verifyStartUpstreamIpv6Forwarding(null, interfaceParams.index, upstreamPrefixes);
- } else {
- verifyNoUpstreamIpv6ForwardingChange(null);
- }
+ Set<IpPrefix> upstreamPrefixes = getTetherableIpv6Prefixes(lp.getLinkAddresses());
+ verify(mBpfCoordinator).updateAllIpv6Rules(
+ mIpServer, TEST_IFACE_PARAMS, interfaceParams.index, upstreamPrefixes);
}
- reset(mCallback, mAddressCoordinator);
- resetNetdBpfMapAndCoordinator();
+ reset(mNetd, mBpfCoordinator, mCallback, mAddressCoordinator);
when(mAddressCoordinator.requestDownstreamAddress(any(), anyInt(),
anyBoolean())).thenReturn(mTestAddress);
}
@@ -363,80 +306,6 @@
private IpServer createIpServer(final int interfaceType) {
mLooper = new TestLooper();
mHandler = new Handler(mLooper.getLooper());
- mBpfDeps = new BpfCoordinator.Dependencies() {
- @NonNull
- public Handler getHandler() {
- return mHandler;
- }
-
- @NonNull
- public INetd getNetd() {
- return mNetd;
- }
-
- @NonNull
- public NetworkStatsManager getNetworkStatsManager() {
- return mStatsManager;
- }
-
- @NonNull
- public SharedLog getSharedLog() {
- return mSharedLog;
- }
-
- @Nullable
- public TetheringConfiguration getTetherConfig() {
- return mTetherConfig;
- }
-
- @NonNull
- public ConntrackMonitor getConntrackMonitor(
- ConntrackMonitor.ConntrackEventConsumer consumer) {
- return mConntrackMonitor;
- }
-
- @Nullable
- public BpfMap<Tether4Key, Tether4Value> getBpfDownstream4Map() {
- return mBpfDownstream4Map;
- }
-
- @Nullable
- public BpfMap<Tether4Key, Tether4Value> getBpfUpstream4Map() {
- return mBpfUpstream4Map;
- }
-
- @Nullable
- public BpfMap<TetherDownstream6Key, Tether6Value> getBpfDownstream6Map() {
- return mBpfDownstream6Map;
- }
-
- @Nullable
- public BpfMap<TetherUpstream6Key, Tether6Value> getBpfUpstream6Map() {
- return mBpfUpstream6Map;
- }
-
- @Nullable
- public BpfMap<TetherStatsKey, TetherStatsValue> getBpfStatsMap() {
- return mBpfStatsMap;
- }
-
- @Nullable
- public BpfMap<TetherLimitKey, TetherLimitValue> getBpfLimitMap() {
- return mBpfLimitMap;
- }
-
- @Nullable
- public BpfMap<TetherDevKey, TetherDevValue> getBpfDevMap() {
- return mBpfDevMap;
- }
-
- @Nullable
- public BpfMap<S32, S32> getBpfErrorMap() {
- return mBpfErrorMap;
- }
- };
-
- mBpfCoordinator = spy(new BpfCoordinator(mBpfDeps));
return new IpServer(IFACE_NAME, mHandler, interfaceType, mSharedLog, mNetd, mBpfCoordinator,
mRoutingCoordinatorManager, mCallback, mTetherConfig, mAddressCoordinator,
mTetheringMetrics, mDependencies);
@@ -886,346 +755,19 @@
verify(mDependencies, never()).makeDhcpServer(any(), any(), any());
}
- private InetAddress addr(String addr) throws Exception {
- return InetAddresses.parseNumericAddress(addr);
- }
-
- private void recvNewNeigh(int ifindex, InetAddress addr, short nudState, MacAddress mac) {
- mNeighborEventConsumer.accept(new NeighborEvent(0, RTM_NEWNEIGH, ifindex, addr,
- nudState, mac));
- mLooper.dispatchAll();
- }
-
- private void recvDelNeigh(int ifindex, InetAddress addr, short nudState, MacAddress mac) {
- mNeighborEventConsumer.accept(new NeighborEvent(0, RTM_DELNEIGH, ifindex, addr,
- nudState, mac));
- mLooper.dispatchAll();
- }
-
- /**
- * Custom ArgumentMatcher for TetherOffloadRuleParcel. This is needed because generated stable
- * AIDL classes don't have equals(), so we cannot just use eq(). A custom assert, such as:
- *
- * private void checkFooCalled(StableParcelable p, ...) {
- * ArgumentCaptor<FooParam> captor = ArgumentCaptor.forClass(FooParam.class);
- * verify(mMock).foo(captor.capture());
- * Foo foo = captor.getValue();
- * assertFooMatchesExpectations(foo);
- * }
- *
- * almost works, but not quite. This is because if the code under test calls foo() twice, the
- * first call to checkFooCalled() matches both the calls, putting both calls into the captor,
- * and then fails with TooManyActualInvocations. It also makes it harder to use other mockito
- * features such as never(), inOrder(), etc.
- *
- * This approach isn't great because if the match fails, the error message is unhelpful
- * (actual: "android.net.TetherOffloadRuleParcel@8c827b0" or some such), but at least it does
- * work.
- *
- * TODO: consider making the error message more readable by adding a method that catching the
- * AssertionFailedError and throwing a new assertion with more details. See
- * NetworkMonitorTest#verifyNetworkTested.
- *
- * See ConnectivityServiceTest#assertRoutesAdded for an alternative approach which solves the
- * TooManyActualInvocations problem described above by forcing the caller of the custom assert
- * method to specify all expected invocations in one call. This is useful when the stable
- * parcelable class being asserted on has a corresponding Java object (eg., RouteInfo and
- * RouteInfoParcelable), and the caller can just pass in a list of them. It not useful here
- * because there is no such object.
- */
- private static class TetherOffloadRuleParcelMatcher implements
- ArgumentMatcher<TetherOffloadRuleParcel> {
- public final int upstreamIfindex;
- public final InetAddress dst;
- public final MacAddress dstMac;
-
- TetherOffloadRuleParcelMatcher(int upstreamIfindex, InetAddress dst, MacAddress dstMac) {
- this.upstreamIfindex = upstreamIfindex;
- this.dst = dst;
- this.dstMac = dstMac;
- }
-
- public boolean matches(TetherOffloadRuleParcel parcel) {
- return upstreamIfindex == parcel.inputInterfaceIndex
- && (TEST_IFACE_PARAMS.index == parcel.outputInterfaceIndex)
- && Arrays.equals(dst.getAddress(), parcel.destination)
- && (128 == parcel.prefixLength)
- && Arrays.equals(TEST_IFACE_PARAMS.macAddr.toByteArray(), parcel.srcL2Address)
- && Arrays.equals(dstMac.toByteArray(), parcel.dstL2Address);
- }
-
- public String toString() {
- return String.format("TetherOffloadRuleParcelMatcher(%d, %s, %s",
- upstreamIfindex, dst.getHostAddress(), dstMac);
- }
- }
-
- @NonNull
- private static TetherOffloadRuleParcel matches(
- int upstreamIfindex, InetAddress dst, MacAddress dstMac) {
- return argThat(new TetherOffloadRuleParcelMatcher(upstreamIfindex, dst, dstMac));
- }
-
- @NonNull
- private static Ipv6DownstreamRule makeDownstreamRule(int upstreamIfindex,
- @NonNull InetAddress dst, @NonNull MacAddress dstMac) {
- return new Ipv6DownstreamRule(upstreamIfindex, TEST_IFACE_PARAMS.index,
- (Inet6Address) dst, TEST_IFACE_PARAMS.macAddr, dstMac);
- }
-
- @NonNull
- private static TetherDownstream6Key makeDownstream6Key(int upstreamIfindex,
- @NonNull MacAddress upstreamMac, @NonNull final InetAddress dst) {
- return new TetherDownstream6Key(upstreamIfindex, upstreamMac, dst.getAddress());
- }
-
- @NonNull
- private static Tether6Value makeDownstream6Value(@NonNull final MacAddress dstMac) {
- return new Tether6Value(TEST_IFACE_PARAMS.index, dstMac,
- TEST_IFACE_PARAMS.macAddr, ETH_P_IPV6, NetworkStackConstants.ETHER_MTU);
- }
-
- private static long prefixToLong(IpPrefix prefix) {
- return ByteBuffer.wrap(prefix.getRawAddress()).getLong();
- }
-
- private <T> T verifyWithOrder(@Nullable InOrder inOrder, @NonNull T t) {
- return verifyWithOrder(inOrder, t, times(1));
- }
-
- private <T> T verifyWithOrder(@Nullable InOrder inOrder, @NonNull T t, VerificationMode mode) {
- if (inOrder != null) {
- return inOrder.verify(t, mode);
- } else {
- return verify(t, mode);
- }
- }
-
- private void verifyTetherOffloadRuleAdd(@Nullable InOrder inOrder, int upstreamIfindex,
- @NonNull MacAddress upstreamMac, @NonNull final InetAddress dst,
- @NonNull final MacAddress dstMac) throws Exception {
- if (mBpfDeps.isAtLeastS()) {
- verifyWithOrder(inOrder, mBpfDownstream6Map).updateEntry(
- makeDownstream6Key(upstreamIfindex, upstreamMac, dst),
- makeDownstream6Value(dstMac));
- } else {
- verifyWithOrder(inOrder, mNetd).tetherOffloadRuleAdd(matches(upstreamIfindex, dst,
- dstMac));
- }
- }
-
- private void verifyNeverTetherOffloadRuleAdd(int upstreamIfindex,
- @NonNull MacAddress upstreamMac, @NonNull final InetAddress dst,
- @NonNull final MacAddress dstMac) throws Exception {
- if (mBpfDeps.isAtLeastS()) {
- verify(mBpfDownstream6Map, never()).updateEntry(
- makeDownstream6Key(upstreamIfindex, upstreamMac, dst),
- makeDownstream6Value(dstMac));
- } else {
- verify(mNetd, never()).tetherOffloadRuleAdd(matches(upstreamIfindex, dst, dstMac));
- }
- }
-
- private void verifyNeverTetherOffloadRuleAdd() throws Exception {
- if (mBpfDeps.isAtLeastS()) {
- verify(mBpfDownstream6Map, never()).updateEntry(any(), any());
- } else {
- verify(mNetd, never()).tetherOffloadRuleAdd(any());
- }
- }
-
- private void verifyTetherOffloadRuleRemove(@Nullable InOrder inOrder, int upstreamIfindex,
- @NonNull MacAddress upstreamMac, @NonNull final InetAddress dst,
- @NonNull final MacAddress dstMac) throws Exception {
- if (mBpfDeps.isAtLeastS()) {
- verifyWithOrder(inOrder, mBpfDownstream6Map).deleteEntry(makeDownstream6Key(
- upstreamIfindex, upstreamMac, dst));
- } else {
- // |dstMac| is not required for deleting rules. Used bacause tetherOffloadRuleRemove
- // uses a whole rule to be a argument.
- // See system/netd/server/TetherController.cpp/TetherController#removeOffloadRule.
- verifyWithOrder(inOrder, mNetd).tetherOffloadRuleRemove(matches(upstreamIfindex, dst,
- dstMac));
- }
- }
-
- private void verifyNeverTetherOffloadRuleRemove() throws Exception {
- if (mBpfDeps.isAtLeastS()) {
- verify(mBpfDownstream6Map, never()).deleteEntry(any());
- } else {
- verify(mNetd, never()).tetherOffloadRuleRemove(any());
- }
- }
-
- private void verifyStartUpstreamIpv6Forwarding(@Nullable InOrder inOrder, int upstreamIfindex,
- @NonNull Set<IpPrefix> upstreamPrefixes) throws Exception {
- if (!mBpfDeps.isAtLeastS()) return;
- ArrayMap<TetherUpstream6Key, Tether6Value> expected = new ArrayMap<>();
- for (IpPrefix upstreamPrefix : upstreamPrefixes) {
- long prefix64 = prefixToLong(upstreamPrefix);
- final TetherUpstream6Key key = new TetherUpstream6Key(TEST_IFACE_PARAMS.index,
- TEST_IFACE_PARAMS.macAddr, prefix64);
- final Tether6Value value = new Tether6Value(upstreamIfindex,
- MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS,
- ETH_P_IPV6, NetworkStackConstants.ETHER_MTU);
- expected.put(key, value);
- }
- ArgumentCaptor<TetherUpstream6Key> keyCaptor =
- ArgumentCaptor.forClass(TetherUpstream6Key.class);
- ArgumentCaptor<Tether6Value> valueCaptor =
- ArgumentCaptor.forClass(Tether6Value.class);
- verifyWithOrder(inOrder, mBpfUpstream6Map, times(expected.size())).insertEntry(
- keyCaptor.capture(), valueCaptor.capture());
- List<TetherUpstream6Key> keys = keyCaptor.getAllValues();
- List<Tether6Value> values = valueCaptor.getAllValues();
- ArrayMap<TetherUpstream6Key, Tether6Value> captured = new ArrayMap<>();
- for (int i = 0; i < keys.size(); i++) {
- captured.put(keys.get(i), values.get(i));
- }
- assertEquals(expected, captured);
- }
-
- private void verifyStopUpstreamIpv6Forwarding(@Nullable InOrder inOrder,
- @NonNull Set<IpPrefix> upstreamPrefixes) throws Exception {
- if (!mBpfDeps.isAtLeastS()) return;
- Set<TetherUpstream6Key> expected = new ArraySet<>();
- for (IpPrefix upstreamPrefix : upstreamPrefixes) {
- long prefix64 = prefixToLong(upstreamPrefix);
- final TetherUpstream6Key key = new TetherUpstream6Key(TEST_IFACE_PARAMS.index,
- TEST_IFACE_PARAMS.macAddr, prefix64);
- expected.add(key);
- }
- ArgumentCaptor<TetherUpstream6Key> keyCaptor =
- ArgumentCaptor.forClass(TetherUpstream6Key.class);
- verifyWithOrder(inOrder, mBpfUpstream6Map, times(expected.size())).deleteEntry(
- keyCaptor.capture());
- assertEquals(expected, new ArraySet(keyCaptor.getAllValues()));
- }
-
- private void verifyNoUpstreamIpv6ForwardingChange(@Nullable InOrder inOrder) throws Exception {
- if (!mBpfDeps.isAtLeastS()) return;
- if (inOrder != null) {
- inOrder.verify(mBpfUpstream6Map, never()).deleteEntry(any());
- inOrder.verify(mBpfUpstream6Map, never()).insertEntry(any(), any());
- inOrder.verify(mBpfUpstream6Map, never()).updateEntry(any(), any());
- } else {
- verify(mBpfUpstream6Map, never()).deleteEntry(any());
- verify(mBpfUpstream6Map, never()).insertEntry(any(), any());
- verify(mBpfUpstream6Map, never()).updateEntry(any(), any());
- }
- }
-
- @NonNull
- private static TetherStatsParcel buildEmptyTetherStatsParcel(int ifIndex) {
- TetherStatsParcel parcel = new TetherStatsParcel();
- parcel.ifIndex = ifIndex;
- return parcel;
- }
-
- private void resetNetdBpfMapAndCoordinator() throws Exception {
- reset(mNetd, mBpfDownstream6Map, mBpfUpstream6Map, mBpfCoordinator);
- // When the last rule is removed, tetherOffloadGetAndClearStats will log a WTF (and
- // potentially crash the test) if the stats map is empty.
- when(mNetd.tetherOffloadGetStats()).thenReturn(new TetherStatsParcel[0]);
- when(mNetd.tetherOffloadGetAndClearStats(UPSTREAM_IFINDEX))
- .thenReturn(buildEmptyTetherStatsParcel(UPSTREAM_IFINDEX));
- when(mNetd.tetherOffloadGetAndClearStats(UPSTREAM_IFINDEX2))
- .thenReturn(buildEmptyTetherStatsParcel(UPSTREAM_IFINDEX2));
- // When the last rule is removed, tetherOffloadGetAndClearStats will log a WTF (and
- // potentially crash the test) if the stats map is empty.
- final TetherStatsValue allZeros = new TetherStatsValue(0, 0, 0, 0, 0, 0);
- when(mBpfStatsMap.getValue(new TetherStatsKey(UPSTREAM_IFINDEX))).thenReturn(allZeros);
- when(mBpfStatsMap.getValue(new TetherStatsKey(UPSTREAM_IFINDEX2))).thenReturn(allZeros);
- }
-
@Test
- public void addRemoveipv6ForwardingRules() throws Exception {
+ public void ipv6UpstreamInterfaceChanges() throws Exception {
initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
false /* usingLegacyDhcp */, DEFAULT_USING_BPF_OFFLOAD);
- final int myIfindex = TEST_IFACE_PARAMS.index;
- final int notMyIfindex = myIfindex - 1;
-
- final InetAddress neighA = InetAddresses.parseNumericAddress("2001:db8::1");
- final InetAddress neighB = InetAddresses.parseNumericAddress("2001:db8::2");
- final InetAddress neighLL = InetAddresses.parseNumericAddress("fe80::1");
- final InetAddress neighMC = InetAddresses.parseNumericAddress("ff02::1234");
- final MacAddress macNull = MacAddress.fromString("00:00:00:00:00:00");
- final MacAddress macA = MacAddress.fromString("00:00:00:00:00:0a");
- final MacAddress macB = MacAddress.fromString("11:22:33:00:00:0b");
-
- resetNetdBpfMapAndCoordinator();
- verifyNoMoreInteractions(mBpfCoordinator, mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
-
- // TODO: Perhaps verify the interaction of tetherOffloadSetInterfaceQuota and
- // tetherOffloadGetAndClearStats in netd while the rules are changed.
-
- // Events on other interfaces are ignored.
- recvNewNeigh(notMyIfindex, neighA, NUD_REACHABLE, macA);
- verifyNoMoreInteractions(mBpfCoordinator, mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
-
- // Events on this interface are received and sent to BpfCoordinator.
- recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, macA);
- verify(mBpfCoordinator).addIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighA, macA));
- verifyTetherOffloadRuleAdd(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macA);
- resetNetdBpfMapAndCoordinator();
-
- recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, macB);
- verify(mBpfCoordinator).addIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighB, macB));
- verifyTetherOffloadRuleAdd(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
- resetNetdBpfMapAndCoordinator();
-
- // Link-local and multicast neighbors are ignored.
- recvNewNeigh(myIfindex, neighLL, NUD_REACHABLE, macA);
- verifyNoMoreInteractions(mBpfCoordinator, mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
- recvNewNeigh(myIfindex, neighMC, NUD_REACHABLE, macA);
- verifyNoMoreInteractions(mBpfCoordinator, mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
-
- // A neighbor that is no longer valid causes the rule to be removed.
- // NUD_FAILED events do not have a MAC address.
- recvNewNeigh(myIfindex, neighA, NUD_FAILED, null);
- verify(mBpfCoordinator).removeIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighA, macNull));
- verifyTetherOffloadRuleRemove(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macNull);
- resetNetdBpfMapAndCoordinator();
-
- // A neighbor that is deleted causes the rule to be removed.
- recvDelNeigh(myIfindex, neighB, NUD_STALE, macB);
- verify(mBpfCoordinator).removeIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighB, macNull));
- verifyTetherOffloadRuleRemove(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macNull);
- resetNetdBpfMapAndCoordinator();
-
// Upstream interface changes result in updating the rules.
- recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, macA);
- recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, macB);
- resetNetdBpfMapAndCoordinator();
-
- InOrder inOrder = inOrder(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
LinkProperties lp = new LinkProperties();
lp.setInterfaceName(UPSTREAM_IFACE2);
lp.setLinkAddresses(UPSTREAM_ADDRESSES);
dispatchTetherConnectionChanged(UPSTREAM_IFACE2, lp, -1);
verify(mBpfCoordinator).updateAllIpv6Rules(
mIpServer, TEST_IFACE_PARAMS, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES);
- verifyTetherOffloadRuleRemove(inOrder,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macA);
- verifyTetherOffloadRuleRemove(inOrder,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
- verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES);
- verifyStartUpstreamIpv6Forwarding(inOrder, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES);
- verifyTetherOffloadRuleAdd(inOrder,
- UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighA, macA);
- verifyTetherOffloadRuleAdd(inOrder,
- UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighB, macB);
- verifyNoUpstreamIpv6ForwardingChange(inOrder);
- resetNetdBpfMapAndCoordinator();
+ reset(mBpfCoordinator);
// Upstream link addresses change result in updating the rules.
LinkProperties lp2 = new LinkProperties();
@@ -1234,17 +776,7 @@
dispatchTetherConnectionChanged(UPSTREAM_IFACE2, lp2, -1);
verify(mBpfCoordinator).updateAllIpv6Rules(
mIpServer, TEST_IFACE_PARAMS, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
- verifyTetherOffloadRuleRemove(inOrder,
- UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighA, macA);
- verifyTetherOffloadRuleRemove(inOrder,
- UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighB, macB);
- verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES);
- verifyStartUpstreamIpv6Forwarding(inOrder, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
- verifyTetherOffloadRuleAdd(inOrder,
- UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighA, macA);
- verifyTetherOffloadRuleAdd(inOrder,
- UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighB, macB);
- resetNetdBpfMapAndCoordinator();
+ reset(mBpfCoordinator);
// When the upstream is lost, rules are removed.
dispatchTetherConnectionChanged(null, null, 0);
@@ -1254,156 +786,51 @@
// See dispatchTetherConnectionChanged.
verify(mBpfCoordinator, times(2)).updateAllIpv6Rules(
mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
- verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES2);
- verifyTetherOffloadRuleRemove(null,
- UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighA, macA);
- verifyTetherOffloadRuleRemove(null,
- UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighB, macB);
- // Upstream lost doesn't clear the downstream rules from BpfCoordinator.
- // Do that here.
- recvDelNeigh(myIfindex, neighA, NUD_STALE, macA);
- recvDelNeigh(myIfindex, neighB, NUD_STALE, macB);
- verify(mBpfCoordinator).removeIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(NO_UPSTREAM, neighA, macNull));
- verify(mBpfCoordinator).removeIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(NO_UPSTREAM, neighB, macNull));
- resetNetdBpfMapAndCoordinator();
+ reset(mBpfCoordinator);
- // If the upstream is IPv4-only, no IPv6 rules are added to BPF map.
+ // If the upstream is IPv4-only, no rules are added.
dispatchTetherConnectionChanged(UPSTREAM_IFACE);
- resetNetdBpfMapAndCoordinator();
- recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, macA);
- verifyNoUpstreamIpv6ForwardingChange(null);
- // Downstream rules are only added to BpfCoordinator but not BPF map.
- verify(mBpfCoordinator).addIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(NO_UPSTREAM, neighA, macA));
- verifyNeverTetherOffloadRuleAdd();
- verifyNoMoreInteractions(mBpfCoordinator, mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+ verify(mBpfCoordinator, never()).updateAllIpv6Rules(
+ mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
+ reset(mBpfCoordinator);
- // Rules can be added again once upstream IPv6 connectivity is available. The existing rules
- // with an upstream of NO_UPSTREAM are reapplied.
+ // Rules are added again once upstream IPv6 connectivity is available.
lp.setInterfaceName(UPSTREAM_IFACE);
dispatchTetherConnectionChanged(UPSTREAM_IFACE, lp, -1);
- verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
- verify(mBpfCoordinator).addIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighA, macA));
- verifyTetherOffloadRuleAdd(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macA);
- recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, macB);
- verify(mBpfCoordinator).addIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighB, macB));
- verifyTetherOffloadRuleAdd(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
+ verify(mBpfCoordinator).updateAllIpv6Rules(
+ mIpServer, TEST_IFACE_PARAMS, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
+ reset(mBpfCoordinator);
// If upstream IPv6 connectivity is lost, rules are removed.
- resetNetdBpfMapAndCoordinator();
dispatchTetherConnectionChanged(UPSTREAM_IFACE, null, 0);
verify(mBpfCoordinator).updateAllIpv6Rules(
mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
- verifyTetherOffloadRuleRemove(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
- verifyStopUpstreamIpv6Forwarding(null, UPSTREAM_PREFIXES);
+ reset(mBpfCoordinator);
- // When upstream IPv6 connectivity comes back, upstream rules are added and downstream rules
- // are reapplied.
+ // When upstream IPv6 connectivity comes back, rules are added.
lp.setInterfaceName(UPSTREAM_IFACE);
dispatchTetherConnectionChanged(UPSTREAM_IFACE, lp, -1);
- verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
- verify(mBpfCoordinator).addIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighA, macA));
- verifyTetherOffloadRuleAdd(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macA);
- verify(mBpfCoordinator).addIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighB, macB));
- verifyTetherOffloadRuleAdd(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
- resetNetdBpfMapAndCoordinator();
+ verify(mBpfCoordinator).updateAllIpv6Rules(
+ mIpServer, TEST_IFACE_PARAMS, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
+ reset(mBpfCoordinator);
// When the downstream interface goes down, rules are removed.
mIpServer.stop();
mLooper.dispatchAll();
verify(mBpfCoordinator).clearAllIpv6Rules(mIpServer);
- verifyStopUpstreamIpv6Forwarding(null, UPSTREAM_PREFIXES);
- verifyTetherOffloadRuleRemove(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macA);
- verifyTetherOffloadRuleRemove(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
- verify(mIpNeighborMonitor).stop();
- resetNetdBpfMapAndCoordinator();
- }
-
- @Test
- public void enableDisableUsingBpfOffload() throws Exception {
- final int myIfindex = TEST_IFACE_PARAMS.index;
- final InetAddress neigh = InetAddresses.parseNumericAddress("2001:db8::1");
- final MacAddress macA = MacAddress.fromString("00:00:00:00:00:0a");
- final MacAddress macNull = MacAddress.fromString("00:00:00:00:00:00");
-
- // Expect that rules can be only added/removed when the BPF offload config is enabled.
- // Note that the BPF offload disabled case is not a realistic test case. Because IP
- // neighbor monitor doesn't start if BPF offload is disabled, there should have no
- // neighbor event listening. This is used for testing the protection check just in case.
- // TODO: Perhaps remove the BPF offload disabled case test once this check isn't needed
- // anymore.
-
- // [1] Enable BPF offload.
- // A neighbor that is added or deleted causes the rule to be added or removed.
- initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
- false /* usingLegacyDhcp */, true /* usingBpfOffload */);
- resetNetdBpfMapAndCoordinator();
-
- recvNewNeigh(myIfindex, neigh, NUD_REACHABLE, macA);
- verify(mBpfCoordinator).addIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neigh, macA));
- verifyTetherOffloadRuleAdd(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neigh, macA);
- resetNetdBpfMapAndCoordinator();
-
- recvDelNeigh(myIfindex, neigh, NUD_STALE, macA);
- verify(mBpfCoordinator).removeIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neigh, macNull));
- verifyTetherOffloadRuleRemove(null,
- UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neigh, macNull);
- resetNetdBpfMapAndCoordinator();
-
- // Upstream IPv6 connectivity change causes upstream rules change.
- LinkProperties lp2 = new LinkProperties();
- lp2.setInterfaceName(UPSTREAM_IFACE2);
- lp2.setLinkAddresses(UPSTREAM_ADDRESSES2);
- dispatchTetherConnectionChanged(UPSTREAM_IFACE2, lp2, 0);
verify(mBpfCoordinator).updateAllIpv6Rules(
- mIpServer, TEST_IFACE_PARAMS, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
- verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
- resetNetdBpfMapAndCoordinator();
-
- // [2] Disable BPF offload.
- // A neighbor that is added or deleted doesn’t cause the rule to be added or removed.
- initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
- false /* usingLegacyDhcp */, false /* usingBpfOffload */);
- resetNetdBpfMapAndCoordinator();
-
- recvNewNeigh(myIfindex, neigh, NUD_REACHABLE, macA);
- verifyNeverTetherOffloadRuleAdd();
- resetNetdBpfMapAndCoordinator();
-
- recvDelNeigh(myIfindex, neigh, NUD_STALE, macA);
- verifyNeverTetherOffloadRuleRemove();
- resetNetdBpfMapAndCoordinator();
-
- // Upstream IPv6 connectivity change doesn't cause the rule to be added or removed.
- dispatchTetherConnectionChanged(UPSTREAM_IFACE2, lp2, 0);
- verifyNoUpstreamIpv6ForwardingChange(null);
- verifyNeverTetherOffloadRuleRemove();
- resetNetdBpfMapAndCoordinator();
+ mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
+ reset(mBpfCoordinator);
}
@Test
- public void doesNotStartIpNeighborMonitorIfBpfOffloadDisabled() throws Exception {
+ public void stopNeighborMonitoringWhenInterfaceDown() throws Exception {
initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
- false /* usingLegacyDhcp */, false /* usingBpfOffload */);
+ false /* usingLegacyDhcp */, DEFAULT_USING_BPF_OFFLOAD);
- // IP neighbor monitor doesn't start if BPF offload is disabled.
- verify(mIpNeighborMonitor, never()).start();
+ mIpServer.stop();
+ mLooper.dispatchAll();
+ verify(mIpNeighborMonitor).stop();
}
private LinkProperties buildIpv6OnlyLinkProperties(final String iface) {
@@ -1659,75 +1086,4 @@
public void testDadProxyUpdates_EnabledAfterR() throws Exception {
checkDadProxyEnabled(true);
}
-
- @Test
- public void testSkipVirtualNetworkInBpf() throws Exception {
- initTetheredStateMachine(TETHERING_BLUETOOTH, null);
- final LinkProperties v6Only = new LinkProperties();
- v6Only.setInterfaceName(IPSEC_IFACE);
- dispatchTetherConnectionChanged(IPSEC_IFACE, v6Only, 0);
-
- verify(mBpfCoordinator).maybeAttachProgram(IFACE_NAME, IPSEC_IFACE);
- verify(mNetd).tetherAddForward(IFACE_NAME, IPSEC_IFACE);
- verify(mNetd).ipfwdAddInterfaceForward(IFACE_NAME, IPSEC_IFACE);
-
- final int myIfindex = TEST_IFACE_PARAMS.index;
- final InetAddress neigh = InetAddresses.parseNumericAddress("2001:db8::1");
- final MacAddress mac = MacAddress.fromString("00:00:00:00:00:0a");
- recvNewNeigh(myIfindex, neigh, NUD_REACHABLE, mac);
- verify(mBpfCoordinator, never()).addIpv6DownstreamRule(
- mIpServer, makeDownstreamRule(IPSEC_IFINDEX, neigh, mac));
- }
-
- // TODO: move to BpfCoordinatorTest once IpNeighborMonitor is migrated to BpfCoordinator.
- @Test
- public void addRemoveTetherClient() throws Exception {
- initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
- false /* usingLegacyDhcp */, DEFAULT_USING_BPF_OFFLOAD);
-
- final int myIfindex = TEST_IFACE_PARAMS.index;
- final int notMyIfindex = myIfindex - 1;
-
- final InetAddress neighA = InetAddresses.parseNumericAddress("192.168.80.1");
- final InetAddress neighB = InetAddresses.parseNumericAddress("192.168.80.2");
- final InetAddress neighLL = InetAddresses.parseNumericAddress("169.254.0.1");
- final InetAddress neighMC = InetAddresses.parseNumericAddress("224.0.0.1");
- final MacAddress macNull = MacAddress.fromString("00:00:00:00:00:00");
- final MacAddress macA = MacAddress.fromString("00:00:00:00:00:0a");
- final MacAddress macB = MacAddress.fromString("11:22:33:00:00:0b");
-
- // Events on other interfaces are ignored.
- recvNewNeigh(notMyIfindex, neighA, NUD_REACHABLE, macA);
- verifyNoMoreInteractions(mBpfCoordinator);
-
- // Events on this interface are received and sent to BpfCoordinator.
- recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, macA);
- verify(mBpfCoordinator).tetherOffloadClientAdd(mIpServer, new ClientInfo(myIfindex,
- TEST_IFACE_PARAMS.macAddr, (Inet4Address) neighA, macA));
- clearInvocations(mBpfCoordinator);
-
- recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, macB);
- verify(mBpfCoordinator).tetherOffloadClientAdd(mIpServer, new ClientInfo(myIfindex,
- TEST_IFACE_PARAMS.macAddr, (Inet4Address) neighB, macB));
- clearInvocations(mBpfCoordinator);
-
- // Link-local and multicast neighbors are ignored.
- recvNewNeigh(myIfindex, neighLL, NUD_REACHABLE, macA);
- verifyNoMoreInteractions(mBpfCoordinator);
- recvNewNeigh(myIfindex, neighMC, NUD_REACHABLE, macA);
- verifyNoMoreInteractions(mBpfCoordinator);
- clearInvocations(mBpfCoordinator);
-
- // A neighbor that is no longer valid causes the client to be removed.
- // NUD_FAILED events do not have a MAC address.
- recvNewNeigh(myIfindex, neighA, NUD_FAILED, null);
- verify(mBpfCoordinator).tetherOffloadClientRemove(mIpServer, new ClientInfo(myIfindex,
- TEST_IFACE_PARAMS.macAddr, (Inet4Address) neighA, macNull));
- clearInvocations(mBpfCoordinator);
-
- // A neighbor that is deleted causes the client to be removed.
- recvDelNeigh(myIfindex, neighB, NUD_STALE, macB);
- verify(mBpfCoordinator).tetherOffloadClientRemove(mIpServer, new ClientInfo(myIfindex,
- TEST_IFACE_PARAMS.macAddr, (Inet4Address) neighB, macNull));
- }
}
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 7fbb670..6c1721e 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java
@@ -25,6 +25,8 @@
import static android.net.NetworkStats.TAG_NONE;
import static android.net.NetworkStats.UID_ALL;
import static android.net.NetworkStats.UID_TETHERING;
+import static android.net.TetheringManager.TETHERING_WIFI;
+import static android.net.ip.IpServer.STATE_TETHERED;
import static android.net.netstats.provider.NetworkStatsProvider.QUOTA_UNLIMITED;
import static android.system.OsConstants.ETH_P_IP;
import static android.system.OsConstants.ETH_P_IPV6;
@@ -43,6 +45,11 @@
import static com.android.net.module.util.netlink.ConntrackMessage.TupleProto;
import static com.android.net.module.util.netlink.NetlinkConstants.IPCTNL_MSG_CT_DELETE;
import static com.android.net.module.util.netlink.NetlinkConstants.IPCTNL_MSG_CT_NEW;
+import static com.android.net.module.util.netlink.NetlinkConstants.RTM_DELNEIGH;
+import static com.android.net.module.util.netlink.NetlinkConstants.RTM_NEWNEIGH;
+import static com.android.net.module.util.netlink.StructNdMsg.NUD_FAILED;
+import static com.android.net.module.util.netlink.StructNdMsg.NUD_REACHABLE;
+import static com.android.net.module.util.netlink.StructNdMsg.NUD_STALE;
import static com.android.networkstack.tethering.BpfCoordinator.CONNTRACK_TIMEOUT_UPDATE_INTERVAL_MS;
import static com.android.networkstack.tethering.BpfCoordinator.INVALID_MTU;
import static com.android.networkstack.tethering.BpfCoordinator.NF_CONNTRACK_TCP_TIMEOUT_ESTABLISHED;
@@ -71,11 +78,15 @@
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.argThat;
import static org.mockito.Mockito.clearInvocations;
+import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.inOrder;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import android.app.usage.NetworkStatsManager;
@@ -88,13 +99,16 @@
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkStats;
+import android.net.RoutingCoordinatorManager;
import android.net.TetherOffloadRuleParcel;
import android.net.TetherStatsParcel;
import android.net.ip.IpServer;
+import android.net.ip.RouterAdvertisementDaemon;
import android.os.Build;
import android.os.Handler;
import android.os.test.TestLooper;
import android.util.ArrayMap;
+import android.util.ArraySet;
import android.util.SparseArray;
import androidx.annotation.NonNull;
@@ -104,10 +118,12 @@
import com.android.dx.mockito.inline.extended.ExtendedMockito;
import com.android.internal.util.IndentingPrintWriter;
+import com.android.modules.utils.build.SdkLevel;
import com.android.net.module.util.CollectionUtils;
import com.android.net.module.util.IBpfMap;
import com.android.net.module.util.InterfaceParams;
import com.android.net.module.util.NetworkStackConstants;
+import com.android.net.module.util.SdkUtil.LateSdk;
import com.android.net.module.util.SharedLog;
import com.android.net.module.util.Struct.S32;
import com.android.net.module.util.bpf.Tether4Key;
@@ -116,6 +132,9 @@
import com.android.net.module.util.bpf.TetherStatsValue;
import com.android.net.module.util.ip.ConntrackMonitor;
import com.android.net.module.util.ip.ConntrackMonitor.ConntrackEventConsumer;
+import com.android.net.module.util.ip.IpNeighborMonitor;
+import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEvent;
+import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEventConsumer;
import com.android.net.module.util.netlink.ConntrackMessage;
import com.android.net.module.util.netlink.NetlinkConstants;
import com.android.net.module.util.netlink.NetlinkUtils;
@@ -123,6 +142,8 @@
import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
import com.android.networkstack.tethering.BpfCoordinator.Ipv6DownstreamRule;
import com.android.networkstack.tethering.BpfCoordinator.Ipv6UpstreamRule;
+import com.android.networkstack.tethering.metrics.TetheringMetrics;
+import com.android.networkstack.tethering.util.InterfaceSet;
import com.android.testutils.DevSdkIgnoreRule;
import com.android.testutils.DevSdkIgnoreRule.IgnoreAfter;
import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
@@ -172,19 +193,27 @@
private static final int UPSTREAM_IFINDEX2 = 1003;
private static final int DOWNSTREAM_IFINDEX = 2001;
private static final int DOWNSTREAM_IFINDEX2 = 2002;
+ private static final int IPSEC_IFINDEX = 103;
private static final String UPSTREAM_IFACE = "rmnet0";
private static final String UPSTREAM_XLAT_IFACE = "v4-rmnet0";
private static final String UPSTREAM_IFACE2 = "wlan0";
private static final String DOWNSTREAM_IFACE = "downstream1";
private static final String DOWNSTREAM_IFACE2 = "downstream2";
+ private static final String IPSEC_IFACE = "ipsec0";
private static final MacAddress DOWNSTREAM_MAC = MacAddress.fromString("12:34:56:78:90:ab");
private static final MacAddress DOWNSTREAM_MAC2 = MacAddress.fromString("ab:90:78:56:34:12");
private static final MacAddress MAC_A = MacAddress.fromString("00:00:00:00:00:0a");
private static final MacAddress MAC_B = MacAddress.fromString("11:22:33:00:00:0b");
+ private static final MacAddress MAC_NULL = MacAddress.fromString("00:00:00:00:00:00");
+ private static final LinkAddress UPSTREAM_ADDRESS = new LinkAddress("2001:db8:0:1234::168/64");
+ private static final LinkAddress UPSTREAM_ADDRESS2 = new LinkAddress("2001:db8:0:abcd::168/64");
+ private static final Set<LinkAddress> UPSTREAM_ADDRESSES = Set.of(UPSTREAM_ADDRESS);
+ private static final Set<LinkAddress> UPSTREAM_ADDRESSES2 =
+ Set.of(UPSTREAM_ADDRESS, UPSTREAM_ADDRESS2);
private static final IpPrefix UPSTREAM_PREFIX = new IpPrefix("2001:db8:0:1234::/64");
private static final IpPrefix UPSTREAM_PREFIX2 = new IpPrefix("2001:db8:0:abcd::/64");
private static final Set<IpPrefix> UPSTREAM_PREFIXES = Set.of(UPSTREAM_PREFIX);
@@ -196,6 +225,8 @@
InetAddresses.parseNumericAddress("2001:db8:0:1234::1");
private static final InetAddress NEIGH_B =
InetAddresses.parseNumericAddress("2001:db8:0:1234::2");
+ private static final InetAddress NEIGH_LL = InetAddresses.parseNumericAddress("fe80::1");
+ private static final InetAddress NEIGH_MC = InetAddresses.parseNumericAddress("ff02::1234");
private static final Inet4Address REMOTE_ADDR =
(Inet4Address) InetAddresses.parseNumericAddress("140.112.8.116");
@@ -235,6 +266,9 @@
private static final InterfaceParams DOWNSTREAM_IFACE_PARAMS2 = new InterfaceParams(
DOWNSTREAM_IFACE2, DOWNSTREAM_IFINDEX2, DOWNSTREAM_MAC2,
NetworkStackConstants.ETHER_MTU);
+ private static final InterfaceParams IPSEC_IFACE_PARAMS = new InterfaceParams(
+ IPSEC_IFACE, IPSEC_IFINDEX, MacAddress.ALL_ZEROS_ADDRESS,
+ NetworkStackConstants.ETHER_MTU);
private static final Map<Integer, UpstreamInformation> UPSTREAM_INFORMATIONS = Map.of(
UPSTREAM_IFINDEX, new UpstreamInformation(UPSTREAM_IFACE_PARAMS,
@@ -414,6 +448,14 @@
@Mock private IpServer mIpServer2;
@Mock private TetheringConfiguration mTetherConfig;
@Mock private ConntrackMonitor mConntrackMonitor;
+ @Mock private IpNeighborMonitor mIpNeighborMonitor;
+ @Mock private RouterAdvertisementDaemon mRaDaemon;
+ @Mock private IpServer.Dependencies mIpServerDeps;
+ @Mock private IpServer.Callback mIpServerCallback;
+ @Mock private PrivateAddressCoordinator mAddressCoordinator;
+ private final LateSdk<RoutingCoordinatorManager> mRoutingCoordinatorManager =
+ new LateSdk<>(SdkLevel.isAtLeastS() ? mock(RoutingCoordinatorManager.class) : null);
+ @Mock private TetheringMetrics mTetheringMetrics;
// Late init since methods must be called by the thread that created this object.
private TestableNetworkStatsProviderCbBinder mTetherStatsProviderCb;
@@ -422,6 +464,7 @@
// Late init since the object must be initialized by the BPF coordinator instance because
// it has to access the non-static function of BPF coordinator.
private BpfConntrackEventConsumer mConsumer;
+ private NeighborEventConsumer mNeighborEventConsumer;
private HashMap<IpServer, HashMap<Inet4Address, ClientInfo>> mTetherClients;
private long mElapsedRealtimeNanos = 0;
@@ -429,6 +472,7 @@
private final ArgumentCaptor<ArrayList> mStringArrayCaptor =
ArgumentCaptor.forClass(ArrayList.class);
private final TestLooper mTestLooper = new TestLooper();
+ private final Handler mHandler = new Handler(mTestLooper.getLooper());
private final IBpfMap<Tether4Key, Tether4Value> mBpfDownstream4Map =
spy(new TestBpfMap<>(Tether4Key.class, Tether4Value.class));
private final IBpfMap<Tether4Key, Tether4Value> mBpfUpstream4Map =
@@ -449,7 +493,7 @@
spy(new BpfCoordinator.Dependencies() {
@NonNull
public Handler getHandler() {
- return new Handler(mTestLooper.getLooper());
+ return mHandler;
}
@NonNull
@@ -529,6 +573,24 @@
@Before public void setUp() {
MockitoAnnotations.initMocks(this);
when(mTetherConfig.isBpfOffloadEnabled()).thenReturn(true /* default value */);
+
+ // Simulate the behavior of RoutingCoordinator
+ if (null != mRoutingCoordinatorManager.value) {
+ doAnswer(it -> {
+ final String fromIface = (String) it.getArguments()[0];
+ final String toIface = (String) it.getArguments()[1];
+ mNetd.tetherAddForward(fromIface, toIface);
+ mNetd.ipfwdAddInterfaceForward(fromIface, toIface);
+ return null;
+ }).when(mRoutingCoordinatorManager.value).addInterfaceForward(any(), any());
+ doAnswer(it -> {
+ final String fromIface = (String) it.getArguments()[0];
+ final String toIface = (String) it.getArguments()[1];
+ mNetd.ipfwdRemoveInterfaceForward(fromIface, toIface);
+ mNetd.tetherRemoveForward(fromIface, toIface);
+ return null;
+ }).when(mRoutingCoordinatorManager.value).removeInterfaceForward(any(), any());
+ }
}
private void waitForIdle() {
@@ -542,7 +604,68 @@
}
@NonNull
+ private IpServer makeAndStartIpServer(String interfaceName, BpfCoordinator bpfCoordinator)
+ throws Exception {
+ final LinkAddress testAddress = new LinkAddress("192.168.42.5/24");
+ when(mIpServerDeps.getRouterAdvertisementDaemon(any())).thenReturn(mRaDaemon);
+ when(mIpServerDeps.getInterfaceParams(DOWNSTREAM_IFACE)).thenReturn(
+ DOWNSTREAM_IFACE_PARAMS);
+ when(mIpServerDeps.getInterfaceParams(UPSTREAM_IFACE)).thenReturn(UPSTREAM_IFACE_PARAMS);
+ when(mIpServerDeps.getInterfaceParams(UPSTREAM_IFACE2)).thenReturn(UPSTREAM_IFACE_PARAMS2);
+ when(mIpServerDeps.getInterfaceParams(IPSEC_IFACE)).thenReturn(IPSEC_IFACE_PARAMS);
+ when(mAddressCoordinator.requestDownstreamAddress(any(), anyInt(),
+ anyBoolean())).thenReturn(testAddress);
+ when(mRaDaemon.start()).thenReturn(true);
+ ArgumentCaptor<NeighborEventConsumer> neighborEventCaptor =
+ ArgumentCaptor.forClass(NeighborEventConsumer.class);
+ doReturn(mIpNeighborMonitor).when(mIpServerDeps).getIpNeighborMonitor(any(), any(),
+ neighborEventCaptor.capture());
+ final IpServer ipServer = new IpServer(
+ interfaceName, mHandler, TETHERING_WIFI, new SharedLog("test"), mNetd,
+ bpfCoordinator, mRoutingCoordinatorManager, mIpServerCallback, mTetherConfig,
+ mAddressCoordinator, mTetheringMetrics, mIpServerDeps);
+ ipServer.start();
+ ipServer.sendMessage(IpServer.CMD_TETHER_REQUESTED, STATE_TETHERED);
+ mTestLooper.dispatchAll();
+
+ LinkProperties lp = new LinkProperties();
+ lp.setInterfaceName(UPSTREAM_IFACE);
+ lp.setLinkAddresses(UPSTREAM_ADDRESSES);
+ dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE, lp, 0);
+
+ mNeighborEventConsumer = neighborEventCaptor.getValue();
+ return ipServer;
+ }
+
+ private void dispatchTetherConnectionChanged(IpServer ipServer, String upstreamIface,
+ LinkProperties v6lp, int ttlAdjustment) {
+ dispatchTetherConnectionChanged(ipServer, upstreamIface);
+ ipServer.sendMessage(IpServer.CMD_IPV6_TETHER_UPDATE, ttlAdjustment, 0, v6lp);
+ mTestLooper.dispatchAll();
+ }
+
+ private void dispatchTetherConnectionChanged(IpServer ipServer, String upstreamIface) {
+ final InterfaceSet ifs = (upstreamIface != null) ? new InterfaceSet(upstreamIface) : null;
+ ipServer.sendMessage(IpServer.CMD_TETHER_CONNECTION_CHANGED, ifs);
+ mTestLooper.dispatchAll();
+ }
+
+ private void recvNewNeigh(int ifindex, InetAddress addr, short nudState, MacAddress mac) {
+ mNeighborEventConsumer.accept(new NeighborEvent(0, RTM_NEWNEIGH, ifindex, addr,
+ nudState, mac));
+ mTestLooper.dispatchAll();
+ }
+
+ private void recvDelNeigh(int ifindex, InetAddress addr, short nudState, MacAddress mac) {
+ mNeighborEventConsumer.accept(new NeighborEvent(0, RTM_DELNEIGH, ifindex, addr,
+ nudState, mac));
+ mTestLooper.dispatchAll();
+ }
+
+ @NonNull
private BpfCoordinator makeBpfCoordinator() throws Exception {
+ // mStatsManager will be invoked twice if BpfCoordinator is created the second time.
+ clearInvocations(mStatsManager);
final BpfCoordinator coordinator = new BpfCoordinator(mDeps);
mConsumer = coordinator.getBpfConntrackEventConsumerForTesting();
@@ -666,6 +789,51 @@
}
}
+ private void verifyStartUpstreamIpv6Forwarding(@Nullable InOrder inOrder, int upstreamIfindex,
+ @NonNull Set<IpPrefix> upstreamPrefixes) throws Exception {
+ if (!mDeps.isAtLeastS()) return;
+ ArrayMap<TetherUpstream6Key, Tether6Value> expected = new ArrayMap<>();
+ for (IpPrefix upstreamPrefix : upstreamPrefixes) {
+ long prefix64 = prefixToLong(upstreamPrefix);
+ final TetherUpstream6Key key = new TetherUpstream6Key(DOWNSTREAM_IFACE_PARAMS.index,
+ DOWNSTREAM_IFACE_PARAMS.macAddr, prefix64);
+ final Tether6Value value = new Tether6Value(upstreamIfindex,
+ MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS, ETH_P_IPV6,
+ NetworkStackConstants.ETHER_MTU);
+ expected.put(key, value);
+ }
+ ArgumentCaptor<TetherUpstream6Key> keyCaptor =
+ ArgumentCaptor.forClass(TetherUpstream6Key.class);
+ ArgumentCaptor<Tether6Value> valueCaptor =
+ ArgumentCaptor.forClass(Tether6Value.class);
+ verifyWithOrder(inOrder, mBpfUpstream6Map, times(expected.size())).insertEntry(
+ keyCaptor.capture(), valueCaptor.capture());
+ List<TetherUpstream6Key> keys = keyCaptor.getAllValues();
+ List<Tether6Value> values = valueCaptor.getAllValues();
+ ArrayMap<TetherUpstream6Key, Tether6Value> captured = new ArrayMap<>();
+ for (int i = 0; i < keys.size(); i++) {
+ captured.put(keys.get(i), values.get(i));
+ }
+ assertEquals(expected, captured);
+ }
+
+ private void verifyStopUpstreamIpv6Forwarding(@Nullable InOrder inOrder,
+ @NonNull Set<IpPrefix> upstreamPrefixes) throws Exception {
+ if (!mDeps.isAtLeastS()) return;
+ Set<TetherUpstream6Key> expected = new ArraySet<>();
+ for (IpPrefix upstreamPrefix : upstreamPrefixes) {
+ long prefix64 = prefixToLong(upstreamPrefix);
+ final TetherUpstream6Key key = new TetherUpstream6Key(DOWNSTREAM_IFACE_PARAMS.index,
+ DOWNSTREAM_IFACE_PARAMS.macAddr, prefix64);
+ expected.add(key);
+ }
+ ArgumentCaptor<TetherUpstream6Key> keyCaptor =
+ ArgumentCaptor.forClass(TetherUpstream6Key.class);
+ verifyWithOrder(inOrder, mBpfUpstream6Map, times(expected.size())).deleteEntry(
+ keyCaptor.capture());
+ assertEquals(expected, new ArraySet(keyCaptor.getAllValues()));
+ }
+
private void verifyNoUpstreamIpv6ForwardingChange(@Nullable InOrder inOrder) throws Exception {
if (!mDeps.isAtLeastS()) return;
if (inOrder != null) {
@@ -708,6 +876,10 @@
assertEquals(expected, captured);
}
+ private void verifyAddDownstreamRule(@NonNull Ipv6DownstreamRule rule) throws Exception {
+ verifyAddDownstreamRule(null, rule);
+ }
+
private void verifyAddDownstreamRule(@Nullable InOrder inOrder,
@NonNull Ipv6DownstreamRule rule) throws Exception {
if (mDeps.isAtLeastS()) {
@@ -752,6 +924,11 @@
assertSameElements(expected, keyCaptor.getAllValues());
}
+ private void verifyRemoveDownstreamRule(@NonNull final Ipv6DownstreamRule rule)
+ throws Exception {
+ verifyRemoveDownstreamRule(null, rule);
+ }
+
private void verifyRemoveDownstreamRule(@Nullable InOrder inOrder,
@NonNull final Ipv6DownstreamRule rule) throws Exception {
if (mDeps.isAtLeastS()) {
@@ -1016,8 +1193,37 @@
mTetherStatsProviderCb.assertNoCallback();
}
- // The custom ArgumentMatcher simply comes from IpServerTest.
- // TODO: move both of them into a common utility class for reusing the code.
+ /**
+ * Custom ArgumentMatcher for TetherOffloadRuleParcel. This is needed because generated stable
+ * AIDL classes don't have equals(), so we cannot just use eq(). A custom assert, such as:
+ *
+ * private void checkFooCalled(StableParcelable p, ...) {
+ * ArgumentCaptor<@FooParam> captor = ArgumentCaptor.forClass(FooParam.class);
+ * verify(mMock).foo(captor.capture());
+ * Foo foo = captor.getValue();
+ * assertFooMatchesExpectations(foo);
+ * }
+ *
+ * almost works, but not quite. This is because if the code under test calls foo() twice, the
+ * first call to checkFooCalled() matches both the calls, putting both calls into the captor,
+ * and then fails with TooManyActualInvocations. It also makes it harder to use other mockito
+ * features such as never(), inOrder(), etc.
+ *
+ * This approach isn't great because if the match fails, the error message is unhelpful
+ * (actual: "android.net.TetherOffloadRuleParcel@8c827b0" or some such), but at least it does
+ * work.
+ *
+ * TODO: consider making the error message more readable by adding a method that catching the
+ * AssertionFailedError and throwing a new assertion with more details. See
+ * NetworkMonitorTest#verifyNetworkTested.
+ *
+ * See ConnectivityServiceTest#assertRoutesAdded for an alternative approach which solves the
+ * TooManyActualInvocations problem described above by forcing the caller of the custom assert
+ * method to specify all expected invocations in one call. This is useful when the stable
+ * parcelable class being asserted on has a corresponding Java object (eg., RouteInfo and
+ * RouteInfoParcelable), and the caller can just pass in a list of them. It not useful here
+ * because there is no such object.
+ */
private static class TetherOffloadRuleParcelMatcher implements
ArgumentMatcher<TetherOffloadRuleParcel> {
public final int upstreamIfindex;
@@ -2064,8 +2270,7 @@
}
private static long prefixToLong(IpPrefix prefix) {
- byte[] prefixBytes = Arrays.copyOf(prefix.getRawAddress(), 8);
- return ByteBuffer.wrap(prefixBytes).getLong();
+ return ByteBuffer.wrap(prefix.getRawAddress()).getLong();
}
void checkRule4ExistInUpstreamDownstreamMap() throws Exception {
@@ -2135,7 +2340,7 @@
assertNull(mTetherClients.get(mIpServer2));
}
- private void asseertClientInfoExist(@NonNull IpServer ipServer,
+ private void assertClientInfoExists(@NonNull IpServer ipServer,
@NonNull ClientInfo clientInfo) {
HashMap<Inet4Address, ClientInfo> clients = mTetherClients.get(ipServer);
assertNotNull(clients);
@@ -2144,16 +2349,16 @@
// Although either ClientInfo for a given downstream (IpServer) is not found or a given
// client address is not found on a given downstream can be treated "ClientInfo not
- // exist", we still want to know the real reason exactly. For example, we don't the
+ // exist", we still want to know the real reason exactly. For example, we don't know the
// exact reason in the following:
- // assertNull(clients == null ? clients : clients.get(clientInfo.clientAddress));
+ // assertNull(clients == null ? clients : clients.get(clientAddress));
// This helper only verifies the case that the downstream still has at least one client.
// In other words, ClientInfo for a given IpServer has not been removed yet.
- private void asseertClientInfoNotExist(@NonNull IpServer ipServer,
- @NonNull ClientInfo clientInfo) {
+ private void assertClientInfoDoesNotExist(@NonNull IpServer ipServer,
+ @NonNull Inet4Address clientAddress) {
HashMap<Inet4Address, ClientInfo> clients = mTetherClients.get(ipServer);
assertNotNull(clients);
- assertNull(clients.get(clientInfo.clientAddress));
+ assertNull(clients.get(clientAddress));
}
@Test
@@ -2189,8 +2394,8 @@
checkRule4NotExistInUpstreamDownstreamMap();
// Client information should be not deleted.
- asseertClientInfoExist(mIpServer, CLIENT_INFO_A);
- asseertClientInfoExist(mIpServer2, CLIENT_INFO_B);
+ assertClientInfoExists(mIpServer, CLIENT_INFO_A);
+ assertClientInfoExists(mIpServer2, CLIENT_INFO_B);
}
@Test
@@ -2205,8 +2410,8 @@
PRIVATE_ADDR2, MAC_B);
coordinator.tetherOffloadClientAdd(mIpServer, clientA);
coordinator.tetherOffloadClientAdd(mIpServer, clientB);
- asseertClientInfoExist(mIpServer, clientA);
- asseertClientInfoExist(mIpServer, clientB);
+ assertClientInfoExists(mIpServer, clientA);
+ assertClientInfoExists(mIpServer, clientB);
// Add the rules for client A and client B.
final Tether4Key upstream4KeyA = makeUpstream4Key(
@@ -2230,8 +2435,8 @@
// [2] Remove client information A. Only the rules on client A should be removed and
// the rules on client B should exist.
coordinator.tetherOffloadClientRemove(mIpServer, clientA);
- asseertClientInfoNotExist(mIpServer, clientA);
- asseertClientInfoExist(mIpServer, clientB);
+ assertClientInfoDoesNotExist(mIpServer, clientA.clientAddress);
+ assertClientInfoExists(mIpServer, clientB);
assertNull(mBpfUpstream4Map.getValue(upstream4KeyA));
assertNull(mBpfDownstream4Map.getValue(downstream4KeyA));
assertEquals(upstream4ValueB, mBpfUpstream4Map.getValue(upstream4KeyB));
@@ -2239,9 +2444,9 @@
// [3] Remove client information B. The rules on client B should be removed.
// Exactly, ClientInfo for a given IpServer is removed because the last client B
- // has been removed from the downstream. Can't use the helper #asseertClientInfoExist
+ // has been removed from the downstream. Can't use the helper #assertClientInfoExists
// to check because the container ClientInfo for a given downstream has been removed.
- // See #asseertClientInfoExist.
+ // See #assertClientInfoExists.
coordinator.tetherOffloadClientRemove(mIpServer, clientB);
assertNull(mTetherClients.get(mIpServer));
assertNull(mBpfUpstream4Map.getValue(upstream4KeyB));
@@ -2581,4 +2786,296 @@
public void testUpdateUpstreamNetworkState() throws Exception {
verifyUpdateUpstreamNetworkState();
}
+
+ @NonNull
+ private static TetherStatsParcel buildEmptyTetherStatsParcel(int ifIndex) {
+ TetherStatsParcel parcel = new TetherStatsParcel();
+ parcel.ifIndex = ifIndex;
+ return parcel;
+ }
+
+ private void resetNetdAndBpfMaps() throws Exception {
+ reset(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+ // When the last rule is removed, tetherOffloadGetAndClearStats will log a WTF (and
+ // potentially crash the test) if the stats map is empty.
+ when(mNetd.tetherOffloadGetStats()).thenReturn(new TetherStatsParcel[0]);
+ when(mNetd.tetherOffloadGetAndClearStats(UPSTREAM_IFINDEX))
+ .thenReturn(buildEmptyTetherStatsParcel(UPSTREAM_IFINDEX));
+ when(mNetd.tetherOffloadGetAndClearStats(UPSTREAM_IFINDEX2))
+ .thenReturn(buildEmptyTetherStatsParcel(UPSTREAM_IFINDEX2));
+ // When the last rule is removed, tetherOffloadGetAndClearStats will log a WTF (and
+ // potentially crash the test) if the stats map is empty.
+ final TetherStatsValue allZeros = new TetherStatsValue(0, 0, 0, 0, 0, 0);
+ when(mBpfStatsMap.getValue(new TetherStatsKey(UPSTREAM_IFINDEX))).thenReturn(allZeros);
+ when(mBpfStatsMap.getValue(new TetherStatsKey(UPSTREAM_IFINDEX2))).thenReturn(allZeros);
+ }
+
+ @Test
+ public void addRemoveIpv6ForwardingRules() throws Exception {
+ final int myIfindex = DOWNSTREAM_IFINDEX;
+ final int notMyIfindex = myIfindex - 1;
+ final BpfCoordinator coordinator = makeBpfCoordinator();
+ final IpServer ipServer = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator);
+
+ resetNetdAndBpfMaps();
+ verifyNoMoreInteractions(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+
+ // TODO: Perhaps verify the interaction of tetherOffloadSetInterfaceQuota and
+ // tetherOffloadGetAndClearStats in netd while the rules are changed.
+
+ // Events on other interfaces are ignored.
+ recvNewNeigh(notMyIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+ verifyNoMoreInteractions(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+
+ // Events on this interface are received and sent to BpfCoordinator.
+ recvNewNeigh(myIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+ final Ipv6DownstreamRule ruleA = buildTestDownstreamRule(UPSTREAM_IFINDEX, NEIGH_A, MAC_A);
+ verifyAddDownstreamRule(ruleA);
+ resetNetdAndBpfMaps();
+
+ recvNewNeigh(myIfindex, NEIGH_B, NUD_REACHABLE, MAC_B);
+ final Ipv6DownstreamRule ruleB = buildTestDownstreamRule(UPSTREAM_IFINDEX, NEIGH_B, MAC_B);
+ verifyAddDownstreamRule(ruleB);
+ resetNetdAndBpfMaps();
+
+ // Link-local and multicast neighbors are ignored.
+ recvNewNeigh(myIfindex, NEIGH_LL, NUD_REACHABLE, MAC_A);
+ verifyNoMoreInteractions(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+ recvNewNeigh(myIfindex, NEIGH_MC, NUD_REACHABLE, MAC_A);
+ verifyNoMoreInteractions(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+
+ // A neighbor that is no longer valid causes the rule to be removed.
+ // NUD_FAILED events do not have a MAC address.
+ recvNewNeigh(myIfindex, NEIGH_A, NUD_FAILED, null);
+ final Ipv6DownstreamRule ruleANull = buildTestDownstreamRule(
+ UPSTREAM_IFINDEX, NEIGH_A, MAC_NULL);
+ verifyRemoveDownstreamRule(ruleANull);
+ resetNetdAndBpfMaps();
+
+ // A neighbor that is deleted causes the rule to be removed.
+ recvDelNeigh(myIfindex, NEIGH_B, NUD_STALE, MAC_B);
+ final Ipv6DownstreamRule ruleBNull = buildTestDownstreamRule(
+ UPSTREAM_IFINDEX, NEIGH_B, MAC_NULL);
+ verifyRemoveDownstreamRule(ruleBNull);
+ resetNetdAndBpfMaps();
+
+ // Upstream interface changes result in updating the rules.
+ recvNewNeigh(myIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+ recvNewNeigh(myIfindex, NEIGH_B, NUD_REACHABLE, MAC_B);
+ resetNetdAndBpfMaps();
+
+ InOrder inOrder = inOrder(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+ LinkProperties lp = new LinkProperties();
+ lp.setInterfaceName(UPSTREAM_IFACE2);
+ lp.setLinkAddresses(UPSTREAM_ADDRESSES);
+ dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE2, lp, -1);
+ final Ipv6DownstreamRule ruleA2 = buildTestDownstreamRule(
+ UPSTREAM_IFINDEX2, NEIGH_A, MAC_A);
+ final Ipv6DownstreamRule ruleB2 = buildTestDownstreamRule(
+ UPSTREAM_IFINDEX2, NEIGH_B, MAC_B);
+ verifyRemoveDownstreamRule(inOrder, ruleA);
+ verifyRemoveDownstreamRule(inOrder, ruleB);
+ verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES);
+ verifyStartUpstreamIpv6Forwarding(inOrder, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES);
+ verifyAddDownstreamRule(inOrder, ruleA2);
+ verifyAddDownstreamRule(inOrder, ruleB2);
+ verifyNoUpstreamIpv6ForwardingChange(inOrder);
+ resetNetdAndBpfMaps();
+
+ // Upstream link addresses change result in updating the rules.
+ LinkProperties lp2 = new LinkProperties();
+ lp2.setInterfaceName(UPSTREAM_IFACE2);
+ lp2.setLinkAddresses(UPSTREAM_ADDRESSES2);
+ dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE2, lp2, -1);
+ verifyRemoveDownstreamRule(inOrder, ruleA2);
+ verifyRemoveDownstreamRule(inOrder, ruleB2);
+ verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES);
+ verifyStartUpstreamIpv6Forwarding(inOrder, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
+ verifyAddDownstreamRule(inOrder, ruleA2);
+ verifyAddDownstreamRule(inOrder, ruleB2);
+ resetNetdAndBpfMaps();
+
+ // When the upstream is lost, rules are removed.
+ dispatchTetherConnectionChanged(ipServer, null, null, 0);
+ verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES2);
+ verifyRemoveDownstreamRule(ruleA2);
+ verifyRemoveDownstreamRule(ruleB2);
+ // Upstream lost doesn't clear the downstream rules from the maps.
+ // Do that here.
+ recvDelNeigh(myIfindex, NEIGH_A, NUD_STALE, MAC_A);
+ recvDelNeigh(myIfindex, NEIGH_B, NUD_STALE, MAC_B);
+ resetNetdAndBpfMaps();
+
+ // If the upstream is IPv4-only, no IPv6 rules are added to BPF map.
+ dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE);
+ resetNetdAndBpfMaps();
+ recvNewNeigh(myIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+ verifyNoUpstreamIpv6ForwardingChange(null);
+ // Downstream rules are only added to BpfCoordinator but not BPF map.
+ verifyNeverAddDownstreamRule();
+ verifyNoMoreInteractions(mNetd, mBpfDownstream6Map, mBpfUpstream6Map);
+
+ // Rules can be added again once upstream IPv6 connectivity is available. The existing rules
+ // with an upstream of NO_UPSTREAM are reapplied.
+ lp.setInterfaceName(UPSTREAM_IFACE);
+ dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE, lp, -1);
+ verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
+ verifyAddDownstreamRule(ruleA);
+ recvNewNeigh(myIfindex, NEIGH_B, NUD_REACHABLE, MAC_B);
+ verifyAddDownstreamRule(ruleB);
+
+ // If upstream IPv6 connectivity is lost, rules are removed.
+ resetNetdAndBpfMaps();
+ dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE, null, 0);
+ verifyRemoveDownstreamRule(ruleA);
+ verifyRemoveDownstreamRule(ruleB);
+ verifyStopUpstreamIpv6Forwarding(null, UPSTREAM_PREFIXES);
+
+ // When upstream IPv6 connectivity comes back, upstream rules are added and downstream rules
+ // are reapplied.
+ lp.setInterfaceName(UPSTREAM_IFACE);
+ dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE, lp, -1);
+ verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
+ verifyAddDownstreamRule(ruleA);
+ verifyAddDownstreamRule(ruleB);
+ resetNetdAndBpfMaps();
+
+ // When the downstream interface goes down, rules are removed.
+ ipServer.stop();
+ mTestLooper.dispatchAll();
+ verifyStopUpstreamIpv6Forwarding(null, UPSTREAM_PREFIXES);
+ verifyRemoveDownstreamRule(ruleA);
+ verifyRemoveDownstreamRule(ruleB);
+ verify(mIpNeighborMonitor).stop();
+ resetNetdAndBpfMaps();
+ }
+
+ @Test
+ public void enableDisableUsingBpfOffload() throws Exception {
+ final int myIfindex = DOWNSTREAM_IFINDEX;
+
+ // Expect that rules can be only added/removed when the BPF offload config is enabled.
+ // Note that the BPF offload disabled case is not a realistic test case. Because IP
+ // neighbor monitor doesn't start if BPF offload is disabled, there should have no
+ // neighbor event listening. This is used for testing the protection check just in case.
+ // TODO: Perhaps remove the BPF offload disabled case test once this check isn't needed
+ // anymore.
+
+ // [1] Enable BPF offload.
+ // A neighbor that is added or deleted causes the rule to be added or removed.
+ final BpfCoordinator coordinator = makeBpfCoordinator();
+ final IpServer ipServer = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator);
+ resetNetdAndBpfMaps();
+
+ recvNewNeigh(myIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+ final Ipv6DownstreamRule rule = buildTestDownstreamRule(UPSTREAM_IFINDEX, NEIGH_A, MAC_A);
+ verifyAddDownstreamRule(rule);
+ resetNetdAndBpfMaps();
+
+ recvDelNeigh(myIfindex, NEIGH_A, NUD_STALE, MAC_A);
+ final Ipv6DownstreamRule ruleNull = buildTestDownstreamRule(
+ UPSTREAM_IFINDEX, NEIGH_A, MAC_NULL);
+ verifyRemoveDownstreamRule(ruleNull);
+ resetNetdAndBpfMaps();
+
+ // Upstream IPv6 connectivity change causes upstream rules change.
+ LinkProperties lp2 = new LinkProperties();
+ lp2.setInterfaceName(UPSTREAM_IFACE2);
+ lp2.setLinkAddresses(UPSTREAM_ADDRESSES2);
+ dispatchTetherConnectionChanged(ipServer, UPSTREAM_IFACE2, lp2, 0);
+ verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX2, UPSTREAM_PREFIXES2);
+ resetNetdAndBpfMaps();
+
+ // [2] Disable BPF offload.
+ // A neighbor that is added or deleted doesn’t cause the rule to be added or removed.
+ when(mTetherConfig.isBpfOffloadEnabled()).thenReturn(false);
+ final BpfCoordinator coordinator2 = makeBpfCoordinator();
+ final IpServer ipServer2 = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator2);
+ verifyNoUpstreamIpv6ForwardingChange(null);
+ resetNetdAndBpfMaps();
+
+ recvNewNeigh(myIfindex, NEIGH_A, NUD_REACHABLE, MAC_A);
+ verifyNeverAddDownstreamRule();
+ resetNetdAndBpfMaps();
+
+ recvDelNeigh(myIfindex, NEIGH_A, NUD_STALE, MAC_A);
+ verifyNeverRemoveDownstreamRule();
+ resetNetdAndBpfMaps();
+
+ // Upstream IPv6 connectivity change doesn't cause the rule to be added or removed.
+ dispatchTetherConnectionChanged(ipServer2, UPSTREAM_IFACE2, lp2, 0);
+ verifyNoUpstreamIpv6ForwardingChange(null);
+ verifyNeverRemoveDownstreamRule();
+ resetNetdAndBpfMaps();
+ }
+
+ @Test
+ public void doesNotStartIpNeighborMonitorIfBpfOffloadDisabled() throws Exception {
+ when(mTetherConfig.isBpfOffloadEnabled()).thenReturn(false);
+ final BpfCoordinator coordinator = makeBpfCoordinator();
+ final IpServer ipServer = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator);
+
+ // IP neighbor monitor doesn't start if BPF offload is disabled.
+ verify(mIpNeighborMonitor, never()).start();
+ }
+
+ @Test
+ public void testSkipVirtualNetworkInBpf() throws Exception {
+ final BpfCoordinator coordinator = makeBpfCoordinator();
+ final IpServer ipServer = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator);
+ final LinkProperties v6Only = new LinkProperties();
+ v6Only.setInterfaceName(IPSEC_IFACE);
+ v6Only.setLinkAddresses(UPSTREAM_ADDRESSES);
+
+ resetNetdAndBpfMaps();
+ dispatchTetherConnectionChanged(ipServer, IPSEC_IFACE, v6Only, 0);
+ verify(mNetd).tetherAddForward(DOWNSTREAM_IFACE, IPSEC_IFACE);
+ verify(mNetd).ipfwdAddInterfaceForward(DOWNSTREAM_IFACE, IPSEC_IFACE);
+ verifyNeverAddUpstreamRule();
+
+ recvNewNeigh(DOWNSTREAM_IFINDEX, NEIGH_A, NUD_REACHABLE, MAC_A);
+ verifyNeverAddDownstreamRule();
+ }
+
+ @Test
+ public void addRemoveTetherClient() throws Exception {
+ final BpfCoordinator coordinator = makeBpfCoordinator();
+ final IpServer ipServer = makeAndStartIpServer(DOWNSTREAM_IFACE, coordinator);
+ final int myIfindex = DOWNSTREAM_IFINDEX;
+ final int notMyIfindex = myIfindex - 1;
+
+ final InetAddress neighA = InetAddresses.parseNumericAddress("192.168.80.1");
+ final InetAddress neighB = InetAddresses.parseNumericAddress("192.168.80.2");
+ final InetAddress neighLL = InetAddresses.parseNumericAddress("169.254.0.1");
+ final InetAddress neighMC = InetAddresses.parseNumericAddress("224.0.0.1");
+
+ // Events on other interfaces are ignored.
+ recvNewNeigh(notMyIfindex, neighA, NUD_REACHABLE, MAC_A);
+ assertNull(mTetherClients.get(ipServer));
+
+ // Events on this interface are received and sent to BpfCoordinator.
+ recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, MAC_A);
+ assertClientInfoExists(ipServer,
+ new ClientInfo(myIfindex, DOWNSTREAM_MAC, (Inet4Address) neighA, MAC_A));
+
+ recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, MAC_B);
+ assertClientInfoExists(ipServer,
+ new ClientInfo(myIfindex, DOWNSTREAM_MAC, (Inet4Address) neighB, MAC_B));
+
+ // Link-local and multicast neighbors are ignored.
+ recvNewNeigh(myIfindex, neighLL, NUD_REACHABLE, MAC_A);
+ assertClientInfoDoesNotExist(ipServer, (Inet4Address) neighLL);
+ recvNewNeigh(myIfindex, neighMC, NUD_REACHABLE, MAC_A);
+ assertClientInfoDoesNotExist(ipServer, (Inet4Address) neighMC);
+
+ // A neighbor that is no longer valid causes the client to be removed.
+ // NUD_FAILED events do not have a MAC address.
+ recvNewNeigh(myIfindex, neighA, NUD_FAILED, null);
+ assertClientInfoDoesNotExist(ipServer, (Inet4Address) neighA);
+
+ // A neighbor that is deleted causes the client to be removed.
+ recvDelNeigh(myIfindex, neighB, NUD_STALE, MAC_B);
+ // When last client information is deleted, IpServer will be removed from mTetherClients
+ assertNull(mTetherClients.get(ipServer));
+ }
}
diff --git a/framework-t/api/system-lint-baseline.txt b/framework-t/api/system-lint-baseline.txt
index 9baf991..c6055f6 100644
--- a/framework-t/api/system-lint-baseline.txt
+++ b/framework-t/api/system-lint-baseline.txt
@@ -5,3 +5,149 @@
GenericException: android.net.IpSecManager.IpSecTunnelInterface#finalize():
Methods must not throw generic exceptions (`java.lang.Throwable`)
+
+
+UnflaggedApi: android.nearby.CredentialElement#equals(Object):
+ New API must be flagged with @FlaggedApi: method android.nearby.CredentialElement.equals(Object)
+UnflaggedApi: android.nearby.CredentialElement#hashCode():
+ New API must be flagged with @FlaggedApi: method android.nearby.CredentialElement.hashCode()
+UnflaggedApi: android.nearby.DataElement#equals(Object):
+ New API must be flagged with @FlaggedApi: method android.nearby.DataElement.equals(Object)
+UnflaggedApi: android.nearby.DataElement#hashCode():
+ New API must be flagged with @FlaggedApi: method android.nearby.DataElement.hashCode()
+UnflaggedApi: android.nearby.NearbyDevice#equals(Object):
+ New API must be flagged with @FlaggedApi: method android.nearby.NearbyDevice.equals(Object)
+UnflaggedApi: android.nearby.NearbyDevice#hashCode():
+ New API must be flagged with @FlaggedApi: method android.nearby.NearbyDevice.hashCode()
+UnflaggedApi: android.nearby.NearbyDevice#toString():
+ New API must be flagged with @FlaggedApi: method android.nearby.NearbyDevice.toString()
+UnflaggedApi: android.nearby.OffloadCapability#equals(Object):
+ New API must be flagged with @FlaggedApi: method android.nearby.OffloadCapability.equals(Object)
+UnflaggedApi: android.nearby.OffloadCapability#hashCode():
+ New API must be flagged with @FlaggedApi: method android.nearby.OffloadCapability.hashCode()
+UnflaggedApi: android.nearby.OffloadCapability#toString():
+ New API must be flagged with @FlaggedApi: method android.nearby.OffloadCapability.toString()
+UnflaggedApi: android.nearby.PresenceCredential#equals(Object):
+ New API must be flagged with @FlaggedApi: method android.nearby.PresenceCredential.equals(Object)
+UnflaggedApi: android.nearby.PresenceCredential#hashCode():
+ New API must be flagged with @FlaggedApi: method android.nearby.PresenceCredential.hashCode()
+UnflaggedApi: android.nearby.PublicCredential#equals(Object):
+ New API must be flagged with @FlaggedApi: method android.nearby.PublicCredential.equals(Object)
+UnflaggedApi: android.nearby.PublicCredential#hashCode():
+ New API must be flagged with @FlaggedApi: method android.nearby.PublicCredential.hashCode()
+UnflaggedApi: android.nearby.ScanRequest#equals(Object):
+ New API must be flagged with @FlaggedApi: method android.nearby.ScanRequest.equals(Object)
+UnflaggedApi: android.nearby.ScanRequest#hashCode():
+ New API must be flagged with @FlaggedApi: method android.nearby.ScanRequest.hashCode()
+UnflaggedApi: android.nearby.ScanRequest#toString():
+ New API must be flagged with @FlaggedApi: method android.nearby.ScanRequest.toString()
+UnflaggedApi: android.net.EthernetNetworkManagementException#equals(Object):
+ New API must be flagged with @FlaggedApi: method android.net.EthernetNetworkManagementException.equals(Object)
+UnflaggedApi: android.net.EthernetNetworkManagementException#hashCode():
+ New API must be flagged with @FlaggedApi: method android.net.EthernetNetworkManagementException.hashCode()
+UnflaggedApi: android.net.EthernetNetworkUpdateRequest#equals(Object):
+ New API must be flagged with @FlaggedApi: method android.net.EthernetNetworkUpdateRequest.equals(Object)
+UnflaggedApi: android.net.EthernetNetworkUpdateRequest#hashCode():
+ New API must be flagged with @FlaggedApi: method android.net.EthernetNetworkUpdateRequest.hashCode()
+UnflaggedApi: android.net.EthernetNetworkUpdateRequest#toString():
+ New API must be flagged with @FlaggedApi: method android.net.EthernetNetworkUpdateRequest.toString()
+UnflaggedApi: android.net.IpSecManager.IpSecTunnelInterface#finalize():
+ New API must be flagged with @FlaggedApi: method android.net.IpSecManager.IpSecTunnelInterface.finalize()
+UnflaggedApi: android.net.IpSecManager.IpSecTunnelInterface#toString():
+ New API must be flagged with @FlaggedApi: method android.net.IpSecManager.IpSecTunnelInterface.toString()
+UnflaggedApi: android.net.IpSecTransform.Builder#buildTunnelModeTransform(java.net.InetAddress, android.net.IpSecManager.SecurityParameterIndex):
+ New API must be flagged with @FlaggedApi: method android.net.IpSecTransform.Builder.buildTunnelModeTransform(java.net.InetAddress,android.net.IpSecManager.SecurityParameterIndex)
+UnflaggedApi: android.net.NetworkStats.Entry#toString():
+ New API must be flagged with @FlaggedApi: method android.net.NetworkStats.Entry.toString()
+UnflaggedApi: android.net.nsd.NsdManager#registerOffloadEngine(String, long, long, java.util.concurrent.Executor, android.net.nsd.OffloadEngine):
+ New API must be flagged with @FlaggedApi: method android.net.nsd.NsdManager.registerOffloadEngine(String,long,long,java.util.concurrent.Executor,android.net.nsd.OffloadEngine)
+UnflaggedApi: android.net.nsd.NsdManager#unregisterOffloadEngine(android.net.nsd.OffloadEngine):
+ New API must be flagged with @FlaggedApi: method android.net.nsd.NsdManager.unregisterOffloadEngine(android.net.nsd.OffloadEngine)
+UnflaggedApi: android.net.nsd.OffloadEngine:
+ New API must be flagged with @FlaggedApi: class android.net.nsd.OffloadEngine
+UnflaggedApi: android.net.nsd.OffloadEngine#OFFLOAD_CAPABILITY_BYPASS_MULTICAST_LOCK:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadEngine.OFFLOAD_CAPABILITY_BYPASS_MULTICAST_LOCK
+UnflaggedApi: android.net.nsd.OffloadEngine#OFFLOAD_TYPE_FILTER_QUERIES:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadEngine.OFFLOAD_TYPE_FILTER_QUERIES
+UnflaggedApi: android.net.nsd.OffloadEngine#OFFLOAD_TYPE_FILTER_REPLIES:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadEngine.OFFLOAD_TYPE_FILTER_REPLIES
+UnflaggedApi: android.net.nsd.OffloadEngine#OFFLOAD_TYPE_REPLY:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadEngine.OFFLOAD_TYPE_REPLY
+UnflaggedApi: android.net.nsd.OffloadEngine#onOffloadServiceRemoved(android.net.nsd.OffloadServiceInfo):
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadEngine.onOffloadServiceRemoved(android.net.nsd.OffloadServiceInfo)
+UnflaggedApi: android.net.nsd.OffloadEngine#onOffloadServiceUpdated(android.net.nsd.OffloadServiceInfo):
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadEngine.onOffloadServiceUpdated(android.net.nsd.OffloadServiceInfo)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo:
+ New API must be flagged with @FlaggedApi: class android.net.nsd.OffloadServiceInfo
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#CONTENTS_FILE_DESCRIPTOR:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.CONTENTS_FILE_DESCRIPTOR
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#CREATOR:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.CREATOR
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#OffloadServiceInfo(android.net.nsd.OffloadServiceInfo.Key, java.util.List<java.lang.String>, String, byte[], int, long):
+ New API must be flagged with @FlaggedApi: constructor android.net.nsd.OffloadServiceInfo(android.net.nsd.OffloadServiceInfo.Key,java.util.List<java.lang.String>,String,byte[],int,long)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#PARCELABLE_STABILITY_LOCAL:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.PARCELABLE_STABILITY_LOCAL
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#PARCELABLE_STABILITY_VINTF:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.PARCELABLE_STABILITY_VINTF
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#PARCELABLE_WRITE_RETURN_VALUE:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.PARCELABLE_WRITE_RETURN_VALUE
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#describeContents():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.describeContents()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#equals(Object):
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.equals(Object)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getHostname():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getHostname()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getKey():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getKey()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getOffloadPayload():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getOffloadPayload()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getOffloadType():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getOffloadType()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getPriority():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getPriority()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#getSubtypes():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.getSubtypes()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#hashCode():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.hashCode()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#toString():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.toString()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo#writeToParcel(android.os.Parcel, int):
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.writeToParcel(android.os.Parcel,int)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key:
+ New API must be flagged with @FlaggedApi: class android.net.nsd.OffloadServiceInfo.Key
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#CONTENTS_FILE_DESCRIPTOR:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.Key.CONTENTS_FILE_DESCRIPTOR
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#CREATOR:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.Key.CREATOR
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#Key(String, String):
+ New API must be flagged with @FlaggedApi: constructor android.net.nsd.OffloadServiceInfo.Key(String,String)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#PARCELABLE_STABILITY_LOCAL:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.Key.PARCELABLE_STABILITY_LOCAL
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#PARCELABLE_STABILITY_VINTF:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.Key.PARCELABLE_STABILITY_VINTF
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#PARCELABLE_WRITE_RETURN_VALUE:
+ New API must be flagged with @FlaggedApi: field android.net.nsd.OffloadServiceInfo.Key.PARCELABLE_WRITE_RETURN_VALUE
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#describeContents():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.describeContents()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#equals(Object):
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.equals(Object)
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#getServiceName():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.getServiceName()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#getServiceType():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.getServiceType()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#hashCode():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.hashCode()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#toString():
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.toString()
+UnflaggedApi: android.net.nsd.OffloadServiceInfo.Key#writeToParcel(android.os.Parcel, int):
+ New API must be flagged with @FlaggedApi: method android.net.nsd.OffloadServiceInfo.Key.writeToParcel(android.os.Parcel,int)
+UnflaggedApi: android.net.thread.ThreadNetworkController:
+ New API must be flagged with @FlaggedApi: class android.net.thread.ThreadNetworkController
+UnflaggedApi: android.net.thread.ThreadNetworkController#THREAD_VERSION_1_3:
+ New API must be flagged with @FlaggedApi: field android.net.thread.ThreadNetworkController.THREAD_VERSION_1_3
+UnflaggedApi: android.net.thread.ThreadNetworkController#getThreadVersion():
+ New API must be flagged with @FlaggedApi: method android.net.thread.ThreadNetworkController.getThreadVersion()
+UnflaggedApi: android.net.thread.ThreadNetworkManager:
+ New API must be flagged with @FlaggedApi: class android.net.thread.ThreadNetworkManager
+UnflaggedApi: android.net.thread.ThreadNetworkManager#getAllThreadNetworkControllers():
+ New API must be flagged with @FlaggedApi: method android.net.thread.ThreadNetworkManager.getAllThreadNetworkControllers()
diff --git a/framework/Android.bp b/framework/Android.bp
index 8c0bdf4..c88bacc 100644
--- a/framework/Android.bp
+++ b/framework/Android.bp
@@ -332,7 +332,7 @@
// Files listed here MUST all be annotated with @RequiresApi(Build.VERSION_CODES.S)
// or above as appropriate so that API checks are enforced for R+ users of this library
"src/android/net/RoutingCoordinatorManager.java",
- "src/android/net/connectivity/TiramisuConnectivityInternalApiUtil.java",
+ "src/android/net/connectivity/ConnectivityInternalApiUtil.java",
],
visibility: [
"//packages/modules/Connectivity/Tethering:__subpackages__",
diff --git a/framework/aidl-export/android/net/LocalNetworkInfo.aidl b/framework/aidl-export/android/net/LocalNetworkInfo.aidl
new file mode 100644
index 0000000..fa0bc41
--- /dev/null
+++ b/framework/aidl-export/android/net/LocalNetworkInfo.aidl
@@ -0,0 +1,20 @@
+/**
+ *
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net;
+
+parcelable LocalNetworkInfo;
diff --git a/framework/jarjar-excludes.txt b/framework/jarjar-excludes.txt
index bd513d2..09abd17 100644
--- a/framework/jarjar-excludes.txt
+++ b/framework/jarjar-excludes.txt
@@ -23,6 +23,7 @@
# of these classes must be protected by a check for >= S SDK.
# It's unlikely anybody else declares a hidden class with this name ?
android\.net\.RoutingCoordinatorManager(\$.+)?
+android\.net\.LocalNetworkInfo(\$.+)?
# KeepaliveUtils is used by ConnectivityManager CTS
# TODO: move into service-connectivity so framework-connectivity stops using
diff --git a/framework/src/android/net/ConnectivityManager.java b/framework/src/android/net/ConnectivityManager.java
index eb8f8c3..66b2840 100644
--- a/framework/src/android/net/ConnectivityManager.java
+++ b/framework/src/android/net/ConnectivityManager.java
@@ -3963,16 +3963,21 @@
* @param network The {@link Network} of the satisfying network.
* @param networkCapabilities The {@link NetworkCapabilities} of the satisfying network.
* @param linkProperties The {@link LinkProperties} of the satisfying network.
+ * @param localInfo The {@link LocalNetworkInfo} of the satisfying network, or null
+ * if this network is not a local network.
* @param blocked Whether access to the {@link Network} is blocked due to system policy.
* @hide
*/
public final void onAvailable(@NonNull Network network,
@NonNull NetworkCapabilities networkCapabilities,
- @NonNull LinkProperties linkProperties, @BlockedReason int blocked) {
+ @NonNull LinkProperties linkProperties,
+ @Nullable LocalNetworkInfo localInfo,
+ @BlockedReason int blocked) {
// Internally only this method is called when a new network is available, and
// it calls the callback in the same way and order that older versions used
// to call so as not to change the behavior.
onAvailable(network, networkCapabilities, linkProperties, blocked != 0);
+ if (null != localInfo) onLocalNetworkInfoChanged(network, localInfo);
onBlockedStatusChanged(network, blocked);
}
@@ -3989,7 +3994,8 @@
*/
public void onAvailable(@NonNull Network network,
@NonNull NetworkCapabilities networkCapabilities,
- @NonNull LinkProperties linkProperties, boolean blocked) {
+ @NonNull LinkProperties linkProperties,
+ boolean blocked) {
onAvailable(network);
if (!networkCapabilities.hasCapability(
NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED)) {
@@ -4116,6 +4122,19 @@
@NonNull LinkProperties linkProperties) {}
/**
+ * Called when there is a change in the {@link LocalNetworkInfo} for this network.
+ *
+ * This is only called for local networks, that is those with the
+ * NET_CAPABILITY_LOCAL_NETWORK network capability.
+ *
+ * @param network the {@link Network} whose local network info has changed.
+ * @param localNetworkInfo the new {@link LocalNetworkInfo} for this network.
+ * @hide
+ */
+ public void onLocalNetworkInfoChanged(@NonNull Network network,
+ @NonNull LocalNetworkInfo localNetworkInfo) {}
+
+ /**
* Called when the network the framework connected to for this request suspends data
* transmission temporarily.
*
@@ -4209,27 +4228,29 @@
}
/** @hide */
- public static final int CALLBACK_PRECHECK = 1;
+ public static final int CALLBACK_PRECHECK = 1;
/** @hide */
- public static final int CALLBACK_AVAILABLE = 2;
+ public static final int CALLBACK_AVAILABLE = 2;
/** @hide arg1 = TTL */
- public static final int CALLBACK_LOSING = 3;
+ public static final int CALLBACK_LOSING = 3;
/** @hide */
- public static final int CALLBACK_LOST = 4;
+ public static final int CALLBACK_LOST = 4;
/** @hide */
- public static final int CALLBACK_UNAVAIL = 5;
+ public static final int CALLBACK_UNAVAIL = 5;
/** @hide */
- public static final int CALLBACK_CAP_CHANGED = 6;
+ public static final int CALLBACK_CAP_CHANGED = 6;
/** @hide */
- public static final int CALLBACK_IP_CHANGED = 7;
+ public static final int CALLBACK_IP_CHANGED = 7;
/** @hide obj = NetworkCapabilities, arg1 = seq number */
- private static final int EXPIRE_LEGACY_REQUEST = 8;
+ private static final int EXPIRE_LEGACY_REQUEST = 8;
/** @hide */
- public static final int CALLBACK_SUSPENDED = 9;
+ public static final int CALLBACK_SUSPENDED = 9;
/** @hide */
- public static final int CALLBACK_RESUMED = 10;
+ public static final int CALLBACK_RESUMED = 10;
/** @hide */
- public static final int CALLBACK_BLK_CHANGED = 11;
+ public static final int CALLBACK_BLK_CHANGED = 11;
+ /** @hide */
+ public static final int CALLBACK_LOCAL_NETWORK_INFO_CHANGED = 12;
/** @hide */
public static String getCallbackName(int whichCallback) {
@@ -4245,6 +4266,7 @@
case CALLBACK_SUSPENDED: return "CALLBACK_SUSPENDED";
case CALLBACK_RESUMED: return "CALLBACK_RESUMED";
case CALLBACK_BLK_CHANGED: return "CALLBACK_BLK_CHANGED";
+ case CALLBACK_LOCAL_NETWORK_INFO_CHANGED: return "CALLBACK_LOCAL_NETWORK_INFO_CHANGED";
default:
return Integer.toString(whichCallback);
}
@@ -4299,7 +4321,8 @@
case CALLBACK_AVAILABLE: {
NetworkCapabilities cap = getObject(message, NetworkCapabilities.class);
LinkProperties lp = getObject(message, LinkProperties.class);
- callback.onAvailable(network, cap, lp, message.arg1);
+ LocalNetworkInfo lni = getObject(message, LocalNetworkInfo.class);
+ callback.onAvailable(network, cap, lp, lni, message.arg1);
break;
}
case CALLBACK_LOSING: {
@@ -4324,6 +4347,11 @@
callback.onLinkPropertiesChanged(network, lp);
break;
}
+ case CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
+ final LocalNetworkInfo info = getObject(message, LocalNetworkInfo.class);
+ callback.onLocalNetworkInfoChanged(network, info);
+ break;
+ }
case CALLBACK_SUSPENDED: {
callback.onNetworkSuspended(network);
break;
diff --git a/framework/src/android/net/LocalNetworkInfo.java b/framework/src/android/net/LocalNetworkInfo.java
new file mode 100644
index 0000000..f945133
--- /dev/null
+++ b/framework/src/android/net/LocalNetworkInfo.java
@@ -0,0 +1,96 @@
+/*
+ * Copyright (C) 2023 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.net;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+
+/**
+ * Information about a local network.
+ *
+ * This is sent to ConnectivityManager.NetworkCallback.
+ * @hide
+ */
+// TODO : make public
+public final class LocalNetworkInfo implements Parcelable {
+ @Nullable private final Network mUpstreamNetwork;
+
+ public LocalNetworkInfo(@Nullable final Network upstreamNetwork) {
+ this.mUpstreamNetwork = upstreamNetwork;
+ }
+
+ /**
+ * Return the upstream network, or null if none.
+ */
+ @Nullable
+ public Network getUpstreamNetwork() {
+ return mUpstreamNetwork;
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(@NonNull final Parcel dest, final int flags) {
+ dest.writeParcelable(mUpstreamNetwork, flags);
+ }
+
+ @Override
+ public String toString() {
+ return "LocalNetworkInfo { upstream=" + mUpstreamNetwork + " }";
+ }
+
+ public static final @NonNull Creator<LocalNetworkInfo> CREATOR = new Creator<>() {
+ public LocalNetworkInfo createFromParcel(Parcel in) {
+ final Network upstreamNetwork = in.readParcelable(null);
+ return new LocalNetworkInfo(upstreamNetwork);
+ }
+
+ @Override
+ public LocalNetworkInfo[] newArray(final int size) {
+ return new LocalNetworkInfo[size];
+ }
+ };
+
+ /**
+ * Builder for LocalNetworkInfo
+ */
+ public static final class Builder {
+ @Nullable private Network mUpstreamNetwork;
+
+ /**
+ * Set the upstream network, or null if none.
+ * @return the builder
+ */
+ @NonNull public Builder setUpstreamNetwork(@Nullable final Network network) {
+ mUpstreamNetwork = network;
+ return this;
+ }
+
+ /**
+ * Build the LocalNetworkInfo
+ */
+ @NonNull public LocalNetworkInfo build() {
+ return new LocalNetworkInfo(mUpstreamNetwork);
+ }
+ }
+}
diff --git a/framework/src/android/net/connectivity/TiramisuConnectivityInternalApiUtil.java b/framework/src/android/net/connectivity/ConnectivityInternalApiUtil.java
similarity index 94%
rename from framework/src/android/net/connectivity/TiramisuConnectivityInternalApiUtil.java
rename to framework/src/android/net/connectivity/ConnectivityInternalApiUtil.java
index c2d75d2..79f1f65 100644
--- a/framework/src/android/net/connectivity/TiramisuConnectivityInternalApiUtil.java
+++ b/framework/src/android/net/connectivity/ConnectivityInternalApiUtil.java
@@ -35,9 +35,8 @@
* linter).
* @hide
*/
-// TODO : rename this so that it doesn't reference "Tiramisu" since it can be used in S.
@RequiresApi(Build.VERSION_CODES.S)
-public class TiramisuConnectivityInternalApiUtil {
+public class ConnectivityInternalApiUtil {
/**
* Get a service binder token for
diff --git a/service-t/src/com/android/server/net/NetworkStatsService.java b/service-t/src/com/android/server/net/NetworkStatsService.java
index 46afd31..804e709 100644
--- a/service-t/src/com/android/server/net/NetworkStatsService.java
+++ b/service-t/src/com/android/server/net/NetworkStatsService.java
@@ -640,12 +640,8 @@
// on the experiment flag, BpfNetMaps starts C SkDestroyListener (existing code) or
// NetworkStatsService starts Java SkDestroyListener (new code).
final BpfNetMaps bpfNetMaps = mDeps.makeBpfNetMaps(mContext);
- if (bpfNetMaps.isSkDestroyListenerRunning()) {
- mSkDestroyListener = null;
- } else {
- mSkDestroyListener = mDeps.makeSkDestroyListener(mCookieTagMap, mHandler);
- mHandler.post(mSkDestroyListener::start);
- }
+ mSkDestroyListener = mDeps.makeSkDestroyListener(mCookieTagMap, mHandler);
+ mHandler.post(mSkDestroyListener::start);
}
/**
diff --git a/service/Android.bp b/service/Android.bp
index 7def200..15ae501 100644
--- a/service/Android.bp
+++ b/service/Android.bp
@@ -124,7 +124,6 @@
"libmodules-utils-build",
"libnetjniutils",
"libnet_utils_device_common_bpfjni",
- "libtraffic_controller",
"netd_aidl_interface-lateststable-ndk",
],
shared_libs: [
diff --git a/service/jni/com_android_server_BpfNetMaps.cpp b/service/jni/com_android_server_BpfNetMaps.cpp
index 50a0635..29f6a60 100644
--- a/service/jni/com_android_server_BpfNetMaps.cpp
+++ b/service/jni/com_android_server_BpfNetMaps.cpp
@@ -14,179 +14,13 @@
* limitations under the License.
*/
-#define LOG_TAG "TrafficControllerJni"
-
-#include "TrafficController.h"
-
-#include "netd.h"
+#include "bpf/BpfUtils.h"
#include <jni.h>
-#include <log/log.h>
#include <nativehelper/JNIHelp.h>
-#include <nativehelper/ScopedUtfChars.h>
-#include <nativehelper/ScopedPrimitiveArray.h>
-#include <netjniutils/netjniutils.h>
-#include <net/if.h>
-#include <private/android_filesystem_config.h>
-#include <unistd.h>
-#include <vector>
-
-
-using android::net::TrafficController;
-using android::netdutils::Status;
-
-using UidOwnerMatchType::PENALTY_BOX_MATCH;
-using UidOwnerMatchType::HAPPY_BOX_MATCH;
-
-static android::net::TrafficController mTc;
namespace android {
-#define CHECK_LOG(status) \
- do { \
- if (!isOk(status)) \
- ALOGE("%s failed, error code = %d", __func__, status.code()); \
- } while (0)
-
-static void native_init(JNIEnv* env, jclass clazz, jboolean startSkDestroyListener) {
- Status status = mTc.start(startSkDestroyListener);
- CHECK_LOG(status);
- if (!isOk(status)) {
- uid_t uid = getuid();
- ALOGE("BpfNetMaps jni init failure as uid=%d", uid);
- // We probably only ever get called from system_server (ie. AID_SYSTEM)
- // or from tests, and never from network_stack (ie. AID_NETWORK_STACK).
- // However, if we ever do add calls from production network_stack code
- // we do want to make sure this initializes correctly.
- // TODO: Fix tests to not use this jni lib, so we can unconditionally abort()
- if (uid == AID_SYSTEM || uid == AID_NETWORK_STACK) abort();
- }
-}
-
-static jint native_addNaughtyApp(JNIEnv* env, jobject self, jint uid) {
- const uint32_t appUids = static_cast<uint32_t>(abs(uid));
- Status status = mTc.updateUidOwnerMap(appUids, PENALTY_BOX_MATCH,
- TrafficController::IptOp::IptOpInsert);
- CHECK_LOG(status);
- return (jint)status.code();
-}
-
-static jint native_removeNaughtyApp(JNIEnv* env, jobject self, jint uid) {
- const uint32_t appUids = static_cast<uint32_t>(abs(uid));
- Status status = mTc.updateUidOwnerMap(appUids, PENALTY_BOX_MATCH,
- TrafficController::IptOp::IptOpDelete);
- CHECK_LOG(status);
- return (jint)status.code();
-}
-
-static jint native_addNiceApp(JNIEnv* env, jobject self, jint uid) {
- const uint32_t appUids = static_cast<uint32_t>(abs(uid));
- Status status = mTc.updateUidOwnerMap(appUids, HAPPY_BOX_MATCH,
- TrafficController::IptOp::IptOpInsert);
- CHECK_LOG(status);
- return (jint)status.code();
-}
-
-static jint native_removeNiceApp(JNIEnv* env, jobject self, jint uid) {
- const uint32_t appUids = static_cast<uint32_t>(abs(uid));
- Status status = mTc.updateUidOwnerMap(appUids, HAPPY_BOX_MATCH,
- TrafficController::IptOp::IptOpDelete);
- CHECK_LOG(status);
- return (jint)status.code();
-}
-
-static jint native_setChildChain(JNIEnv* env, jobject self, jint childChain, jboolean enable) {
- auto chain = static_cast<ChildChain>(childChain);
- int res = mTc.toggleUidOwnerMap(chain, enable);
- if (res) ALOGE("%s failed, error code = %d", __func__, res);
- return (jint)res;
-}
-
-static jint native_replaceUidChain(JNIEnv* env, jobject self, jstring name, jboolean isAllowlist,
- jintArray jUids) {
- const ScopedUtfChars chainNameUtf8(env, name);
- if (chainNameUtf8.c_str() == nullptr) return -EINVAL;
- const std::string chainName(chainNameUtf8.c_str());
-
- ScopedIntArrayRO uids(env, jUids);
- if (uids.get() == nullptr) return -EINVAL;
-
- size_t size = uids.size();
- static_assert(sizeof(*(uids.get())) == sizeof(int32_t));
- std::vector<int32_t> data ((int32_t *)&uids[0], (int32_t*)&uids[size]);
- int res = mTc.replaceUidOwnerMap(chainName, isAllowlist, data);
- if (res) ALOGE("%s failed, error code = %d", __func__, res);
- return (jint)res;
-}
-
-static jint native_setUidRule(JNIEnv* env, jobject self, jint childChain, jint uid,
- jint firewallRule) {
- auto chain = static_cast<ChildChain>(childChain);
- auto rule = static_cast<FirewallRule>(firewallRule);
- FirewallType fType = mTc.getFirewallType(chain);
-
- int res = mTc.changeUidOwnerRule(chain, uid, rule, fType);
- if (res) ALOGE("%s failed, error code = %d", __func__, res);
- return (jint)res;
-}
-
-static jint native_addUidInterfaceRules(JNIEnv* env, jobject self, jstring ifName,
- jintArray jUids) {
- // Null ifName is a wildcard to allow apps to receive packets on all interfaces and ifIndex is
- // set to 0.
- int ifIndex = 0;
- if (ifName != nullptr) {
- const ScopedUtfChars ifNameUtf8(env, ifName);
- const std::string interfaceName(ifNameUtf8.c_str());
- ifIndex = if_nametoindex(interfaceName.c_str());
- }
-
- ScopedIntArrayRO uids(env, jUids);
- if (uids.get() == nullptr) return -EINVAL;
-
- size_t size = uids.size();
- static_assert(sizeof(*(uids.get())) == sizeof(int32_t));
- std::vector<int32_t> data ((int32_t *)&uids[0], (int32_t*)&uids[size]);
- Status status = mTc.addUidInterfaceRules(ifIndex, data);
- CHECK_LOG(status);
- return (jint)status.code();
-}
-
-static jint native_removeUidInterfaceRules(JNIEnv* env, jobject self, jintArray jUids) {
- ScopedIntArrayRO uids(env, jUids);
- if (uids.get() == nullptr) return -EINVAL;
-
- size_t size = uids.size();
- static_assert(sizeof(*(uids.get())) == sizeof(int32_t));
- std::vector<int32_t> data ((int32_t *)&uids[0], (int32_t*)&uids[size]);
- Status status = mTc.removeUidInterfaceRules(data);
- CHECK_LOG(status);
- return (jint)status.code();
-}
-
-static jint native_updateUidLockdownRule(JNIEnv* env, jobject self, jint uid, jboolean add) {
- Status status = mTc.updateUidLockdownRule(uid, add);
- CHECK_LOG(status);
- return (jint)status.code();
-}
-
-static jint native_swapActiveStatsMap(JNIEnv* env, jobject self) {
- Status status = mTc.swapActiveStatsMap();
- CHECK_LOG(status);
- return (jint)status.code();
-}
-
-static void native_setPermissionForUids(JNIEnv* env, jobject self, jint permission,
- jintArray jUids) {
- ScopedIntArrayRO uids(env, jUids);
- if (uids.get() == nullptr) return;
-
- size_t size = uids.size();
- static_assert(sizeof(*(uids.get())) == sizeof(uid_t));
- std::vector<uid_t> data ((uid_t *)&uids[0], (uid_t*)&uids[size]);
- mTc.setPermissionForUids(permission, data);
-}
-
static jint native_synchronizeKernelRCU(JNIEnv* env, jobject self) {
return -bpf::synchronizeKernelRCU();
}
@@ -197,32 +31,6 @@
// clang-format off
static const JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
- {"native_init", "(Z)V",
- (void*)native_init},
- {"native_addNaughtyApp", "(I)I",
- (void*)native_addNaughtyApp},
- {"native_removeNaughtyApp", "(I)I",
- (void*)native_removeNaughtyApp},
- {"native_addNiceApp", "(I)I",
- (void*)native_addNiceApp},
- {"native_removeNiceApp", "(I)I",
- (void*)native_removeNiceApp},
- {"native_setChildChain", "(IZ)I",
- (void*)native_setChildChain},
- {"native_replaceUidChain", "(Ljava/lang/String;Z[I)I",
- (void*)native_replaceUidChain},
- {"native_setUidRule", "(III)I",
- (void*)native_setUidRule},
- {"native_addUidInterfaceRules", "(Ljava/lang/String;[I)I",
- (void*)native_addUidInterfaceRules},
- {"native_removeUidInterfaceRules", "([I)I",
- (void*)native_removeUidInterfaceRules},
- {"native_updateUidLockdownRule", "(IZ)I",
- (void*)native_updateUidLockdownRule},
- {"native_swapActiveStatsMap", "()I",
- (void*)native_swapActiveStatsMap},
- {"native_setPermissionForUids", "(I[I)V",
- (void*)native_setPermissionForUids},
{"native_synchronizeKernelRCU", "()I",
(void*)native_synchronizeKernelRCU},
};
diff --git a/service/native/Android.bp b/service/native/Android.bp
deleted file mode 100644
index 697fcbd..0000000
--- a/service/native/Android.bp
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package {
- default_applicable_licenses: ["Android-Apache-2.0"],
-}
-
-cc_library {
- name: "libtraffic_controller",
- defaults: ["netd_defaults"],
- srcs: [
- "TrafficController.cpp",
- ],
- header_libs: [
- "bpf_connectivity_headers",
- ],
- static_libs: [
- // TrafficController would use the constants of INetd so that add
- // netd_aidl_interface-lateststable-ndk.
- "netd_aidl_interface-lateststable-ndk",
- ],
- shared_libs: [
- // TODO: Find a good way to remove libbase.
- "libbase",
- "libcutils",
- "libnetdutils",
- "libutils",
- "liblog",
- ],
- export_include_dirs: ["include"],
- sanitize: {
- cfi: true,
- },
- apex_available: [
- "com.android.tethering",
- ],
- min_sdk_version: "30",
-}
-
-cc_test {
- name: "traffic_controller_unit_test",
- test_suites: ["general-tests", "mts-tethering"],
- test_config_template: ":net_native_test_config_template",
- require_root: true,
- local_include_dirs: ["include"],
- header_libs: [
- "bpf_connectivity_headers",
- ],
- srcs: [
- "TrafficControllerTest.cpp",
- ],
- static_libs: [
- "libbase",
- "libgmock",
- "liblog",
- "libnetdutils",
- "libtraffic_controller",
- "libutils",
- "libnetd_updatable",
- "netd_aidl_interface-lateststable-ndk",
- ],
- compile_multilib: "both",
- multilib: {
- lib32: {
- suffix: "32",
- },
- lib64: {
- suffix: "64",
- },
- },
-}
diff --git a/service/native/TrafficController.cpp b/service/native/TrafficController.cpp
deleted file mode 100644
index 8cd698e..0000000
--- a/service/native/TrafficController.cpp
+++ /dev/null
@@ -1,577 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#define LOG_TAG "TrafficController"
-#include <inttypes.h>
-#include <linux/if_ether.h>
-#include <linux/in.h>
-#include <linux/inet_diag.h>
-#include <linux/netlink.h>
-#include <linux/sock_diag.h>
-#include <linux/unistd.h>
-#include <net/if.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <sys/utsname.h>
-#include <sys/wait.h>
-#include <map>
-#include <mutex>
-#include <unordered_set>
-#include <vector>
-
-#include <android-base/stringprintf.h>
-#include <android-base/strings.h>
-#include <android-base/unique_fd.h>
-#include <netdutils/StatusOr.h>
-#include <netdutils/Syscalls.h>
-#include <netdutils/UidConstants.h>
-#include <netdutils/Utils.h>
-#include <private/android_filesystem_config.h>
-
-#include "TrafficController.h"
-#include "bpf/BpfMap.h"
-
-namespace android {
-namespace net {
-
-using base::StringPrintf;
-using base::unique_fd;
-using bpf::BpfMap;
-using bpf::synchronizeKernelRCU;
-using netdutils::NetlinkListener;
-using netdutils::NetlinkListenerInterface;
-using netdutils::Slice;
-using netdutils::sSyscalls;
-using netdutils::Status;
-using netdutils::statusFromErrno;
-using netdutils::StatusOr;
-
-constexpr int kSockDiagMsgType = SOCK_DIAG_BY_FAMILY;
-constexpr int kSockDiagDoneMsgType = NLMSG_DONE;
-
-const char* TrafficController::LOCAL_DOZABLE = "fw_dozable";
-const char* TrafficController::LOCAL_STANDBY = "fw_standby";
-const char* TrafficController::LOCAL_POWERSAVE = "fw_powersave";
-const char* TrafficController::LOCAL_RESTRICTED = "fw_restricted";
-const char* TrafficController::LOCAL_LOW_POWER_STANDBY = "fw_low_power_standby";
-const char* TrafficController::LOCAL_OEM_DENY_1 = "fw_oem_deny_1";
-const char* TrafficController::LOCAL_OEM_DENY_2 = "fw_oem_deny_2";
-const char* TrafficController::LOCAL_OEM_DENY_3 = "fw_oem_deny_3";
-
-static_assert(BPF_PERMISSION_INTERNET == INetd::PERMISSION_INTERNET,
- "Mismatch between BPF and AIDL permissions: PERMISSION_INTERNET");
-static_assert(BPF_PERMISSION_UPDATE_DEVICE_STATS == INetd::PERMISSION_UPDATE_DEVICE_STATS,
- "Mismatch between BPF and AIDL permissions: PERMISSION_UPDATE_DEVICE_STATS");
-
-#define FLAG_MSG_TRANS(result, flag, value) \
- do { \
- if ((value) & (flag)) { \
- (result).append(" " #flag); \
- (value) &= ~(flag); \
- } \
- } while (0)
-
-const std::string uidMatchTypeToString(uint32_t match) {
- std::string matchType;
- FLAG_MSG_TRANS(matchType, HAPPY_BOX_MATCH, match);
- FLAG_MSG_TRANS(matchType, PENALTY_BOX_MATCH, match);
- FLAG_MSG_TRANS(matchType, DOZABLE_MATCH, match);
- FLAG_MSG_TRANS(matchType, STANDBY_MATCH, match);
- FLAG_MSG_TRANS(matchType, POWERSAVE_MATCH, match);
- FLAG_MSG_TRANS(matchType, RESTRICTED_MATCH, match);
- FLAG_MSG_TRANS(matchType, LOW_POWER_STANDBY_MATCH, match);
- FLAG_MSG_TRANS(matchType, IIF_MATCH, match);
- FLAG_MSG_TRANS(matchType, LOCKDOWN_VPN_MATCH, match);
- FLAG_MSG_TRANS(matchType, OEM_DENY_1_MATCH, match);
- FLAG_MSG_TRANS(matchType, OEM_DENY_2_MATCH, match);
- FLAG_MSG_TRANS(matchType, OEM_DENY_3_MATCH, match);
- if (match) {
- return StringPrintf("Unknown match: %u", match);
- }
- return matchType;
-}
-
-const std::string UidPermissionTypeToString(int permission) {
- if (permission == INetd::PERMISSION_NONE) {
- return "PERMISSION_NONE";
- }
- if (permission == INetd::PERMISSION_UNINSTALLED) {
- // This should never appear in the map, complain loudly if it does.
- return "PERMISSION_UNINSTALLED error!";
- }
- std::string permissionType;
- FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_INTERNET, permission);
- FLAG_MSG_TRANS(permissionType, BPF_PERMISSION_UPDATE_DEVICE_STATS, permission);
- if (permission) {
- return StringPrintf("Unknown permission: %u", permission);
- }
- return permissionType;
-}
-
-StatusOr<std::unique_ptr<NetlinkListenerInterface>> TrafficController::makeSkDestroyListener() {
- const auto& sys = sSyscalls.get();
- ASSIGN_OR_RETURN(auto event, sys.eventfd(0, EFD_CLOEXEC));
- const int domain = AF_NETLINK;
- const int type = SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK;
- const int protocol = NETLINK_INET_DIAG;
- ASSIGN_OR_RETURN(auto sock, sys.socket(domain, type, protocol));
-
- // TODO: if too many sockets are closed too quickly, we can overflow the socket buffer, and
- // some entries in mCookieTagMap will not be freed. In order to fix this we would need to
- // periodically dump all sockets and remove the tag entries for sockets that have been closed.
- // For now, set a large-enough buffer that we can close hundreds of sockets without getting
- // ENOBUFS and leaking mCookieTagMap entries.
- int rcvbuf = 512 * 1024;
- auto ret = sys.setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
- if (!ret.ok()) {
- ALOGW("Failed to set SkDestroyListener buffer size to %d: %s", rcvbuf, ret.msg().c_str());
- }
-
- sockaddr_nl addr = {
- .nl_family = AF_NETLINK,
- .nl_groups = 1 << (SKNLGRP_INET_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET_UDP_DESTROY - 1) |
- 1 << (SKNLGRP_INET6_TCP_DESTROY - 1) | 1 << (SKNLGRP_INET6_UDP_DESTROY - 1)};
- RETURN_IF_NOT_OK(sys.bind(sock, addr));
-
- const sockaddr_nl kernel = {.nl_family = AF_NETLINK};
- RETURN_IF_NOT_OK(sys.connect(sock, kernel));
-
- std::unique_ptr<NetlinkListenerInterface> listener =
- std::make_unique<NetlinkListener>(std::move(event), std::move(sock), "SkDestroyListen");
-
- return listener;
-}
-
-Status TrafficController::initMaps() {
- std::lock_guard guard(mMutex);
-
- RETURN_IF_NOT_OK(mCookieTagMap.init(COOKIE_TAG_MAP_PATH));
- RETURN_IF_NOT_OK(mUidCounterSetMap.init(UID_COUNTERSET_MAP_PATH));
- RETURN_IF_NOT_OK(mAppUidStatsMap.init(APP_UID_STATS_MAP_PATH));
- RETURN_IF_NOT_OK(mStatsMapA.init(STATS_MAP_A_PATH));
- RETURN_IF_NOT_OK(mStatsMapB.init(STATS_MAP_B_PATH));
- RETURN_IF_NOT_OK(mIfaceIndexNameMap.init(IFACE_INDEX_NAME_MAP_PATH));
- RETURN_IF_NOT_OK(mIfaceStatsMap.init(IFACE_STATS_MAP_PATH));
-
- RETURN_IF_NOT_OK(mConfigurationMap.init(CONFIGURATION_MAP_PATH));
-
- RETURN_IF_NOT_OK(mUidOwnerMap.init(UID_OWNER_MAP_PATH));
- RETURN_IF_NOT_OK(mUidPermissionMap.init(UID_PERMISSION_MAP_PATH));
- ALOGI("%s successfully", __func__);
-
- return netdutils::status::ok;
-}
-
-Status TrafficController::start(bool startSkDestroyListener) {
- RETURN_IF_NOT_OK(initMaps());
-
- if (!startSkDestroyListener) {
- return netdutils::status::ok;
- }
-
- auto result = makeSkDestroyListener();
- if (!isOk(result)) {
- ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
- } else {
- mSkDestroyListener = std::move(result.value());
- }
- // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
- const auto rxHandler = [this](const nlmsghdr&, const Slice msg) {
- std::lock_guard guard(mMutex);
- inet_diag_msg diagmsg = {};
- if (extract(msg, diagmsg) < sizeof(inet_diag_msg)) {
- ALOGE("Unrecognized netlink message: %s", toString(msg).c_str());
- return;
- }
- uint64_t sock_cookie = static_cast<uint64_t>(diagmsg.id.idiag_cookie[0]) |
- (static_cast<uint64_t>(diagmsg.id.idiag_cookie[1]) << 32);
-
- Status s = mCookieTagMap.deleteValue(sock_cookie);
- if (!isOk(s) && s.code() != ENOENT) {
- ALOGE("Failed to delete cookie %" PRIx64 ": %s", sock_cookie, toString(s).c_str());
- return;
- }
- };
- expectOk(mSkDestroyListener->subscribe(kSockDiagMsgType, rxHandler));
-
- // In case multiple netlink message comes in as a stream, we need to handle the rxDone message
- // properly.
- const auto rxDoneHandler = [](const nlmsghdr&, const Slice msg) {
- // Ignore NLMSG_DONE messages
- inet_diag_msg diagmsg = {};
- extract(msg, diagmsg);
- };
- expectOk(mSkDestroyListener->subscribe(kSockDiagDoneMsgType, rxDoneHandler));
-
- return netdutils::status::ok;
-}
-
-Status TrafficController::updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
- FirewallType type) {
- std::lock_guard guard(mMutex);
- if ((rule == ALLOW && type == ALLOWLIST) || (rule == DENY && type == DENYLIST)) {
- RETURN_IF_NOT_OK(addRule(uid, match));
- } else if ((rule == ALLOW && type == DENYLIST) || (rule == DENY && type == ALLOWLIST)) {
- RETURN_IF_NOT_OK(removeRule(uid, match));
- } else {
- //Cannot happen.
- return statusFromErrno(EINVAL, "");
- }
- return netdutils::status::ok;
-}
-
-Status TrafficController::removeRule(uint32_t uid, UidOwnerMatchType match) {
- auto oldMatch = mUidOwnerMap.readValue(uid);
- if (oldMatch.ok()) {
- UidOwnerValue newMatch = {
- .iif = (match == IIF_MATCH) ? 0 : oldMatch.value().iif,
- .rule = oldMatch.value().rule & ~match,
- };
- if (newMatch.rule == 0) {
- RETURN_IF_NOT_OK(mUidOwnerMap.deleteValue(uid));
- } else {
- RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
- }
- } else {
- return statusFromErrno(ENOENT, StringPrintf("uid: %u does not exist in map", uid));
- }
- return netdutils::status::ok;
-}
-
-Status TrafficController::addRule(uint32_t uid, UidOwnerMatchType match, uint32_t iif) {
- if (match != IIF_MATCH && iif != 0) {
- return statusFromErrno(EINVAL, "Non-interface match must have zero interface index");
- }
- auto oldMatch = mUidOwnerMap.readValue(uid);
- if (oldMatch.ok()) {
- UidOwnerValue newMatch = {
- .iif = (match == IIF_MATCH) ? iif : oldMatch.value().iif,
- .rule = oldMatch.value().rule | match,
- };
- RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
- } else {
- UidOwnerValue newMatch = {
- .iif = iif,
- .rule = match,
- };
- RETURN_IF_NOT_OK(mUidOwnerMap.writeValue(uid, newMatch, BPF_ANY));
- }
- return netdutils::status::ok;
-}
-
-Status TrafficController::updateUidOwnerMap(const uint32_t uid,
- UidOwnerMatchType matchType, IptOp op) {
- std::lock_guard guard(mMutex);
- if (op == IptOpDelete) {
- RETURN_IF_NOT_OK(removeRule(uid, matchType));
- } else if (op == IptOpInsert) {
- RETURN_IF_NOT_OK(addRule(uid, matchType));
- } else {
- // Cannot happen.
- return statusFromErrno(EINVAL, StringPrintf("invalid IptOp: %d, %d", op, matchType));
- }
- return netdutils::status::ok;
-}
-
-FirewallType TrafficController::getFirewallType(ChildChain chain) {
- switch (chain) {
- case DOZABLE:
- return ALLOWLIST;
- case STANDBY:
- return DENYLIST;
- case POWERSAVE:
- return ALLOWLIST;
- case RESTRICTED:
- return ALLOWLIST;
- case LOW_POWER_STANDBY:
- return ALLOWLIST;
- case OEM_DENY_1:
- return DENYLIST;
- case OEM_DENY_2:
- return DENYLIST;
- case OEM_DENY_3:
- return DENYLIST;
- case NONE:
- default:
- return DENYLIST;
- }
-}
-
-int TrafficController::changeUidOwnerRule(ChildChain chain, uid_t uid, FirewallRule rule,
- FirewallType type) {
- Status res;
- switch (chain) {
- case DOZABLE:
- res = updateOwnerMapEntry(DOZABLE_MATCH, uid, rule, type);
- break;
- case STANDBY:
- res = updateOwnerMapEntry(STANDBY_MATCH, uid, rule, type);
- break;
- case POWERSAVE:
- res = updateOwnerMapEntry(POWERSAVE_MATCH, uid, rule, type);
- break;
- case RESTRICTED:
- res = updateOwnerMapEntry(RESTRICTED_MATCH, uid, rule, type);
- break;
- case LOW_POWER_STANDBY:
- res = updateOwnerMapEntry(LOW_POWER_STANDBY_MATCH, uid, rule, type);
- break;
- case OEM_DENY_1:
- res = updateOwnerMapEntry(OEM_DENY_1_MATCH, uid, rule, type);
- break;
- case OEM_DENY_2:
- res = updateOwnerMapEntry(OEM_DENY_2_MATCH, uid, rule, type);
- break;
- case OEM_DENY_3:
- res = updateOwnerMapEntry(OEM_DENY_3_MATCH, uid, rule, type);
- break;
- case NONE:
- default:
- ALOGW("Unknown child chain: %d", chain);
- return -EINVAL;
- }
- if (!isOk(res)) {
- ALOGE("change uid(%u) rule of %d failed: %s, rule: %d, type: %d", uid, chain,
- res.msg().c_str(), rule, type);
- return -res.code();
- }
- return 0;
-}
-
-Status TrafficController::replaceRulesInMap(const UidOwnerMatchType match,
- const std::vector<int32_t>& uids) {
- std::lock_guard guard(mMutex);
- std::set<int32_t> uidSet(uids.begin(), uids.end());
- std::vector<uint32_t> uidsToDelete;
- auto getUidsToDelete = [&uidsToDelete, &uidSet](const uint32_t& key,
- const BpfMap<uint32_t, UidOwnerValue>&) {
- if (uidSet.find((int32_t) key) == uidSet.end()) {
- uidsToDelete.push_back(key);
- }
- return base::Result<void>();
- };
- RETURN_IF_NOT_OK(mUidOwnerMap.iterate(getUidsToDelete));
-
- for(auto uid : uidsToDelete) {
- RETURN_IF_NOT_OK(removeRule(uid, match));
- }
-
- for (auto uid : uids) {
- RETURN_IF_NOT_OK(addRule(uid, match));
- }
- return netdutils::status::ok;
-}
-
-Status TrafficController::addUidInterfaceRules(const int iif,
- const std::vector<int32_t>& uidsToAdd) {
- std::lock_guard guard(mMutex);
-
- for (auto uid : uidsToAdd) {
- netdutils::Status result = addRule(uid, IIF_MATCH, iif);
- if (!isOk(result)) {
- ALOGW("addRule failed(%d): uid=%d iif=%d", result.code(), uid, iif);
- }
- }
- return netdutils::status::ok;
-}
-
-Status TrafficController::removeUidInterfaceRules(const std::vector<int32_t>& uidsToDelete) {
- std::lock_guard guard(mMutex);
-
- for (auto uid : uidsToDelete) {
- netdutils::Status result = removeRule(uid, IIF_MATCH);
- if (!isOk(result)) {
- ALOGW("removeRule failed(%d): uid=%d", result.code(), uid);
- }
- }
- return netdutils::status::ok;
-}
-
-Status TrafficController::updateUidLockdownRule(const uid_t uid, const bool add) {
- std::lock_guard guard(mMutex);
-
- netdutils::Status result = add ? addRule(uid, LOCKDOWN_VPN_MATCH)
- : removeRule(uid, LOCKDOWN_VPN_MATCH);
- if (!isOk(result)) {
- ALOGW("%s Lockdown rule failed(%d): uid=%d",
- (add ? "add": "remove"), result.code(), uid);
- }
- return result;
-}
-
-int TrafficController::replaceUidOwnerMap(const std::string& name, bool isAllowlist __unused,
- const std::vector<int32_t>& uids) {
- // FirewallRule rule = isAllowlist ? ALLOW : DENY;
- // FirewallType type = isAllowlist ? ALLOWLIST : DENYLIST;
- Status res;
- if (!name.compare(LOCAL_DOZABLE)) {
- res = replaceRulesInMap(DOZABLE_MATCH, uids);
- } else if (!name.compare(LOCAL_STANDBY)) {
- res = replaceRulesInMap(STANDBY_MATCH, uids);
- } else if (!name.compare(LOCAL_POWERSAVE)) {
- res = replaceRulesInMap(POWERSAVE_MATCH, uids);
- } else if (!name.compare(LOCAL_RESTRICTED)) {
- res = replaceRulesInMap(RESTRICTED_MATCH, uids);
- } else if (!name.compare(LOCAL_LOW_POWER_STANDBY)) {
- res = replaceRulesInMap(LOW_POWER_STANDBY_MATCH, uids);
- } else if (!name.compare(LOCAL_OEM_DENY_1)) {
- res = replaceRulesInMap(OEM_DENY_1_MATCH, uids);
- } else if (!name.compare(LOCAL_OEM_DENY_2)) {
- res = replaceRulesInMap(OEM_DENY_2_MATCH, uids);
- } else if (!name.compare(LOCAL_OEM_DENY_3)) {
- res = replaceRulesInMap(OEM_DENY_3_MATCH, uids);
- } else {
- ALOGE("unknown chain name: %s", name.c_str());
- return -EINVAL;
- }
- if (!isOk(res)) {
- ALOGE("Failed to clean up chain: %s: %s", name.c_str(), res.msg().c_str());
- return -res.code();
- }
- return 0;
-}
-
-int TrafficController::toggleUidOwnerMap(ChildChain chain, bool enable) {
- std::lock_guard guard(mMutex);
- uint32_t key = UID_RULES_CONFIGURATION_KEY;
- auto oldConfigure = mConfigurationMap.readValue(key);
- if (!oldConfigure.ok()) {
- ALOGE("Cannot read the old configuration from map: %s",
- oldConfigure.error().message().c_str());
- return -oldConfigure.error().code();
- }
- uint32_t match;
- switch (chain) {
- case DOZABLE:
- match = DOZABLE_MATCH;
- break;
- case STANDBY:
- match = STANDBY_MATCH;
- break;
- case POWERSAVE:
- match = POWERSAVE_MATCH;
- break;
- case RESTRICTED:
- match = RESTRICTED_MATCH;
- break;
- case LOW_POWER_STANDBY:
- match = LOW_POWER_STANDBY_MATCH;
- break;
- case OEM_DENY_1:
- match = OEM_DENY_1_MATCH;
- break;
- case OEM_DENY_2:
- match = OEM_DENY_2_MATCH;
- break;
- case OEM_DENY_3:
- match = OEM_DENY_3_MATCH;
- break;
- default:
- return -EINVAL;
- }
- BpfConfig newConfiguration =
- enable ? (oldConfigure.value() | match) : (oldConfigure.value() & ~match);
- Status res = mConfigurationMap.writeValue(key, newConfiguration, BPF_EXIST);
- if (!isOk(res)) {
- ALOGE("Failed to toggleUidOwnerMap(%d): %s", chain, res.msg().c_str());
- }
- return -res.code();
-}
-
-Status TrafficController::swapActiveStatsMap() {
- std::lock_guard guard(mMutex);
-
- uint32_t key = CURRENT_STATS_MAP_CONFIGURATION_KEY;
- auto oldConfigure = mConfigurationMap.readValue(key);
- if (!oldConfigure.ok()) {
- ALOGE("Cannot read the old configuration from map: %s",
- oldConfigure.error().message().c_str());
- return Status(oldConfigure.error().code(), oldConfigure.error().message());
- }
-
- // Write to the configuration map to inform the kernel eBPF program to switch
- // from using one map to the other. Use flag BPF_EXIST here since the map should
- // be already populated in initMaps.
- uint32_t newConfigure = (oldConfigure.value() == SELECT_MAP_A) ? SELECT_MAP_B : SELECT_MAP_A;
- auto res = mConfigurationMap.writeValue(CURRENT_STATS_MAP_CONFIGURATION_KEY, newConfigure,
- BPF_EXIST);
- if (!res.ok()) {
- ALOGE("Failed to toggle the stats map: %s", strerror(res.error().code()));
- return res;
- }
- // After changing the config, we need to make sure all the current running
- // eBPF programs are finished and all the CPUs are aware of this config change
- // before we modify the old map. So we do a special hack here to wait for
- // the kernel to do a synchronize_rcu(). Once the kernel called
- // synchronize_rcu(), the config we just updated will be available to all cores
- // and the next eBPF programs triggered inside the kernel will use the new
- // map configuration. So once this function returns we can safely modify the
- // old stats map without concerning about race between the kernel and
- // userspace.
- int ret = synchronizeKernelRCU();
- if (ret) {
- ALOGE("map swap synchronize_rcu() ended with failure: %s", strerror(-ret));
- return statusFromErrno(-ret, "map swap synchronize_rcu() failed");
- }
- return netdutils::status::ok;
-}
-
-void TrafficController::setPermissionForUids(int permission, const std::vector<uid_t>& uids) {
- std::lock_guard guard(mMutex);
- if (permission == INetd::PERMISSION_UNINSTALLED) {
- for (uid_t uid : uids) {
- // Clean up all permission information for the related uid if all the
- // packages related to it are uninstalled.
- mPrivilegedUser.erase(uid);
- Status ret = mUidPermissionMap.deleteValue(uid);
- if (!isOk(ret) && ret.code() != ENOENT) {
- ALOGE("Failed to clean up the permission for %u: %s", uid, strerror(ret.code()));
- }
- }
- return;
- }
-
- bool privileged = (permission & INetd::PERMISSION_UPDATE_DEVICE_STATS);
-
- for (uid_t uid : uids) {
- if (privileged) {
- mPrivilegedUser.insert(uid);
- } else {
- mPrivilegedUser.erase(uid);
- }
-
- // The map stores all the permissions that the UID has, except if the only permission
- // the UID has is the INTERNET permission, then the UID should not appear in the map.
- if (permission != INetd::PERMISSION_INTERNET) {
- Status ret = mUidPermissionMap.writeValue(uid, permission, BPF_ANY);
- if (!isOk(ret)) {
- ALOGE("Failed to set permission: %s of uid(%u) to permission map: %s",
- UidPermissionTypeToString(permission).c_str(), uid, strerror(ret.code()));
- }
- } else {
- Status ret = mUidPermissionMap.deleteValue(uid);
- if (!isOk(ret) && ret.code() != ENOENT) {
- ALOGE("Failed to remove uid %u from permission map: %s", uid, strerror(ret.code()));
- }
- }
- }
-}
-
-} // namespace net
-} // namespace android
diff --git a/service/native/TrafficControllerTest.cpp b/service/native/TrafficControllerTest.cpp
deleted file mode 100644
index 99e9831..0000000
--- a/service/native/TrafficControllerTest.cpp
+++ /dev/null
@@ -1,822 +0,0 @@
-/*
- * Copyright 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * TrafficControllerTest.cpp - unit tests for TrafficController.cpp
- */
-
-#include <cstdint>
-#include <string>
-#include <vector>
-
-#include <fcntl.h>
-#include <inttypes.h>
-#include <linux/inet_diag.h>
-#include <linux/sock_diag.h>
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include <gtest/gtest.h>
-
-#include <android-base/file.h>
-#include <android-base/logging.h>
-#include <android-base/stringprintf.h>
-#include <android-base/strings.h>
-#include <binder/Status.h>
-
-#include <netdutils/MockSyscalls.h>
-
-#define BPF_MAP_MAKE_VISIBLE_FOR_TESTING
-#include "TrafficController.h"
-#include "bpf/BpfUtils.h"
-#include "NetdUpdatablePublic.h"
-
-using namespace android::bpf; // NOLINT(google-build-using-namespace): grandfathered
-
-namespace android {
-namespace net {
-
-using android::netdutils::Status;
-using base::Result;
-using netdutils::isOk;
-using netdutils::statusFromErrno;
-
-constexpr int TEST_MAP_SIZE = 10;
-constexpr uid_t TEST_UID = 10086;
-constexpr uid_t TEST_UID2 = 54321;
-constexpr uid_t TEST_UID3 = 98765;
-constexpr uint32_t TEST_TAG = 42;
-constexpr uint32_t TEST_COUNTERSET = 1;
-constexpr int TEST_IFINDEX = 999;
-constexpr int RXPACKETS = 1;
-constexpr int RXBYTES = 100;
-constexpr int TXPACKETS = 0;
-constexpr int TXBYTES = 0;
-
-#define ASSERT_VALID(x) ASSERT_TRUE((x).isValid())
-#define ASSERT_INVALID(x) ASSERT_FALSE((x).isValid())
-
-class TrafficControllerTest : public ::testing::Test {
- protected:
- TrafficControllerTest() {}
- TrafficController mTc;
- BpfMap<uint64_t, UidTagValue> mFakeCookieTagMap;
- BpfMap<uint32_t, StatsValue> mFakeAppUidStatsMap;
- BpfMap<StatsKey, StatsValue> mFakeStatsMapA;
- BpfMap<StatsKey, StatsValue> mFakeStatsMapB; // makeTrafficControllerMapsInvalid only
- BpfMap<uint32_t, StatsValue> mFakeIfaceStatsMap; ; // makeTrafficControllerMapsInvalid only
- BpfMap<uint32_t, uint32_t> mFakeConfigurationMap;
- BpfMap<uint32_t, UidOwnerValue> mFakeUidOwnerMap;
- BpfMap<uint32_t, uint8_t> mFakeUidPermissionMap;
- BpfMap<uint32_t, uint8_t> mFakeUidCounterSetMap;
- BpfMap<uint32_t, IfaceValue> mFakeIfaceIndexNameMap;
-
- void SetUp() {
- std::lock_guard guard(mTc.mMutex);
- ASSERT_EQ(0, setrlimitForTest());
-
- mFakeCookieTagMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
- ASSERT_VALID(mFakeCookieTagMap);
-
- mFakeAppUidStatsMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
- ASSERT_VALID(mFakeAppUidStatsMap);
-
- mFakeStatsMapA.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
- ASSERT_VALID(mFakeStatsMapA);
-
- mFakeConfigurationMap.resetMap(BPF_MAP_TYPE_ARRAY, CONFIGURATION_MAP_SIZE);
- ASSERT_VALID(mFakeConfigurationMap);
-
- mFakeUidOwnerMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
- ASSERT_VALID(mFakeUidOwnerMap);
- mFakeUidPermissionMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
- ASSERT_VALID(mFakeUidPermissionMap);
-
- mFakeUidCounterSetMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
- ASSERT_VALID(mFakeUidCounterSetMap);
-
- mFakeIfaceIndexNameMap.resetMap(BPF_MAP_TYPE_HASH, TEST_MAP_SIZE);
- ASSERT_VALID(mFakeIfaceIndexNameMap);
-
- mTc.mCookieTagMap = mFakeCookieTagMap;
- ASSERT_VALID(mTc.mCookieTagMap);
- mTc.mAppUidStatsMap = mFakeAppUidStatsMap;
- ASSERT_VALID(mTc.mAppUidStatsMap);
- mTc.mStatsMapA = mFakeStatsMapA;
- ASSERT_VALID(mTc.mStatsMapA);
- mTc.mConfigurationMap = mFakeConfigurationMap;
- ASSERT_VALID(mTc.mConfigurationMap);
-
- // Always write to stats map A by default.
- static_assert(SELECT_MAP_A == 0);
-
- mTc.mUidOwnerMap = mFakeUidOwnerMap;
- ASSERT_VALID(mTc.mUidOwnerMap);
- mTc.mUidPermissionMap = mFakeUidPermissionMap;
- ASSERT_VALID(mTc.mUidPermissionMap);
- mTc.mPrivilegedUser.clear();
-
- mTc.mUidCounterSetMap = mFakeUidCounterSetMap;
- ASSERT_VALID(mTc.mUidCounterSetMap);
-
- mTc.mIfaceIndexNameMap = mFakeIfaceIndexNameMap;
- ASSERT_VALID(mTc.mIfaceIndexNameMap);
- }
-
- void populateFakeStats(uint64_t cookie, uint32_t uid, uint32_t tag, StatsKey* key) {
- UidTagValue cookieMapkey = {.uid = (uint32_t)uid, .tag = tag};
- EXPECT_RESULT_OK(mFakeCookieTagMap.writeValue(cookie, cookieMapkey, BPF_ANY));
- *key = {.uid = uid, .tag = tag, .counterSet = TEST_COUNTERSET, .ifaceIndex = TEST_IFINDEX};
- StatsValue statsMapValue = {.rxPackets = RXPACKETS, .rxBytes = RXBYTES,
- .txPackets = TXPACKETS, .txBytes = TXBYTES};
- EXPECT_RESULT_OK(mFakeStatsMapA.writeValue(*key, statsMapValue, BPF_ANY));
- EXPECT_RESULT_OK(mFakeAppUidStatsMap.writeValue(uid, statsMapValue, BPF_ANY));
- // put tag information back to statsKey
- key->tag = tag;
- }
-
- void populateFakeCounterSet(uint32_t uid, uint32_t counterSet) {
- EXPECT_RESULT_OK(mFakeUidCounterSetMap.writeValue(uid, counterSet, BPF_ANY));
- }
-
- void populateFakeIfaceIndexName(const char* name, uint32_t ifaceIndex) {
- if (name == nullptr || ifaceIndex <= 0) return;
-
- IfaceValue iface;
- strlcpy(iface.name, name, sizeof(IfaceValue));
- EXPECT_RESULT_OK(mFakeIfaceIndexNameMap.writeValue(ifaceIndex, iface, BPF_ANY));
- }
-
- void checkUidOwnerRuleForChain(ChildChain chain, UidOwnerMatchType match) {
- uint32_t uid = TEST_UID;
- EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, DENYLIST));
- Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
- EXPECT_RESULT_OK(value);
- EXPECT_TRUE(value.value().rule & match);
-
- uid = TEST_UID2;
- EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, ALLOWLIST));
- value = mFakeUidOwnerMap.readValue(uid);
- EXPECT_RESULT_OK(value);
- EXPECT_TRUE(value.value().rule & match);
-
- EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, DENY, ALLOWLIST));
- value = mFakeUidOwnerMap.readValue(uid);
- EXPECT_FALSE(value.ok());
- EXPECT_EQ(ENOENT, value.error().code());
-
- uid = TEST_UID;
- EXPECT_EQ(0, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
- value = mFakeUidOwnerMap.readValue(uid);
- EXPECT_FALSE(value.ok());
- EXPECT_EQ(ENOENT, value.error().code());
-
- uid = TEST_UID3;
- EXPECT_EQ(-ENOENT, mTc.changeUidOwnerRule(chain, uid, ALLOW, DENYLIST));
- value = mFakeUidOwnerMap.readValue(uid);
- EXPECT_FALSE(value.ok());
- EXPECT_EQ(ENOENT, value.error().code());
- }
-
- void checkEachUidValue(const std::vector<int32_t>& uids, UidOwnerMatchType match) {
- for (uint32_t uid : uids) {
- Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
- EXPECT_RESULT_OK(value);
- EXPECT_TRUE(value.value().rule & match);
- }
- std::set<uint32_t> uidSet(uids.begin(), uids.end());
- const auto checkNoOtherUid = [&uidSet](const int32_t& key,
- const BpfMap<uint32_t, UidOwnerValue>&) {
- EXPECT_NE(uidSet.end(), uidSet.find(key));
- return Result<void>();
- };
- EXPECT_RESULT_OK(mFakeUidOwnerMap.iterate(checkNoOtherUid));
- }
-
- void checkUidMapReplace(const std::string& name, const std::vector<int32_t>& uids,
- UidOwnerMatchType match) {
- bool isAllowlist = true;
- EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
- checkEachUidValue(uids, match);
-
- isAllowlist = false;
- EXPECT_EQ(0, mTc.replaceUidOwnerMap(name, isAllowlist, uids));
- checkEachUidValue(uids, match);
- }
-
- void expectUidOwnerMapValues(const std::vector<uint32_t>& appUids, uint32_t expectedRule,
- uint32_t expectedIif) {
- for (uint32_t uid : appUids) {
- Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
- EXPECT_RESULT_OK(value);
- EXPECT_EQ(expectedRule, value.value().rule)
- << "Expected rule for UID " << uid << " to be " << expectedRule << ", but was "
- << value.value().rule;
- EXPECT_EQ(expectedIif, value.value().iif)
- << "Expected iif for UID " << uid << " to be " << expectedIif << ", but was "
- << value.value().iif;
- }
- }
-
- template <class Key, class Value>
- void expectMapEmpty(BpfMap<Key, Value>& map) {
- auto isEmpty = map.isEmpty();
- EXPECT_RESULT_OK(isEmpty);
- EXPECT_TRUE(isEmpty.value());
- }
-
- void expectUidPermissionMapValues(const std::vector<uid_t>& appUids, uint8_t expectedValue) {
- for (uid_t uid : appUids) {
- Result<uint8_t> value = mFakeUidPermissionMap.readValue(uid);
- EXPECT_RESULT_OK(value);
- EXPECT_EQ(expectedValue, value.value())
- << "Expected value for UID " << uid << " to be " << expectedValue
- << ", but was " << value.value();
- }
- }
-
- void expectPrivilegedUserSet(const std::vector<uid_t>& appUids) {
- std::lock_guard guard(mTc.mMutex);
- EXPECT_EQ(appUids.size(), mTc.mPrivilegedUser.size());
- for (uid_t uid : appUids) {
- EXPECT_NE(mTc.mPrivilegedUser.end(), mTc.mPrivilegedUser.find(uid));
- }
- }
-
- void expectPrivilegedUserSetEmpty() {
- std::lock_guard guard(mTc.mMutex);
- EXPECT_TRUE(mTc.mPrivilegedUser.empty());
- }
-
- Status updateUidOwnerMaps(const std::vector<uint32_t>& appUids,
- UidOwnerMatchType matchType, TrafficController::IptOp op) {
- Status ret(0);
- for (auto uid : appUids) {
- ret = mTc.updateUidOwnerMap(uid, matchType, op);
- if(!isOk(ret)) break;
- }
- return ret;
- }
-};
-
-TEST_F(TrafficControllerTest, TestUpdateOwnerMapEntry) {
- uint32_t uid = TEST_UID;
- ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, DENY, DENYLIST)));
- Result<UidOwnerValue> value = mFakeUidOwnerMap.readValue(uid);
- ASSERT_RESULT_OK(value);
- ASSERT_TRUE(value.value().rule & STANDBY_MATCH);
-
- ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, ALLOW, ALLOWLIST)));
- value = mFakeUidOwnerMap.readValue(uid);
- ASSERT_RESULT_OK(value);
- ASSERT_TRUE(value.value().rule & DOZABLE_MATCH);
-
- ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(DOZABLE_MATCH, uid, DENY, ALLOWLIST)));
- value = mFakeUidOwnerMap.readValue(uid);
- ASSERT_RESULT_OK(value);
- ASSERT_FALSE(value.value().rule & DOZABLE_MATCH);
-
- ASSERT_TRUE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
- ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
-
- uid = TEST_UID2;
- ASSERT_FALSE(isOk(mTc.updateOwnerMapEntry(STANDBY_MATCH, uid, ALLOW, DENYLIST)));
- ASSERT_FALSE(mFakeUidOwnerMap.readValue(uid).ok());
-}
-
-TEST_F(TrafficControllerTest, TestChangeUidOwnerRule) {
- checkUidOwnerRuleForChain(DOZABLE, DOZABLE_MATCH);
- checkUidOwnerRuleForChain(STANDBY, STANDBY_MATCH);
- checkUidOwnerRuleForChain(POWERSAVE, POWERSAVE_MATCH);
- checkUidOwnerRuleForChain(RESTRICTED, RESTRICTED_MATCH);
- checkUidOwnerRuleForChain(LOW_POWER_STANDBY, LOW_POWER_STANDBY_MATCH);
- checkUidOwnerRuleForChain(OEM_DENY_1, OEM_DENY_1_MATCH);
- checkUidOwnerRuleForChain(OEM_DENY_2, OEM_DENY_2_MATCH);
- checkUidOwnerRuleForChain(OEM_DENY_3, OEM_DENY_3_MATCH);
- ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(NONE, TEST_UID, ALLOW, ALLOWLIST));
- ASSERT_EQ(-EINVAL, mTc.changeUidOwnerRule(INVALID_CHAIN, TEST_UID, ALLOW, ALLOWLIST));
-}
-
-TEST_F(TrafficControllerTest, TestReplaceUidOwnerMap) {
- std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
- checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
- checkUidMapReplace("fw_standby", uids, STANDBY_MATCH);
- checkUidMapReplace("fw_powersave", uids, POWERSAVE_MATCH);
- checkUidMapReplace("fw_restricted", uids, RESTRICTED_MATCH);
- checkUidMapReplace("fw_low_power_standby", uids, LOW_POWER_STANDBY_MATCH);
- checkUidMapReplace("fw_oem_deny_1", uids, OEM_DENY_1_MATCH);
- checkUidMapReplace("fw_oem_deny_2", uids, OEM_DENY_2_MATCH);
- checkUidMapReplace("fw_oem_deny_3", uids, OEM_DENY_3_MATCH);
- ASSERT_EQ(-EINVAL, mTc.replaceUidOwnerMap("unknow", true, uids));
-}
-
-TEST_F(TrafficControllerTest, TestReplaceSameChain) {
- std::vector<int32_t> uids = {TEST_UID, TEST_UID2, TEST_UID3};
- checkUidMapReplace("fw_dozable", uids, DOZABLE_MATCH);
- std::vector<int32_t> newUids = {TEST_UID2, TEST_UID3};
- checkUidMapReplace("fw_dozable", newUids, DOZABLE_MATCH);
-}
-
-TEST_F(TrafficControllerTest, TestDenylistUidMatch) {
- std::vector<uint32_t> appUids = {1000, 1001, 10012};
- ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
- TrafficController::IptOpInsert)));
- expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
- ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
- TrafficController::IptOpDelete)));
- expectMapEmpty(mFakeUidOwnerMap);
-}
-
-TEST_F(TrafficControllerTest, TestAllowlistUidMatch) {
- std::vector<uint32_t> appUids = {1000, 1001, 10012};
- ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
- expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
- ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
- expectMapEmpty(mFakeUidOwnerMap);
-}
-
-TEST_F(TrafficControllerTest, TestReplaceMatchUid) {
- std::vector<uint32_t> appUids = {1000, 1001, 10012};
- // Add appUids to the denylist and expect that their values are all PENALTY_BOX_MATCH.
- ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
- TrafficController::IptOpInsert)));
- expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
-
- // Add the same UIDs to the allowlist and expect that we get PENALTY_BOX_MATCH |
- // HAPPY_BOX_MATCH.
- ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpInsert)));
- expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH | PENALTY_BOX_MATCH, 0);
-
- // Remove the same UIDs from the allowlist and check the PENALTY_BOX_MATCH is still there.
- ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH, TrafficController::IptOpDelete)));
- expectUidOwnerMapValues(appUids, PENALTY_BOX_MATCH, 0);
-
- // Remove the same UIDs from the denylist and check the map is empty.
- ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
- TrafficController::IptOpDelete)));
- ASSERT_FALSE(mFakeUidOwnerMap.getFirstKey().ok());
-}
-
-TEST_F(TrafficControllerTest, TestDeleteWrongMatchSilentlyFails) {
- std::vector<uint32_t> appUids = {1000, 1001, 10012};
- // If the uid does not exist in the map, trying to delete a rule about it will fail.
- ASSERT_FALSE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
- TrafficController::IptOpDelete)));
- expectMapEmpty(mFakeUidOwnerMap);
-
- // Add denylist rules for appUids.
- ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, HAPPY_BOX_MATCH,
- TrafficController::IptOpInsert)));
- expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
-
- // Delete (non-existent) denylist rules for appUids, and check that this silently does
- // nothing if the uid is in the map but does not have denylist match. This is required because
- // NetworkManagementService will try to remove a uid from denylist after adding it to the
- // allowlist and if the remove fails it will not update the uid status.
- ASSERT_TRUE(isOk(updateUidOwnerMaps(appUids, PENALTY_BOX_MATCH,
- TrafficController::IptOpDelete)));
- expectUidOwnerMapValues(appUids, HAPPY_BOX_MATCH, 0);
-}
-
-TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRules) {
- int iif0 = 15;
- ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
- expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
-
- // Add some non-overlapping new uids. They should coexist with existing rules
- int iif1 = 16;
- ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
- expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
- expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
-
- // Overwrite some existing uids
- int iif2 = 17;
- ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif2, {1000, 2000})));
- expectUidOwnerMapValues({1001}, IIF_MATCH, iif0);
- expectUidOwnerMapValues({2001}, IIF_MATCH, iif1);
- expectUidOwnerMapValues({1000, 2000}, IIF_MATCH, iif2);
-}
-
-TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRules) {
- int iif0 = 15;
- int iif1 = 16;
- ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif0, {1000, 1001})));
- ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {2000, 2001})));
- expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif0);
- expectUidOwnerMapValues({2000, 2001}, IIF_MATCH, iif1);
-
- // Rmove some uids
- ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001, 2001})));
- expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
- expectUidOwnerMapValues({2000}, IIF_MATCH, iif1);
- checkEachUidValue({1000, 2000}, IIF_MATCH); // Make sure there are only two uids remaining
-
- // Remove non-existent uids shouldn't fail
- ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({2000, 3000})));
- expectUidOwnerMapValues({1000}, IIF_MATCH, iif0);
- checkEachUidValue({1000}, IIF_MATCH); // Make sure there are only one uid remaining
-
- // Remove everything
- ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
- expectMapEmpty(mFakeUidOwnerMap);
-}
-
-TEST_F(TrafficControllerTest, TestUpdateUidLockdownRule) {
- // Add Lockdown rules
- ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, true /* add */)));
- ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, true /* add */)));
- expectUidOwnerMapValues({1000, 1001}, LOCKDOWN_VPN_MATCH, 0);
-
- // Remove one of Lockdown rules
- ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1000, false /* add */)));
- expectUidOwnerMapValues({1001}, LOCKDOWN_VPN_MATCH, 0);
-
- // Remove remaining Lockdown rule
- ASSERT_TRUE(isOk(mTc.updateUidLockdownRule(1001, false /* add */)));
- expectMapEmpty(mFakeUidOwnerMap);
-}
-
-TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithExistingMatches) {
- // Set up existing PENALTY_BOX_MATCH rules
- ASSERT_TRUE(isOk(updateUidOwnerMaps({1000, 1001, 10012}, PENALTY_BOX_MATCH,
- TrafficController::IptOpInsert)));
- expectUidOwnerMapValues({1000, 1001, 10012}, PENALTY_BOX_MATCH, 0);
-
- // Add some partially-overlapping uid owner rules and check result
- int iif1 = 32;
- ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10012, 10013, 10014})));
- expectUidOwnerMapValues({1000, 1001}, PENALTY_BOX_MATCH, 0);
- expectUidOwnerMapValues({10012}, PENALTY_BOX_MATCH | IIF_MATCH, iif1);
- expectUidOwnerMapValues({10013, 10014}, IIF_MATCH, iif1);
-
- // Removing some PENALTY_BOX_MATCH rules should not change uid interface rule
- ASSERT_TRUE(isOk(updateUidOwnerMaps({1001, 10012}, PENALTY_BOX_MATCH,
- TrafficController::IptOpDelete)));
- expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
- expectUidOwnerMapValues({10012, 10013, 10014}, IIF_MATCH, iif1);
-
- // Remove all uid interface rules
- ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({10012, 10013, 10014})));
- expectUidOwnerMapValues({1000}, PENALTY_BOX_MATCH, 0);
- // Make sure these are the only uids left
- checkEachUidValue({1000}, PENALTY_BOX_MATCH);
-}
-
-TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesCoexistWithNewMatches) {
- int iif1 = 56;
- // Set up existing uid interface rules
- ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif1, {10001, 10002})));
- expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
-
- // Add some partially-overlapping doze rules
- EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {10002, 10003}));
- expectUidOwnerMapValues({10001}, IIF_MATCH, iif1);
- expectUidOwnerMapValues({10002}, DOZABLE_MATCH | IIF_MATCH, iif1);
- expectUidOwnerMapValues({10003}, DOZABLE_MATCH, 0);
-
- // Introduce a third rule type (powersave) on various existing UIDs
- EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {10000, 10001, 10002, 10003}));
- expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
- expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
- expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif1);
- expectUidOwnerMapValues({10003}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
-
- // Remove all doze rules
- EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_dozable", true, {}));
- expectUidOwnerMapValues({10000}, POWERSAVE_MATCH, 0);
- expectUidOwnerMapValues({10001}, POWERSAVE_MATCH | IIF_MATCH, iif1);
- expectUidOwnerMapValues({10002}, POWERSAVE_MATCH | IIF_MATCH, iif1);
- expectUidOwnerMapValues({10003}, POWERSAVE_MATCH, 0);
-
- // Remove all powersave rules, expect ownerMap to only have uid interface rules left
- EXPECT_EQ(0, mTc.replaceUidOwnerMap("fw_powersave", true, {}));
- expectUidOwnerMapValues({10001, 10002}, IIF_MATCH, iif1);
- // Make sure these are the only uids left
- checkEachUidValue({10001, 10002}, IIF_MATCH);
-}
-
-TEST_F(TrafficControllerTest, TestAddUidInterfaceFilteringRulesWithWildcard) {
- // iif=0 is a wildcard
- int iif = 0;
- // Add interface rule with wildcard to uids
- ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
- expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
-}
-
-TEST_F(TrafficControllerTest, TestRemoveUidInterfaceFilteringRulesWithWildcard) {
- // iif=0 is a wildcard
- int iif = 0;
- // Add interface rule with wildcard to two uids
- ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000, 1001})));
- expectUidOwnerMapValues({1000, 1001}, IIF_MATCH, iif);
-
- // Remove interface rule from one of the uids
- ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
- expectUidOwnerMapValues({1001}, IIF_MATCH, iif);
- checkEachUidValue({1001}, IIF_MATCH);
-
- // Remove interface rule from the remaining uid
- ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1001})));
- expectMapEmpty(mFakeUidOwnerMap);
-}
-
-TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndExistingMatches) {
- // Set up existing DOZABLE_MATCH and POWERSAVE_MATCH rule
- ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
- TrafficController::IptOpInsert)));
- ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
- TrafficController::IptOpInsert)));
-
- // iif=0 is a wildcard
- int iif = 0;
- // Add interface rule with wildcard to the existing uid
- ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
- expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
-
- // Remove interface rule with wildcard from the existing uid
- ASSERT_TRUE(isOk(mTc.removeUidInterfaceRules({1000})));
- expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH, 0);
-}
-
-TEST_F(TrafficControllerTest, TestUidInterfaceFilteringRulesWithWildcardAndNewMatches) {
- // iif=0 is a wildcard
- int iif = 0;
- // Set up existing interface rule with wildcard
- ASSERT_TRUE(isOk(mTc.addUidInterfaceRules(iif, {1000})));
-
- // Add DOZABLE_MATCH and POWERSAVE_MATCH rule to the existing uid
- ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
- TrafficController::IptOpInsert)));
- ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
- TrafficController::IptOpInsert)));
- expectUidOwnerMapValues({1000}, POWERSAVE_MATCH | DOZABLE_MATCH | IIF_MATCH, iif);
-
- // Remove DOZABLE_MATCH and POWERSAVE_MATCH rule from the existing uid
- ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, DOZABLE_MATCH,
- TrafficController::IptOpDelete)));
- ASSERT_TRUE(isOk(updateUidOwnerMaps({1000}, POWERSAVE_MATCH,
- TrafficController::IptOpDelete)));
- expectUidOwnerMapValues({1000}, IIF_MATCH, iif);
-}
-
-TEST_F(TrafficControllerTest, TestGrantInternetPermission) {
- std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
- mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
- expectMapEmpty(mFakeUidPermissionMap);
- expectPrivilegedUserSetEmpty();
-}
-
-TEST_F(TrafficControllerTest, TestRevokeInternetPermission) {
- std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
- mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
- expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
-}
-
-TEST_F(TrafficControllerTest, TestPermissionUninstalled) {
- std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
- mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
- expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
- expectPrivilegedUserSet(appUids);
-
- std::vector<uid_t> uidToRemove = {TEST_UID};
- mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidToRemove);
-
- std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
- expectUidPermissionMapValues(uidRemain, INetd::PERMISSION_UPDATE_DEVICE_STATS);
- expectPrivilegedUserSet(uidRemain);
-
- mTc.setPermissionForUids(INetd::PERMISSION_UNINSTALLED, uidRemain);
- expectMapEmpty(mFakeUidPermissionMap);
- expectPrivilegedUserSetEmpty();
-}
-
-TEST_F(TrafficControllerTest, TestGrantUpdateStatsPermission) {
- std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
- mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
- expectUidPermissionMapValues(appUids, INetd::PERMISSION_UPDATE_DEVICE_STATS);
- expectPrivilegedUserSet(appUids);
-
- mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
- expectPrivilegedUserSetEmpty();
- expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
-}
-
-TEST_F(TrafficControllerTest, TestRevokeUpdateStatsPermission) {
- std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
- mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
- expectPrivilegedUserSet(appUids);
-
- std::vector<uid_t> uidToRemove = {TEST_UID};
- mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidToRemove);
-
- std::vector<uid_t> uidRemain = {TEST_UID3, TEST_UID2};
- expectPrivilegedUserSet(uidRemain);
-
- mTc.setPermissionForUids(INetd::PERMISSION_NONE, uidRemain);
- expectPrivilegedUserSetEmpty();
-}
-
-TEST_F(TrafficControllerTest, TestGrantWrongPermission) {
- std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
- mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
- expectPrivilegedUserSetEmpty();
- expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
-}
-
-TEST_F(TrafficControllerTest, TestGrantDuplicatePermissionSlientlyFail) {
- std::vector<uid_t> appUids = {TEST_UID, TEST_UID2, TEST_UID3};
-
- mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, appUids);
- expectMapEmpty(mFakeUidPermissionMap);
-
- std::vector<uid_t> uidToAdd = {TEST_UID};
- mTc.setPermissionForUids(INetd::PERMISSION_INTERNET, uidToAdd);
-
- expectPrivilegedUserSetEmpty();
-
- mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
- expectUidPermissionMapValues(appUids, INetd::PERMISSION_NONE);
-
- mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, appUids);
- expectPrivilegedUserSet(appUids);
-
- mTc.setPermissionForUids(INetd::PERMISSION_UPDATE_DEVICE_STATS, uidToAdd);
- expectPrivilegedUserSet(appUids);
-
- mTc.setPermissionForUids(INetd::PERMISSION_NONE, appUids);
- expectPrivilegedUserSetEmpty();
-}
-
-TEST_F(TrafficControllerTest, getFirewallType) {
- static const struct TestConfig {
- ChildChain childChain;
- FirewallType firewallType;
- } testConfigs[] = {
- // clang-format off
- {NONE, DENYLIST},
- {DOZABLE, ALLOWLIST},
- {STANDBY, DENYLIST},
- {POWERSAVE, ALLOWLIST},
- {RESTRICTED, ALLOWLIST},
- {LOW_POWER_STANDBY, ALLOWLIST},
- {OEM_DENY_1, DENYLIST},
- {OEM_DENY_2, DENYLIST},
- {OEM_DENY_3, DENYLIST},
- {INVALID_CHAIN, DENYLIST},
- // clang-format on
- };
-
- for (const auto& config : testConfigs) {
- SCOPED_TRACE(fmt::format("testConfig: [{}, {}]", config.childChain, config.firewallType));
- EXPECT_EQ(config.firewallType, mTc.getFirewallType(config.childChain));
- }
-}
-
-constexpr uint32_t SOCK_CLOSE_WAIT_US = 30 * 1000;
-constexpr uint32_t ENOBUFS_POLL_WAIT_US = 10 * 1000;
-
-using android::base::Error;
-using android::base::Result;
-using android::bpf::BpfMap;
-
-// This test set up a SkDestroyListener that is running parallel with the production
-// SkDestroyListener. The test will create thousands of sockets and tag them on the
-// production cookieUidTagMap and close them in a short time. When the number of
-// sockets get closed exceeds the buffer size, it will start to return ENOBUFF
-// error. The error will be ignored by the production SkDestroyListener and the
-// test will clean up the tags in tearDown if there is any remains.
-
-// TODO: Instead of test the ENOBUFF error, we can test the production
-// SkDestroyListener to see if it failed to delete a tagged socket when ENOBUFF
-// triggered.
-class NetlinkListenerTest : public testing::Test {
- protected:
- NetlinkListenerTest() {}
- BpfMap<uint64_t, UidTagValue> mCookieTagMap;
-
- void SetUp() {
- mCookieTagMap.init(COOKIE_TAG_MAP_PATH);
- ASSERT_TRUE(mCookieTagMap.isValid());
- }
-
- void TearDown() {
- const auto deleteTestCookieEntries = [](const uint64_t& key, const UidTagValue& value,
- BpfMap<uint64_t, UidTagValue>& map) {
- if ((value.uid == TEST_UID) && (value.tag == TEST_TAG)) {
- Result<void> res = map.deleteValue(key);
- if (res.ok() || (res.error().code() == ENOENT)) {
- return Result<void>();
- }
- ALOGE("Failed to delete data(cookie = %" PRIu64 "): %s", key,
- strerror(res.error().code()));
- }
- // Move forward to next cookie in the map.
- return Result<void>();
- };
- EXPECT_RESULT_OK(mCookieTagMap.iterateWithValue(deleteTestCookieEntries));
- }
-
- Result<void> checkNoGarbageTagsExist() {
- const auto checkGarbageTags = [](const uint64_t&, const UidTagValue& value,
- const BpfMap<uint64_t, UidTagValue>&) -> Result<void> {
- if ((TEST_UID == value.uid) && (TEST_TAG == value.tag)) {
- return Error(EUCLEAN) << "Closed socket is not untagged";
- }
- return {};
- };
- return mCookieTagMap.iterateWithValue(checkGarbageTags);
- }
-
- bool checkMassiveSocketDestroy(int totalNumber, bool expectError) {
- std::unique_ptr<android::netdutils::NetlinkListenerInterface> skDestroyListener;
- auto result = android::net::TrafficController::makeSkDestroyListener();
- if (!isOk(result)) {
- ALOGE("Unable to create SkDestroyListener: %s", toString(result).c_str());
- } else {
- skDestroyListener = std::move(result.value());
- }
- int rxErrorCount = 0;
- // Rx handler extracts nfgenmsg looks up and invokes registered dispatch function.
- const auto rxErrorHandler = [&rxErrorCount](const int, const int) { rxErrorCount++; };
- skDestroyListener->registerSkErrorHandler(rxErrorHandler);
- int fds[totalNumber];
- for (int i = 0; i < totalNumber; i++) {
- fds[i] = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
- // The likely reason for a failure is running out of available file descriptors.
- EXPECT_LE(0, fds[i]) << i << " of " << totalNumber;
- if (fds[i] < 0) {
- // EXPECT_LE already failed above, so test case is a failure, but we don't
- // want potentially tens of thousands of extra failures creating and then
- // closing all these fds cluttering up the logs.
- totalNumber = i;
- break;
- };
- libnetd_updatable_tagSocket(fds[i], TEST_TAG, TEST_UID, 1000);
- }
-
- // TODO: Use a separate thread that has its own fd table so we can
- // close sockets even faster simply by terminating that thread.
- for (int i = 0; i < totalNumber; i++) {
- EXPECT_EQ(0, close(fds[i]));
- }
- // wait a bit for netlink listener to handle all the messages.
- usleep(SOCK_CLOSE_WAIT_US);
- if (expectError) {
- // If ENOBUFS triggered, check it only called into the handler once, ie.
- // that the netlink handler is not spinning.
- int currentErrorCount = rxErrorCount;
- // 0 error count is acceptable because the system has chances to close all sockets
- // normally.
- EXPECT_LE(0, rxErrorCount);
- if (!rxErrorCount) return true;
-
- usleep(ENOBUFS_POLL_WAIT_US);
- EXPECT_EQ(currentErrorCount, rxErrorCount);
- } else {
- EXPECT_RESULT_OK(checkNoGarbageTagsExist());
- EXPECT_EQ(0, rxErrorCount);
- }
- return false;
- }
-};
-
-TEST_F(NetlinkListenerTest, TestAllSocketUntagged) {
- checkMassiveSocketDestroy(10, false);
- checkMassiveSocketDestroy(100, false);
-}
-
-// Disabled because flaky on blueline-userdebug; this test relies on the main thread
-// winning a race against the NetlinkListener::run() thread. There's no way to ensure
-// things will be scheduled the same way across all architectures and test environments.
-TEST_F(NetlinkListenerTest, DISABLED_TestSkDestroyError) {
- bool needRetry = false;
- int retryCount = 0;
- do {
- needRetry = checkMassiveSocketDestroy(32500, true);
- if (needRetry) retryCount++;
- } while (needRetry && retryCount < 3);
- // Should review test if it can always close all sockets correctly.
- EXPECT_GT(3, retryCount);
-}
-
-
-} // namespace net
-} // namespace android
diff --git a/service/native/include/TrafficController.h b/service/native/include/TrafficController.h
deleted file mode 100644
index 86cf50a..0000000
--- a/service/native/include/TrafficController.h
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright (C) 2022 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#pragma once
-
-#include <set>
-#include <Common.h>
-
-#include "android-base/thread_annotations.h"
-#include "bpf/BpfMap.h"
-#include "netd.h"
-#include "netdutils/NetlinkListener.h"
-#include "netdutils/StatusOr.h"
-
-namespace android {
-namespace net {
-
-using netdutils::StatusOr;
-
-class TrafficController {
- public:
- /*
- * Initialize the whole controller
- */
- netdutils::Status start(bool startSkDestroyListener);
-
- /*
- * Swap the stats map config from current active stats map to the idle one.
- */
- netdutils::Status swapActiveStatsMap() EXCLUDES(mMutex);
-
- int changeUidOwnerRule(ChildChain chain, const uid_t uid, FirewallRule rule, FirewallType type);
-
- int removeUidOwnerRule(const uid_t uid);
-
- int replaceUidOwnerMap(const std::string& name, bool isAllowlist,
- const std::vector<int32_t>& uids);
-
- enum IptOp { IptOpInsert, IptOpDelete };
-
- netdutils::Status updateOwnerMapEntry(UidOwnerMatchType match, uid_t uid, FirewallRule rule,
- FirewallType type) EXCLUDES(mMutex);
-
- netdutils::Status replaceRulesInMap(UidOwnerMatchType match, const std::vector<int32_t>& uids)
- EXCLUDES(mMutex);
-
- netdutils::Status addUidInterfaceRules(const int ifIndex, const std::vector<int32_t>& uids)
- EXCLUDES(mMutex);
- netdutils::Status removeUidInterfaceRules(const std::vector<int32_t>& uids) EXCLUDES(mMutex);
-
- netdutils::Status updateUidLockdownRule(const uid_t uid, const bool add) EXCLUDES(mMutex);
-
- netdutils::Status updateUidOwnerMap(const uint32_t uid,
- UidOwnerMatchType matchType, IptOp op) EXCLUDES(mMutex);
-
- int toggleUidOwnerMap(ChildChain chain, bool enable) EXCLUDES(mMutex);
-
- static netdutils::StatusOr<std::unique_ptr<netdutils::NetlinkListenerInterface>>
- makeSkDestroyListener();
-
- void setPermissionForUids(int permission, const std::vector<uid_t>& uids) EXCLUDES(mMutex);
-
- FirewallType getFirewallType(ChildChain);
-
- static const char* LOCAL_DOZABLE;
- static const char* LOCAL_STANDBY;
- static const char* LOCAL_POWERSAVE;
- static const char* LOCAL_RESTRICTED;
- static const char* LOCAL_LOW_POWER_STANDBY;
- static const char* LOCAL_OEM_DENY_1;
- static const char* LOCAL_OEM_DENY_2;
- static const char* LOCAL_OEM_DENY_3;
-
- private:
- /*
- * mCookieTagMap: Store the corresponding tag and uid for a specific socket.
- * DO NOT hold any locks when modifying this map, otherwise when the untag
- * operation is waiting for a lock hold by other process and there are more
- * sockets being closed than can fit in the socket buffer of the netlink socket
- * that receives them, then the kernel will drop some of these sockets and we
- * won't delete their tags.
- * Map Key: uint64_t socket cookie
- * Map Value: UidTagValue, contains a uint32 uid and a uint32 tag.
- */
- bpf::BpfMap<uint64_t, UidTagValue> mCookieTagMap GUARDED_BY(mMutex);
-
- /*
- * mUidCounterSetMap: Store the counterSet of a specific uid.
- * Map Key: uint32 uid.
- * Map Value: uint32 counterSet specifies if the traffic is a background
- * or foreground traffic.
- */
- bpf::BpfMap<uint32_t, uint8_t> mUidCounterSetMap GUARDED_BY(mMutex);
-
- /*
- * mAppUidStatsMap: Store the total traffic stats for a uid regardless of
- * tag, counterSet and iface. The stats is used by TrafficStats.getUidStats
- * API to return persistent stats for a specific uid since device boot.
- */
- bpf::BpfMap<uint32_t, StatsValue> mAppUidStatsMap;
-
- /*
- * mStatsMapA/mStatsMapB: Store the traffic statistics for a specific
- * combination of uid, tag, iface and counterSet. These two maps contain
- * both tagged and untagged traffic.
- * Map Key: StatsKey contains the uid, tag, counterSet and ifaceIndex
- * information.
- * Map Value: Stats, contains packet count and byte count of each
- * transport protocol on egress and ingress direction.
- */
- bpf::BpfMap<StatsKey, StatsValue> mStatsMapA GUARDED_BY(mMutex);
-
- bpf::BpfMap<StatsKey, StatsValue> mStatsMapB GUARDED_BY(mMutex);
-
- /*
- * mIfaceIndexNameMap: Store the index name pair of each interface show up
- * on the device since boot. The interface index is used by the eBPF program
- * to correctly match the iface name when receiving a packet.
- */
- bpf::BpfMap<uint32_t, IfaceValue> mIfaceIndexNameMap;
-
- /*
- * mIfaceStataMap: Store per iface traffic stats gathered from xt_bpf
- * filter.
- */
- bpf::BpfMap<uint32_t, StatsValue> mIfaceStatsMap;
-
- /*
- * mConfigurationMap: Store the current network policy about uid filtering
- * and the current stats map in use. There are two configuration entries in
- * the map right now:
- * - Entry with UID_RULES_CONFIGURATION_KEY:
- * Store the configuration for the current uid rules. It indicates the device
- * is in doze/powersave/standby/restricted/low power standby/oem deny mode.
- * - Entry with CURRENT_STATS_MAP_CONFIGURATION_KEY:
- * Stores the current live stats map that kernel program is writing to.
- * Userspace can do scraping and cleaning job on the other one depending on the
- * current configs.
- */
- bpf::BpfMap<uint32_t, uint32_t> mConfigurationMap GUARDED_BY(mMutex);
-
- /*
- * mUidOwnerMap: Store uids that are used for bandwidth control uid match.
- */
- bpf::BpfMap<uint32_t, UidOwnerValue> mUidOwnerMap GUARDED_BY(mMutex);
-
- /*
- * mUidOwnerMap: Store uids that are used for INTERNET permission check.
- */
- bpf::BpfMap<uint32_t, uint8_t> mUidPermissionMap GUARDED_BY(mMutex);
-
- std::unique_ptr<netdutils::NetlinkListenerInterface> mSkDestroyListener;
-
- netdutils::Status removeRule(uint32_t uid, UidOwnerMatchType match) REQUIRES(mMutex);
-
- netdutils::Status addRule(uint32_t uid, UidOwnerMatchType match, uint32_t iif = 0)
- REQUIRES(mMutex);
-
- std::mutex mMutex;
-
- netdutils::Status initMaps() EXCLUDES(mMutex);
-
- // Keep track of uids that have permission UPDATE_DEVICE_STATS so we don't
- // need to call back to system server for permission check.
- std::set<uid_t> mPrivilegedUser GUARDED_BY(mMutex);
-
- // For testing
- friend class TrafficControllerTest;
-};
-
-} // namespace net
-} // namespace android
diff --git a/service/src/com/android/server/BpfNetMaps.java b/service/src/com/android/server/BpfNetMaps.java
index f20159c..b7e928d 100644
--- a/service/src/com/android/server/BpfNetMaps.java
+++ b/service/src/com/android/server/BpfNetMaps.java
@@ -35,14 +35,6 @@
import static android.net.BpfNetMapsUtils.getMatchByFirewallChain;
import static android.net.BpfNetMapsUtils.isFirewallAllowList;
import static android.net.BpfNetMapsUtils.matchToString;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_DOZABLE;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_1;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_2;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_OEM_DENY_3;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_POWERSAVE;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_RESTRICTED;
-import static android.net.ConnectivityManager.FIREWALL_CHAIN_STANDBY;
import static android.net.ConnectivityManager.FIREWALL_RULE_ALLOW;
import static android.net.ConnectivityManager.FIREWALL_RULE_DENY;
import static android.net.INetd.PERMISSION_INTERNET;
@@ -76,10 +68,8 @@
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;
import com.android.net.module.util.Struct;
import com.android.net.module.util.Struct.S32;
@@ -116,7 +106,6 @@
// Use legacy netd for releases before T.
private static boolean sInitialized = false;
- private static Boolean sEnableJavaBpfMap = null;
private static final String BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP =
"bpf_net_maps_force_disable_java_bpf_map";
@@ -149,14 +138,6 @@
);
/**
- * Set sEnableJavaBpfMap for test.
- */
- @VisibleForTesting
- public static void setEnableJavaBpfMapForTest(boolean enable) {
- sEnableJavaBpfMap = enable;
- }
-
- /**
* Set configurationMap for test.
*/
@VisibleForTesting
@@ -319,22 +300,10 @@
*/
private static synchronized void ensureInitialized(final Context context) {
if (sInitialized) return;
- if (sEnableJavaBpfMap == null) {
- sEnableJavaBpfMap = SdkLevel.isAtLeastU() ||
- DeviceConfigUtils.isTetheringFeatureNotChickenedOut(context,
- BPF_NET_MAPS_FORCE_DISABLE_JAVA_BPF_MAP);
- }
- Log.d(TAG, "BpfNetMaps is initialized with sEnableJavaBpfMap=" + sEnableJavaBpfMap);
-
initBpfMaps();
- native_init(!sEnableJavaBpfMap /* startSkDestroyListener */);
sInitialized = true;
}
- public boolean isSkDestroyListenerRunning() {
- return !sEnableJavaBpfMap;
- }
-
/**
* Dependencies of BpfNetMaps, for injection in tests.
*/
@@ -476,12 +445,7 @@
public void addNaughtyApp(final int uid) {
throwIfPreT("addNaughtyApp is not available on pre-T devices");
- if (sEnableJavaBpfMap) {
- addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
- } else {
- final int err = native_addNaughtyApp(uid);
- maybeThrow(err, "Unable to add naughty app");
- }
+ addRule(uid, PENALTY_BOX_MATCH, "addNaughtyApp");
}
/**
@@ -495,12 +459,7 @@
public void removeNaughtyApp(final int uid) {
throwIfPreT("removeNaughtyApp is not available on pre-T devices");
- if (sEnableJavaBpfMap) {
- removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
- } else {
- final int err = native_removeNaughtyApp(uid);
- maybeThrow(err, "Unable to remove naughty app");
- }
+ removeRule(uid, PENALTY_BOX_MATCH, "removeNaughtyApp");
}
/**
@@ -514,12 +473,7 @@
public void addNiceApp(final int uid) {
throwIfPreT("addNiceApp is not available on pre-T devices");
- if (sEnableJavaBpfMap) {
- addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
- } else {
- final int err = native_addNiceApp(uid);
- maybeThrow(err, "Unable to add nice app");
- }
+ addRule(uid, HAPPY_BOX_MATCH, "addNiceApp");
}
/**
@@ -533,12 +487,7 @@
public void removeNiceApp(final int uid) {
throwIfPreT("removeNiceApp is not available on pre-T devices");
- if (sEnableJavaBpfMap) {
- removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
- } else {
- final int err = native_removeNiceApp(uid);
- maybeThrow(err, "Unable to remove nice app");
- }
+ removeRule(uid, HAPPY_BOX_MATCH, "removeNiceApp");
}
/**
@@ -554,21 +503,16 @@
public void setChildChain(final int childChain, final boolean enable) {
throwIfPreT("setChildChain is not available on pre-T devices");
- if (sEnableJavaBpfMap) {
- final long match = getMatchByFirewallChain(childChain);
- try {
- synchronized (sUidRulesConfigBpfMapLock) {
- final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
- final long newConfig = enable ? (config.val | match) : (config.val & ~match);
- sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
- }
- } catch (ErrnoException e) {
- throw new ServiceSpecificException(e.errno,
- "Unable to set child chain: " + Os.strerror(e.errno));
+ final long match = getMatchByFirewallChain(childChain);
+ try {
+ synchronized (sUidRulesConfigBpfMapLock) {
+ final U32 config = sConfigurationMap.getValue(UID_RULES_CONFIGURATION_KEY);
+ final long newConfig = enable ? (config.val | match) : (config.val & ~match);
+ sConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(newConfig));
}
- } else {
- final int err = native_setChildChain(childChain, enable);
- maybeThrow(err, "Unable to set child chain");
+ } catch (ErrnoException e) {
+ throw new ServiceSpecificException(e.errno,
+ "Unable to set child chain: " + Os.strerror(e.errno));
}
}
@@ -611,75 +555,38 @@
public void replaceUidChain(final int chain, final int[] uids) {
throwIfPreT("replaceUidChain is not available on pre-T devices");
- if (sEnableJavaBpfMap) {
- final long match;
- try {
- match = getMatchByFirewallChain(chain);
- } catch (ServiceSpecificException e) {
- // Throws IllegalArgumentException to keep the behavior of
- // ConnectivityManager#replaceFirewallChain API
- throw new IllegalArgumentException("Invalid firewall chain: " + chain);
- }
- final Set<Integer> uidSet = asSet(uids);
- final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
- try {
- synchronized (sUidOwnerMap) {
- sUidOwnerMap.forEach((uid, config) -> {
- // config could be null if there is a concurrent entry deletion.
- // http://b/220084230. But sUidOwnerMap update must be done while holding a
- // lock, so this should not happen.
- if (config == null) {
- Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
- } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
- uidSetToRemoveRule.add((int) uid.val);
- }
- });
+ final long match;
+ try {
+ match = getMatchByFirewallChain(chain);
+ } catch (ServiceSpecificException e) {
+ // Throws IllegalArgumentException to keep the behavior of
+ // ConnectivityManager#replaceFirewallChain API
+ throw new IllegalArgumentException("Invalid firewall chain: " + chain);
+ }
+ final Set<Integer> uidSet = asSet(uids);
+ final Set<Integer> uidSetToRemoveRule = new ArraySet<>();
+ try {
+ synchronized (sUidOwnerMap) {
+ sUidOwnerMap.forEach((uid, config) -> {
+ // config could be null if there is a concurrent entry deletion.
+ // http://b/220084230. But sUidOwnerMap update must be done while holding a
+ // lock, so this should not happen.
+ if (config == null) {
+ Log.wtf(TAG, "sUidOwnerMap entry was deleted while holding a lock");
+ } else if (!uidSet.contains((int) uid.val) && (config.rule & match) != 0) {
+ uidSetToRemoveRule.add((int) uid.val);
+ }
+ });
- for (final int uid : uidSetToRemoveRule) {
- removeRule(uid, match, "replaceUidChain");
- }
- for (final int uid : uids) {
- addRule(uid, match, "replaceUidChain");
- }
+ for (final int uid : uidSetToRemoveRule) {
+ removeRule(uid, match, "replaceUidChain");
}
- } catch (ErrnoException | ServiceSpecificException e) {
- Log.e(TAG, "replaceUidChain failed: " + e);
+ for (final int uid : uids) {
+ addRule(uid, match, "replaceUidChain");
+ }
}
- } else {
- final int err;
- switch (chain) {
- case FIREWALL_CHAIN_DOZABLE:
- err = native_replaceUidChain("fw_dozable", true /* isAllowList */, uids);
- break;
- case FIREWALL_CHAIN_STANDBY:
- err = native_replaceUidChain("fw_standby", false /* isAllowList */, uids);
- break;
- case FIREWALL_CHAIN_POWERSAVE:
- err = native_replaceUidChain("fw_powersave", true /* isAllowList */, uids);
- break;
- case FIREWALL_CHAIN_RESTRICTED:
- err = native_replaceUidChain("fw_restricted", true /* isAllowList */, uids);
- break;
- case FIREWALL_CHAIN_LOW_POWER_STANDBY:
- err = native_replaceUidChain(
- "fw_low_power_standby", true /* isAllowList */, uids);
- break;
- case FIREWALL_CHAIN_OEM_DENY_1:
- err = native_replaceUidChain("fw_oem_deny_1", false /* isAllowList */, uids);
- break;
- case FIREWALL_CHAIN_OEM_DENY_2:
- err = native_replaceUidChain("fw_oem_deny_2", false /* isAllowList */, uids);
- break;
- case FIREWALL_CHAIN_OEM_DENY_3:
- err = native_replaceUidChain("fw_oem_deny_3", false /* isAllowList */, uids);
- break;
- default:
- throw new IllegalArgumentException("replaceFirewallChain with invalid chain: "
- + chain);
- }
- if (err != 0) {
- Log.e(TAG, "replaceUidChain failed: " + Os.strerror(-err));
- }
+ } catch (ErrnoException | ServiceSpecificException e) {
+ Log.e(TAG, "replaceUidChain failed: " + e);
}
}
@@ -696,20 +603,15 @@
public void setUidRule(final int childChain, final int uid, final int firewallRule) {
throwIfPreT("setUidRule is not available on pre-T devices");
- if (sEnableJavaBpfMap) {
- final long match = getMatchByFirewallChain(childChain);
- final boolean isAllowList = isFirewallAllowList(childChain);
- final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
- || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
+ final long match = getMatchByFirewallChain(childChain);
+ final boolean isAllowList = isFirewallAllowList(childChain);
+ final boolean add = (firewallRule == FIREWALL_RULE_ALLOW && isAllowList)
+ || (firewallRule == FIREWALL_RULE_DENY && !isAllowList);
- if (add) {
- addRule(uid, match, "setUidRule");
- } else {
- removeRule(uid, match, "setUidRule");
- }
+ if (add) {
+ addRule(uid, match, "setUidRule");
} else {
- final int err = native_setUidRule(childChain, uid, firewallRule);
- maybeThrow(err, "Unable to set uid rule");
+ removeRule(uid, match, "setUidRule");
}
}
@@ -812,29 +714,24 @@
return;
}
- if (sEnableJavaBpfMap) {
- // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
- // ifIndex is set to 0.
- final int ifIndex;
- if (ifName == null) {
- ifIndex = 0;
- } else {
- ifIndex = mDeps.getIfIndex(ifName);
- if (ifIndex == 0) {
- throw new ServiceSpecificException(ENODEV,
- "Failed to get index of interface " + ifName);
- }
- }
- for (final int uid : uids) {
- try {
- addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
- } catch (ServiceSpecificException e) {
- Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
- }
- }
+ // Null ifName is a wildcard to allow apps to receive packets on all interfaces and
+ // ifIndex is set to 0.
+ final int ifIndex;
+ if (ifName == null) {
+ ifIndex = 0;
} else {
- final int err = native_addUidInterfaceRules(ifName, uids);
- maybeThrow(err, "Unable to add uid interface rules");
+ ifIndex = mDeps.getIfIndex(ifName);
+ if (ifIndex == 0) {
+ throw new ServiceSpecificException(ENODEV,
+ "Failed to get index of interface " + ifName);
+ }
+ }
+ for (final int uid : uids) {
+ try {
+ addRule(uid, IIF_MATCH, ifIndex, "addUidInterfaceRules");
+ } catch (ServiceSpecificException e) {
+ Log.e(TAG, "addRule failed uid=" + uid + " ifName=" + ifName + ", " + e);
+ }
}
}
@@ -855,17 +752,12 @@
return;
}
- if (sEnableJavaBpfMap) {
- for (final int uid : uids) {
- try {
- removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
- } catch (ServiceSpecificException e) {
- Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
- }
+ for (final int uid : uids) {
+ try {
+ removeRule(uid, IIF_MATCH, "removeUidInterfaceRules");
+ } catch (ServiceSpecificException e) {
+ Log.e(TAG, "removeRule failed uid=" + uid + ", " + e);
}
- } else {
- final int err = native_removeUidInterfaceRules(uids);
- maybeThrow(err, "Unable to remove uid interface rules");
}
}
@@ -881,15 +773,10 @@
public void updateUidLockdownRule(final int uid, final boolean add) {
throwIfPreT("updateUidLockdownRule is not available on pre-T devices");
- if (sEnableJavaBpfMap) {
- if (add) {
- addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
- } else {
- removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
- }
+ if (add) {
+ addRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
} else {
- final int err = native_updateUidLockdownRule(uid, add);
- maybeThrow(err, "Unable to update lockdown rule");
+ removeRule(uid, LOCKDOWN_VPN_MATCH, "updateUidLockdownRule");
}
}
@@ -904,33 +791,28 @@
public void swapActiveStatsMap() {
throwIfPreT("swapActiveStatsMap is not available on pre-T devices");
- if (sEnableJavaBpfMap) {
- try {
- synchronized (sCurrentStatsMapConfigLock) {
- final long config = sConfigurationMap.getValue(
- CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
- final long newConfig = (config == STATS_SELECT_MAP_A)
- ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
- sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
- new U32(newConfig));
- }
- } catch (ErrnoException e) {
- throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
+ try {
+ synchronized (sCurrentStatsMapConfigLock) {
+ final long config = sConfigurationMap.getValue(
+ CURRENT_STATS_MAP_CONFIGURATION_KEY).val;
+ final long newConfig = (config == STATS_SELECT_MAP_A)
+ ? STATS_SELECT_MAP_B : STATS_SELECT_MAP_A;
+ sConfigurationMap.updateEntry(CURRENT_STATS_MAP_CONFIGURATION_KEY,
+ new U32(newConfig));
}
-
- // After changing the config, it's needed to make sure all the current running eBPF
- // programs are finished and all the CPUs are aware of this config change before the old
- // map is modified. So special hack is needed here to wait for the kernel to do a
- // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
- // be available to all cores and the next eBPF programs triggered inside the kernel will
- // use the new map configuration. So once this function returns it is safe to modify the
- // old stats map without concerning about race between the kernel and userspace.
- final int err = mDeps.synchronizeKernelRCU();
- maybeThrow(err, "synchronizeKernelRCU failed");
- } else {
- final int err = native_swapActiveStatsMap();
- maybeThrow(err, "Unable to swap active stats map");
+ } catch (ErrnoException e) {
+ throw new ServiceSpecificException(e.errno, "Failed to swap active stats map");
}
+
+ // After changing the config, it's needed to make sure all the current running eBPF
+ // programs are finished and all the CPUs are aware of this config change before the old
+ // map is modified. So special hack is needed here to wait for the kernel to do a
+ // synchronize_rcu(). Once the kernel called synchronize_rcu(), the updated config will
+ // be available to all cores and the next eBPF programs triggered inside the kernel will
+ // use the new map configuration. So once this function returns it is safe to modify the
+ // old stats map without concerning about race between the kernel and userspace.
+ final int err = mDeps.synchronizeKernelRCU();
+ maybeThrow(err, "synchronizeKernelRCU failed");
}
/**
@@ -949,29 +831,25 @@
return;
}
- if (sEnableJavaBpfMap) {
- // Remove the entry if package is uninstalled or uid has only INTERNET permission.
- if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
- for (final int uid : uids) {
- try {
- sUidPermissionMap.deleteEntry(new S32(uid));
- } catch (ErrnoException e) {
- Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
- }
- }
- return;
- }
-
+ // Remove the entry if package is uninstalled or uid has only INTERNET permission.
+ if (permissions == PERMISSION_UNINSTALLED || permissions == PERMISSION_INTERNET) {
for (final int uid : uids) {
try {
- sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
+ sUidPermissionMap.deleteEntry(new S32(uid));
} catch (ErrnoException e) {
- Log.e(TAG, "Failed to set permission "
- + permissions + " to uid " + uid + ": " + e);
+ Log.e(TAG, "Failed to remove uid " + uid + " from permission map: " + e);
}
}
- } else {
- native_setPermissionForUids(permissions, uids);
+ return;
+ }
+
+ for (final int uid : uids) {
+ try {
+ sUidPermissionMap.updateEntry(new S32(uid), new U8((short) permissions));
+ } catch (ErrnoException e) {
+ Log.e(TAG, "Failed to set permission "
+ + permissions + " to uid " + uid + ": " + e);
+ }
}
}
@@ -1147,7 +1025,6 @@
pw.println("TrafficController"); // required by CTS testDumpBpfNetMaps
pw.println();
- pw.println("sEnableJavaBpfMap: " + sEnableJavaBpfMap);
if (verbose) {
pw.println();
pw.println("BPF map content:");
@@ -1186,44 +1063,5 @@
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private static native void native_init(boolean startSkDestroyListener);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native int native_addNaughtyApp(int uid);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native int native_removeNaughtyApp(int uid);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native int native_addNiceApp(int uid);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native int native_removeNiceApp(int uid);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native int native_setChildChain(int childChain, boolean enable);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native int native_replaceUidChain(String name, boolean isAllowlist, int[] uids);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native int native_setUidRule(int childChain, int uid, int firewallRule);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native int native_addUidInterfaceRules(String ifName, int[] uids);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native int native_removeUidInterfaceRules(int[] uids);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native int native_updateUidLockdownRule(int uid, boolean add);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native int native_swapActiveStatsMap();
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
- private native void native_setPermissionForUids(int permissions, int[] uids);
-
- @RequiresApi(Build.VERSION_CODES.TIRAMISU)
private static native int native_synchronizeKernelRCU();
}
diff --git a/service/src/com/android/server/ConnectivityService.java b/service/src/com/android/server/ConnectivityService.java
index 50b4134..d8417c1 100755
--- a/service/src/com/android/server/ConnectivityService.java
+++ b/service/src/com/android/server/ConnectivityService.java
@@ -168,6 +168,7 @@
import android.net.IpPrefix;
import android.net.LinkProperties;
import android.net.LocalNetworkConfig;
+import android.net.LocalNetworkInfo;
import android.net.MatchAllNetworkSpecifier;
import android.net.NativeNetworkConfig;
import android.net.NativeNetworkType;
@@ -4183,7 +4184,7 @@
}
case NetworkAgent.EVENT_LOCAL_NETWORK_CONFIG_CHANGED: {
final LocalNetworkConfig config = (LocalNetworkConfig) arg.second;
- updateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
+ handleUpdateLocalNetworkConfig(nai, nai.localNetworkConfig, config);
break;
}
case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
@@ -4946,7 +4947,7 @@
notifyIfacesChangedForNetworkStats();
// If this was a local network forwarded to some upstream, or if some local network was
// forwarded to this nai, then disable forwarding rules now.
- maybeDisableForwardRulesForDisconnectingNai(nai);
+ maybeDisableForwardRulesForDisconnectingNai(nai, true /* sendCallbacks */);
// If this is a local network with an upstream selector, remove the associated network
// request.
if (nai.isLocalNetwork()) {
@@ -5069,7 +5070,7 @@
}
private void maybeDisableForwardRulesForDisconnectingNai(
- @NonNull final NetworkAgentInfo disconnecting) {
+ @NonNull final NetworkAgentInfo disconnecting, final boolean sendCallbacks) {
// Step 1 : maybe this network was the upstream for one or more local networks.
for (final NetworkAgentInfo local : mNetworkAgentInfos) {
if (!local.isLocalNetwork()) continue;
@@ -5082,6 +5083,13 @@
final NetworkAgentInfo satisfier = nri.getSatisfier();
if (disconnecting != satisfier) continue;
removeLocalNetworkUpstream(local, disconnecting);
+ // Set the satisfier to null immediately so that the LOCAL_NETWORK_CHANGED callback
+ // correctly contains null as an upstream.
+ if (sendCallbacks) {
+ nri.setSatisfier(null, null);
+ notifyNetworkCallbacks(local,
+ ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
+ }
}
// Step 2 : maybe this is a local network that had an upstream.
@@ -5148,8 +5156,10 @@
mDscpPolicyTracker.removeAllDscpPolicies(nai, false);
}
// Remove any forwarding rules to and from the interface for this network, since
- // the interface is going to go away.
- maybeDisableForwardRulesForDisconnectingNai(nai);
+ // the interface is going to go away. Don't send the callbacks however ; if the network
+ // was is being disconnected the callbacks have already been sent, and if it is being
+ // destroyed pending replacement they will be sent when it is disconnected.
+ maybeDisableForwardRulesForDisconnectingNai(nai, false /* sendCallbacks */);
try {
mNetd.networkDestroy(nai.network.getNetId());
} catch (RemoteException | ServiceSpecificException e) {
@@ -8320,7 +8330,7 @@
}
if (nai.isLocalNetwork()) {
- updateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
+ handleUpdateLocalNetworkConfig(nai, null /* oldConfig */, nai.localNetworkConfig);
}
nai.notifyRegistered();
NetworkInfo networkInfo = nai.networkInfo;
@@ -8988,7 +8998,7 @@
}
// oldConfig is null iff this is the original registration of the local network config
- private void updateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
+ private void handleUpdateLocalNetworkConfig(@NonNull final NetworkAgentInfo nai,
@Nullable final LocalNetworkConfig oldConfig,
@NonNull final LocalNetworkConfig newConfig) {
if (!nai.isLocalNetwork()) {
@@ -9021,6 +9031,12 @@
// If there is an old satisfier, but no new request, then remove the old upstream.
removeLocalNetworkUpstream(nai, oldSatisfier);
nai.localNetworkConfig = configBuilder.build();
+ // When there is a new request, the rematch sees the new request and sends the
+ // LOCAL_NETWORK_INFO_CHANGED callbacks accordingly.
+ // But here there is no new request, so the rematch won't see anything. Send
+ // callbacks to apps now to tell them about the loss of upstream.
+ notifyNetworkCallbacks(nai,
+ ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
return;
}
}
@@ -9042,12 +9058,14 @@
nri.setSatisfier(oldSatisfier, nr);
}
nai.localNetworkConfig = configBuilder.build();
+ // handleRegisterNetworkRequest causes a rematch. The rematch must happen after
+ // nai.localNetworkConfig is set, since it will base its callbacks on the old
+ // satisfier and the new request.
handleRegisterNetworkRequest(nri);
} else {
configBuilder.setUpstreamSelector(oldRequest);
nai.localNetworkConfig = configBuilder.build();
}
-
}
/**
@@ -9378,6 +9396,21 @@
releasePendingNetworkRequestWithDelay(pendingIntent);
}
+ @Nullable
+ private LocalNetworkInfo localNetworkInfoForNai(@NonNull final NetworkAgentInfo nai) {
+ if (!nai.isLocalNetwork()) return null;
+ final Network upstream;
+ final NetworkRequest selector = nai.localNetworkConfig.getUpstreamSelector();
+ if (null == selector) {
+ upstream = null;
+ } else {
+ final NetworkRequestInfo upstreamNri = mNetworkRequests.get(selector);
+ final NetworkAgentInfo satisfier = upstreamNri.getSatisfier();
+ upstream = (null == satisfier) ? null : satisfier.network;
+ }
+ return new LocalNetworkInfo.Builder().setUpstreamNetwork(upstream).build();
+ }
+
// networkAgent is only allowed to be null if notificationType is
// CALLBACK_UNAVAIL. This is because UNAVAIL is about no network being
// available, while all other cases are about some particular network.
@@ -9413,6 +9446,10 @@
putParcelable(bundle, nc);
putParcelable(bundle, linkPropertiesRestrictedForCallerPermissions(
networkAgent.linkProperties, nri.mPid, nri.mUid));
+ // The local network info is often null, so can't use the static putParcelable
+ // method here.
+ bundle.putParcelable(LocalNetworkInfo.class.getSimpleName(),
+ localNetworkInfoForNai(networkAgent));
// For this notification, arg1 contains the blocked status.
msg.arg1 = arg1;
break;
@@ -9444,6 +9481,14 @@
msg.arg1 = arg1;
break;
}
+ case ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED: {
+ if (!networkAgent.isLocalNetwork()) {
+ Log.wtf(TAG, "Callback for local info for a non-local network");
+ return;
+ }
+ putParcelable(bundle, localNetworkInfoForNai(networkAgent));
+ break;
+ }
}
msg.what = notificationType;
msg.setData(bundle);
@@ -10077,6 +10122,7 @@
loge("Can't update forwarding rules", e);
}
}
+ notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOCAL_NETWORK_INFO_CHANGED);
}
updateLegacyTypeTrackerAndVpnLockdownForRematch(changes, nais);
diff --git a/staticlibs/testutils/devicetests/com/android/testutils/TestableNetworkCallback.kt b/staticlibs/testutils/devicetests/com/android/testutils/TestableNetworkCallback.kt
index df9c61a..05c0444 100644
--- a/staticlibs/testutils/devicetests/com/android/testutils/TestableNetworkCallback.kt
+++ b/staticlibs/testutils/devicetests/com/android/testutils/TestableNetworkCallback.kt
@@ -18,6 +18,7 @@
import android.net.ConnectivityManager.NetworkCallback
import android.net.LinkProperties
+import android.net.LocalNetworkInfo
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED
@@ -28,6 +29,7 @@
import com.android.testutils.RecorderCallback.CallbackEntry.BlockedStatusInt
import com.android.testutils.RecorderCallback.CallbackEntry.CapabilitiesChanged
import com.android.testutils.RecorderCallback.CallbackEntry.LinkPropertiesChanged
+import com.android.testutils.RecorderCallback.CallbackEntry.LocalInfoChanged
import com.android.testutils.RecorderCallback.CallbackEntry.Losing
import com.android.testutils.RecorderCallback.CallbackEntry.Lost
import com.android.testutils.RecorderCallback.CallbackEntry.Resumed
@@ -68,6 +70,10 @@
override val network: Network,
val lp: LinkProperties
) : CallbackEntry()
+ data class LocalInfoChanged(
+ override val network: Network,
+ val info: LocalNetworkInfo
+ ) : CallbackEntry()
data class Suspended(override val network: Network) : CallbackEntry()
data class Resumed(override val network: Network) : CallbackEntry()
data class Losing(override val network: Network, val maxMsToLive: Int) : CallbackEntry()
@@ -94,6 +100,8 @@
@JvmField
val LINK_PROPERTIES_CHANGED = LinkPropertiesChanged::class
@JvmField
+ val LOCAL_INFO_CHANGED = LocalInfoChanged::class
+ @JvmField
val SUSPENDED = Suspended::class
@JvmField
val RESUMED = Resumed::class
@@ -131,6 +139,11 @@
history.add(LinkPropertiesChanged(network, lp))
}
+ override fun onLocalNetworkInfoChanged(network: Network, info: LocalNetworkInfo) {
+ Log.d(TAG, "onLocalNetworkInfoChanged $network $info")
+ history.add(LocalInfoChanged(network, info))
+ }
+
override fun onBlockedStatusChanged(network: Network, blocked: Boolean) {
Log.d(TAG, "onBlockedStatusChanged $network $blocked")
history.add(BlockedStatus(network, blocked))
@@ -430,37 +443,63 @@
suspended: Boolean = false,
validated: Boolean? = true,
blocked: Boolean = false,
+ upstream: Network? = null,
tmt: Long = defaultTimeoutMs
) {
- expectAvailableCallbacksCommon(net, suspended, validated, tmt)
+ expectAvailableCallbacksCommon(net, suspended, validated, upstream, tmt)
expect<BlockedStatus>(net, tmt) { it.blocked == blocked }
}
+ // For backward compatibility, add a method that allows callers to specify a timeout but
+ // no upstream.
+ fun expectAvailableCallbacks(
+ net: Network,
+ suspended: Boolean = false,
+ validated: Boolean? = true,
+ blocked: Boolean = false,
+ tmt: Long = defaultTimeoutMs
+ ) = expectAvailableCallbacks(net, suspended, validated, blocked, upstream = null, tmt = tmt)
+
fun expectAvailableCallbacks(
net: Network,
suspended: Boolean,
validated: Boolean,
blockedReason: Int,
+ upstream: Network? = null,
tmt: Long
) {
- expectAvailableCallbacksCommon(net, suspended, validated, tmt)
+ expectAvailableCallbacksCommon(net, suspended, validated, upstream, tmt)
expect<BlockedStatusInt>(net) { it.reason == blockedReason }
}
+ // For backward compatibility, add a method that allows callers to specify a timeout but
+ // no upstream.
+ fun expectAvailableCallbacks(
+ net: Network,
+ suspended: Boolean = false,
+ validated: Boolean = true,
+ blockedReason: Int,
+ tmt: Long = defaultTimeoutMs
+ ) = expectAvailableCallbacks(net, suspended, validated, blockedReason, upstream = null, tmt)
+
private fun expectAvailableCallbacksCommon(
net: Network,
suspended: Boolean,
validated: Boolean?,
+ upstream: Network?,
tmt: Long
) {
expect<Available>(net, tmt)
if (suspended) {
expect<Suspended>(net, tmt)
}
- expect<CapabilitiesChanged>(net, tmt) {
+ val caps = expect<CapabilitiesChanged>(net, tmt) {
validated == null || validated == it.caps.hasCapability(NET_CAPABILITY_VALIDATED)
- }
+ }.caps
expect<LinkPropertiesChanged>(net, tmt)
+ if (caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK)) {
+ expect<LocalInfoChanged>(net, tmt) { it.info.upstreamNetwork == upstream }
+ }
}
// Backward compatibility for existing Java code. Use named arguments instead and remove all
@@ -507,13 +546,15 @@
val network: Network
}
+ @JvmOverloads
fun expectAvailableCallbacks(
n: HasNetwork,
suspended: Boolean,
validated: Boolean,
blocked: Boolean,
+ upstream: Network? = null,
timeoutMs: Long
- ) = expectAvailableCallbacks(n.network, suspended, validated, blocked, timeoutMs)
+ ) = expectAvailableCallbacks(n.network, suspended, validated, blocked, upstream, timeoutMs)
fun expectAvailableAndSuspendedCallbacks(n: HasNetwork, expectValidated: Boolean) {
expectAvailableAndSuspendedCallbacks(n.network, expectValidated)
diff --git a/tests/unit/java/com/android/server/BpfNetMapsTest.java b/tests/unit/java/com/android/server/BpfNetMapsTest.java
index 1e08fcc..ea905d5 100644
--- a/tests/unit/java/com/android/server/BpfNetMapsTest.java
+++ b/tests/unit/java/com/android/server/BpfNetMapsTest.java
@@ -161,7 +161,6 @@
doReturn(TEST_IF_INDEX).when(mDeps).getIfIndex(TEST_IF_NAME);
doReturn(TEST_IF_NAME).when(mDeps).getIfName(TEST_IF_INDEX);
doReturn(0).when(mDeps).synchronizeKernelRCU();
- BpfNetMaps.setEnableJavaBpfMapForTest(true /* enable */);
BpfNetMaps.setConfigurationMapForTest(mConfigurationMap);
mConfigurationMap.updateEntry(UID_RULES_CONFIGURATION_KEY, new U32(0));
mConfigurationMap.updateEntry(
diff --git a/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt b/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
index 3a76ad0..235f7de 100644
--- a/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
+++ b/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
@@ -38,10 +38,7 @@
import android.os.Build
import com.android.testutils.DevSdkIgnoreRule
import com.android.testutils.DevSdkIgnoreRunner
-import com.android.testutils.RecorderCallback.CallbackEntry.Available
-import com.android.testutils.RecorderCallback.CallbackEntry.BlockedStatus
-import com.android.testutils.RecorderCallback.CallbackEntry.CapabilitiesChanged
-import com.android.testutils.RecorderCallback.CallbackEntry.LinkPropertiesChanged
+import com.android.testutils.RecorderCallback.CallbackEntry.LocalInfoChanged
import com.android.testutils.RecorderCallback.CallbackEntry.Lost
import com.android.testutils.TestableNetworkCallback
import org.junit.Test
@@ -114,10 +111,7 @@
.build(),
lnc = LocalNetworkConfig.Builder().build())
agent.connect()
- cb.expect<Available>(agent.network)
- cb.expect<CapabilitiesChanged>(agent.network)
- cb.expect<LinkPropertiesChanged>(agent.network)
- cb.expect<BlockedStatus>(agent.network)
+ cb.expectAvailableCallbacks(agent.network, validated = false)
agent.sendNetworkCapabilities(NetworkCapabilities.Builder().build())
cb.expect<Lost>(agent.network)
@@ -125,10 +119,7 @@
.build(),
lnc = null)
agent2.connect()
- cb.expect<Available>(agent2.network)
- cb.expect<CapabilitiesChanged>(agent2.network)
- cb.expect<LinkPropertiesChanged>(agent2.network)
- cb.expect<BlockedStatus>(agent2.network)
+ cb.expectAvailableCallbacks(agent2.network, validated = false)
agent2.sendNetworkCapabilities(NetworkCapabilities.Builder()
.addCapability(NET_CAPABILITY_LOCAL_NETWORK)
.build())
@@ -153,10 +144,11 @@
)
localAgent.connect()
- cb.expect<Available>(localAgent.network)
- cb.expect<CapabilitiesChanged>(localAgent.network)
- cb.expect<LinkPropertiesChanged>(localAgent.network)
- cb.expect<BlockedStatus>(localAgent.network)
+ cb.expectAvailableCallbacks(localAgent.network, validated = false)
+
+ val wifiAgent = Agent(score = keepScore(), lp = lp("wifi0"),
+ nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET))
+ wifiAgent.connect()
val newLnc = LocalNetworkConfig.Builder()
.setUpstreamSelector(NetworkRequest.Builder()
@@ -165,6 +157,21 @@
.build()
localAgent.sendLocalNetworkConfig(newLnc)
+ cb.expect<LocalInfoChanged>(localAgent.network) {
+ it.info.upstreamNetwork == wifiAgent.network
+ }
+
+ localAgent.sendLocalNetworkConfig(LocalNetworkConfig.Builder().build())
+ cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
+
+ localAgent.sendLocalNetworkConfig(newLnc)
+ cb.expect<LocalInfoChanged>(localAgent.network) {
+ it.info.upstreamNetwork == wifiAgent.network
+ }
+
+ wifiAgent.disconnect()
+ cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
+
localAgent.disconnect()
}
@@ -204,6 +211,9 @@
wifiAgent.connect()
cb.expectAvailableCallbacks(wifiAgent.network, validated = false)
+ cb.expect<LocalInfoChanged>(localAgent.network) {
+ it.info.upstreamNetwork == wifiAgent.network
+ }
clearInvocations(netd)
val inOrder = inOrder(netd)
@@ -218,6 +228,7 @@
wifiAgent2.connect()
cb.expectAvailableCallbacks(wifiAgent2.network, validated = false)
+ cb.expect<LocalInfoChanged> { it.info.upstreamNetwork == wifiAgent2.network }
cb.expect<Lost> { it.network == wifiAgent.network }
inOrder.verify(netd).ipfwdAddInterfaceForward("local0", wifiIface2)
@@ -252,7 +263,10 @@
nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET))
wifiAgent.connect()
- cb.expectAvailableCallbacksUnvalidated(wifiAgent)
+ cb.expectAvailableCallbacks(wifiAgent.network, validated = false)
+ cb.expect<LocalInfoChanged>(localAgent.network) {
+ it.info.upstreamNetwork == wifiAgent.network
+ }
clearInvocations(netd)
wifiAgent.unregisterAfterReplacement(TIMEOUT_MS.toInt())
@@ -260,6 +274,7 @@
verify(netd).networkDestroy(wifiAgent.network.netId)
verify(netd).ipfwdRemoveInterfaceForward("local0", "wifi0")
+ cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
cb.expect<Lost> { it.network == wifiAgent.network }
}
@@ -294,7 +309,12 @@
val wifiAgent = Agent(lp = lp("wifi0"), nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET))
wifiAgent.connect()
- cb.expectAvailableCallbacksUnvalidated(wifiAgent)
+ cb.expectAvailableCallbacks(wifiAgent.network, validated = false)
+ listOf(cb, localCb).forEach {
+ it.expect<LocalInfoChanged>(localAgent.network) {
+ it.info.upstreamNetwork == wifiAgent.network
+ }
+ }
verify(netd).ipfwdAddInterfaceForward("local0", "wifi0")
@@ -303,8 +323,10 @@
val localAgent2 = Agent(nc = localNc, lp = lp("local0"), lnc = lnc, score = localScore)
localAgent2.connect()
- localCb.expectAvailableCallbacks(localAgent2.network, validated = false)
- cb.expectAvailableCallbacks(localAgent2.network, validated = false)
+ localCb.expectAvailableCallbacks(localAgent2.network,
+ validated = false, upstream = wifiAgent.network)
+ cb.expectAvailableCallbacks(localAgent2.network,
+ validated = false, upstream = wifiAgent.network)
cb.expect<Lost> { it.network == localAgent.network }
}
@@ -316,9 +338,11 @@
val wifiAgent = Agent(lp = lp("wifi0"), nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET))
wifiAgent.connect()
- cb.expectAvailableCallbacksUnvalidated(wifiAgent)
+ cb.expectAvailableCallbacks(wifiAgent.network, validated = false)
- // Set up a local agent that should forward its traffic to the best wifi upstream.
+ // Unregister wifi pending replacement, then set up a local agent that would have
+ // this network as its upstream.
+ wifiAgent.unregisterAfterReplacement(LONG_TIMEOUT_MS)
val localAgent = Agent(nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_LOCAL_NETWORK),
lp = lp("local0"),
lnc = LocalNetworkConfig.Builder()
@@ -331,14 +355,18 @@
.build())
)
- // ...but destroy the wifi agent before connecting it
- wifiAgent.unregisterAfterReplacement(LONG_TIMEOUT_MS)
-
+ // Connect the local agent. The zombie wifi is its upstream, but the stack doesn't
+ // tell netd to add the forward since the wifi0 interface has gone.
localAgent.connect()
- cb.expectAvailableCallbacks(localAgent.network, validated = false)
+ cb.expectAvailableCallbacks(localAgent.network,
+ validated = false, upstream = wifiAgent.network)
- verify(netd).ipfwdAddInterfaceForward("local0", "wifi0")
- verify(netd).ipfwdRemoveInterfaceForward("local0", "wifi0")
+ verify(netd, never()).ipfwdAddInterfaceForward("local0", "wifi0")
+
+ // Disconnect wifi without a replacement. Expect an update with upstream null.
+ wifiAgent.disconnect()
+ verify(netd, never()).ipfwdAddInterfaceForward("local0", "wifi0")
+ cb.expect<LocalInfoChanged> { it.info.upstreamNetwork == null }
}
@Test
@@ -366,19 +394,34 @@
val wifiAgentDun = Agent(score = keepScore(), lp = lp("wifi1"),
nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET, NET_CAPABILITY_DUN))
+ val cb = TestableNetworkCallback()
+ cm.registerNetworkCallback(NetworkRequest.Builder()
+ .addCapability(NET_CAPABILITY_LOCAL_NETWORK)
+ .build(),
+ cb)
+ cb.expectAvailableCallbacks(localAgent.network, validated = false)
+
val inOrder = inOrder(netd)
inOrder.verify(netd, never()).ipfwdAddInterfaceForward(any(), any())
+ cb.assertNoCallback()
wifiAgent.connect()
inOrder.verify(netd, never()).ipfwdAddInterfaceForward(any(), any())
+ cb.assertNoCallback()
cellAgentDun.connect()
inOrder.verify(netd).ipfwdEnableForwarding(any())
inOrder.verify(netd).ipfwdAddInterfaceForward("local0", "cell0")
+ cb.expect<LocalInfoChanged>(localAgent.network) {
+ it.info.upstreamNetwork == cellAgentDun.network
+ }
wifiAgentDun.connect()
inOrder.verify(netd).ipfwdRemoveInterfaceForward("local0", "cell0")
inOrder.verify(netd).ipfwdAddInterfaceForward("local0", "wifi1")
+ cb.expect<LocalInfoChanged>(localAgent.network) {
+ it.info.upstreamNetwork == wifiAgentDun.network
+ }
// Make sure sending the same config again doesn't do anything
repeat(5) {
@@ -387,6 +430,10 @@
inOrder.verifyNoMoreInteractions()
wifiAgentDun.disconnect()
+ cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
+ cb.expect<LocalInfoChanged>(localAgent.network) {
+ it.info.upstreamNetwork == cellAgentDun.network
+ }
inOrder.verify(netd).ipfwdRemoveInterfaceForward("local0", "wifi1")
// This can take a little bit of time because it needs to wait for the rematch
inOrder.verify(netd, timeout(MEDIUM_TIMEOUT_MS)).ipfwdAddInterfaceForward("local0", "cell0")
@@ -394,15 +441,35 @@
cellAgentDun.disconnect()
inOrder.verify(netd).ipfwdRemoveInterfaceForward("local0", "cell0")
inOrder.verify(netd).ipfwdDisableForwarding(any())
+ cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
val wifiAgentDun2 = Agent(score = keepScore(), lp = lp("wifi2"),
nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET, NET_CAPABILITY_DUN))
wifiAgentDun2.connect()
inOrder.verify(netd).ipfwdEnableForwarding(any())
inOrder.verify(netd).ipfwdAddInterfaceForward("local0", "wifi2")
+ cb.expect<LocalInfoChanged>(localAgent.network) {
+ it.info.upstreamNetwork == wifiAgentDun2.network
+ }
- localAgent.disconnect()
+ wifiAgentDun2.disconnect()
inOrder.verify(netd).ipfwdRemoveInterfaceForward("local0", "wifi2")
inOrder.verify(netd).ipfwdDisableForwarding(any())
+ cb.expect<LocalInfoChanged>(localAgent.network) { it.info.upstreamNetwork == null }
+
+ val wifiAgentDun3 = Agent(score = keepScore(), lp = lp("wifi3"),
+ nc = nc(TRANSPORT_WIFI, NET_CAPABILITY_INTERNET, NET_CAPABILITY_DUN))
+ wifiAgentDun3.connect()
+ inOrder.verify(netd).ipfwdEnableForwarding(any())
+ inOrder.verify(netd).ipfwdAddInterfaceForward("local0", "wifi3")
+ cb.expect<LocalInfoChanged>(localAgent.network) {
+ it.info.upstreamNetwork == wifiAgentDun3.network
+ }
+
+ localAgent.disconnect()
+ inOrder.verify(netd).ipfwdRemoveInterfaceForward("local0", "wifi3")
+ inOrder.verify(netd).ipfwdDisableForwarding(any())
+ cb.expect<Lost>(localAgent.network)
+ cb.assertNoCallback()
}
}
diff --git a/thread/framework/java/android/net/thread/OperationalDatasetTimestamp.java b/thread/framework/java/android/net/thread/OperationalDatasetTimestamp.java
index bda9373..520acbd 100644
--- a/thread/framework/java/android/net/thread/OperationalDatasetTimestamp.java
+++ b/thread/framework/java/android/net/thread/OperationalDatasetTimestamp.java
@@ -43,9 +43,10 @@
/** @hide */
public static final int LENGTH_TIMESTAMP = Long.BYTES;
- private static final long TICKS_UPPER_BOUND = 0x8000;
+ private static final int TICKS_UPPER_BOUND = 0x8000;
- private final Instant mInstant;
+ private final long mSeconds;
+ private final int mTicks;
private final boolean mIsAuthoritativeSource;
/**
@@ -55,18 +56,34 @@
* {@link instant#getNano()} based on frequency of 32768 Hz, and {@code isAuthoritativeSource}
* is set to {@code true}.
*
+ * <p>Note that this conversion can lose precision and a value returned by {@link #toInstant}
+ * may not equal exactly the {@code instant}.
+ *
* @throws IllegalArgumentException if {@code instant.getEpochSecond()} is larger than {@code
* 0xffffffffffffL}
+ * @see toInstant
*/
@NonNull
public static OperationalDatasetTimestamp fromInstant(@NonNull Instant instant) {
- return new OperationalDatasetTimestamp(instant, /* isAuthoritativeSource= */ true);
+ int ticks = getRoundedTicks(instant.getNano());
+ long seconds = instant.getEpochSecond() + ticks / TICKS_UPPER_BOUND;
+ // the rounded ticks can be 0x8000 if instant.getNano() >= 999984742
+ ticks = ticks % TICKS_UPPER_BOUND;
+ return new OperationalDatasetTimestamp(seconds, ticks, true /* isAuthoritativeSource */);
}
- /** Converts this {@link OperationalDatasetTimestamp} object to an {@link Instant}. */
+ /**
+ * Converts this {@link OperationalDatasetTimestamp} object to an {@link Instant}.
+ *
+ * <p>Note that the return value may not equal exactly the {@code instant} if this object is
+ * created with {@link #fromInstant}.
+ *
+ * @see fromInstant
+ */
@NonNull
public Instant toInstant() {
- return mInstant;
+ long nanos = Math.round((double) mTicks * 1000000000L / TICKS_UPPER_BOUND);
+ return Instant.ofEpochSecond(mSeconds, nanos);
}
/**
@@ -100,10 +117,7 @@
public byte[] toTlvValue() {
byte[] tlv = new byte[LENGTH_TIMESTAMP];
ByteBuffer buffer = ByteBuffer.wrap(tlv);
- long encodedValue =
- (mInstant.getEpochSecond() << 16)
- | ((mInstant.getNano() * TICKS_UPPER_BOUND / 1000000000L) << 1)
- | (mIsAuthoritativeSource ? 1 : 0);
+ long encodedValue = (mSeconds << 16) | (mTicks << 1) | (mIsAuthoritativeSource ? 1 : 0);
buffer.putLong(encodedValue);
return tlv;
}
@@ -125,10 +139,6 @@
@IntRange(from = 0x0, to = 0xffffffffffffL) long seconds,
@IntRange(from = 0x0, to = 0x7fff) int ticks,
boolean isAuthoritativeSource) {
- this(makeInstant(seconds, ticks), isAuthoritativeSource);
- }
-
- private static Instant makeInstant(long seconds, int ticks) {
checkArgument(
seconds >= 0 && seconds <= 0xffffffffffffL,
"seconds exceeds allowed range (seconds = %d,"
@@ -138,25 +148,8 @@
ticks >= 0 && ticks <= 0x7fff,
"ticks exceeds allowed ranged (ticks = %d, allowedRange" + " = [0x0, 0x7fff])",
ticks);
- long nanos = Math.round((double) ticks * 1000000000L / TICKS_UPPER_BOUND);
- return Instant.ofEpochSecond(seconds, nanos);
- }
-
- /**
- * Creates new {@link OperationalDatasetTimestamp} object.
- *
- * @throws IllegalArgumentException if {@code instant.getEpochSecond()} is larger than {@code
- * 0xffffffffffffL}
- */
- private OperationalDatasetTimestamp(@NonNull Instant instant, boolean isAuthoritativeSource) {
- requireNonNull(instant, "instant cannot be null");
- long seconds = instant.getEpochSecond();
- checkArgument(
- seconds >= 0 && seconds <= 0xffffffffffffL,
- "instant seconds exceeds allowed range (seconds = %d, allowedRange = [0x0,"
- + " 0xffffffffffffL])",
- seconds);
- mInstant = instant;
+ mSeconds = seconds;
+ mTicks = ticks;
mIsAuthoritativeSource = isAuthoritativeSource;
}
@@ -171,13 +164,12 @@
/** Returns the seconds portion of the timestamp. */
public @IntRange(from = 0x0, to = 0xffffffffffffL) long getSeconds() {
- return mInstant.getEpochSecond() + getRoundedTicks(mInstant.getNano()) / TICKS_UPPER_BOUND;
+ return mSeconds;
}
/** Returns the ticks portion of the timestamp. */
public @IntRange(from = 0x0, to = 0x7fff) int getTicks() {
- // the rounded ticks can be 0x8000 if mInstant.getNano() >= 999984742
- return (int) (getRoundedTicks(mInstant.getNano()) % TICKS_UPPER_BOUND);
+ return mTicks;
}
/** Returns {@code true} if the timestamp comes from an authoritative source. */
@@ -208,13 +200,14 @@
return false;
} else {
OperationalDatasetTimestamp otherTimestamp = (OperationalDatasetTimestamp) other;
- return mInstant.equals(otherTimestamp.mInstant)
+ return mSeconds == otherTimestamp.mSeconds
+ && mTicks == otherTimestamp.mTicks
&& mIsAuthoritativeSource == otherTimestamp.mIsAuthoritativeSource;
}
}
@Override
public int hashCode() {
- return Objects.hash(mInstant, mIsAuthoritativeSource);
+ return Objects.hash(mSeconds, mTicks, mIsAuthoritativeSource);
}
}
diff --git a/thread/tests/unit/src/android/net/thread/OperationalDatasetTimestampTest.java b/thread/tests/unit/src/android/net/thread/OperationalDatasetTimestampTest.java
index 32063fc..2244a89 100644
--- a/thread/tests/unit/src/android/net/thread/OperationalDatasetTimestampTest.java
+++ b/thread/tests/unit/src/android/net/thread/OperationalDatasetTimestampTest.java
@@ -27,6 +27,8 @@
import org.junit.Test;
import org.junit.runner.RunWith;
+import java.time.Instant;
+
/** Unit tests for {@link OperationalDatasetTimestamp}. */
@SmallTest
@RunWith(AndroidJUnit4.class)
@@ -58,4 +60,22 @@
assertThat(timestamp2).isEqualTo(timestamp1);
}
+
+ @Test
+ public void toTlvValue_timestampFromInstant_conversionIsLossLess() {
+ // This results in ticks = 999938900 / 1000000000 * 32768 = 32765.9978752 ~= 32766.
+ // The ticks 32766 is then converted back to 999938964.84375 ~= 999938965 nanoseconds.
+ // A wrong implementation may save Instant.getNano() and compare against the nanoseconds
+ // and results in precision loss when converted between OperationalDatasetTimestamp and the
+ // TLV values.
+ OperationalDatasetTimestamp timestamp1 =
+ OperationalDatasetTimestamp.fromInstant(Instant.ofEpochSecond(100, 999938900));
+
+ OperationalDatasetTimestamp timestamp2 =
+ OperationalDatasetTimestamp.fromTlvValue(timestamp1.toTlvValue());
+
+ assertThat(timestamp2.getSeconds()).isEqualTo(100);
+ assertThat(timestamp2.getTicks()).isEqualTo(32766);
+ assertThat(timestamp2).isEqualTo(timestamp1);
+ }
}