Merge "Support StructInetDiagSockId parse"
diff --git a/staticlibs/Android.bp b/staticlibs/Android.bp
index c04d1d4..4dfc752 100644
--- a/staticlibs/Android.bp
+++ b/staticlibs/Android.bp
@@ -284,7 +284,7 @@
     // TODO: remove "apex_available:platform".
     apex_available: [
         "//apex_available:platform",
-        "com.android.bluetooth",
+        "com.android.btservices",
         "com.android.tethering",
         "com.android.wifi",
     ],
diff --git a/staticlibs/device/com/android/net/module/util/BpfDump.java b/staticlibs/device/com/android/net/module/util/BpfDump.java
index fec225c..67e9c93 100644
--- a/staticlibs/device/com/android/net/module/util/BpfDump.java
+++ b/staticlibs/device/com/android/net/module/util/BpfDump.java
@@ -16,16 +16,20 @@
 package com.android.net.module.util;
 
 import android.util.Base64;
+import android.util.Pair;
 
 import androidx.annotation.NonNull;
 
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
 /**
  * The classes and the methods for BPF dump utilization.
  */
 public class BpfDump {
     // Using "," as a separator between base64 encoded key and value is safe because base64
     // characters are [0-9a-zA-Z/=+].
-    public static final String BASE64_DELIMITER = ",";
+    private static final String BASE64_DELIMITER = ",";
 
     /**
      * Encode BPF key and value into a base64 format string which uses the delimiter ',':
@@ -43,6 +47,33 @@
         return keyBase64Str + BASE64_DELIMITER + valueBase64Str;
     }
 
+    /**
+     * Decode Struct from a base64 format string
+     */
+    private static <T extends Struct> T parseStruct(
+            Class<T> structClass, @NonNull String base64Str) {
+        final byte[] bytes = Base64.decode(base64Str, Base64.DEFAULT);
+        final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
+        byteBuffer.order(ByteOrder.nativeOrder());
+        return Struct.parse(structClass, byteBuffer);
+    }
+
+    /**
+     * Decode BPF key and value from a base64 format string which uses the delimiter ',':
+     * <base64 encoded key>,<base64 encoded value>
+     */
+    public static <K extends Struct, V extends Struct> Pair<K, V> fromBase64EncodedString(
+            Class<K> keyClass, Class<V> valueClass, @NonNull String base64Str) {
+        String[] keyValueStrs = base64Str.split(BASE64_DELIMITER);
+        if (keyValueStrs.length != 2 /* key + value */) {
+            throw new IllegalArgumentException("Invalid base64Str (" + base64Str + "), base64Str"
+                    + " must contain exactly one delimiter '" + BASE64_DELIMITER + "'");
+        }
+        final K k = parseStruct(keyClass, keyValueStrs[0]);
+        final V v = parseStruct(valueClass, keyValueStrs[1]);
+        return new Pair<>(k, v);
+    }
+
     // TODO: add a helper to dump bpf map content with the map name, the header line
     // (ex: "BPF ingress map: iif nat64Prefix v6Addr -> v4Addr oif"), a lambda that
     // knows how to dump each line, and the PrintWriter.
diff --git a/staticlibs/device/com/android/net/module/util/Struct.java b/staticlibs/device/com/android/net/module/util/Struct.java
index d717bc7..b638a46 100644
--- a/staticlibs/device/com/android/net/module/util/Struct.java
+++ b/staticlibs/device/com/android/net/module/util/Struct.java
@@ -742,6 +742,17 @@
         }
     }
 
+    /** A simple Struct which only contains an s32 field. */
+    public static class S32 extends Struct {
+        @Struct.Field(order = 0, type = Struct.Type.S32)
+        public final int val;
+
+        public S32(final int val) {
+            this.val = val;
+        }
+    }
+
+    /** A simple Struct which only contains a u32 field. */
     public static class U32 extends Struct {
         @Struct.Field(order = 0, type = Struct.Type.U32)
         public final long val;
@@ -751,6 +762,7 @@
         }
     }
 
