Merge "Remove dependency on compatibility-device-util-axt"
diff --git a/staticlibs/Android.bp b/staticlibs/Android.bp
index 047d51e..ef80170 100644
--- a/staticlibs/Android.bp
+++ b/staticlibs/Android.bp
@@ -116,6 +116,7 @@
         "device/com/android/net/module/util/JniUtil.java",
         "device/com/android/net/module/util/Struct.java",
         "device/com/android/net/module/util/TcUtils.java",
+        "device/com/android/net/module/util/bpf/*.java",
     ],
     sdk_version: "module_current",
     min_sdk_version: "29",
@@ -233,6 +234,7 @@
     libs: [
         "framework-annotations-lib",
         "framework-connectivity.stubs.module_lib",
+        "framework-connectivity-tiramisu.stubs.module_lib",
     ],
     jarjar_rules: "jarjar-rules-shared.txt",
     visibility: [
diff --git a/staticlibs/device/com/android/net/module/util/BpfMap.java b/staticlibs/device/com/android/net/module/util/BpfMap.java
index b42c388..d171b11 100644
--- a/staticlibs/device/com/android/net/module/util/BpfMap.java
+++ b/staticlibs/device/com/android/net/module/util/BpfMap.java
@@ -250,7 +250,7 @@
      * Otherwise, iteration will result in undefined behaviour.
      */
     @Override
-    public void forEach(BiConsumer<K, V> action) throws ErrnoException {
+    public void forEach(ThrowingBiConsumer<K, V> action) throws ErrnoException {
         @Nullable K nextKey = getFirstKey();
 
         while (nextKey != null) {
diff --git a/staticlibs/device/com/android/net/module/util/IBpfMap.java b/staticlibs/device/com/android/net/module/util/IBpfMap.java
index 708cf61..d43b22c 100644
--- a/staticlibs/device/com/android/net/module/util/IBpfMap.java
+++ b/staticlibs/device/com/android/net/module/util/IBpfMap.java
@@ -64,10 +64,14 @@
     /** Retrieve a value from the map. */
     V getValue(@NonNull K key) throws ErrnoException;
 
+    public interface ThrowingBiConsumer<T,U> {
+        void accept(T t, U u) throws ErrnoException;
+    }
+
     /**
      * Iterate through the map and handle each key -> value retrieved base on the given BiConsumer.
      */
-    void forEach(BiConsumer<K, V> action) throws ErrnoException;
+    void forEach(ThrowingBiConsumer<K, V> action) throws ErrnoException;
 
     /** Clears the map. */
     void clear() throws ErrnoException;
diff --git a/staticlibs/device/com/android/net/module/util/bpf/Tether4Key.java b/staticlibs/device/com/android/net/module/util/bpf/Tether4Key.java
new file mode 100644
index 0000000..638576f
--- /dev/null
+++ b/staticlibs/device/com/android/net/module/util/bpf/Tether4Key.java
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2020 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.bpf;
+
+import android.net.MacAddress;
+
+import androidx.annotation.NonNull;
+
+import com.android.net.module.util.Struct;
+import com.android.net.module.util.Struct.Field;
+import com.android.net.module.util.Struct.Type;
+
+import java.net.Inet4Address;
+import java.net.UnknownHostException;
+import java.util.Objects;
+
+/** Key type for downstream & upstream IPv4 forwarding maps. */
+public class Tether4Key extends Struct {
+    @Field(order = 0, type = Type.U32)
+    public final long iif;
+
+    @Field(order = 1, type = Type.EUI48)
+    public final MacAddress dstMac;
+
+    @Field(order = 2, type = Type.U8, padding = 1)
+    public final short l4proto;
+
+    @Field(order = 3, type = Type.ByteArray, arraysize = 4)
+    public final byte[] src4;
+
+    @Field(order = 4, type = Type.ByteArray, arraysize = 4)
+    public final byte[] dst4;
+
+    @Field(order = 5, type = Type.UBE16)
+    public final int srcPort;
+
+    @Field(order = 6, type = Type.UBE16)
+    public final int dstPort;
+
+    public Tether4Key(final long iif, @NonNull final MacAddress dstMac, final short l4proto,
+            final byte[] src4, final byte[] dst4, final int srcPort,
+            final int dstPort) {
+        Objects.requireNonNull(dstMac);
+
+        this.iif = iif;
+        this.dstMac = dstMac;
+        this.l4proto = l4proto;
+        this.src4 = src4;
+        this.dst4 = dst4;
+        this.srcPort = srcPort;
+        this.dstPort = dstPort;
+    }
+
+    @Override
+    public String toString() {
+        try {
+            return String.format(
+                    "iif: %d, dstMac: %s, l4proto: %d, src4: %s, dst4: %s, "
+                            + "srcPort: %d, dstPort: %d",
+                    iif, dstMac, l4proto,
+                    Inet4Address.getByAddress(src4), Inet4Address.getByAddress(dst4),
+                    Short.toUnsignedInt((short) srcPort), Short.toUnsignedInt((short) dstPort));
+        } catch (UnknownHostException | IllegalArgumentException e) {
+            return String.format("Invalid IP address", e);
+        }
+    }
+}
diff --git a/staticlibs/device/com/android/net/module/util/bpf/Tether4Value.java b/staticlibs/device/com/android/net/module/util/bpf/Tether4Value.java
new file mode 100644
index 0000000..de98766
--- /dev/null
+++ b/staticlibs/device/com/android/net/module/util/bpf/Tether4Value.java
@@ -0,0 +1,97 @@
+/*
+ * Copyright (C) 2020 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.bpf;
+
+import android.net.MacAddress;
+
+import androidx.annotation.NonNull;
+
+import com.android.net.module.util.Struct;
+import com.android.net.module.util.Struct.Field;
+import com.android.net.module.util.Struct.Type;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Objects;
+
+/** Value type for downstream & upstream IPv4 forwarding maps. */
+public class Tether4Value extends Struct {
+    @Field(order = 0, type = Type.U32)
+    public final long oif;
+
+    // The ethhdr struct which is defined in uapi/linux/if_ether.h
+    @Field(order = 1, type = Type.EUI48)
+    public final MacAddress ethDstMac;
+    @Field(order = 2, type = Type.EUI48)
+    public final MacAddress ethSrcMac;
+    @Field(order = 3, type = Type.UBE16)
+    public final int ethProto;  // Packet type ID field.
+
+    @Field(order = 4, type = Type.U16)
+    public final int pmtu;
+
+    @Field(order = 5, type = Type.ByteArray, arraysize = 16)
+    public final byte[] src46;
+
+    @Field(order = 6, type = Type.ByteArray, arraysize = 16)
+    public final byte[] dst46;
+
+    @Field(order = 7, type = Type.UBE16)
+    public final int srcPort;
+
+    @Field(order = 8, type = Type.UBE16)
+    public final int dstPort;
+
+    // TODO: consider using U64.
+    @Field(order = 9, type = Type.U63)
+    public final long lastUsed;
+
+    public Tether4Value(final long oif, @NonNull final MacAddress ethDstMac,
+            @NonNull final MacAddress ethSrcMac, final int ethProto, final int pmtu,
+            final byte[] src46, final byte[] dst46, final int srcPort,
+            final int dstPort, final long lastUsed) {
+        Objects.requireNonNull(ethDstMac);
+        Objects.requireNonNull(ethSrcMac);
+
+        this.oif = oif;
+        this.ethDstMac = ethDstMac;
+        this.ethSrcMac = ethSrcMac;
+        this.ethProto = ethProto;
+        this.pmtu = pmtu;
+        this.src46 = src46;
+        this.dst46 = dst46;
+        this.srcPort = srcPort;
+        this.dstPort = dstPort;
+        this.lastUsed = lastUsed;
+    }
+
+    @Override
+    public String toString() {
+        try {
+            return String.format(
+                    "oif: %d, ethDstMac: %s, ethSrcMac: %s, ethProto: %d, pmtu: %d, "
+                            + "src46: %s, dst46: %s, srcPort: %d, dstPort: %d, "
+                            + "lastUsed: %d",
+                    oif, ethDstMac, ethSrcMac, ethProto, pmtu,
+                    InetAddress.getByAddress(src46), InetAddress.getByAddress(dst46),
+                    Short.toUnsignedInt((short) srcPort), Short.toUnsignedInt((short) dstPort),
+                    lastUsed);
+        } catch (UnknownHostException | IllegalArgumentException e) {
+            return String.format("Invalid IP address", e);
+        }
+    }
+}
diff --git a/staticlibs/framework/com/android/net/module/util/CollectionUtils.java b/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
index 312ca48..a16ef33 100644
--- a/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
+++ b/staticlibs/framework/com/android/net/module/util/CollectionUtils.java
@@ -193,4 +193,30 @@
         }
         return total;
     }
+
+    /**
+     * Returns true if the first collection contains any of the elements of the second.
+     * @param haystack where to search
+     * @param needles what to search for
+     * @param <T> type of elements
+     * @return true if |haystack| contains any of the |needles|, false otherwise
+     */
+    public static <T> boolean containsAny(Collection<T> haystack, Collection<? extends T> needles) {
+        for (T needle : needles) {
+            if (haystack.contains(needle)) return true;
+        }
+        return false;
+    }
+
+    /**
+     * Returns true if the first collection contains all of the elements of the second.
+     * @param haystack where to search
+     * @param needles what to search for
+     * @param <T> type of elements
+     * @return true if |haystack| contains all of the |needles|, false otherwise
+     */
+    public static <T> boolean containsAll(Collection<T> haystack, Collection<? extends T> needles) {
+        return haystack.containsAll(needles);
+    }
+
 }
diff --git a/staticlibs/framework/com/android/net/module/util/PermissionUtils.java b/staticlibs/framework/com/android/net/module/util/PermissionUtils.java
index 0f3dc15..be5b0cd 100644
--- a/staticlibs/framework/com/android/net/module/util/PermissionUtils.java
+++ b/staticlibs/framework/com/android/net/module/util/PermissionUtils.java
@@ -19,17 +19,21 @@
 import static android.Manifest.permission.ACCESS_NETWORK_STATE;
 import static android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS;
 import static android.Manifest.permission.NETWORK_STACK;
+import static android.content.pm.PackageInfo.REQUESTED_PERMISSION_GRANTED;
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
 import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.content.Context;
+import android.content.pm.PackageInfo;
 import android.os.Binder;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
 
 /**
  * Collection of permission utilities.
@@ -144,4 +148,25 @@
             throw new UnsupportedOperationException(errorMessage);
         }
     }
+
+    /**
+     * Get the list of granted permissions for a package info.
+     *
+     * PackageInfo contains the list of requested permissions, and their state (whether they
+     * were granted or not, in particular) as a parallel array. Most users care only about
+     * granted permissions. This method returns the list of them.
+     *
+     * @param packageInfo the package info for the relevant uid.
+     * @return the list of granted permissions.
+     */
+    public static List<String> getGrantedPermissions(final @NonNull PackageInfo packageInfo) {
+        if (null == packageInfo.requestedPermissions) return Collections.emptyList();
+        final ArrayList<String> result = new ArrayList<>(packageInfo.requestedPermissions.length);
+        for (int i = 0; i < packageInfo.requestedPermissions.length; ++i) {
+            if (0 != (REQUESTED_PERMISSION_GRANTED & packageInfo.requestedPermissionsFlags[i])) {
+                result.add(packageInfo.requestedPermissions[i]);
+            }
+        }
+        return result;
+    }
 }
