Merge "remove BpfNetMaps.cpp" into main
diff --git a/Tethering/apex/Android.bp b/Tethering/apex/Android.bp
index ee44f3c..de9017a 100644
--- a/Tethering/apex/Android.bp
+++ b/Tethering/apex/Android.bp
@@ -80,6 +80,7 @@
first: {
jni_libs: [
"libservice-connectivity",
+ "libservice-thread-jni",
"libandroid_net_connectivity_com_android_net_module_util_jni",
],
native_shared_libs: [
diff --git a/Tethering/tests/integration/base/android/net/EthernetTetheringTestBase.java b/Tethering/tests/integration/base/android/net/EthernetTetheringTestBase.java
index 1c4a662..377da91 100644
--- a/Tethering/tests/integration/base/android/net/EthernetTetheringTestBase.java
+++ b/Tethering/tests/integration/base/android/net/EthernetTetheringTestBase.java
@@ -146,8 +146,6 @@
private final TetheringManager mTm = mContext.getSystemService(TetheringManager.class);
private final PackageManager mPackageManager = mContext.getPackageManager();
private final CtsNetUtils mCtsNetUtils = new CtsNetUtils(mContext);
- private final UiAutomation mUiAutomation =
- InstrumentationRegistry.getInstrumentation().getUiAutomation();
// Late initialization in setUp()
private boolean mRunTests;
@@ -276,7 +274,6 @@
} finally {
mHandlerThread.quitSafely();
mHandlerThread.join();
- mUiAutomation.dropShellPermissionIdentity();
}
}
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/bpf_progs/netd.h b/bpf_progs/netd.h
index d1fc58d..64ed633 100644
--- a/bpf_progs/netd.h
+++ b/bpf_progs/netd.h
@@ -192,6 +192,7 @@
OEM_DENY_1_MATCH = (1 << 9),
OEM_DENY_2_MATCH = (1 << 10),
OEM_DENY_3_MATCH = (1 << 11),
+ BACKGROUND_MATCH = (1 << 12)
};
// LINT.ThenChange(../framework/src/android/net/BpfNetMapsConstants.java)
@@ -244,7 +245,8 @@
// DROP_IF_SET is set of rules that DROP if rule is globally enabled, and per-uid bit is set
#define DROP_IF_SET (STANDBY_MATCH | OEM_DENY_1_MATCH | OEM_DENY_2_MATCH | OEM_DENY_3_MATCH)
// DROP_IF_UNSET is set of rules that should DROP if globally enabled, and per-uid bit is NOT set
-#define DROP_IF_UNSET (DOZABLE_MATCH | POWERSAVE_MATCH | RESTRICTED_MATCH | LOW_POWER_STANDBY_MATCH)
+#define DROP_IF_UNSET (DOZABLE_MATCH | POWERSAVE_MATCH | RESTRICTED_MATCH \
+ | LOW_POWER_STANDBY_MATCH | BACKGROUND_MATCH)
// Warning: funky bit-wise arithmetic: in parallel, for all DROP_IF_SET/UNSET rules
// check whether the rules are globally enabled, and if so whether the rules are
diff --git a/common/flags.aconfig b/common/flags.aconfig
index 0c46b48..b85c2fe 100644
--- a/common/flags.aconfig
+++ b/common/flags.aconfig
@@ -34,3 +34,10 @@
description: "This flag controls whether isUidNetworkingBlocked is supported"
bug: "297836825"
}
+
+flag {
+ name: "basic_background_restrictions_enabled"
+ namespace: "android_core_networking"
+ description: "Block network access for apps in a low importance background state"
+ bug: "304347838"
+}
diff --git a/framework-t/api/OWNERS b/framework-t/api/OWNERS
index 607f85a..8ef735c 100644
--- a/framework-t/api/OWNERS
+++ b/framework-t/api/OWNERS
@@ -1,2 +1,3 @@
file:platform/packages/modules/Connectivity:main:/nearby/OWNERS
file:platform/packages/modules/Connectivity:main:/remoteauth/OWNERS
+file:platform/packages/modules/Connectivity:main:/thread/OWNERS
diff --git a/framework-t/api/system-current.txt b/framework-t/api/system-current.txt
index 23510e1..b285d85 100644
--- a/framework-t/api/system-current.txt
+++ b/framework-t/api/system-current.txt
@@ -418,7 +418,6 @@
package android.net.thread {
@FlaggedApi("com.android.net.thread.flags.thread_enabled") public final class ActiveOperationalDataset implements android.os.Parcelable {
- method @NonNull public static android.net.thread.ActiveOperationalDataset createRandomDataset();
method public int describeContents();
method @NonNull public static android.net.thread.ActiveOperationalDataset fromThreadTlvs(@NonNull byte[]);
method @NonNull public android.net.thread.OperationalDatasetTimestamp getActiveTimestamp();
@@ -493,10 +492,49 @@
}
@FlaggedApi("com.android.net.thread.flags.thread_enabled") public final class ThreadNetworkController {
+ method public void createRandomizedDataset(@NonNull String, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<android.net.thread.ActiveOperationalDataset,android.net.thread.ThreadNetworkException>);
method public int getThreadVersion();
+ method public static boolean isAttached(int);
+ method @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED") public void join(@NonNull android.net.thread.ActiveOperationalDataset, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Void,android.net.thread.ThreadNetworkException>);
+ method @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED") public void leave(@NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Void,android.net.thread.ThreadNetworkException>);
+ method @RequiresPermission(allOf={android.Manifest.permission.ACCESS_NETWORK_STATE, "android.permission.THREAD_NETWORK_PRIVILEGED"}) public void registerOperationalDatasetCallback(@NonNull java.util.concurrent.Executor, @NonNull android.net.thread.ThreadNetworkController.OperationalDatasetCallback);
+ method @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) public void registerStateCallback(@NonNull java.util.concurrent.Executor, @NonNull android.net.thread.ThreadNetworkController.StateCallback);
+ method @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED") public void scheduleMigration(@NonNull android.net.thread.PendingOperationalDataset, @NonNull java.util.concurrent.Executor, @NonNull android.os.OutcomeReceiver<java.lang.Void,android.net.thread.ThreadNetworkException>);
+ method public void unregisterOperationalDatasetCallback(@NonNull android.net.thread.ThreadNetworkController.OperationalDatasetCallback);
+ method public void unregisterStateCallback(@NonNull android.net.thread.ThreadNetworkController.StateCallback);
+ field public static final int DEVICE_ROLE_CHILD = 2; // 0x2
+ field public static final int DEVICE_ROLE_DETACHED = 1; // 0x1
+ field public static final int DEVICE_ROLE_LEADER = 4; // 0x4
+ field public static final int DEVICE_ROLE_ROUTER = 3; // 0x3
+ field public static final int DEVICE_ROLE_STOPPED = 0; // 0x0
field public static final int THREAD_VERSION_1_3 = 4; // 0x4
}
+ public static interface ThreadNetworkController.OperationalDatasetCallback {
+ method public void onActiveOperationalDatasetChanged(@Nullable android.net.thread.ActiveOperationalDataset);
+ method public default void onPendingOperationalDatasetChanged(@Nullable android.net.thread.PendingOperationalDataset);
+ }
+
+ public static interface ThreadNetworkController.StateCallback {
+ method public void onDeviceRoleChanged(int);
+ method public default void onPartitionIdChanged(long);
+ }
+
+ @FlaggedApi("com.android.net.thread.flags.thread_enabled") public class ThreadNetworkException extends java.lang.Exception {
+ ctor public ThreadNetworkException(int, @NonNull String);
+ method public int getErrorCode();
+ field public static final int ERROR_ABORTED = 2; // 0x2
+ field public static final int ERROR_BUSY = 5; // 0x5
+ field public static final int ERROR_FAILED_PRECONDITION = 6; // 0x6
+ field public static final int ERROR_INTERNAL_ERROR = 1; // 0x1
+ field public static final int ERROR_REJECTED_BY_PEER = 8; // 0x8
+ field public static final int ERROR_RESOURCE_EXHAUSTED = 10; // 0xa
+ field public static final int ERROR_RESPONSE_BAD_FORMAT = 9; // 0x9
+ field public static final int ERROR_TIMEOUT = 3; // 0x3
+ field public static final int ERROR_UNAVAILABLE = 4; // 0x4
+ field public static final int ERROR_UNSUPPORTED_CHANNEL = 7; // 0x7
+ }
+
@FlaggedApi("com.android.net.thread.flags.thread_enabled") public final class ThreadNetworkManager {
method @NonNull public java.util.List<android.net.thread.ThreadNetworkController> getAllThreadNetworkControllers();
}
diff --git a/framework/api/module-lib-current.txt b/framework/api/module-lib-current.txt
index 4d55067..bfb4981 100644
--- a/framework/api/module-lib-current.txt
+++ b/framework/api/module-lib-current.txt
@@ -45,6 +45,7 @@
field public static final int BLOCKED_METERED_REASON_DATA_SAVER = 65536; // 0x10000
field public static final int BLOCKED_METERED_REASON_MASK = -65536; // 0xffff0000
field public static final int BLOCKED_METERED_REASON_USER_RESTRICTED = 131072; // 0x20000
+ field @FlaggedApi("com.android.net.flags.basic_background_restrictions_enabled") public static final int BLOCKED_REASON_APP_BACKGROUND = 64; // 0x40
field public static final int BLOCKED_REASON_APP_STANDBY = 4; // 0x4
field public static final int BLOCKED_REASON_BATTERY_SAVER = 1; // 0x1
field public static final int BLOCKED_REASON_DOZE = 2; // 0x2
@@ -52,6 +53,7 @@
field public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 32; // 0x20
field public static final int BLOCKED_REASON_NONE = 0; // 0x0
field public static final int BLOCKED_REASON_RESTRICTED_MODE = 8; // 0x8
+ field @FlaggedApi("com.android.net.flags.basic_background_restrictions_enabled") public static final int FIREWALL_CHAIN_BACKGROUND = 6; // 0x6
field public static final int FIREWALL_CHAIN_DOZABLE = 1; // 0x1
field public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5; // 0x5
field public static final int FIREWALL_CHAIN_OEM_DENY_1 = 7; // 0x7
diff --git a/framework/src/android/net/BpfNetMapsConstants.java b/framework/src/android/net/BpfNetMapsConstants.java
index c784597..5d0fe73 100644
--- a/framework/src/android/net/BpfNetMapsConstants.java
+++ b/framework/src/android/net/BpfNetMapsConstants.java
@@ -16,6 +16,7 @@
package android.net;
+import static android.net.ConnectivityManager.FIREWALL_CHAIN_BACKGROUND;
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;
@@ -77,6 +78,7 @@
public static final long OEM_DENY_1_MATCH = (1 << 9);
public static final long OEM_DENY_2_MATCH = (1 << 10);
public static final long OEM_DENY_3_MATCH = (1 << 11);
+ public static final long BACKGROUND_MATCH = (1 << 12);
public static final List<Pair<Long, String>> MATCH_LIST = Arrays.asList(
Pair.create(HAPPY_BOX_MATCH, "HAPPY_BOX_MATCH"),
@@ -90,7 +92,8 @@
Pair.create(LOCKDOWN_VPN_MATCH, "LOCKDOWN_VPN_MATCH"),
Pair.create(OEM_DENY_1_MATCH, "OEM_DENY_1_MATCH"),
Pair.create(OEM_DENY_2_MATCH, "OEM_DENY_2_MATCH"),
- Pair.create(OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH")
+ Pair.create(OEM_DENY_3_MATCH, "OEM_DENY_3_MATCH"),
+ Pair.create(BACKGROUND_MATCH, "BACKGROUND_MATCH")
);
/**
@@ -102,7 +105,8 @@
FIREWALL_CHAIN_DOZABLE,
FIREWALL_CHAIN_POWERSAVE,
FIREWALL_CHAIN_RESTRICTED,
- FIREWALL_CHAIN_LOW_POWER_STANDBY
+ FIREWALL_CHAIN_LOW_POWER_STANDBY,
+ FIREWALL_CHAIN_BACKGROUND
);
/**
diff --git a/framework/src/android/net/BpfNetMapsUtils.java b/framework/src/android/net/BpfNetMapsUtils.java
index e9c9137..11d610c 100644
--- a/framework/src/android/net/BpfNetMapsUtils.java
+++ b/framework/src/android/net/BpfNetMapsUtils.java
@@ -17,6 +17,7 @@
package android.net;
import static android.net.BpfNetMapsConstants.ALLOW_CHAINS;
+import static android.net.BpfNetMapsConstants.BACKGROUND_MATCH;
import static android.net.BpfNetMapsConstants.DENY_CHAINS;
import static android.net.BpfNetMapsConstants.DOZABLE_MATCH;
import static android.net.BpfNetMapsConstants.LOW_POWER_STANDBY_MATCH;
@@ -28,6 +29,7 @@
import static android.net.BpfNetMapsConstants.POWERSAVE_MATCH;
import static android.net.BpfNetMapsConstants.RESTRICTED_MATCH;
import static android.net.BpfNetMapsConstants.STANDBY_MATCH;
+import static android.net.ConnectivityManager.FIREWALL_CHAIN_BACKGROUND;
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;
@@ -70,6 +72,8 @@
return POWERSAVE_MATCH;
case FIREWALL_CHAIN_RESTRICTED:
return RESTRICTED_MATCH;
+ case FIREWALL_CHAIN_BACKGROUND:
+ return BACKGROUND_MATCH;
case FIREWALL_CHAIN_LOW_POWER_STANDBY:
return LOW_POWER_STANDBY_MATCH;
case FIREWALL_CHAIN_OEM_DENY_1:
diff --git a/framework/src/android/net/ConnectivityManager.java b/framework/src/android/net/ConnectivityManager.java
index 66b2840..57ecf49 100644
--- a/framework/src/android/net/ConnectivityManager.java
+++ b/framework/src/android/net/ConnectivityManager.java
@@ -135,6 +135,8 @@
"com.android.net.flags.set_data_saver_via_cm";
static final String SUPPORT_IS_UID_NETWORKING_BLOCKED =
"com.android.net.flags.support_is_uid_networking_blocked";
+ static final String BASIC_BACKGROUND_RESTRICTIONS_ENABLED =
+ "com.android.net.flags.basic_background_restrictions_enabled";
}
/**
@@ -908,6 +910,16 @@
public static final int BLOCKED_REASON_LOW_POWER_STANDBY = 1 << 5;
/**
+ * Flag to indicate that an app is subject to default background restrictions that would
+ * result in its network access being blocked.
+ *
+ * @hide
+ */
+ @FlaggedApi(Flags.BASIC_BACKGROUND_RESTRICTIONS_ENABLED)
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
+ public static final int BLOCKED_REASON_APP_BACKGROUND = 1 << 6;
+
+ /**
* Flag to indicate that an app is subject to Data saver restrictions that would
* result in its metered network access being blocked.
*
@@ -946,6 +958,7 @@
BLOCKED_REASON_RESTRICTED_MODE,
BLOCKED_REASON_LOCKDOWN_VPN,
BLOCKED_REASON_LOW_POWER_STANDBY,
+ BLOCKED_REASON_APP_BACKGROUND,
BLOCKED_METERED_REASON_DATA_SAVER,
BLOCKED_METERED_REASON_USER_RESTRICTED,
BLOCKED_METERED_REASON_ADMIN_DISABLED,
@@ -963,7 +976,6 @@
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
private final IConnectivityManager mService;
- // LINT.IfChange(firewall_chain)
/**
* Firewall chain for device idle (doze mode).
* Allowlist of apps that have network access in device idle.
@@ -1005,6 +1017,16 @@
public static final int FIREWALL_CHAIN_LOW_POWER_STANDBY = 5;
/**
+ * Firewall chain used for always-on default background restrictions.
+ * Allowlist of apps that have access because either they are in the foreground or they are
+ * exempted for specific situations while in the background.
+ * @hide
+ */
+ @FlaggedApi(Flags.BASIC_BACKGROUND_RESTRICTIONS_ENABLED)
+ @SystemApi(client = MODULE_LIBRARIES)
+ public static final int FIREWALL_CHAIN_BACKGROUND = 6;
+
+ /**
* Firewall chain used for OEM-specific application restrictions.
*
* Denylist of apps that will not have network access due to OEM-specific restrictions. If an
@@ -1063,12 +1085,12 @@
FIREWALL_CHAIN_POWERSAVE,
FIREWALL_CHAIN_RESTRICTED,
FIREWALL_CHAIN_LOW_POWER_STANDBY,
+ FIREWALL_CHAIN_BACKGROUND,
FIREWALL_CHAIN_OEM_DENY_1,
FIREWALL_CHAIN_OEM_DENY_2,
FIREWALL_CHAIN_OEM_DENY_3
})
public @interface FirewallChain {}
- // LINT.ThenChange(packages/modules/Connectivity/service/native/include/Common.h)
/**
* A firewall rule which allows or drops packets depending on existing policy.
diff --git a/framework/src/android/net/LocalNetworkConfig.java b/framework/src/android/net/LocalNetworkConfig.java
index fca7fd1..e1b33e8 100644
--- a/framework/src/android/net/LocalNetworkConfig.java
+++ b/framework/src/android/net/LocalNetworkConfig.java
@@ -82,6 +82,15 @@
dest.writeParcelable(mDownstreamMulticastRoutingConfig, flags);
}
+ @Override
+ public String toString() {
+ return "LocalNetworkConfig{"
+ + "UpstreamSelector=" + mUpstreamSelector
+ + ", UpstreamMulticastConfig=" + mUpstreamMulticastRoutingConfig
+ + ", DownstreamMulticastConfig=" + mDownstreamMulticastRoutingConfig
+ + '}';
+ }
+
public static final @NonNull Creator<LocalNetworkConfig> CREATOR = new Creator<>() {
public LocalNetworkConfig createFromParcel(Parcel in) {
final NetworkRequest upstreamSelector = in.readParcelable(null);
diff --git a/framework/src/android/net/MulticastRoutingConfig.java b/framework/src/android/net/MulticastRoutingConfig.java
index ebd9fc5..6f4ab11 100644
--- a/framework/src/android/net/MulticastRoutingConfig.java
+++ b/framework/src/android/net/MulticastRoutingConfig.java
@@ -159,6 +159,24 @@
}
};
+ @Override
+ public String toString() {
+ return "MulticastRoutingConfig{"
+ + "ForwardingMode=" + forwardingModeToString(mForwardingMode)
+ + ", MinScope=" + mMinScope
+ + ", ListeningAddresses=" + mListeningAddresses
+ + '}';
+ }
+
+ private static String forwardingModeToString(final int forwardingMode) {
+ switch (forwardingMode) {
+ case FORWARD_NONE: return "NONE";
+ case FORWARD_SELECTED: return "SELECTED";
+ case FORWARD_WITH_MIN_SCOPE: return "WITH_MIN_SCOPE";
+ default: return "UNKNOWN";
+ }
+ }
+
public static class Builder {
@MulticastForwardingMode
private final int mForwardingMode;
diff --git a/service/Android.bp b/service/Android.bp
index 8164af7..82f64ba 100644
--- a/service/Android.bp
+++ b/service/Android.bp
@@ -107,10 +107,15 @@
"-Werror",
"-Wno-unused-parameter",
"-Wthread-safety",
+
+ // AServiceManager_waitForService is available on only 31+, but it's still safe for Thread
+ // service because it's enabled on only 34+
+ "-Wno-unguarded-availability",
],
srcs: [
":services.connectivity-netstats-jni-sources",
"jni/com_android_server_connectivity_ClatCoordinator.cpp",
+ "jni/com_android_server_ServiceManagerWrapper.cpp",
"jni/com_android_server_TestNetworkService.cpp",
"jni/onload.cpp",
],
@@ -127,6 +132,7 @@
],
shared_libs: [
"libbase",
+ "libbinder_ndk",
"libcutils",
"libnetdutils",
"liblog",
@@ -202,6 +208,8 @@
visibility: [
"//packages/modules/Connectivity/service-t",
"//packages/modules/Connectivity/tests:__subpackages__",
+ "//packages/modules/Connectivity/thread/service:__subpackages__",
+ "//packages/modules/Connectivity/thread/tests:__subpackages__",
],
}
diff --git a/service/jni/com_android_server_ServiceManagerWrapper.cpp b/service/jni/com_android_server_ServiceManagerWrapper.cpp
new file mode 100644
index 0000000..0cd58f4
--- /dev/null
+++ b/service/jni/com_android_server_ServiceManagerWrapper.cpp
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ */
+
+#include <android/binder_ibinder_jni.h>
+#include <android/binder_manager.h>
+#include <jni.h>
+#include "nativehelper/JNIHelp.h"
+#include <nativehelper/ScopedUtfChars.h>
+#include <private/android_filesystem_config.h>
+
+namespace android {
+static jobject com_android_server_ServiceManagerWrapper_waitForService(
+ JNIEnv* env, jobject clazz, jstring serviceName) {
+ ScopedUtfChars name(env, serviceName);
+ return AIBinder_toJavaBinder(env, AServiceManager_waitForService(name.c_str()));
+}
+
+/*
+ * JNI registration.
+ */
+
+static const JNINativeMethod gMethods[] = {
+ /* name, signature, funcPtr */
+ {"nativeWaitForService",
+ "(Ljava/lang/String;)Landroid/os/IBinder;",
+ (void*)com_android_server_ServiceManagerWrapper_waitForService},
+};
+
+int register_com_android_server_ServiceManagerWrapper(JNIEnv* env) {
+ return jniRegisterNativeMethods(env,
+ "android/net/connectivity/com/android/server/ServiceManagerWrapper",
+ gMethods, NELEM(gMethods));
+}
+
+}; // namespace android
diff --git a/service/jni/onload.cpp b/service/jni/onload.cpp
index 7a3983c..bb70d4f 100644
--- a/service/jni/onload.cpp
+++ b/service/jni/onload.cpp
@@ -25,6 +25,7 @@
int register_com_android_server_connectivity_ClatCoordinator(JNIEnv* env);
int register_android_server_net_NetworkStatsFactory(JNIEnv* env);
int register_android_server_net_NetworkStatsService(JNIEnv* env);
+int register_com_android_server_ServiceManagerWrapper(JNIEnv* env);
extern "C" jint JNI_OnLoad(JavaVM* vm, void*) {
JNIEnv *env;
@@ -37,6 +38,10 @@
return JNI_ERR;
}
+ if (register_com_android_server_ServiceManagerWrapper(env) < 0) {
+ return JNI_ERR;
+ }
+
if (android::modules::sdklevel::IsAtLeastT()) {
if (register_com_android_server_connectivity_ClatCoordinator(env) < 0) {
return JNI_ERR;
diff --git a/service/native/include/Common.h b/service/native/include/Common.h
deleted file mode 100644
index 03f449a..0000000
--- a/service/native/include/Common.h
+++ /dev/null
@@ -1,46 +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
-// TODO: deduplicate with the constants in NetdConstants.h.
-#include <aidl/android/net/INetd.h>
-#include "clat_mark.h"
-
-using aidl::android::net::INetd;
-
-static_assert(INetd::CLAT_MARK == CLAT_MARK, "must be 0xDEADC1A7");
-
-enum FirewallRule { ALLOW = INetd::FIREWALL_RULE_ALLOW, DENY = INetd::FIREWALL_RULE_DENY };
-
-// ALLOWLIST means the firewall denies all by default, uids must be explicitly ALLOWed
-// DENYLIST means the firewall allows all by default, uids must be explicitly DENYed
-
-enum FirewallType { ALLOWLIST = INetd::FIREWALL_ALLOWLIST, DENYLIST = INetd::FIREWALL_DENYLIST };
-
-// LINT.IfChange(firewall_chain)
-enum ChildChain {
- NONE = 0,
- DOZABLE = 1,
- STANDBY = 2,
- POWERSAVE = 3,
- RESTRICTED = 4,
- LOW_POWER_STANDBY = 5,
- OEM_DENY_1 = 7,
- OEM_DENY_2 = 8,
- OEM_DENY_3 = 9,
- INVALID_CHAIN
-};
-// LINT.ThenChange(packages/modules/Connectivity/framework/src/android/net/ConnectivityManager.java)
diff --git a/service/native/libs/libclat/Android.bp b/service/native/libs/libclat/Android.bp
index 996706e..5c6b123 100644
--- a/service/native/libs/libclat/Android.bp
+++ b/service/native/libs/libclat/Android.bp
@@ -43,11 +43,15 @@
srcs: [
"clatutils_test.cpp",
],
+ header_libs: [
+ "bpf_connectivity_headers",
+ ],
static_libs: [
"libbase",
"libclat",
"libip_checksum",
"libnetd_test_tun_interface",
+ "netd_aidl_interface-lateststable-ndk",
],
shared_libs: [
"liblog",
diff --git a/service/native/libs/libclat/clatutils_test.cpp b/service/native/libs/libclat/clatutils_test.cpp
index f4f97db..cf6492f 100644
--- a/service/native/libs/libclat/clatutils_test.cpp
+++ b/service/native/libs/libclat/clatutils_test.cpp
@@ -26,6 +26,10 @@
#include "checksum.h"
}
+#include <aidl/android/net/INetd.h>
+#include "clat_mark.h"
+static_assert(aidl::android::net::INetd::CLAT_MARK == CLAT_MARK, "must be 0xDEADC1A7");
+
// Default translation parameters.
static const char kIPv4LocalAddr[] = "192.0.0.4";
diff --git a/service/src/com/android/server/ConnectivityService.java b/service/src/com/android/server/ConnectivityService.java
index d8417c1..7d1644e 100755
--- a/service/src/com/android/server/ConnectivityService.java
+++ b/service/src/com/android/server/ConnectivityService.java
@@ -9006,6 +9006,9 @@
return;
}
+ if (VDBG) {
+ Log.v(TAG, "Update local network config " + nai.network.netId + " : " + newConfig);
+ }
final LocalNetworkConfig.Builder configBuilder = new LocalNetworkConfig.Builder();
// TODO : apply the diff for multicast routing.
configBuilder.setUpstreamMulticastRoutingConfig(
@@ -12884,6 +12887,7 @@
case ConnectivityManager.FIREWALL_CHAIN_POWERSAVE:
case ConnectivityManager.FIREWALL_CHAIN_RESTRICTED:
case ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY:
+ case ConnectivityManager.FIREWALL_CHAIN_BACKGROUND:
defaultRule = FIREWALL_RULE_DENY;
break;
default:
diff --git a/service/src/com/android/server/ServiceManagerWrapper.java b/service/src/com/android/server/ServiceManagerWrapper.java
new file mode 100644
index 0000000..6d99f33
--- /dev/null
+++ b/service/src/com/android/server/ServiceManagerWrapper.java
@@ -0,0 +1,46 @@
+/*
+ * 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 com.android.server;
+
+import android.annotation.RequiresApi;
+import android.os.IBinder;
+import android.os.Build;
+import android.os.ServiceManager;
+
+/** Provides a way to access {@link ServiceManager#waitForService} API. */
+@RequiresApi(Build.VERSION_CODES.S)
+public final class ServiceManagerWrapper {
+ static {
+ System.loadLibrary("service-connectivity");
+ }
+
+ private ServiceManagerWrapper() {}
+
+ /**
+ * Returns the specified service from the service manager.
+ *
+ * If the service is not running, service manager will attempt to start it, and this function
+ * will wait for it to be ready.
+ *
+ * @return {@code null} only if there are permission problems or fatal errors
+ */
+ public static IBinder waitForService(String serviceName) {
+ return nativeWaitForService(serviceName);
+ }
+
+ private static native IBinder nativeWaitForService(String serviceName);
+}
diff --git a/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
index 62614c1..0a143c5 100644
--- a/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
+++ b/tests/cts/net/src/android/net/cts/ConnectivityManagerTest.java
@@ -38,6 +38,7 @@
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.net.ConnectivityManager.EXTRA_NETWORK;
import static android.net.ConnectivityManager.EXTRA_NETWORK_REQUEST;
+import static android.net.ConnectivityManager.FIREWALL_CHAIN_BACKGROUND;
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;
@@ -3538,6 +3539,12 @@
doTestFirewallBlocking(FIREWALL_CHAIN_DOZABLE, ALLOWLIST);
}
+ @Test @IgnoreUpTo(Build.VERSION_CODES.UPSIDE_DOWN_CAKE) @ConnectivityModuleTest
+ @AppModeFull(reason = "Socket cannot bind in instant app mode")
+ public void testFirewallBlockingBackground() {
+ doTestFirewallBlocking(FIREWALL_CHAIN_BACKGROUND, ALLOWLIST);
+ }
+
@Test @IgnoreUpTo(SC_V2) @ConnectivityModuleTest
@AppModeFull(reason = "Socket cannot bind in instant app mode")
public void testFirewallBlockingPowersave() {
diff --git a/tests/unit/java/com/android/server/ConnectivityServiceTest.java b/tests/unit/java/com/android/server/ConnectivityServiceTest.java
index aae37e5..bafd450 100755
--- a/tests/unit/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/unit/java/com/android/server/ConnectivityServiceTest.java
@@ -59,6 +59,7 @@
import static android.net.ConnectivityManager.EXTRA_NETWORK_INFO;
import static android.net.ConnectivityManager.EXTRA_NETWORK_TYPE;
import static android.net.ConnectivityManager.EXTRA_REALTIME_NS;
+import static android.net.ConnectivityManager.FIREWALL_CHAIN_BACKGROUND;
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;
@@ -10475,6 +10476,7 @@
doTestSetUidFirewallRule(FIREWALL_CHAIN_POWERSAVE, FIREWALL_RULE_DENY);
doTestSetUidFirewallRule(FIREWALL_CHAIN_RESTRICTED, FIREWALL_RULE_DENY);
doTestSetUidFirewallRule(FIREWALL_CHAIN_LOW_POWER_STANDBY, FIREWALL_RULE_DENY);
+ doTestSetUidFirewallRule(FIREWALL_CHAIN_BACKGROUND, FIREWALL_RULE_DENY);
doTestSetUidFirewallRule(FIREWALL_CHAIN_OEM_DENY_1, FIREWALL_RULE_ALLOW);
doTestSetUidFirewallRule(FIREWALL_CHAIN_OEM_DENY_2, FIREWALL_RULE_ALLOW);
doTestSetUidFirewallRule(FIREWALL_CHAIN_OEM_DENY_3, FIREWALL_RULE_ALLOW);
@@ -10488,6 +10490,7 @@
FIREWALL_CHAIN_POWERSAVE,
FIREWALL_CHAIN_RESTRICTED,
FIREWALL_CHAIN_LOW_POWER_STANDBY,
+ FIREWALL_CHAIN_BACKGROUND,
FIREWALL_CHAIN_OEM_DENY_1,
FIREWALL_CHAIN_OEM_DENY_2,
FIREWALL_CHAIN_OEM_DENY_3);
@@ -10537,6 +10540,7 @@
doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_POWERSAVE, allowlist);
doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_RESTRICTED, allowlist);
doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_LOW_POWER_STANDBY, allowlist);
+ doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_BACKGROUND, allowlist);
doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_STANDBY, denylist);
doTestSetFirewallChainEnabledCloseSocket(FIREWALL_CHAIN_OEM_DENY_1, denylist);
@@ -10558,6 +10562,7 @@
doTestReplaceFirewallChain(FIREWALL_CHAIN_POWERSAVE);
doTestReplaceFirewallChain(FIREWALL_CHAIN_RESTRICTED);
doTestReplaceFirewallChain(FIREWALL_CHAIN_LOW_POWER_STANDBY);
+ doTestReplaceFirewallChain(FIREWALL_CHAIN_BACKGROUND);
doTestReplaceFirewallChain(FIREWALL_CHAIN_OEM_DENY_1);
doTestReplaceFirewallChain(FIREWALL_CHAIN_OEM_DENY_2);
doTestReplaceFirewallChain(FIREWALL_CHAIN_OEM_DENY_3);
diff --git a/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt b/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
index 235f7de..1dab548 100644
--- a/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
+++ b/tests/unit/java/com/android/server/connectivityservice/CSLocalAgentTests.kt
@@ -29,6 +29,7 @@
import android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED
import android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED
import android.net.NetworkCapabilities.TRANSPORT_CELLULAR
+import android.net.NetworkCapabilities.TRANSPORT_THREAD
import android.net.NetworkCapabilities.TRANSPORT_WIFI
import android.net.NetworkRequest
import android.net.NetworkScore
@@ -472,4 +473,55 @@
cb.expect<Lost>(localAgent.network)
cb.assertNoCallback()
}
+
+ @Test
+ fun testLocalNetworkUnwanted_withUpstream() {
+ doTestLocalNetworkUnwanted(true)
+ }
+
+ @Test
+ fun testLocalNetworkUnwanted_withoutUpstream() {
+ doTestLocalNetworkUnwanted(false)
+ }
+
+ fun doTestLocalNetworkUnwanted(haveUpstream: Boolean) {
+ deps.setBuildSdk(VERSION_V)
+
+ val nr = NetworkRequest.Builder().addCapability(NET_CAPABILITY_LOCAL_NETWORK).build()
+ val requestCb = TestableNetworkCallback()
+ cm.requestNetwork(nr, requestCb)
+ val listenCb = TestableNetworkCallback()
+ cm.registerNetworkCallback(nr, listenCb)
+
+ val upstream = if (haveUpstream) {
+ Agent(score = keepScore(), lp = lp("wifi0"),
+ nc = nc(TRANSPORT_WIFI)).also { it.connect() }
+ } else {
+ null
+ }
+
+ // Set up a local agent.
+ val lnc = LocalNetworkConfig.Builder().apply {
+ if (haveUpstream) {
+ setUpstreamSelector(NetworkRequest.Builder()
+ .addTransportType(TRANSPORT_WIFI)
+ .build())
+ }
+ }.build()
+ val localAgent = Agent(nc = nc(TRANSPORT_THREAD, NET_CAPABILITY_LOCAL_NETWORK),
+ lp = lp("local0"),
+ lnc = lnc,
+ score = FromS(NetworkScore.Builder().build())
+ )
+ localAgent.connect()
+
+ requestCb.expectAvailableCallbacks(localAgent.network,
+ validated = false, upstream = upstream?.network)
+ listenCb.expectAvailableCallbacks(localAgent.network,
+ validated = false, upstream = upstream?.network)
+
+ cm.unregisterNetworkCallback(requestCb)
+
+ listenCb.expect<Lost>()
+ }
}
diff --git a/thread/framework/java/android/net/thread/ActiveOperationalDataset.java b/thread/framework/java/android/net/thread/ActiveOperationalDataset.java
index c9b047a..b74a15a 100644
--- a/thread/framework/java/android/net/thread/ActiveOperationalDataset.java
+++ b/thread/framework/java/android/net/thread/ActiveOperationalDataset.java
@@ -16,8 +16,6 @@
package android.net.thread;
-import static android.net.thread.ActiveOperationalDataset.SecurityPolicy.DEFAULT_ROTATION_TIME_HOURS;
-
import static com.android.internal.util.Preconditions.checkArgument;
import static com.android.internal.util.Preconditions.checkState;
import static com.android.net.module.util.HexDump.dumpHexString;
@@ -41,26 +39,25 @@
import java.io.ByteArrayOutputStream;
import java.net.Inet6Address;
import java.net.UnknownHostException;
-import java.security.SecureRandom;
-import java.time.Instant;
import java.util.Arrays;
-import java.util.Random;
/**
* Data interface for managing a Thread Active Operational Dataset.
*
- * <p>An example usage of creating an Active Operational Dataset with random parameters:
+ * <p>An example usage of creating an Active Operational Dataset with randomized parameters:
*
* <pre>{@code
- * ActiveOperationalDataset activeDataset = ActiveOperationalDataset.createRandomDataset();
+ * ActiveOperationalDataset activeDataset = controller.createRandomizedDataset("MyNet");
* }</pre>
*
- * <p>or random Dataset with customized Network Name:
+ * <p>or randomized Dataset with customized channel:
*
* <pre>{@code
* ActiveOperationalDataset activeDataset =
- * new ActiveOperationalDataset.Builder(ActiveOperationalDataset.createRandomDataset())
- * .setNetworkName("MyThreadNet").build();
+ * new ActiveOperationalDataset.Builder(controller.createRandomizedDataset("MyNet"))
+ * .setChannel(CHANNEL_PAGE_24_GHZ, 17)
+ * .setActiveTimestamp(OperationalDatasetTimestamp.fromInstant(Instant.now()))
+ * .build();
* }</pre>
*
* <p>If the Active Operational Dataset is already known as <a
@@ -116,7 +113,9 @@
/** @hide */
@VisibleForTesting public static final int TYPE_CHANNEL_MASK = 53;
- private static final byte MESH_LOCAL_PREFIX_FIRST_BYTE = (byte) 0xfd;
+ /** @hide */
+ public static final byte MESH_LOCAL_PREFIX_FIRST_BYTE = (byte) 0xfd;
+
private static final int LENGTH_CHANNEL = 3;
private static final int LENGTH_PAN_ID = 2;
@@ -344,86 +343,6 @@
outputStream.write(entries, 0, entries.length);
}
- /**
- * Creates a new {@link ActiveOperationalDataset} object with randomized or default parameters.
- *
- * <p>The randomized (or default) value for each parameter:
- *
- * <ul>
- * <li>{@code Active Timestamp} defaults to {@code new OperationalDatasetTimestamp(1, 0,
- * false)}
- * <li>{@code Network Name} defaults to "THREAD-PAN-<PAN ID decimal>", for example
- * "THREAD-PAN-12345"
- * <li>{@code Extended PAN ID} filled with randomly generated bytes
- * <li>{@code PAN ID} randomly generated integer in range of [0, 0xfffe]
- * <li>{@code Channel Page} defaults to {@link #CHANNEL_PAGE_24_GHZ}
- * <li>{@code Channel} randomly selected channel in range of [{@link #CHANNEL_MIN_24_GHZ},
- * {@link #CHANNEL_MAX_24_GHZ}]
- * <li>{@code Channel Mask} all bits from {@link #CHANNEL_MIN_24_GHZ} to {@link
- * #CHANNEL_MAX_24_GHZ} are set to {@code true}
- * <li>{@code PSKc} filled with bytes generated by secure random generator
- * <li>{@code Network Key} filled with bytes generated by secure random generator
- * <li>{@code Mesh-local Prefix} filled with randomly generated bytes except that the first
- * byte is always set to {@code 0xfd}
- * <li>{@code Security Policy} defaults to {@code new SecurityPolicy(
- * DEFAULT_ROTATION_TIME_HOURS, new byte[]{(byte)0xff, (byte)0xf8})}. This is the default
- * values required by the Thread 1.2 specification
- * </ul>
- *
- * <p>This method is the recommended way to create a randomized operational dataset for a new
- * Thread network. It may be desired to change one or more of the generated value(s). For
- * example, to use a more meaningful Network Name. To do that, create a new {@link Builder}
- * object from this dataset with {@link Builder#Builder(ActiveOperationalDataset)} and override
- * the value with the setters of {@link Builder}.
- *
- * <p>Note that it's highly discouraged to change the randomly generated Extended PAN ID,
- * Network Key or PSKc, as it will compromise the security of a Thread network.
- */
- @NonNull
- public static ActiveOperationalDataset createRandomDataset() {
- return createRandomDataset(new Random(Instant.now().toEpochMilli()), new SecureRandom());
- }
-
- /** @hide */
- @VisibleForTesting
- public static ActiveOperationalDataset createRandomDataset(
- Random random, SecureRandom secureRandom) {
- int panId = random.nextInt(/* bound= */ 0xffff);
- byte[] meshLocalPrefix = newRandomBytes(random, LENGTH_MESH_LOCAL_PREFIX_BITS / 8);
- meshLocalPrefix[0] = MESH_LOCAL_PREFIX_FIRST_BYTE;
-
- SparseArray<byte[]> channelMask = new SparseArray<>(1);
- channelMask.put(CHANNEL_PAGE_24_GHZ, new byte[] {0x00, 0x1f, (byte) 0xff, (byte) 0xe0});
-
- return new Builder()
- .setActiveTimestamp(
- new OperationalDatasetTimestamp(
- /* seconds= */ 1,
- /* ticks= */ 0,
- /* isAuthoritativeSource= */ false))
- .setExtendedPanId(newRandomBytes(random, LENGTH_EXTENDED_PAN_ID))
- .setPanId(panId)
- .setNetworkName("THREAD-PAN-" + panId)
- .setChannel(
- CHANNEL_PAGE_24_GHZ,
- random.nextInt(CHANNEL_MAX_24_GHZ - CHANNEL_MIN_24_GHZ + 1)
- + CHANNEL_MIN_24_GHZ)
- .setChannelMask(channelMask)
- .setPskc(newRandomBytes(secureRandom, LENGTH_PSKC))
- .setNetworkKey(newRandomBytes(secureRandom, LENGTH_NETWORK_KEY))
- .setMeshLocalPrefix(meshLocalPrefix)
- .setSecurityPolicy(
- new SecurityPolicy(
- DEFAULT_ROTATION_TIME_HOURS, new byte[] {(byte) 0xff, (byte) 0xf8}))
- .build();
- }
-
- private static byte[] newRandomBytes(Random random, int length) {
- byte[] result = new byte[length];
- random.nextBytes(result);
- return result;
- }
-
private static boolean areByteSparseArraysEqual(
@NonNull SparseArray<byte[]> first, @NonNull SparseArray<byte[]> second) {
if (first == second) {
@@ -683,6 +602,20 @@
return sb.toString();
}
+ static String checkNetworkName(@NonNull String networkName) {
+ requireNonNull(networkName, "networkName cannot be null");
+
+ int nameLength = networkName.getBytes(UTF_8).length;
+ checkArgument(
+ nameLength >= LENGTH_MIN_NETWORK_NAME_BYTES
+ && nameLength <= LENGTH_MAX_NETWORK_NAME_BYTES,
+ "Invalid network name (length = %d, expectedLengthRange = [%d, %d])",
+ nameLength,
+ LENGTH_MIN_NETWORK_NAME_BYTES,
+ LENGTH_MAX_NETWORK_NAME_BYTES);
+ return networkName;
+ }
+
/** The builder for creating {@link ActiveOperationalDataset} objects. */
public static final class Builder {
private OperationalDatasetTimestamp mActiveTimestamp;
@@ -748,7 +681,7 @@
* @param networkName the name of the Thread network
* @throws IllegalArgumentException if length of the UTF-8 representation of {@code
* networkName} isn't in range of [{@link #LENGTH_MIN_NETWORK_NAME_BYTES}, {@link
- * #LENGTH_MAX_NETWORK_NAME_BYTES}].
+ * #LENGTH_MAX_NETWORK_NAME_BYTES}]
*/
@NonNull
public Builder setNetworkName(
@@ -757,26 +690,16 @@
min = LENGTH_MIN_NETWORK_NAME_BYTES,
max = LENGTH_MAX_NETWORK_NAME_BYTES)
String networkName) {
- requireNonNull(networkName, "networkName cannot be null");
-
- int nameLength = networkName.getBytes(UTF_8).length;
- checkArgument(
- nameLength >= LENGTH_MIN_NETWORK_NAME_BYTES
- && nameLength <= LENGTH_MAX_NETWORK_NAME_BYTES,
- "Invalid network name (length = %d, expectedLengthRange = [%d, %d])",
- nameLength,
- LENGTH_MIN_NETWORK_NAME_BYTES,
- LENGTH_MAX_NETWORK_NAME_BYTES);
- this.mNetworkName = networkName;
+ this.mNetworkName = checkNetworkName(networkName);
return this;
}
/**
* Sets the Extended PAN ID.
*
- * <p>Use with caution. A randomly generated Extended PAN ID should be used for real Thread
+ * <p>Use with caution. A randomized Extended PAN ID should be used for real Thread
* networks. It's discouraged to call this method to override the default value created by
- * {@link ActiveOperationalDataset#createRandomDataset} in production.
+ * {@link ThreadNetworkController#createRandomizedDataset} in production.
*
* @throws IllegalArgumentException if length of {@code extendedPanId} is not {@link
* #LENGTH_EXTENDED_PAN_ID}.
@@ -867,7 +790,7 @@
*
* <p>Use with caution. A randomly generated PSKc should be used for real Thread networks.
* It's discouraged to call this method to override the default value created by {@link
- * ActiveOperationalDataset#createRandomDataset} in production.
+ * ThreadNetworkController#createRandomizedDataset} in production.
*
* @param pskc the key stretched version of the Commissioning Credential for the network
* @throws IllegalArgumentException if length of {@code pskc} is not {@link #LENGTH_PSKC}
@@ -889,7 +812,7 @@
*
* <p>Use with caution, randomly generated Network Key should be used for real Thread
* networks. It's discouraged to call this method to override the default value created by
- * {@link ActiveOperationalDataset#createRandomDataset} in production.
+ * {@link ThreadNetworkController#createRandomizedDataset} in production.
*
* @param networkKey a 128-bit security key-derivation key for the Thread Network
* @throws IllegalArgumentException if length of {@code networkKey} is not {@link
@@ -930,8 +853,16 @@
return this;
}
+ /**
+ * Sets the Mesh-Local Prefix.
+ *
+ * @param meshLocalPrefix the prefix used for realm-local traffic within the mesh
+ * @throws IllegalArgumentException if {@code meshLocalPrefix} doesn't start with {@code
+ * 0xfd} or has length other than {@code LENGTH_MESH_LOCAL_PREFIX_BITS / 8}
+ * @hide
+ */
@NonNull
- private Builder setMeshLocalPrefix(byte[] meshLocalPrefix) {
+ public Builder setMeshLocalPrefix(byte[] meshLocalPrefix) {
final int prefixLength = meshLocalPrefix.length * 8;
checkArgument(
prefixLength == LENGTH_MESH_LOCAL_PREFIX_BITS,
diff --git a/thread/framework/java/android/net/thread/IActiveOperationalDatasetReceiver.aidl b/thread/framework/java/android/net/thread/IActiveOperationalDatasetReceiver.aidl
new file mode 100644
index 0000000..aba54eb
--- /dev/null
+++ b/thread/framework/java/android/net/thread/IActiveOperationalDatasetReceiver.aidl
@@ -0,0 +1,25 @@
+/*
+ * Copyright 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.thread;
+
+import android.net.thread.ActiveOperationalDataset;
+
+/** Receives the result of an operation which returns an Active Operational Dataset. @hide */
+oneway interface IActiveOperationalDatasetReceiver {
+ void onSuccess(in ActiveOperationalDataset dataset);
+ void onError(int errorCode, String errorMessage);
+}
diff --git a/thread/framework/java/android/net/thread/IOperationReceiver.aidl b/thread/framework/java/android/net/thread/IOperationReceiver.aidl
new file mode 100644
index 0000000..42e157b
--- /dev/null
+++ b/thread/framework/java/android/net/thread/IOperationReceiver.aidl
@@ -0,0 +1,23 @@
+/*
+ * Copyright 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.thread;
+
+/** Receives the result of a Thread network operation. @hide */
+oneway interface IOperationReceiver {
+ void onSuccess();
+ void onError(int errorCode, String errorMessage);
+}
diff --git a/thread/framework/java/android/net/thread/IOperationalDatasetCallback.aidl b/thread/framework/java/android/net/thread/IOperationalDatasetCallback.aidl
new file mode 100644
index 0000000..b576b33
--- /dev/null
+++ b/thread/framework/java/android/net/thread/IOperationalDatasetCallback.aidl
@@ -0,0 +1,28 @@
+/*
+ * Copyright 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.thread;
+
+import android.net.thread.ActiveOperationalDataset;
+import android.net.thread.PendingOperationalDataset;
+
+/**
+ * @hide
+ */
+oneway interface IOperationalDatasetCallback {
+ void onActiveOperationalDatasetChanged(in @nullable ActiveOperationalDataset activeOpDataset);
+ void onPendingOperationalDatasetChanged(in @nullable PendingOperationalDataset pendingOpDataset);
+}
diff --git a/thread/framework/java/android/net/thread/IScheduleMigrationReceiver.aidl b/thread/framework/java/android/net/thread/IScheduleMigrationReceiver.aidl
new file mode 100644
index 0000000..c45d463
--- /dev/null
+++ b/thread/framework/java/android/net/thread/IScheduleMigrationReceiver.aidl
@@ -0,0 +1,24 @@
+/*
+ * Copyright 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.thread;
+
+/** Receives the result of {@link ThreadNetworkManager#scheduleMigration}. @hide */
+oneway interface IScheduleMigrationReceiver {
+ void onScheduled(long delayTimerMillis);
+ void onMigrated();
+ void onError(int errorCode, String errorMessage);
+}
diff --git a/thread/framework/java/android/net/thread/IStateCallback.aidl b/thread/framework/java/android/net/thread/IStateCallback.aidl
new file mode 100644
index 0000000..d7cbda9
--- /dev/null
+++ b/thread/framework/java/android/net/thread/IStateCallback.aidl
@@ -0,0 +1,25 @@
+/*
+ * Copyright 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.thread;
+
+/**
+ * @hide
+ */
+oneway interface IStateCallback {
+ void onDeviceRoleChanged(int deviceRole);
+ void onPartitionIdChanged(long partitionId);
+}
diff --git a/thread/framework/java/android/net/thread/IThreadNetworkController.aidl b/thread/framework/java/android/net/thread/IThreadNetworkController.aidl
index 0219beb..51e4d88 100644
--- a/thread/framework/java/android/net/thread/IThreadNetworkController.aidl
+++ b/thread/framework/java/android/net/thread/IThreadNetworkController.aidl
@@ -16,10 +16,29 @@
package android.net.thread;
+import android.net.Network;
+import android.net.thread.ActiveOperationalDataset;
+import android.net.thread.IActiveOperationalDatasetReceiver;
+import android.net.thread.IOperationalDatasetCallback;
+import android.net.thread.IOperationReceiver;
+import android.net.thread.IScheduleMigrationReceiver;
+import android.net.thread.IStateCallback;
+import android.net.thread.PendingOperationalDataset;
+
/**
* Interface for communicating with ThreadNetworkControllerService.
* @hide
*/
interface IThreadNetworkController {
+ void registerStateCallback(in IStateCallback callback);
+ void unregisterStateCallback(in IStateCallback callback);
+ void registerOperationalDatasetCallback(in IOperationalDatasetCallback callback);
+ void unregisterOperationalDatasetCallback(in IOperationalDatasetCallback callback);
+
+ void join(in ActiveOperationalDataset activeOpDataset, in IOperationReceiver receiver);
+ void scheduleMigration(in PendingOperationalDataset pendingOpDataset, in IOperationReceiver receiver);
+ void leave(in IOperationReceiver receiver);
+
int getThreadVersion();
+ void createRandomizedDataset(String networkName, IActiveOperationalDatasetReceiver receiver);
}
diff --git a/thread/framework/java/android/net/thread/PendingOperationalDataset.java b/thread/framework/java/android/net/thread/PendingOperationalDataset.java
index 4762d7f..9cfd0b8 100644
--- a/thread/framework/java/android/net/thread/PendingOperationalDataset.java
+++ b/thread/framework/java/android/net/thread/PendingOperationalDataset.java
@@ -69,7 +69,15 @@
@NonNull private final OperationalDatasetTimestamp mPendingTimestamp;
@NonNull private final Duration mDelayTimer;
- /** Creates a new {@link PendingOperationalDataset} object. */
+ /**
+ * Creates a new {@link PendingOperationalDataset} object.
+ *
+ * @param activeOpDataset the included Active Operational Dataset
+ * @param pendingTimestamp the Pending Timestamp which represents the version of this Pending
+ * Dataset
+ * @param delayTimer the delay after when {@code activeOpDataset} will be committed on this
+ * device
+ */
public PendingOperationalDataset(
@NonNull ActiveOperationalDataset activeOpDataset,
@NonNull OperationalDatasetTimestamp pendingTimestamp,
diff --git a/thread/framework/java/android/net/thread/ThreadNetworkController.java b/thread/framework/java/android/net/thread/ThreadNetworkController.java
index fc77b1a..ec39db4 100644
--- a/thread/framework/java/android/net/thread/ThreadNetworkController.java
+++ b/thread/framework/java/android/net/thread/ThreadNetworkController.java
@@ -18,23 +18,64 @@
import static java.util.Objects.requireNonNull;
+import android.Manifest.permission;
+import android.annotation.CallbackExecutor;
import android.annotation.FlaggedApi;
import android.annotation.IntDef;
import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
+import android.os.OutcomeReceiver;
import android.os.RemoteException;
+import com.android.internal.annotations.GuardedBy;
+
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.Executor;
/**
- * Provides the primary API for controlling all aspects of a Thread network.
+ * Provides the primary APIs for controlling all aspects of a Thread network.
+ *
+ * <p>For example, join this device to a Thread network with given Thread Operational Dataset, or
+ * migrate an existing network.
*
* @hide
*/
@FlaggedApi(ThreadNetworkFlags.FLAG_THREAD_ENABLED)
@SystemApi
public final class ThreadNetworkController {
+ private static final String TAG = "ThreadNetworkController";
+
+ /** The Thread stack is stopped. */
+ public static final int DEVICE_ROLE_STOPPED = 0;
+
+ /** The device is not currently participating in a Thread network/partition. */
+ public static final int DEVICE_ROLE_DETACHED = 1;
+
+ /** The device is a Thread Child. */
+ public static final int DEVICE_ROLE_CHILD = 2;
+
+ /** The device is a Thread Router. */
+ public static final int DEVICE_ROLE_ROUTER = 3;
+
+ /** The device is a Thread Leader. */
+ public static final int DEVICE_ROLE_LEADER = 4;
+
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({
+ DEVICE_ROLE_STOPPED,
+ DEVICE_ROLE_DETACHED,
+ DEVICE_ROLE_CHILD,
+ DEVICE_ROLE_ROUTER,
+ DEVICE_ROLE_LEADER
+ })
+ public @interface DeviceRole {}
/** Thread standard version 1.3. */
public static final int THREAD_VERSION_1_3 = 4;
@@ -46,9 +87,19 @@
private final IThreadNetworkController mControllerService;
+ private final Object mStateCallbackMapLock = new Object();
+
+ @GuardedBy("mStateCallbackMapLock")
+ private final Map<StateCallback, StateCallbackProxy> mStateCallbackMap = new HashMap<>();
+
+ private final Object mOpDatasetCallbackMapLock = new Object();
+
+ @GuardedBy("mOpDatasetCallbackMapLock")
+ private final Map<OperationalDatasetCallback, OperationalDatasetCallbackProxy>
+ mOpDatasetCallbackMap = new HashMap<>();
+
ThreadNetworkController(@NonNull IThreadNetworkController controllerService) {
requireNonNull(controllerService, "controllerService cannot be null");
-
mControllerService = controllerService;
}
@@ -61,4 +112,412 @@
throw e.rethrowFromSystemServer();
}
}
+
+ /**
+ * Creates a new Active Operational Dataset with randomized parameters.
+ *
+ * <p>This method is the recommended way to create a randomized dataset which can be used with
+ * {@link #join} to securely join this device to the specified network . It's highly discouraged
+ * to change the randomly generated Extended PAN ID, Network Key or PSKc, as it will compromise
+ * the security of a Thread network.
+ *
+ * @throws IllegalArgumentException if length of the UTF-8 representation of {@code networkName}
+ * isn't in range of [{@link #LENGTH_MIN_NETWORK_NAME_BYTES}, {@link
+ * #LENGTH_MAX_NETWORK_NAME_BYTES}]
+ */
+ public void createRandomizedDataset(
+ @NonNull String networkName,
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull OutcomeReceiver<ActiveOperationalDataset, ThreadNetworkException> receiver) {
+ ActiveOperationalDataset.checkNetworkName(networkName);
+ requireNonNull(executor, "executor cannot be null");
+ requireNonNull(receiver, "receiver cannot be null");
+ try {
+ mControllerService.createRandomizedDataset(
+ networkName, new ActiveDatasetReceiverProxy(executor, receiver));
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+
+ /** Returns {@code true} if {@code deviceRole} indicates an attached state. */
+ public static boolean isAttached(@DeviceRole int deviceRole) {
+ return deviceRole == DEVICE_ROLE_CHILD
+ || deviceRole == DEVICE_ROLE_ROUTER
+ || deviceRole == DEVICE_ROLE_LEADER;
+ }
+
+ /**
+ * Callback to receive notifications when the Thread network states are changed.
+ *
+ * <p>Applications which are interested in monitoring Thread network states should implement
+ * this interface and register the callback with {@link #registerStateCallback}.
+ */
+ public interface StateCallback {
+ /**
+ * The Thread device role has changed.
+ *
+ * @param deviceRole the new Thread device role
+ */
+ void onDeviceRoleChanged(@DeviceRole int deviceRole);
+
+ /**
+ * The Thread network partition ID has changed.
+ *
+ * @param partitionId the new Thread partition ID
+ */
+ default void onPartitionIdChanged(long partitionId) {}
+ }
+
+ private static final class StateCallbackProxy extends IStateCallback.Stub {
+ private final Executor mExecutor;
+ private final StateCallback mCallback;
+
+ StateCallbackProxy(@CallbackExecutor Executor executor, StateCallback callback) {
+ mExecutor = executor;
+ mCallback = callback;
+ }
+
+ @Override
+ public void onDeviceRoleChanged(@DeviceRole int deviceRole) {
+ mExecutor.execute(() -> mCallback.onDeviceRoleChanged(deviceRole));
+ }
+
+ @Override
+ public void onPartitionIdChanged(long partitionId) {
+ mExecutor.execute(() -> mCallback.onPartitionIdChanged(partitionId));
+ }
+ }
+
+ /**
+ * Registers a callback to be called when Thread network states are changed.
+ *
+ * <p>Upon return of this method, methods of {@code callback} will be invoked immediately with
+ * existing states.
+ *
+ * @param executor the executor to execute the {@code callback}
+ * @param callback the callback to receive Thread network state changes
+ * @throws IllegalArgumentException if {@code callback} has already been registered
+ */
+ @RequiresPermission(permission.ACCESS_NETWORK_STATE)
+ public void registerStateCallback(
+ @NonNull @CallbackExecutor Executor executor, @NonNull StateCallback callback) {
+ requireNonNull(executor, "executor cannot be null");
+ requireNonNull(callback, "callback cannot be null");
+ synchronized (mStateCallbackMapLock) {
+ if (mStateCallbackMap.containsKey(callback)) {
+ throw new IllegalArgumentException("callback has already been registered");
+ }
+ StateCallbackProxy callbackProxy = new StateCallbackProxy(executor, callback);
+ mStateCallbackMap.put(callback, callbackProxy);
+
+ try {
+ mControllerService.registerStateCallback(callbackProxy);
+ } catch (RemoteException e) {
+ mStateCallbackMap.remove(callback);
+ e.rethrowFromSystemServer();
+ }
+ }
+ }
+
+ /**
+ * Unregisters the Thread state changed callback.
+ *
+ * @param callback the callback which has been registered with {@link #registerStateCallback}
+ * @throws IllegalArgumentException if {@code callback} hasn't been registered
+ */
+ public void unregisterStateCallback(@NonNull StateCallback callback) {
+ requireNonNull(callback, "callback cannot be null");
+ synchronized (mStateCallbackMapLock) {
+ StateCallbackProxy callbackProxy = mStateCallbackMap.remove(callback);
+ if (callbackProxy == null) {
+ throw new IllegalArgumentException("callback hasn't been registered");
+ }
+ try {
+ mControllerService.unregisterStateCallback(callbackProxy);
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+ }
+
+ /**
+ * Callback to receive notifications when the Thread Operational Datasets are changed.
+ *
+ * <p>Applications which are interested in monitoring Thread network datasets should implement
+ * this interface and register the callback with {@link #registerOperationalDatasetCallback}.
+ */
+ public interface OperationalDatasetCallback {
+ /**
+ * Called when the Active Operational Dataset is changed.
+ *
+ * @param activeDataset the new Active Operational Dataset or {@code null} if the dataset is
+ * absent
+ */
+ void onActiveOperationalDatasetChanged(@Nullable ActiveOperationalDataset activeDataset);
+
+ /**
+ * Called when the Pending Operational Dataset is changed.
+ *
+ * @param pendingDataset the new Pending Operational Dataset or {@code null} if the dataset
+ * has been committed and removed
+ */
+ default void onPendingOperationalDatasetChanged(
+ @Nullable PendingOperationalDataset pendingDataset) {}
+ }
+
+ private static final class OperationalDatasetCallbackProxy
+ extends IOperationalDatasetCallback.Stub {
+ private final Executor mExecutor;
+ private final OperationalDatasetCallback mCallback;
+
+ OperationalDatasetCallbackProxy(
+ @CallbackExecutor Executor executor, OperationalDatasetCallback callback) {
+ mExecutor = executor;
+ mCallback = callback;
+ }
+
+ @Override
+ public void onActiveOperationalDatasetChanged(
+ @Nullable ActiveOperationalDataset activeDataset) {
+ mExecutor.execute(() -> mCallback.onActiveOperationalDatasetChanged(activeDataset));
+ }
+
+ @Override
+ public void onPendingOperationalDatasetChanged(
+ @Nullable PendingOperationalDataset pendingDataset) {
+ mExecutor.execute(() -> mCallback.onPendingOperationalDatasetChanged(pendingDataset));
+ }
+ }
+
+ /**
+ * Registers a callback to be called when Thread Operational Datasets are changed.
+ *
+ * <p>Upon return of this method, methods of {@code callback} will be invoked immediately with
+ * existing Operational Datasets.
+ *
+ * @param executor the executor to execute {@code callback}
+ * @param callback the callback to receive Operational Dataset changes
+ * @throws IllegalArgumentException if {@code callback} has already been registered
+ */
+ @RequiresPermission(
+ allOf = {
+ permission.ACCESS_NETWORK_STATE,
+ "android.permission.THREAD_NETWORK_PRIVILEGED"
+ })
+ public void registerOperationalDatasetCallback(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull OperationalDatasetCallback callback) {
+ requireNonNull(executor, "executor cannot be null");
+ requireNonNull(callback, "callback cannot be null");
+ synchronized (mOpDatasetCallbackMapLock) {
+ if (mOpDatasetCallbackMap.containsKey(callback)) {
+ throw new IllegalArgumentException("callback has already been registered");
+ }
+ OperationalDatasetCallbackProxy callbackProxy =
+ new OperationalDatasetCallbackProxy(executor, callback);
+ mOpDatasetCallbackMap.put(callback, callbackProxy);
+
+ try {
+ mControllerService.registerOperationalDatasetCallback(callbackProxy);
+ } catch (RemoteException e) {
+ mOpDatasetCallbackMap.remove(callback);
+ e.rethrowFromSystemServer();
+ }
+ }
+ }
+
+ /**
+ * Unregisters the Thread Operational Dataset callback.
+ *
+ * @param callback the callback which has been registered with {@link
+ * #registerOperationalDatasetCallback}
+ * @throws IllegalArgumentException if {@code callback} hasn't been registered
+ */
+ public void unregisterOperationalDatasetCallback(@NonNull OperationalDatasetCallback callback) {
+ requireNonNull(callback, "callback cannot be null");
+ synchronized (mOpDatasetCallbackMapLock) {
+ OperationalDatasetCallbackProxy callbackProxy = mOpDatasetCallbackMap.remove(callback);
+ if (callbackProxy == null) {
+ throw new IllegalArgumentException("callback hasn't been registered");
+ }
+ try {
+ mControllerService.unregisterOperationalDatasetCallback(callbackProxy);
+ } catch (RemoteException e) {
+ e.rethrowFromSystemServer();
+ }
+ }
+ }
+
+ /**
+ * Joins to a Thread network with given Active Operational Dataset.
+ *
+ * <p>This method does nothing if this device has already joined to the same network specified
+ * by {@code activeDataset}. If this device has already joined to a different network, this
+ * device will first leave from that network and then join the new network. This method changes
+ * only this device and all other connected devices will stay in the old network. To change the
+ * network for all connected devices together, use {@link #scheduleMigration}.
+ *
+ * <p>On success, {@link OutcomeReceiver#onResult} of {@code receiver} is called and the Dataset
+ * will be persisted on this device; this device will try to attach to the Thread network and
+ * the state changes can be observed by {@link #registerStateCallback}. On failure, {@link
+ * OutcomeReceiver#onError} of {@code receiver} will be invoked with a specific error:
+ *
+ * <ul>
+ * <li>{@link ThreadNetworkException#ERROR_UNSUPPORTED_CHANNEL} {@code activeDataset}
+ * specifies a channel which is not supported in the current country or region; the {@code
+ * activeDataset} is rejected and not persisted so this device won't auto re-join the next
+ * time
+ * <li>{@link ThreadNetworkException#ERROR_ABORTED} this operation is aborted by another
+ * {@code join} or {@code leave} operation
+ * </ul>
+ *
+ * @param activeDataset the Active Operational Dataset represents the Thread network to join
+ * @param executor the executor to execute {@code receiver}
+ * @param receiver the receiver to receive result of this operation
+ */
+ @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED")
+ public void join(
+ @NonNull ActiveOperationalDataset activeDataset,
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull OutcomeReceiver<Void, ThreadNetworkException> receiver) {
+ requireNonNull(activeDataset, "activeDataset cannot be null");
+ requireNonNull(executor, "executor cannot be null");
+ requireNonNull(receiver, "receiver cannot be null");
+ try {
+ mControllerService.join(activeDataset, new OperationReceiverProxy(executor, receiver));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Schedules a network migration which moves all devices in the current connected network to a
+ * new network or updates parameters of the current connected network.
+ *
+ * <p>The migration doesn't happen immediately but is registered to the Leader device so that
+ * all devices in the current Thread network can be scheduled to apply the new dataset together.
+ *
+ * <p>On success, the Pending Dataset is successfully registered and persisted on the Leader and
+ * {@link OutcomeReceiver#onResult} of {@code receiver} will be called; Operational Dataset
+ * changes will be asynchronously delivered via {@link OperationalDatasetCallback} if a callback
+ * has been registered with {@link #registerOperationalDatasetCallback}. When failed, {@link
+ * OutcomeReceiver#onError} will be called with a specific error:
+ *
+ * <ul>
+ * <li>{@link ThreadNetworkException#ERROR_FAILED_PRECONDITION} the migration is rejected
+ * because this device is not attached
+ * <li>{@link ThreadNetworkException#ERROR_UNSUPPORTED_CHANNEL} {@code pendingDataset}
+ * specifies a channel which is not supported in the current country or region; the {@code
+ * pendingDataset} is rejected and not persisted
+ * <li>{@link ThreadNetworkException#ERROR_REJECTED_BY_PEER} the Pending Dataset is rejected
+ * by the Leader device
+ * <li>{@link ThreadNetworkException#ERROR_BUSY} another {@code scheduleMigration} request is
+ * being processed
+ * <li>{@link ThreadNetworkException#ERROR_TIMEOUT} response from the Leader device hasn't
+ * been received before deadline
+ * </ul>
+ *
+ * <p>The Delay Timer of {@code pendingDataset} can vary from several minutes to a few days.
+ * It's important to select a proper value to safely migrate all devices in the network without
+ * leaving sleepy end devices orphaned. Apps are not suggested to specify the Delay Timer value
+ * if it's unclear how long it can take to propagate the {@code pendingDataset} to the whole
+ * network. Instead, use {@link Duration#ZERO} to use the default value suggested by the system.
+ *
+ * @param pendingDataset the Pending Operational Dataset
+ * @param executor the executor to execute {@code receiver}
+ * @param receiver the receiver to receive result of this operation
+ */
+ @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED")
+ public void scheduleMigration(
+ @NonNull PendingOperationalDataset pendingDataset,
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull OutcomeReceiver<Void, ThreadNetworkException> receiver) {
+ requireNonNull(pendingDataset, "pendingDataset cannot be null");
+ requireNonNull(executor, "executor cannot be null");
+ requireNonNull(receiver, "receiver cannot be null");
+ try {
+ mControllerService.scheduleMigration(
+ pendingDataset, new OperationReceiverProxy(executor, receiver));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
+ * Leaves from the Thread network.
+ *
+ * <p>This undoes a {@link join} operation. On success, this device is disconnected from the
+ * joined network and will not automatically join a network before {@link #join} is called
+ * again. Active and Pending Operational Dataset configured and persisted on this device will be
+ * removed too.
+ *
+ * @param executor the executor to execute {@code receiver}
+ * @param receiver the receiver to receive result of this operation
+ */
+ @RequiresPermission("android.permission.THREAD_NETWORK_PRIVILEGED")
+ public void leave(
+ @NonNull @CallbackExecutor Executor executor,
+ @NonNull OutcomeReceiver<Void, ThreadNetworkException> receiver) {
+ requireNonNull(executor, "executor cannot be null");
+ requireNonNull(receiver, "receiver cannot be null");
+ try {
+ mControllerService.leave(new OperationReceiverProxy(executor, receiver));
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ private static <T> void propagateError(
+ Executor executor,
+ OutcomeReceiver<T, ThreadNetworkException> receiver,
+ int errorCode,
+ String errorMsg) {
+ executor.execute(() -> receiver.onError(new ThreadNetworkException(errorCode, errorMsg)));
+ }
+
+ private static final class ActiveDatasetReceiverProxy
+ extends IActiveOperationalDatasetReceiver.Stub {
+ final Executor mExecutor;
+ final OutcomeReceiver<ActiveOperationalDataset, ThreadNetworkException> mResultReceiver;
+
+ ActiveDatasetReceiverProxy(
+ @CallbackExecutor Executor executor,
+ OutcomeReceiver<ActiveOperationalDataset, ThreadNetworkException> resultReceiver) {
+ this.mExecutor = executor;
+ this.mResultReceiver = resultReceiver;
+ }
+
+ @Override
+ public void onSuccess(ActiveOperationalDataset dataset) {
+ mExecutor.execute(() -> mResultReceiver.onResult(dataset));
+ }
+
+ @Override
+ public void onError(int errorCode, String errorMessage) {
+ propagateError(mExecutor, mResultReceiver, errorCode, errorMessage);
+ }
+ }
+
+ private static final class OperationReceiverProxy extends IOperationReceiver.Stub {
+ final Executor mExecutor;
+ final OutcomeReceiver<Void, ThreadNetworkException> mResultReceiver;
+
+ OperationReceiverProxy(
+ @CallbackExecutor Executor executor,
+ OutcomeReceiver<Void, ThreadNetworkException> resultReceiver) {
+ this.mExecutor = executor;
+ this.mResultReceiver = resultReceiver;
+ }
+
+ @Override
+ public void onSuccess() {
+ mExecutor.execute(() -> mResultReceiver.onResult(null));
+ }
+
+ @Override
+ public void onError(int errorCode, String errorMessage) {
+ propagateError(mExecutor, mResultReceiver, errorCode, errorMessage);
+ }
+ }
}
diff --git a/thread/framework/java/android/net/thread/ThreadNetworkException.java b/thread/framework/java/android/net/thread/ThreadNetworkException.java
new file mode 100644
index 0000000..c5e1e97
--- /dev/null
+++ b/thread/framework/java/android/net/thread/ThreadNetworkException.java
@@ -0,0 +1,137 @@
+/*
+ * 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.thread;
+
+import static java.util.Objects.requireNonNull;
+
+import android.annotation.FlaggedApi;
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Represents a Thread network specific failure.
+ *
+ * @hide
+ */
+@FlaggedApi(ThreadNetworkFlags.FLAG_THREAD_ENABLED)
+@SystemApi
+public class ThreadNetworkException extends Exception {
+ /** @hide */
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef({
+ ERROR_INTERNAL_ERROR,
+ ERROR_ABORTED,
+ ERROR_TIMEOUT,
+ ERROR_UNAVAILABLE,
+ ERROR_BUSY,
+ ERROR_FAILED_PRECONDITION,
+ ERROR_UNSUPPORTED_CHANNEL,
+ ERROR_REJECTED_BY_PEER,
+ ERROR_RESPONSE_BAD_FORMAT,
+ ERROR_RESOURCE_EXHAUSTED,
+ })
+ public @interface ErrorCode {}
+
+ /**
+ * The operation failed because some invariants expected by the underlying system have been
+ * broken. This error code is reserved for serious errors. The caller can do nothing to recover
+ * from this error. A bugreport should be created and sent to the Android community if this
+ * error is ever returned.
+ */
+ public static final int ERROR_INTERNAL_ERROR = 1;
+
+ /**
+ * The operation failed because concurrent operations are overriding this one. Retrying an
+ * aborted operation has the risk of aborting another ongoing operation again. So the caller
+ * should retry at a higher level where it knows there won't be race conditions.
+ */
+ public static final int ERROR_ABORTED = 2;
+
+ /**
+ * The operation failed because a deadline expired before the operation could complete. This may
+ * be caused by connectivity unavailability and the caller can retry the same operation when the
+ * connectivity issue is fixed.
+ */
+ public static final int ERROR_TIMEOUT = 3;
+
+ /**
+ * The operation failed because the service is currently unavailable and that this is most
+ * likely a transient condition. The caller can recover from this error by retrying with a
+ * back-off scheme. Note that it is not always safe to retry non-idempotent operations.
+ */
+ public static final int ERROR_UNAVAILABLE = 4;
+
+ /**
+ * The operation failed because this device is currently busy processing concurrent requests.
+ * The caller may recover from this error when the current operations has been finished.
+ */
+ public static final int ERROR_BUSY = 5;
+
+ /**
+ * The operation failed because required preconditions were not satisfied. For example, trying
+ * to schedule a network migration when this device is not attached will receive this error. The
+ * caller should not retry the same operation before the precondition is satisfied.
+ */
+ public static final int ERROR_FAILED_PRECONDITION = 6;
+
+ /**
+ * The operation was rejected because the specified channel is currently not supported by this
+ * device in this country. For example, trying to join or migrate to a network with channel
+ * which is not supported. The caller should should change the channel or return an error to the
+ * user if the channel cannot be changed.
+ */
+ public static final int ERROR_UNSUPPORTED_CHANNEL = 7;
+
+ /**
+ * The operation failed because a request is rejected by the peer device. This happens because
+ * the peer device is not capable of processing the request, or a request from another device
+ * has already been accepted by the peer device. The caller may not be able to recover from this
+ * error by retrying the same operation.
+ */
+ public static final int ERROR_REJECTED_BY_PEER = 8;
+
+ /**
+ * The operation failed because the received response is malformed. This is typically because
+ * the peer device is misbehaving. The caller may only recover from this error by retrying with
+ * a different peer device.
+ */
+ public static final int ERROR_RESPONSE_BAD_FORMAT = 9;
+
+ /**
+ * The operation failed because some resource has been exhausted. For example, no enough
+ * allocated memory buffers, or maximum number of supported operations has been exceeded. The
+ * caller may retry and recover from this error when the resource has been freed.
+ */
+ public static final int ERROR_RESOURCE_EXHAUSTED = 10;
+
+ private final int mErrorCode;
+
+ /** Creates a new {@link ThreadNetworkException} object with given error code and message. */
+ public ThreadNetworkException(@ErrorCode int errorCode, @NonNull String errorMessage) {
+ super(requireNonNull(errorMessage, "errorMessage cannot be null"));
+ this.mErrorCode = errorCode;
+ }
+
+ /** Returns the error code. */
+ public @ErrorCode int getErrorCode() {
+ return mErrorCode;
+ }
+}
diff --git a/thread/framework/java/android/net/thread/ThreadNetworkManager.java b/thread/framework/java/android/net/thread/ThreadNetworkManager.java
index c3bdbd7..28012a7 100644
--- a/thread/framework/java/android/net/thread/ThreadNetworkManager.java
+++ b/thread/framework/java/android/net/thread/ThreadNetworkManager.java
@@ -66,6 +66,19 @@
*/
public static final String FEATURE_NAME = "android.hardware.thread_network";
+ /**
+ * Permission allows changing Thread network state and access to Thread network credentials such
+ * as Network Key and PSKc.
+ *
+ * <p>This is the same value as android.Manifest.permission.THREAD_NETWORK_PRIVILEGED. That
+ * symbol is not available on U while this feature needs to support Android U TV devices, so
+ * here is making a copy of android.Manifest.permission.THREAD_NETWORK_PRIVILEGED.
+ *
+ * @hide
+ */
+ public static final String PERMISSION_THREAD_NETWORK_PRIVILEGED =
+ "android.permission.THREAD_NETWORK_PRIVILEGED";
+
@NonNull private final Context mContext;
@NonNull private final List<ThreadNetworkController> mUnmodifiableControllerServices;
diff --git a/thread/service/Android.bp b/thread/service/Android.bp
index f1af653..bd265e6 100644
--- a/thread/service/Android.bp
+++ b/thread/service/Android.bp
@@ -33,10 +33,35 @@
min_sdk_version: "30",
srcs: [":service-thread-sources"],
libs: [
+ "framework-connectivity-pre-jarjar",
"framework-connectivity-t-pre-jarjar",
+ "service-connectivity-pre-jarjar",
],
static_libs: [
"net-utils-device-common",
+ "net-utils-device-common-netlink",
+ "ot-daemon-aidl-java",
+ ],
+ apex_available: ["com.android.tethering"],
+}
+
+cc_library_shared {
+ name: "libservice-thread-jni",
+ min_sdk_version: "30",
+ cflags: [
+ "-Wall",
+ "-Werror",
+ "-Wno-unused-parameter",
+ "-Wthread-safety",
+ ],
+ srcs: [
+ "jni/**/*.cpp",
+ ],
+ shared_libs: [
+ "libbase",
+ "libcutils",
+ "liblog",
+ "libnativehelper",
],
apex_available: ["com.android.tethering"],
}
diff --git a/thread/service/java/com/android/server/thread/OperationReceiverWrapper.java b/thread/service/java/com/android/server/thread/OperationReceiverWrapper.java
new file mode 100644
index 0000000..a8909bc
--- /dev/null
+++ b/thread/service/java/com/android/server/thread/OperationReceiverWrapper.java
@@ -0,0 +1,82 @@
+/*
+ * 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 com.android.server.thread;
+
+import static android.net.thread.ThreadNetworkException.ERROR_UNAVAILABLE;
+
+import android.net.thread.IOperationReceiver;
+import android.os.RemoteException;
+
+import com.android.internal.annotations.GuardedBy;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/** A {@link IOperationReceiver} wrapper which makes it easier to invoke the callbacks. */
+final class OperationReceiverWrapper {
+ private final IOperationReceiver mReceiver;
+
+ private static final Object sPendingReceiversLock = new Object();
+
+ @GuardedBy("sPendingReceiversLock")
+ private static final Set<OperationReceiverWrapper> sPendingReceivers = new HashSet<>();
+
+ public OperationReceiverWrapper(IOperationReceiver receiver) {
+ this.mReceiver = receiver;
+
+ synchronized (sPendingReceiversLock) {
+ sPendingReceivers.add(this);
+ }
+ }
+
+ public static void onOtDaemonDied() {
+ synchronized (sPendingReceiversLock) {
+ for (OperationReceiverWrapper receiver : sPendingReceivers) {
+ try {
+ receiver.mReceiver.onError(ERROR_UNAVAILABLE, "Thread daemon died");
+ } catch (RemoteException e) {
+ // The client is dead, do nothing
+ }
+ }
+ sPendingReceivers.clear();
+ }
+ }
+
+ public void onSuccess() {
+ synchronized (sPendingReceiversLock) {
+ sPendingReceivers.remove(this);
+ }
+
+ try {
+ mReceiver.onSuccess();
+ } catch (RemoteException e) {
+ // The client is dead, do nothing
+ }
+ }
+
+ public void onError(int errorCode, String errorMessage, Object... messageArgs) {
+ synchronized (sPendingReceiversLock) {
+ sPendingReceivers.remove(this);
+ }
+
+ try {
+ mReceiver.onError(errorCode, String.format(errorMessage, messageArgs));
+ } catch (RemoteException e) {
+ // The client is dead, do nothing
+ }
+ }
+}
diff --git a/thread/service/java/com/android/server/thread/ThreadNetworkControllerService.java b/thread/service/java/com/android/server/thread/ThreadNetworkControllerService.java
index e8b95bc..6c9a775 100644
--- a/thread/service/java/com/android/server/thread/ThreadNetworkControllerService.java
+++ b/thread/service/java/com/android/server/thread/ThreadNetworkControllerService.java
@@ -1,31 +1,833 @@
/*
* 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
+ * 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
+ * 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.
+ * 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 com.android.server.thread;
+import static android.net.thread.ActiveOperationalDataset.CHANNEL_PAGE_24_GHZ;
+import static android.net.thread.ActiveOperationalDataset.LENGTH_EXTENDED_PAN_ID;
+import static android.net.thread.ActiveOperationalDataset.LENGTH_MESH_LOCAL_PREFIX_BITS;
+import static android.net.thread.ActiveOperationalDataset.LENGTH_NETWORK_KEY;
+import static android.net.thread.ActiveOperationalDataset.LENGTH_PSKC;
+import static android.net.thread.ActiveOperationalDataset.MESH_LOCAL_PREFIX_FIRST_BYTE;
+import static android.net.thread.ActiveOperationalDataset.SecurityPolicy.DEFAULT_ROTATION_TIME_HOURS;
+import static android.net.thread.ThreadNetworkController.DEVICE_ROLE_DETACHED;
import static android.net.thread.ThreadNetworkController.THREAD_VERSION_1_3;
+import static android.net.thread.ThreadNetworkException.ERROR_ABORTED;
+import static android.net.thread.ThreadNetworkException.ERROR_BUSY;
+import static android.net.thread.ThreadNetworkException.ERROR_FAILED_PRECONDITION;
+import static android.net.thread.ThreadNetworkException.ERROR_INTERNAL_ERROR;
+import static android.net.thread.ThreadNetworkException.ERROR_REJECTED_BY_PEER;
+import static android.net.thread.ThreadNetworkException.ERROR_RESOURCE_EXHAUSTED;
+import static android.net.thread.ThreadNetworkException.ERROR_RESPONSE_BAD_FORMAT;
+import static android.net.thread.ThreadNetworkException.ERROR_TIMEOUT;
+import static android.net.thread.ThreadNetworkException.ERROR_UNSUPPORTED_CHANNEL;
+import static android.net.thread.ThreadNetworkException.ErrorCode;
+import static android.net.thread.ThreadNetworkManager.PERMISSION_THREAD_NETWORK_PRIVILEGED;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_ABORT;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_BUSY;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_DETACHED;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_INVALID_STATE;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_NO_BUFS;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_PARSE;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_REASSEMBLY_TIMEOUT;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_REJECTED;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_RESPONSE_TIMEOUT;
+import static com.android.server.thread.openthread.IOtDaemon.ErrorCode.OT_ERROR_UNSUPPORTED_CHANNEL;
+import static com.android.server.thread.openthread.IOtDaemon.TUN_IF_NAME;
+
+import android.Manifest.permission;
+import android.annotation.NonNull;
+import android.content.Context;
+import android.net.ConnectivityManager;
+import android.net.LinkAddress;
+import android.net.LinkProperties;
+import android.net.NetworkAgent;
+import android.net.NetworkAgentConfig;
+import android.net.NetworkCapabilities;
+import android.net.NetworkProvider;
+import android.net.NetworkScore;
+import android.net.thread.ActiveOperationalDataset;
+import android.net.thread.ActiveOperationalDataset.SecurityPolicy;
+import android.net.thread.IActiveOperationalDatasetReceiver;
+import android.net.thread.IOperationReceiver;
+import android.net.thread.IOperationalDatasetCallback;
+import android.net.thread.IStateCallback;
import android.net.thread.IThreadNetworkController;
+import android.net.thread.OperationalDatasetTimestamp;
+import android.net.thread.PendingOperationalDataset;
import android.net.thread.ThreadNetworkController;
+import android.net.thread.ThreadNetworkController.DeviceRole;
+import android.os.Handler;
+import android.os.HandlerThread;
+import android.os.IBinder;
+import android.os.Looper;
+import android.os.RemoteException;
+import android.os.SystemClock;
+import android.util.Log;
+import android.util.SparseArray;
-/** Implementation of the {@link ThreadNetworkController} API. */
-public final class ThreadNetworkControllerService extends IThreadNetworkController.Stub {
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.server.ServiceManagerWrapper;
+import com.android.server.thread.openthread.IOtDaemon;
+import com.android.server.thread.openthread.IOtDaemonCallback;
+import com.android.server.thread.openthread.IOtStatusReceiver;
+import com.android.server.thread.openthread.Ipv6AddressInfo;
+import com.android.server.thread.openthread.OtDaemonState;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.security.SecureRandom;
+import java.time.Instant;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Random;
+import java.util.function.Supplier;
+
+/**
+ * Implementation of the {@link ThreadNetworkController} API.
+ *
+ * <p>Threading model: This class is not Thread-safe and should only be accessed from the
+ * ThreadNetworkService class. Additional attention should be paid to handle the threading code
+ * correctly: 1. All member fields other than `mHandler` and `mContext` MUST be accessed from
+ * `mHandlerThread` 2. In the @Override methods, the actual work MUST be dispatched to the
+ * HandlerThread except for arguments or permissions checking
+ */
+final class ThreadNetworkControllerService extends IThreadNetworkController.Stub {
+ private static final String TAG = "ThreadNetworkService";
+
+ // Below member fields can be accessed from both the binder and handler threads
+
+ private final Context mContext;
+ private final Handler mHandler;
+
+ // Below member fields can only be accessed from the handler thread (`mHandlerThread`). In
+ // particular, the constructor does not run on the handler thread, so it must not touch any of
+ // the non-final fields, nor must it mutate any of the non-final fields inside these objects.
+
+ private final HandlerThread mHandlerThread;
+ private final NetworkProvider mNetworkProvider;
+ private final Supplier<IOtDaemon> mOtDaemonSupplier;
+ private final ConnectivityManager mConnectivityManager;
+ private final TunInterfaceController mTunIfController;
+ private final LinkProperties mLinkProperties = new LinkProperties();
+ private final OtDaemonCallbackProxy mOtDaemonCallbackProxy = new OtDaemonCallbackProxy();
+
+ // TODO(b/308310823): read supported channel from Thread dameon
+ private final int mSupportedChannelMask = 0x07FFF800; // from channel 11 to 26
+
+ private IOtDaemon mOtDaemon;
+ private NetworkAgent mNetworkAgent;
+
+ @VisibleForTesting
+ ThreadNetworkControllerService(
+ Context context,
+ HandlerThread handlerThread,
+ NetworkProvider networkProvider,
+ Supplier<IOtDaemon> otDaemonSupplier,
+ ConnectivityManager connectivityManager,
+ TunInterfaceController tunIfController) {
+ mContext = context;
+ mHandlerThread = handlerThread;
+ mHandler = new Handler(handlerThread.getLooper());
+ mNetworkProvider = networkProvider;
+ mOtDaemonSupplier = otDaemonSupplier;
+ mConnectivityManager = connectivityManager;
+ mTunIfController = tunIfController;
+ }
+
+ public static ThreadNetworkControllerService newInstance(Context context) {
+ HandlerThread handlerThread = new HandlerThread("ThreadHandlerThread");
+ handlerThread.start();
+ NetworkProvider networkProvider =
+ new NetworkProvider(context, handlerThread.getLooper(), "ThreadNetworkProvider");
+
+ return new ThreadNetworkControllerService(
+ context,
+ handlerThread,
+ networkProvider,
+ () -> IOtDaemon.Stub.asInterface(ServiceManagerWrapper.waitForService("ot_daemon")),
+ context.getSystemService(ConnectivityManager.class),
+ new TunInterfaceController(TUN_IF_NAME));
+ }
+
+ private static NetworkCapabilities newNetworkCapabilities() {
+ return new NetworkCapabilities.Builder()
+ .addTransportType(NetworkCapabilities.TRANSPORT_THREAD)
+ .addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED)
+ .build();
+ }
+
+ private static InetAddress addressInfoToInetAddress(Ipv6AddressInfo addressInfo) {
+ try {
+ return InetAddress.getByAddress(addressInfo.address);
+ } catch (UnknownHostException e) {
+ // This is impossible unless the Thread daemon is critically broken
+ return null;
+ }
+ }
+
+ private static LinkAddress newLinkAddress(Ipv6AddressInfo addressInfo) {
+ long deprecationTimeMillis =
+ addressInfo.isPreferred
+ ? LinkAddress.LIFETIME_PERMANENT
+ : SystemClock.elapsedRealtime();
+
+ InetAddress address = addressInfoToInetAddress(addressInfo);
+
+ // flags and scope will be adjusted automatically depending on the address and
+ // its lifetimes.
+ return new LinkAddress(
+ address,
+ addressInfo.prefixLength,
+ 0 /* flags */,
+ 0 /* scope */,
+ deprecationTimeMillis,
+ LinkAddress.LIFETIME_PERMANENT /* expirationTime */);
+ }
+
+ private void initializeOtDaemon() {
+ try {
+ getOtDaemon();
+ } catch (RemoteException e) {
+ Log.e(TAG, "Failed to initialize ot-daemon");
+ }
+ }
+
+ private IOtDaemon getOtDaemon() throws RemoteException {
+ if (mOtDaemon != null) {
+ return mOtDaemon;
+ }
+
+ IOtDaemon otDaemon = mOtDaemonSupplier.get();
+ if (otDaemon == null) {
+ throw new RemoteException("Internal error: failed to start OT daemon");
+ }
+ otDaemon.asBinder().linkToDeath(() -> mHandler.post(this::onOtDaemonDied), 0);
+ otDaemon.initialize(mTunIfController.getTunFd());
+ otDaemon.registerStateCallback(mOtDaemonCallbackProxy, -1);
+ mOtDaemon = otDaemon;
+ return mOtDaemon;
+ }
+
+ private void onOtDaemonDied() {
+ Log.w(TAG, "OT daemon became dead, clean up...");
+ OperationReceiverWrapper.onOtDaemonDied();
+ mOtDaemonCallbackProxy.onOtDaemonDied();
+ mOtDaemon = null;
+ }
+
+ public void initialize() {
+ mHandler.post(
+ () -> {
+ Log.d(TAG, "Initializing Thread system service...");
+ try {
+ mTunIfController.createTunInterface();
+ } catch (IOException e) {
+ throw new IllegalStateException(
+ "Failed to create Thread tunnel interface", e);
+ }
+ mLinkProperties.setInterfaceName(TUN_IF_NAME);
+ mLinkProperties.setMtu(TunInterfaceController.MTU);
+ mConnectivityManager.registerNetworkProvider(mNetworkProvider);
+
+ initializeOtDaemon();
+ });
+ }
+
+ private void registerThreadNetwork() {
+ if (mNetworkAgent != null) {
+ return;
+ }
+ NetworkCapabilities netCaps = newNetworkCapabilities();
+ NetworkScore score =
+ new NetworkScore.Builder()
+ .setKeepConnectedReason(NetworkScore.KEEP_CONNECTED_LOCAL_NETWORK)
+ .build();
+ mNetworkAgent =
+ new NetworkAgent(
+ mContext,
+ mHandlerThread.getLooper(),
+ TAG,
+ netCaps,
+ mLinkProperties,
+ score,
+ new NetworkAgentConfig.Builder().build(),
+ mNetworkProvider) {};
+ mNetworkAgent.register();
+ mNetworkAgent.markConnected();
+ Log.i(TAG, "Registered Thread network");
+ }
+
+ private void unregisterThreadNetwork() {
+ if (mNetworkAgent == null) {
+ // unregisterThreadNetwork can be called every time this device becomes detached or
+ // disabled and the mNetworkAgent may not be created in this cases
+ return;
+ }
+
+ Log.d(TAG, "Unregistering Thread network agent");
+
+ mNetworkAgent.unregister();
+ mNetworkAgent = null;
+ }
+
+ private void updateTunInterfaceAddress(LinkAddress linkAddress, boolean isAdded) {
+ try {
+ if (isAdded) {
+ mTunIfController.addAddress(linkAddress);
+ } else {
+ mTunIfController.removeAddress(linkAddress);
+ }
+ } catch (IOException e) {
+ Log.e(
+ TAG,
+ String.format(
+ "Failed to %s Thread tun interface address %s",
+ (isAdded ? "add" : "remove"), linkAddress),
+ e);
+ }
+ }
+
+ private void updateNetworkLinkProperties(LinkAddress linkAddress, boolean isAdded) {
+ if (isAdded) {
+ mLinkProperties.addLinkAddress(linkAddress);
+ } else {
+ mLinkProperties.removeLinkAddress(linkAddress);
+ }
+
+ // The Thread daemon can send link property updates before the networkAgent is
+ // registered
+ if (mNetworkAgent != null) {
+ mNetworkAgent.sendLinkProperties(mLinkProperties);
+ }
+ }
@Override
public int getThreadVersion() {
return THREAD_VERSION_1_3;
}
+
+ @Override
+ public void createRandomizedDataset(
+ String networkName, IActiveOperationalDatasetReceiver receiver) {
+ mHandler.post(
+ () -> {
+ ActiveOperationalDataset dataset =
+ createRandomizedDatasetInternal(
+ networkName,
+ mSupportedChannelMask,
+ Instant.now(),
+ new Random(),
+ new SecureRandom());
+ try {
+ receiver.onSuccess(dataset);
+ } catch (RemoteException e) {
+ // The client is dead, do nothing
+ }
+ });
+ }
+
+ private static ActiveOperationalDataset createRandomizedDatasetInternal(
+ String networkName,
+ int supportedChannelMask,
+ Instant now,
+ Random random,
+ SecureRandom secureRandom) {
+ int panId = random.nextInt(/* bound= */ 0xffff);
+ final byte[] meshLocalPrefix = newRandomBytes(random, LENGTH_MESH_LOCAL_PREFIX_BITS / 8);
+ meshLocalPrefix[0] = MESH_LOCAL_PREFIX_FIRST_BYTE;
+
+ final SparseArray<byte[]> channelMask = new SparseArray<>(1);
+ channelMask.put(CHANNEL_PAGE_24_GHZ, channelMaskToByteArray(supportedChannelMask));
+
+ final byte[] securityFlags = new byte[] {(byte) 0xff, (byte) 0xf8};
+
+ return new ActiveOperationalDataset.Builder()
+ .setActiveTimestamp(
+ new OperationalDatasetTimestamp(
+ now.getEpochSecond() & 0xffffffffffffL, 0, false))
+ .setExtendedPanId(newRandomBytes(random, LENGTH_EXTENDED_PAN_ID))
+ .setPanId(panId)
+ .setNetworkName(networkName)
+ .setChannel(CHANNEL_PAGE_24_GHZ, selectRandomChannel(supportedChannelMask, random))
+ .setChannelMask(channelMask)
+ .setPskc(newRandomBytes(secureRandom, LENGTH_PSKC))
+ .setNetworkKey(newRandomBytes(secureRandom, LENGTH_NETWORK_KEY))
+ .setMeshLocalPrefix(meshLocalPrefix)
+ .setSecurityPolicy(new SecurityPolicy(DEFAULT_ROTATION_TIME_HOURS, securityFlags))
+ .build();
+ }
+
+ private static byte[] newRandomBytes(Random random, int length) {
+ byte[] result = new byte[length];
+ random.nextBytes(result);
+ return result;
+ }
+
+ private static byte[] channelMaskToByteArray(int channelMask) {
+ // Per Thread spec, a Channel Mask is:
+ // A variable-length bit mask that identifies the channels within the channel page
+ // (1 = selected, 0 = unselected). The channels are represented in most significant bit
+ // order. For example, the most significant bit of the left-most byte indicates channel 0.
+ // If channel 0 and channel 10 are selected, the mask would be: 80 20 00 00. For IEEE
+ // 802.15.4-2006 2.4 GHz PHY, the ChannelMask is 27 bits and MaskLength is 4.
+ //
+ // The pass-in channelMask represents a channel K by (channelMask & (1 << K)), so here
+ // needs to do bit-wise reverse to convert it to the Thread spec format in bytes.
+ channelMask = Integer.reverse(channelMask);
+ return new byte[] {
+ (byte) (channelMask >>> 24),
+ (byte) (channelMask >>> 16),
+ (byte) (channelMask >>> 8),
+ (byte) channelMask
+ };
+ }
+
+ private static int selectRandomChannel(int supportedChannelMask, Random random) {
+ int num = random.nextInt(Integer.bitCount(supportedChannelMask));
+ for (int i = 0; i < 32; i++) {
+ if ((supportedChannelMask & 1) == 1 && (num--) == 0) {
+ return i;
+ }
+ supportedChannelMask >>>= 1;
+ }
+ return -1;
+ }
+
+ private void enforceAllCallingPermissionsGranted(String... permissions) {
+ for (String permission : permissions) {
+ mContext.enforceCallingPermission(
+ permission, "Permission " + permission + " is missing");
+ }
+ }
+
+ @Override
+ public void registerStateCallback(IStateCallback stateCallback) throws RemoteException {
+ enforceAllCallingPermissionsGranted(permission.ACCESS_NETWORK_STATE);
+
+ mHandler.post(() -> mOtDaemonCallbackProxy.registerStateCallback(stateCallback));
+ }
+
+ @Override
+ public void unregisterStateCallback(IStateCallback stateCallback) throws RemoteException {
+ mHandler.post(() -> mOtDaemonCallbackProxy.unregisterStateCallback(stateCallback));
+ }
+
+ @Override
+ public void registerOperationalDatasetCallback(IOperationalDatasetCallback callback)
+ throws RemoteException {
+ enforceAllCallingPermissionsGranted(
+ permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+ mHandler.post(() -> mOtDaemonCallbackProxy.registerDatasetCallback(callback));
+ }
+
+ @Override
+ public void unregisterOperationalDatasetCallback(IOperationalDatasetCallback callback)
+ throws RemoteException {
+ mHandler.post(() -> mOtDaemonCallbackProxy.unregisterDatasetCallback(callback));
+ }
+
+ private void checkOnHandlerThread() {
+ if (Looper.myLooper() != mHandlerThread.getLooper()) {
+ Log.wtf(TAG, "Must be on the handler thread!");
+ }
+ }
+
+ private IOtStatusReceiver newOtStatusReceiver(OperationReceiverWrapper receiver) {
+ return new IOtStatusReceiver.Stub() {
+ @Override
+ public void onSuccess() {
+ receiver.onSuccess();
+ }
+
+ @Override
+ public void onError(int otError, String message) {
+ receiver.onError(otErrorToAndroidError(otError), message);
+ }
+ };
+ }
+
+ @ErrorCode
+ private static int otErrorToAndroidError(int otError) {
+ // See external/openthread/include/openthread/error.h for OT error definition
+ switch (otError) {
+ case OT_ERROR_ABORT:
+ return ERROR_ABORTED;
+ case OT_ERROR_BUSY:
+ return ERROR_BUSY;
+ case OT_ERROR_DETACHED:
+ case OT_ERROR_INVALID_STATE:
+ return ERROR_FAILED_PRECONDITION;
+ case OT_ERROR_NO_BUFS:
+ return ERROR_RESOURCE_EXHAUSTED;
+ case OT_ERROR_PARSE:
+ return ERROR_RESPONSE_BAD_FORMAT;
+ case OT_ERROR_REASSEMBLY_TIMEOUT:
+ case OT_ERROR_RESPONSE_TIMEOUT:
+ return ERROR_TIMEOUT;
+ case OT_ERROR_REJECTED:
+ return ERROR_REJECTED_BY_PEER;
+ case OT_ERROR_UNSUPPORTED_CHANNEL:
+ return ERROR_UNSUPPORTED_CHANNEL;
+ default:
+ return ERROR_INTERNAL_ERROR;
+ }
+ }
+
+ @Override
+ public void join(
+ @NonNull ActiveOperationalDataset activeDataset, @NonNull IOperationReceiver receiver) {
+ enforceAllCallingPermissionsGranted(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ OperationReceiverWrapper receiverWrapper = new OperationReceiverWrapper(receiver);
+ mHandler.post(() -> joinInternal(activeDataset, receiverWrapper));
+ }
+
+ private void joinInternal(
+ @NonNull ActiveOperationalDataset activeDataset,
+ @NonNull OperationReceiverWrapper receiver) {
+ checkOnHandlerThread();
+
+ try {
+ // The otDaemon.join() will leave first if this device is currently attached
+ getOtDaemon().join(activeDataset.toThreadTlvs(), newOtStatusReceiver(receiver));
+ } catch (RemoteException e) {
+ Log.e(TAG, "otDaemon.join failed", e);
+ receiver.onError(ERROR_INTERNAL_ERROR, "Thread stack error");
+ }
+ }
+
+ @Override
+ public void scheduleMigration(
+ @NonNull PendingOperationalDataset pendingDataset,
+ @NonNull IOperationReceiver receiver) {
+ enforceAllCallingPermissionsGranted(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ OperationReceiverWrapper receiverWrapper = new OperationReceiverWrapper(receiver);
+ mHandler.post(() -> scheduleMigrationInternal(pendingDataset, receiverWrapper));
+ }
+
+ public void scheduleMigrationInternal(
+ @NonNull PendingOperationalDataset pendingDataset,
+ @NonNull OperationReceiverWrapper receiver) {
+ checkOnHandlerThread();
+
+ try {
+ getOtDaemon()
+ .scheduleMigration(
+ pendingDataset.toThreadTlvs(), newOtStatusReceiver(receiver));
+ } catch (RemoteException e) {
+ Log.e(TAG, "otDaemon.scheduleMigration failed", e);
+ receiver.onError(ERROR_INTERNAL_ERROR, "Thread stack error");
+ }
+ }
+
+ @Override
+ public void leave(@NonNull IOperationReceiver receiver) throws RemoteException {
+ enforceAllCallingPermissionsGranted(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ mHandler.post(() -> leaveInternal(new OperationReceiverWrapper(receiver)));
+ }
+
+ private void leaveInternal(@NonNull OperationReceiverWrapper receiver) {
+ checkOnHandlerThread();
+
+ try {
+ getOtDaemon().leave(newOtStatusReceiver(receiver));
+ } catch (RemoteException e) {
+ // Oneway AIDL API should never throw?
+ receiver.onError(ERROR_INTERNAL_ERROR, "Thread stack error");
+ }
+ }
+
+ private void handleThreadInterfaceStateChanged(boolean isUp) {
+ try {
+ mTunIfController.setInterfaceUp(isUp);
+ Log.d(TAG, "Thread network interface becomes " + (isUp ? "up" : "down"));
+ } catch (IOException e) {
+ Log.e(TAG, "Failed to handle Thread interface state changes", e);
+ }
+ }
+
+ private void handleDeviceRoleChanged(@DeviceRole int deviceRole) {
+ if (ThreadNetworkController.isAttached(deviceRole)) {
+ Log.d(TAG, "Attached to the Thread network");
+ registerThreadNetwork();
+ } else {
+ Log.d(TAG, "Detached from the Thread network");
+ unregisterThreadNetwork();
+ }
+ }
+
+ private void handleAddressChanged(Ipv6AddressInfo addressInfo, boolean isAdded) {
+ checkOnHandlerThread();
+ InetAddress address = addressInfoToInetAddress(addressInfo);
+ if (address.isMulticastAddress()) {
+ Log.i(TAG, "Ignoring multicast address " + address.getHostAddress());
+ return;
+ }
+
+ LinkAddress linkAddress = newLinkAddress(addressInfo);
+ Log.d(TAG, (isAdded ? "Adding" : "Removing") + " address " + linkAddress);
+
+ updateTunInterfaceAddress(linkAddress, isAdded);
+ updateNetworkLinkProperties(linkAddress, isAdded);
+ }
+
+ private static final class CallbackMetadata {
+ private static long gId = 0;
+
+ // The unique ID
+ final long id;
+
+ final IBinder.DeathRecipient deathRecipient;
+
+ CallbackMetadata(IBinder.DeathRecipient deathRecipient) {
+ this.id = allocId();
+ this.deathRecipient = deathRecipient;
+ }
+
+ private static long allocId() {
+ if (gId == Long.MAX_VALUE) {
+ gId = 0;
+ }
+ return gId++;
+ }
+ }
+
+ /**
+ * Handles and forwards Thread daemon callbacks. This class must be accessed from the {@code
+ * mHandlerThread}.
+ */
+ private final class OtDaemonCallbackProxy extends IOtDaemonCallback.Stub {
+ private final Map<IStateCallback, CallbackMetadata> mStateCallbacks = new HashMap<>();
+ private final Map<IOperationalDatasetCallback, CallbackMetadata> mOpDatasetCallbacks =
+ new HashMap<>();
+
+ private OtDaemonState mState;
+ private ActiveOperationalDataset mActiveDataset;
+ private PendingOperationalDataset mPendingDataset;
+
+ public void registerStateCallback(IStateCallback callback) {
+ checkOnHandlerThread();
+ if (mStateCallbacks.containsKey(callback)) {
+ return;
+ }
+
+ IBinder.DeathRecipient deathRecipient =
+ () -> mHandler.post(() -> unregisterStateCallback(callback));
+ CallbackMetadata callbackMetadata = new CallbackMetadata(deathRecipient);
+ mStateCallbacks.put(callback, callbackMetadata);
+ try {
+ callback.asBinder().linkToDeath(deathRecipient, 0);
+ } catch (RemoteException e) {
+ mStateCallbacks.remove(callback);
+ // This is thrown when the client is dead, do nothing
+ }
+
+ try {
+ getOtDaemon().registerStateCallback(this, callbackMetadata.id);
+ } catch (RemoteException e) {
+ // oneway operation should never fail
+ }
+ }
+
+ public void unregisterStateCallback(IStateCallback callback) {
+ checkOnHandlerThread();
+ if (!mStateCallbacks.containsKey(callback)) {
+ return;
+ }
+ callback.asBinder().unlinkToDeath(mStateCallbacks.remove(callback).deathRecipient, 0);
+ }
+
+ public void registerDatasetCallback(IOperationalDatasetCallback callback) {
+ checkOnHandlerThread();
+ if (mOpDatasetCallbacks.containsKey(callback)) {
+ return;
+ }
+
+ IBinder.DeathRecipient deathRecipient =
+ () -> mHandler.post(() -> unregisterDatasetCallback(callback));
+ CallbackMetadata callbackMetadata = new CallbackMetadata(deathRecipient);
+ mOpDatasetCallbacks.put(callback, callbackMetadata);
+ try {
+ callback.asBinder().linkToDeath(deathRecipient, 0);
+ } catch (RemoteException e) {
+ mOpDatasetCallbacks.remove(callback);
+ }
+
+ try {
+ getOtDaemon().registerStateCallback(this, callbackMetadata.id);
+ } catch (RemoteException e) {
+ // oneway operation should never fail
+ }
+ }
+
+ public void unregisterDatasetCallback(IOperationalDatasetCallback callback) {
+ checkOnHandlerThread();
+ if (!mOpDatasetCallbacks.containsKey(callback)) {
+ return;
+ }
+ callback.asBinder()
+ .unlinkToDeath(mOpDatasetCallbacks.remove(callback).deathRecipient, 0);
+ }
+
+ public void onOtDaemonDied() {
+ checkOnHandlerThread();
+ if (mState == null) {
+ return;
+ }
+
+ // If this device is already STOPPED or DETACHED, do nothing
+ if (!ThreadNetworkController.isAttached(mState.deviceRole)) {
+ return;
+ }
+
+ // The Thread device role is considered DETACHED when the OT daemon process is dead
+ handleDeviceRoleChanged(DEVICE_ROLE_DETACHED);
+ for (IStateCallback callback : mStateCallbacks.keySet()) {
+ try {
+ callback.onDeviceRoleChanged(DEVICE_ROLE_DETACHED);
+ } catch (RemoteException ignored) {
+ // do nothing if the client is dead
+ }
+ }
+ }
+
+ @Override
+ public void onStateChanged(OtDaemonState newState, long listenerId) {
+ mHandler.post(() -> onStateChangedInternal(newState, listenerId));
+ }
+
+ private void onStateChangedInternal(OtDaemonState newState, long listenerId) {
+ checkOnHandlerThread();
+ onInterfaceStateChanged(newState.isInterfaceUp);
+ onDeviceRoleChanged(newState.deviceRole, listenerId);
+ onPartitionIdChanged(newState.partitionId, listenerId);
+ mState = newState;
+
+ ActiveOperationalDataset newActiveDataset;
+ try {
+ if (newState.activeDatasetTlvs.length != 0) {
+ newActiveDataset =
+ ActiveOperationalDataset.fromThreadTlvs(newState.activeDatasetTlvs);
+ } else {
+ newActiveDataset = null;
+ }
+ onActiveOperationalDatasetChanged(newActiveDataset, listenerId);
+ mActiveDataset = newActiveDataset;
+ } catch (IllegalArgumentException e) {
+ // Is unlikely that OT will generate invalid Operational Dataset
+ Log.w(TAG, "Ignoring invalid Active Operational Dataset changes", e);
+ }
+
+ PendingOperationalDataset newPendingDataset;
+ try {
+ if (newState.pendingDatasetTlvs.length != 0) {
+ newPendingDataset =
+ PendingOperationalDataset.fromThreadTlvs(newState.pendingDatasetTlvs);
+ } else {
+ newPendingDataset = null;
+ }
+ onPendingOperationalDatasetChanged(newPendingDataset, listenerId);
+ mPendingDataset = newPendingDataset;
+ } catch (IllegalArgumentException e) {
+ Log.w(TAG, "Ignoring invalid Pending Operational Dataset changes", e);
+ }
+ }
+
+ private void onInterfaceStateChanged(boolean isUp) {
+ checkOnHandlerThread();
+ if (mState == null || mState.isInterfaceUp != isUp) {
+ handleThreadInterfaceStateChanged(isUp);
+ }
+ }
+
+ private void onDeviceRoleChanged(@DeviceRole int deviceRole, long listenerId) {
+ checkOnHandlerThread();
+ boolean hasChange = (mState == null || mState.deviceRole != deviceRole);
+ if (hasChange) {
+ handleDeviceRoleChanged(deviceRole);
+ }
+
+ for (var callbackEntry : mStateCallbacks.entrySet()) {
+ if (!hasChange && callbackEntry.getValue().id != listenerId) {
+ continue;
+ }
+ try {
+ callbackEntry.getKey().onDeviceRoleChanged(deviceRole);
+ } catch (RemoteException ignored) {
+ // do nothing if the client is dead
+ }
+ }
+ }
+
+ private void onPartitionIdChanged(long partitionId, long listenerId) {
+ checkOnHandlerThread();
+ boolean hasChange = (mState == null || mState.partitionId != partitionId);
+
+ for (var callbackEntry : mStateCallbacks.entrySet()) {
+ if (!hasChange && callbackEntry.getValue().id != listenerId) {
+ continue;
+ }
+ try {
+ callbackEntry.getKey().onPartitionIdChanged(partitionId);
+ } catch (RemoteException ignored) {
+ // do nothing if the client is dead
+ }
+ }
+ }
+
+ private void onActiveOperationalDatasetChanged(
+ ActiveOperationalDataset activeDataset, long listenerId) {
+ checkOnHandlerThread();
+ boolean hasChange = !Objects.equals(mActiveDataset, activeDataset);
+
+ for (var callbackEntry : mOpDatasetCallbacks.entrySet()) {
+ if (!hasChange && callbackEntry.getValue().id != listenerId) {
+ continue;
+ }
+ try {
+ callbackEntry.getKey().onActiveOperationalDatasetChanged(activeDataset);
+ } catch (RemoteException ignored) {
+ // do nothing if the client is dead
+ }
+ }
+ }
+
+ private void onPendingOperationalDatasetChanged(
+ PendingOperationalDataset pendingDataset, long listenerId) {
+ checkOnHandlerThread();
+ boolean hasChange = !Objects.equals(mPendingDataset, pendingDataset);
+ for (var callbackEntry : mOpDatasetCallbacks.entrySet()) {
+ if (!hasChange && callbackEntry.getValue().id != listenerId) {
+ continue;
+ }
+ try {
+ callbackEntry.getKey().onPendingOperationalDatasetChanged(pendingDataset);
+ } catch (RemoteException ignored) {
+ // do nothing if the client is dead
+ }
+ }
+ }
+
+ @Override
+ public void onAddressChanged(Ipv6AddressInfo addressInfo, boolean isAdded) {
+ mHandler.post(() -> handleAddressChanged(addressInfo, isAdded));
+ }
+ }
}
diff --git a/thread/service/java/com/android/server/thread/ThreadNetworkService.java b/thread/service/java/com/android/server/thread/ThreadNetworkService.java
index c6d47df..cc694a1 100644
--- a/thread/service/java/com/android/server/thread/ThreadNetworkService.java
+++ b/thread/service/java/com/android/server/thread/ThreadNetworkService.java
@@ -16,6 +16,7 @@
package com.android.server.thread;
+import android.annotation.Nullable;
import android.content.Context;
import android.net.thread.IThreadNetworkController;
import android.net.thread.IThreadNetworkManager;
@@ -29,16 +30,12 @@
* Implementation of the Thread network service. This is the entry point of Android Thread feature.
*/
public class ThreadNetworkService extends IThreadNetworkManager.Stub {
- private final ThreadNetworkControllerService mControllerService;
+ private final Context mContext;
+ @Nullable private ThreadNetworkControllerService mControllerService;
/** Creates a new {@link ThreadNetworkService} object. */
public ThreadNetworkService(Context context) {
- this(context, new ThreadNetworkControllerService());
- }
-
- private ThreadNetworkService(
- Context context, ThreadNetworkControllerService controllerService) {
- mControllerService = controllerService;
+ mContext = context;
}
/**
@@ -48,12 +45,16 @@
*/
public void onBootPhase(int phase) {
if (phase == SystemService.PHASE_BOOT_COMPLETED) {
- // TODO: initialize ThreadNetworkManagerService
+ mControllerService = ThreadNetworkControllerService.newInstance(mContext);
+ mControllerService.initialize();
}
}
@Override
public List<IThreadNetworkController> getAllThreadNetworkControllers() {
+ if (mControllerService == null) {
+ return Collections.emptyList();
+ }
return Collections.singletonList(mControllerService);
}
}
diff --git a/thread/service/java/com/android/server/thread/TunInterfaceController.java b/thread/service/java/com/android/server/thread/TunInterfaceController.java
new file mode 100644
index 0000000..ac65b11
--- /dev/null
+++ b/thread/service/java/com/android/server/thread/TunInterfaceController.java
@@ -0,0 +1,140 @@
+/*
+ * 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 com.android.server.thread;
+
+import android.net.LinkAddress;
+import android.net.util.SocketUtils;
+import android.os.ParcelFileDescriptor;
+import android.os.SystemClock;
+import android.system.ErrnoException;
+import android.system.Os;
+import android.system.OsConstants;
+import android.util.Log;
+
+import com.android.net.module.util.netlink.NetlinkUtils;
+import com.android.net.module.util.netlink.RtNetlinkAddressMessage;
+
+import java.io.FileDescriptor;
+import java.io.IOException;
+
+/** Controller for virtual/tunnel network interfaces. */
+public class TunInterfaceController {
+ private static final String TAG = "TunIfController";
+ static final int MTU = 1280;
+
+ static {
+ System.loadLibrary("service-thread-jni");
+ }
+
+ private final String mIfName;
+ private ParcelFileDescriptor mParcelTunFd;
+ private FileDescriptor mNetlinkSocket;
+ private static int sNetlinkSeqNo = 0;
+
+ /** Creates a new {@link TunInterfaceController} instance for given interface. */
+ public TunInterfaceController(String interfaceName) {
+ this.mIfName = interfaceName;
+ }
+
+ /**
+ * Creates the tunnel interface.
+ *
+ * @throws IOException if failed to create the interface
+ */
+ public void createTunInterface() throws IOException {
+ mParcelTunFd = ParcelFileDescriptor.adoptFd(nativeCreateTunInterface(mIfName, MTU));
+ try {
+ mNetlinkSocket = NetlinkUtils.netlinkSocketForProto(OsConstants.NETLINK_ROUTE);
+ } catch (ErrnoException e) {
+ throw new IOException("Failed to create netlink socket", e);
+ }
+ }
+
+ public void destroyTunInterface() {
+ try {
+ mParcelTunFd.close();
+ SocketUtils.closeSocket(mNetlinkSocket);
+ } catch (IOException e) {
+ // Should never fail
+ }
+ mParcelTunFd = null;
+ mNetlinkSocket = null;
+ }
+
+ /** Returns the FD of the tunnel interface. */
+ public ParcelFileDescriptor getTunFd() {
+ return mParcelTunFd;
+ }
+
+ private native int nativeCreateTunInterface(String interfaceName, int mtu) throws IOException;
+
+ /** Sets the interface up or down according to {@code isUp}. */
+ public void setInterfaceUp(boolean isUp) throws IOException {
+ nativeSetInterfaceUp(mIfName, isUp);
+ }
+
+ private native void nativeSetInterfaceUp(String interfaceName, boolean isUp) throws IOException;
+
+ /** Adds a new address to the interface. */
+ public void addAddress(LinkAddress address) throws IOException {
+ Log.d(TAG, "Adding address " + address + " with flags: " + address.getFlags());
+
+ long validLifetimeSeconds;
+ long preferredLifetimeSeconds;
+
+ if (address.getDeprecationTime() == LinkAddress.LIFETIME_PERMANENT
+ || address.getDeprecationTime() == LinkAddress.LIFETIME_UNKNOWN) {
+ validLifetimeSeconds = 0xffffffffL;
+ } else {
+ validLifetimeSeconds =
+ Math.max(
+ (address.getDeprecationTime() - SystemClock.elapsedRealtime()) / 1000L,
+ 0L);
+ }
+
+ if (address.getExpirationTime() == LinkAddress.LIFETIME_PERMANENT
+ || address.getExpirationTime() == LinkAddress.LIFETIME_UNKNOWN) {
+ preferredLifetimeSeconds = 0xffffffffL;
+ } else {
+ preferredLifetimeSeconds =
+ Math.max(
+ (address.getExpirationTime() - SystemClock.elapsedRealtime()) / 1000L,
+ 0L);
+ }
+
+ byte[] message =
+ RtNetlinkAddressMessage.newRtmNewAddressMessage(
+ sNetlinkSeqNo,
+ address.getAddress(),
+ (short) address.getPrefixLength(),
+ address.getFlags(),
+ (byte) address.getScope(),
+ Os.if_nametoindex(mIfName),
+ validLifetimeSeconds,
+ preferredLifetimeSeconds);
+ try {
+ Os.write(mNetlinkSocket, message, 0, message.length);
+ } catch (ErrnoException e) {
+ throw new IOException("Failed to send netlink message", e);
+ }
+ }
+
+ /** Removes an address from the interface. */
+ public void removeAddress(LinkAddress address) throws IOException {
+ // TODO(b/263222068): remove address with netlink
+ }
+}
diff --git a/thread/service/jni/com_android_server_thread_TunInterfaceController.cpp b/thread/service/jni/com_android_server_thread_TunInterfaceController.cpp
new file mode 100644
index 0000000..ed39fab
--- /dev/null
+++ b/thread/service/jni/com_android_server_thread_TunInterfaceController.cpp
@@ -0,0 +1,124 @@
+/*
+ * 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.
+ */
+
+#define LOG_TAG "jniThreadTun"
+
+#include <arpa/inet.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <inttypes.h>
+#include <linux/if_arp.h>
+#include <linux/if_tun.h>
+#include <linux/ioctl.h>
+#include <log/log.h>
+#include <net/if.h>
+#include <spawn.h>
+#include <sys/wait.h>
+#include <string>
+
+#include <private/android_filesystem_config.h>
+
+#include "jni.h"
+#include "nativehelper/JNIHelp.h"
+#include "nativehelper/scoped_utf_chars.h"
+
+namespace android {
+static jint com_android_server_thread_TunInterfaceController_createTunInterface(
+ JNIEnv* env, jobject clazz, jstring interfaceName, jint mtu) {
+ ScopedUtfChars ifName(env, interfaceName);
+
+ int fd = open("/dev/net/tun", O_RDWR | O_NONBLOCK | O_CLOEXEC);
+ if (fd == -1) {
+ jniThrowExceptionFmt(env, "java/io/IOException", "open tun device failed (%s)",
+ strerror(errno));
+ return -1;
+ }
+
+ struct ifreq ifr = {
+ .ifr_flags = IFF_TUN | IFF_NO_PI | static_cast<short>(IFF_TUN_EXCL),
+ };
+ strlcpy(ifr.ifr_name, ifName.c_str(), sizeof(ifr.ifr_name));
+
+ if (ioctl(fd, TUNSETIFF, &ifr, sizeof(ifr)) != 0) {
+ close(fd);
+ jniThrowExceptionFmt(env, "java/io/IOException", "ioctl(TUNSETIFF) failed (%s)",
+ strerror(errno));
+ return -1;
+ }
+
+ int inet6 = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, IPPROTO_IP);
+ if (inet6 == -1) {
+ close(fd);
+ jniThrowExceptionFmt(env, "java/io/IOException", "create inet6 socket failed (%s)",
+ strerror(errno));
+ return -1;
+ }
+ ifr.ifr_mtu = mtu;
+ if (ioctl(inet6, SIOCSIFMTU, &ifr) != 0) {
+ close(fd);
+ close(inet6);
+ jniThrowExceptionFmt(env, "java/io/IOException", "ioctl(SIOCSIFMTU) failed (%s)",
+ strerror(errno));
+ return -1;
+ }
+
+ close(inet6);
+ return fd;
+}
+
+static void com_android_server_thread_TunInterfaceController_setInterfaceUp(
+ JNIEnv* env, jobject clazz, jstring interfaceName, jboolean isUp) {
+ struct ifreq ifr;
+ ScopedUtfChars ifName(env, interfaceName);
+
+ ifr.ifr_flags = isUp ? IFF_UP : 0;
+ strlcpy(ifr.ifr_name, ifName.c_str(), sizeof(ifr.ifr_name));
+
+ int inet6 = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, IPPROTO_IP);
+ if (inet6 == -1) {
+ jniThrowExceptionFmt(env, "java/io/IOException", "create inet6 socket failed (%s)",
+ strerror(errno));
+ }
+
+ if (ioctl(inet6, SIOCSIFFLAGS, &ifr) != 0) {
+ close(inet6);
+ jniThrowExceptionFmt(env, "java/io/IOException", "ioctl(SIOCSIFFLAGS) failed (%s)",
+ strerror(errno));
+ }
+
+ close(inet6);
+}
+
+/*
+ * JNI registration.
+ */
+
+static const JNINativeMethod gMethods[] = {
+ /* name, signature, funcPtr */
+ {"nativeCreateTunInterface",
+ "(Ljava/lang/String;I)I",
+ (void*)com_android_server_thread_TunInterfaceController_createTunInterface},
+ {"nativeSetInterfaceUp",
+ "(Ljava/lang/String;Z)V",
+ (void*)com_android_server_thread_TunInterfaceController_setInterfaceUp},
+};
+
+int register_com_android_server_thread_TunInterfaceController(JNIEnv* env) {
+ return jniRegisterNativeMethods(env, "com/android/server/thread/TunInterfaceController",
+ gMethods, NELEM(gMethods));
+}
+
+}; // namespace android
diff --git a/thread/service/jni/onload.cpp b/thread/service/jni/onload.cpp
new file mode 100644
index 0000000..5081664
--- /dev/null
+++ b/thread/service/jni/onload.cpp
@@ -0,0 +1,37 @@
+/*
+ * 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.
+ */
+
+#include "jni.h"
+#include "utils/Log.h"
+
+namespace android {
+int register_com_android_server_thread_TunInterfaceController(JNIEnv* env);
+}
+
+using namespace android;
+
+extern "C" jint JNI_OnLoad(JavaVM* vm, void* /* reserved */) {
+ JNIEnv* env = NULL;
+
+ if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
+ ALOGE("GetEnv failed!");
+ return -1;
+ }
+ ALOG_ASSERT(env != NULL, "Could not retrieve the env!");
+
+ register_com_android_server_thread_TunInterfaceController(env);
+ return JNI_VERSION_1_4;
+}
diff --git a/thread/tests/cts/src/android/net/thread/cts/ActiveOperationalDatasetTest.java b/thread/tests/cts/src/android/net/thread/cts/ActiveOperationalDatasetTest.java
index 39df21b..0e76930 100644
--- a/thread/tests/cts/src/android/net/thread/cts/ActiveOperationalDatasetTest.java
+++ b/thread/tests/cts/src/android/net/thread/cts/ActiveOperationalDatasetTest.java
@@ -70,7 +70,7 @@
// PAN ID: 0xD9A0
// PSKc: A245479C836D551B9CA557F7B9D351B4
// Security Policy: 672 onrcb
- private static final byte[] VALID_DATASET =
+ private static final byte[] VALID_DATASET_TLVS =
base16().decode(
"0E080000000000010000000300001335060004001FFFE002"
+ "08ACC214689BC40BDF0708FD64DB1225F47E0B0510F26B31"
@@ -78,6 +78,9 @@
+ "642D643961300102D9A00410A245479C836D551B9CA557F7"
+ "B9D351B40C0402A0FFF8");
+ private static final ActiveOperationalDataset DEFAULT_DATASET =
+ ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET_TLVS);
+
private static byte[] removeTlv(byte[] dataset, int type) {
ByteArrayOutputStream os = new ByteArrayOutputStream(dataset.length);
int i = 0;
@@ -105,7 +108,8 @@
@Test
public void parcelable_parcelingIsLossLess() {
- ActiveOperationalDataset dataset = ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET);
+ ActiveOperationalDataset dataset =
+ ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET_TLVS);
assertParcelingIsLossless(dataset);
}
@@ -126,7 +130,8 @@
@Test
public void fromThreadTlvs_invalidNetworkKeyTlv_throwsIllegalArgument() {
- byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_NETWORK_KEY, "05080000000000000000");
+ byte[] invalidTlv =
+ replaceTlv(VALID_DATASET_TLVS, TYPE_NETWORK_KEY, "05080000000000000000");
assertThrows(
IllegalArgumentException.class,
@@ -135,7 +140,7 @@
@Test
public void fromThreadTlvs_noNetworkKeyTlv_throwsIllegalArgument() {
- byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_NETWORK_KEY);
+ byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_NETWORK_KEY);
assertThrows(
IllegalArgumentException.class,
@@ -144,7 +149,8 @@
@Test
public void fromThreadTlvs_invalidActiveTimestampTlv_throwsIllegalArgument() {
- byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_ACTIVE_TIMESTAMP, "0E0700000000010000");
+ byte[] invalidTlv =
+ replaceTlv(VALID_DATASET_TLVS, TYPE_ACTIVE_TIMESTAMP, "0E0700000000010000");
assertThrows(
IllegalArgumentException.class,
@@ -153,7 +159,7 @@
@Test
public void fromThreadTlvs_noActiveTimestampTlv_throwsIllegalArgument() {
- byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_ACTIVE_TIMESTAMP);
+ byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_ACTIVE_TIMESTAMP);
assertThrows(
IllegalArgumentException.class,
@@ -162,7 +168,7 @@
@Test
public void fromThreadTlvs_invalidNetworkNameTlv_emptyName_throwsIllegalArgument() {
- byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_NETWORK_NAME, "0300");
+ byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_NETWORK_NAME, "0300");
assertThrows(
IllegalArgumentException.class,
@@ -173,7 +179,9 @@
public void fromThreadTlvs_invalidNetworkNameTlv_tooLongName_throwsIllegalArgument() {
byte[] invalidTlv =
replaceTlv(
- VALID_DATASET, TYPE_NETWORK_NAME, "03114142434445464748494A4B4C4D4E4F5051");
+ VALID_DATASET_TLVS,
+ TYPE_NETWORK_NAME,
+ "03114142434445464748494A4B4C4D4E4F5051");
assertThrows(
IllegalArgumentException.class,
@@ -182,7 +190,7 @@
@Test
public void fromThreadTlvs_noNetworkNameTlv_throwsIllegalArgument() {
- byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_NETWORK_NAME);
+ byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_NETWORK_NAME);
assertThrows(
IllegalArgumentException.class,
@@ -191,7 +199,7 @@
@Test
public void fromThreadTlvs_invalidChannelTlv_channelMissing_throwsIllegalArgument() {
- byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_CHANNEL, "000100");
+ byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL, "000100");
assertThrows(
IllegalArgumentException.class,
@@ -200,7 +208,7 @@
@Test
public void fromThreadTlvs_undefinedChannelPage_success() {
- byte[] datasetTlv = replaceTlv(VALID_DATASET, TYPE_CHANNEL, "0003010020");
+ byte[] datasetTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL, "0003010020");
ActiveOperationalDataset dataset = ActiveOperationalDataset.fromThreadTlvs(datasetTlv);
@@ -210,8 +218,8 @@
@Test
public void fromThreadTlvs_invalid2P4GhzChannel_throwsIllegalArgument() {
- byte[] invalidTlv1 = replaceTlv(VALID_DATASET, TYPE_CHANNEL, "000300000A");
- byte[] invalidTlv2 = replaceTlv(VALID_DATASET, TYPE_CHANNEL, "000300001B");
+ byte[] invalidTlv1 = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL, "000300000A");
+ byte[] invalidTlv2 = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL, "000300001B");
assertThrows(
IllegalArgumentException.class,
@@ -223,7 +231,7 @@
@Test
public void fromThreadTlvs_valid2P4GhzChannelTlv_success() {
- byte[] validTlv = replaceTlv(VALID_DATASET, TYPE_CHANNEL, "0003000010");
+ byte[] validTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL, "0003000010");
ActiveOperationalDataset dataset = ActiveOperationalDataset.fromThreadTlvs(validTlv);
@@ -232,7 +240,7 @@
@Test
public void fromThreadTlvs_noChannelTlv_throwsIllegalArgument() {
- byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_CHANNEL);
+ byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_CHANNEL);
assertThrows(
IllegalArgumentException.class,
@@ -241,7 +249,7 @@
@Test
public void fromThreadTlvs_prematureEndOfChannelMaskEntry_throwsIllegalArgument() {
- byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_CHANNEL_MASK, "350100");
+ byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL_MASK, "350100");
assertThrows(
IllegalArgumentException.class,
@@ -250,7 +258,7 @@
@Test
public void fromThreadTlvs_inconsistentChannelMaskLength_throwsIllegalArgument() {
- byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_CHANNEL_MASK, "3506000500010000");
+ byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL_MASK, "3506000500010000");
assertThrows(
IllegalArgumentException.class,
@@ -261,7 +269,7 @@
public void fromThreadTlvs_unsupportedChannelMaskLength_success() {
ActiveOperationalDataset dataset =
ActiveOperationalDataset.fromThreadTlvs(
- replaceTlv(VALID_DATASET, TYPE_CHANNEL_MASK, "350700050001000000"));
+ replaceTlv(VALID_DATASET_TLVS, TYPE_CHANNEL_MASK, "350700050001000000"));
SparseArray<byte[]> channelMask = dataset.getChannelMask();
assertThat(channelMask.size()).isEqualTo(1);
@@ -271,7 +279,7 @@
@Test
public void fromThreadTlvs_noChannelMaskTlv_throwsIllegalArgument() {
- byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_CHANNEL_MASK);
+ byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_CHANNEL_MASK);
assertThrows(
IllegalArgumentException.class,
@@ -280,7 +288,7 @@
@Test
public void fromThreadTlvs_invalidPanIdTlv_throwsIllegalArgument() {
- byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_PAN_ID, "010101");
+ byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_PAN_ID, "010101");
assertThrows(
IllegalArgumentException.class,
@@ -289,7 +297,7 @@
@Test
public void fromThreadTlvs_noPanIdTlv_throwsIllegalArgument() {
- byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_PAN_ID);
+ byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_PAN_ID);
assertThrows(
IllegalArgumentException.class,
@@ -298,7 +306,8 @@
@Test
public void fromThreadTlvs_invalidExtendedPanIdTlv_throwsIllegalArgument() {
- byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_EXTENDED_PAN_ID, "020700010203040506");
+ byte[] invalidTlv =
+ replaceTlv(VALID_DATASET_TLVS, TYPE_EXTENDED_PAN_ID, "020700010203040506");
assertThrows(
IllegalArgumentException.class,
@@ -307,7 +316,7 @@
@Test
public void fromThreadTlvs_noExtendedPanIdTlv_throwsIllegalArgument() {
- byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_EXTENDED_PAN_ID);
+ byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_EXTENDED_PAN_ID);
assertThrows(
IllegalArgumentException.class,
@@ -317,7 +326,7 @@
@Test
public void fromThreadTlvs_invalidPskcTlv_throwsIllegalArgument() {
byte[] invalidTlv =
- replaceTlv(VALID_DATASET, TYPE_PSKC, "0411000102030405060708090A0B0C0D0E0F10");
+ replaceTlv(VALID_DATASET_TLVS, TYPE_PSKC, "0411000102030405060708090A0B0C0D0E0F10");
assertThrows(
IllegalArgumentException.class,
@@ -326,7 +335,7 @@
@Test
public void fromThreadTlvs_noPskcTlv_throwsIllegalArgument() {
- byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_PSKC);
+ byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_PSKC);
assertThrows(
IllegalArgumentException.class,
@@ -336,7 +345,7 @@
@Test
public void fromThreadTlvs_invalidMeshLocalPrefixTlv_throwsIllegalArgument() {
byte[] invalidTlv =
- replaceTlv(VALID_DATASET, TYPE_MESH_LOCAL_PREFIX, "0709FD0001020304050607");
+ replaceTlv(VALID_DATASET_TLVS, TYPE_MESH_LOCAL_PREFIX, "0709FD0001020304050607");
assertThrows(
IllegalArgumentException.class,
@@ -345,7 +354,7 @@
@Test
public void fromThreadTlvs_noMeshLocalPrefixTlv_throwsIllegalArgument() {
- byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_MESH_LOCAL_PREFIX);
+ byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_MESH_LOCAL_PREFIX);
assertThrows(
IllegalArgumentException.class,
@@ -354,7 +363,7 @@
@Test
public void fromThreadTlvs_tooShortSecurityPolicyTlv_throwsIllegalArgument() {
- byte[] invalidTlv = replaceTlv(VALID_DATASET, TYPE_SECURITY_POLICY, "0C0101");
+ byte[] invalidTlv = replaceTlv(VALID_DATASET_TLVS, TYPE_SECURITY_POLICY, "0C0101");
assertThrows(
IllegalArgumentException.class,
@@ -363,7 +372,7 @@
@Test
public void fromThreadTlvs_noSecurityPolicyTlv_throwsIllegalArgument() {
- byte[] invalidTlv = removeTlv(VALID_DATASET, TYPE_SECURITY_POLICY);
+ byte[] invalidTlv = removeTlv(VALID_DATASET_TLVS, TYPE_SECURITY_POLICY);
assertThrows(
IllegalArgumentException.class,
@@ -429,7 +438,7 @@
@Test
public void fromThreadTlvs_containsUnknownTlvs_unknownTlvsRetained() {
- final byte[] datasetWithUnknownTlvs = addTlv(VALID_DATASET, "AA01FFBB020102");
+ final byte[] datasetWithUnknownTlvs = addTlv(VALID_DATASET_TLVS, "AA01FFBB020102");
ActiveOperationalDataset dataset =
ActiveOperationalDataset.fromThreadTlvs(datasetWithUnknownTlvs);
@@ -443,7 +452,7 @@
@Test
public void toThreadTlvs_conversionIsLossLess() {
- ActiveOperationalDataset dataset1 = ActiveOperationalDataset.createRandomDataset();
+ ActiveOperationalDataset dataset1 = DEFAULT_DATASET;
ActiveOperationalDataset dataset2 =
ActiveOperationalDataset.fromThreadTlvs(dataset1.toThreadTlvs());
@@ -465,9 +474,7 @@
};
ActiveOperationalDataset dataset =
- new Builder(ActiveOperationalDataset.createRandomDataset())
- .setNetworkKey(networkKey)
- .build();
+ new Builder(DEFAULT_DATASET).setNetworkKey(networkKey).build();
assertThat(dataset.getNetworkKey()).isEqualTo(networkKey);
}
@@ -475,7 +482,7 @@
@Test
public void builder_setInvalidNetworkKey_throwsIllegalArgument() {
byte[] invalidNetworkKey = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder();
assertThrows(
IllegalArgumentException.class, () -> builder.setNetworkKey(invalidNetworkKey));
@@ -486,9 +493,7 @@
byte[] extendedPanId = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07};
ActiveOperationalDataset dataset =
- new Builder(ActiveOperationalDataset.createRandomDataset())
- .setExtendedPanId(extendedPanId)
- .build();
+ new Builder(DEFAULT_DATASET).setExtendedPanId(extendedPanId).build();
assertThat(dataset.getExtendedPanId()).isEqualTo(extendedPanId);
}
@@ -496,31 +501,28 @@
@Test
public void builder_setInvalidExtendedPanId_throwsIllegalArgument() {
byte[] extendedPanId = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder();
assertThrows(IllegalArgumentException.class, () -> builder.setExtendedPanId(extendedPanId));
}
@Test
public void builder_setValidPanId_success() {
- ActiveOperationalDataset dataset =
- new Builder(ActiveOperationalDataset.createRandomDataset())
- .setPanId(0xfffe)
- .build();
+ ActiveOperationalDataset dataset = new Builder(DEFAULT_DATASET).setPanId(0xfffe).build();
assertThat(dataset.getPanId()).isEqualTo(0xfffe);
}
@Test
public void builder_setInvalidPanId_throwsIllegalArgument() {
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder();
assertThrows(IllegalArgumentException.class, () -> builder.setPanId(0xffff));
}
@Test
public void builder_setInvalidChannel_throwsIllegalArgument() {
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder();
assertThrows(IllegalArgumentException.class, () -> builder.setChannel(0, 0));
assertThrows(IllegalArgumentException.class, () -> builder.setChannel(0, 27));
@@ -529,9 +531,7 @@
@Test
public void builder_setValid2P4GhzChannel_success() {
ActiveOperationalDataset dataset =
- new Builder(ActiveOperationalDataset.createRandomDataset())
- .setChannel(CHANNEL_PAGE_24_GHZ, 16)
- .build();
+ new Builder(DEFAULT_DATASET).setChannel(CHANNEL_PAGE_24_GHZ, 16).build();
assertThat(dataset.getChannel()).isEqualTo(16);
assertThat(dataset.getChannelPage()).isEqualTo(CHANNEL_PAGE_24_GHZ);
@@ -540,23 +540,21 @@
@Test
public void builder_setValidNetworkName_success() {
ActiveOperationalDataset dataset =
- new Builder(ActiveOperationalDataset.createRandomDataset())
- .setNetworkName("ot-network")
- .build();
+ new Builder(DEFAULT_DATASET).setNetworkName("ot-network").build();
assertThat(dataset.getNetworkName()).isEqualTo("ot-network");
}
@Test
public void builder_setEmptyNetworkName_throwsIllegalArgument() {
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder();
assertThrows(IllegalArgumentException.class, () -> builder.setNetworkName(""));
}
@Test
public void builder_setTooLongNetworkName_throwsIllegalArgument() {
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder();
assertThrows(
IllegalArgumentException.class, () -> builder.setNetworkName("openthread-network"));
@@ -564,7 +562,7 @@
@Test
public void builder_setTooLongUtf8NetworkName_throwsIllegalArgument() {
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder();
// UTF-8 encoded length of "我的线程网络" is 18 bytes which exceeds the max length
assertThrows(IllegalArgumentException.class, () -> builder.setNetworkName("我的线程网络"));
@@ -573,9 +571,7 @@
@Test
public void builder_setValidUtf8NetworkName_success() {
ActiveOperationalDataset dataset =
- new Builder(ActiveOperationalDataset.createRandomDataset())
- .setNetworkName("我的网络")
- .build();
+ new Builder(DEFAULT_DATASET).setNetworkName("我的网络").build();
assertThat(dataset.getNetworkName()).isEqualTo("我的网络");
}
@@ -584,8 +580,7 @@
public void builder_setValidPskc_success() {
byte[] pskc = base16().decode("A245479C836D551B9CA557F7B9D351B4");
- ActiveOperationalDataset dataset =
- new Builder(ActiveOperationalDataset.createRandomDataset()).setPskc(pskc).build();
+ ActiveOperationalDataset dataset = new Builder(DEFAULT_DATASET).setPskc(pskc).build();
assertThat(dataset.getPskc()).isEqualTo(pskc);
}
@@ -593,18 +588,18 @@
@Test
public void builder_setTooLongPskc_throwsIllegalArgument() {
byte[] tooLongPskc = base16().decode("A245479C836D551B9CA557F7B9D351B400");
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder();
assertThrows(IllegalArgumentException.class, () -> builder.setPskc(tooLongPskc));
}
@Test
public void builder_setValidChannelMask_success() {
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
SparseArray<byte[]> channelMask = new SparseArray<byte[]>(1);
channelMask.put(0, new byte[] {0x00, 0x00, 0x01, 0x00});
- ActiveOperationalDataset dataset = builder.setChannelMask(channelMask).build();
+ ActiveOperationalDataset dataset =
+ new Builder(DEFAULT_DATASET).setChannelMask(channelMask).build();
SparseArray<byte[]> resultChannelMask = dataset.getChannelMask();
assertThat(resultChannelMask.size()).isEqualTo(1);
@@ -613,7 +608,7 @@
@Test
public void builder_setEmptyChannelMask_throwsIllegalArgument() {
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder();
assertThrows(
IllegalArgumentException.class,
@@ -623,7 +618,7 @@
@Test
public void builder_setValidActiveTimestamp_success() {
ActiveOperationalDataset dataset =
- new Builder(ActiveOperationalDataset.createRandomDataset())
+ new Builder(DEFAULT_DATASET)
.setActiveTimestamp(
new OperationalDatasetTimestamp(
/* seconds= */ 1,
@@ -638,7 +633,7 @@
@Test
public void builder_wrongMeshLocalPrefixLength_throwsIllegalArguments() {
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder();
// The Mesh-Local Prefix length must be 64 bits
assertThrows(
@@ -656,7 +651,7 @@
@Test
public void builder_meshLocalPrefixNotStartWith0xfd_throwsIllegalArguments() {
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder();
assertThrows(
IllegalArgumentException.class,
@@ -666,9 +661,7 @@
@Test
public void builder_setValidMeshLocalPrefix_success() {
ActiveOperationalDataset dataset =
- new Builder(ActiveOperationalDataset.createRandomDataset())
- .setMeshLocalPrefix(new IpPrefix("fd00::/64"))
- .build();
+ new Builder(DEFAULT_DATASET).setMeshLocalPrefix(new IpPrefix("fd00::/64")).build();
assertThat(dataset.getMeshLocalPrefix()).isEqualTo(new IpPrefix("fd00::/64"));
}
@@ -676,7 +669,7 @@
@Test
public void builder_setValid1P2SecurityPolicy_success() {
ActiveOperationalDataset dataset =
- new Builder(ActiveOperationalDataset.createRandomDataset())
+ new Builder(DEFAULT_DATASET)
.setSecurityPolicy(
new SecurityPolicy(672, new byte[] {(byte) 0xff, (byte) 0xf8}))
.build();
@@ -689,7 +682,7 @@
@Test
public void builder_setValid1P1SecurityPolicy_success() {
ActiveOperationalDataset dataset =
- new Builder(ActiveOperationalDataset.createRandomDataset())
+ new Builder(DEFAULT_DATASET)
.setSecurityPolicy(new SecurityPolicy(672, new byte[] {(byte) 0xff}))
.build();
diff --git a/thread/tests/cts/src/android/net/thread/cts/PendingOperationalDatasetTest.java b/thread/tests/cts/src/android/net/thread/cts/PendingOperationalDatasetTest.java
index 7a49957..0bb18ce 100644
--- a/thread/tests/cts/src/android/net/thread/cts/PendingOperationalDatasetTest.java
+++ b/thread/tests/cts/src/android/net/thread/cts/PendingOperationalDatasetTest.java
@@ -25,8 +25,10 @@
import android.net.IpPrefix;
import android.net.thread.ActiveOperationalDataset;
+import android.net.thread.ActiveOperationalDataset.SecurityPolicy;
import android.net.thread.OperationalDatasetTimestamp;
import android.net.thread.PendingOperationalDataset;
+import android.util.SparseArray;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
@@ -37,20 +39,36 @@
import org.junit.Test;
import org.junit.runner.RunWith;
+import java.net.InetAddress;
import java.time.Duration;
/** Tests for {@link PendingOperationalDataset}. */
@SmallTest
@RunWith(AndroidJUnit4.class)
public final class PendingOperationalDatasetTest {
- private static final ActiveOperationalDataset DEFAULT_ACTIVE_DATASET =
- ActiveOperationalDataset.createRandomDataset();
+ private static ActiveOperationalDataset createActiveDataset() throws Exception {
+ SparseArray<byte[]> channelMask = new SparseArray<>(1);
+ channelMask.put(0, new byte[] {0x00, 0x1f, (byte) 0xff, (byte) 0xe0});
+
+ return new ActiveOperationalDataset.Builder()
+ .setActiveTimestamp(new OperationalDatasetTimestamp(100, 10, false))
+ .setExtendedPanId(new byte[] {0, 1, 2, 3, 4, 5, 6, 7})
+ .setPanId(12345)
+ .setNetworkName("defaultNet")
+ .setChannel(0, 18)
+ .setChannelMask(channelMask)
+ .setPskc(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15})
+ .setNetworkKey(new byte[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})
+ .setMeshLocalPrefix(new IpPrefix(InetAddress.getByName("fd00::1"), 64))
+ .setSecurityPolicy(new SecurityPolicy(672, new byte[] {(byte) 0xff, (byte) 0xf8}))
+ .build();
+ }
@Test
- public void parcelable_parcelingIsLossLess() {
+ public void parcelable_parcelingIsLossLess() throws Exception {
PendingOperationalDataset dataset =
new PendingOperationalDataset(
- DEFAULT_ACTIVE_DATASET,
+ createActiveDataset(),
new OperationalDatasetTimestamp(31536000, 200, false),
Duration.ofHours(100));
@@ -58,9 +76,15 @@
}
@Test
- public void equalityTests() {
- ActiveOperationalDataset activeDataset1 = ActiveOperationalDataset.createRandomDataset();
- ActiveOperationalDataset activeDataset2 = ActiveOperationalDataset.createRandomDataset();
+ public void equalityTests() throws Exception {
+ ActiveOperationalDataset activeDataset1 =
+ new ActiveOperationalDataset.Builder(createActiveDataset())
+ .setNetworkName("net1")
+ .build();
+ ActiveOperationalDataset activeDataset2 =
+ new ActiveOperationalDataset.Builder(createActiveDataset())
+ .setNetworkName("net2")
+ .build();
new EqualsTester()
.addEqualityGroup(
@@ -103,14 +127,15 @@
}
@Test
- public void constructor_correctValuesAreSet() {
+ public void constructor_correctValuesAreSet() throws Exception {
+ final ActiveOperationalDataset activeDataset = createActiveDataset();
PendingOperationalDataset dataset =
new PendingOperationalDataset(
- DEFAULT_ACTIVE_DATASET,
+ activeDataset,
new OperationalDatasetTimestamp(31536000, 200, false),
Duration.ofHours(100));
- assertThat(dataset.getActiveOperationalDataset()).isEqualTo(DEFAULT_ACTIVE_DATASET);
+ assertThat(dataset.getActiveOperationalDataset()).isEqualTo(activeDataset);
assertThat(dataset.getPendingTimestamp())
.isEqualTo(new OperationalDatasetTimestamp(31536000, 200, false));
assertThat(dataset.getDelayTimer()).isEqualTo(Duration.ofHours(100));
@@ -166,33 +191,35 @@
}
@Test
- public void fromThreadTlvs_completePendingDatasetTlvs_success() {
+ public void fromThreadTlvs_completePendingDatasetTlvs_success() throws Exception {
+ final ActiveOperationalDataset activeDataset = createActiveDataset();
+
// Type Length Value
// 0x33 0x08 0x0000000000010000 (Pending Timestamp TLV)
// 0x34 0x04 0x0000012C (Delay Timer TLV)
final byte[] pendingTimestampAndDelayTimerTlvs =
base16().decode("3308000000000001000034040000012C");
final byte[] pendingDatasetTlvs =
- Bytes.concat(
- pendingTimestampAndDelayTimerTlvs, DEFAULT_ACTIVE_DATASET.toThreadTlvs());
+ Bytes.concat(pendingTimestampAndDelayTimerTlvs, activeDataset.toThreadTlvs());
PendingOperationalDataset dataset =
PendingOperationalDataset.fromThreadTlvs(pendingDatasetTlvs);
- assertThat(dataset.getActiveOperationalDataset()).isEqualTo(DEFAULT_ACTIVE_DATASET);
+ assertThat(dataset.getActiveOperationalDataset()).isEqualTo(activeDataset);
assertThat(dataset.getPendingTimestamp())
.isEqualTo(new OperationalDatasetTimestamp(1, 0, false));
assertThat(dataset.getDelayTimer()).isEqualTo(Duration.ofMillis(300));
}
@Test
- public void fromThreadTlvs_PendingTimestampTlvIsMissing_throwsIllegalArgument() {
+ public void fromThreadTlvs_PendingTimestampTlvIsMissing_throwsIllegalArgument()
+ throws Exception {
// Type Length Value
// 0x34 0x04 0x00000064 (Delay Timer TLV)
final byte[] pendingTimestampAndDelayTimerTlvs = base16().decode("34040000012C");
final byte[] pendingDatasetTlvs =
Bytes.concat(
- pendingTimestampAndDelayTimerTlvs, DEFAULT_ACTIVE_DATASET.toThreadTlvs());
+ pendingTimestampAndDelayTimerTlvs, createActiveDataset().toThreadTlvs());
assertThrows(
IllegalArgumentException.class,
@@ -200,13 +227,13 @@
}
@Test
- public void fromThreadTlvs_delayTimerTlvIsMissing_throwsIllegalArgument() {
+ public void fromThreadTlvs_delayTimerTlvIsMissing_throwsIllegalArgument() throws Exception {
// Type Length Value
// 0x33 0x08 0x0000000000010000 (Pending Timestamp TLV)
final byte[] pendingTimestampAndDelayTimerTlvs = base16().decode("33080000000000010000");
final byte[] pendingDatasetTlvs =
Bytes.concat(
- pendingTimestampAndDelayTimerTlvs, DEFAULT_ACTIVE_DATASET.toThreadTlvs());
+ pendingTimestampAndDelayTimerTlvs, createActiveDataset().toThreadTlvs());
assertThrows(
IllegalArgumentException.class,
@@ -214,8 +241,8 @@
}
@Test
- public void fromThreadTlvs_activeDatasetTlvs_throwsIllegalArgument() {
- final byte[] activeDatasetTlvs = DEFAULT_ACTIVE_DATASET.toThreadTlvs();
+ public void fromThreadTlvs_activeDatasetTlvs_throwsIllegalArgument() throws Exception {
+ final byte[] activeDatasetTlvs = createActiveDataset().toThreadTlvs();
assertThrows(
IllegalArgumentException.class,
@@ -232,10 +259,10 @@
}
@Test
- public void toThreadTlvs_conversionIsLossLess() {
+ public void toThreadTlvs_conversionIsLossLess() throws Exception {
PendingOperationalDataset dataset1 =
new PendingOperationalDataset(
- DEFAULT_ACTIVE_DATASET,
+ createActiveDataset(),
new OperationalDatasetTimestamp(31536000, 200, false),
Duration.ofHours(100));
diff --git a/thread/tests/cts/src/android/net/thread/cts/ThreadNetworkControllerTest.java b/thread/tests/cts/src/android/net/thread/cts/ThreadNetworkControllerTest.java
index b3118f4..e17dd02 100644
--- a/thread/tests/cts/src/android/net/thread/cts/ThreadNetworkControllerTest.java
+++ b/thread/tests/cts/src/android/net/thread/cts/ThreadNetworkControllerTest.java
@@ -16,58 +16,612 @@
package android.net.thread.cts;
+import static android.net.thread.ThreadNetworkController.DEVICE_ROLE_STOPPED;
import static android.net.thread.ThreadNetworkController.THREAD_VERSION_1_3;
+import static android.net.thread.ThreadNetworkException.ERROR_ABORTED;
+import static android.net.thread.ThreadNetworkException.ERROR_FAILED_PRECONDITION;
+import static android.net.thread.ThreadNetworkException.ERROR_REJECTED_BY_PEER;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
+import static org.junit.Assert.assertThrows;
import static org.junit.Assume.assumeNotNull;
+import static java.util.concurrent.TimeUnit.MILLISECONDS;
+
+import android.Manifest.permission;
import android.content.Context;
+import android.net.thread.ActiveOperationalDataset;
+import android.net.thread.OperationalDatasetTimestamp;
+import android.net.thread.PendingOperationalDataset;
import android.net.thread.ThreadNetworkController;
+import android.net.thread.ThreadNetworkController.OperationalDatasetCallback;
+import android.net.thread.ThreadNetworkController.StateCallback;
+import android.net.thread.ThreadNetworkException;
import android.net.thread.ThreadNetworkManager;
import android.os.Build;
+import android.os.OutcomeReceiver;
import androidx.test.core.app.ApplicationProvider;
-import androidx.test.filters.SmallTest;
+import androidx.test.filters.LargeTest;
import com.android.testutils.DevSdkIgnoreRule;
import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
import com.android.testutils.DevSdkIgnoreRunner;
+import com.google.common.util.concurrent.SettableFuture;
+
+import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.HashSet;
import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
/** CTS tests for {@link ThreadNetworkController}. */
-@SmallTest
+@LargeTest
@RunWith(DevSdkIgnoreRunner.class)
@IgnoreUpTo(Build.VERSION_CODES.TIRAMISU) // Thread is available on only U+
public class ThreadNetworkControllerTest {
+ private static final int CALLBACK_TIMEOUT_MILLIS = 1000;
+ private static final String PERMISSION_THREAD_NETWORK_PRIVILEGED =
+ "android.permission.THREAD_NETWORK_PRIVILEGED";
+
@Rule public DevSdkIgnoreRule mIgnoreRule = new DevSdkIgnoreRule();
private final Context mContext = ApplicationProvider.getApplicationContext();
+ private ExecutorService mExecutor;
private ThreadNetworkManager mManager;
+ private Set<String> mGrantedPermissions;
+
@Before
public void setUp() {
+ mExecutor = Executors.newSingleThreadExecutor();
mManager = mContext.getSystemService(ThreadNetworkManager.class);
+ mGrantedPermissions = new HashSet<String>();
// TODO: we will also need it in tearDown(), it's better to have a Rule to skip
// tests if a feature is not available.
assumeNotNull(mManager);
}
+ @After
+ public void tearDown() throws Exception {
+ if (mManager != null) {
+ leaveAndWait();
+ dropPermissions();
+ }
+ }
+
private List<ThreadNetworkController> getAllControllers() {
return mManager.getAllThreadNetworkControllers();
}
+ private void leaveAndWait() throws Exception {
+ grantPermissions(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ SettableFuture<Void> future = SettableFuture.create();
+ controller.leave(mExecutor, future::set);
+ future.get();
+ }
+ }
+
+ private void grantPermissions(String... permissions) {
+ for (String permission : permissions) {
+ mGrantedPermissions.add(permission);
+ }
+ String[] allPermissions = new String[mGrantedPermissions.size()];
+ mGrantedPermissions.toArray(allPermissions);
+ getInstrumentation().getUiAutomation().adoptShellPermissionIdentity(allPermissions);
+ }
+
+ private static void dropPermissions() {
+ getInstrumentation().getUiAutomation().dropShellPermissionIdentity();
+ }
+
+ private static ActiveOperationalDataset newRandomizedDataset(
+ String networkName, ThreadNetworkController controller) throws Exception {
+ SettableFuture<ActiveOperationalDataset> future = SettableFuture.create();
+ controller.createRandomizedDataset(networkName, directExecutor(), future::set);
+ return future.get(CALLBACK_TIMEOUT_MILLIS, MILLISECONDS);
+ }
+
+ private static boolean isAttached(ThreadNetworkController controller) throws Exception {
+ return ThreadNetworkController.isAttached(getDeviceRole(controller));
+ }
+
+ private static int getDeviceRole(ThreadNetworkController controller) throws Exception {
+ SettableFuture<Integer> future = SettableFuture.create();
+ StateCallback callback = future::set;
+ controller.registerStateCallback(directExecutor(), callback);
+ int role = future.get(CALLBACK_TIMEOUT_MILLIS, MILLISECONDS);
+ controller.unregisterStateCallback(callback);
+ return role;
+ }
+
+ private static int waitForStateAnyOf(
+ ThreadNetworkController controller, List<Integer> deviceRoles) throws Exception {
+ SettableFuture<Integer> future = SettableFuture.create();
+ StateCallback callback =
+ newRole -> {
+ if (deviceRoles.contains(newRole)) {
+ future.set(newRole);
+ }
+ };
+ controller.registerStateCallback(directExecutor(), callback);
+ int role = future.get();
+ controller.unregisterStateCallback(callback);
+ return role;
+ }
+
+ private static ActiveOperationalDataset getActiveOperationalDataset(
+ ThreadNetworkController controller) throws Exception {
+ SettableFuture<ActiveOperationalDataset> future = SettableFuture.create();
+ OperationalDatasetCallback callback = future::set;
+ controller.registerOperationalDatasetCallback(directExecutor(), callback);
+ ActiveOperationalDataset dataset = future.get(CALLBACK_TIMEOUT_MILLIS, MILLISECONDS);
+ controller.unregisterOperationalDatasetCallback(callback);
+ return dataset;
+ }
+
+ private static PendingOperationalDataset getPendingOperationalDataset(
+ ThreadNetworkController controller) throws Exception {
+ SettableFuture<ActiveOperationalDataset> activeFuture = SettableFuture.create();
+ SettableFuture<PendingOperationalDataset> pendingFuture = SettableFuture.create();
+ controller.registerOperationalDatasetCallback(
+ directExecutor(), newDatasetCallback(activeFuture, pendingFuture));
+ return pendingFuture.get();
+ }
+
+ private static OperationalDatasetCallback newDatasetCallback(
+ SettableFuture<ActiveOperationalDataset> activeFuture,
+ SettableFuture<PendingOperationalDataset> pendingFuture) {
+ return new OperationalDatasetCallback() {
+ @Override
+ public void onActiveOperationalDatasetChanged(
+ ActiveOperationalDataset activeOpDataset) {
+ activeFuture.set(activeOpDataset);
+ }
+
+ @Override
+ public void onPendingOperationalDatasetChanged(
+ PendingOperationalDataset pendingOpDataset) {
+ pendingFuture.set(pendingOpDataset);
+ }
+ };
+ }
+
@Test
public void getThreadVersion_returnsAtLeastThreadVersion1P3() {
for (ThreadNetworkController controller : getAllControllers()) {
assertThat(controller.getThreadVersion()).isAtLeast(THREAD_VERSION_1_3);
}
}
+
+ @Test
+ public void registerStateCallback_permissionsGranted_returnsCurrentStates() throws Exception {
+ grantPermissions(permission.ACCESS_NETWORK_STATE);
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ SettableFuture<Integer> deviceRole = SettableFuture.create();
+
+ controller.registerStateCallback(mExecutor, role -> deviceRole.set(role));
+
+ assertThat(deviceRole.get()).isEqualTo(DEVICE_ROLE_STOPPED);
+ }
+ }
+
+ @Test
+ public void registerStateCallback_noPermissions_throwsSecurityException() throws Exception {
+ dropPermissions();
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ assertThrows(
+ SecurityException.class,
+ () -> controller.registerStateCallback(mExecutor, role -> {}));
+ }
+ }
+
+ @Test
+ public void registerStateCallback_alreadyRegistered_throwsIllegalArgumentException()
+ throws Exception {
+ grantPermissions(permission.ACCESS_NETWORK_STATE);
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ SettableFuture<Integer> deviceRole = SettableFuture.create();
+ StateCallback callback = role -> deviceRole.set(role);
+ controller.registerStateCallback(mExecutor, callback);
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> controller.registerStateCallback(mExecutor, callback));
+ }
+ }
+
+ @Test
+ public void unregisterStateCallback_callbackRegistered_success() throws Exception {
+ grantPermissions(permission.ACCESS_NETWORK_STATE);
+ for (ThreadNetworkController controller : getAllControllers()) {
+ SettableFuture<Integer> deviceRole = SettableFuture.create();
+ StateCallback callback = role -> deviceRole.set(role);
+ controller.registerStateCallback(mExecutor, callback);
+
+ controller.unregisterStateCallback(callback);
+ }
+ }
+
+ @Test
+ public void unregisterStateCallback_callbackNotRegistered_throwsIllegalArgumentException()
+ throws Exception {
+ for (ThreadNetworkController controller : getAllControllers()) {
+ SettableFuture<Integer> deviceRole = SettableFuture.create();
+ StateCallback callback = role -> deviceRole.set(role);
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> controller.unregisterStateCallback(callback));
+ }
+ }
+
+ @Test
+ public void unregisterStateCallback_alreadyUnregistered_throwsIllegalArgumentException()
+ throws Exception {
+ grantPermissions(permission.ACCESS_NETWORK_STATE);
+ for (ThreadNetworkController controller : getAllControllers()) {
+ SettableFuture<Integer> deviceRole = SettableFuture.create();
+ StateCallback callback = role -> deviceRole.set(role);
+ controller.registerStateCallback(mExecutor, callback);
+ controller.unregisterStateCallback(callback);
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> controller.unregisterStateCallback(callback));
+ }
+ }
+
+ @Test
+ public void registerOperationalDatasetCallback_permissionsGranted_returnsCurrentStates()
+ throws Exception {
+ grantPermissions(permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ SettableFuture<ActiveOperationalDataset> activeFuture = SettableFuture.create();
+ SettableFuture<PendingOperationalDataset> pendingFuture = SettableFuture.create();
+
+ controller.registerOperationalDatasetCallback(
+ mExecutor, newDatasetCallback(activeFuture, pendingFuture));
+
+ assertThat(activeFuture.get()).isNull();
+ assertThat(pendingFuture.get()).isNull();
+ }
+ }
+
+ private static <V> OutcomeReceiver<V, ThreadNetworkException> newOutcomeReceiver(
+ SettableFuture<V> future) {
+ return new OutcomeReceiver<V, ThreadNetworkException>() {
+ @Override
+ public void onResult(V result) {
+ future.set(result);
+ }
+
+ @Override
+ public void onError(ThreadNetworkException e) {
+ future.setException(e);
+ }
+ };
+ }
+
+ @Test
+ public void join_withPrivilegedPermission_success() throws Exception {
+ grantPermissions(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ ActiveOperationalDataset activeDataset = newRandomizedDataset("TestNet", controller);
+ SettableFuture<Void> joinFuture = SettableFuture.create();
+
+ controller.join(activeDataset, mExecutor, newOutcomeReceiver(joinFuture));
+ joinFuture.get();
+
+ grantPermissions(permission.ACCESS_NETWORK_STATE);
+ assertThat(isAttached(controller)).isTrue();
+ assertThat(getActiveOperationalDataset(controller)).isEqualTo(activeDataset);
+ }
+ }
+
+ @Test
+ public void join_withoutPrivilegedPermission_throwsSecurityException() throws Exception {
+ dropPermissions();
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ ActiveOperationalDataset activeDataset = newRandomizedDataset("TestNet", controller);
+
+ assertThrows(
+ SecurityException.class,
+ () -> controller.join(activeDataset, mExecutor, v -> {}));
+ }
+ }
+
+ @Test
+ public void join_concurrentRequests_firstOneIsAborted() throws Exception {
+ grantPermissions(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ final byte[] KEY_1 = new byte[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
+ final byte[] KEY_2 = new byte[] {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2};
+ for (ThreadNetworkController controller : getAllControllers()) {
+ ActiveOperationalDataset activeDataset1 =
+ new ActiveOperationalDataset.Builder(
+ newRandomizedDataset("TestNet", controller))
+ .setNetworkKey(KEY_1)
+ .build();
+ ActiveOperationalDataset activeDataset2 =
+ new ActiveOperationalDataset.Builder(activeDataset1)
+ .setNetworkKey(KEY_2)
+ .build();
+ SettableFuture<Void> joinFuture1 = SettableFuture.create();
+ SettableFuture<Void> joinFuture2 = SettableFuture.create();
+
+ controller.join(activeDataset1, mExecutor, newOutcomeReceiver(joinFuture1));
+ controller.join(activeDataset2, mExecutor, newOutcomeReceiver(joinFuture2));
+
+ ThreadNetworkException thrown =
+ (ThreadNetworkException)
+ assertThrows(ExecutionException.class, joinFuture1::get).getCause();
+ assertThat(thrown.getErrorCode()).isEqualTo(ERROR_ABORTED);
+ joinFuture2.get();
+ grantPermissions(permission.ACCESS_NETWORK_STATE);
+ assertThat(isAttached(controller)).isTrue();
+ assertThat(getActiveOperationalDataset(controller)).isEqualTo(activeDataset2);
+ }
+ }
+
+ @Test
+ public void leave_withPrivilegedPermission_success() throws Exception {
+ grantPermissions(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ ActiveOperationalDataset activeDataset = newRandomizedDataset("TestNet", controller);
+ SettableFuture<Void> joinFuture = SettableFuture.create();
+ SettableFuture<Void> leaveFuture = SettableFuture.create();
+ controller.join(activeDataset, mExecutor, newOutcomeReceiver(joinFuture));
+ joinFuture.get();
+
+ controller.leave(mExecutor, newOutcomeReceiver(leaveFuture));
+ leaveFuture.get();
+
+ grantPermissions(permission.ACCESS_NETWORK_STATE);
+ assertThat(getDeviceRole(controller)).isEqualTo(DEVICE_ROLE_STOPPED);
+ }
+ }
+
+ @Test
+ public void leave_withoutPrivilegedPermission_throwsSecurityException() {
+ dropPermissions();
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ assertThrows(SecurityException.class, () -> controller.leave(mExecutor, v -> {}));
+ }
+ }
+
+ @Test
+ public void leave_concurrentRequests_bothSuccess() throws Exception {
+ grantPermissions(PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ ActiveOperationalDataset activeDataset = newRandomizedDataset("TestNet", controller);
+ SettableFuture<Void> joinFuture = SettableFuture.create();
+ SettableFuture<Void> leaveFuture1 = SettableFuture.create();
+ SettableFuture<Void> leaveFuture2 = SettableFuture.create();
+ controller.join(activeDataset, mExecutor, newOutcomeReceiver(joinFuture));
+ joinFuture.get();
+
+ controller.leave(mExecutor, newOutcomeReceiver(leaveFuture1));
+ controller.leave(mExecutor, newOutcomeReceiver(leaveFuture2));
+
+ leaveFuture1.get();
+ leaveFuture2.get();
+ grantPermissions(permission.ACCESS_NETWORK_STATE);
+ assertThat(getDeviceRole(controller)).isEqualTo(DEVICE_ROLE_STOPPED);
+ }
+ }
+
+ @Test
+ public void scheduleMigration_withPrivilegedPermission_success() throws Exception {
+ grantPermissions(permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ ActiveOperationalDataset activeDataset1 =
+ new ActiveOperationalDataset.Builder(
+ newRandomizedDataset("TestNet", controller))
+ .setActiveTimestamp(new OperationalDatasetTimestamp(1L, 0, false))
+ .setExtendedPanId(new byte[] {1, 1, 1, 1, 1, 1, 1, 1})
+ .build();
+ ActiveOperationalDataset activeDataset2 =
+ new ActiveOperationalDataset.Builder(activeDataset1)
+ .setActiveTimestamp(new OperationalDatasetTimestamp(2L, 0, false))
+ .setNetworkName("ThreadNet2")
+ .build();
+ PendingOperationalDataset pendingDataset2 =
+ new PendingOperationalDataset(
+ activeDataset2,
+ OperationalDatasetTimestamp.fromInstant(Instant.now()),
+ Duration.ofSeconds(30));
+ SettableFuture<Void> joinFuture = SettableFuture.create();
+ SettableFuture<Void> migrateFuture = SettableFuture.create();
+ controller.join(activeDataset1, mExecutor, newOutcomeReceiver(joinFuture));
+ joinFuture.get();
+
+ controller.scheduleMigration(
+ pendingDataset2, mExecutor, newOutcomeReceiver(migrateFuture));
+
+ migrateFuture.get();
+ Thread.sleep(35 * 1000);
+ assertThat(getActiveOperationalDataset(controller)).isEqualTo(activeDataset2);
+ assertThat(getPendingOperationalDataset(controller)).isNull();
+ }
+ }
+
+ @Test
+ public void scheduleMigration_whenNotAttached_failWithPreconditionError() throws Exception {
+ grantPermissions(permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ PendingOperationalDataset pendingDataset =
+ new PendingOperationalDataset(
+ newRandomizedDataset("TestNet", controller),
+ OperationalDatasetTimestamp.fromInstant(Instant.now()),
+ Duration.ofSeconds(30));
+ SettableFuture<Void> migrateFuture = SettableFuture.create();
+
+ controller.scheduleMigration(
+ pendingDataset, mExecutor, newOutcomeReceiver(migrateFuture));
+
+ ThreadNetworkException thrown =
+ (ThreadNetworkException)
+ assertThrows(ExecutionException.class, migrateFuture::get).getCause();
+ assertThat(thrown.getErrorCode()).isEqualTo(ERROR_FAILED_PRECONDITION);
+ }
+ }
+
+ @Test
+ public void scheduleMigration_secondRequestHasSmallerTimestamp_rejectedByLeader()
+ throws Exception {
+ grantPermissions(permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ final ActiveOperationalDataset activeDataset =
+ new ActiveOperationalDataset.Builder(
+ newRandomizedDataset("testNet", controller))
+ .setActiveTimestamp(new OperationalDatasetTimestamp(1L, 0, false))
+ .build();
+ ActiveOperationalDataset activeDataset1 =
+ new ActiveOperationalDataset.Builder(activeDataset)
+ .setActiveTimestamp(new OperationalDatasetTimestamp(2L, 0, false))
+ .setNetworkName("testNet1")
+ .build();
+ PendingOperationalDataset pendingDataset1 =
+ new PendingOperationalDataset(
+ activeDataset1,
+ new OperationalDatasetTimestamp(100, 0, false),
+ Duration.ofSeconds(30));
+ ActiveOperationalDataset activeDataset2 =
+ new ActiveOperationalDataset.Builder(activeDataset)
+ .setActiveTimestamp(new OperationalDatasetTimestamp(3L, 0, false))
+ .setNetworkName("testNet2")
+ .build();
+ PendingOperationalDataset pendingDataset2 =
+ new PendingOperationalDataset(
+ activeDataset2,
+ new OperationalDatasetTimestamp(20, 0, false),
+ Duration.ofSeconds(30));
+ SettableFuture<Void> joinFuture = SettableFuture.create();
+ SettableFuture<Void> migrateFuture1 = SettableFuture.create();
+ SettableFuture<Void> migrateFuture2 = SettableFuture.create();
+ controller.join(activeDataset, mExecutor, newOutcomeReceiver(joinFuture));
+ joinFuture.get();
+
+ controller.scheduleMigration(
+ pendingDataset1, mExecutor, newOutcomeReceiver(migrateFuture1));
+ migrateFuture1.get();
+ controller.scheduleMigration(
+ pendingDataset2, mExecutor, newOutcomeReceiver(migrateFuture2));
+
+ ThreadNetworkException thrown =
+ (ThreadNetworkException)
+ assertThrows(ExecutionException.class, migrateFuture2::get).getCause();
+ assertThat(thrown.getErrorCode()).isEqualTo(ERROR_REJECTED_BY_PEER);
+ }
+ }
+
+ @Test
+ public void scheduleMigration_secondRequestHasLargerTimestamp_success() throws Exception {
+ grantPermissions(permission.ACCESS_NETWORK_STATE, PERMISSION_THREAD_NETWORK_PRIVILEGED);
+
+ for (ThreadNetworkController controller : getAllControllers()) {
+ final ActiveOperationalDataset activeDataset =
+ new ActiveOperationalDataset.Builder(
+ newRandomizedDataset("validName", controller))
+ .setActiveTimestamp(new OperationalDatasetTimestamp(1L, 0, false))
+ .build();
+ ActiveOperationalDataset activeDataset1 =
+ new ActiveOperationalDataset.Builder(activeDataset)
+ .setActiveTimestamp(new OperationalDatasetTimestamp(2L, 0, false))
+ .setNetworkName("testNet1")
+ .build();
+ PendingOperationalDataset pendingDataset1 =
+ new PendingOperationalDataset(
+ activeDataset1,
+ new OperationalDatasetTimestamp(100, 0, false),
+ Duration.ofSeconds(30));
+ ActiveOperationalDataset activeDataset2 =
+ new ActiveOperationalDataset.Builder(activeDataset)
+ .setActiveTimestamp(new OperationalDatasetTimestamp(3L, 0, false))
+ .setNetworkName("testNet2")
+ .build();
+ PendingOperationalDataset pendingDataset2 =
+ new PendingOperationalDataset(
+ activeDataset2,
+ new OperationalDatasetTimestamp(200, 0, false),
+ Duration.ofSeconds(30));
+ SettableFuture<Void> joinFuture = SettableFuture.create();
+ SettableFuture<Void> migrateFuture1 = SettableFuture.create();
+ SettableFuture<Void> migrateFuture2 = SettableFuture.create();
+ controller.join(activeDataset, mExecutor, newOutcomeReceiver(joinFuture));
+ joinFuture.get();
+
+ controller.scheduleMigration(
+ pendingDataset1, mExecutor, newOutcomeReceiver(migrateFuture1));
+ migrateFuture1.get();
+ controller.scheduleMigration(
+ pendingDataset2, mExecutor, newOutcomeReceiver(migrateFuture2));
+
+ migrateFuture2.get();
+ Thread.sleep(35 * 1000);
+ assertThat(getActiveOperationalDataset(controller)).isEqualTo(activeDataset2);
+ assertThat(getPendingOperationalDataset(controller)).isNull();
+ }
+ }
+
+ @Test
+ public void createRandomizedDataset_wrongNetworkNameLength_throwsIllegalArgumentException() {
+ for (ThreadNetworkController controller : getAllControllers()) {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> controller.createRandomizedDataset("", mExecutor, dataset -> {}));
+
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ controller.createRandomizedDataset(
+ "ANetNameIs17Bytes", mExecutor, dataset -> {}));
+ }
+ }
+
+ @Test
+ public void createRandomizedDataset_validNetworkName_success() throws Exception {
+ for (ThreadNetworkController controller : getAllControllers()) {
+ ActiveOperationalDataset dataset = newRandomizedDataset("validName", controller);
+
+ assertThat(dataset.getNetworkName()).isEqualTo("validName");
+ assertThat(dataset.getPanId()).isLessThan(0xffff);
+ assertThat(dataset.getChannelMask().size()).isAtLeast(1);
+ assertThat(dataset.getExtendedPanId()).hasLength(8);
+ assertThat(dataset.getNetworkKey()).hasLength(16);
+ assertThat(dataset.getPskc()).hasLength(16);
+ assertThat(dataset.getMeshLocalPrefix().getPrefixLength()).isEqualTo(64);
+ assertThat(dataset.getMeshLocalPrefix().getRawAddress()[0]).isEqualTo((byte) 0xfd);
+ }
+ }
}
diff --git a/thread/tests/unit/src/android/net/thread/ActiveOperationalDatasetTest.java b/thread/tests/unit/src/android/net/thread/ActiveOperationalDatasetTest.java
index 78eb3d0..7284968 100644
--- a/thread/tests/unit/src/android/net/thread/ActiveOperationalDatasetTest.java
+++ b/thread/tests/unit/src/android/net/thread/ActiveOperationalDatasetTest.java
@@ -20,14 +20,7 @@
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyInt;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import android.net.IpPrefix;
import android.net.thread.ActiveOperationalDataset.Builder;
import android.net.thread.ActiveOperationalDataset.SecurityPolicy;
import android.util.SparseArray;
@@ -61,7 +54,7 @@
// PAN ID: 0xD9A0
// PSKc: A245479C836D551B9CA557F7B9D351B4
// Security Policy: 672 onrcb
- private static final byte[] VALID_DATASET =
+ private static final byte[] VALID_DATASET_TLVS =
base16().decode(
"0E080000000000010000000300001335060004001FFFE002"
+ "08ACC214689BC40BDF0708FD64DB1225F47E0B0510F26B31"
@@ -83,7 +76,7 @@
@Test
public void fromThreadTlvs_containsUnknownTlvs_unknownTlvsRetained() {
- byte[] datasetWithUnknownTlvs = addTlv(VALID_DATASET, "AA01FFBB020102");
+ byte[] datasetWithUnknownTlvs = addTlv(VALID_DATASET_TLVS, "AA01FFBB020102");
ActiveOperationalDataset dataset1 =
ActiveOperationalDataset.fromThreadTlvs(datasetWithUnknownTlvs);
@@ -98,66 +91,8 @@
}
@Test
- public void createRandomDataset_fieldsAreRandomized() {
- // Always return the max bounded value
- doAnswer(invocation -> (int) invocation.getArgument(0) - 1)
- .when(mockRandom)
- .nextInt(anyInt());
- doAnswer(
- invocation -> {
- byte[] output = invocation.getArgument(0);
- for (int i = 0; i < output.length; ++i) {
- output[i] = (byte) (i + 10);
- }
- return null;
- })
- .when(mockRandom)
- .nextBytes(any(byte[].class));
- doAnswer(
- invocation -> {
- byte[] output = invocation.getArgument(0);
- for (int i = 0; i < output.length; ++i) {
- output[i] = (byte) (i + 30);
- }
- return null;
- })
- .when(mockSecureRandom)
- .nextBytes(any(byte[].class));
-
- ActiveOperationalDataset dataset =
- ActiveOperationalDataset.createRandomDataset(mockRandom, mockSecureRandom);
-
- assertThat(dataset.getActiveTimestamp())
- .isEqualTo(new OperationalDatasetTimestamp(1, 0, false));
- assertThat(dataset.getExtendedPanId())
- .isEqualTo(new byte[] {10, 11, 12, 13, 14, 15, 16, 17});
- assertThat(dataset.getMeshLocalPrefix())
- .isEqualTo(new IpPrefix("fd0b:0c0d:0e0f:1011::/64"));
- verify(mockRandom, times(2)).nextBytes(any(byte[].class));
- assertThat(dataset.getPanId()).isEqualTo(0xfffe); // PAN ID <= 0xfffe
- verify(mockRandom, times(1)).nextInt(eq(0xffff));
- assertThat(dataset.getChannel()).isEqualTo(26);
- verify(mockRandom, times(1)).nextInt(eq(16));
- assertThat(dataset.getChannelPage()).isEqualTo(0);
- assertThat(dataset.getChannelMask().size()).isEqualTo(1);
- assertThat(dataset.getPskc())
- .isEqualTo(
- new byte[] {
- 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45
- });
- assertThat(dataset.getNetworkKey())
- .isEqualTo(
- new byte[] {
- 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45
- });
- verify(mockSecureRandom, times(2)).nextBytes(any(byte[].class));
- assertThat(dataset.getSecurityPolicy())
- .isEqualTo(new SecurityPolicy(672, new byte[] {(byte) 0xff, (byte) 0xf8}));
- }
-
- @Test
public void builder_buildWithTooLongTlvs_throwsIllegalState() {
- Builder builder = new Builder(ActiveOperationalDataset.createRandomDataset());
+ Builder builder = new Builder(ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET_TLVS));
for (int i = 0; i < 10; i++) {
builder.addUnknownTlv(i, new byte[20]);
}
@@ -167,7 +102,8 @@
@Test
public void builder_setUnknownTlvs_success() {
- ActiveOperationalDataset dataset1 = ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET);
+ ActiveOperationalDataset dataset1 =
+ ActiveOperationalDataset.fromThreadTlvs(VALID_DATASET_TLVS);
SparseArray<byte[]> unknownTlvs = new SparseArray<>(2);
unknownTlvs.put(0x33, new byte[] {1, 2, 3});
unknownTlvs.put(0x44, new byte[] {1, 2, 3, 4});