+    /** A simple Struct which only contains an s64 field. */
     public static class S64 extends Struct {
         @Struct.Field(order = 0, type = Struct.Type.S64)
         public final long val;
diff --git a/staticlibs/framework/com/android/net/module/util/CollectionUtils.java b/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
index a16ef33..d1728c2 100644
--- a/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
+++ b/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
@@ -22,6 +22,7 @@
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.List;
 import java.util.Objects;
 import java.util.function.Predicate;
 
@@ -165,6 +166,26 @@
     }
 
     /**
+     * Returns the index of the needle array in the haystack array, or -1 if it can't be found.
+     * This is a byte array equivalent of Collections.indexOfSubList().
+     */
+    public static int indexOfSubArray(@NonNull byte[] haystack, @NonNull byte[] needle) {
+        for (int i = 0; i < haystack.length - needle.length + 1; i++) {
+            boolean found = true;
+            for (int j = 0; j < needle.length; j++) {
+                if (haystack[i + j] != needle[j]) {
+                    found = false;
+                    break;
+                }
+            }
+            if (found) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    /**
      * Returns a new collection of elements that match the passed predicate.
      * @param source the elements to filter.
      * @param test the predicate to test for.
@@ -219,4 +240,38 @@
         return haystack.containsAll(needles);
     }
 
+    /**
+     * Returns the first item of a collection that matches the predicate.
+     * @param haystack The collection to search.
+     * @param condition The predicate to match.
+     * @param <T> The type of element in the collection.
+     * @return The first element matching the predicate, or null if none.
+     */
+    @Nullable
+    public static <T> T findFirst(Collection<T> haystack, Predicate<? super T> condition) {
+        for (T needle : haystack) {
+            if (condition.test(needle)) return needle;
+        }
+        return null;
+    }
+
+    /**
+     * Returns the last item of a List that matches the predicate.
+     * @param haystack The List to search.
+     * @param condition The predicate to match.
+     * @param <T> The type of element in the list.
+     * @return The last element matching the predicate, or null if none.
+     */
+    // There is no way to reverse iterate a Collection in Java (e.g. the collection may
+    // be a single-linked list), so implementing this on Collection is necessarily very
+    // wasteful (store and reverse a copy, test all elements, or recurse to the end of the
+    // list to test on the up path and possibly blow the call stack)
+    @Nullable
+    public static <T> T findLast(List<T> haystack, Predicate<? super T> condition) {
+        for (int i = haystack.size() - 1; i >= 0; --i) {
+            final T needle = haystack.get(i);
+            if (condition.test(needle)) return needle;
+        }
+        return null;
+    }
 }
diff --git a/staticlibs/framework/com/android/net/module/util/IpRange.java b/staticlibs/framework/com/android/net/module/util/IpRange.java
index 40b57b1..0a3f95b 100644
--- a/staticlibs/framework/com/android/net/module/util/IpRange.java
+++ b/staticlibs/framework/com/android/net/module/util/IpRange.java
@@ -200,7 +200,7 @@
 
     @Override
     public int hashCode() {
-        return Objects.hash(mStartAddr, mEndAddr);
+        return Objects.hash(Arrays.hashCode(mStartAddr), Arrays.hashCode(mEndAddr));
     }
 
     @Override
diff --git a/staticlibs/framework/com/android/net/module/util/PerUidCounter.java b/staticlibs/framework/com/android/net/module/util/PerUidCounter.java
index 0b2de7a..463b0c4 100644
--- a/staticlibs/framework/com/android/net/module/util/PerUidCounter.java
+++ b/staticlibs/framework/com/android/net/module/util/PerUidCounter.java
@@ -32,7 +32,7 @@
 
     // Map from UID to count that UID has filed.
     @VisibleForTesting
-    @GuardedBy("mUidToCount")
+    @GuardedBy("this")
     final SparseIntArray mUidToCount = new SparseIntArray();
 
     /**
@@ -57,15 +57,8 @@
      *
      * @param uid the uid that the counter was made under
      */
-    public void incrementCountOrThrow(final int uid) {
-        incrementCountOrThrow(uid, 1 /* numToIncrement */);
-    }
-
-    public synchronized void incrementCountOrThrow(final int uid, final int numToIncrement) {
-        if (numToIncrement <= 0) {
-            throw new IllegalArgumentException("Increment count must be positive");
-        }
-        final long newCount = ((long) mUidToCount.get(uid, 0)) + numToIncrement;
+    public synchronized void incrementCountOrThrow(final int uid) {
+        final long newCount = ((long) mUidToCount.get(uid, 0)) + 1;
         if (newCount > mMaxCountPerUid) {
             throw new IllegalStateException("Uid " + uid + " exceeded its allowed limit");
         }
@@ -83,15 +76,8 @@
      *
      * @param uid the uid that the count was made under
      */
-    public void decrementCountOrThrow(final int uid) {
-        decrementCountOrThrow(uid, 1 /* numToDecrement */);
-    }
-
-    public synchronized void decrementCountOrThrow(final int uid, final int numToDecrement) {
-        if (numToDecrement <= 0) {
-            throw new IllegalArgumentException("Decrement count must be positive");
-        }
-        final int newCount = mUidToCount.get(uid, 0) - numToDecrement;
+    public synchronized void decrementCountOrThrow(final int uid) {
+        final int newCount = mUidToCount.get(uid, 0) - 1;
         if (newCount < 0) {
             throw new IllegalStateException("BUG: too small count " + newCount + " for UID " + uid);
         } else if (newCount == 0) {
@@ -100,4 +86,9 @@
             mUidToCount.put(uid, newCount);
         }
     }
+
+    @VisibleForTesting
+    public synchronized int get(int uid) {
+        return mUidToCount.get(uid, 0);
+    }
 }
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/BpfDumpTest.java b/staticlibs/tests/unit/src/com/android/net/module/util/BpfDumpTest.java
index b166b4a..395011c 100644
--- a/staticlibs/tests/unit/src/com/android/net/module/util/BpfDumpTest.java
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/BpfDumpTest.java
@@ -17,6 +17,9 @@
 package com.android.net.module.util;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+
+import android.util.Pair;
 
 import androidx.test.filters.SmallTest;
 import androidx.test.runner.AndroidJUnit4;
@@ -27,17 +30,53 @@
 @RunWith(AndroidJUnit4.class)
 @SmallTest
 public class BpfDumpTest {
+    private static final int TEST_KEY = 123;
+    private static final String TEST_KEY_BASE64 = "ewAAAA==";
+    private static final int TEST_VAL = 456;
+    private static final String TEST_VAL_BASE64 = "yAEAAA==";
+    private static final String BASE64_DELIMITER = ",";
+    private static final String TEST_KEY_VAL_BASE64 =
+            TEST_KEY_BASE64 + BASE64_DELIMITER + TEST_VAL_BASE64;
+    private static final String INVALID_BASE64_STRING = "Map is null";
+
     @Test
     public void testToBase64EncodedString() {
-        final Struct.U32 key = new Struct.U32(123);
-        final Struct.U32 value = new Struct.U32(456);
+        final Struct.U32 key = new Struct.U32(TEST_KEY);
+        final Struct.U32 value = new Struct.U32(TEST_VAL);
 
         // Verified in python:
         //   import base64
-        //   print(base64.b64encode(b'\x7b\x00\x00\x00')) # key: ewAAAA==
-        //   print(base64.b64encode(b'\xc8\x01\x00\x00')) # value: yAEAAA==
+        //   print(base64.b64encode(b'\x7b\x00\x00\x00')) # key: ewAAAA== (TEST_KEY_BASE64)
+        //   print(base64.b64encode(b'\xc8\x01\x00\x00')) # value: yAEAAA== (TEST_VAL_BASE64)
         assertEquals("7B000000", HexDump.toHexString(key.writeToBytes()));
         assertEquals("C8010000", HexDump.toHexString(value.writeToBytes()));
-        assertEquals("ewAAAA==,yAEAAA==", BpfDump.toBase64EncodedString(key, value));
+        assertEquals(TEST_KEY_VAL_BASE64, BpfDump.toBase64EncodedString(key, value));
+    }
+
+    @Test
+    public void testFromBase64EncodedString() {
+        Pair<Struct.U32, Struct.U32> decodedKeyValue = BpfDump.fromBase64EncodedString(
+                Struct.U32.class, Struct.U32.class, TEST_KEY_VAL_BASE64);
+        assertEquals(TEST_KEY, decodedKeyValue.first.val);
+        assertEquals(TEST_VAL, decodedKeyValue.second.val);
+    }
+
+    private void assertThrowsIllegalArgumentException(final String testStr) {
+        assertThrows(IllegalArgumentException.class,
+                () -> BpfDump.fromBase64EncodedString(Struct.U32.class, Struct.U32.class, testStr));
+    }
+
+    @Test
+    public void testFromBase64EncodedStringInvalidString() {
+        assertThrowsIllegalArgumentException(INVALID_BASE64_STRING);
+        assertThrowsIllegalArgumentException(TEST_KEY_BASE64);
+        assertThrowsIllegalArgumentException(
+                TEST_KEY_BASE64 + BASE64_DELIMITER + INVALID_BASE64_STRING);
+        assertThrowsIllegalArgumentException(
+                INVALID_BASE64_STRING + BASE64_DELIMITER + TEST_VAL_BASE64);
+        assertThrowsIllegalArgumentException(
+                INVALID_BASE64_STRING + BASE64_DELIMITER + INVALID_BASE64_STRING);
+        assertThrowsIllegalArgumentException(
+                TEST_KEY_VAL_BASE64 + BASE64_DELIMITER + TEST_KEY_BASE64);
     }
 }
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt b/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt
index 911483a..0991352 100644
--- a/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/CollectionUtilsTest.kt
@@ -18,10 +18,13 @@
 
 import androidx.test.filters.SmallTest
 import androidx.test.runner.AndroidJUnit4
+import com.android.testutils.assertThrows
 import org.junit.Test
 import org.junit.runner.RunWith
 import kotlin.test.assertEquals
 import kotlin.test.assertFalse
+import kotlin.test.assertNull
+import kotlin.test.assertSame
 import kotlin.test.assertTrue
 
 @RunWith(AndroidJUnit4::class)
@@ -50,6 +53,21 @@
     }
 
     @Test
+    fun testIndexOfSubArray() {
+        val haystack = byteArrayOf(1, 2, 3, 4, 5)
+        assertEquals(2, CollectionUtils.indexOfSubArray(haystack, byteArrayOf(3, 4)))
+        assertEquals(3, CollectionUtils.indexOfSubArray(haystack, byteArrayOf(4, 5)))
+        assertEquals(4, CollectionUtils.indexOfSubArray(haystack, byteArrayOf(5)))
+        assertEquals(-1, CollectionUtils.indexOfSubArray(haystack, byteArrayOf(3, 2)))
+        assertEquals(0, CollectionUtils.indexOfSubArray(haystack, byteArrayOf()))
+        assertEquals(-1, CollectionUtils.indexOfSubArray(byteArrayOf(), byteArrayOf(3, 2)))
+        assertEquals(0, CollectionUtils.indexOfSubArray(byteArrayOf(), byteArrayOf()))
+        assertThrows(NullPointerException::class.java) {
+            CollectionUtils.indexOfSubArray(haystack, null)
+        }
+    }
+
+    @Test
     fun testAll() {
         assertFalse(CollectionUtils.all(listOf("A", "B", "C", "D", "E")) { it != "E" })
         assertTrue(CollectionUtils.all(listOf("A", "B", "C", "D", "E")) { it != "F" })
@@ -86,4 +104,27 @@
         assertEquals(3, CollectionUtils.total(longArrayOf(1, 1, 1)))
         assertEquals(0, CollectionUtils.total(null))
     }
+
+    @Test
+    fun testFindFirstFindLast() {
+        val listAE = listOf("A", "B", "C", "D", "E")
+        assertSame(CollectionUtils.findFirst(listAE) { it == "A" }, listAE[0])
+        assertSame(CollectionUtils.findFirst(listAE) { it == "B" }, listAE[1])
+        assertSame(CollectionUtils.findFirst(listAE) { it == "E" }, listAE[4])
+        assertNull(CollectionUtils.findFirst(listAE) { it == "F" })
+        assertSame(CollectionUtils.findLast(listAE) { it == "A" }, listAE[0])
+        assertSame(CollectionUtils.findLast(listAE) { it == "B" }, listAE[1])
+        assertSame(CollectionUtils.findLast(listAE) { it == "E" }, listAE[4])
+        assertNull(CollectionUtils.findLast(listAE) { it == "F" })
+
+        val listMulti = listOf("A", "B", "A", "C", "D", "E", "A", "E")
+        assertSame(CollectionUtils.findFirst(listMulti) { it == "A" }, listMulti[0])
+        assertSame(CollectionUtils.findFirst(listMulti) { it == "B" }, listMulti[1])
+        assertSame(CollectionUtils.findFirst(listMulti) { it == "E" }, listMulti[5])
+        assertNull(CollectionUtils.findFirst(listMulti) { it == "F" })
+        assertSame(CollectionUtils.findLast(listMulti) { it == "A" }, listMulti[6])
+        assertSame(CollectionUtils.findLast(listMulti) { it == "B" }, listMulti[1])
+        assertSame(CollectionUtils.findLast(listMulti) { it == "E" }, listMulti[7])
+        assertNull(CollectionUtils.findLast(listMulti) { it == "F" })
+    }
 }
diff --git a/staticlibs/tests/unit/src/com/android/net/module/util/PerUidCounterTest.kt b/staticlibs/tests/unit/src/com/android/net/module/util/PerUidCounterTest.kt
index 0f2d52a..321fe59 100644
--- a/staticlibs/tests/unit/src/com/android/net/module/util/PerUidCounterTest.kt
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/PerUidCounterTest.kt
@@ -20,6 +20,7 @@
 import androidx.test.runner.AndroidJUnit4
 import org.junit.Test
 import org.junit.runner.RunWith
+import kotlin.test.assertEquals
 import kotlin.test.assertFailsWith
 
 @RunWith(AndroidJUnit4::class)
@@ -27,6 +28,7 @@
 class PerUidCounterTest {
     private val UID_A = 1000
     private val UID_B = 1001
+    private val UID_C = 1002
 
     @Test
     fun testCounterMaximum() {
@@ -37,31 +39,35 @@
             PerUidCounter(0)
         }
 
-        val largeMaxCounter = PerUidCounter(Integer.MAX_VALUE)
-        largeMaxCounter.incrementCountOrThrow(UID_A, Integer.MAX_VALUE)
-        assertFailsWith<IllegalStateException> {
-            largeMaxCounter.incrementCountOrThrow(UID_A)
+        val testLimit = 1000
+        val testCounter = PerUidCounter(testLimit)
+        assertEquals(0, testCounter[UID_A])
+        repeat(testLimit) {
+            testCounter.incrementCountOrThrow(UID_A)
         }
+        assertEquals(testLimit, testCounter[UID_A])
+        assertFailsWith<IllegalStateException> {
+            testCounter.incrementCountOrThrow(UID_A)
+        }
+        assertEquals(testLimit, testCounter[UID_A])
     }
 
     @Test
     fun testIncrementCountOrThrow() {
         val counter = PerUidCounter(3)
 
-        // Verify the increment count cannot be zero.
-        assertFailsWith<IllegalArgumentException> {
-            counter.incrementCountOrThrow(UID_A, 0)
-        }
-
         // Verify the counters work independently.
         counter.incrementCountOrThrow(UID_A)
-        counter.incrementCountOrThrow(UID_B, 2)
+        counter.incrementCountOrThrow(UID_B)
         counter.incrementCountOrThrow(UID_B)
         counter.incrementCountOrThrow(UID_A)
         counter.incrementCountOrThrow(UID_A)
+        assertEquals(3, counter[UID_A])
+        assertEquals(2, counter[UID_B])
         assertFailsWith<IllegalStateException> {
             counter.incrementCountOrThrow(UID_A)
         }
+        counter.incrementCountOrThrow(UID_B)
         assertFailsWith<IllegalStateException> {
             counter.incrementCountOrThrow(UID_B)
         }
@@ -71,39 +77,66 @@
             counter.incrementCountOrThrow(UID_A)
         }
         assertFailsWith<IllegalStateException> {
-            counter.incrementCountOrThrow(UID_A, 3)
+            repeat(3) {
+                counter.incrementCountOrThrow(UID_A)
+            }
         }
+        assertEquals(3, counter[UID_A])
+        assertEquals(3, counter[UID_B])
+        assertEquals(0, counter[UID_C])
     }
 
     @Test
     fun testDecrementCountOrThrow() {
         val counter = PerUidCounter(3)
 
-        // Verify the decrement count cannot be zero.
-        assertFailsWith<IllegalArgumentException> {
-            counter.decrementCountOrThrow(UID_A, 0)
-        }
-
         // Verify the count cannot go below zero.
         assertFailsWith<IllegalStateException> {
             counter.decrementCountOrThrow(UID_A)
         }
         assertFailsWith<IllegalStateException> {
-            counter.decrementCountOrThrow(UID_A, 5)
-        }
-        assertFailsWith<IllegalStateException> {
-            counter.decrementCountOrThrow(UID_A, Integer.MAX_VALUE)
+            repeat(5) {
+                counter.decrementCountOrThrow(UID_A)
+            }
         }
 
         // Verify the counters work independently.
         counter.incrementCountOrThrow(UID_A)
         counter.incrementCountOrThrow(UID_B)
+        assertEquals(1, counter[UID_A])
+        assertEquals(1, counter[UID_B])
         assertFailsWith<IllegalStateException> {
-            counter.decrementCountOrThrow(UID_A, 3)
+            repeat(3) {
+                counter.decrementCountOrThrow(UID_A)
+            }
         }
-        counter.decrementCountOrThrow(UID_A)
         assertFailsWith<IllegalStateException> {
             counter.decrementCountOrThrow(UID_A)
         }
+        assertEquals(0, counter[UID_A])
+        assertEquals(1, counter[UID_B])
+
+        // Verify mixing increment and decrement.
+        val largeCounter = PerUidCounter(100)
+        repeat(90) {
+            largeCounter.incrementCountOrThrow(UID_A)
+        }
+        repeat(70) {
+            largeCounter.decrementCountOrThrow(UID_A)
+        }
+        repeat(80) {
+            largeCounter.incrementCountOrThrow(UID_A)
+        }
+        assertFailsWith<IllegalStateException> {
+            largeCounter.incrementCountOrThrow(UID_A)
+        }
+        assertEquals(100, largeCounter[UID_A])
+        repeat(100) {
+            largeCounter.decrementCountOrThrow(UID_A)
+        }
+        assertFailsWith<IllegalStateException> {
+            largeCounter.decrementCountOrThrow(UID_A)
+        }
+        assertEquals(0, largeCounter[UID_A])
     }
 }
