Merge "Add shims for ConnectivityFrameworkInitializer"
diff --git a/Android.bp b/Android.bp
index ebd81cd..cfe9353 100644
--- a/Android.bp
+++ b/Android.bp
@@ -45,6 +45,8 @@
     default_applicable_licenses: ["Android-Apache-2.0"],
 }
 
+// TODO: remove this default and replace with ConnectivityNextEnableDefaults. This will need to be
+// done separately in each branch due to merge conflicts.
 // Defaults to enable/disable java targets that depend on
 // NetworkStackNext, which uses development APIs. "enabled" may
 // have a different value depending on the branch.
@@ -159,7 +161,7 @@
 // integer so if the next SDK release happens to use that integer, we don't need to rename them.
 java_library {
     name: "NetworkStackApi33Shims",
-    defaults: ["NetworkStackShimsDefaults"],
+    defaults: ["NetworkStackShimsDefaults", "ConnectivityNextEnableDefaults"],
     srcs: [
         "apishim/33/**/*.java",
     ],
@@ -168,6 +170,7 @@
         "NetworkStackApi29Shims",
         "NetworkStackApi30Shims",
         "NetworkStackApi31Shims",
+        "framework-bluetooth",
         "framework-connectivity",
         "framework-connectivity-tiramisu.stubs.module_lib",
         "framework-tethering",
@@ -181,7 +184,7 @@
 // called directly by the networkstack code.
 java_library {
     name: "NetworkStackApiCurrentShims",
-    defaults: ["NetworkStackShimsDefaults"],
+    defaults: ["NetworkStackShimsDefaults", "ConnectivityNextEnableDefaults"],
     static_libs: [
         "NetworkStackShimsCommon",
         "NetworkStackApi29Shims",
@@ -192,6 +195,8 @@
     sdk_version: "module_current",
     visibility: [
         "//packages/modules/Connectivity/Tethering",
+        "//packages/modules/Connectivity/service",
+        "//packages/modules/Connectivity/service-t",
         "//packages/modules/Connectivity/tests/cts/net",
         "//packages/modules/Connectivity/tests/cts/hostside/app",
     ],
@@ -213,6 +218,8 @@
     sdk_version: "module_31",
     visibility: [
         "//packages/modules/Connectivity/Tethering",
+        "//packages/modules/Connectivity/service",
+        "//packages/modules/Connectivity/service-t",
         "//packages/modules/Connectivity/tests/cts/net",
         "//packages/modules/Connectivity/tests/cts/hostside/app",
     ],
@@ -251,7 +258,7 @@
     defaults: [
         "NetworkStackDevApiLevel",
         "NetworkStackAndroidLibraryDefaults",
-        "NetworkStackNextEnableDefaults",
+        "ConnectivityNextEnableDefaults",
     ],
     srcs: [
         "src/**/*.java",
@@ -324,7 +331,7 @@
     defaults: [
         "NetworkStackAppDefaults",
         "NetworkStackDevApiLevel",
-        "NetworkStackNextEnableDefaults",
+        "ConnectivityNextEnableDefaults",
     ],
     static_libs: ["NetworkStackApiCurrentLib"],
     certificate: "platform",
@@ -346,7 +353,7 @@
     defaults: [
         "NetworkStackAppDefaults",
         "NetworkStackDevApiLevel",
-        "NetworkStackNextEnableDefaults",
+        "ConnectivityNextEnableDefaults",
     ],
     static_libs: ["NetworkStackApiCurrentLib"],
     manifest: "AndroidManifest.xml"
@@ -358,7 +365,7 @@
     defaults: [
         "NetworkStackAppDefaults",
         "NetworkStackDevApiLevel",
-        "NetworkStackNextEnableDefaults",
+        "ConnectivityNextEnableDefaults",
     ],
     static_libs: ["NetworkStackNextManifestBase"],
     certificate: "networkstack",
diff --git a/apishim/29/com/android/networkstack/apishim/api29/TelephonyManagerShimImpl.java b/apishim/29/com/android/networkstack/apishim/api29/TelephonyManagerShimImpl.java
new file mode 100644
index 0000000..376c4f3
--- /dev/null
+++ b/apishim/29/com/android/networkstack/apishim/api29/TelephonyManagerShimImpl.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2021 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.apishim.api29;
+
+import android.os.Build;
+import android.telephony.TelephonyManager;
+
+import androidx.annotation.RequiresApi;
+
+import com.android.networkstack.apishim.common.TelephonyManagerShim;
+
+/**
+ * Implementation of {@link TelephonyManagerShim} for API 29.
+ */
+@RequiresApi(Build.VERSION_CODES.Q)
+public class TelephonyManagerShimImpl implements TelephonyManagerShim {
+    protected final TelephonyManager mTm;
+    public TelephonyManagerShimImpl(TelephonyManager tm) {
+        mTm = tm;
+    }
+}
diff --git a/apishim/30/com/android/networkstack/apishim/api30/TelephonyManagerShimImpl.java b/apishim/30/com/android/networkstack/apishim/api30/TelephonyManagerShimImpl.java
new file mode 100644
index 0000000..67344f5
--- /dev/null
+++ b/apishim/30/com/android/networkstack/apishim/api30/TelephonyManagerShimImpl.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2021 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.apishim.api30;
+
+import android.os.Build;
+import android.telephony.TelephonyManager;
+
+import androidx.annotation.RequiresApi;
+
+import com.android.networkstack.apishim.common.TelephonyManagerShim;
+
+/**
+ * Implementation of {@link TelephonyManagerShim} for API 30.
+ */
+@RequiresApi(Build.VERSION_CODES.R)
+public class TelephonyManagerShimImpl
+        extends com.android.networkstack.apishim.api29.TelephonyManagerShimImpl {
+    public TelephonyManagerShimImpl(TelephonyManager telephonyManager) {
+        super(telephonyManager);
+    }
+}
diff --git a/apishim/31/com/android/networkstack/apishim/api31/ConstantsShim.java b/apishim/31/com/android/networkstack/apishim/api31/ConstantsShim.java
index 95ff072..e73e7f5 100644
--- a/apishim/31/com/android/networkstack/apishim/api31/ConstantsShim.java
+++ b/apishim/31/com/android/networkstack/apishim/api31/ConstantsShim.java
@@ -34,4 +34,11 @@
     // When removing this shim, the version in NetworkMonitorUtils should be removed too.
     // TODO: add TRANSPORT_TEST to system API in API 31 (it is only a test API as of R)
     public static final int TRANSPORT_TEST = 7;
+
+    /**
+     * Flag for {@link android.content.Context#registerReceiver}: The receiver cannot receive
+     * broadcasts from other apps; has the same behavior as marking a statically registered receiver
+     * with "exported=false".
+     */
+    public static final int RECEIVER_NOT_EXPORTED = 0x4;
 }
diff --git a/apishim/31/com/android/networkstack/apishim/api31/TelephonyManagerShimImpl.java b/apishim/31/com/android/networkstack/apishim/api31/TelephonyManagerShimImpl.java
new file mode 100644
index 0000000..74d200d
--- /dev/null
+++ b/apishim/31/com/android/networkstack/apishim/api31/TelephonyManagerShimImpl.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright (C) 2021 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.apishim.api31;
+
+import android.os.Build;
+import android.telephony.TelephonyManager;
+
+import androidx.annotation.RequiresApi;
+
+import com.android.networkstack.apishim.common.TelephonyManagerShim;
+
+/**
+ * Implementation of {@link TelephonyManagerShim} for API 31.
+ */
+@RequiresApi(Build.VERSION_CODES.S)
+public class TelephonyManagerShimImpl
+        extends com.android.networkstack.apishim.api30.TelephonyManagerShimImpl {
+    public TelephonyManagerShimImpl(TelephonyManager telephonyManager) {
+        super(telephonyManager);
+    }
+}
diff --git a/apishim/33/com/android/networkstack/apishim/TelephonyManagerShimImpl.java b/apishim/33/com/android/networkstack/apishim/TelephonyManagerShimImpl.java
new file mode 100644
index 0000000..98e061d
--- /dev/null
+++ b/apishim/33/com/android/networkstack/apishim/TelephonyManagerShimImpl.java
@@ -0,0 +1,73 @@
+/*
+ * 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.networkstack.apishim;
+
+import android.os.Build;
+import android.telephony.TelephonyManager;
+import android.telephony.TelephonyManager.CarrierPrivilegesListener;
+
+import androidx.annotation.RequiresApi;
+
+import com.android.networkstack.apishim.common.TelephonyManagerShim;
+import com.android.networkstack.apishim.common.UnsupportedApiLevelException;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.concurrent.Executor;
+
+/**
+ * Implementation of {@link TelephonyManagerShim} for API 33.
+ */
+@RequiresApi(Build.VERSION_CODES.TIRAMISU)
+public class TelephonyManagerShimImpl extends
+        com.android.networkstack.apishim.api31.TelephonyManagerShimImpl {
+    private HashMap<CarrierPrivilegesListenerShim, CarrierPrivilegesListener> mListenerMap =
+            new HashMap<>();
+    public TelephonyManagerShimImpl(TelephonyManager telephonyManager) {
+        super(telephonyManager);
+    }
+
+    /** See android.telephony.TelephonyManager#addCarrierPrivilegesListener */
+    public void addCarrierPrivilegesListener(
+            int logicalSlotIndex,
+            Executor executor,
+            CarrierPrivilegesListenerShim listener)
+            throws UnsupportedApiLevelException {
+        CarrierPrivilegesListener carrierPrivilegesListener = new CarrierPrivilegesListener() {
+            public void onCarrierPrivilegesChanged(
+                    List<String> privilegedPackageNames,
+                    int[] privilegedUids) {
+                listener.onCarrierPrivilegesChanged(privilegedPackageNames, privilegedUids);
+            }
+        };
+        mTm.addCarrierPrivilegesListener(logicalSlotIndex, executor, carrierPrivilegesListener);
+        mListenerMap.put(listener, carrierPrivilegesListener);
+    }
+
+    /** See android.telephony.TelephonyManager#addCarrierPrivilegesListener */
+    public void removeCarrierPrivilegesListener(
+            CarrierPrivilegesListenerShim listener)
+            throws UnsupportedApiLevelException {
+        mTm.removeCarrierPrivilegesListener(mListenerMap.get(listener));
+        mListenerMap.remove(listener);
+    }
+
+    /** See android.telephony.TelephonyManager#getCarrierServicePackageNameForLogicalSlot */
+    public String getCarrierServicePackageNameForLogicalSlot(int logicalSlotIndex) {
+        return mTm.getCarrierServicePackageNameForLogicalSlot(logicalSlotIndex);
+    }
+}
diff --git a/apishim/common/com/android/networkstack/apishim/common/TelephonyManagerShim.java b/apishim/common/com/android/networkstack/apishim/common/TelephonyManagerShim.java
new file mode 100644
index 0000000..492624a
--- /dev/null
+++ b/apishim/common/com/android/networkstack/apishim/common/TelephonyManagerShim.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2021 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.apishim.common;
+
+import java.util.List;
+import java.util.concurrent.Executor;
+
+/**
+ * Interface used to access API methods in {@link android.telephony.TelephonyManager}, with
+ * appropriate fallbacks if the methods are not yet part of the released API.
+ *
+ * <p>This interface makes it easier for callers to use TelephonyManagerShimImpl, as it's more
+ * obvious what methods must be implemented on each API level, and it abstracts from callers the
+ * need to reference classes that have different implementations (which also does not work well
+ * with IDEs).
+ */
+public interface TelephonyManagerShim {
+    /** See android.telephony.TelephonyManager.CarrierPrivilegesListener */
+    public interface CarrierPrivilegesListenerShim {
+        /** See android.telephony.TelephonyManager
+         * .CarrierPrivilegesListener#onCarrierPrivilegesChanged */
+        void onCarrierPrivilegesChanged(
+                List<String> privilegedPackageNames,
+                int[] privilegedUids);
+    }
+
+    /** See android.telephony.TelephonyManager#addCarrierPrivilegesListener */
+    default void addCarrierPrivilegesListener(
+            int logicalSlotIndex,
+            Executor executor,
+            CarrierPrivilegesListenerShim listener)
+            throws UnsupportedApiLevelException {
+        throw new UnsupportedApiLevelException("Only supported starting from API 33");
+    }
+
+    /** See android.telephony.TelephonyManager#addCarrierPrivilegesListener */
+    default void removeCarrierPrivilegesListener(
+            CarrierPrivilegesListenerShim listener)
+            throws UnsupportedApiLevelException {
+        throw new UnsupportedApiLevelException("Only supported starting from API 33");
+    }
+
+    /** See android.telephony.TelephonyManager#getCarrierServicePackageNameForLogicalSlot */
+    default String getCarrierServicePackageNameForLogicalSlot(int logicalSlotIndex)
+            throws UnsupportedApiLevelException {
+        throw new UnsupportedApiLevelException("Only supported starting from API 33");
+    }
+}
diff --git a/src/com/android/server/connectivity/NetworkMonitor.java b/src/com/android/server/connectivity/NetworkMonitor.java
index 948ce8d..72c55df 100755
--- a/src/com/android/server/connectivity/NetworkMonitor.java
+++ b/src/com/android/server/connectivity/NetworkMonitor.java
@@ -83,6 +83,7 @@
 import static com.android.net.module.util.DeviceConfigUtils.getResBooleanConfig;
 import static com.android.networkstack.apishim.ConstantsShim.DETECTION_METHOD_DNS_EVENTS;
 import static com.android.networkstack.apishim.ConstantsShim.DETECTION_METHOD_TCP_METRICS;
+import static com.android.networkstack.apishim.ConstantsShim.RECEIVER_NOT_EXPORTED;
 import static com.android.networkstack.apishim.ConstantsShim.TRANSPORT_TEST;
 import static com.android.networkstack.util.DnsUtils.PRIVATE_DNS_PROBE_HOST_SUFFIX;
 import static com.android.networkstack.util.DnsUtils.TYPE_ADDRCONFIG;
@@ -157,6 +158,7 @@
 import com.android.internal.util.RingBufferIndices;
 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.DeviceConfigUtils;
 import com.android.net.module.util.NetworkStackConstants;
 import com.android.networkstack.NetworkStackNotifier;
@@ -1428,7 +1430,8 @@
             mToken = token;
             mWhat = what;
             mAction = action + "_" + mCleartextDnsNetwork.getNetworkHandle() + "_" + token;
-            mContext.registerReceiver(this, new IntentFilter(mAction));
+            final int flags = SdkLevel.isAtLeastT() ? RECEIVER_NOT_EXPORTED : 0;
+            mContext.registerReceiver(this, new IntentFilter(mAction), flags);
         }
         public PendingIntent getPendingIntent() {
             final Intent intent = new Intent(mAction);
diff --git a/tests/integration/Android.bp b/tests/integration/Android.bp
index 6056ee5..36c6162 100644
--- a/tests/integration/Android.bp
+++ b/tests/integration/Android.bp
@@ -81,7 +81,7 @@
     defaults: [
         "NetworkStackIntegrationTestsDefaults",
         "NetworkStackIntegrationTestsJniDefaults",
-        "NetworkStackNextEnableDefaults",
+        "ConnectivityNextEnableDefaults",
     ],
     static_libs: [
         "NetworkStackApiCurrentLib",
diff --git a/tests/integration/src/android/net/ip/IpClientIntegrationTestCommon.java b/tests/integration/src/android/net/ip/IpClientIntegrationTestCommon.java
index 22a4844..0ae7012 100644
--- a/tests/integration/src/android/net/ip/IpClientIntegrationTestCommon.java
+++ b/tests/integration/src/android/net/ip/IpClientIntegrationTestCommon.java
@@ -16,6 +16,7 @@
 
 package android.net.ip;
 
+import static android.Manifest.permission.MANAGE_TEST_NETWORKS;
 import static android.net.dhcp.DhcpClient.EXPIRED_LEASE;
 import static android.net.dhcp.DhcpPacket.DHCP_BOOTREQUEST;
 import static android.net.dhcp.DhcpPacket.DHCP_CLIENT;
@@ -58,6 +59,7 @@
 import static com.android.net.module.util.NetworkStackConstants.PIO_FLAG_AUTONOMOUS;
 import static com.android.net.module.util.NetworkStackConstants.PIO_FLAG_ON_LINK;
 import static com.android.testutils.MiscAsserts.assertThrows;
+import static com.android.testutils.TestPermissionUtil.runAsShell;
 
 import static junit.framework.Assert.fail;
 
@@ -641,19 +643,11 @@
 
     private void setUpTapInterface() throws Exception {
         final Instrumentation inst = InstrumentationRegistry.getInstrumentation();
-        // Adopt the shell permission identity to create a test TAP interface.
-        inst.getUiAutomation().adoptShellPermissionIdentity();
-
-        final TestNetworkInterface iface;
-        try {
-            final TestNetworkManager tnm = (TestNetworkManager)
-                    inst.getContext().getSystemService(Context.TEST_NETWORK_SERVICE);
-            iface = tnm.createTapInterface();
-        } finally {
-            // Drop the identity in order to regain the network stack permissions, which the shell
-            // does not have.
-            inst.getUiAutomation().dropShellPermissionIdentity();
-        }
+        final TestNetworkInterface iface = runAsShell(MANAGE_TEST_NETWORKS, () -> {
+            final TestNetworkManager tnm =
+                    inst.getContext().getSystemService(TestNetworkManager.class);
+            return tnm.createTapInterface();
+        });
         mIfaceName = iface.getInterfaceName();
         mClientMac = getIfaceMacAddr(mIfaceName).toByteArray();
         mPacketReaderThread = new HandlerThread(
diff --git a/tests/unit/Android.bp b/tests/unit/Android.bp
index 9f40ee9..7bb0d48 100644
--- a/tests/unit/Android.bp
+++ b/tests/unit/Android.bp
@@ -47,6 +47,7 @@
         "libnetworkstackutilsjni",
     ],
     jni_uses_sdk_apis: true,
+    exclude_kotlinc_generated_files: false,
 }
 
 // Tests for NetworkStackNext.
@@ -58,7 +59,7 @@
     test_suites: ["general-tests"],
     defaults: [
         "NetworkStackTestsDefaults",
-        "NetworkStackNextEnableDefaults",
+        "ConnectivityNextEnableDefaults",
         "connectivity-mainline-presubmit-java-defaults",
     ],
     static_libs: ["NetworkStackApiCurrentLib"],
diff --git a/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java b/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java
index ff43325..8099725 100644
--- a/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java
+++ b/tests/unit/src/com/android/server/connectivity/NetworkMonitorTest.java
@@ -555,6 +555,11 @@
             mRegisteredReceivers.add(invocation.getArgument(0));
             return new Intent();
         });
+        when(mContext.registerReceiver(any(BroadcastReceiver.class), any(), anyInt())).then(
+                (invocation) -> {
+                    mRegisteredReceivers.add(invocation.getArgument(0));
+                    return new Intent();
+                });
 
         doAnswer((invocation) -> {
             mRegisteredReceivers.remove(invocation.getArgument(0));