diff --git a/staticlibs/native/bpf_headers/Android.bp b/staticlibs/native/bpf_headers/Android.bp
index ebb5678..4c8e728 100644
--- a/staticlibs/native/bpf_headers/Android.bp
+++ b/staticlibs/native/bpf_headers/Android.bp
@@ -18,7 +18,7 @@
 
 cc_library_headers {
     name: "bpf_headers",
-    vendor_available: false,
+    vendor_available: true,
     host_supported: true,
     native_bridge_supported: true,
     header_libs: ["bpf_syscall_wrappers"],
@@ -35,29 +35,6 @@
         "com.android.tethering",
         "com.android.art.debug",
     ],
-    visibility: [
-        "//bootable/libbootloader/vts",
-        "//cts/tests/tests/net/native",
-        "//frameworks/base/services/core/jni",
-        "//frameworks/native/libs/cputimeinstate",
-        "//frameworks/native/services/gpuservice",
-        "//frameworks/native/services/gpuservice/gpumem",
-        "//frameworks/native/services/gpuservice/tests/unittests",
-        "//frameworks/native/services/gpuservice/tracing",
-        "//packages/modules/Connectivity/bpf_progs",
-        "//packages/modules/Connectivity/netd",
-        "//packages/modules/Connectivity/service/native",
-        "//packages/modules/Connectivity/service/native/libs/libclat",
-        "//packages/modules/Connectivity/tests/unit/jni",
-        "//packages/modules/DnsResolver/tests",
-        "//system/bpf/bpfloader",
-        "//system/bpf/libbpf_android",
-        "//system/memory/libmeminfo",
-        "//system/netd/server",
-        "//system/netd/tests",
-        "//system/netd/tests/benchmarks",
-        "//test/vts-testcase/kernel/api/bpf_native_test",
-    ],
 }
 
 