\ No newline at end of file
diff --git a/staticlibs/testutils/app/connectivitychecker/src/com/android/testutils/connectivitychecker/ConnectivityCheckTest.kt b/staticlibs/testutils/app/connectivitychecker/src/com/android/testutils/connectivitychecker/ConnectivityCheckTest.kt
index 43b130b..f34ca22 100644
--- a/staticlibs/testutils/app/connectivitychecker/src/com/android/testutils/connectivitychecker/ConnectivityCheckTest.kt
+++ b/staticlibs/testutils/app/connectivitychecker/src/com/android/testutils/connectivitychecker/ConnectivityCheckTest.kt
@@ -18,10 +18,17 @@
 
 import android.content.pm.PackageManager.FEATURE_TELEPHONY
 import android.content.pm.PackageManager.FEATURE_WIFI
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET
+import android.net.NetworkCapabilities.TRANSPORT_CELLULAR
+import android.net.NetworkRequest
 import android.telephony.TelephonyManager
 import androidx.test.ext.junit.runners.AndroidJUnit4
 import androidx.test.platform.app.InstrumentationRegistry
 import com.android.testutils.ConnectUtil
+import com.android.testutils.RecorderCallback
+import com.android.testutils.TestableNetworkCallback
+import com.android.testutils.tryTest
 import org.junit.Test
 import org.junit.runner.RunWith
 import kotlin.test.assertTrue
