From e7ccfca9da333e755d1b1fa9065543db788323b6 Mon Sep 17 00:00:00 2001 From: markchien Date: Mon, 16 Dec 2019 20:15:20 +0800 Subject: [PATCH] [Tether13] Move TetheringManager into framework Move tethering out of ConnectivityService. All client would use TetheringManager to talk with TetheringService directly. Bug: 144320246 Test: -build, flash, boot -atest TetheringTests Change-Id: Ib051bea724a256f9c4572b566e46ae7b9c4abe6e --- Tethering/Android.bp | 11 +- Tethering/AndroidManifest.xml | 15 + Tethering/AndroidManifest_InProcess.xml | 4 +- Tethering/CleanSpec.mk | 6 + Tethering/apex/Android.bp | 1 + Tethering/common/TetheringLib/Android.bp | 32 +- .../common/TetheringLib/jarjar-rules.txt | 1 + .../src/android/net/IIntResultListener.aidl | 25 + .../src/android/net/ITetheringConnector.aidl | 24 +- ...back.aidl => ITetheringEventCallback.aidl} | 9 +- .../src/android/net/TetheringManager.java | 625 +++++++++--------- Tethering/jarjar-rules.txt | 15 + Tethering/proguard.flags | 10 +- Tethering/src/android/net/ip/IpServer.java | 17 +- .../connectivity/tethering/Tethering.java | 86 ++- .../tethering/TetheringDependencies.java | 18 +- .../tethering/TetheringService.java | 253 ++++++- Tethering/tests/unit/Android.bp | 2 + Tethering/tests/unit/jarjar-rules.txt | 11 + .../connectivity/tethering/TetheringTest.java | 53 +- 20 files changed, 785 insertions(+), 433 deletions(-) create mode 100644 Tethering/common/TetheringLib/jarjar-rules.txt create mode 100644 Tethering/common/TetheringLib/src/android/net/IIntResultListener.aidl rename Tethering/common/TetheringLib/src/android/net/{ITetherInternalCallback.aidl => ITetheringEventCallback.aidl} (83%) create mode 100644 Tethering/jarjar-rules.txt create mode 100644 Tethering/tests/unit/jarjar-rules.txt diff --git a/Tethering/Android.bp b/Tethering/Android.bp index 3c953b348e..08552cbfd3 100644 --- a/Tethering/Android.bp +++ b/Tethering/Android.bp @@ -29,9 +29,11 @@ java_defaults { "netlink-client", "networkstack-aidl-interfaces-unstable-java", "android.hardware.tetheroffload.control-V1.0-java", - "tethering-client", ], - libs: ["unsupportedappusage"], + libs: [ + "framework-tethering", + ], + manifest: "AndroidManifestBase.xml", } @@ -90,6 +92,10 @@ java_defaults { resource_dirs: [ "res", ], + libs: [ + "framework-tethering", + ], + jarjar_rules: "jarjar-rules.txt", optimize: { proguard_flags_files: ["proguard.flags"], }, @@ -104,7 +110,6 @@ android_app { manifest: "AndroidManifest_InProcess.xml", // InProcessTethering is a replacement for Tethering overrides: ["Tethering"], - // TODO: use PlatformNetworkPermissionConfig. } // Updatable tethering packaged as an application diff --git a/Tethering/AndroidManifest.xml b/Tethering/AndroidManifest.xml index 8ba05df99e..87a8c3f5c6 100644 --- a/Tethering/AndroidManifest.xml +++ b/Tethering/AndroidManifest.xml @@ -21,6 +21,21 @@ android:sharedUserId="android.uid.networkstack"> + + + + + + + + + + + + - + android:permission="android.permission.MAINLINE_NETWORK_STACK"> diff --git a/Tethering/CleanSpec.mk b/Tethering/CleanSpec.mk index 70db351a69..30bdd581d0 100644 --- a/Tethering/CleanSpec.mk +++ b/Tethering/CleanSpec.mk @@ -46,6 +46,12 @@ $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/priv-app/Tethering) $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/priv-app/InProcessTethering) +$(call add-clean-step, rm -rf $(OUT_DIR)/target/common/obj/APPS/InProcessTethering*) +$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/InProcessTethering*) +$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system_other/system/priv-app/InProcessTethering) +$(call add-clean-step, rm -rf $(PRODUCT_OUT)/apex/com.android.tethering) +$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/apex/com.android.tethering.apex) +$(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/ETC/com.android.tethering*) # ****************************************************************** # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST ABOVE THIS BANNER diff --git a/Tethering/apex/Android.bp b/Tethering/apex/Android.bp index af6af93650..94ef11cc12 100644 --- a/Tethering/apex/Android.bp +++ b/Tethering/apex/Android.bp @@ -16,6 +16,7 @@ apex { name: "com.android.tethering", + java_libs: ["framework-tethering"], apps: ["Tethering"], manifest: "manifest.json", key: "com.android.tethering.key", diff --git a/Tethering/common/TetheringLib/Android.bp b/Tethering/common/TetheringLib/Android.bp index adc5a723a9..5785707cb9 100644 --- a/Tethering/common/TetheringLib/Android.bp +++ b/Tethering/common/TetheringLib/Android.bp @@ -12,7 +12,6 @@ // 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. -// // AIDL interfaces between the core system and the tethering mainline module. aidl_interface { @@ -20,10 +19,7 @@ aidl_interface { local_include_dir: "src", include_dirs: ["frameworks/base/core/java"], // For framework parcelables. srcs: [ - "src/android/net/ITetherInternalCallback.aidl", - "src/android/net/ITetheringConnector.aidl", - "src/android/net/TetheringConfigurationParcel.aidl", - "src/android/net/TetherStatesParcel.aidl", + "src/android/net/*.aidl", ], backend: { ndk: { @@ -36,16 +32,32 @@ aidl_interface { } java_library { - name: "tethering-client", + name: "framework-tethering", sdk_version: "system_current", + srcs: [ + "src/android/net/TetheringManager.java", + ":framework-tethering-annotations", + ], static_libs: [ "tethering-aidl-interfaces-java", ], + jarjar_rules: "jarjar-rules.txt", + installable: true, + + libs: [ + "android_system_stubs_current", + ], } -// This is temporary file group which would be removed after TetheringManager is built -// into tethering-client. Will be done by aosp/1156906. filegroup { - name: "tethering-manager", - srcs: ["src/android/net/TetheringManager.java"], + name: "framework-tethering-srcs", + srcs: [ + "src/android/net/TetheringManager.java", + "src/android/net/IIntResultListener.aidl", + "src/android/net/ITetheringEventCallback.aidl", + "src/android/net/ITetheringConnector.aidl", + "src/android/net/TetheringConfigurationParcel.aidl", + "src/android/net/TetherStatesParcel.aidl", + ], + path: "src" } diff --git a/Tethering/common/TetheringLib/jarjar-rules.txt b/Tethering/common/TetheringLib/jarjar-rules.txt new file mode 100644 index 0000000000..35e0f88e70 --- /dev/null +++ b/Tethering/common/TetheringLib/jarjar-rules.txt @@ -0,0 +1 @@ +rule android.annotation.** com.android.networkstack.tethering.annotation.@1 diff --git a/Tethering/common/TetheringLib/src/android/net/IIntResultListener.aidl b/Tethering/common/TetheringLib/src/android/net/IIntResultListener.aidl new file mode 100644 index 0000000000..c3d66ee145 --- /dev/null +++ b/Tethering/common/TetheringLib/src/android/net/IIntResultListener.aidl @@ -0,0 +1,25 @@ +/* + * 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 android.net; + +/** + * Listener interface allowing objects to listen to various module event. + * {@hide} + */ +oneway interface IIntResultListener { + void onResult(int resultCode); +} diff --git a/Tethering/common/TetheringLib/src/android/net/ITetheringConnector.aidl b/Tethering/common/TetheringLib/src/android/net/ITetheringConnector.aidl index bfe502fbeb..d30c399869 100644 --- a/Tethering/common/TetheringLib/src/android/net/ITetheringConnector.aidl +++ b/Tethering/common/TetheringLib/src/android/net/ITetheringConnector.aidl @@ -15,23 +15,31 @@ */ package android.net; -import android.net.ITetherInternalCallback; +import android.net.IIntResultListener; +import android.net.ITetheringEventCallback; import android.os.ResultReceiver; /** @hide */ oneway interface ITetheringConnector { - void tether(String iface); + void tether(String iface, String callerPkg, IIntResultListener receiver); - void untether(String iface); + void untether(String iface, String callerPkg, IIntResultListener receiver); - void setUsbTethering(boolean enable); + void setUsbTethering(boolean enable, String callerPkg, IIntResultListener receiver); - void startTethering(int type, in ResultReceiver receiver, boolean showProvisioningUi); + void startTethering(int type, in ResultReceiver receiver, boolean showProvisioningUi, + String callerPkg); - void stopTethering(int type); + void stopTethering(int type, String callerPkg, IIntResultListener receiver); void requestLatestTetheringEntitlementResult(int type, in ResultReceiver receiver, - boolean showEntitlementUi); + boolean showEntitlementUi, String callerPkg); - void registerTetherInternalCallback(ITetherInternalCallback callback); + void registerTetheringEventCallback(ITetheringEventCallback callback, String callerPkg); + + void unregisterTetheringEventCallback(ITetheringEventCallback callback, String callerPkg); + + void isTetheringSupported(String callerPkg, IIntResultListener receiver); + + void stopAllTethering(String callerPkg, IIntResultListener receiver); } diff --git a/Tethering/common/TetheringLib/src/android/net/ITetherInternalCallback.aidl b/Tethering/common/TetheringLib/src/android/net/ITetheringEventCallback.aidl similarity index 83% rename from Tethering/common/TetheringLib/src/android/net/ITetherInternalCallback.aidl rename to Tethering/common/TetheringLib/src/android/net/ITetheringEventCallback.aidl index abb00e819f..28361954e1 100644 --- a/Tethering/common/TetheringLib/src/android/net/ITetherInternalCallback.aidl +++ b/Tethering/common/TetheringLib/src/android/net/ITetheringEventCallback.aidl @@ -21,14 +21,15 @@ import android.net.TetheringConfigurationParcel; import android.net.TetherStatesParcel; /** - * Callback class for receiving tethering changed events + * Callback class for receiving tethering changed events. * @hide */ -oneway interface ITetherInternalCallback +oneway interface ITetheringEventCallback { + void onCallbackStarted(in Network network, in TetheringConfigurationParcel config, + in TetherStatesParcel states); + void onCallbackStopped(int errorCode); void onUpstreamChanged(in Network network); void onConfigurationChanged(in TetheringConfigurationParcel config); void onTetherStatesChanged(in TetherStatesParcel states); - void onCallbackCreated(in Network network, in TetheringConfigurationParcel config, - in TetherStatesParcel states); } diff --git a/Tethering/common/TetheringLib/src/android/net/TetheringManager.java b/Tethering/common/TetheringLib/src/android/net/TetheringManager.java index 7fb286b5fa..a49ab85d2f 100644 --- a/Tethering/common/TetheringLib/src/android/net/TetheringManager.java +++ b/Tethering/common/TetheringLib/src/android/net/TetheringManager.java @@ -15,94 +15,141 @@ */ package android.net; -import static android.Manifest.permission.NETWORK_STACK; import static android.net.ConnectivityManager.TETHER_ERROR_NO_ERROR; -import static android.net.ConnectivityManager.TETHER_ERROR_SERVICE_UNAVAIL; import android.annotation.NonNull; -import android.annotation.Nullable; -import android.net.util.SharedLog; +import android.content.Context; +import android.net.ConnectivityManager.OnTetheringEventCallback; import android.os.ConditionVariable; import android.os.IBinder; -import android.os.RemoteCallbackList; import android.os.RemoteException; import android.os.ResultReceiver; -import android.util.Slog; +import android.util.ArrayMap; +import android.util.Log; -import com.android.internal.annotations.GuardedBy; - -import java.io.PrintWriter; -import java.util.StringJoiner; +import java.util.concurrent.Executor; /** - * Service used to communicate with the tethering, which is running in a separate module. + * This class provides the APIs to control the tethering service. + *

The primary responsibilities of this class are to provide the APIs for applications to + * start tethering, stop tethering, query configuration and query status. + * * @hide */ +// TODO: make it @SystemApi public class TetheringManager { private static final String TAG = TetheringManager.class.getSimpleName(); + private static final int DEFAULT_TIMEOUT_MS = 60_000; private static TetheringManager sInstance; - @Nullable - private ITetheringConnector mConnector; - private TetherInternalCallback mCallback; - private Network mTetherUpstream; + private final ITetheringConnector mConnector; + private final TetheringCallbackInternal mCallback; + private final Context mContext; + private final ArrayMap + mTetheringEventCallbacks = new ArrayMap<>(); + private TetheringConfigurationParcel mTetheringConfiguration; private TetherStatesParcel mTetherStatesParcel; - private final RemoteCallbackList mTetheringEventCallbacks = - new RemoteCallbackList<>(); - @GuardedBy("mLog") - private final SharedLog mLog = new SharedLog(TAG); - - private TetheringManager() { } + public static final int TETHER_ERROR_NO_ERROR = 0; + public static final int TETHER_ERROR_UNKNOWN_IFACE = 1; + public static final int TETHER_ERROR_SERVICE_UNAVAIL = 2; + public static final int TETHER_ERROR_UNSUPPORTED = 3; + public static final int TETHER_ERROR_UNAVAIL_IFACE = 4; + public static final int TETHER_ERROR_MASTER_ERROR = 5; + public static final int TETHER_ERROR_TETHER_IFACE_ERROR = 6; + public static final int TETHER_ERROR_UNTETHER_IFACE_ERROR = 7; + public static final int TETHER_ERROR_ENABLE_NAT_ERROR = 8; + public static final int TETHER_ERROR_DISABLE_NAT_ERROR = 9; + public static final int TETHER_ERROR_IFACE_CFG_ERROR = 10; + public static final int TETHER_ERROR_PROVISION_FAILED = 11; + public static final int TETHER_ERROR_DHCPSERVER_ERROR = 12; + public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13; + public static final int TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION = 14; + public static final int TETHER_ERROR_NO_ACCESS_TETHERING_PERMISSION = 15; /** - * Get the TetheringManager singleton instance. + * Create a TetheringManager object for interacting with the tethering service. */ - public static synchronized TetheringManager getInstance() { - if (sInstance == null) { - sInstance = new TetheringManager(); - } - return sInstance; - } + public TetheringManager(@NonNull final Context context, @NonNull final IBinder service) { + mContext = context; + mConnector = ITetheringConnector.Stub.asInterface(service); + mCallback = new TetheringCallbackInternal(); - private class TetheringConnection implements - ConnectivityModuleConnector.ModuleServiceCallback { - @Override - public void onModuleServiceConnected(@NonNull IBinder service) { - logi("Tethering service connected"); - registerTetheringService(service); - } - } - - private void registerTetheringService(@NonNull IBinder service) { - final ITetheringConnector connector = ITetheringConnector.Stub.asInterface(service); - - log("Tethering service registered"); - - // Currently TetheringManager instance is only used by ConnectivityService and mConnector - // only expect to assign once when system server start and bind tethering service. - // STOPSHIP: Change mConnector to final before TetheringManager put into boot classpath. - mConnector = connector; - mCallback = new TetherInternalCallback(); + final String pkgName = mContext.getOpPackageName(); + Log.i(TAG, "registerTetheringEventCallback:" + pkgName); try { - mConnector.registerTetherInternalCallback(mCallback); + mConnector.registerTetheringEventCallback(mCallback, pkgName); } catch (RemoteException e) { - e.rethrowFromSystemServer(); + throw new IllegalStateException(e); } } - private class TetherInternalCallback extends ITetherInternalCallback.Stub { - private final ConditionVariable mWaitForCallback = new ConditionVariable(false); - private static final int EVENT_CALLBACK_TIMEOUT_MS = 60_000; + private interface RequestHelper { + void runRequest(IIntResultListener listener); + } + + private class RequestDispatcher { + private final ConditionVariable mWaiting; + public int mRemoteResult; + + private final IIntResultListener mListener = new IIntResultListener.Stub() { + @Override + public void onResult(final int resultCode) { + mRemoteResult = resultCode; + mWaiting.open(); + } + }; + + RequestDispatcher() { + mWaiting = new ConditionVariable(); + } + + int waitForResult(final RequestHelper request) { + request.runRequest(mListener); + if (!mWaiting.block(DEFAULT_TIMEOUT_MS)) { + throw new IllegalStateException("Callback timeout"); + } + + throwIfPermissionFailure(mRemoteResult); + + return mRemoteResult; + } + } + + private void throwIfPermissionFailure(final int errorCode) { + switch (errorCode) { + case TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION: + throw new SecurityException("No android.permission.TETHER_PRIVILEGED" + + " or android.permission.WRITE_SETTINGS permission"); + case TETHER_ERROR_NO_ACCESS_TETHERING_PERMISSION: + throw new SecurityException( + "No android.permission.ACCESS_NETWORK_STATE permission"); + } + } + + private class TetheringCallbackInternal extends ITetheringEventCallback.Stub { + private int mError = TETHER_ERROR_NO_ERROR; + private final ConditionVariable mWaitForCallback = new ConditionVariable(); @Override - public void onUpstreamChanged(Network network) { - mTetherUpstream = network; - reportUpstreamChanged(network); + public void onCallbackStarted(Network network, TetheringConfigurationParcel config, + TetherStatesParcel states) { + mTetheringConfiguration = config; + mTetherStatesParcel = states; + mWaitForCallback.open(); } + @Override + public void onCallbackStopped(int errorCode) { + mError = errorCode; + mWaitForCallback.open(); + } + + @Override + public void onUpstreamChanged(Network network) { } + @Override public void onConfigurationChanged(TetheringConfigurationParcel config) { mTetheringConfiguration = config; @@ -113,49 +160,10 @@ public class TetheringManager { mTetherStatesParcel = states; } - @Override - public void onCallbackCreated(Network network, TetheringConfigurationParcel config, - TetherStatesParcel states) { - mTetherUpstream = network; - mTetheringConfiguration = config; - mTetherStatesParcel = states; - mWaitForCallback.open(); + public void waitForStarted() { + mWaitForCallback.block(DEFAULT_TIMEOUT_MS); + throwIfPermissionFailure(mError); } - - boolean awaitCallbackCreation() { - return mWaitForCallback.block(EVENT_CALLBACK_TIMEOUT_MS); - } - } - - private void reportUpstreamChanged(Network network) { - final int length = mTetheringEventCallbacks.beginBroadcast(); - try { - for (int i = 0; i < length; i++) { - try { - mTetheringEventCallbacks.getBroadcastItem(i).onUpstreamChanged(network); - } catch (RemoteException e) { - // Not really very much to do here. - } - } - } finally { - mTetheringEventCallbacks.finishBroadcast(); - } - } - - /** - * Start the tethering service. Should be called only once on device startup. - * - *

This method will start the tethering service either in the network stack process, - * or inside the system server on devices that do not support the tethering module. - * - * {@hide} - */ - public void start() { - // Using MAINLINE_NETWORK_STACK permission after cutting off the dpendency of system server. - ConnectivityModuleConnector.getInstance().startModuleService( - ITetheringConnector.class.getName(), NETWORK_STACK, - new TetheringConnection()); - log("Tethering service start requested"); } /** @@ -165,108 +173,110 @@ public class TetheringManager { * IP network interface is available, dhcp will still run and traffic will be * allowed between the tethered devices and this device, though upstream net * access will of course fail until an upstream network interface becomes - * active. Note: return value do not have any meaning. It is better to use - * #getTetherableIfaces() to ensure corresponding interface is available for - * tethering before calling #tether(). + * active. * - * @deprecated The only usages should be in PanService and Wifi P2P which - * need direct access. + * @deprecated The only usages is PanService. It uses this for legacy reasons + * and will migrate away as soon as possible. * - * {@hide} + * @param iface the interface name to tether. + * @return error a {@code TETHER_ERROR} value indicating success or failure type */ @Deprecated - public int tether(@NonNull String iface) { - if (mConnector == null) { - Slog.wtf(TAG, "Tethering not ready yet"); - return TETHER_ERROR_SERVICE_UNAVAIL; - } - try { - mConnector.tether(iface); - } catch (RemoteException e) { - e.rethrowFromSystemServer(); - } - return TETHER_ERROR_NO_ERROR; + public int tether(@NonNull final String iface) { + final String callerPkg = mContext.getOpPackageName(); + Log.i(TAG, "tether caller:" + callerPkg); + final RequestDispatcher dispatcher = new RequestDispatcher(); + + return dispatcher.waitForResult(listener -> { + try { + mConnector.tether(iface, callerPkg, listener); + } catch (RemoteException e) { + throw new IllegalStateException(e); + } + }); } /** * Stop tethering the named interface. * - * @deprecated - * {@hide} + * @deprecated The only usages is PanService. It uses this for legacy reasons + * and will migrate away as soon as possible. */ @Deprecated - public int untether(@NonNull String iface) { - if (mConnector == null) { - Slog.wtf(TAG, "Tethering not ready yet"); - return TETHER_ERROR_SERVICE_UNAVAIL; - } - try { - mConnector.untether(iface); - } catch (RemoteException e) { - e.rethrowFromSystemServer(); - } - return TETHER_ERROR_NO_ERROR; + public int untether(@NonNull final String iface) { + final String callerPkg = mContext.getOpPackageName(); + Log.i(TAG, "untether caller:" + callerPkg); + + final RequestDispatcher dispatcher = new RequestDispatcher(); + + return dispatcher.waitForResult(listener -> { + try { + mConnector.untether(iface, callerPkg, listener); + } catch (RemoteException e) { + throw new IllegalStateException(e); + } + }); } /** - * Attempt to both alter the mode of USB and Tethering of USB. WARNING: New client should not - * use this API anymore. All clients should use #startTethering or #stopTethering which - * encapsulate proper entitlement logic. If the API is used and an entitlement check is needed, - * downstream USB tethering will be enabled but will not have any upstream. + * Attempt to both alter the mode of USB and Tethering of USB. * - * @deprecated - * {@hide} + * @deprecated New client should not use this API anymore. All clients should use + * #startTethering or #stopTethering which encapsulate proper entitlement logic. If the API is + * used and an entitlement check is needed, downstream USB tethering will be enabled but will + * not have any upstream. */ @Deprecated - public int setUsbTethering(boolean enable) { - if (mConnector == null) { - Slog.wtf(TAG, "Tethering not ready yet"); - return TETHER_ERROR_SERVICE_UNAVAIL; - } - try { - mConnector.setUsbTethering(enable); - } catch (RemoteException e) { - e.rethrowFromSystemServer(); - } - return TETHER_ERROR_NO_ERROR; + public int setUsbTethering(final boolean enable) { + final String callerPkg = mContext.getOpPackageName(); + Log.i(TAG, "setUsbTethering caller:" + callerPkg); + + final RequestDispatcher dispatcher = new RequestDispatcher(); + + return dispatcher.waitForResult(listener -> { + try { + mConnector.setUsbTethering(enable, callerPkg, listener); + } catch (RemoteException e) { + throw new IllegalStateException(e); + } + }); } /** * Starts tethering and runs tether provisioning for the given type if needed. If provisioning * fails, stopTethering will be called automatically. * - * {@hide} */ // TODO: improve the usage of ResultReceiver, b/145096122 - public void startTethering(int type, @NonNull ResultReceiver receiver, - boolean showProvisioningUi) { - if (mConnector == null) { - Slog.wtf(TAG, "Tethering not ready yet"); - return; - } + public void startTethering(final int type, @NonNull final ResultReceiver receiver, + final boolean showProvisioningUi) { + final String callerPkg = mContext.getOpPackageName(); + Log.i(TAG, "startTethering caller:" + callerPkg); + try { - mConnector.startTethering(type, receiver, showProvisioningUi); + mConnector.startTethering(type, receiver, showProvisioningUi, callerPkg); } catch (RemoteException e) { - e.rethrowFromSystemServer(); + throw new IllegalStateException(e); } } /** * Stops tethering for the given type. Also cancels any provisioning rechecks for that type if * applicable. - * - * {@hide} */ - public void stopTethering(int type) { - if (mConnector == null) { - Slog.wtf(TAG, "Tethering not ready yet"); - return; - } - try { - mConnector.stopTethering(type); - } catch (RemoteException e) { - e.rethrowFromSystemServer(); - } + public void stopTethering(final int type) { + final String callerPkg = mContext.getOpPackageName(); + Log.i(TAG, "stopTethering caller:" + callerPkg); + + final RequestDispatcher dispatcher = new RequestDispatcher(); + + dispatcher.waitForResult(listener -> { + try { + mConnector.stopTethering(type, callerPkg, listener); + } catch (RemoteException e) { + throw new IllegalStateException(e); + } + }); } /** @@ -277,47 +287,109 @@ public class TetheringManager { * if it's really needed. */ // TODO: improve the usage of ResultReceiver, b/145096122 - public void requestLatestTetheringEntitlementResult(int type, @NonNull ResultReceiver receiver, - boolean showEntitlementUi) { - if (mConnector == null) { - Slog.wtf(TAG, "Tethering not ready yet"); - return; - } + public void requestLatestTetheringEntitlementResult(final int type, + @NonNull final ResultReceiver receiver, final boolean showEntitlementUi) { + final String callerPkg = mContext.getOpPackageName(); + Log.i(TAG, "getLatestTetheringEntitlementResult caller:" + callerPkg); + try { - mConnector.requestLatestTetheringEntitlementResult(type, receiver, showEntitlementUi); + mConnector.requestLatestTetheringEntitlementResult(type, receiver, showEntitlementUi, + callerPkg); } catch (RemoteException e) { - e.rethrowFromSystemServer(); + throw new IllegalStateException(e); } } /** - * Register tethering event callback. + * Start listening to tethering change events. Any new added callback will receive the last + * tethering status right away. If callback is registered, + * {@link OnTetheringEventCallback#onUpstreamChanged} will immediately be called. If tethering + * has no upstream or disabled, the argument of callback will be null. The same callback object + * cannot be registered twice. * - * {@hide} + * @param executor the executor on which callback will be invoked. + * @param callback the callback to be called when tethering has change events. */ - public void registerTetheringEventCallback(@NonNull ITetheringEventCallback callback) { - mTetheringEventCallbacks.register(callback); + public void registerTetheringEventCallback(@NonNull Executor executor, + @NonNull OnTetheringEventCallback callback) { + final String callerPkg = mContext.getOpPackageName(); + Log.i(TAG, "registerTetheringEventCallback caller:" + callerPkg); + + synchronized (mTetheringEventCallbacks) { + if (!mTetheringEventCallbacks.containsKey(callback)) { + throw new IllegalArgumentException("callback was already registered."); + } + final ITetheringEventCallback remoteCallback = new ITetheringEventCallback.Stub() { + @Override + public void onUpstreamChanged(Network network) throws RemoteException { + executor.execute(() -> { + callback.onUpstreamChanged(network); + }); + } + + @Override + public void onCallbackStarted(Network network, TetheringConfigurationParcel config, + TetherStatesParcel states) { + executor.execute(() -> { + callback.onUpstreamChanged(network); + }); + } + + @Override + public void onCallbackStopped(int errorCode) { + executor.execute(() -> { + throwIfPermissionFailure(errorCode); + }); + } + + @Override + public void onConfigurationChanged(TetheringConfigurationParcel config) { } + + @Override + public void onTetherStatesChanged(TetherStatesParcel states) { } + }; + try { + mConnector.registerTetheringEventCallback(remoteCallback, callerPkg); + } catch (RemoteException e) { + throw new IllegalStateException(e); + } + mTetheringEventCallbacks.put(callback, remoteCallback); + } } /** - * Unregister tethering event callback. + * Remove tethering event callback previously registered with + * {@link #registerTetheringEventCallback}. * - * {@hide} + * @param callback previously registered callback. */ - public void unregisterTetheringEventCallback(@NonNull ITetheringEventCallback callback) { - mTetheringEventCallbacks.unregister(callback); + public void unregisterTetheringEventCallback(@NonNull final OnTetheringEventCallback callback) { + final String callerPkg = mContext.getOpPackageName(); + Log.i(TAG, "unregisterTetheringEventCallback caller:" + callerPkg); + + synchronized (mTetheringEventCallbacks) { + ITetheringEventCallback remoteCallback = mTetheringEventCallbacks.remove(callback); + if (remoteCallback == null) { + throw new IllegalArgumentException("callback was not registered."); + } + try { + mConnector.unregisterTetheringEventCallback(remoteCallback, callerPkg); + } catch (RemoteException e) { + throw new IllegalStateException(e); + } + } } /** * Get a more detailed error code after a Tethering or Untethering * request asynchronously failed. * - * {@hide} + * @param iface The name of the interface of interest + * @return error The error code of the last error tethering or untethering the named + * interface */ - public int getLastTetherError(@NonNull String iface) { - if (!mCallback.awaitCallbackCreation()) { - throw new NullPointerException("callback was not ready yet"); - } + public int getLastTetherError(@NonNull final String iface) { + mCallback.waitForStarted(); if (mTetherStatesParcel == null) return TETHER_ERROR_NO_ERROR; int i = 0; @@ -334,12 +406,11 @@ public class TetheringManager { * USB network interfaces. If USB tethering is not supported by the * device, this list should be empty. * - * {@hide} + * @return an array of 0 or more regular expression Strings defining + * what interfaces are considered tetherable usb interfaces. */ public @NonNull String[] getTetherableUsbRegexs() { - if (!mCallback.awaitCallbackCreation()) { - throw new NullPointerException("callback was not ready yet"); - } + mCallback.waitForStarted(); return mTetheringConfiguration.tetherableUsbRegexs; } @@ -348,12 +419,11 @@ public class TetheringManager { * Wifi network interfaces. If Wifi tethering is not supported by the * device, this list should be empty. * - * {@hide} + * @return an array of 0 or more regular expression Strings defining + * what interfaces are considered tetherable wifi interfaces. */ public @NonNull String[] getTetherableWifiRegexs() { - if (!mCallback.awaitCallbackCreation()) { - throw new NullPointerException("callback was not ready yet"); - } + mCallback.waitForStarted(); return mTetheringConfiguration.tetherableWifiRegexs; } @@ -362,12 +432,11 @@ public class TetheringManager { * Bluetooth network interfaces. If Bluetooth tethering is not supported by the * device, this list should be empty. * - * {@hide} + * @return an array of 0 or more regular expression Strings defining + * what interfaces are considered tetherable bluetooth interfaces. */ public @NonNull String[] getTetherableBluetoothRegexs() { - if (!mCallback.awaitCallbackCreation()) { - throw new NullPointerException("callback was not ready yet"); - } + mCallback.waitForStarted(); return mTetheringConfiguration.tetherableBluetoothRegexs; } @@ -375,40 +444,42 @@ public class TetheringManager { * Get the set of tetherable, available interfaces. This list is limited by * device configuration and current interface existence. * - * {@hide} + * @return an array of 0 or more Strings of tetherable interface names. */ public @NonNull String[] getTetherableIfaces() { - if (!mCallback.awaitCallbackCreation()) { - throw new NullPointerException("callback was not ready yet"); - } + mCallback.waitForStarted(); if (mTetherStatesParcel == null) return new String[0]; + return mTetherStatesParcel.availableList; } /** * Get the set of tethered interfaces. * - * {@hide} + * @return an array of 0 or more String of currently tethered interface names. */ public @NonNull String[] getTetheredIfaces() { - if (!mCallback.awaitCallbackCreation()) { - throw new NullPointerException("callback was not ready yet"); - } + mCallback.waitForStarted(); if (mTetherStatesParcel == null) return new String[0]; + return mTetherStatesParcel.tetheredList; } /** * Get the set of interface names which attempted to tether but - * failed. + * failed. Re-attempting to tether may cause them to reset to the Tethered + * state. Alternatively, causing the interface to be destroyed and recreated + * may cause them to reset to the available state. + * {@link ConnectivityManager#getLastTetherError} can be used to get more + * information on the cause of the errors. * - * {@hide} + * @return an array of 0 or more String indicating the interface names + * which failed to tether. */ public @NonNull String[] getTetheringErroredIfaces() { - if (!mCallback.awaitCallbackCreation()) { - throw new NullPointerException("callback was not ready yet"); - } + mCallback.waitForStarted(); if (mTetherStatesParcel == null) return new String[0]; + return mTetherStatesParcel.erroredIfaceList; } @@ -416,123 +487,49 @@ public class TetheringManager { * Get the set of tethered dhcp ranges. * * @deprecated This API just return the default value which is not used in DhcpServer. - * {@hide} */ @Deprecated public @NonNull String[] getTetheredDhcpRanges() { - if (!mCallback.awaitCallbackCreation()) { - throw new NullPointerException("callback was not ready yet"); - } + mCallback.waitForStarted(); return mTetheringConfiguration.legacyDhcpRanges; } /** - * Check if the device allows for tethering. + * Check if the device allows for tethering. It may be disabled via + * {@code ro.tether.denied} system property, Settings.TETHER_SUPPORTED or + * due to device configuration. * - * {@hide} + * @return a boolean - {@code true} indicating Tethering is supported. */ - public boolean hasTetherableConfiguration() { - if (!mCallback.awaitCallbackCreation()) { - throw new NullPointerException("callback was not ready yet"); - } - final boolean hasDownstreamConfiguration = - (mTetheringConfiguration.tetherableUsbRegexs.length != 0) - || (mTetheringConfiguration.tetherableWifiRegexs.length != 0) - || (mTetheringConfiguration.tetherableBluetoothRegexs.length != 0); - final boolean hasUpstreamConfiguration = - (mTetheringConfiguration.preferredUpstreamIfaceTypes.length != 0) - || mTetheringConfiguration.chooseUpstreamAutomatically; + public boolean isTetheringSupported() { + final String callerPkg = mContext.getOpPackageName(); - return hasDownstreamConfiguration && hasUpstreamConfiguration; + final RequestDispatcher dispatcher = new RequestDispatcher(); + final int ret = dispatcher.waitForResult(listener -> { + try { + mConnector.isTetheringSupported(callerPkg, listener); + } catch (RemoteException e) { + throw new IllegalStateException(e); + } + }); + + return ret == TETHER_ERROR_NO_ERROR; } /** - * Log a message in the local log. + * Stop all active tethering. */ - private void log(@NonNull String message) { - synchronized (mLog) { - mLog.log(message); - } - } + public void stopAllTethering() { + final String callerPkg = mContext.getOpPackageName(); + Log.i(TAG, "stopAllTethering caller:" + callerPkg); - /** - * Log a condition that should never happen. - */ - private void logWtf(@NonNull String message, @Nullable Throwable e) { - Slog.wtf(TAG, message); - synchronized (mLog) { - mLog.e(message, e); - } - } - - /** - * Log a ERROR level message in the local and system logs. - */ - private void loge(@NonNull String message, @Nullable Throwable e) { - synchronized (mLog) { - mLog.e(message, e); - } - } - - /** - * Log a INFO level message in the local and system logs. - */ - private void logi(@NonNull String message) { - synchronized (mLog) { - mLog.i(message); - } - } - - /** - * Dump TetheringManager logs to the specified {@link PrintWriter}. - */ - public void dump(@NonNull PrintWriter pw) { - // dump is thread-safe on SharedLog - mLog.dump(null, pw, null); - - pw.print("subId: "); - pw.println(mTetheringConfiguration.subId); - - dumpStringArray(pw, "tetherableUsbRegexs", - mTetheringConfiguration.tetherableUsbRegexs); - dumpStringArray(pw, "tetherableWifiRegexs", - mTetheringConfiguration.tetherableWifiRegexs); - dumpStringArray(pw, "tetherableBluetoothRegexs", - mTetheringConfiguration.tetherableBluetoothRegexs); - - pw.print("isDunRequired: "); - pw.println(mTetheringConfiguration.isDunRequired); - - pw.print("chooseUpstreamAutomatically: "); - pw.println(mTetheringConfiguration.chooseUpstreamAutomatically); - - dumpStringArray(pw, "legacyDhcpRanges", mTetheringConfiguration.legacyDhcpRanges); - dumpStringArray(pw, "defaultIPv4DNS", mTetheringConfiguration.defaultIPv4DNS); - - dumpStringArray(pw, "provisioningApp", mTetheringConfiguration.provisioningApp); - pw.print("provisioningAppNoUi: "); - pw.println(mTetheringConfiguration.provisioningAppNoUi); - - pw.print("enableLegacyDhcpServer: "); - pw.println(mTetheringConfiguration.enableLegacyDhcpServer); - - pw.println(); - } - - private static void dumpStringArray(@NonNull PrintWriter pw, @NonNull String label, - @Nullable String[] values) { - pw.print(label); - pw.print(": "); - - if (values != null) { - final StringJoiner sj = new StringJoiner(", ", "[", "]"); - for (String value : values) sj.add(value); - - pw.print(sj.toString()); - } else { - pw.print("null"); - } - - pw.println(); + final RequestDispatcher dispatcher = new RequestDispatcher(); + dispatcher.waitForResult(listener -> { + try { + mConnector.stopAllTethering(callerPkg, listener); + } catch (RemoteException e) { + throw new IllegalStateException(e); + } + }); } } diff --git a/Tethering/jarjar-rules.txt b/Tethering/jarjar-rules.txt new file mode 100644 index 0000000000..dd9eab74e8 --- /dev/null +++ b/Tethering/jarjar-rules.txt @@ -0,0 +1,15 @@ +# These must be kept in sync with the framework-tethering-shared-srcs filegroup. +# If there are files in that filegroup that do not appear here, the classes in the +# module will be overwritten by the ones in the framework. +# Don't jar-jar the entire package because tethering still use some internal classes +# (like TrafficStatsConstants in com.android.internal.util) +# TODO: simply these when tethering is built as system_current. +rule com.android.internal.util.BitUtils* com.android.networkstack.tethering.util.BitUtils@1 +rule com.android.internal.util.IndentingPrintWriter.java* com.android.networkstack.tethering.util.IndentingPrintWriter.java@1 +rule com.android.internal.util.IState.java* com.android.networkstack.tethering.util.IState.java@1 +rule com.android.internal.util.MessageUtils* com.android.networkstack.tethering.util.MessageUtils@1 +rule com.android.internal.util.Preconditions* com.android.networkstack.tethering.util.Preconditions@1 +rule com.android.internal.util.State* com.android.networkstack.tethering.util.State@1 +rule com.android.internal.util.StateMachine* com.android.networkstack.tethering.util.StateMachine@1 + +rule android.net.LocalLog* com.android.networkstack.tethering.LocalLog@1 diff --git a/Tethering/proguard.flags b/Tethering/proguard.flags index 77fc024a87..1f83a66382 100644 --- a/Tethering/proguard.flags +++ b/Tethering/proguard.flags @@ -1 +1,9 @@ -#TBD +# Keep class's integer static field for MessageUtils to parsing their name. +-keep class com.android.server.connectivity.tethering.Tethering$TetherMasterSM { + static final int CMD_*; + static final int EVENT_*; +} + +-keepclassmembers class android.net.ip.IpServer { + static final int CMD_*; +} diff --git a/Tethering/src/android/net/ip/IpServer.java b/Tethering/src/android/net/ip/IpServer.java index ff3d7bc6fd..8fde52040e 100644 --- a/Tethering/src/android/net/ip/IpServer.java +++ b/Tethering/src/android/net/ip/IpServer.java @@ -30,7 +30,6 @@ import android.net.InterfaceConfiguration; import android.net.IpPrefix; import android.net.LinkAddress; import android.net.LinkProperties; -import android.net.NetworkStackClient; import android.net.RouteInfo; import android.net.dhcp.DhcpServerCallbacks; import android.net.dhcp.DhcpServingParamsParcel; @@ -122,7 +121,7 @@ public class IpServer extends StateMachine { * @param state one of STATE_* * @param lastError one of ConnectivityManager.TETHER_ERROR_* */ - public void updateInterfaceState(IpServer who, int state, int lastError) {} + public void updateInterfaceState(IpServer who, int state, int lastError) { } /** * Notify that |who| has new LinkProperties. @@ -130,11 +129,11 @@ public class IpServer extends StateMachine { * @param who the calling instance of IpServer * @param newLp the new LinkProperties to report */ - public void updateLinkProperties(IpServer who, LinkProperties newLp) {} + public void updateLinkProperties(IpServer who, LinkProperties newLp) { } } /** Capture IpServer dependencies, for injection. */ - public static class Dependencies { + public abstract static class Dependencies { /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/ public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) { return new RouterAdvertisementDaemon(ifParams); @@ -149,13 +148,9 @@ public class IpServer extends StateMachine { return NetdService.getInstance(); } - /** - * Create a DhcpServer instance to be used by IpServer. - */ - public void makeDhcpServer(String ifName, DhcpServingParamsParcel params, - DhcpServerCallbacks cb) { - NetworkStackClient.getInstance().makeDhcpServer(ifName, params, cb); - } + /** Create a DhcpServer instance to be used by IpServer. */ + public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params, + DhcpServerCallbacks cb); } private static final int BASE_IFACE = Protocol.BASE_TETHERING + 100; diff --git a/Tethering/src/com/android/server/connectivity/tethering/Tethering.java b/Tethering/src/com/android/server/connectivity/tethering/Tethering.java index c4b360d929..a68b9b261e 100644 --- a/Tethering/src/com/android/server/connectivity/tethering/Tethering.java +++ b/Tethering/src/com/android/server/connectivity/tethering/Tethering.java @@ -16,6 +16,7 @@ package com.android.server.connectivity.tethering; +import static android.content.pm.PackageManager.PERMISSION_GRANTED; import static android.hardware.usb.UsbManager.USB_CONFIGURED; import static android.hardware.usb.UsbManager.USB_CONNECTED; import static android.hardware.usb.UsbManager.USB_FUNCTION_RNDIS; @@ -63,7 +64,7 @@ import android.hardware.usb.UsbManager; import android.net.INetd; import android.net.INetworkPolicyManager; import android.net.INetworkStatsService; -import android.net.ITetherInternalCallback; +import android.net.ITetheringEventCallback; import android.net.IpPrefix; import android.net.LinkAddress; import android.net.LinkProperties; @@ -89,6 +90,7 @@ import android.os.Handler; import android.os.INetworkManagementService; import android.os.Looper; import android.os.Message; +import android.os.RemoteCallbackList; import android.os.RemoteException; import android.os.ResultReceiver; import android.os.UserHandle; @@ -103,7 +105,6 @@ import android.util.SparseArray; import com.android.internal.annotations.VisibleForTesting; import com.android.internal.messages.nano.SystemMessageProto.SystemMessage; import com.android.internal.notification.SystemNotificationChannels; -import com.android.internal.util.DumpUtils; import com.android.internal.util.IndentingPrintWriter; import com.android.internal.util.MessageUtils; import com.android.internal.util.Protocol; @@ -162,6 +163,8 @@ public class Tethering { } private final SharedLog mLog = new SharedLog(TAG); + private final RemoteCallbackList mTetheringEventCallbacks = + new RemoteCallbackList<>(); // used to synchronize public access to members private final Object mPublicSync; @@ -188,8 +191,8 @@ public class Tethering { private final NetdCallback mNetdCallback; private final UserRestrictionActionListener mTetheringRestriction; private int mActiveDataSubId = INVALID_SUBSCRIPTION_ID; - // All the usage of mTetherInternalCallback should run in the same thread. - private ITetherInternalCallback mTetherInternalCallback = null; + // All the usage of mTetheringEventCallback should run in the same thread. + private ITetheringEventCallback mTetheringEventCallback = null; private volatile TetheringConfiguration mConfig; private InterfaceSet mCurrentUpstreamIfaceSet; @@ -573,6 +576,11 @@ public class Tethering { } } + boolean isTetherProvisioningRequired() { + final TetheringConfiguration cfg = mConfig; + return mEntitlementMgr.isTetherProvisioningRequired(cfg); + } + // TODO: Figure out how to update for local hotspot mode interfaces. private void sendTetherStateChangedBroadcast() { if (!mDeps.isTetheringSupported()) return; @@ -588,7 +596,7 @@ public class Tethering { boolean bluetoothTethered = false; final TetheringConfiguration cfg = mConfig; - final TetherStatesParcel mTetherStatesParcel = new TetherStatesParcel(); + mTetherStatesParcel = new TetherStatesParcel(); synchronized (mPublicSync) { for (int i = 0; i < mTetherStates.size(); i++) { @@ -1796,47 +1804,67 @@ public class Tethering { } /** Register tethering event callback */ - void registerTetherInternalCallback(ITetherInternalCallback callback) { + void registerTetheringEventCallback(ITetheringEventCallback callback) { mHandler.post(() -> { - mTetherInternalCallback = callback; + mTetheringEventCallbacks.register(callback); try { - mTetherInternalCallback.onCallbackCreated(mTetherUpstream, - mConfig.toStableParcelable(), mTetherStatesParcel); + callback.onCallbackStarted(mTetherUpstream, mConfig.toStableParcelable(), + mTetherStatesParcel); } catch (RemoteException e) { // Not really very much to do here. } }); } - private void reportUpstreamChanged(Network network) { - // Don't need to synchronized mTetherInternalCallback because all the usage of this variable - // should run at the same thread. - if (mTetherInternalCallback == null) return; + /** Unregister tethering event callback */ + void unregisterTetheringEventCallback(ITetheringEventCallback callback) { + mHandler.post(() -> { + mTetheringEventCallbacks.unregister(callback); + }); + } + private void reportUpstreamChanged(Network network) { + final int length = mTetheringEventCallbacks.beginBroadcast(); try { - mTetherInternalCallback.onUpstreamChanged(network); - } catch (RemoteException e) { - // Not really very much to do here. + for (int i = 0; i < length; i++) { + try { + mTetheringEventCallbacks.getBroadcastItem(i).onUpstreamChanged(network); + } catch (RemoteException e) { + // Not really very much to do here. + } + } + } finally { + mTetheringEventCallbacks.finishBroadcast(); } } private void reportConfigurationChanged(TetheringConfigurationParcel config) { - if (mTetherInternalCallback == null) return; - + final int length = mTetheringEventCallbacks.beginBroadcast(); try { - mTetherInternalCallback.onConfigurationChanged(config); - } catch (RemoteException e) { - // Not really very much to do here. + for (int i = 0; i < length; i++) { + try { + mTetheringEventCallbacks.getBroadcastItem(i).onConfigurationChanged(config); + } catch (RemoteException e) { + // Not really very much to do here. + } + } + } finally { + mTetheringEventCallbacks.finishBroadcast(); } } private void reportTetherStateChanged(TetherStatesParcel states) { - if (mTetherInternalCallback == null) return; - + final int length = mTetheringEventCallbacks.beginBroadcast(); try { - mTetherInternalCallback.onTetherStatesChanged(states); - } catch (RemoteException e) { - // Not really very much to do here. + for (int i = 0; i < length; i++) { + try { + mTetheringEventCallbacks.getBroadcastItem(i).onTetherStatesChanged(states); + } catch (RemoteException e) { + // Not really very much to do here. + } + } + } finally { + mTetheringEventCallbacks.finishBroadcast(); } } @@ -1844,7 +1872,11 @@ public class Tethering { // Binder.java closes the resource for us. @SuppressWarnings("resource") final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " "); - if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return; + if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) + != PERMISSION_GRANTED) { + pw.println("Permission Denial: can't dump."); + return; + } pw.println("Tethering:"); pw.increaseIndent(); diff --git a/Tethering/src/com/android/server/connectivity/tethering/TetheringDependencies.java b/Tethering/src/com/android/server/connectivity/tethering/TetheringDependencies.java index 0ba84127d8..b16b3294a1 100644 --- a/Tethering/src/com/android/server/connectivity/tethering/TetheringDependencies.java +++ b/Tethering/src/com/android/server/connectivity/tethering/TetheringDependencies.java @@ -39,7 +39,7 @@ import java.util.ArrayList; * * @hide */ -public class TetheringDependencies { +public abstract class TetheringDependencies { /** * Get a reference to the offload hardware interface to be used by tethering. */ @@ -66,9 +66,7 @@ public class TetheringDependencies { /** * Get dependencies to be used by IpServer. */ - public IpServer.Dependencies getIpServerDependencies() { - return new IpServer.Dependencies(); - } + public abstract IpServer.Dependencies getIpServerDependencies(); /** * Indicates whether tethering is supported on the device. @@ -80,9 +78,7 @@ public class TetheringDependencies { /** * Get the NetworkRequest that should be fulfilled by the default network. */ - public NetworkRequest getDefaultNetworkRequest() { - return null; - } + public abstract NetworkRequest getDefaultNetworkRequest(); /** * Get a reference to the EntitlementManager to be used by tethering. @@ -138,14 +134,10 @@ public class TetheringDependencies { /** * Get tethering thread looper. */ - public Looper getTetheringLooper() { - return null; - } + public abstract Looper getTetheringLooper(); /** * Get Context of TetheringSerice. */ - public Context getContext() { - return null; - } + public abstract Context getContext(); } diff --git a/Tethering/src/com/android/server/connectivity/tethering/TetheringService.java b/Tethering/src/com/android/server/connectivity/tethering/TetheringService.java index 456f2f7f27..ba30845e63 100644 --- a/Tethering/src/com/android/server/connectivity/tethering/TetheringService.java +++ b/Tethering/src/com/android/server/connectivity/tethering/TetheringService.java @@ -16,20 +16,36 @@ package com.android.server.connectivity.tethering; +import static android.content.pm.PackageManager.PERMISSION_GRANTED; +import static android.net.TetheringManager.TETHER_ERROR_NO_ACCESS_TETHERING_PERMISSION; +import static android.net.TetheringManager.TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION; +import static android.net.TetheringManager.TETHER_ERROR_NO_ERROR; +import static android.net.TetheringManager.TETHER_ERROR_UNSUPPORTED; + import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; -import android.net.ITetherInternalCallback; +import android.net.IIntResultListener; +import android.net.INetworkStackConnector; import android.net.ITetheringConnector; +import android.net.ITetheringEventCallback; import android.net.NetworkRequest; +import android.net.dhcp.DhcpServerCallbacks; +import android.net.dhcp.DhcpServingParamsParcel; +import android.net.ip.IpServer; import android.net.util.SharedLog; +import android.os.Binder; import android.os.HandlerThread; import android.os.IBinder; import android.os.Looper; +import android.os.RemoteException; import android.os.ResultReceiver; +import android.os.ServiceManager; import android.os.SystemProperties; +import android.os.UserManager; import android.provider.Settings; +import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; @@ -52,6 +68,7 @@ public class TetheringService extends Service { private Context mContext; private TetheringDependencies mDeps; private Tethering mTethering; + private UserManager mUserManager; @Override public void onCreate() { @@ -59,6 +76,7 @@ public class TetheringService extends Service { mDeps = getTetheringDependencies(); mContext = mDeps.getContext(); mTethering = makeTethering(mDeps); + mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); } /** @@ -74,7 +92,7 @@ public class TetheringService extends Service { */ private synchronized IBinder makeConnector() { if (mConnector == null) { - mConnector = new TetheringConnector(mTethering); + mConnector = new TetheringConnector(mTethering, TetheringService.this); } return mConnector; } @@ -87,55 +105,197 @@ public class TetheringService extends Service { } private static class TetheringConnector extends ITetheringConnector.Stub { - private final Tethering mService; + private final TetheringService mService; + private final Tethering mTethering; - TetheringConnector(Tethering tether) { - mService = tether; + TetheringConnector(Tethering tether, TetheringService service) { + mTethering = tether; + mService = service; } @Override - public void tether(String iface) { - mService.tether(iface); + public void tether(String iface, String callerPkg, IIntResultListener listener) { + if (checkAndNotifyCommonError(callerPkg, listener)) return; + + try { + listener.onResult(mTethering.tether(iface)); + } catch (RemoteException e) { } } @Override - public void untether(String iface) { - mService.untether(iface); + public void untether(String iface, String callerPkg, IIntResultListener listener) { + if (checkAndNotifyCommonError(callerPkg, listener)) return; + + try { + listener.onResult(mTethering.untether(iface)); + } catch (RemoteException e) { } } @Override - public void setUsbTethering(boolean enable) { - mService.setUsbTethering(enable); + public void setUsbTethering(boolean enable, String callerPkg, IIntResultListener listener) { + if (checkAndNotifyCommonError(callerPkg, listener)) return; + + try { + listener.onResult(mTethering.setUsbTethering(enable)); + } catch (RemoteException e) { } } @Override - public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) { - mService.startTethering(type, receiver, showProvisioningUi); + public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi, + String callerPkg) { + if (checkAndNotifyCommonError(callerPkg, receiver)) return; + + mTethering.startTethering(type, receiver, showProvisioningUi); } @Override - public void stopTethering(int type) { - mService.stopTethering(type); + public void stopTethering(int type, String callerPkg, IIntResultListener listener) { + if (checkAndNotifyCommonError(callerPkg, listener)) return; + + try { + mTethering.stopTethering(type); + listener.onResult(TETHER_ERROR_NO_ERROR); + } catch (RemoteException e) { } } @Override public void requestLatestTetheringEntitlementResult(int type, ResultReceiver receiver, - boolean showEntitlementUi) { - mService.requestLatestTetheringEntitlementResult(type, receiver, showEntitlementUi); + boolean showEntitlementUi, String callerPkg) { + if (checkAndNotifyCommonError(callerPkg, receiver)) return; + + mTethering.requestLatestTetheringEntitlementResult(type, receiver, showEntitlementUi); } @Override - public void registerTetherInternalCallback(ITetherInternalCallback callback) { - mService.registerTetherInternalCallback(callback); + public void registerTetheringEventCallback(ITetheringEventCallback callback, + String callerPkg) { + try { + if (!mService.hasTetherAccessPermission()) { + callback.onCallbackStopped(TETHER_ERROR_NO_ACCESS_TETHERING_PERMISSION); + return; + } + mTethering.registerTetheringEventCallback(callback); + } catch (RemoteException e) { } } + + @Override + public void unregisterTetheringEventCallback(ITetheringEventCallback callback, + String callerPkg) { + try { + if (!mService.hasTetherAccessPermission()) { + callback.onCallbackStopped(TETHER_ERROR_NO_ACCESS_TETHERING_PERMISSION); + return; + } + mTethering.unregisterTetheringEventCallback(callback); + } catch (RemoteException e) { } + } + + @Override + public void stopAllTethering(String callerPkg, IIntResultListener listener) { + if (checkAndNotifyCommonError(callerPkg, listener)) return; + + try { + mTethering.untetherAll(); + listener.onResult(TETHER_ERROR_NO_ERROR); + } catch (RemoteException e) { } + } + + @Override + public void isTetheringSupported(String callerPkg, IIntResultListener listener) { + if (checkAndNotifyCommonError(callerPkg, listener)) return; + + try { + listener.onResult(TETHER_ERROR_NO_ERROR); + } catch (RemoteException e) { } + } + + @Override + protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer, + @Nullable String[] args) { + mTethering.dump(fd, writer, args); + } + + private boolean checkAndNotifyCommonError(String callerPkg, IIntResultListener listener) { + try { + if (!mService.hasTetherChangePermission(callerPkg)) { + listener.onResult(TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION); + return true; + } + if (!mService.isTetheringSupported()) { + listener.onResult(TETHER_ERROR_UNSUPPORTED); + return true; + } + } catch (RemoteException e) { + return true; + } + + return false; + } + + private boolean checkAndNotifyCommonError(String callerPkg, ResultReceiver receiver) { + if (!mService.hasTetherChangePermission(callerPkg)) { + receiver.send(TETHER_ERROR_NO_CHANGE_TETHERING_PERMISSION, null); + return true; + } + if (!mService.isTetheringSupported()) { + receiver.send(TETHER_ERROR_UNSUPPORTED, null); + return true; + } + + return false; + } + } - @Override - protected void dump(@NonNull FileDescriptor fd, @NonNull PrintWriter writer, - @Nullable String[] args) { - mTethering.dump(fd, writer, args); + // if ro.tether.denied = true we default to no tethering + // gservices could set the secure setting to 1 though to enable it on a build where it + // had previously been turned off. + private boolean isTetheringSupported() { + final int defaultVal = + SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1; + final boolean tetherSupported = Settings.Global.getInt(mContext.getContentResolver(), + Settings.Global.TETHER_SUPPORTED, defaultVal) != 0; + final boolean tetherEnabledInSettings = tetherSupported + && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING); + + return tetherEnabledInSettings && mTethering.hasTetherableConfiguration(); } + private boolean hasTetherChangePermission(String callerPkg) { + if (checkCallingOrSelfPermission( + android.Manifest.permission.TETHER_PRIVILEGED) == PERMISSION_GRANTED) { + return true; + } + + if (mTethering.isTetherProvisioningRequired()) return false; + + + int uid = Binder.getCallingUid(); + // If callerPkg's uid is not same as Binder.getCallingUid(), + // checkAndNoteWriteSettingsOperation will return false and the operation will be denied. + if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid, callerPkg, + false /* throwException */)) { + return true; + } + + return false; + } + + private boolean hasTetherAccessPermission() { + if (checkCallingOrSelfPermission( + android.Manifest.permission.TETHER_PRIVILEGED) == PERMISSION_GRANTED) { + return true; + } + + if (checkCallingOrSelfPermission( + android.Manifest.permission.ACCESS_NETWORK_STATE) == PERMISSION_GRANTED) { + return true; + } + + return false; + } + + /** * An injection method for testing. */ @@ -159,20 +319,55 @@ public class TetheringService extends Service { @Override public boolean isTetheringSupported() { - int defaultVal = - SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1; - boolean tetherSupported = Settings.Global.getInt(mContext.getContentResolver(), - Settings.Global.TETHER_SUPPORTED, defaultVal) != 0; - return tetherSupported; + return TetheringService.this.isTetheringSupported(); } @Override public Context getContext() { return TetheringService.this; } + + @Override + public IpServer.Dependencies getIpServerDependencies() { + return new IpServer.Dependencies() { + @Override + public void makeDhcpServer(String ifName, DhcpServingParamsParcel params, + DhcpServerCallbacks cb) { + try { + final INetworkStackConnector service = getNetworkStackConnector(); + if (service == null) return; + + service.makeDhcpServer(ifName, params, cb); + } catch (RemoteException e) { + e.rethrowFromSystemServer(); + } + } + }; + } + + // TODO: replace this by NetworkStackClient#getRemoteConnector after refactoring + // networkStackClient. + static final int NETWORKSTACK_TIMEOUT_MS = 60_000; + private INetworkStackConnector getNetworkStackConnector() { + IBinder connector; + try { + final long before = System.currentTimeMillis(); + while ((connector = ServiceManager.getService( + Context.NETWORK_STACK_SERVICE)) == null) { + if (System.currentTimeMillis() - before > NETWORKSTACK_TIMEOUT_MS) { + Log.wtf(TAG, "Timeout, fail to get INetworkStackConnector"); + return null; + } + Thread.sleep(200); + } + } catch (InterruptedException e) { + Log.wtf(TAG, "Interrupted, fail to get INetworkStackConnector"); + return null; + } + return INetworkStackConnector.Stub.asInterface(connector); + } }; } - return mDeps; } } diff --git a/Tethering/tests/unit/Android.bp b/Tethering/tests/unit/Android.bp index 5b018df21a..81a0548cd7 100644 --- a/Tethering/tests/unit/Android.bp +++ b/Tethering/tests/unit/Android.bp @@ -33,10 +33,12 @@ android_test { "android.test.runner", "android.test.base", "android.test.mock", + "framework-tethering", ], jni_libs: [ // For mockito extended "libdexmakerjvmtiagent", "libstaticjvmtiagent", ], + jarjar_rules: "jarjar-rules.txt", } diff --git a/Tethering/tests/unit/jarjar-rules.txt b/Tethering/tests/unit/jarjar-rules.txt new file mode 100644 index 0000000000..64fdebd927 --- /dev/null +++ b/Tethering/tests/unit/jarjar-rules.txt @@ -0,0 +1,11 @@ +# Don't jar-jar the entire package because this test use some +# internal classes (like ArrayUtils in com.android.internal.util) +rule com.android.internal.util.BitUtils* com.android.networkstack.tethering.util.BitUtils@1 +rule com.android.internal.util.IndentingPrintWriter.java* com.android.networkstack.tethering.util.IndentingPrintWriter.java@1 +rule com.android.internal.util.IState.java* com.android.networkstack.tethering.util.IState.java@1 +rule com.android.internal.util.MessageUtils* com.android.networkstack.tethering.util.MessageUtils@1 +rule com.android.internal.util.Preconditions* com.android.networkstack.tethering.util.Preconditions@1 +rule com.android.internal.util.State* com.android.networkstack.tethering.util.State@1 +rule com.android.internal.util.StateMachine* com.android.networkstack.tethering.util.StateMachine@1 + +rule android.net.LocalLog* com.android.networkstack.tethering.LocalLog@1 diff --git a/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java b/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java index cdbc54106c..31ed8238b6 100644 --- a/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java +++ b/Tethering/tests/unit/src/com/android/server/connectivity/tethering/TetheringTest.java @@ -72,7 +72,7 @@ import android.hardware.usb.UsbManager; import android.net.INetd; import android.net.INetworkPolicyManager; import android.net.INetworkStatsService; -import android.net.ITetherInternalCallback; +import android.net.ITetheringEventCallback; import android.net.InterfaceConfiguration; import android.net.IpPrefix; import android.net.LinkAddress; @@ -81,6 +81,7 @@ import android.net.MacAddress; import android.net.Network; import android.net.NetworkCapabilities; import android.net.NetworkInfo; +import android.net.NetworkRequest; import android.net.NetworkState; import android.net.NetworkUtils; import android.net.RouteInfo; @@ -167,6 +168,7 @@ public class TetheringTest { @Mock private IDhcpServer mDhcpServer; @Mock private INetd mNetd; @Mock private UserManager mUserManager; + @Mock private NetworkRequest mNetworkRequest; private final MockIpServerDependencies mIpServerDependencies = spy(new MockIpServerDependencies()); @@ -310,6 +312,11 @@ public class TetheringTest { return mIpServerDependencies; } + @Override + public NetworkRequest getDefaultNetworkRequest() { + return mNetworkRequest; + } + @Override public boolean isTetheringSupported() { mIsTetheringSupportedCalls++; @@ -1039,7 +1046,7 @@ public class TetheringTest { expectedInteractionsWithShowNotification); } - private class TestTetherInternalCallback extends ITetherInternalCallback.Stub { + private class TestTetheringEventCallback extends ITetheringEventCallback.Stub { private final ArrayList mActualUpstreams = new ArrayList<>(); private final ArrayList mTetheringConfigs = new ArrayList<>(); @@ -1100,13 +1107,16 @@ public class TetheringTest { } @Override - public void onCallbackCreated(Network network, TetheringConfigurationParcel config, + public void onCallbackStarted(Network network, TetheringConfigurationParcel config, TetherStatesParcel states) { mActualUpstreams.add(network); mTetheringConfigs.add(config); mTetherStates.add(states); } + @Override + public void onCallbackStopped(int errorCode) { } + public void assertNoUpstreamChangeCallback() { assertTrue(mActualUpstreams.isEmpty()); } @@ -1115,10 +1125,20 @@ public class TetheringTest { assertTrue(mTetheringConfigs.isEmpty()); } + public void assertNoStateChangeCallback() { + assertTrue(mTetherStates.isEmpty()); + } + public void assertStateChangeCallback() { assertFalse(mTetherStates.isEmpty()); } + public void assertNoCallback() { + assertNoUpstreamChangeCallback(); + assertNoConfigChangeCallback(); + assertNoStateChangeCallback(); + } + private void assertTetherConfigParcelEqual(@NonNull TetheringConfigurationParcel actual, @NonNull TetheringConfigurationParcel expect) { assertEquals(actual.subId, expect.subId); @@ -1139,18 +1159,19 @@ public class TetheringTest { } @Test - public void testRegisterTetherInternalCallback() throws Exception { - TestTetherInternalCallback callback = new TestTetherInternalCallback(); + public void testRegisterTetheringEventCallback() throws Exception { + TestTetheringEventCallback callback = new TestTetheringEventCallback(); + TestTetheringEventCallback callback2 = new TestTetheringEventCallback(); // 1. Register one callback before running any tethering. - mTethering.registerTetherInternalCallback(callback); + mTethering.registerTetheringEventCallback(callback); mLooper.dispatchAll(); callback.expectUpstreamChanged(new Network[] {null}); callback.expectConfigurationChanged( mTethering.getTetheringConfiguration().toStableParcelable()); TetherStatesParcel tetherState = callback.pollTetherStatesChanged(); assertEquals(tetherState, null); - // 2. Enable wifi tethering + // 2. Enable wifi tethering. NetworkState upstreamState = buildMobileDualStackUpstreamState(); when(mUpstreamNetworkMonitor.getCurrentPreferredUpstream()).thenReturn(upstreamState); when(mUpstreamNetworkMonitor.selectPreferredUpstreamType(any())) @@ -1168,14 +1189,26 @@ public class TetheringTest { assertArrayEquals(tetherState.tetheredList, new String[] {TEST_WLAN_IFNAME}); callback.expectUpstreamChanged(upstreamState.network); - // 3. Disable wifi tethering. + // 3. Register second callback. + mTethering.registerTetheringEventCallback(callback2); + mLooper.dispatchAll(); + callback2.expectUpstreamChanged(upstreamState.network); + callback2.expectConfigurationChanged( + mTethering.getTetheringConfiguration().toStableParcelable()); + tetherState = callback2.pollTetherStatesChanged(); + assertEquals(tetherState.tetheredList, new String[] {TEST_WLAN_IFNAME}); + + // 4. Unregister first callback and disable wifi tethering + mTethering.unregisterTetheringEventCallback(callback); + mLooper.dispatchAll(); mTethering.stopTethering(TETHERING_WIFI); sendWifiApStateChanged(WifiManager.WIFI_AP_STATE_DISABLED); mLooper.dispatchAll(); - tetherState = callback.pollTetherStatesChanged(); + tetherState = callback2.pollTetherStatesChanged(); assertArrayEquals(tetherState.availableList, new String[] {TEST_WLAN_IFNAME}); mLooper.dispatchAll(); - callback.expectUpstreamChanged(new Network[] {null}); + callback2.expectUpstreamChanged(new Network[] {null}); + callback.assertNoCallback(); } @Test