Merge "Add findFirst and findLast to CollectionsUtils"
diff --git a/staticlibs/Android.bp b/staticlibs/Android.bp
index d13f938..4dfc752 100644
--- a/staticlibs/Android.bp
+++ b/staticlibs/Android.bp
@@ -37,6 +37,7 @@
       "device/com/android/net/module/util/DeviceConfigUtils.java",
       "device/com/android/net/module/util/FdEventsReader.java",
       "device/com/android/net/module/util/HexDump.java",
+      "device/com/android/net/module/util/NetworkMonitorUtils.java",
       "device/com/android/net/module/util/PacketReader.java",
       "device/com/android/net/module/util/SharedLog.java",
       // This library is used by system modules, for which the system health impact of Kotlin
@@ -69,6 +70,7 @@
   libs: [
       "androidx.annotation_annotation",
       "framework-annotations-lib",
+      "framework-connectivity.stubs.module_lib",
   ],
   lint: { strict_updatability_linting: true },
 }
@@ -282,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/NetworkMonitorUtils.java b/staticlibs/device/com/android/net/module/util/NetworkMonitorUtils.java
new file mode 100644
index 0000000..f6cd044
--- /dev/null
+++ b/staticlibs/device/com/android/net/module/util/NetworkMonitorUtils.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2019 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.net.module.util;
+
+import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
+import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
+import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
+import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
+import static android.net.NetworkCapabilities.NET_CAPABILITY_TRUSTED;
+import static android.net.NetworkCapabilities.TRANSPORT_BLUETOOTH;
+import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
+import static android.net.NetworkCapabilities.TRANSPORT_ETHERNET;
+import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
+
+import android.annotation.NonNull;
+import android.net.NetworkCapabilities;
+import android.os.Build;
+
+/** @hide */
+public class NetworkMonitorUtils {
+    // This class is used by both NetworkMonitor and ConnectivityService, so it cannot use
+    // NetworkStack shims, but at the same time cannot use non-system APIs.
+    // TRANSPORT_TEST is test API as of R (so it is enforced to always be 7 and can't be changed),
+    // and it is being added as a system API in S.
+    // TODO: use NetworkCapabilities.TRANSPORT_TEST once NetworkStack builds against API 31.
+    private static final int TRANSPORT_TEST = 7;
+
+    // This class is used by both NetworkMonitor and ConnectivityService, so it cannot use
+    // NetworkStack shims, but at the same time cannot use non-system APIs.
+    // NET_CAPABILITY_NOT_VCN_MANAGED is system API as of S (so it is enforced to always be 28 and
+    // can't be changed).
+    // TODO: use NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED once NetworkStack builds against
+    //       API 31.
+    public static final int NET_CAPABILITY_NOT_VCN_MANAGED = 28;
+
+    // Network conditions broadcast constants
+    public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
+            "android.net.conn.NETWORK_CONDITIONS_MEASURED";
+    public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
+    public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
+    public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
+    public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
+    public static final String EXTRA_CELL_ID = "extra_cellid";
+    public static final String EXTRA_SSID = "extra_ssid";
+    public static final String EXTRA_BSSID = "extra_bssid";
+    /** real time since boot */
+    public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
+    public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
+    public static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
+            "android.permission.ACCESS_NETWORK_CONDITIONS";
+
+    /**
+     * Return whether validation is required for private DNS in strict mode.
+     * @param nc Network capabilities of the network to test.
+     */
+    public static boolean isPrivateDnsValidationRequired(@NonNull final NetworkCapabilities nc) {
+        final boolean isVcnManaged = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
+                && !nc.hasCapability(NET_CAPABILITY_NOT_VCN_MANAGED);
+        final boolean isOemPaid = nc.hasCapability(NET_CAPABILITY_OEM_PAID)
+                && nc.hasCapability(NET_CAPABILITY_TRUSTED);
+        final boolean isDefaultCapable = nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)
+                && nc.hasCapability(NET_CAPABILITY_TRUSTED);
+
+        // TODO: Consider requiring validation for DUN networks.
+        if (nc.hasCapability(NET_CAPABILITY_INTERNET)
+                && (isVcnManaged || isOemPaid || isDefaultCapable)) {
+            return true;
+        }
+
+        // Test networks that also have one of the major transport types are attempting to replicate
+        // that transport on a test interface (for example, test ethernet networks with
+        // EthernetManager#setIncludeTestInterfaces). Run validation on them for realistic tests.
+        // See also comments on EthernetManager#setIncludeTestInterfaces and on TestNetworkManager.
+        if (nc.hasTransport(TRANSPORT_TEST) && nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) && (
+                nc.hasTransport(TRANSPORT_WIFI)
+                || nc.hasTransport(TRANSPORT_CELLULAR)
+                || nc.hasTransport(TRANSPORT_BLUETOOTH)
+                || nc.hasTransport(TRANSPORT_ETHERNET))) {
+            return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Return whether validation is required for a network.
+     * @param isVpnValidationRequired Whether network validation should be performed for VPN
+     *                                networks.
+     * @param nc Network capabilities of the network to test.
+     */
+    public static boolean isValidationRequired(boolean isVpnValidationRequired,
+            @NonNull final NetworkCapabilities nc) {
+        // TODO: Consider requiring validation for DUN networks.
+        if (!nc.hasCapability(NET_CAPABILITY_NOT_VPN)) {
+            return isVpnValidationRequired;
+        }
+        return isPrivateDnsValidationRequired(nc);
+    }
+}
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 73f6cd8..d1728c2 100644
--- a/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
+++ b/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
@@ -166,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.
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/native/tcutils/tests/tcutils_test.cpp b/staticlibs/native/tcutils/tests/tcutils_test.cpp
index 32736d6..8129286 100644
--- a/staticlibs/native/tcutils/tests/tcutils_test.cpp
+++ b/staticlibs/native/tcutils/tests/tcutils_test.cpp
@@ -113,12 +113,9 @@
 TEST(LibTcUtilsTest, AddAndDeleteIngressPoliceFilter) {
   // TODO: this should use bpf_shared.h rather than hardcoding the path
   static constexpr char bpfProgPath[] =
-      "/sys/fs/bpf/prog_netd_schedact_ingress_account";
+      "/sys/fs/bpf/netd_shared/prog_netd_schedact_ingress_account";
   int fd = bpf::retrieveProgram(bpfProgPath);
-  if (fd == -1) {
-    // ingress policing is not supported.
-    return;
-  }
+  ASSERT_LE(3, fd);
   close(fd);
 
   const int errNOENT = isAtLeastKernelVersion(4, 19, 0) ? ENOENT : EINVAL;
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 2de92f4..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,6 +18,7 @@
 
 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
@@ -52,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" })
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/tests/unit/src/com/android/net/module/util/netlink/StructInetDiagSockIdTest.java b/staticlibs/tests/unit/src/com/android/net/module/util/netlink/StructInetDiagSockIdTest.java
new file mode 100644
index 0000000..fb929fc
--- /dev/null
+++ b/staticlibs/tests/unit/src/com/android/net/module/util/netlink/StructInetDiagSockIdTest.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.net.module.util.netlink;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+
+import android.net.InetAddresses;
+
+import androidx.test.filters.SmallTest;
+import androidx.test.runner.AndroidJUnit4;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class StructInetDiagSockIdTest {
+    private static final Inet4Address IPV4_SRC_ADDR =
+            (Inet4Address) InetAddresses.parseNumericAddress("192.0.2.1");
+    private static final Inet4Address IPV4_DST_ADDR =
+            (Inet4Address) InetAddresses.parseNumericAddress("198.51.100.1");
+    private static final Inet6Address IPV6_SRC_ADDR =
+            (Inet6Address) InetAddresses.parseNumericAddress("2001:db8::1");
+    private static final Inet6Address IPV6_DST_ADDR =
+            (Inet6Address) InetAddresses.parseNumericAddress("2001:db8::2");
+    private static final int SRC_PORT = 65297;
+    private static final int DST_PORT = 443;
+
+    private static final byte[] INET_DIAG_SOCKET_ID_IPV4 =
+            new byte[] {
+                    // src port, dst port
+                    (byte) 0xff, (byte) 0x11, (byte) 0x01, (byte) 0xbb,
+                    // src address
+                    (byte) 0xc0, (byte) 0x00, (byte) 0x02, (byte) 0x01,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // dst address
+                    (byte) 0xc6, (byte) 0x33, (byte) 0x64, (byte) 0x01,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // if index
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // cookie
+                    (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+                    (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff
+            };
+
+    private static final byte[] INET_DIAG_SOCKET_ID_IPV6 =
+            new byte[] {
+                    // src port, dst port
+                    (byte) 0xff, (byte) 0x11, (byte) 0x01, (byte) 0xbb,
+                    // src address
+                    (byte) 0x20, (byte) 0x01, (byte) 0x0d, (byte) 0xb8,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01,
+                    // dst address
+                    (byte) 0x20, (byte) 0x01, (byte) 0x0d, (byte) 0xb8,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x02,
+                    // if index
+                    (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
+                    // cookie
+                    (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
+                    (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff
+            };
+
+    @Test
+    public void testPackStructInetDiagSockIdWithIpv4() {
+        final InetSocketAddress srcAddr = new InetSocketAddress(IPV4_SRC_ADDR, SRC_PORT);
+        final InetSocketAddress dstAddr = new InetSocketAddress(IPV4_DST_ADDR, DST_PORT);
+        final StructInetDiagSockId sockId = new StructInetDiagSockId(srcAddr, dstAddr);
+        final ByteBuffer buffer = ByteBuffer.allocate(StructInetDiagSockId.STRUCT_SIZE);
+        sockId.pack(buffer);
+        assertArrayEquals(INET_DIAG_SOCKET_ID_IPV4, buffer.array());
+    }
+
+    @Test
+    public void testPackStructInetDiagSockIdWithIpv6() {
+        final InetSocketAddress srcAddr = new InetSocketAddress(IPV6_SRC_ADDR, SRC_PORT);
+        final InetSocketAddress dstAddr = new InetSocketAddress(IPV6_DST_ADDR, DST_PORT);
+        final StructInetDiagSockId sockId = new StructInetDiagSockId(srcAddr, dstAddr);
+        final ByteBuffer buffer = ByteBuffer.allocate(StructInetDiagSockId.STRUCT_SIZE);
+        sockId.pack(buffer);
+        assertArrayEquals(INET_DIAG_SOCKET_ID_IPV6, buffer.array());
+    }
+
+    @Test
+    public void testToStringStructInetDiagSockIdWithIpv4() {
+        final InetSocketAddress srcAddr = new InetSocketAddress(IPV4_SRC_ADDR, SRC_PORT);
+        final InetSocketAddress dstAddr = new InetSocketAddress(IPV4_DST_ADDR, DST_PORT);
+        final StructInetDiagSockId sockId = new StructInetDiagSockId(srcAddr, dstAddr);
+        assertEquals("StructInetDiagSockId{ idiag_sport{65297}, idiag_dport{443},"
+                + " idiag_src{192.0.2.1}, idiag_dst{198.51.100.1}, idiag_if{0}"
+                + " idiag_cookie{INET_DIAG_NOCOOKIE}}", sockId.toString());
+    }
+
+    @Test
+    public void testToStringStructInetDiagSockIdWithIpv6() {
+        final InetSocketAddress srcAddr = new InetSocketAddress(IPV6_SRC_ADDR, SRC_PORT);
+        final InetSocketAddress dstAddr = new InetSocketAddress(IPV6_DST_ADDR, DST_PORT);
+        final StructInetDiagSockId sockId = new StructInetDiagSockId(srcAddr, dstAddr);
+        assertEquals("StructInetDiagSockId{ idiag_sport{65297}, idiag_dport{443},"
+                + " idiag_src{2001:db8::1}, idiag_dst{2001:db8::2}, idiag_if{0}"
+                + " idiag_cookie{INET_DIAG_NOCOOKIE}}", sockId.toString());
+    }
+}
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