@@ -61,5 +68,20 @@
         assertTrue(tm.isDataConnectivityPossible,
             "The device is not setup with a SIM card that supports data connectivity. " +
                     commonError)
+        val cb = TestableNetworkCallback()
+        val cm = context.getSystemService(ConnectivityManager::class.java)
+                ?: fail("Could not get ConnectivityManager")
+        cm.registerNetworkCallback(
+                NetworkRequest.Builder()
+                        .addTransportType(TRANSPORT_CELLULAR)
+                        .addCapability(NET_CAPABILITY_INTERNET).build(), cb)
+        tryTest {
+            cb.eventuallyExpectOrNull<RecorderCallback.CallbackEntry.Available>()
+                    ?: fail("The device does not have mobile data available. Check that it is " +
+                            "setup with a SIM card that has a working data plan, and that the " +
+                            "APN configuration is valid.")
+        } cleanup {
+            cm.unregisterNetworkCallback(cb)
+        }
     }
 }
\ No newline at end of file
diff --git a/staticlibs/testutils/devicetests/com/android/testutils/TestPermissionUtil.kt b/staticlibs/testutils/devicetests/com/android/testutils/TestPermissionUtil.kt
index a4dbd9a..f571f64 100644
--- a/staticlibs/testutils/devicetests/com/android/testutils/TestPermissionUtil.kt
+++ b/staticlibs/testutils/devicetests/com/android/testutils/TestPermissionUtil.kt
@@ -20,8 +20,8 @@
 
 import androidx.test.platform.app.InstrumentationRegistry
 import com.android.modules.utils.build.SdkLevel