@@ -73,9 +50,9 @@
         "-Werror",
         "-Wno-error=unused-variable",
     ],
+    header_libs: ["bpf_headers"],
     static_libs: ["libgmock"],
     shared_libs: [
-        "libbpf_android",
         "libbase",
         "liblog",
         "libutils",
diff --git a/staticlibs/native/bpf_headers/include/bpf/bpf_map_def.h b/staticlibs/native/bpf_headers/include/bpf/bpf_map_def.h
index 02b2096..1371668 100644
--- a/staticlibs/native/bpf_headers/include/bpf/bpf_map_def.h
+++ b/staticlibs/native/bpf_headers/include/bpf/bpf_map_def.h
@@ -23,7 +23,7 @@
 #include <linux/bpf.h>
 
 // Pull in AID_* constants from //system/core/libcutils/include/private/android_filesystem_config.h
-#include <private/android_filesystem_config.h>
+#include <cutils/android_filesystem_config.h>
 
 /******************************************************************************
  *                                                                            *
diff --git a/staticlibs/native/bpf_syscall_wrappers/Android.bp b/staticlibs/native/bpf_syscall_wrappers/Android.bp
index 26f311b..f41a244 100644
--- a/staticlibs/native/bpf_syscall_wrappers/Android.bp
+++ b/staticlibs/native/bpf_syscall_wrappers/Android.bp
@@ -18,7 +18,7 @@
 
 cc_library_headers {
     name: "bpf_syscall_wrappers",
-    vendor_available: false,
+    vendor_available: true,
     host_supported: true,
     native_bridge_supported: true,
     export_include_dirs: ["include"],
@@ -30,20 +30,8 @@
     min_sdk_version: "30",
     apex_available: [
         "//apex_available:platform",
+        "com.android.art.debug",
         "com.android.mediaprovider",
         "com.android.tethering",
     ],
-    visibility: [
-        "//frameworks/libs/net/common/native/bpf_headers",
-        "//frameworks/libs/net/common/native/bpfmapjni",
-        "//frameworks/libs/net/common/native/tcutils",
-        "//packages/modules/Connectivity/netd",
-        "//packages/modules/Connectivity/service",
-        "//packages/modules/Connectivity/service/native",
-        "//packages/modules/Connectivity/service/native/libs/libclat",
-        "//packages/modules/Connectivity/Tethering",
-        "//packages/providers/MediaProvider/jni",
-        "//system/bpf/libbpf_android",
-        "//system/memory/lmkd",
-    ],
 }
diff --git a/staticlibs/native/bpf_syscall_wrappers/include/BpfSyscallWrappers.h b/staticlibs/native/bpf_syscall_wrappers/include/BpfSyscallWrappers.h
index 72eebf3..abf83da 100644
--- a/staticlibs/native/bpf_syscall_wrappers/include/BpfSyscallWrappers.h
+++ b/staticlibs/native/bpf_syscall_wrappers/include/BpfSyscallWrappers.h
@@ -125,11 +125,12 @@
 }
 
 inline int attachProgram(bpf_attach_type type, const BPF_FD_TYPE prog_fd,
-                         const BPF_FD_TYPE cg_fd) {
+                         const BPF_FD_TYPE cg_fd, uint32_t flags = 0) {
     return bpf(BPF_PROG_ATTACH, {
                                         .target_fd = BPF_FD_TO_U32(cg_fd),
                                         .attach_bpf_fd = BPF_FD_TO_U32(prog_fd),
                                         .attach_type = type,
+                                        .attach_flags = flags,
                                 });
 }
 
@@ -140,6 +141,15 @@
                                 });
 }
 
+inline int detachSingleProgram(bpf_attach_type type, const BPF_FD_TYPE prog_fd,
+                               const BPF_FD_TYPE cg_fd) {
+    return bpf(BPF_PROG_DETACH, {
+                                        .target_fd = BPF_FD_TO_U32(cg_fd),
+                                        .attach_bpf_fd = BPF_FD_TO_U32(prog_fd),
+                                        .attach_type = type,
+                                });
+}
+
 }  // namespace bpf
 }  // namespace android
 
diff --git a/staticlibs/native/tcutils/tcutils.cpp b/staticlibs/native/tcutils/tcutils.cpp
index 0e17f67..144a4c9 100644
--- a/staticlibs/native/tcutils/tcutils.cpp
+++ b/staticlibs/native/tcutils/tcutils.cpp
@@ -196,7 +196,7 @@
                 .acts = {
                     .attr = {
                         .nla_len = sizeof(mRequest.opt.acts),
-                        .nla_type = TCA_U32_ACT,
+                        .nla_type = TCA_MATCHALL_ACT,
                     },
                     .act1 = {
                         .attr = {
diff --git a/staticlibs/testutils/devicetests/com/android/testutils/TestBpfMap.java b/staticlibs/testutils/devicetests/com/android/testutils/TestBpfMap.java
index 5614a99..73bc3a9 100644
--- a/staticlibs/testutils/devicetests/com/android/testutils/TestBpfMap.java
+++ b/staticlibs/testutils/devicetests/com/android/testutils/TestBpfMap.java
@@ -21,6 +21,7 @@
 import androidx.annotation.NonNull;
 
 import com.android.net.module.util.BpfMap;
+import com.android.net.module.util.IBpfMap.ThrowingBiConsumer;
 import com.android.net.module.util.Struct;
 
 import java.util.HashMap;
@@ -28,7 +29,6 @@
 import java.util.Map;
 import java.util.NoSuchElementException;
 import java.util.Objects;
-import java.util.function.BiConsumer;
 
 /**
  *
@@ -49,7 +49,7 @@
     }
 
     @Override
-    public void forEach(BiConsumer<K, V> action) throws ErrnoException {
+    public void forEach(ThrowingBiConsumer<K, V> action) throws ErrnoException {
         // TODO: consider using mocked #getFirstKey and #getNextKey to iterate. It helps to
         // implement the entry deletion in the iteration if required.
         for (Map.Entry<K, V> entry : mMap.entrySet()) {