Merge "Cleanup modifyRoutes" into main
diff --git a/Tethering/src/android/net/ip/IpServer.java b/Tethering/src/android/net/ip/IpServer.java
index 2a25a86..c78893a 100644
--- a/Tethering/src/android/net/ip/IpServer.java
+++ b/Tethering/src/android/net/ip/IpServer.java
@@ -33,6 +33,7 @@
import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
import static com.android.net.module.util.NetworkStackConstants.RFC7421_PREFIX_LENGTH;
+import static com.android.networkstack.tethering.TetheringConfiguration.USE_SYNC_SM;
import static com.android.networkstack.tethering.UpstreamNetworkState.isVcnInterface;
import static com.android.networkstack.tethering.util.PrefixUtils.asIpPrefix;
import static com.android.networkstack.tethering.util.TetheringMessageBase.BASE_IPSERVER;
@@ -56,7 +57,6 @@
import android.net.dhcp.IDhcpServer;
import android.net.ip.RouterAdvertisementDaemon.RaParams;
import android.os.Handler;
-import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.os.ServiceSpecificException;
@@ -66,9 +66,9 @@
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
+import com.android.internal.annotations.VisibleForTesting;
import com.android.internal.util.MessageUtils;
import com.android.internal.util.State;
-import com.android.internal.util.StateMachine;
import com.android.modules.utils.build.SdkLevel;
import com.android.net.module.util.InterfaceParams;
import com.android.net.module.util.NetdUtils;
@@ -85,12 +85,15 @@
import com.android.networkstack.tethering.metrics.TetheringMetrics;
import com.android.networkstack.tethering.util.InterfaceSet;
import com.android.networkstack.tethering.util.PrefixUtils;
+import com.android.networkstack.tethering.util.StateMachineShim;
+import com.android.networkstack.tethering.util.SyncStateMachine.StateInfo;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
@@ -104,7 +107,7 @@
*
* @hide
*/
-public class IpServer extends StateMachine {
+public class IpServer extends StateMachineShim {
public static final int STATE_UNAVAILABLE = 0;
public static final int STATE_AVAILABLE = 1;
public static final int STATE_TETHERED = 2;
@@ -297,6 +300,8 @@
private int mLastIPv6UpstreamIfindex = 0;
private boolean mUpstreamSupportsBpf = false;
+ @NonNull
+ private Set<IpPrefix> mLastIPv6UpstreamPrefixes = Collections.emptySet();
private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
public void accept(NeighborEvent e) {
@@ -309,16 +314,18 @@
private LinkAddress mIpv4Address;
private final TetheringMetrics mTetheringMetrics;
+ private final Handler mHandler;
// TODO: Add a dependency object to pass the data members or variables from the tethering
// object. It helps to reduce the arguments of the constructor.
public IpServer(
- String ifaceName, Looper looper, int interfaceType, SharedLog log,
+ String ifaceName, Handler handler, int interfaceType, SharedLog log,
INetd netd, @NonNull BpfCoordinator bpfCoordinator,
@Nullable LateSdk<RoutingCoordinatorManager> routingCoordinator, Callback callback,
TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
TetheringMetrics tetheringMetrics, Dependencies deps) {
- super(ifaceName, looper);
+ super(ifaceName, USE_SYNC_SM ? null : handler.getLooper());
+ mHandler = handler;
mLog = log.forSubComponent(ifaceName);
mNetd = netd;
mBpfCoordinator = bpfCoordinator;
@@ -351,13 +358,22 @@
mTetheredState = new TetheredState();
mUnavailableState = new UnavailableState();
mWaitingForRestartState = new WaitingForRestartState();
- addState(mInitialState);
- addState(mLocalHotspotState);
- addState(mTetheredState);
- addState(mWaitingForRestartState, mTetheredState);
- addState(mUnavailableState);
+ final ArrayList allStates = new ArrayList<StateInfo>();
+ allStates.add(new StateInfo(mInitialState, null));
+ allStates.add(new StateInfo(mLocalHotspotState, null));
+ allStates.add(new StateInfo(mTetheredState, null));
+ allStates.add(new StateInfo(mWaitingForRestartState, mTetheredState));
+ allStates.add(new StateInfo(mUnavailableState, null));
+ addAllStates(allStates);
+ }
- setInitialState(mInitialState);
+ private Handler getHandler() {
+ return mHandler;
+ }
+
+ /** Start IpServer state machine. */
+ public void start() {
+ start(mInitialState);
}
/** Interface name which IpServer served.*/
@@ -770,13 +786,8 @@
if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
- for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
- if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
-
- final IpPrefix prefix = new IpPrefix(
- linkAddr.getAddress(), linkAddr.getPrefixLength());
- params.prefixes.add(prefix);
-
+ params.prefixes = getTetherableIpv6Prefixes(v6only);
+ for (IpPrefix prefix : params.prefixes) {
final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
if (dnsServer != null) {
params.dnses.add(dnsServer);
@@ -796,9 +807,12 @@
// Not support BPF on virtual upstream interface
final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
- updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, upstreamSupportsBpf);
+ final Set<IpPrefix> upstreamPrefixes = params != null ? params.prefixes : Set.of();
+ updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamPrefixes,
+ upstreamIfIndex, upstreamPrefixes, upstreamSupportsBpf);
mLastIPv6LinkProperties = v6only;
mLastIPv6UpstreamIfindex = upstreamIfIndex;
+ mLastIPv6UpstreamPrefixes = upstreamPrefixes;
mUpstreamSupportsBpf = upstreamSupportsBpf;
if (mDadProxy != null) {
mDadProxy.setUpstreamIface(upstreamIfaceParams);
@@ -947,14 +961,17 @@
return supportsBpf ? ifindex : NO_UPSTREAM;
}
- // Handles updates to IPv6 forwarding rules if the upstream changes.
- private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
- boolean upstreamSupportsBpf) {
+ // Handles updates to IPv6 forwarding rules if the upstream or its prefixes change.
+ private void updateIpv6ForwardingRules(int prevUpstreamIfindex,
+ @NonNull Set<IpPrefix> prevUpstreamPrefixes, int upstreamIfindex,
+ @NonNull Set<IpPrefix> upstreamPrefixes, boolean upstreamSupportsBpf) {
// If the upstream interface has changed, remove all rules and re-add them with the new
// upstream interface. If upstream is a virtual network, treated as no upstream.
- if (prevUpstreamIfindex != upstreamIfindex) {
+ if (prevUpstreamIfindex != upstreamIfindex
+ || !prevUpstreamPrefixes.equals(upstreamPrefixes)) {
mBpfCoordinator.updateAllIpv6Rules(this, this.mInterfaceParams,
- getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf));
+ getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf),
+ upstreamPrefixes);
}
}
@@ -1359,7 +1376,7 @@
for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
mUpstreamIfaceSet = null;
mBpfCoordinator.updateAllIpv6Rules(
- IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM);
+ IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM, Set.of());
}
private void cleanupUpstreamInterface(String upstreamIface) {
@@ -1536,4 +1553,21 @@
}
return random;
}
+
+ /** Get IPv6 prefixes from LinkProperties */
+ @NonNull
+ @VisibleForTesting
+ static HashSet<IpPrefix> getTetherableIpv6Prefixes(@NonNull Collection<LinkAddress> addrs) {
+ final HashSet<IpPrefix> prefixes = new HashSet<>();
+ for (LinkAddress linkAddr : addrs) {
+ if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
+ prefixes.add(new IpPrefix(linkAddr.getAddress(), RFC7421_PREFIX_LENGTH));
+ }
+ return prefixes;
+ }
+
+ @NonNull
+ private HashSet<IpPrefix> getTetherableIpv6Prefixes(@NonNull LinkProperties lp) {
+ return getTetherableIpv6Prefixes(lp.getLinkAddresses());
+ }
}
diff --git a/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java b/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
index 46c815f..2b14a42 100644
--- a/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
+++ b/Tethering/src/com/android/networkstack/tethering/BpfCoordinator.java
@@ -28,6 +28,7 @@
import static android.system.OsConstants.ETH_P_IPV6;
import static com.android.net.module.util.NetworkStackConstants.IPV4_MIN_MTU;
+import static com.android.net.module.util.NetworkStackConstants.IPV6_ADDR_LEN;
import static com.android.net.module.util.ip.ConntrackMonitor.ConntrackEvent;
import static com.android.networkstack.tethering.BpfUtils.DOWNSTREAM;
import static com.android.networkstack.tethering.BpfUtils.UPSTREAM;
@@ -90,7 +91,6 @@
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -123,7 +123,6 @@
private static final int DUMP_TIMEOUT_MS = 10_000;
private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString(
"00:00:00:00:00:00");
- private static final IpPrefix IPV6_ZERO_PREFIX64 = new IpPrefix("::/64");
private static final String TETHER_DOWNSTREAM4_MAP_PATH = makeMapPath(DOWNSTREAM, 4);
private static final String TETHER_UPSTREAM4_MAP_PATH = makeMapPath(UPSTREAM, 4);
private static final String TETHER_DOWNSTREAM6_FS_PATH = makeMapPath(DOWNSTREAM, 6);
@@ -768,7 +767,8 @@
* Note that this can be only called on handler thread.
*/
public void updateAllIpv6Rules(@NonNull final IpServer ipServer,
- final InterfaceParams interfaceParams, int newUpstreamIfindex) {
+ final InterfaceParams interfaceParams, int newUpstreamIfindex,
+ @NonNull final Set<IpPrefix> newUpstreamPrefixes) {
if (!isUsingBpf()) return;
// Remove IPv6 downstream rules. Remove the old ones before adding the new rules, otherwise
@@ -791,9 +791,11 @@
// Add new upstream rules.
if (newUpstreamIfindex != 0 && interfaceParams != null && interfaceParams.macAddr != null) {
- addIpv6UpstreamRule(ipServer, new Ipv6UpstreamRule(
- newUpstreamIfindex, interfaceParams.index, IPV6_ZERO_PREFIX64,
- interfaceParams.macAddr, NULL_MAC_ADDRESS, NULL_MAC_ADDRESS));
+ for (final IpPrefix ipPrefix : newUpstreamPrefixes) {
+ addIpv6UpstreamRule(ipServer, new Ipv6UpstreamRule(
+ newUpstreamIfindex, interfaceParams.index, ipPrefix,
+ interfaceParams.macAddr, NULL_MAC_ADDRESS, NULL_MAC_ADDRESS));
+ }
}
// Add updated downstream rules.
@@ -1256,10 +1258,24 @@
pw.decreaseIndent();
}
+ private IpPrefix longToPrefix(long ip64) {
+ final ByteBuffer prefixBuffer = ByteBuffer.allocate(IPV6_ADDR_LEN);
+ prefixBuffer.putLong(ip64);
+ IpPrefix sourcePrefix;
+ try {
+ sourcePrefix = new IpPrefix(InetAddress.getByAddress(prefixBuffer.array()), 64);
+ } catch (UnknownHostException e) {
+ // Cannot happen. InetAddress.getByAddress can only throw an exception if the byte array
+ // is the wrong length, but we allocate it with fixed length IPV6_ADDR_LEN.
+ throw new IllegalArgumentException("Invalid IPv6 address");
+ }
+ return sourcePrefix;
+ }
+
private String ipv6UpstreamRuleToString(TetherUpstream6Key key, Tether6Value value) {
- return String.format("%d(%s) [%s] -> %d(%s) %04x [%s] [%s]",
- key.iif, getIfName(key.iif), key.dstMac, value.oif, getIfName(value.oif),
- value.ethProto, value.ethSrcMac, value.ethDstMac);
+ return String.format("%d(%s) [%s] [%s] -> %d(%s) %04x [%s] [%s]",
+ key.iif, getIfName(key.iif), key.dstMac, longToPrefix(key.src64), value.oif,
+ getIfName(value.oif), value.ethProto, value.ethSrcMac, value.ethDstMac);
}
private void dumpIpv6UpstreamRules(IndentingPrintWriter pw) {
@@ -1309,8 +1325,8 @@
// TODO: use dump utils with headerline and lambda which prints key and value to reduce
// duplicate bpf map dump code.
private void dumpBpfForwardingRulesIpv6(IndentingPrintWriter pw) {
- pw.println("IPv6 Upstream: iif(iface) [inDstMac] -> oif(iface) etherType [outSrcMac] "
- + "[outDstMac]");
+ pw.println("IPv6 Upstream: iif(iface) [inDstMac] [sourcePrefix] -> oif(iface) etherType "
+ + "[outSrcMac] [outDstMac]");
pw.increaseIndent();
dumpIpv6UpstreamRules(pw);
pw.decreaseIndent();
@@ -1554,8 +1570,7 @@
*/
@NonNull
public TetherUpstream6Key makeTetherUpstream6Key() {
- byte[] prefixBytes = Arrays.copyOf(sourcePrefix.getRawAddress(), 8);
- long prefix64 = ByteBuffer.wrap(prefixBytes).order(ByteOrder.BIG_ENDIAN).getLong();
+ long prefix64 = ByteBuffer.wrap(sourcePrefix.getRawAddress()).getLong();
return new TetherUpstream6Key(downstreamIfindex, inDstMac, prefix64);
}
diff --git a/Tethering/src/com/android/networkstack/tethering/Tethering.java b/Tethering/src/com/android/networkstack/tethering/Tethering.java
index f52bed9..996ee11 100644
--- a/Tethering/src/com/android/networkstack/tethering/Tethering.java
+++ b/Tethering/src/com/android/networkstack/tethering/Tethering.java
@@ -1687,6 +1687,8 @@
static final int EVENT_IFACE_UPDATE_LINKPROPERTIES = BASE_MAIN_SM + 7;
// Events from EntitlementManager to choose upstream again.
static final int EVENT_UPSTREAM_PERMISSION_CHANGED = BASE_MAIN_SM + 8;
+ // Internal request from IpServer to enable or disable downstream.
+ static final int EVENT_REQUEST_CHANGE_DOWNSTREAM = BASE_MAIN_SM + 9;
private final State mInitialState;
private final State mTetherModeAliveState;
@@ -2186,6 +2188,12 @@
}
break;
}
+ case EVENT_REQUEST_CHANGE_DOWNSTREAM: {
+ final int tetheringType = message.arg1;
+ final Boolean enabled = (Boolean) message.obj;
+ enableTetheringInternal(tetheringType, enabled, null);
+ break;
+ }
default:
retValue = false;
break;
@@ -2743,7 +2751,8 @@
@Override
public void requestEnableTethering(int tetheringType, boolean enabled) {
- enableTetheringInternal(tetheringType, enabled, null);
+ mTetherMainSM.sendMessage(TetherMainSM.EVENT_REQUEST_CHANGE_DOWNSTREAM,
+ tetheringType, 0, enabled ? Boolean.TRUE : Boolean.FALSE);
}
};
}
@@ -2841,7 +2850,7 @@
mLog.i("adding IpServer for: " + iface);
final TetherState tetherState = new TetherState(
- new IpServer(iface, mLooper, interfaceType, mLog, mNetd, mBpfCoordinator,
+ new IpServer(iface, mHandler, interfaceType, mLog, mNetd, mBpfCoordinator,
mRoutingCoordinator, makeControlCallback(), mConfig,
mPrivateAddressCoordinator, mTetheringMetrics,
mDeps.getIpServerDependencies()), isNcm);
diff --git a/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java b/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java
index 747cc20..502fee8 100644
--- a/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java
+++ b/Tethering/src/com/android/networkstack/tethering/TetheringConfiguration.java
@@ -136,6 +136,9 @@
*/
public static final int DEFAULT_TETHER_OFFLOAD_POLL_INTERVAL_MS = 5000;
+ /** A flag for using synchronous or asynchronous state machine. */
+ public static final boolean USE_SYNC_SM = false;
+
public final String[] tetherableUsbRegexs;
public final String[] tetherableWifiRegexs;
public final String[] tetherableWigigRegexs;
diff --git a/Tethering/src/com/android/networkstack/tethering/util/StateMachineShim.java b/Tethering/src/com/android/networkstack/tethering/util/StateMachineShim.java
new file mode 100644
index 0000000..fc432f7
--- /dev/null
+++ b/Tethering/src/com/android/networkstack/tethering/util/StateMachineShim.java
@@ -0,0 +1,176 @@
+/*
+ * 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.networkstack.tethering.util;
+
+import android.annotation.Nullable;
+import android.os.Looper;
+
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.State;
+import com.android.internal.util.StateMachine;
+import com.android.networkstack.tethering.util.SyncStateMachine.StateInfo;
+
+import java.util.List;
+
+/** A wrapper to decide whether use synchronous state machine for tethering. */
+public class StateMachineShim {
+ // Exactly one of mAsyncSM or mSyncSM is non-null.
+ private final StateMachine mAsyncSM;
+ private final SyncStateMachine mSyncSM;
+
+ /**
+ * The Looper parameter is only needed for AsyncSM, so if looper is null, the shim will be
+ * created for SyncSM.
+ */
+ public StateMachineShim(final String name, @Nullable final Looper looper) {
+ this(name, looper, new Dependencies());
+ }
+
+ @VisibleForTesting
+ public StateMachineShim(final String name, @Nullable final Looper looper,
+ final Dependencies deps) {
+ if (looper == null) {
+ mAsyncSM = null;
+ mSyncSM = deps.makeSyncStateMachine(name, Thread.currentThread());
+ } else {
+ mAsyncSM = deps.makeAsyncStateMachine(name, looper);
+ mSyncSM = null;
+ }
+ }
+
+ /** A dependencies class which used for testing injection. */
+ @VisibleForTesting
+ public static class Dependencies {
+ /** Create SyncSM instance, for injection. */
+ public SyncStateMachine makeSyncStateMachine(final String name, final Thread thread) {
+ return new SyncStateMachine(name, thread);
+ }
+
+ /** Create AsyncSM instance, for injection. */
+ public AsyncStateMachine makeAsyncStateMachine(final String name, final Looper looper) {
+ return new AsyncStateMachine(name, looper);
+ }
+ }
+
+ /** Start the state machine */
+ public void start(final State initialState) {
+ if (mSyncSM != null) {
+ mSyncSM.start(initialState);
+ } else {
+ mAsyncSM.setInitialState(initialState);
+ mAsyncSM.start();
+ }
+ }
+
+ /** Add states to state machine. */
+ public void addAllStates(final List<StateInfo> stateInfos) {
+ if (mSyncSM != null) {
+ mSyncSM.addAllStates(stateInfos);
+ } else {
+ for (final StateInfo info : stateInfos) {
+ mAsyncSM.addState(info.state, info.parent);
+ }
+ }
+ }
+
+ /**
+ * Transition to given state.
+ *
+ * SyncSM doesn't allow this be called during state transition (#enter() or #exit() methods),
+ * or multiple times while processing a single message.
+ */
+ public void transitionTo(final State state) {
+ if (mSyncSM != null) {
+ mSyncSM.transitionTo(state);
+ } else {
+ mAsyncSM.transitionTo(state);
+ }
+ }
+
+ /** Send message to state machine. */
+ public void sendMessage(int what) {
+ sendMessage(what, 0, 0, null);
+ }
+
+ /** Send message to state machine. */
+ public void sendMessage(int what, Object obj) {
+ sendMessage(what, 0, 0, obj);
+ }
+
+ /** Send message to state machine. */
+ public void sendMessage(int what, int arg1) {
+ sendMessage(what, arg1, 0, null);
+ }
+
+ /**
+ * Send message to state machine.
+ *
+ * If using asynchronous state machine, putting the message into looper's message queue.
+ * Tethering runs on single looper thread that ipServers and mainSM all share with same message
+ * queue. The enqueued message will be processed by asynchronous state machine when all the
+ * messages before such enqueued message are processed.
+ * If using synchronous state machine, the message is processed right away without putting into
+ * looper's message queue.
+ */
+ public void sendMessage(int what, int arg1, int arg2, Object obj) {
+ if (mSyncSM != null) {
+ mSyncSM.processMessage(what, arg1, arg2, obj);
+ } else {
+ mAsyncSM.sendMessage(what, arg1, arg2, obj);
+ }
+ }
+
+ /**
+ * Send message after delayMillis millisecond.
+ *
+ * This can only be used with async state machine, so this will throw if using sync state
+ * machine.
+ */
+ public void sendMessageDelayedToAsyncSM(final int what, final long delayMillis) {
+ if (mSyncSM != null) {
+ throw new IllegalStateException("sendMessageDelayed can only be used with async SM");
+ }
+
+ mAsyncSM.sendMessageDelayed(what, delayMillis);
+ }
+
+ /**
+ * Send self message.
+ * This can only be used with sync state machine, so this will throw if using async state
+ * machine.
+ */
+ public void sendSelfMessageToSyncSM(final int what, final Object obj) {
+ if (mSyncSM == null) {
+ throw new IllegalStateException("sendSelfMessage can only be used with sync SM");
+ }
+
+ mSyncSM.sendSelfMessage(what, 0, 0, obj);
+ }
+
+ /**
+ * An alias StateMahchine class with public construtor.
+ *
+ * Since StateMachine.java only provides protected construtor, adding a child class so that this
+ * shim could create StateMachine instance.
+ */
+ @VisibleForTesting
+ public static class AsyncStateMachine extends StateMachine {
+ public AsyncStateMachine(final String name, final Looper looper) {
+ super(name, looper);
+ }
+ }
+}
diff --git a/Tethering/tests/unit/src/android/net/ip/IpServerTest.java b/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
index 15df3ba..bc970e4 100644
--- a/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
+++ b/Tethering/tests/unit/src/android/net/ip/IpServerTest.java
@@ -34,6 +34,7 @@
import static android.net.ip.IpServer.STATE_LOCAL_ONLY;
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;
@@ -95,6 +96,8 @@
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;
@@ -145,12 +148,15 @@
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;
@RunWith(AndroidJUnit4.class)
@SmallTest
@@ -188,6 +194,18 @@
private final LinkAddress mTestAddress = new LinkAddress("192.168.42.5/24");
private final IpPrefix mBluetoothPrefix = new IpPrefix("192.168.44.0/24");
+ private static final Set<LinkAddress> NO_ADDRESSES = Set.of();
+ private static final Set<IpPrefix> NO_PREFIXES = Set.of();
+ private static final Set<LinkAddress> UPSTREAM_ADDRESSES =
+ Set.of(new LinkAddress("2001:db8:0:1234::168/64"));
+ private static final Set<IpPrefix> UPSTREAM_PREFIXES =
+ Set.of(new IpPrefix("2001:db8:0:1234::/64"));
+ private static final Set<LinkAddress> UPSTREAM_ADDRESSES2 = Set.of(
+ new LinkAddress("2001:db8:0:1234::168/64"),
+ new LinkAddress("2001:db8:0:abcd::168/64"));
+ private static final Set<IpPrefix> UPSTREAM_PREFIXES2 = Set.of(
+ new IpPrefix("2001:db8:0:1234::/64"), new IpPrefix("2001:db8:0:abcd::/64"));
+
@Mock private INetd mNetd;
@Mock private IpServer.Callback mCallback;
@Mock private SharedLog mSharedLog;
@@ -215,6 +233,7 @@
@Captor private ArgumentCaptor<DhcpServingParamsParcel> mDhcpParamsCaptor;
private final TestLooper mLooper = new TestLooper();
+ private final Handler mHandler = new Handler(mLooper.getLooper());
private final ArgumentCaptor<LinkProperties> mLinkPropertiesCaptor =
ArgumentCaptor.forClass(LinkProperties.class);
private IpServer mIpServer;
@@ -254,7 +273,7 @@
// Recreate mBpfCoordinator again here because mTetherConfig has changed
mBpfCoordinator = spy(new BpfCoordinator(mBpfDeps));
mIpServer = new IpServer(
- IFACE_NAME, mLooper.getLooper(), interfaceType, mSharedLog, mNetd, mBpfCoordinator,
+ IFACE_NAME, mHandler, interfaceType, mSharedLog, mNetd, mBpfCoordinator,
mRoutingCoordinatorManager, mCallback, mTetherConfig, mAddressCoordinator,
mTetheringMetrics, mDependencies);
mIpServer.start();
@@ -270,24 +289,27 @@
private void initTetheredStateMachine(int interfaceType, String upstreamIface)
throws Exception {
- initTetheredStateMachine(interfaceType, upstreamIface, false,
+ initTetheredStateMachine(interfaceType, upstreamIface, NO_ADDRESSES, false,
DEFAULT_USING_BPF_OFFLOAD);
}
private void initTetheredStateMachine(int interfaceType, String upstreamIface,
- boolean usingLegacyDhcp, boolean usingBpfOffload) throws Exception {
+ Set<LinkAddress> upstreamAddresses, boolean usingLegacyDhcp, boolean usingBpfOffload)
+ throws Exception {
initStateMachine(interfaceType, usingLegacyDhcp, usingBpfOffload);
dispatchCommand(IpServer.CMD_TETHER_REQUESTED, STATE_TETHERED);
if (upstreamIface != null) {
LinkProperties lp = new LinkProperties();
lp.setInterfaceName(upstreamIface);
+ lp.setLinkAddresses(upstreamAddresses);
dispatchTetherConnectionChanged(upstreamIface, lp, 0);
- if (usingBpfOffload) {
+ 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);
- verifyStartUpstreamIpv6Forwarding(null, interfaceParams.index);
+ mIpServer, TEST_IFACE_PARAMS, interfaceParams.index, upstreamPrefixes);
+ verifyStartUpstreamIpv6Forwarding(null, interfaceParams.index, upstreamPrefixes);
} else {
verifyNoUpstreamIpv6ForwardingChange(null);
}
@@ -341,7 +363,7 @@
mBpfDeps = new BpfCoordinator.Dependencies() {
@NonNull
public Handler getHandler() {
- return new Handler(mLooper.getLooper());
+ return mHandler;
}
@NonNull
@@ -419,7 +441,7 @@
public void startsOutAvailable() {
when(mDependencies.getIpNeighborMonitor(any(), any(), any()))
.thenReturn(mIpNeighborMonitor);
- mIpServer = new IpServer(IFACE_NAME, mLooper.getLooper(), TETHERING_BLUETOOTH, mSharedLog,
+ mIpServer = new IpServer(IFACE_NAME, mHandler, TETHERING_BLUETOOTH, mSharedLog,
mNetd, mBpfCoordinator, mRoutingCoordinatorManager, mCallback, mTetherConfig,
mAddressCoordinator, mTetheringMetrics, mDependencies);
mIpServer.start();
@@ -663,10 +685,7 @@
inOrder.verify(mNetd).ipfwdRemoveInterfaceForward(IFACE_NAME, UPSTREAM_IFACE);
inOrder.verify(mNetd).tetherRemoveForward(IFACE_NAME, UPSTREAM_IFACE);
inOrder.verify(mBpfCoordinator).updateAllIpv6Rules(
- mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM);
- if (!mBpfDeps.isAtLeastS()) {
- inOrder.verify(mNetd).tetherOffloadGetAndClearStats(UPSTREAM_IFINDEX);
- }
+ mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
// When tethering stops, upstream interface is set to zero and thus clearing all upstream
// rules. Downstream rules are needed to be cleared explicitly by calling
// BpfCoordinator#clearAllIpv6Rules in TetheredState#exit.
@@ -856,8 +875,8 @@
@Test
public void doesNotStartDhcpServerIfDisabled() throws Exception {
- initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, true /* usingLegacyDhcp */,
- DEFAULT_USING_BPF_OFFLOAD);
+ initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, NO_ADDRESSES,
+ true /* usingLegacyDhcp */, DEFAULT_USING_BPF_OFFLOAD);
dispatchTetherConnectionChanged(UPSTREAM_IFACE);
verify(mDependencies, never()).makeDhcpServer(any(), any(), any());
@@ -962,11 +981,19 @@
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);
+ return inOrder.verify(t, mode);
} else {
- return verify(t);
+ return verify(t, mode);
}
}
@@ -1026,23 +1053,49 @@
}
}
- private void verifyStartUpstreamIpv6Forwarding(@Nullable InOrder inOrder, int upstreamIfindex)
- throws Exception {
+ private void verifyStartUpstreamIpv6Forwarding(@Nullable InOrder inOrder, int upstreamIfindex,
+ @NonNull Set<IpPrefix> upstreamPrefixes) throws Exception {
if (!mBpfDeps.isAtLeastS()) return;
- final TetherUpstream6Key key = new TetherUpstream6Key(TEST_IFACE_PARAMS.index,
- TEST_IFACE_PARAMS.macAddr, 0);
- final Tether6Value value = new Tether6Value(upstreamIfindex,
- MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS,
- ETH_P_IPV6, NetworkStackConstants.ETHER_MTU);
- verifyWithOrder(inOrder, mBpfUpstream6Map).insertEntry(key, value);
+ 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)
- throws Exception {
+ private void verifyStopUpstreamIpv6Forwarding(@Nullable InOrder inOrder,
+ @NonNull Set<IpPrefix> upstreamPrefixes) throws Exception {
if (!mBpfDeps.isAtLeastS()) return;
- final TetherUpstream6Key key = new TetherUpstream6Key(TEST_IFACE_PARAMS.index,
- TEST_IFACE_PARAMS.macAddr, 0);
- verifyWithOrder(inOrder, mBpfUpstream6Map).deleteEntry(key);
+ 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 {
@@ -1083,8 +1136,8 @@
@Test
public void addRemoveipv6ForwardingRules() throws Exception {
- initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, false /* usingLegacyDhcp */,
- DEFAULT_USING_BPF_OFFLOAD);
+ 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;
@@ -1145,7 +1198,7 @@
UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macNull);
resetNetdBpfMapAndCoordinator();
- // Upstream changes result in updating the rules.
+ // Upstream interface changes result in updating the rules.
recvNewNeigh(myIfindex, neighA, NUD_REACHABLE, macA);
recvNewNeigh(myIfindex, neighB, NUD_REACHABLE, macB);
resetNetdBpfMapAndCoordinator();
@@ -1153,14 +1206,36 @@
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);
+ 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);
- verifyStartUpstreamIpv6Forwarding(inOrder, UPSTREAM_IFINDEX2);
+ 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();
+
+ // Upstream link addresses change result in updating the rules.
+ LinkProperties lp2 = new LinkProperties();
+ lp2.setInterfaceName(UPSTREAM_IFACE2);
+ lp2.setLinkAddresses(UPSTREAM_ADDRESSES2);
+ 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,
@@ -1174,8 +1249,8 @@
// - processMessage CMD_IPV6_TETHER_UPDATE for the IPv6 upstream is lost.
// See dispatchTetherConnectionChanged.
verify(mBpfCoordinator, times(2)).updateAllIpv6Rules(
- mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM);
- verifyStopUpstreamIpv6Forwarding(inOrder);
+ mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
+ verifyStopUpstreamIpv6Forwarding(inOrder, UPSTREAM_PREFIXES2);
verifyTetherOffloadRuleRemove(null,
UPSTREAM_IFINDEX2, UPSTREAM_IFACE_PARAMS2.macAddr, neighA, macA);
verifyTetherOffloadRuleRemove(null,
@@ -1205,7 +1280,7 @@
// with an upstream of NO_UPSTREAM are reapplied.
lp.setInterfaceName(UPSTREAM_IFACE);
dispatchTetherConnectionChanged(UPSTREAM_IFACE, lp, -1);
- verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX);
+ verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
verify(mBpfCoordinator).addIpv6DownstreamRule(
mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighA, macA));
verifyTetherOffloadRuleAdd(null,
@@ -1219,16 +1294,17 @@
// If upstream IPv6 connectivity is lost, rules are removed.
resetNetdBpfMapAndCoordinator();
dispatchTetherConnectionChanged(UPSTREAM_IFACE, null, 0);
- verify(mBpfCoordinator).updateAllIpv6Rules(mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM);
+ verify(mBpfCoordinator).updateAllIpv6Rules(
+ mIpServer, TEST_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
verifyTetherOffloadRuleRemove(null,
UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighB, macB);
- verifyStopUpstreamIpv6Forwarding(null);
+ verifyStopUpstreamIpv6Forwarding(null, UPSTREAM_PREFIXES);
// When upstream IPv6 connectivity comes back, upstream rules are added and downstream rules
// are reapplied.
lp.setInterfaceName(UPSTREAM_IFACE);
dispatchTetherConnectionChanged(UPSTREAM_IFACE, lp, -1);
- verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX);
+ verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
verify(mBpfCoordinator).addIpv6DownstreamRule(
mIpServer, makeDownstreamRule(UPSTREAM_IFINDEX, neighA, macA));
verifyTetherOffloadRuleAdd(null,
@@ -1243,7 +1319,7 @@
mIpServer.stop();
mLooper.dispatchAll();
verify(mBpfCoordinator).clearAllIpv6Rules(mIpServer);
- verifyStopUpstreamIpv6Forwarding(null);
+ verifyStopUpstreamIpv6Forwarding(null, UPSTREAM_PREFIXES);
verifyTetherOffloadRuleRemove(null,
UPSTREAM_IFINDEX, UPSTREAM_IFACE_PARAMS.macAddr, neighA, macA);
verifyTetherOffloadRuleRemove(null,
@@ -1268,8 +1344,8 @@
// [1] Enable BPF offload.
// A neighbor that is added or deleted causes the rule to be added or removed.
- initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, false /* usingLegacyDhcp */,
- true /* usingBpfOffload */);
+ initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
+ false /* usingLegacyDhcp */, true /* usingBpfOffload */);
resetNetdBpfMapAndCoordinator();
recvNewNeigh(myIfindex, neigh, NUD_REACHABLE, macA);
@@ -1289,15 +1365,17 @@
// 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);
- verifyStartUpstreamIpv6Forwarding(null, UPSTREAM_IFINDEX2);
+ 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, false /* usingLegacyDhcp */,
- false /* usingBpfOffload */);
+ initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
+ false /* usingLegacyDhcp */, false /* usingBpfOffload */);
resetNetdBpfMapAndCoordinator();
recvNewNeigh(myIfindex, neigh, NUD_REACHABLE, macA);
@@ -1317,8 +1395,8 @@
@Test
public void doesNotStartIpNeighborMonitorIfBpfOffloadDisabled() throws Exception {
- initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, false /* usingLegacyDhcp */,
- false /* usingBpfOffload */);
+ initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, UPSTREAM_ADDRESSES,
+ false /* usingLegacyDhcp */, false /* usingBpfOffload */);
// IP neighbor monitor doesn't start if BPF offload is disabled.
verify(mIpNeighborMonitor, never()).start();
@@ -1600,8 +1678,8 @@
// TODO: move to BpfCoordinatorTest once IpNeighborMonitor is migrated to BpfCoordinator.
@Test
public void addRemoveTetherClient() throws Exception {
- initTetheredStateMachine(TETHERING_WIFI, UPSTREAM_IFACE, false /* usingLegacyDhcp */,
- DEFAULT_USING_BPF_OFFLOAD);
+ 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;
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 601f587..7fbb670 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/BpfCoordinatorTest.java
@@ -55,6 +55,7 @@
import static com.android.networkstack.tethering.BpfUtils.DOWNSTREAM;
import static com.android.networkstack.tethering.BpfUtils.UPSTREAM;
import static com.android.networkstack.tethering.TetheringConfiguration.DEFAULT_TETHER_OFFLOAD_POLL_INTERVAL_MS;
+import static com.android.testutils.MiscAsserts.assertSameElements;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -73,6 +74,7 @@
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -92,6 +94,7 @@
import android.os.Build;
import android.os.Handler;
import android.os.test.TestLooper;
+import android.util.ArrayMap;
import android.util.SparseArray;
import androidx.annotation.NonNull;
@@ -136,16 +139,20 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.MockitoSession;
+import org.mockito.verification.VerificationMode;
import java.io.StringWriter;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
+import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
@RunWith(AndroidJUnit4.class)
@SmallTest
@@ -159,7 +166,7 @@
private static final int TEST_NET_ID = 24;
private static final int TEST_NET_ID2 = 25;
- private static final int INVALID_IFINDEX = 0;
+ private static final int NO_UPSTREAM = 0;
private static final int UPSTREAM_IFINDEX = 1001;
private static final int UPSTREAM_XLAT_IFINDEX = 1002;
private static final int UPSTREAM_IFINDEX2 = 1003;
@@ -178,8 +185,17 @@
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 InetAddress NEIGH_A = InetAddresses.parseNumericAddress("2001:db8::1");
- private static final InetAddress NEIGH_B = InetAddresses.parseNumericAddress("2001:db8::2");
+ 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);
+ private static final Set<IpPrefix> UPSTREAM_PREFIXES2 =
+ Set.of(UPSTREAM_PREFIX, UPSTREAM_PREFIX2);
+ private static final Set<IpPrefix> NO_PREFIXES = Set.of();
+
+ private static final InetAddress NEIGH_A =
+ InetAddresses.parseNumericAddress("2001:db8:0:1234::1");
+ private static final InetAddress NEIGH_B =
+ InetAddresses.parseNumericAddress("2001:db8:0:1234::2");
private static final Inet4Address REMOTE_ADDR =
(Inet4Address) InetAddresses.parseNumericAddress("140.112.8.116");
@@ -195,7 +211,6 @@
private static final Inet4Address XLAT_LOCAL_IPV4ADDR =
(Inet4Address) InetAddresses.parseNumericAddress("192.0.0.46");
private static final IpPrefix NAT64_IP_PREFIX = new IpPrefix("64:ff9b::/96");
- private static final IpPrefix IPV6_ZERO_PREFIX = new IpPrefix("::/64");
// Generally, public port and private port are the same in the NAT conntrack message.
// TODO: consider using different private port and public port for testing.
@@ -624,10 +639,14 @@
}
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);
+ return inOrder.verify(t, mode);
} else {
- return verify(t);
+ return verify(t, mode);
}
}
@@ -667,6 +686,28 @@
rule.makeTetherUpstream6Key(), rule.makeTether6Value());
}
+ private void verifyAddUpstreamRules(@Nullable InOrder inOrder,
+ @NonNull Set<Ipv6UpstreamRule> rules) throws Exception {
+ if (!mDeps.isAtLeastS()) return;
+ ArrayMap<TetherUpstream6Key, Tether6Value> expected = new ArrayMap<>();
+ for (Ipv6UpstreamRule rule : rules) {
+ expected.put(rule.makeTetherUpstream6Key(), rule.makeTether6Value());
+ }
+ 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 verifyAddDownstreamRule(@Nullable InOrder inOrder,
@NonNull Ipv6DownstreamRule rule) throws Exception {
if (mDeps.isAtLeastS()) {
@@ -697,6 +738,20 @@
rule.makeTetherUpstream6Key());
}
+ private void verifyRemoveUpstreamRules(@Nullable InOrder inOrder,
+ @NonNull Set<Ipv6UpstreamRule> rules) throws Exception {
+ if (!mDeps.isAtLeastS()) return;
+ List<TetherUpstream6Key> expected = new ArrayList<>();
+ for (Ipv6UpstreamRule rule : rules) {
+ expected.add(rule.makeTetherUpstream6Key());
+ }
+ ArgumentCaptor<TetherUpstream6Key> keyCaptor =
+ ArgumentCaptor.forClass(TetherUpstream6Key.class);
+ verifyWithOrder(inOrder, mBpfUpstream6Map, times(expected.size())).deleteEntry(
+ keyCaptor.capture());
+ assertSameElements(expected, keyCaptor.getAllValues());
+ }
+
private void verifyRemoveDownstreamRule(@Nullable InOrder inOrder,
@NonNull final Ipv6DownstreamRule rule) throws Exception {
if (mDeps.isAtLeastS()) {
@@ -785,10 +840,11 @@
final InOrder inOrder = inOrder(mNetd, mBpfUpstream6Map, mBpfDownstream6Map, mBpfLimitMap,
mBpfStatsMap);
final Ipv6UpstreamRule upstreamRule = buildTestUpstreamRule(
- mobileIfIndex, DOWNSTREAM_IFINDEX, DOWNSTREAM_MAC);
+ mobileIfIndex, DOWNSTREAM_IFINDEX, UPSTREAM_PREFIX, DOWNSTREAM_MAC);
final Ipv6DownstreamRule downstreamRule = buildTestDownstreamRule(
mobileIfIndex, NEIGH_A, MAC_A);
- coordinator.updateAllIpv6Rules(mIpServer, DOWNSTREAM_IFACE_PARAMS, mobileIfIndex);
+ coordinator.updateAllIpv6Rules(
+ mIpServer, DOWNSTREAM_IFACE_PARAMS, mobileIfIndex, UPSTREAM_PREFIXES);
verifyTetherOffloadSetInterfaceQuota(inOrder, mobileIfIndex, QUOTA_UNLIMITED,
true /* isInit */);
verifyAddUpstreamRule(inOrder, upstreamRule);
@@ -798,7 +854,8 @@
// Removing the last rule on current upstream immediately sends the cleanup stuff to BPF.
updateStatsEntryForTetherOffloadGetAndClearStats(
buildTestTetherStatsParcel(mobileIfIndex, 0, 0, 0, 0));
- coordinator.updateAllIpv6Rules(mIpServer, DOWNSTREAM_IFACE_PARAMS, 0);
+ coordinator.updateAllIpv6Rules(
+ mIpServer, DOWNSTREAM_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
verifyRemoveDownstreamRule(inOrder, downstreamRule);
verifyRemoveUpstreamRule(inOrder, upstreamRule);
verifyTetherOffloadGetAndClearStats(inOrder, mobileIfIndex);
@@ -998,11 +1055,10 @@
}
@NonNull
- private static Ipv6UpstreamRule buildTestUpstreamRule(
- int upstreamIfindex, int downstreamIfindex, @NonNull MacAddress inDstMac) {
- return new Ipv6UpstreamRule(upstreamIfindex, downstreamIfindex,
- IPV6_ZERO_PREFIX, inDstMac, MacAddress.ALL_ZEROS_ADDRESS,
- MacAddress.ALL_ZEROS_ADDRESS);
+ private static Ipv6UpstreamRule buildTestUpstreamRule(int upstreamIfindex,
+ int downstreamIfindex, @NonNull IpPrefix sourcePrefix, @NonNull MacAddress inDstMac) {
+ return new Ipv6UpstreamRule(upstreamIfindex, downstreamIfindex, sourcePrefix, inDstMac,
+ MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS);
}
@NonNull
@@ -1054,9 +1110,10 @@
// Set the unlimited quota as default if the service has never applied a data limit for a
// given upstream. Note that the data limit only be applied on an upstream which has rules.
final Ipv6UpstreamRule rule = buildTestUpstreamRule(
- mobileIfIndex, DOWNSTREAM_IFINDEX, DOWNSTREAM_MAC);
+ mobileIfIndex, DOWNSTREAM_IFINDEX, UPSTREAM_PREFIX, DOWNSTREAM_MAC);
final InOrder inOrder = inOrder(mNetd, mBpfUpstream6Map, mBpfLimitMap, mBpfStatsMap);
- coordinator.updateAllIpv6Rules(mIpServer, DOWNSTREAM_IFACE_PARAMS, mobileIfIndex);
+ coordinator.updateAllIpv6Rules(
+ mIpServer, DOWNSTREAM_IFACE_PARAMS, mobileIfIndex, UPSTREAM_PREFIXES);
verifyTetherOffloadSetInterfaceQuota(inOrder, mobileIfIndex, QUOTA_UNLIMITED,
true /* isInit */);
verifyAddUpstreamRule(inOrder, rule);
@@ -1104,28 +1161,32 @@
// Adding the first rule on current upstream immediately sends the quota to BPF.
final Ipv6UpstreamRule ruleA = buildTestUpstreamRule(
- mobileIfIndex, DOWNSTREAM_IFINDEX, DOWNSTREAM_MAC);
- coordinator.updateAllIpv6Rules(mIpServer, DOWNSTREAM_IFACE_PARAMS, mobileIfIndex);
+ mobileIfIndex, DOWNSTREAM_IFINDEX, UPSTREAM_PREFIX, DOWNSTREAM_MAC);
+ coordinator.updateAllIpv6Rules(
+ mIpServer, DOWNSTREAM_IFACE_PARAMS, mobileIfIndex, UPSTREAM_PREFIXES);
verifyTetherOffloadSetInterfaceQuota(inOrder, mobileIfIndex, limit, true /* isInit */);
verifyAddUpstreamRule(inOrder, ruleA);
inOrder.verifyNoMoreInteractions();
// Adding the second rule on current upstream does not send the quota to BPF.
final Ipv6UpstreamRule ruleB = buildTestUpstreamRule(
- mobileIfIndex, DOWNSTREAM_IFINDEX2, DOWNSTREAM_MAC2);
- coordinator.updateAllIpv6Rules(mIpServer2, DOWNSTREAM_IFACE_PARAMS2, mobileIfIndex);
+ mobileIfIndex, DOWNSTREAM_IFINDEX2, UPSTREAM_PREFIX, DOWNSTREAM_MAC2);
+ coordinator.updateAllIpv6Rules(
+ mIpServer2, DOWNSTREAM_IFACE_PARAMS2, mobileIfIndex, UPSTREAM_PREFIXES);
verifyAddUpstreamRule(inOrder, ruleB);
verifyNeverTetherOffloadSetInterfaceQuota(inOrder);
// Removing the second rule on current upstream does not send the quota to BPF.
- coordinator.updateAllIpv6Rules(mIpServer2, DOWNSTREAM_IFACE_PARAMS2, 0);
+ coordinator.updateAllIpv6Rules(
+ mIpServer2, DOWNSTREAM_IFACE_PARAMS2, NO_UPSTREAM, NO_PREFIXES);
verifyRemoveUpstreamRule(inOrder, ruleB);
verifyNeverTetherOffloadSetInterfaceQuota(inOrder);
// Removing the last rule on current upstream immediately sends the cleanup stuff to BPF.
updateStatsEntryForTetherOffloadGetAndClearStats(
buildTestTetherStatsParcel(mobileIfIndex, 0, 0, 0, 0));
- coordinator.updateAllIpv6Rules(mIpServer, DOWNSTREAM_IFACE_PARAMS, 0);
+ coordinator.updateAllIpv6Rules(
+ mIpServer, DOWNSTREAM_IFACE_PARAMS, NO_UPSTREAM, NO_PREFIXES);
verifyRemoveUpstreamRule(inOrder, ruleA);
verifyTetherOffloadGetAndClearStats(inOrder, mobileIfIndex);
inOrder.verifyNoMoreInteractions();
@@ -1157,13 +1218,14 @@
// [1] Adding rules on the upstream Ethernet.
// Note that the default data limit is applied after the first rule is added.
final Ipv6UpstreamRule ethernetUpstreamRule = buildTestUpstreamRule(
- ethIfIndex, DOWNSTREAM_IFINDEX, DOWNSTREAM_MAC);
+ ethIfIndex, DOWNSTREAM_IFINDEX, UPSTREAM_PREFIX, DOWNSTREAM_MAC);
final Ipv6DownstreamRule ethernetRuleA = buildTestDownstreamRule(
ethIfIndex, NEIGH_A, MAC_A);
final Ipv6DownstreamRule ethernetRuleB = buildTestDownstreamRule(
ethIfIndex, NEIGH_B, MAC_B);
- coordinator.updateAllIpv6Rules(mIpServer, DOWNSTREAM_IFACE_PARAMS, ethIfIndex);
+ coordinator.updateAllIpv6Rules(
+ mIpServer, DOWNSTREAM_IFACE_PARAMS, ethIfIndex, UPSTREAM_PREFIXES);
verifyTetherOffloadSetInterfaceQuota(inOrder, ethIfIndex, QUOTA_UNLIMITED,
true /* isInit */);
verifyAddUpstreamRule(inOrder, ethernetUpstreamRule);
@@ -1174,7 +1236,9 @@
// [2] Update the existing rules from Ethernet to cellular.
final Ipv6UpstreamRule mobileUpstreamRule = buildTestUpstreamRule(
- mobileIfIndex, DOWNSTREAM_IFINDEX, DOWNSTREAM_MAC);
+ mobileIfIndex, DOWNSTREAM_IFINDEX, UPSTREAM_PREFIX, DOWNSTREAM_MAC);
+ final Ipv6UpstreamRule mobileUpstreamRule2 = buildTestUpstreamRule(
+ mobileIfIndex, DOWNSTREAM_IFINDEX, UPSTREAM_PREFIX2, DOWNSTREAM_MAC);
final Ipv6DownstreamRule mobileRuleA = buildTestDownstreamRule(
mobileIfIndex, NEIGH_A, MAC_A);
final Ipv6DownstreamRule mobileRuleB = buildTestDownstreamRule(
@@ -1183,15 +1247,16 @@
buildTestTetherStatsParcel(ethIfIndex, 10, 20, 30, 40));
// Update the existing rules for upstream changes. The rules are removed and re-added one
- // by one for updating upstream interface index by #tetherOffloadRuleUpdate.
- coordinator.updateAllIpv6Rules(mIpServer, DOWNSTREAM_IFACE_PARAMS, mobileIfIndex);
+ // by one for updating upstream interface index and prefixes by #tetherOffloadRuleUpdate.
+ coordinator.updateAllIpv6Rules(
+ mIpServer, DOWNSTREAM_IFACE_PARAMS, mobileIfIndex, UPSTREAM_PREFIXES2);
verifyRemoveDownstreamRule(inOrder, ethernetRuleA);
verifyRemoveDownstreamRule(inOrder, ethernetRuleB);
verifyRemoveUpstreamRule(inOrder, ethernetUpstreamRule);
verifyTetherOffloadGetAndClearStats(inOrder, ethIfIndex);
verifyTetherOffloadSetInterfaceQuota(inOrder, mobileIfIndex, QUOTA_UNLIMITED,
true /* isInit */);
- verifyAddUpstreamRule(inOrder, mobileUpstreamRule);
+ verifyAddUpstreamRules(inOrder, Set.of(mobileUpstreamRule, mobileUpstreamRule2));
verifyAddDownstreamRule(inOrder, mobileRuleA);
verifyAddDownstreamRule(inOrder, mobileRuleB);
@@ -1201,7 +1266,7 @@
coordinator.clearAllIpv6Rules(mIpServer);
verifyRemoveDownstreamRule(inOrder, mobileRuleA);
verifyRemoveDownstreamRule(inOrder, mobileRuleB);
- verifyRemoveUpstreamRule(inOrder, mobileUpstreamRule);
+ verifyRemoveUpstreamRules(inOrder, Set.of(mobileUpstreamRule, mobileUpstreamRule2));
verifyTetherOffloadGetAndClearStats(inOrder, mobileIfIndex);
// [4] Force pushing stats update to verify that the last diff of stats is reported on all
@@ -1264,8 +1329,8 @@
assertEquals(1, rules.size());
// The rule can't be updated.
- coordinator.updateAllIpv6Rules(
- mIpServer, DOWNSTREAM_IFACE_PARAMS, rule.upstreamIfindex + 1 /* new */);
+ coordinator.updateAllIpv6Rules(mIpServer, DOWNSTREAM_IFACE_PARAMS,
+ rule.upstreamIfindex + 1 /* new */, UPSTREAM_PREFIXES);
verifyNeverRemoveDownstreamRule();
verifyNeverAddDownstreamRule();
rules = coordinator.getIpv6DownstreamRulesForTesting().get(mIpServer);
@@ -1561,12 +1626,12 @@
//
// @param coordinator BpfCoordinator instance.
// @param upstreamIfindex upstream interface index. can be the following values.
- // INVALID_IFINDEX: no upstream interface
+ // NO_UPSTREAM: no upstream interface
// UPSTREAM_IFINDEX: CELLULAR (raw ip interface)
// UPSTREAM_IFINDEX2: WIFI (ethernet interface)
private void setUpstreamInformationTo(final BpfCoordinator coordinator,
@Nullable Integer upstreamIfindex) {
- if (upstreamIfindex == INVALID_IFINDEX) {
+ if (upstreamIfindex == NO_UPSTREAM) {
coordinator.updateUpstreamNetworkState(null);
return;
}
@@ -1706,7 +1771,8 @@
final BpfCoordinator coordinator = makeBpfCoordinator();
coordinator.maybeAddUpstreamToLookupTable(UPSTREAM_IFINDEX, UPSTREAM_IFACE);
- coordinator.updateAllIpv6Rules(mIpServer, DOWNSTREAM_IFACE_PARAMS, UPSTREAM_IFINDEX);
+ coordinator.updateAllIpv6Rules(
+ mIpServer, DOWNSTREAM_IFACE_PARAMS, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
verify(mBpfDevMap).updateEntry(eq(new TetherDevKey(UPSTREAM_IFINDEX)),
eq(new TetherDevValue(UPSTREAM_IFINDEX)));
verify(mBpfDevMap).updateEntry(eq(new TetherDevKey(DOWNSTREAM_IFINDEX)),
@@ -1715,7 +1781,8 @@
// Adding the second downstream, only the second downstream ifindex is added to DevMap,
// the existing upstream ifindex won't be added again.
- coordinator.updateAllIpv6Rules(mIpServer2, DOWNSTREAM_IFACE_PARAMS2, UPSTREAM_IFINDEX);
+ coordinator.updateAllIpv6Rules(
+ mIpServer2, DOWNSTREAM_IFACE_PARAMS2, UPSTREAM_IFINDEX, UPSTREAM_PREFIXES);
verify(mBpfDevMap).updateEntry(eq(new TetherDevKey(DOWNSTREAM_IFINDEX2)),
eq(new TetherDevValue(DOWNSTREAM_IFINDEX2)));
verify(mBpfDevMap, never()).updateEntry(eq(new TetherDevKey(UPSTREAM_IFINDEX)),
@@ -1996,6 +2063,11 @@
100 /* nonzero, CT_NEW */);
}
+ private static long prefixToLong(IpPrefix prefix) {
+ byte[] prefixBytes = Arrays.copyOf(prefix.getRawAddress(), 8);
+ return ByteBuffer.wrap(prefixBytes).getLong();
+ }
+
void checkRule4ExistInUpstreamDownstreamMap() throws Exception {
assertEquals(UPSTREAM4_RULE_VALUE_A, mBpfUpstream4Map.getValue(UPSTREAM4_RULE_KEY_A));
assertEquals(DOWNSTREAM4_RULE_VALUE_A, mBpfDownstream4Map.getValue(
@@ -2113,7 +2185,7 @@
// [3] Switch upstream from the first upstream (rawip, bpf supported) to no upstream. Clear
// all rules.
- setUpstreamInformationTo(coordinator, INVALID_IFINDEX);
+ setUpstreamInformationTo(coordinator, NO_UPSTREAM);
checkRule4NotExistInUpstreamDownstreamMap();
// Client information should be not deleted.
@@ -2180,14 +2252,15 @@
public void testIpv6ForwardingRuleToString() throws Exception {
final Ipv6DownstreamRule downstreamRule = buildTestDownstreamRule(UPSTREAM_IFINDEX, NEIGH_A,
MAC_A);
- assertEquals("upstreamIfindex: 1001, downstreamIfindex: 2001, address: 2001:db8::1, "
+ assertEquals("upstreamIfindex: 1001, downstreamIfindex: 2001, address: 2001:db8:0:1234::1, "
+ "srcMac: 12:34:56:78:90:ab, dstMac: 00:00:00:00:00:0a",
downstreamRule.toString());
final Ipv6UpstreamRule upstreamRule = buildTestUpstreamRule(
- UPSTREAM_IFINDEX, DOWNSTREAM_IFINDEX, DOWNSTREAM_MAC);
- assertEquals("upstreamIfindex: 1001, downstreamIfindex: 2001, sourcePrefix: ::/64, "
- + "inDstMac: 12:34:56:78:90:ab, outSrcMac: 00:00:00:00:00:00, "
- + "outDstMac: 00:00:00:00:00:00", upstreamRule.toString());
+ UPSTREAM_IFINDEX, DOWNSTREAM_IFINDEX, UPSTREAM_PREFIX, DOWNSTREAM_MAC);
+ assertEquals("upstreamIfindex: 1001, downstreamIfindex: 2001, "
+ + "sourcePrefix: 2001:db8:0:1234::/64, inDstMac: 12:34:56:78:90:ab, "
+ + "outSrcMac: 00:00:00:00:00:00, outDstMac: 00:00:00:00:00:00",
+ upstreamRule.toString());
}
private void verifyDump(@NonNull final BpfCoordinator coordinator) {
@@ -2237,8 +2310,9 @@
final Ipv6DownstreamRule rule = buildTestDownstreamRule(UPSTREAM_IFINDEX, NEIGH_A, MAC_A);
mBpfDownstream6Map.insertEntry(rule.makeTetherDownstream6Key(), rule.makeTether6Value());
+ final long prefix64 = prefixToLong(UPSTREAM_PREFIX);
final TetherUpstream6Key upstream6Key = new TetherUpstream6Key(DOWNSTREAM_IFINDEX,
- DOWNSTREAM_MAC, 0);
+ DOWNSTREAM_MAC, prefix64);
final Tether6Value upstream6Value = new Tether6Value(UPSTREAM_IFINDEX,
MacAddress.ALL_ZEROS_ADDRESS, MacAddress.ALL_ZEROS_ADDRESS,
ETH_P_IPV6, NetworkStackConstants.ETHER_MTU);
diff --git a/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java b/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java
index ba39f22..f89ee8e 100644
--- a/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/TetheringTest.java
@@ -2880,24 +2880,33 @@
final Network wifiNetwork = new Network(200);
final Network[] allNetworks = { wifiNetwork };
doReturn(allNetworks).when(mCm).getAllNetworks();
+ InOrder inOrder = inOrder(mUsbManager, mNetd);
runUsbTethering(null);
+
+ inOrder.verify(mNetd).tetherInterfaceAdd(TEST_RNDIS_IFNAME);
+
final ArgumentCaptor<InterfaceConfigurationParcel> ifaceConfigCaptor =
ArgumentCaptor.forClass(InterfaceConfigurationParcel.class);
verify(mNetd).interfaceSetCfg(ifaceConfigCaptor.capture());
final String ipv4Address = ifaceConfigCaptor.getValue().ipv4Addr;
verify(mDhcpServer, timeout(DHCPSERVER_START_TIMEOUT_MS).times(1)).startWithCallbacks(
any(), any());
- reset(mUsbManager);
// Cause a prefix conflict by assigning a /30 out of the downstream's /24 to the upstream.
updateV4Upstream(new LinkAddress(InetAddresses.parseNumericAddress(ipv4Address), 30),
wifiNetwork, TEST_WIFI_IFNAME, TRANSPORT_WIFI);
// verify turn off usb tethering
- verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_NONE);
+ inOrder.verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_NONE);
sendUsbBroadcast(true, true, -1 /* function */);
mLooper.dispatchAll();
+ inOrder.verify(mNetd).tetherInterfaceRemove(TEST_RNDIS_IFNAME);
+
// verify restart usb tethering
- verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_RNDIS);
+ inOrder.verify(mUsbManager).setCurrentFunctions(UsbManager.FUNCTION_RNDIS);
+
+ sendUsbBroadcast(true, true, TETHER_USB_RNDIS_FUNCTION);
+ mLooper.dispatchAll();
+ inOrder.verify(mNetd).tetherInterfaceAdd(TEST_RNDIS_IFNAME);
}
@Test
diff --git a/Tethering/tests/unit/src/com/android/networkstack/tethering/util/StateMachineShimTest.kt b/Tethering/tests/unit/src/com/android/networkstack/tethering/util/StateMachineShimTest.kt
new file mode 100644
index 0000000..2c4df76
--- /dev/null
+++ b/Tethering/tests/unit/src/com/android/networkstack/tethering/util/StateMachineShimTest.kt
@@ -0,0 +1,128 @@
+/**
+ * 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.networkstack.tethering.util
+
+import android.os.Looper
+import androidx.test.ext.junit.runners.AndroidJUnit4
+import androidx.test.filters.SmallTest
+import com.android.internal.util.State
+import com.android.networkstack.tethering.util.StateMachineShim.AsyncStateMachine
+import com.android.networkstack.tethering.util.StateMachineShim.Dependencies
+import com.android.networkstack.tethering.util.SyncStateMachine.StateInfo
+import kotlin.test.assertFailsWith
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.Mockito.inOrder
+import org.mockito.Mockito.mock
+import org.mockito.Mockito.verify
+import org.mockito.Mockito.verifyNoMoreInteractions
+
+@RunWith(AndroidJUnit4::class)
+@SmallTest
+class StateMachineShimTest {
+ private val mSyncSM = mock(SyncStateMachine::class.java)
+ private val mAsyncSM = mock(AsyncStateMachine::class.java)
+ private val mState1 = mock(State::class.java)
+ private val mState2 = mock(State::class.java)
+
+ inner class MyDependencies() : Dependencies() {
+
+ override fun makeSyncStateMachine(name: String, thread: Thread) = mSyncSM
+
+ override fun makeAsyncStateMachine(name: String, looper: Looper) = mAsyncSM
+ }
+
+ @Test
+ fun testUsingSyncStateMachine() {
+ val inOrder = inOrder(mSyncSM, mAsyncSM)
+ val shimUsingSyncSM = StateMachineShim("ShimTest", null, MyDependencies())
+ shimUsingSyncSM.start(mState1)
+ inOrder.verify(mSyncSM).start(mState1)
+
+ val allStates = ArrayList<StateInfo>()
+ allStates.add(StateInfo(mState1, null))
+ allStates.add(StateInfo(mState2, mState1))
+ shimUsingSyncSM.addAllStates(allStates)
+ inOrder.verify(mSyncSM).addAllStates(allStates)
+
+ shimUsingSyncSM.transitionTo(mState1)
+ inOrder.verify(mSyncSM).transitionTo(mState1)
+
+ val what = 10
+ shimUsingSyncSM.sendMessage(what)
+ inOrder.verify(mSyncSM).processMessage(what, 0, 0, null)
+ val obj = Object()
+ shimUsingSyncSM.sendMessage(what, obj)
+ inOrder.verify(mSyncSM).processMessage(what, 0, 0, obj)
+ val arg1 = 11
+ shimUsingSyncSM.sendMessage(what, arg1)
+ inOrder.verify(mSyncSM).processMessage(what, arg1, 0, null)
+ val arg2 = 12
+ shimUsingSyncSM.sendMessage(what, arg1, arg2, obj)
+ inOrder.verify(mSyncSM).processMessage(what, arg1, arg2, obj)
+
+ assertFailsWith(IllegalStateException::class) {
+ shimUsingSyncSM.sendMessageDelayedToAsyncSM(what, 1000 /* delayMillis */)
+ }
+
+ shimUsingSyncSM.sendSelfMessageToSyncSM(what, obj)
+ inOrder.verify(mSyncSM).sendSelfMessage(what, 0, 0, obj)
+
+ verifyNoMoreInteractions(mSyncSM, mAsyncSM)
+ }
+
+ @Test
+ fun testUsingAsyncStateMachine() {
+ val inOrder = inOrder(mSyncSM, mAsyncSM)
+ val shimUsingAsyncSM = StateMachineShim("ShimTest", mock(Looper::class.java),
+ MyDependencies())
+ shimUsingAsyncSM.start(mState1)
+ inOrder.verify(mAsyncSM).setInitialState(mState1)
+ inOrder.verify(mAsyncSM).start()
+
+ val allStates = ArrayList<StateInfo>()
+ allStates.add(StateInfo(mState1, null))
+ allStates.add(StateInfo(mState2, mState1))
+ shimUsingAsyncSM.addAllStates(allStates)
+ inOrder.verify(mAsyncSM).addState(mState1, null)
+ inOrder.verify(mAsyncSM).addState(mState2, mState1)
+
+ shimUsingAsyncSM.transitionTo(mState1)
+ inOrder.verify(mAsyncSM).transitionTo(mState1)
+
+ val what = 10
+ shimUsingAsyncSM.sendMessage(what)
+ inOrder.verify(mAsyncSM).sendMessage(what, 0, 0, null)
+ val obj = Object()
+ shimUsingAsyncSM.sendMessage(what, obj)
+ inOrder.verify(mAsyncSM).sendMessage(what, 0, 0, obj)
+ val arg1 = 11
+ shimUsingAsyncSM.sendMessage(what, arg1)
+ inOrder.verify(mAsyncSM).sendMessage(what, arg1, 0, null)
+ val arg2 = 12
+ shimUsingAsyncSM.sendMessage(what, arg1, arg2, obj)
+ inOrder.verify(mAsyncSM).sendMessage(what, arg1, arg2, obj)
+
+ shimUsingAsyncSM.sendMessageDelayedToAsyncSM(what, 1000 /* delayMillis */)
+ inOrder.verify(mAsyncSM).sendMessageDelayed(what, 1000)
+
+ assertFailsWith(IllegalStateException::class) {
+ shimUsingAsyncSM.sendSelfMessageToSyncSM(what, obj)
+ }
+
+ verifyNoMoreInteractions(mSyncSM, mAsyncSM)
+ }
+}
diff --git a/bpf_progs/offload.c b/bpf_progs/offload.c
index 35b8eea..90f96a1 100644
--- a/bpf_progs/offload.c
+++ b/bpf_progs/offload.c
@@ -198,7 +198,8 @@
TetherUpstream6Key ku = {
.iif = skb->ifindex,
- .src64 = 0,
+ // Retrieve the first 64 bits of the source IPv6 address in network order
+ .src64 = *(uint64_t*)&(ip6->saddr.s6_addr32[0]),
};
if (is_ethernet) __builtin_memcpy(stream.down ? kd.dstMac : ku.dstMac, eth->h_dest, ETH_ALEN);
diff --git a/framework-t/api/system-current.txt b/framework-t/api/system-current.txt
index 6c98a4f..23510e1 100644
--- a/framework-t/api/system-current.txt
+++ b/framework-t/api/system-current.txt
@@ -492,12 +492,12 @@
field @NonNull public static final android.os.Parcelable.Creator<android.net.thread.PendingOperationalDataset> CREATOR;
}
- @FlaggedApi("com.android.net.thread.flags.thread_enabled") public class ThreadNetworkController {
+ @FlaggedApi("com.android.net.thread.flags.thread_enabled") public final class ThreadNetworkController {
method public int getThreadVersion();
field public static final int THREAD_VERSION_1_3 = 4; // 0x4
}
- @FlaggedApi("com.android.net.thread.flags.thread_enabled") public class ThreadNetworkManager {
+ @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/netbpfload/NetBpfLoad.cpp b/netbpfload/NetBpfLoad.cpp
index d150373..6152287 100644
--- a/netbpfload/NetBpfLoad.cpp
+++ b/netbpfload/NetBpfLoad.cpp
@@ -38,6 +38,7 @@
#include <sys/stat.h>
#include <sys/types.h>
+#include <android/api-level.h>
#include <android-base/logging.h>
#include <android-base/macros.h>
#include <android-base/properties.h>
@@ -172,6 +173,9 @@
(void)argc;
android::base::InitLogging(argv, &android::base::KernelLogger);
+ const int device_api_level = android_get_device_api_level();
+ const bool isAtLeastU = (device_api_level >= __ANDROID_API_U__);
+
if (!android::bpf::isAtLeastKernelVersion(4, 19, 0)) {
ALOGE("Android U QPR2 requires kernel 4.19.");
return 1;
@@ -208,24 +212,27 @@
return 1;
}
- // Linux 5.16-rc1 changed the default to 2 (disabled but changeable), but we need 0 (enabled)
- // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on pre-5.13,
- // on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
- if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
- android::bpf::isAtLeastKernelVersion(5, 13, 0)) return 1;
+ if (isAtLeastU) {
+ // Linux 5.16-rc1 changed the default to 2 (disabled but changeable),
+ // but we need 0 (enabled)
+ // (this writeFile is known to fail on at least 4.19, but always defaults to 0 on
+ // pre-5.13, on 5.13+ it depends on CONFIG_BPF_UNPRIV_DEFAULT_OFF)
+ if (writeProcSysFile("/proc/sys/kernel/unprivileged_bpf_disabled", "0\n") &&
+ android::bpf::isAtLeastKernelVersion(5, 13, 0)) return 1;
- // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
- // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
- // (Note: this (open) will fail with ENOENT 'No such file or directory' if
- // kernel does not have CONFIG_BPF_JIT=y)
- // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
- // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
- if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
+ // Enable the eBPF JIT -- but do note that on 64-bit kernels it is likely
+ // already force enabled by the kernel config option BPF_JIT_ALWAYS_ON.
+ // (Note: this (open) will fail with ENOENT 'No such file or directory' if
+ // kernel does not have CONFIG_BPF_JIT=y)
+ // BPF_JIT is required by R VINTF (which means 4.14/4.19/5.4 kernels),
+ // but 4.14/4.19 were released with P & Q, and only 5.4 is new in R+.
+ if (writeProcSysFile("/proc/sys/net/core/bpf_jit_enable", "1\n")) return 1;
- // Enable JIT kallsyms export for privileged users only
- // (Note: this (open) will fail with ENOENT 'No such file or directory' if
- // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
- if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
+ // Enable JIT kallsyms export for privileged users only
+ // (Note: this (open) will fail with ENOENT 'No such file or directory' if
+ // kernel does not have CONFIG_HAVE_EBPF_JIT=y)
+ if (writeProcSysFile("/proc/sys/net/core/bpf_jit_kallsyms", "1\n")) return 1;
+ }
// Create all the pin subdirectories
// (this must be done first to allow selinux_context and pin_subdir functionality,
diff --git a/service-t/src/com/android/server/net/NetworkStatsEventLogger.java b/service-t/src/com/android/server/net/NetworkStatsEventLogger.java
new file mode 100644
index 0000000..679837a
--- /dev/null
+++ b/service-t/src/com/android/server/net/NetworkStatsEventLogger.java
@@ -0,0 +1,152 @@
+/*
+ * 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.net;
+
+import static com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.util.IndentingPrintWriter;
+import android.util.LocalLog;
+
+import com.android.internal.annotations.VisibleForTesting;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * Helper class for NetworkStatsService to log events.
+ *
+ * @hide
+ */
+public class NetworkStatsEventLogger {
+ static final int POLL_REASON_DUMPSYS = 0;
+ static final int POLL_REASON_FORCE_UPDATE = 1;
+ static final int POLL_REASON_GLOBAL_ALERT = 2;
+ static final int POLL_REASON_NETWORK_STATUS_CHANGED = 3;
+ static final int POLL_REASON_OPEN_SESSION = 4;
+ static final int POLL_REASON_PERIODIC = 5;
+ static final int POLL_REASON_RAT_CHANGED = 6;
+ static final int POLL_REASON_REG_CALLBACK = 7;
+ static final int POLL_REASON_REMOVE_UIDS = 8;
+ static final int POLL_REASON_UPSTREAM_CHANGED = 9;
+
+ @Retention(RetentionPolicy.SOURCE)
+ @IntDef(prefix = { "POLL_REASON_" }, value = {
+ POLL_REASON_DUMPSYS,
+ POLL_REASON_FORCE_UPDATE,
+ POLL_REASON_GLOBAL_ALERT,
+ POLL_REASON_NETWORK_STATUS_CHANGED,
+ POLL_REASON_OPEN_SESSION,
+ POLL_REASON_PERIODIC,
+ POLL_REASON_RAT_CHANGED,
+ POLL_REASON_REMOVE_UIDS,
+ POLL_REASON_REG_CALLBACK,
+ POLL_REASON_UPSTREAM_CHANGED
+ })
+ public @interface PollReason {
+ }
+ static final int MAX_POLL_REASON = POLL_REASON_UPSTREAM_CHANGED;
+
+ @VisibleForTesting(visibility = PRIVATE)
+ public static final int MAX_EVENTS_LOGS = 50;
+ private final LocalLog mEventChanges = new LocalLog(MAX_EVENTS_LOGS);
+ private final int[] mPollEventCounts = new int[MAX_POLL_REASON + 1];
+
+ /**
+ * Log a poll event.
+ *
+ * @param flags Flags used when polling. See NetworkStatsService#FLAG_PERSIST_*.
+ * @param event The event of polling to be logged.
+ */
+ public void logPollEvent(int flags, @NonNull PollEvent event) {
+ mEventChanges.log("Poll(flags=" + flags + ", " + event + ")");
+ mPollEventCounts[event.reason]++;
+ }
+
+ /**
+ * Print poll counts per reason into the given stream.
+ */
+ @VisibleForTesting(visibility = PRIVATE)
+ public void dumpPollCountsPerReason(@NonNull IndentingPrintWriter pw) {
+ pw.println("Poll counts per reason:");
+ pw.increaseIndent();
+ for (int i = 0; i <= MAX_POLL_REASON; i++) {
+ pw.println(PollEvent.pollReasonNameOf(i) + ": " + mPollEventCounts[i]);
+ }
+ pw.decreaseIndent();
+ pw.println();
+ }
+
+ /**
+ * Print recent poll events into the given stream.
+ */
+ @VisibleForTesting(visibility = PRIVATE)
+ public void dumpRecentPollEvents(@NonNull IndentingPrintWriter pw) {
+ pw.println("Recent poll events:");
+ pw.increaseIndent();
+ mEventChanges.reverseDump(pw);
+ pw.decreaseIndent();
+ pw.println();
+ }
+
+ /**
+ * Print the object's state into the given stream.
+ */
+ public void dump(@NonNull IndentingPrintWriter pw) {
+ dumpPollCountsPerReason(pw);
+ dumpRecentPollEvents(pw);
+ }
+
+ public static class PollEvent {
+ public final int reason;
+
+ public PollEvent(@PollReason int reason) {
+ if (reason < 0 || reason > MAX_POLL_REASON) {
+ throw new IllegalArgumentException("Unsupported poll reason: " + reason);
+ }
+ this.reason = reason;
+ }
+
+ @Override
+ public String toString() {
+ return "PollEvent{" + "reason=" + pollReasonNameOf(reason) + "}";
+ }
+
+ /**
+ * Get the name of the given reason.
+ *
+ * If the reason does not have a String representation, returns its integer representation.
+ */
+ @NonNull
+ public static String pollReasonNameOf(@PollReason int reason) {
+ switch (reason) {
+ case POLL_REASON_DUMPSYS: return "DUMPSYS";
+ case POLL_REASON_FORCE_UPDATE: return "FORCE_UPDATE";
+ case POLL_REASON_GLOBAL_ALERT: return "GLOBAL_ALERT";
+ case POLL_REASON_NETWORK_STATUS_CHANGED: return "NETWORK_STATUS_CHANGED";
+ case POLL_REASON_OPEN_SESSION: return "OPEN_SESSION";
+ case POLL_REASON_PERIODIC: return "PERIODIC";
+ case POLL_REASON_RAT_CHANGED: return "RAT_CHANGED";
+ case POLL_REASON_REMOVE_UIDS: return "REMOVE_UIDS";
+ case POLL_REASON_REG_CALLBACK: return "REG_CALLBACK";
+ case POLL_REASON_UPSTREAM_CHANGED: return "UPSTREAM_CHANGED";
+ default: return Integer.toString(reason);
+ }
+ }
+ }
+}
diff --git a/service-t/src/com/android/server/net/NetworkStatsService.java b/service-t/src/com/android/server/net/NetworkStatsService.java
index cc67550..46afd31 100644
--- a/service-t/src/com/android/server/net/NetworkStatsService.java
+++ b/service-t/src/com/android/server/net/NetworkStatsService.java
@@ -66,6 +66,17 @@
import static com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE;
import static com.android.net.module.util.NetworkCapabilitiesUtils.getDisplayTransport;
import static com.android.net.module.util.NetworkStatsUtils.LIMIT_GLOBAL_ALERT;
+import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_PERIODIC;
+import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_DUMPSYS;
+import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_FORCE_UPDATE;
+import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_GLOBAL_ALERT;
+import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_NETWORK_STATUS_CHANGED;
+import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_OPEN_SESSION;
+import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_RAT_CHANGED;
+import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_REG_CALLBACK;
+import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_REMOVE_UIDS;
+import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_UPSTREAM_CHANGED;
+import static com.android.server.net.NetworkStatsEventLogger.PollEvent;
import android.annotation.NonNull;
import android.annotation.Nullable;
@@ -281,6 +292,8 @@
static final String NETSTATS_IMPORT_ATTEMPTS_COUNTER_NAME = "import.attempts";
static final String NETSTATS_IMPORT_SUCCESSES_COUNTER_NAME = "import.successes";
static final String NETSTATS_IMPORT_FALLBACKS_COUNTER_NAME = "import.fallbacks";
+ static final String CONFIG_ENABLE_NETWORK_STATS_EVENT_LOGGER =
+ "enable_network_stats_event_logger";
private final Context mContext;
private final NetworkStatsFactory mStatsFactory;
@@ -441,6 +454,7 @@
* Map from key {@code OpenSessionKey} to count of opened sessions. This is for recording
* the caller of open session and it is only for debugging.
*/
+ // TODO: Move to NetworkStatsEventLogger to centralize event logging.
@GuardedBy("mOpenSessionCallsLock")
private final HashMap<OpenSessionKey, Integer> mOpenSessionCallsPerCaller = new HashMap<>();
@@ -513,20 +527,21 @@
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_PERFORM_POLL: {
- performPoll(FLAG_PERSIST_ALL);
+ performPoll(FLAG_PERSIST_ALL, maybeCreatePollEvent((int) msg.obj));
break;
}
case MSG_NOTIFY_NETWORK_STATUS: {
synchronized (mStatsLock) {
// If no cached states, ignore.
if (mLastNetworkStateSnapshots == null) break;
- handleNotifyNetworkStatus(
- mDefaultNetworks, mLastNetworkStateSnapshots, mActiveIface);
+ handleNotifyNetworkStatus(mDefaultNetworks, mLastNetworkStateSnapshots,
+ mActiveIface, maybeCreatePollEvent((int) msg.obj));
}
break;
}
case MSG_PERFORM_POLL_REGISTER_ALERT: {
- performPoll(FLAG_PERSIST_NETWORK);
+ performPoll(FLAG_PERSIST_NETWORK,
+ maybeCreatePollEvent(POLL_REASON_GLOBAL_ALERT));
registerGlobalAlert();
break;
}
@@ -612,6 +627,13 @@
mStatsMapB = mDeps.getStatsMapB();
mAppUidStatsMap = mDeps.getAppUidStatsMap();
mIfaceStatsMap = mDeps.getIfaceStatsMap();
+ // To prevent any possible races, the flag is not allowed to change until rebooting.
+ mSupportEventLogger = mDeps.supportEventLogger(mContext);
+ if (mSupportEventLogger) {
+ mEventLogger = new NetworkStatsEventLogger();
+ } else {
+ mEventLogger = null;
+ }
// TODO: Remove bpfNetMaps creation and always start SkDestroyListener
// Following code is for the experiment to verify the SkDestroyListener refactoring. Based
@@ -840,6 +862,14 @@
IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap, Handler handler) {
return new SkDestroyListener(cookieTagMap, handler, new SharedLog(TAG));
}
+
+ /**
+ * Get whether event logger feature is supported.
+ */
+ public boolean supportEventLogger(Context ctx) {
+ return DeviceConfigUtils.isTetheringFeatureNotChickenedOut(
+ ctx, CONFIG_ENABLE_NETWORK_STATS_EVENT_LOGGER);
+ }
}
/**
@@ -1432,7 +1462,7 @@
| NetworkStatsManager.FLAG_POLL_FORCE)) != 0) {
final long ident = Binder.clearCallingIdentity();
try {
- performPoll(FLAG_PERSIST_ALL);
+ performPoll(FLAG_PERSIST_ALL, maybeCreatePollEvent(POLL_REASON_OPEN_SESSION));
} finally {
Binder.restoreCallingIdentity(ident);
}
@@ -1828,7 +1858,8 @@
final long token = Binder.clearCallingIdentity();
try {
- handleNotifyNetworkStatus(defaultNetworks, networkStates, activeIface);
+ handleNotifyNetworkStatus(defaultNetworks, networkStates, activeIface,
+ maybeCreatePollEvent(POLL_REASON_NETWORK_STATUS_CHANGED));
} finally {
Binder.restoreCallingIdentity(token);
}
@@ -1845,7 +1876,8 @@
final long token = Binder.clearCallingIdentity();
try {
- performPoll(FLAG_PERSIST_ALL);
+ // TODO: Log callstack for system server callers.
+ performPoll(FLAG_PERSIST_ALL, maybeCreatePollEvent(POLL_REASON_FORCE_UPDATE));
} finally {
Binder.restoreCallingIdentity(token);
}
@@ -1902,7 +1934,8 @@
}
// Create baseline stats
- mHandler.sendMessage(mHandler.obtainMessage(MSG_PERFORM_POLL));
+ mHandler.sendMessage(mHandler.obtainMessage(MSG_PERFORM_POLL,
+ POLL_REASON_REG_CALLBACK));
return normalizedRequest;
}
@@ -1999,7 +2032,8 @@
new TetheringManager.TetheringEventCallback() {
@Override
public void onUpstreamChanged(@Nullable Network network) {
- performPoll(FLAG_PERSIST_NETWORK);
+ performPoll(FLAG_PERSIST_NETWORK,
+ maybeCreatePollEvent(POLL_REASON_UPSTREAM_CHANGED));
}
};
@@ -2008,7 +2042,7 @@
public void onReceive(Context context, Intent intent) {
// on background handler thread, and verified UPDATE_DEVICE_STATS
// permission above.
- performPoll(FLAG_PERSIST_ALL);
+ performPoll(FLAG_PERSIST_ALL, maybeCreatePollEvent(POLL_REASON_PERIODIC));
// verify that we're watching global alert
registerGlobalAlert();
@@ -2072,19 +2106,20 @@
public void handleOnCollapsedRatTypeChanged() {
// Protect service from frequently updating. Remove pending messages if any.
mHandler.removeMessages(MSG_NOTIFY_NETWORK_STATUS);
- mHandler.sendMessageDelayed(
- mHandler.obtainMessage(MSG_NOTIFY_NETWORK_STATUS), mSettings.getPollDelay());
+ mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_NOTIFY_NETWORK_STATUS,
+ POLL_REASON_RAT_CHANGED), mSettings.getPollDelay());
}
private void handleNotifyNetworkStatus(
Network[] defaultNetworks,
NetworkStateSnapshot[] snapshots,
- String activeIface) {
+ String activeIface,
+ @Nullable PollEvent event) {
synchronized (mStatsLock) {
mWakeLock.acquire();
try {
mActiveIface = activeIface;
- handleNotifyNetworkStatusLocked(defaultNetworks, snapshots);
+ handleNotifyNetworkStatusLocked(defaultNetworks, snapshots, event);
} finally {
mWakeLock.release();
}
@@ -2098,7 +2133,7 @@
*/
@GuardedBy("mStatsLock")
private void handleNotifyNetworkStatusLocked(@NonNull Network[] defaultNetworks,
- @NonNull NetworkStateSnapshot[] snapshots) {
+ @NonNull NetworkStateSnapshot[] snapshots, @Nullable PollEvent event) {
if (!mSystemReady) return;
if (LOGV) Log.v(TAG, "handleNotifyNetworkStatusLocked()");
@@ -2108,7 +2143,7 @@
// poll, but only persist network stats to keep codepath fast. UID stats
// will be persisted during next alarm poll event.
- performPollLocked(FLAG_PERSIST_NETWORK);
+ performPollLocked(FLAG_PERSIST_NETWORK, event);
// Rebuild active interfaces based on connected networks
mActiveIfaces.clear();
@@ -2325,12 +2360,12 @@
}
}
- private void performPoll(int flags) {
+ private void performPoll(int flags, @Nullable PollEvent event) {
synchronized (mStatsLock) {
mWakeLock.acquire();
try {
- performPollLocked(flags);
+ performPollLocked(flags, event);
} finally {
mWakeLock.release();
}
@@ -2342,11 +2377,15 @@
* {@link NetworkStatsHistory}.
*/
@GuardedBy("mStatsLock")
- private void performPollLocked(int flags) {
+ private void performPollLocked(int flags, @Nullable PollEvent event) {
if (!mSystemReady) return;
if (LOGV) Log.v(TAG, "performPollLocked(flags=0x" + Integer.toHexString(flags) + ")");
Trace.traceBegin(TRACE_TAG_NETWORK, "performPollLocked");
+ if (mSupportEventLogger) {
+ mEventLogger.logPollEvent(flags, event);
+ }
+
final boolean persistNetwork = (flags & FLAG_PERSIST_NETWORK) != 0;
final boolean persistUid = (flags & FLAG_PERSIST_UID) != 0;
final boolean persistForce = (flags & FLAG_PERSIST_FORCE) != 0;
@@ -2546,7 +2585,7 @@
if (LOGV) Log.v(TAG, "removeUidsLocked() for UIDs " + Arrays.toString(uids));
// Perform one last poll before removing
- performPollLocked(FLAG_PERSIST_ALL);
+ performPollLocked(FLAG_PERSIST_ALL, maybeCreatePollEvent(POLL_REASON_REMOVE_UIDS));
mUidRecorder.removeUidsLocked(uids);
mUidTagRecorder.removeUidsLocked(uids);
@@ -2629,7 +2668,8 @@
}
if (poll) {
- performPollLocked(FLAG_PERSIST_ALL | FLAG_PERSIST_FORCE);
+ performPollLocked(FLAG_PERSIST_ALL | FLAG_PERSIST_FORCE,
+ maybeCreatePollEvent(POLL_REASON_DUMPSYS));
pw.println("Forced poll");
return;
}
@@ -2689,6 +2729,7 @@
pw.println("(failed to dump platform legacy stats import counters)");
}
}
+ pw.println(CONFIG_ENABLE_NETWORK_STATS_EVENT_LOGGER + ": " + mSupportEventLogger);
pw.decreaseIndent();
@@ -2746,6 +2787,10 @@
pw.decreaseIndent();
pw.println();
+ if (mSupportEventLogger) {
+ mEventLogger.dump(pw);
+ }
+
pw.println("Stats Providers:");
pw.increaseIndent();
invokeForAllStatsProviderCallbacks((cb) -> {
@@ -3215,6 +3260,22 @@
}
}
+ private final boolean mSupportEventLogger;
+ @GuardedBy("mStatsLock")
+ @Nullable
+ private final NetworkStatsEventLogger mEventLogger;
+
+ /**
+ * Create a PollEvent instance if the feature is enabled.
+ */
+ @Nullable
+ public PollEvent maybeCreatePollEvent(@NetworkStatsEventLogger.PollReason int reason) {
+ if (mSupportEventLogger) {
+ return new PollEvent(reason);
+ }
+ return null;
+ }
+
private class DropBoxNonMonotonicObserver implements NonMonotonicObserver<String> {
@Override
public void foundNonMonotonic(NetworkStats left, int leftIndex, NetworkStats right,
diff --git a/service/src/com/android/server/ConnectivityService.java b/service/src/com/android/server/ConnectivityService.java
index c559fa3..c4cb4c7 100755
--- a/service/src/com/android/server/ConnectivityService.java
+++ b/service/src/com/android/server/ConnectivityService.java
@@ -1538,9 +1538,9 @@
/**
* Get BPF program Id from CGROUP. See {@link BpfUtils#getProgramId}.
*/
- public int getBpfProgramId(final int attachType, @NonNull final String cgroupPath)
+ public int getBpfProgramId(final int attachType)
throws IOException {
- return BpfUtils.getProgramId(attachType, cgroupPath);
+ return BpfUtils.getProgramId(attachType);
}
/**
@@ -3274,15 +3274,15 @@
pw.increaseIndent();
try {
pw.print("CGROUP_INET_INGRESS: ");
- pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS, BpfUtils.CGROUP_PATH));
+ pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_INGRESS));
pw.print("CGROUP_INET_EGRESS: ");
- pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS, BpfUtils.CGROUP_PATH));
+ pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_EGRESS));
pw.print("CGROUP_INET_SOCK_CREATE: ");
- pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE, BpfUtils.CGROUP_PATH));
+ pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET_SOCK_CREATE));
pw.print("CGROUP_INET4_BIND: ");
- pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND, BpfUtils.CGROUP_PATH));
+ pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET4_BIND));
pw.print("CGROUP_INET6_BIND: ");
- pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND, BpfUtils.CGROUP_PATH));
+ pw.println(mDeps.getBpfProgramId(BPF_CGROUP_INET6_BIND));
} catch (IOException e) {
pw.println(" IOException");
}
@@ -10816,7 +10816,7 @@
// If type can't be parsed, this throws NumberFormatException, which
// is passed back to adb who prints it.
final int type = Integer.parseInt(getNextArg());
- final int ret = BpfUtils.getProgramId(type, BpfUtils.CGROUP_PATH);
+ final int ret = BpfUtils.getProgramId(type);
pw.println(ret);
return 0;
}
diff --git a/staticlibs/device/com/android/net/module/util/BpfMap.java b/staticlibs/device/com/android/net/module/util/BpfMap.java
index d45cace..595ac74 100644
--- a/staticlibs/device/com/android/net/module/util/BpfMap.java
+++ b/staticlibs/device/com/android/net/module/util/BpfMap.java
@@ -187,12 +187,6 @@
return nativeDeleteMapEntry(mMapFd.getFd(), key.writeToBytes());
}
- /** Returns {@code true} if this map contains no elements. */
- @Override
- public boolean isEmpty() throws ErrnoException {
- return getFirstKey() == null;
- }
-
private K getNextKeyInternal(@Nullable K key) throws ErrnoException {
byte[] rawKey = new byte[mKeySize];
@@ -245,49 +239,6 @@
return Struct.parse(mValueClass, buffer);
}
- /**
- * Iterate through the map and handle each key -> value retrieved base on the given BiConsumer.
- * The given BiConsumer may to delete the passed-in entry, but is not allowed to perform any
- * other structural modifications to the map, such as adding entries or deleting other entries.
- * Otherwise, iteration will result in undefined behaviour.
- */
- @Override
- public void forEach(ThrowingBiConsumer<K, V> action) throws ErrnoException {
- @Nullable K nextKey = getFirstKey();
-
- while (nextKey != null) {
- @NonNull final K curKey = nextKey;
- @NonNull final V value = getValue(curKey);
-
- nextKey = getNextKey(curKey);
- action.accept(curKey, value);
- }
- }
-
- /* Empty implementation to implement AutoCloseable, so we can use BpfMaps
- * with try with resources, but due to persistent FD cache, there is no actual
- * need to close anything. File descriptors will actually be closed when we
- * unlock the BpfMap class and destroy the ParcelFileDescriptor objects.
- */
- @Override
- public void close() throws IOException {
- }
-
- /**
- * Clears the map. The map may already be empty.
- *
- * @throws ErrnoException if the map is already closed, if an error occurred during iteration,
- * or if a non-ENOENT error occurred when deleting a key.
- */
- @Override
- public void clear() throws ErrnoException {
- K key = getFirstKey();
- while (key != null) {
- deleteEntry(key); // ignores ENOENT.
- key = getFirstKey();
- }
- }
-
private static native int nativeBpfFdGet(String path, int mode, int keySize, int valueSize)
throws ErrnoException, NullPointerException;
diff --git a/staticlibs/device/com/android/net/module/util/BpfUtils.java b/staticlibs/device/com/android/net/module/util/BpfUtils.java
index 6116a5f..10a8f60 100644
--- a/staticlibs/device/com/android/net/module/util/BpfUtils.java
+++ b/staticlibs/device/com/android/net/module/util/BpfUtils.java
@@ -41,49 +41,18 @@
public static final String CGROUP_PATH = "/sys/fs/cgroup/";
/**
- * Attach BPF program to CGROUP
- */
- public static void attachProgram(int type, @NonNull String programPath,
- @NonNull String cgroupPath, int flags) throws IOException {
- native_attachProgramToCgroup(type, programPath, cgroupPath, flags);
- }
-
- /**
- * Detach BPF program from CGROUP
- */
- public static void detachProgram(int type, @NonNull String cgroupPath)
- throws IOException {
- native_detachProgramFromCgroup(type, cgroupPath);
- }
-
- /**
* Get BPF program Id from CGROUP.
*
* Note: This requires a 4.19 kernel which is only guaranteed on V+.
*
* @param attachType Bpf attach type. See bpf_attach_type in include/uapi/linux/bpf.h.
- * @param cgroupPath Path of cgroup.
* @return Positive integer for a Program Id. 0 if no program is attached.
* @throws IOException if failed to open the cgroup directory or query bpf program.
*/
- public static int getProgramId(int attachType, @NonNull String cgroupPath) throws IOException {
- return native_getProgramIdFromCgroup(attachType, cgroupPath);
+ public static int getProgramId(int attachType) throws IOException {
+ return native_getProgramIdFromCgroup(attachType, CGROUP_PATH);
}
- /**
- * Detach single BPF program from CGROUP
- */
- public static void detachSingleProgram(int type, @NonNull String programPath,
- @NonNull String cgroupPath) throws IOException {
- native_detachSingleProgramFromCgroup(type, programPath, cgroupPath);
- }
-
- private static native boolean native_attachProgramToCgroup(int type, String programPath,
- String cgroupPath, int flags) throws IOException;
- private static native boolean native_detachProgramFromCgroup(int type, String cgroupPath)
- throws IOException;
- private static native boolean native_detachSingleProgramFromCgroup(int type,
- String programPath, String cgroupPath) throws IOException;
private static native int native_getProgramIdFromCgroup(int type, String cgroupPath)
throws IOException;
}
diff --git a/staticlibs/device/com/android/net/module/util/IBpfMap.java b/staticlibs/device/com/android/net/module/util/IBpfMap.java
index 83ff875..ca56830 100644
--- a/staticlibs/device/com/android/net/module/util/IBpfMap.java
+++ b/staticlibs/device/com/android/net/module/util/IBpfMap.java
@@ -18,6 +18,7 @@
import android.system.ErrnoException;
import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
import java.io.IOException;
import java.util.NoSuchElementException;
@@ -49,15 +50,17 @@
/** Remove existing key from eBpf map. Return true if something was deleted. */
boolean deleteEntry(K key) throws ErrnoException;
- /** Returns {@code true} if this map contains no elements. */
- boolean isEmpty() throws ErrnoException;
-
/** Get the key after the passed-in key. */
K getNextKey(@NonNull K key) throws ErrnoException;
/** Get the first key of the eBpf map. */
K getFirstKey() throws ErrnoException;
+ /** Returns {@code true} if this map contains no elements. */
+ default boolean isEmpty() throws ErrnoException {
+ return getFirstKey() == null;
+ }
+
/** Check whether a key exists in the map. */
boolean containsKey(@NonNull K key) throws ErrnoException;
@@ -70,13 +73,38 @@
/**
* Iterate through the map and handle each key -> value retrieved base on the given BiConsumer.
+ * The given BiConsumer may to delete the passed-in entry, but is not allowed to perform any
+ * other structural modifications to the map, such as adding entries or deleting other entries.
+ * Otherwise, iteration will result in undefined behaviour.
*/
- void forEach(ThrowingBiConsumer<K, V> action) throws ErrnoException;
+ default public void forEach(ThrowingBiConsumer<K, V> action) throws ErrnoException {
+ @Nullable K nextKey = getFirstKey();
- /** Clears the map. */
- void clear() throws ErrnoException;
+ while (nextKey != null) {
+ @NonNull final K curKey = nextKey;
+ @NonNull final V value = getValue(curKey);
+
+ nextKey = getNextKey(curKey);
+ action.accept(curKey, value);
+ }
+ }
+
+ /**
+ * Clears the map. The map may already be empty.
+ *
+ * @throws ErrnoException if the map is already closed, if an error occurred during iteration,
+ * or if a non-ENOENT error occurred when deleting a key.
+ */
+ default public void clear() throws ErrnoException {
+ K key = getFirstKey();
+ while (key != null) {
+ deleteEntry(key); // ignores ENOENT.
+ key = getFirstKey();
+ }
+ }
/** Close for AutoCloseable. */
@Override
- void close() throws IOException;
+ default void close() throws IOException {
+ };
}
diff --git a/staticlibs/device/com/android/net/module/util/structs/IaPrefixOption.java b/staticlibs/device/com/android/net/module/util/structs/IaPrefixOption.java
index ecdd440..b0f19e2 100644
--- a/staticlibs/device/com/android/net/module/util/structs/IaPrefixOption.java
+++ b/staticlibs/device/com/android/net/module/util/structs/IaPrefixOption.java
@@ -129,6 +129,10 @@
return true;
}
+ public IpPrefix getIpPrefix() {
+ return mIpPrefix;
+ }
+
/**
* Check whether or not IA Prefix option has 0 preferred and valid lifetimes.
*/
diff --git a/staticlibs/native/bpfutiljni/com_android_net_module_util_BpfUtils.cpp b/staticlibs/native/bpfutiljni/com_android_net_module_util_BpfUtils.cpp
index cf09379..bcc3ded 100644
--- a/staticlibs/native/bpfutiljni/com_android_net_module_util_BpfUtils.cpp
+++ b/staticlibs/native/bpfutiljni/com_android_net_module_util_BpfUtils.cpp
@@ -30,86 +30,6 @@
using base::unique_fd;
-// If attach fails throw error and return false.
-static jboolean com_android_net_module_util_BpfUtil_attachProgramToCgroup(JNIEnv *env,
- jclass clazz, jint type, jstring bpfProgPath, jstring cgroupPath, jint flags) {
-
- ScopedUtfChars dirPath(env, cgroupPath);
- unique_fd cg_fd(open(dirPath.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
- if (cg_fd == -1) {
- jniThrowExceptionFmt(env, "java/io/IOException",
- "Failed to open the cgroup directory %s: %s",
- dirPath.c_str(), strerror(errno));
- return false;
- }
-
- ScopedUtfChars bpfProg(env, bpfProgPath);
- unique_fd bpf_fd(bpf::retrieveProgram(bpfProg.c_str()));
- if (bpf_fd == -1) {
- jniThrowExceptionFmt(env, "java/io/IOException",
- "Failed to retrieve bpf program from %s: %s",
- bpfProg.c_str(), strerror(errno));
- return false;
- }
- if (bpf::attachProgram((bpf_attach_type) type, bpf_fd, cg_fd, flags)) {
- jniThrowExceptionFmt(env, "java/io/IOException",
- "Failed to attach bpf program %s to %s: %s",
- bpfProg.c_str(), dirPath.c_str(), strerror(errno));
- return false;
- }
- return true;
-}
-
-// If detach fails throw error and return false.
-static jboolean com_android_net_module_util_BpfUtil_detachProgramFromCgroup(JNIEnv *env,
- jclass clazz, jint type, jstring cgroupPath) {
-
- ScopedUtfChars dirPath(env, cgroupPath);
- unique_fd cg_fd(open(dirPath.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
- if (cg_fd == -1) {
- jniThrowExceptionFmt(env, "java/io/IOException",
- "Failed to open the cgroup directory %s: %s",
- dirPath.c_str(), strerror(errno));
- return false;
- }
-
- if (bpf::detachProgram((bpf_attach_type) type, cg_fd)) {
- jniThrowExceptionFmt(env, "Failed to detach bpf program from %s: %s",
- dirPath.c_str(), strerror(errno));
- return false;
- }
- return true;
-}
-
-// If detach single program fails throw error and return false.
-static jboolean com_android_net_module_util_BpfUtil_detachSingleProgramFromCgroup(JNIEnv *env,
- jclass clazz, jint type, jstring bpfProgPath, jstring cgroupPath) {
-
- ScopedUtfChars dirPath(env, cgroupPath);
- unique_fd cg_fd(open(dirPath.c_str(), O_DIRECTORY | O_RDONLY | O_CLOEXEC));
- if (cg_fd == -1) {
- jniThrowExceptionFmt(env, "java/io/IOException",
- "Failed to open the cgroup directory %s: %s",
- dirPath.c_str(), strerror(errno));
- return false;
- }
-
- ScopedUtfChars bpfProg(env, bpfProgPath);
- unique_fd bpf_fd(bpf::retrieveProgram(bpfProg.c_str()));
- if (bpf_fd == -1) {
- jniThrowExceptionFmt(env, "java/io/IOException",
- "Failed to retrieve bpf program from %s: %s",
- bpfProg.c_str(), strerror(errno));
- return false;
- }
- if (bpf::detachSingleProgram((bpf_attach_type) type, bpf_fd, cg_fd)) {
- jniThrowExceptionFmt(env, "Failed to detach bpf program %s from %s: %s",
- bpfProg.c_str(), dirPath.c_str(), strerror(errno));
- return false;
- }
- return true;
-}
-
static jint com_android_net_module_util_BpfUtil_getProgramIdFromCgroup(JNIEnv *env,
jclass clazz, jint type, jstring cgroupPath) {
@@ -138,12 +58,6 @@
*/
static const JNINativeMethod gMethods[] = {
/* name, signature, funcPtr */
- { "native_attachProgramToCgroup", "(ILjava/lang/String;Ljava/lang/String;I)Z",
- (void*) com_android_net_module_util_BpfUtil_attachProgramToCgroup },
- { "native_detachProgramFromCgroup", "(ILjava/lang/String;)Z",
- (void*) com_android_net_module_util_BpfUtil_detachProgramFromCgroup },
- { "native_detachSingleProgramFromCgroup", "(ILjava/lang/String;Ljava/lang/String;)Z",
- (void*) com_android_net_module_util_BpfUtil_detachSingleProgramFromCgroup },
{ "native_getProgramIdFromCgroup", "(ILjava/lang/String;)I",
(void*) com_android_net_module_util_BpfUtil_getProgramIdFromCgroup },
};
diff --git a/tests/unit/java/com/android/server/ConnectivityServiceTest.java b/tests/unit/java/com/android/server/ConnectivityServiceTest.java
index 194cec3..11cece1 100755
--- a/tests/unit/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/unit/java/com/android/server/ConnectivityServiceTest.java
@@ -2299,7 +2299,7 @@
}
@Override
- public int getBpfProgramId(final int attachType, @NonNull final String cgroupPath) {
+ public int getBpfProgramId(final int attachType) {
return 0;
}
diff --git a/tests/unit/java/com/android/server/net/NetworkStatsEventLoggerTest.kt b/tests/unit/java/com/android/server/net/NetworkStatsEventLoggerTest.kt
new file mode 100644
index 0000000..9f2d4d3
--- /dev/null
+++ b/tests/unit/java/com/android/server/net/NetworkStatsEventLoggerTest.kt
@@ -0,0 +1,173 @@
+/*
+ * 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.net
+
+import android.util.IndentingPrintWriter
+import com.android.server.net.NetworkStatsEventLogger.MAX_POLL_REASON
+import com.android.server.net.NetworkStatsEventLogger.POLL_REASON_DUMPSYS
+import com.android.server.net.NetworkStatsEventLogger.POLL_REASON_FORCE_UPDATE
+import com.android.server.net.NetworkStatsEventLogger.POLL_REASON_GLOBAL_ALERT
+import com.android.server.net.NetworkStatsEventLogger.POLL_REASON_NETWORK_STATUS_CHANGED
+import com.android.server.net.NetworkStatsEventLogger.POLL_REASON_OPEN_SESSION
+import com.android.server.net.NetworkStatsEventLogger.POLL_REASON_PERIODIC
+import com.android.server.net.NetworkStatsEventLogger.POLL_REASON_RAT_CHANGED
+import com.android.server.net.NetworkStatsEventLogger.POLL_REASON_REG_CALLBACK
+import com.android.server.net.NetworkStatsEventLogger.PollEvent
+import com.android.server.net.NetworkStatsEventLogger.PollEvent.pollReasonNameOf
+import com.android.testutils.DevSdkIgnoreRunner
+import java.io.StringWriter
+import kotlin.test.assertEquals
+import kotlin.test.assertFailsWith
+import kotlin.test.assertFalse
+import kotlin.test.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+
+const val TEST_PERSIST_FLAG = 0x101
+
+@RunWith(DevSdkIgnoreRunner::class)
+class NetworkStatsEventLoggerTest {
+ val logger = NetworkStatsEventLogger()
+ val stringWriter = TestStringWriter()
+ val pw = IndentingPrintWriter(stringWriter)
+
+ @Test
+ fun testDump_invalid() {
+ // Verify it won't crash.
+ logger.dump(pw)
+ // Clear output buffer.
+ stringWriter.getOutputAndClear()
+
+ // Verify log invalid event throws. And nothing output in the dump.
+ val invalidReasons = listOf(-1, MAX_POLL_REASON + 1)
+ invalidReasons.forEach {
+ assertFailsWith<IllegalArgumentException> {
+ logger.logPollEvent(TEST_PERSIST_FLAG, PollEvent(it))
+ }
+ logger.dumpRecentPollEvents(pw)
+ val output = stringWriter.getOutputAndClear()
+ assertStringNotContains(output, pollReasonNameOf(it))
+ }
+ }
+
+ @Test
+ fun testDump_valid() {
+ // Choose arbitrary set of reasons for testing.
+ val loggedReasons = listOf(
+ POLL_REASON_GLOBAL_ALERT,
+ POLL_REASON_FORCE_UPDATE,
+ POLL_REASON_DUMPSYS,
+ POLL_REASON_PERIODIC,
+ POLL_REASON_RAT_CHANGED
+ )
+ val nonLoggedReasons = listOf(
+ POLL_REASON_NETWORK_STATUS_CHANGED,
+ POLL_REASON_OPEN_SESSION,
+ POLL_REASON_REG_CALLBACK)
+
+ // Add some valid records.
+ loggedReasons.forEach {
+ logger.logPollEvent(TEST_PERSIST_FLAG, PollEvent(it))
+ }
+
+ // Collect dumps.
+ logger.dumpRecentPollEvents(pw)
+ val outputRecentEvents = stringWriter.getOutputAndClear()
+ logger.dumpPollCountsPerReason(pw)
+ val outputCountsPerReason = stringWriter.getOutputAndClear()
+
+ // Verify the output contains at least necessary information.
+ loggedReasons.forEach {
+ // Verify all events are shown in the recent event dump.
+ val eventString = PollEvent(it).toString()
+ assertStringContains(outputRecentEvents, TEST_PERSIST_FLAG.toString())
+ assertStringContains(eventString, pollReasonNameOf(it))
+ assertStringContains(outputRecentEvents, eventString)
+ // Verify counts are 1 for each reason.
+ assertCountForReason(outputCountsPerReason, it, 1)
+ }
+
+ // Verify the output remains untouched for other reasons.
+ nonLoggedReasons.forEach {
+ assertStringNotContains(outputRecentEvents, PollEvent(it).toString())
+ assertCountForReason(outputCountsPerReason, it, 0)
+ }
+ }
+
+ @Test
+ fun testDump_maxEventLogs() {
+ // Choose arbitrary reason.
+ val reasonToBeTested = POLL_REASON_PERIODIC
+ val repeatCount = NetworkStatsEventLogger.MAX_EVENTS_LOGS * 2
+
+ // Collect baseline.
+ logger.dumpRecentPollEvents(pw)
+ val lineCountBaseLine = getLineCount(stringWriter.getOutputAndClear())
+
+ repeat(repeatCount) {
+ logger.logPollEvent(TEST_PERSIST_FLAG, PollEvent(reasonToBeTested))
+ }
+
+ // Collect dump.
+ logger.dumpRecentPollEvents(pw)
+ val lineCountAfterTest = getLineCount(stringWriter.getOutputAndClear())
+
+ // Verify line count increment is limited.
+ assertEquals(
+ NetworkStatsEventLogger.MAX_EVENTS_LOGS,
+ lineCountAfterTest - lineCountBaseLine
+ )
+
+ // Verify count per reason increased for the testing reason.
+ logger.dumpPollCountsPerReason(pw)
+ val outputCountsPerReason = stringWriter.getOutputAndClear()
+ for (reason in 0..MAX_POLL_REASON) {
+ assertCountForReason(
+ outputCountsPerReason,
+ reason,
+ if (reason == reasonToBeTested) repeatCount else 0
+ )
+ }
+ }
+
+ private fun getLineCount(multilineString: String) = multilineString.lines().size
+
+ private fun assertStringContains(got: String, want: String) {
+ assertTrue(got.contains(want), "Wanted: $want, but got: $got")
+ }
+
+ private fun assertStringNotContains(got: String, unwant: String) {
+ assertFalse(got.contains(unwant), "Unwanted: $unwant, but got: $got")
+ }
+
+ /**
+ * Assert the reason and the expected count are at the same line.
+ */
+ private fun assertCountForReason(dump: String, reason: Int, expectedCount: Int) {
+ // Matches strings like "GLOBAL_ALERT: 50" but not too strict since the format might change.
+ val regex = Regex(pollReasonNameOf(reason) + "[^0-9]+" + expectedCount)
+ assertEquals(
+ 1,
+ regex.findAll(dump).count(),
+ "Unexpected output: $dump " + " for reason: " + pollReasonNameOf(reason)
+ )
+ }
+
+ class TestStringWriter : StringWriter() {
+ fun getOutputAndClear() = toString().also { buffer.setLength(0) }
+ }
+}
diff --git a/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java b/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
index 9453617..e8d5c66 100644
--- a/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
+++ b/tests/unit/java/com/android/server/net/NetworkStatsServiceTest.java
@@ -64,6 +64,8 @@
import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
import static android.text.format.DateUtils.WEEK_IN_MILLIS;
+import static com.android.server.net.NetworkStatsEventLogger.POLL_REASON_RAT_CHANGED;
+import static com.android.server.net.NetworkStatsEventLogger.PollEvent.pollReasonNameOf;
import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_POLL;
import static com.android.server.net.NetworkStatsService.NETSTATS_IMPORT_ATTEMPTS_COUNTER_NAME;
import static com.android.server.net.NetworkStatsService.NETSTATS_IMPORT_FALLBACKS_COUNTER_NAME;
@@ -525,6 +527,11 @@
IBpfMap<CookieTagMapKey, CookieTagMapValue> cookieTagMap, Handler handler) {
return mSkDestroyListener;
}
+
+ @Override
+ public boolean supportEventLogger(@NonNull Context cts) {
+ return true;
+ }
};
}
@@ -2674,4 +2681,14 @@
doReturn(null).when(mBpfInterfaceMapUpdater).getIfNameByIndex(10 /* index */);
doTestDumpIfaceStatsMap("unknown");
}
+
+ // Basic test to ensure event logger dump is called.
+ // Note that tests to ensure detailed correctness is done in the dedicated tests.
+ // See NetworkStatsEventLoggerTest.
+ @Test
+ public void testDumpEventLogger() {
+ setMobileRatTypeAndWaitForIdle(TelephonyManager.NETWORK_TYPE_UMTS);
+ final String dump = getDump();
+ assertDumpContains(dump, pollReasonNameOf(POLL_REASON_RAT_CHANGED));
+ }
}
diff --git a/thread/TEST_MAPPING b/thread/TEST_MAPPING
index 17a74f6..3eaebfa 100644
--- a/thread/TEST_MAPPING
+++ b/thread/TEST_MAPPING
@@ -1,7 +1,5 @@
{
- // TODO (b/297729075): graduate this test to presubmit once it meets the SLO requirements.
- // See go/test-mapping-slo-guide
- "postsubmit": [
+ "presubmit": [
{
"name": "CtsThreadNetworkTestCases"
}
diff --git a/thread/framework/java/android/net/thread/ThreadNetworkController.java b/thread/framework/java/android/net/thread/ThreadNetworkController.java
index 9db8132..7575757 100644
--- a/thread/framework/java/android/net/thread/ThreadNetworkController.java
+++ b/thread/framework/java/android/net/thread/ThreadNetworkController.java
@@ -34,7 +34,7 @@
*/
@FlaggedApi(ThreadNetworkFlags.FLAG_THREAD_ENABLED)
@SystemApi
-public class ThreadNetworkController {
+public final class ThreadNetworkController {
/** Thread standard version 1.3. */
public static final int THREAD_VERSION_1_3 = 4;
diff --git a/thread/framework/java/android/net/thread/ThreadNetworkManager.java b/thread/framework/java/android/net/thread/ThreadNetworkManager.java
index 3e8288c..c3bdbd7 100644
--- a/thread/framework/java/android/net/thread/ThreadNetworkManager.java
+++ b/thread/framework/java/android/net/thread/ThreadNetworkManager.java
@@ -38,7 +38,7 @@
@FlaggedApi(ThreadNetworkFlags.FLAG_THREAD_ENABLED)
@SystemApi
@SystemService(ThreadNetworkManager.SERVICE_NAME)
-public class ThreadNetworkManager {
+public final class ThreadNetworkManager {
/**
* This value tracks {@link Context#THREAD_NETWORK_SERVICE}.
*
diff --git a/thread/tests/unit/Android.bp b/thread/tests/unit/Android.bp
index 1f16ad1..3a087c7 100644
--- a/thread/tests/unit/Android.bp
+++ b/thread/tests/unit/Android.bp
@@ -38,7 +38,7 @@
"framework-connectivity-t-pre-jarjar",
"guava-android-testlib",
"net-tests-utils",
- "truth-prebuilt",
+ "truth",
],
libs: [
"android.test.base",