-import com.android.testutils.ExceptionUtils.ThrowingRunnable
-import com.android.testutils.ExceptionUtils.ThrowingSupplier
+import com.android.testutils.FunctionalUtils.ThrowingRunnable
+import com.android.testutils.FunctionalUtils.ThrowingSupplier
 
 /**
  * Run the specified [task] with the specified [permissions] obtained through shell
diff --git a/staticlibs/testutils/hostdevice/com/android/testutils/Cleanup.kt b/staticlibs/testutils/hostdevice/com/android/testutils/Cleanup.kt
index 3db357b..9f28234 100644
--- a/staticlibs/testutils/hostdevice/com/android/testutils/Cleanup.kt
+++ b/staticlibs/testutils/hostdevice/com/android/testutils/Cleanup.kt
@@ -18,8 +18,8 @@
 
 package com.android.testutils
 
-import com.android.testutils.ExceptionUtils.ThrowingRunnable
-import com.android.testutils.ExceptionUtils.ThrowingSupplier
+import com.android.testutils.FunctionalUtils.ThrowingRunnable
+import com.android.testutils.FunctionalUtils.ThrowingSupplier
 import javax.annotation.CheckReturnValue
 
 /**
diff --git a/staticlibs/testutils/hostdevice/com/android/testutils/ExceptionUtils.java b/staticlibs/testutils/hostdevice/com/android/testutils/FunctionalUtils.java
similarity index 74%
rename from staticlibs/testutils/hostdevice/com/android/testutils/ExceptionUtils.java
rename to staticlibs/testutils/hostdevice/com/android/testutils/FunctionalUtils.java
index d3bda98..da36e4d 100644
--- a/staticlibs/testutils/hostdevice/com/android/testutils/ExceptionUtils.java
+++ b/staticlibs/testutils/hostdevice/com/android/testutils/FunctionalUtils.java
@@ -21,7 +21,7 @@
 /**
  * A class grouping some utilities to deal with exceptions.
  */
-public class ExceptionUtils {
+public class FunctionalUtils {
     /**
      * Like a Consumer, but declared to throw an exception.
      * @param <T>
@@ -79,4 +79,21 @@
             }
         };
     }
+
+    // Java has Function<T, R> and BiFunction<T, U, V> but nothing for higher-arity functions.
+    // Function3 is what Kotlin and Scala use (they also have higher-arity variants, with
+    // FunctionN taking N arguments, as the JVM does not have variadic formal parameters)
+    /**
+     * A function with three arguments.
+     * @param <TArg1> Type of the first argument
+     * @param <TArg2> Type of the second argument
+     * @param <TArg3> Type of the third argument
+     * @param <TResult> Type of the return value
+     */
+    public interface Function3<TArg1, TArg2, TArg3, TResult> {
+        /**
+         * Apply the function to the arguments
+         */
+        TResult apply(TArg1 a1, TArg2 a2, TArg3 a3);
+    }
 }
diff --git a/staticlibs/testutils/hostdevice/com/android/testutils/MiscAsserts.kt b/staticlibs/testutils/hostdevice/com/android/testutils/MiscAsserts.kt
index efd9402..1883387 100644
--- a/staticlibs/testutils/hostdevice/com/android/testutils/MiscAsserts.kt
+++ b/staticlibs/testutils/hostdevice/com/android/testutils/MiscAsserts.kt
@@ -18,7 +18,7 @@
 
 package com.android.testutils
 
-import com.android.testutils.ExceptionUtils.ThrowingRunnable
+import com.android.testutils.FunctionalUtils.ThrowingRunnable
 import java.lang.reflect.Modifier
 import kotlin.system.measureTimeMillis
 import kotlin.test.assertEquals