Merge "Clean up T&C implementation"
diff --git a/framework/Android.bp b/framework/Android.bp
index 8db8d76..ffca971 100644
--- a/framework/Android.bp
+++ b/framework/Android.bp
@@ -14,16 +14,48 @@
// limitations under the License.
//
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "frameworks_base_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["frameworks_base_license"],
+}
+
// TODO: use a java_library in the bootclasspath instead
filegroup {
- name: "framework-connectivity-sources",
+ name: "framework-connectivity-internal-sources",
srcs: [
"src/**/*.java",
"src/**/*.aidl",
],
path: "src",
visibility: [
+ "//visibility:private",
+ ],
+}
+
+filegroup {
+ name: "framework-connectivity-aidl-export-sources",
+ srcs: [
+ "aidl-export/**/*.aidl",
+ ],
+ path: "aidl-export",
+ visibility: [
+ "//visibility:private",
+ ],
+}
+
+// TODO: use a java_library in the bootclasspath instead
+filegroup {
+ name: "framework-connectivity-sources",
+ srcs: [
+ ":framework-connectivity-internal-sources",
+ ":framework-connectivity-aidl-export-sources",
+ ],
+ visibility: [
"//frameworks/base",
"//packages/modules/Connectivity:__subpackages__",
],
-}
\ No newline at end of file
+}
diff --git a/framework/src/android/net/CaptivePortalData.aidl b/framework/aidl-export/android/net/CaptivePortalData.aidl
similarity index 100%
rename from framework/src/android/net/CaptivePortalData.aidl
rename to framework/aidl-export/android/net/CaptivePortalData.aidl
diff --git a/framework/src/android/net/ConnectivityDiagnosticsManager.aidl b/framework/aidl-export/android/net/ConnectivityDiagnosticsManager.aidl
similarity index 100%
rename from framework/src/android/net/ConnectivityDiagnosticsManager.aidl
rename to framework/aidl-export/android/net/ConnectivityDiagnosticsManager.aidl
diff --git a/framework/src/android/net/DhcpInfo.aidl b/framework/aidl-export/android/net/DhcpInfo.aidl
similarity index 100%
rename from framework/src/android/net/DhcpInfo.aidl
rename to framework/aidl-export/android/net/DhcpInfo.aidl
diff --git a/framework/src/android/net/IpConfiguration.aidl b/framework/aidl-export/android/net/IpConfiguration.aidl
similarity index 100%
rename from framework/src/android/net/IpConfiguration.aidl
rename to framework/aidl-export/android/net/IpConfiguration.aidl
diff --git a/framework/src/android/net/IpPrefix.aidl b/framework/aidl-export/android/net/IpPrefix.aidl
similarity index 100%
rename from framework/src/android/net/IpPrefix.aidl
rename to framework/aidl-export/android/net/IpPrefix.aidl
diff --git a/framework/src/android/net/KeepalivePacketData.aidl b/framework/aidl-export/android/net/KeepalivePacketData.aidl
similarity index 100%
rename from framework/src/android/net/KeepalivePacketData.aidl
rename to framework/aidl-export/android/net/KeepalivePacketData.aidl
diff --git a/framework/src/android/net/LinkAddress.aidl b/framework/aidl-export/android/net/LinkAddress.aidl
similarity index 100%
rename from framework/src/android/net/LinkAddress.aidl
rename to framework/aidl-export/android/net/LinkAddress.aidl
diff --git a/framework/src/android/net/LinkProperties.aidl b/framework/aidl-export/android/net/LinkProperties.aidl
similarity index 100%
rename from framework/src/android/net/LinkProperties.aidl
rename to framework/aidl-export/android/net/LinkProperties.aidl
diff --git a/framework/src/android/net/MacAddress.aidl b/framework/aidl-export/android/net/MacAddress.aidl
similarity index 100%
rename from framework/src/android/net/MacAddress.aidl
rename to framework/aidl-export/android/net/MacAddress.aidl
diff --git a/framework/src/android/net/Network.aidl b/framework/aidl-export/android/net/Network.aidl
similarity index 100%
rename from framework/src/android/net/Network.aidl
rename to framework/aidl-export/android/net/Network.aidl
diff --git a/framework/src/android/net/NetworkAgentConfig.aidl b/framework/aidl-export/android/net/NetworkAgentConfig.aidl
similarity index 100%
rename from framework/src/android/net/NetworkAgentConfig.aidl
rename to framework/aidl-export/android/net/NetworkAgentConfig.aidl
diff --git a/framework/src/android/net/NetworkCapabilities.aidl b/framework/aidl-export/android/net/NetworkCapabilities.aidl
similarity index 100%
rename from framework/src/android/net/NetworkCapabilities.aidl
rename to framework/aidl-export/android/net/NetworkCapabilities.aidl
diff --git a/framework/src/android/net/NetworkInfo.aidl b/framework/aidl-export/android/net/NetworkInfo.aidl
similarity index 100%
rename from framework/src/android/net/NetworkInfo.aidl
rename to framework/aidl-export/android/net/NetworkInfo.aidl
diff --git a/framework/src/android/net/NetworkRequest.aidl b/framework/aidl-export/android/net/NetworkRequest.aidl
similarity index 100%
rename from framework/src/android/net/NetworkRequest.aidl
rename to framework/aidl-export/android/net/NetworkRequest.aidl
diff --git a/framework/src/android/net/ProxyInfo.aidl b/framework/aidl-export/android/net/ProxyInfo.aidl
similarity index 100%
rename from framework/src/android/net/ProxyInfo.aidl
rename to framework/aidl-export/android/net/ProxyInfo.aidl
diff --git a/framework/src/android/net/RouteInfo.aidl b/framework/aidl-export/android/net/RouteInfo.aidl
similarity index 100%
rename from framework/src/android/net/RouteInfo.aidl
rename to framework/aidl-export/android/net/RouteInfo.aidl
diff --git a/framework/src/android/net/StaticIpConfiguration.aidl b/framework/aidl-export/android/net/StaticIpConfiguration.aidl
similarity index 100%
rename from framework/src/android/net/StaticIpConfiguration.aidl
rename to framework/aidl-export/android/net/StaticIpConfiguration.aidl
diff --git a/framework/src/android/net/TestNetworkInterface.aidl b/framework/aidl-export/android/net/TestNetworkInterface.aidl
similarity index 100%
rename from framework/src/android/net/TestNetworkInterface.aidl
rename to framework/aidl-export/android/net/TestNetworkInterface.aidl
diff --git a/framework/src/android/net/apf/ApfCapabilities.aidl b/framework/aidl-export/android/net/apf/ApfCapabilities.aidl
similarity index 100%
rename from framework/src/android/net/apf/ApfCapabilities.aidl
rename to framework/aidl-export/android/net/apf/ApfCapabilities.aidl
diff --git a/framework/src/android/net/ConnectivityFrameworkInitializer.java b/framework/src/android/net/ConnectivityFrameworkInitializer.java
new file mode 100644
index 0000000..92a792b
--- /dev/null
+++ b/framework/src/android/net/ConnectivityFrameworkInitializer.java
@@ -0,0 +1,72 @@
+/*
+ * 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 android.net;
+
+import android.annotation.SystemApi;
+import android.app.SystemServiceRegistry;
+import android.content.Context;
+
+/**
+ * Class for performing registration for all core connectivity services.
+ *
+ * @hide
+ */
+@SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
+public final class ConnectivityFrameworkInitializer {
+ private ConnectivityFrameworkInitializer() {}
+
+ /**
+ * Called by {@link SystemServiceRegistry}'s static initializer and registers all core
+ * connectivity services to {@link Context}, so that {@link Context#getSystemService} can
+ * return them.
+ *
+ * @throws IllegalStateException if this is called anywhere besides
+ * {@link SystemServiceRegistry}.
+ */
+ public static void registerServiceWrappers() {
+ // registerContextAwareService will throw if this is called outside of SystemServiceRegistry
+ // initialization.
+ SystemServiceRegistry.registerContextAwareService(
+ Context.CONNECTIVITY_SERVICE,
+ ConnectivityManager.class,
+ (context, serviceBinder) -> {
+ IConnectivityManager icm = IConnectivityManager.Stub.asInterface(serviceBinder);
+ return new ConnectivityManager(context, icm);
+ }
+ );
+
+ SystemServiceRegistry.registerContextAwareService(
+ Context.CONNECTIVITY_DIAGNOSTICS_SERVICE,
+ ConnectivityDiagnosticsManager.class,
+ (context) -> {
+ final ConnectivityManager cm = context.getSystemService(
+ ConnectivityManager.class);
+ return cm.createDiagnosticsManager();
+ }
+ );
+
+ SystemServiceRegistry.registerContextAwareService(
+ Context.TEST_NETWORK_SERVICE,
+ TestNetworkManager.class,
+ context -> {
+ final ConnectivityManager cm = context.getSystemService(
+ ConnectivityManager.class);
+ return cm.startOrGetTestNetworkManager();
+ }
+ );
+ }
+}
diff --git a/framework/src/android/net/ConnectivityManager.java b/framework/src/android/net/ConnectivityManager.java
index 7f07bba..6273f4b 100644
--- a/framework/src/android/net/ConnectivityManager.java
+++ b/framework/src/android/net/ConnectivityManager.java
@@ -21,6 +21,7 @@
import static android.net.NetworkRequest.Type.LISTEN;
import static android.net.NetworkRequest.Type.REQUEST;
import static android.net.NetworkRequest.Type.TRACK_DEFAULT;
+import static android.net.NetworkRequest.Type.TRACK_SYSTEM_DEFAULT;
import static android.net.QosCallback.QosCallbackRegistrationException;
import android.annotation.CallbackExecutor;
@@ -48,8 +49,6 @@
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
-import android.os.INetworkActivityListener;
-import android.os.INetworkManagementService;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
@@ -455,7 +454,7 @@
* @hide
*/
@SystemApi
- public static final int TETHERING_WIFI = TetheringManager.TETHERING_WIFI;
+ public static final int TETHERING_WIFI = 0;
/**
* USB tethering type.
@@ -463,7 +462,7 @@
* @hide
*/
@SystemApi
- public static final int TETHERING_USB = TetheringManager.TETHERING_USB;
+ public static final int TETHERING_USB = 1;
/**
* Bluetooth tethering type.
@@ -471,7 +470,7 @@
* @hide
*/
@SystemApi
- public static final int TETHERING_BLUETOOTH = TetheringManager.TETHERING_BLUETOOTH;
+ public static final int TETHERING_BLUETOOTH = 2;
/**
* Wifi P2p tethering type.
@@ -823,6 +822,7 @@
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 130143562)
private final IConnectivityManager mService;
+
/**
* A kludge to facilitate static access where a Context pointer isn't available, like in the
* case of the static set/getProcessDefaultNetwork methods and from the Network class.
@@ -833,7 +833,6 @@
private final Context mContext;
- private INetworkManagementService mNMService;
private INetworkPolicyManager mNPManager;
private final TetheringManager mTetheringManager;
@@ -1068,109 +1067,6 @@
}
/**
- * Checks if a VPN app supports always-on mode.
- *
- * In order to support the always-on feature, an app has to
- * <ul>
- * <li>target {@link VERSION_CODES#N API 24} or above, and
- * <li>not opt out through the {@link VpnService#SERVICE_META_DATA_SUPPORTS_ALWAYS_ON}
- * meta-data field.
- * </ul>
- *
- * @param userId The identifier of the user for whom the VPN app is installed.
- * @param vpnPackage The canonical package name of the VPN app.
- * @return {@code true} if and only if the VPN app exists and supports always-on mode.
- * @hide
- */
- public boolean isAlwaysOnVpnPackageSupportedForUser(int userId, @Nullable String vpnPackage) {
- try {
- return mService.isAlwaysOnVpnPackageSupported(userId, vpnPackage);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Configures an always-on VPN connection through a specific application.
- * This connection is automatically granted and persisted after a reboot.
- *
- * <p>The designated package should declare a {@link VpnService} in its
- * manifest guarded by {@link android.Manifest.permission.BIND_VPN_SERVICE},
- * otherwise the call will fail.
- *
- * @param userId The identifier of the user to set an always-on VPN for.
- * @param vpnPackage The package name for an installed VPN app on the device, or {@code null}
- * to remove an existing always-on VPN configuration.
- * @param lockdownEnabled {@code true} to disallow networking when the VPN is not connected or
- * {@code false} otherwise.
- * @param lockdownAllowlist The list of packages that are allowed to access network directly
- * when VPN is in lockdown mode but is not running. Non-existent packages are ignored so
- * this method must be called when a package that should be allowed is installed or
- * uninstalled.
- * @return {@code true} if the package is set as always-on VPN controller;
- * {@code false} otherwise.
- * @hide
- */
- @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
- public boolean setAlwaysOnVpnPackageForUser(int userId, @Nullable String vpnPackage,
- boolean lockdownEnabled, @Nullable List<String> lockdownAllowlist) {
- try {
- return mService.setAlwaysOnVpnPackage(
- userId, vpnPackage, lockdownEnabled, lockdownAllowlist);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns the package name of the currently set always-on VPN application.
- * If there is no always-on VPN set, or the VPN is provided by the system instead
- * of by an app, {@code null} will be returned.
- *
- * @return Package name of VPN controller responsible for always-on VPN,
- * or {@code null} if none is set.
- * @hide
- */
- @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
- public String getAlwaysOnVpnPackageForUser(int userId) {
- try {
- return mService.getAlwaysOnVpnPackage(userId);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * @return whether always-on VPN is in lockdown mode.
- *
- * @hide
- **/
- @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
- public boolean isVpnLockdownEnabled(int userId) {
- try {
- return mService.isVpnLockdownEnabled(userId);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
-
- }
-
- /**
- * @return the list of packages that are allowed to access network when always-on VPN is in
- * lockdown mode but not connected. Returns {@code null} when VPN lockdown is not active.
- *
- * @hide
- **/
- @RequiresPermission(android.Manifest.permission.CONTROL_ALWAYS_ON_VPN)
- public List<String> getVpnLockdownWhitelist(int userId) {
- try {
- return mService.getVpnLockdownWhitelist(userId);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
* Adds or removes a requirement for given UID ranges to use the VPN.
*
* If set to {@code true}, informs the system that the UIDs in the specified ranges must not
@@ -1220,6 +1116,45 @@
}
/**
+ * Informs ConnectivityService of whether the legacy lockdown VPN, as implemented by
+ * LockdownVpnTracker, is in use. This is deprecated for new devices starting from Android 12
+ * but is still supported for backwards compatibility.
+ * <p>
+ * This type of VPN is assumed always to use the system default network, and must always declare
+ * exactly one underlying network, which is the network that was the default when the VPN
+ * connected.
+ * <p>
+ * Calling this method with {@code true} enables legacy behaviour, specifically:
+ * <ul>
+ * <li>Any VPN that applies to userId 0 behaves specially with respect to deprecated
+ * {@link #CONNECTIVITY_ACTION} broadcasts. Any such broadcasts will have the state in the
+ * {@link #EXTRA_NETWORK_INFO} replaced by state of the VPN network. Also, any time the VPN
+ * connects, a {@link #CONNECTIVITY_ACTION} broadcast will be sent for the network
+ * underlying the VPN.</li>
+ * <li>Deprecated APIs that return {@link NetworkInfo} objects will have their state
+ * similarly replaced by the VPN network state.</li>
+ * <li>Information on current network interfaces passed to NetworkStatsService will not
+ * include any VPN interfaces.</li>
+ * </ul>
+ *
+ * @param enabled whether legacy lockdown VPN is enabled or disabled
+ *
+ * TODO: @SystemApi(client = MODULE_LIBRARIES)
+ *
+ * @hide
+ */
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_SETTINGS})
+ public void setLegacyLockdownVpnEnabled(boolean enabled) {
+ try {
+ mService.setLegacyLockdownVpnEnabled(enabled);
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+ }
+
+ /**
* Returns details about the currently active default data network
* for a given uid. This is for internal use only to avoid spying
* other apps.
@@ -1368,7 +1303,7 @@
public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
try {
return mService.getDefaultNetworkCapabilitiesForUser(
- userId, mContext.getOpPackageName());
+ userId, mContext.getOpPackageName(), getAttributionTag());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -1450,7 +1385,8 @@
@Nullable
public NetworkCapabilities getNetworkCapabilities(@Nullable Network network) {
try {
- return mService.getNetworkCapabilities(network, mContext.getOpPackageName());
+ return mService.getNetworkCapabilities(
+ network, mContext.getOpPackageName(), getAttributionTag());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -2142,7 +2078,7 @@
*/
// TODO: Remove method and replace with direct call once R code is pushed to AOSP
private @Nullable String getAttributionTag() {
- return null;
+ return mContext.getAttributionTag();
}
/**
@@ -2220,17 +2156,6 @@
void onNetworkActive();
}
- private INetworkManagementService getNetworkManagementService() {
- synchronized (this) {
- if (mNMService != null) {
- return mNMService;
- }
- IBinder b = ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE);
- mNMService = INetworkManagementService.Stub.asInterface(b);
- return mNMService;
- }
- }
-
private final ArrayMap<OnNetworkActiveListener, INetworkActivityListener>
mNetworkActivityListeners = new ArrayMap<>();
@@ -2255,7 +2180,7 @@
};
try {
- getNetworkManagementService().registerNetworkActivityListener(rl);
+ mService.registerNetworkActivityListener(rl);
mNetworkActivityListeners.put(l, rl);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
@@ -2272,7 +2197,7 @@
INetworkActivityListener rl = mNetworkActivityListeners.get(l);
Preconditions.checkArgument(rl != null, "Listener was not registered.");
try {
- getNetworkManagementService().unregisterNetworkActivityListener(rl);
+ mService.registerNetworkActivityListener(rl);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -2288,7 +2213,7 @@
*/
public boolean isDefaultNetworkActive() {
try {
- return getNetworkManagementService().isNetworkActive();
+ return mService.isDefaultNetworkActive();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
@@ -2808,7 +2733,7 @@
*/
@SystemApi
@Deprecated
- public static final int TETHER_ERROR_NO_ERROR = TetheringManager.TETHER_ERROR_NO_ERROR;
+ public static final int TETHER_ERROR_NO_ERROR = 0;
/**
* @deprecated Use {@link TetheringManager#TETHER_ERROR_UNKNOWN_IFACE}.
* {@hide}
@@ -2884,8 +2809,7 @@
*/
@SystemApi
@Deprecated
- public static final int TETHER_ERROR_PROVISION_FAILED =
- TetheringManager.TETHER_ERROR_PROVISIONING_FAILED;
+ public static final int TETHER_ERROR_PROVISION_FAILED = 11;
/**
* @deprecated Use {@link TetheringManager#TETHER_ERROR_DHCPSERVER_ERROR}.
* {@hide}
@@ -2899,8 +2823,7 @@
*/
@SystemApi
@Deprecated
- public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN =
- TetheringManager.TETHER_ERROR_ENTITLEMENT_UNKNOWN;
+ public static final int TETHER_ERROR_ENTITLEMENT_UNKONWN = 13;
/**
* Get a more detailed error code after a Tethering or Untethering
@@ -3178,23 +3101,6 @@
}
/**
- * If the LockdownVpn mechanism is enabled, updates the vpn
- * with a reload of its profile.
- *
- * @return a boolean with {@code} indicating success
- *
- * <p>This method can only be called by the system UID
- * {@hide}
- */
- public boolean updateLockdownVpn() {
- try {
- return mService.updateLockdownVpn();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
* Set sign in error notification to visible or invisible
*
* @hide
@@ -3231,32 +3137,6 @@
}
}
- /** {@hide} - returns the factory serial number */
- @UnsupportedAppUsage
- @RequiresPermission(anyOf = {
- NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
- android.Manifest.permission.NETWORK_FACTORY})
- public int registerNetworkFactory(Messenger messenger, String name) {
- try {
- return mService.registerNetworkFactory(messenger, name);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** {@hide} */
- @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
- @RequiresPermission(anyOf = {
- NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
- android.Manifest.permission.NETWORK_FACTORY})
- public void unregisterNetworkFactory(Messenger messenger) {
- try {
- mService.unregisterNetworkFactory(messenger);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
/**
* Registers the specified {@link NetworkProvider}.
* Each listener must only be registered once. The listener can be unregistered with
@@ -3746,7 +3626,8 @@
printStackTrace();
checkCallbackNotNull(callback);
Preconditions.checkArgument(
- reqType == TRACK_DEFAULT || need != null, "null NetworkCapabilities");
+ reqType == TRACK_DEFAULT || reqType == TRACK_SYSTEM_DEFAULT || need != null,
+ "null NetworkCapabilities");
final NetworkRequest request;
final String callingPackageName = mContext.getOpPackageName();
try {
@@ -3761,7 +3642,8 @@
Binder binder = new Binder();
if (reqType == LISTEN) {
request = mService.listenForNetwork(
- need, messenger, binder, callingPackageName);
+ need, messenger, binder, callingPackageName,
+ getAttributionTag());
} else {
request = mService.requestNetwork(
need, reqType.ordinal(), messenger, timeoutMs, binder, legacyType,
@@ -4206,7 +4088,8 @@
checkPendingIntentNotNull(operation);
try {
mService.pendingListenForNetwork(
- request.networkCapabilities, operation, mContext.getOpPackageName());
+ request.networkCapabilities, operation, mContext.getOpPackageName(),
+ getAttributionTag());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
} catch (ServiceSpecificException e) {
@@ -4215,8 +4098,9 @@
}
/**
- * Registers to receive notifications about changes in the system default network. The callbacks
- * will continue to be called until either the application exits or
+ * Registers to receive notifications about changes in the application's default network. This
+ * may be a physical network or a virtual network, such as a VPN that applies to the
+ * application. The callbacks will continue to be called until either the application exits or
* {@link #unregisterNetworkCallback(NetworkCallback)} is called.
*
* <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
@@ -4229,7 +4113,7 @@
* {@link #unregisterNetworkCallback(NetworkCallback)}.
*
* @param networkCallback The {@link NetworkCallback} that the system will call as the
- * system default network changes.
+ * application's default network changes.
* The callback is invoked on the default internal Handler.
* @throws RuntimeException if the app already has too many callbacks registered.
*/
@@ -4239,10 +4123,46 @@
}
/**
+ * Registers to receive notifications about changes in the application's default network. This
+ * may be a physical network or a virtual network, such as a VPN that applies to the
+ * application. The callbacks will continue to be called until either the application exits or
+ * {@link #unregisterNetworkCallback(NetworkCallback)} is called.
+ *
+ * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
+ * number of outstanding requests to 100 per app (identified by their UID), shared with
+ * all variants of this method, of {@link #requestNetwork} as well as
+ * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
+ * Requesting a network with this method will count toward this limit. If this limit is
+ * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
+ * make sure to unregister the callbacks with
+ * {@link #unregisterNetworkCallback(NetworkCallback)}.
+ *
+ * @param networkCallback The {@link NetworkCallback} that the system will call as the
+ * application's default network changes.
+ * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
+ * @throws RuntimeException if the app already has too many callbacks registered.
+ */
+ @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
+ public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
+ @NonNull Handler handler) {
+ CallbackHandler cbHandler = new CallbackHandler(handler);
+ sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
+ TRACK_DEFAULT, TYPE_NONE, cbHandler);
+ }
+
+ /**
* Registers to receive notifications about changes in the system default network. The callbacks
* will continue to be called until either the application exits or
* {@link #unregisterNetworkCallback(NetworkCallback)} is called.
*
+ * This method should not be used to determine networking state seen by applications, because in
+ * many cases, most or even all application traffic may not use the default network directly,
+ * and traffic from different applications may go on different networks by default. As an
+ * example, if a VPN is connected, traffic from all applications might be sent through the VPN
+ * and not onto the system default network. Applications or system components desiring to do
+ * determine network state as seen by applications should use other methods such as
+ * {@link #registerDefaultNetworkCallback(NetworkCallback, Handler)}.
+ *
* <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
* number of outstanding requests to 100 per app (identified by their UID), shared with
* all variants of this method, of {@link #requestNetwork} as well as
@@ -4256,20 +4176,19 @@
* system default network changes.
* @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
* @throws RuntimeException if the app already has too many callbacks registered.
+ *
+ * @hide
*/
- @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
- public void registerDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
+ @SystemApi(client = MODULE_LIBRARIES)
+ @SuppressLint({"ExecutorRegistration", "PairedRegistration"})
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_SETTINGS})
+ public void registerSystemDefaultNetworkCallback(@NonNull NetworkCallback networkCallback,
@NonNull Handler handler) {
- // This works because if the NetworkCapabilities are null,
- // ConnectivityService takes them from the default request.
- //
- // Since the capabilities are exactly the same as the default request's
- // capabilities, this request is guaranteed, at all times, to be
- // satisfied by the same network, if any, that satisfies the default
- // request, i.e., the system default network.
CallbackHandler cbHandler = new CallbackHandler(handler);
sendRequestForNetwork(null /* NetworkCapabilities need */, networkCallback, 0,
- TRACK_DEFAULT, TYPE_NONE, cbHandler);
+ TRACK_SYSTEM_DEFAULT, TYPE_NONE, cbHandler);
}
/**
@@ -4609,7 +4528,7 @@
// Set HTTP proxy system properties to match network.
// TODO: Deprecate this static method and replace it with a non-static version.
try {
- Proxy.setHttpProxySystemProperty(getInstance().getDefaultProxy());
+ Proxy.setHttpProxyConfiguration(getInstance().getDefaultProxy());
} catch (SecurityException e) {
// The process doesn't have ACCESS_NETWORK_STATE, so we can't fetch the proxy.
Log.e(TAG, "Can't set proxy properties", e);
@@ -4823,6 +4742,23 @@
}
}
+ /** @hide */
+ public TestNetworkManager startOrGetTestNetworkManager() {
+ final IBinder tnBinder;
+ try {
+ tnBinder = mService.startOrGetTestNetworkService();
+ } catch (RemoteException e) {
+ throw e.rethrowFromSystemServer();
+ }
+
+ return new TestNetworkManager(ITestNetworkManager.Stub.asInterface(tnBinder));
+ }
+
+ /** @hide */
+ public ConnectivityDiagnosticsManager createDiagnosticsManager() {
+ return new ConnectivityDiagnosticsManager(mContext, mService);
+ }
+
/**
* Simulates a Data Stall for the specified Network.
*
@@ -4849,11 +4785,6 @@
}
}
- private void setOemNetworkPreference(@NonNull OemNetworkPreferences preference) {
- Log.d(TAG, "setOemNetworkPreference called with preference: "
- + preference.toString());
- }
-
@NonNull
private final List<QosCallbackConnection> mQosCallbackConnections = new ArrayList<>();
@@ -5055,4 +4986,60 @@
sendRequestForNetwork(nc, networkCallback, 0, BACKGROUND_REQUEST,
TYPE_NONE, handler == null ? getDefaultHandler() : new CallbackHandler(handler));
}
+
+ /**
+ * Listener for {@link #setOemNetworkPreference(OemNetworkPreferences, Executor,
+ * OnSetOemNetworkPreferenceListener)}.
+ * @hide
+ */
+ @SystemApi
+ public interface OnSetOemNetworkPreferenceListener {
+ /**
+ * Called when setOemNetworkPreference() successfully completes.
+ */
+ void onComplete();
+ }
+
+ /**
+ * Used by automotive devices to set the network preferences used to direct traffic at an
+ * application level as per the given OemNetworkPreferences. An example use-case would be an
+ * automotive OEM wanting to provide connectivity for applications critical to the usage of a
+ * vehicle via a particular network.
+ *
+ * Calling this will overwrite the existing preference.
+ *
+ * @param preference {@link OemNetworkPreferences} The application network preference to be set.
+ * @param executor the executor on which listener will be invoked.
+ * @param listener {@link OnSetOemNetworkPreferenceListener} optional listener used to
+ * communicate completion of setOemNetworkPreference(). This will only be
+ * called once upon successful completion of setOemNetworkPreference().
+ * @throws IllegalArgumentException if {@code preference} contains invalid preference values.
+ * @throws SecurityException if missing the appropriate permissions.
+ * @throws UnsupportedOperationException if called on a non-automotive device.
+ * @hide
+ */
+ @SystemApi
+ @RequiresPermission(android.Manifest.permission.CONTROL_OEM_PAID_NETWORK_PREFERENCE)
+ public void setOemNetworkPreference(@NonNull final OemNetworkPreferences preference,
+ @Nullable @CallbackExecutor final Executor executor,
+ @Nullable final OnSetOemNetworkPreferenceListener listener) {
+ Objects.requireNonNull(preference, "OemNetworkPreferences must be non-null");
+ if (null != listener) {
+ Objects.requireNonNull(executor, "Executor must be non-null");
+ }
+ final IOnSetOemNetworkPreferenceListener listenerInternal = listener == null ? null :
+ new IOnSetOemNetworkPreferenceListener.Stub() {
+ @Override
+ public void onComplete() {
+ executor.execute(listener::onComplete);
+ }
+ };
+
+ try {
+ mService.setOemNetworkPreference(preference, listenerInternal);
+ } catch (RemoteException e) {
+ Log.e(TAG, "setOemNetworkPreference() failed for preference: " + preference.toString());
+ throw e.rethrowFromSystemServer();
+ }
+ }
}
diff --git a/framework/src/android/net/ConnectivityMetricsEvent.aidl b/framework/src/android/net/ConnectivityMetricsEvent.aidl
deleted file mode 100644
index 1c541dc..0000000
--- a/framework/src/android/net/ConnectivityMetricsEvent.aidl
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright (C) 2016 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;
-
-/** {@hide} */
-parcelable ConnectivityMetricsEvent;
diff --git a/framework/src/android/net/IConnectivityManager.aidl b/framework/src/android/net/IConnectivityManager.aidl
index 1b4d2e4..160338d 100644
--- a/framework/src/android/net/IConnectivityManager.aidl
+++ b/framework/src/android/net/IConnectivityManager.aidl
@@ -20,6 +20,8 @@
import android.net.ConnectionInfo;
import android.net.ConnectivityDiagnosticsManager;
import android.net.IConnectivityDiagnosticsCallback;
+import android.net.IOnSetOemNetworkPreferenceListener;
+import android.net.INetworkActivityListener;
import android.net.IQosCallback;
import android.net.ISocketKeepaliveCallback;
import android.net.LinkProperties;
@@ -29,21 +31,18 @@
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.NetworkState;
+import android.net.OemNetworkPreferences;
import android.net.ProxyInfo;
import android.net.UidRange;
import android.net.QosSocketInfo;
import android.os.Bundle;
import android.os.IBinder;
-import android.os.INetworkActivityListener;
import android.os.Messenger;
import android.os.ParcelFileDescriptor;
import android.os.PersistableBundle;
import android.os.ResultReceiver;
import com.android.connectivity.aidl.INetworkAgent;
-import com.android.internal.net.LegacyVpnInfo;
-import com.android.internal.net.VpnConfig;
-import com.android.internal.net.VpnProfile;
/**
* Interface that answers queries about, and allows changing, the
@@ -65,7 +64,7 @@
Network getNetworkForType(int networkType);
Network[] getAllNetworks();
NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(
- int userId, String callingPackageName);
+ int userId, String callingPackageName, String callingAttributionTag);
boolean isNetworkSupported(int networkType);
@@ -74,7 +73,8 @@
LinkProperties getLinkPropertiesForType(int networkType);
LinkProperties getLinkProperties(in Network network);
- NetworkCapabilities getNetworkCapabilities(in Network network, String callingPackageName);
+ NetworkCapabilities getNetworkCapabilities(in Network network, String callingPackageName,
+ String callingAttributionTag);
@UnsupportedAppUsage(maxTargetSdk = 30, trackingBug = 170729553)
NetworkState[] getAllNetworkState();
@@ -120,35 +120,8 @@
ProxyInfo getProxyForNetwork(in Network nework);
- boolean prepareVpn(String oldPackage, String newPackage, int userId);
-
- void setVpnPackageAuthorization(String packageName, int userId, int vpnType);
-
- ParcelFileDescriptor establishVpn(in VpnConfig config);
-
- boolean provisionVpnProfile(in VpnProfile profile, String packageName);
-
- void deleteVpnProfile(String packageName);
-
- void startVpnProfile(String packageName);
-
- void stopVpnProfile(String packageName);
-
- VpnConfig getVpnConfig(int userId);
-
- @UnsupportedAppUsage(maxTargetSdk = 30, trackingBug = 170729553)
- void startLegacyVpn(in VpnProfile profile);
-
- LegacyVpnInfo getLegacyVpnInfo(int userId);
-
- boolean updateLockdownVpn();
- boolean isAlwaysOnVpnPackageSupported(int userId, String packageName);
- boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown,
- in List<String> lockdownWhitelist);
- String getAlwaysOnVpnPackage(int userId);
- boolean isVpnLockdownEnabled(int userId);
- List<String> getVpnLockdownWhitelist(int userId);
void setRequireVpnForUids(boolean requireVpn, in UidRange[] ranges);
+ void setLegacyLockdownVpnEnabled(boolean enabled);
void setProvisioningNotificationVisible(boolean visible, int networkType, in String action);
@@ -156,9 +129,6 @@
boolean requestBandwidthUpdate(in Network network);
- int registerNetworkFactory(in Messenger messenger, in String name);
- void unregisterNetworkFactory(in Messenger messenger);
-
int registerNetworkProvider(in Messenger messenger, in String name);
void unregisterNetworkProvider(in Messenger messenger);
@@ -178,10 +148,12 @@
void releasePendingNetworkRequest(in PendingIntent operation);
NetworkRequest listenForNetwork(in NetworkCapabilities networkCapabilities,
- in Messenger messenger, in IBinder binder, String callingPackageName);
+ in Messenger messenger, in IBinder binder, String callingPackageName,
+ String callingAttributionTag);
void pendingListenForNetwork(in NetworkCapabilities networkCapabilities,
- in PendingIntent operation, String callingPackageName);
+ in PendingIntent operation, String callingPackageName,
+ String callingAttributionTag);
void releaseNetworkRequest(in NetworkRequest networkRequest);
@@ -198,10 +170,6 @@
int getRestoreDefaultNetworkDelay(int networkType);
- boolean addVpnAddress(String address, int prefixLength);
- boolean removeVpnAddress(String address, int prefixLength);
- boolean setUnderlyingNetworksForVpn(in Network[] networks);
-
void factoryReset();
void startNattKeepalive(in Network network, int intervalSeconds,
@@ -221,8 +189,6 @@
byte[] getNetworkWatchlistConfigHash();
int getConnectionOwnerUid(in ConnectionInfo connectionInfo);
- boolean isCallerCurrentAlwaysOnVpnApp();
- boolean isCallerCurrentAlwaysOnVpnLockdownApp();
void registerConnectivityDiagnosticsCallback(in IConnectivityDiagnosticsCallback callback,
in NetworkRequest request, String callingPackageName);
@@ -243,4 +209,7 @@
void registerQosSocketCallback(in QosSocketInfo socketInfo, in IQosCallback callback);
void unregisterQosCallback(in IQosCallback callback);
+
+ void setOemNetworkPreference(in OemNetworkPreferences preference,
+ in IOnSetOemNetworkPreferenceListener listener);
}
diff --git a/framework/src/android/net/INetworkActivityListener.aidl b/framework/src/android/net/INetworkActivityListener.aidl
new file mode 100644
index 0000000..79687dd
--- /dev/null
+++ b/framework/src/android/net/INetworkActivityListener.aidl
@@ -0,0 +1,24 @@
+/* Copyright 2013, 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;
+
+/**
+ * @hide
+ */
+oneway interface INetworkActivityListener
+{
+ void onNetworkActive();
+}
diff --git a/framework/src/android/net/InterfaceConfiguration.aidl b/framework/src/android/net/InterfaceConfiguration.aidl
deleted file mode 100644
index 8aa5e34..0000000
--- a/framework/src/android/net/InterfaceConfiguration.aidl
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- * Copyright (c) 2008, 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;
-
-parcelable InterfaceConfiguration;
diff --git a/framework/src/android/net/IpConfiguration.java b/framework/src/android/net/IpConfiguration.java
index 0b20564..d5f8b2e 100644
--- a/framework/src/android/net/IpConfiguration.java
+++ b/framework/src/android/net/IpConfiguration.java
@@ -167,7 +167,7 @@
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (o == this) {
return true;
}
diff --git a/framework/src/android/net/IpPrefix.java b/framework/src/android/net/IpPrefix.java
index e7c8014..bcb65fa 100644
--- a/framework/src/android/net/IpPrefix.java
+++ b/framework/src/android/net/IpPrefix.java
@@ -18,6 +18,7 @@
import android.annotation.IntRange;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.os.Parcel;
import android.os.Parcelable;
@@ -124,7 +125,7 @@
* @return {@code true} if both objects are equal, {@code false} otherwise.
*/
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (!(obj instanceof IpPrefix)) {
return false;
}
diff --git a/framework/src/android/net/LinkAddress.java b/framework/src/android/net/LinkAddress.java
index 44d25a1..d1bdaa0 100644
--- a/framework/src/android/net/LinkAddress.java
+++ b/framework/src/android/net/LinkAddress.java
@@ -349,7 +349,7 @@
* @return {@code true} if both objects are equal, {@code false} otherwise.
*/
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (!(obj instanceof LinkAddress)) {
return false;
}
diff --git a/framework/src/android/net/LinkProperties.java b/framework/src/android/net/LinkProperties.java
index 486e2d7..e41ed72 100644
--- a/framework/src/android/net/LinkProperties.java
+++ b/framework/src/android/net/LinkProperties.java
@@ -1613,7 +1613,7 @@
* @return {@code true} if both objects are equal, {@code false} otherwise.
*/
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof LinkProperties)) return false;
diff --git a/framework/src/android/net/MacAddress.java b/framework/src/android/net/MacAddress.java
index c7116b4..c83c23a 100644
--- a/framework/src/android/net/MacAddress.java
+++ b/framework/src/android/net/MacAddress.java
@@ -161,7 +161,7 @@
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
return (o instanceof MacAddress) && ((MacAddress) o).mAddr == mAddr;
}
diff --git a/framework/src/android/net/Network.java b/framework/src/android/net/Network.java
index b07bd68..46141e0 100644
--- a/framework/src/android/net/Network.java
+++ b/framework/src/android/net/Network.java
@@ -17,6 +17,7 @@
package android.net;
import android.annotation.NonNull;
+import android.annotation.Nullable;
import android.annotation.SystemApi;
import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
@@ -510,7 +511,7 @@
};
@Override
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (!(obj instanceof Network)) return false;
Network other = (Network)obj;
return this.netId == other.netId;
diff --git a/framework/src/android/net/NetworkAgent.java b/framework/src/android/net/NetworkAgent.java
index d22d82d..27aa15d 100644
--- a/framework/src/android/net/NetworkAgent.java
+++ b/framework/src/android/net/NetworkAgent.java
@@ -20,6 +20,7 @@
import android.annotation.IntRange;
import android.annotation.NonNull;
import android.annotation.Nullable;
+import android.annotation.SuppressLint;
import android.annotation.SystemApi;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
@@ -775,7 +776,8 @@
* @param underlyingNetworks the new list of underlying networks.
* @see {@link VpnService.Builder#setUnderlyingNetworks(Network[])}
*/
- public final void setUnderlyingNetworks(@Nullable List<Network> underlyingNetworks) {
+ public final void setUnderlyingNetworks(
+ @SuppressLint("NullableCollection") @Nullable List<Network> underlyingNetworks) {
final ArrayList<Network> underlyingArray = (underlyingNetworks != null)
? new ArrayList<>(underlyingNetworks) : null;
queueOrSendMessage(reg -> reg.sendUnderlyingNetworks(underlyingArray));
diff --git a/framework/src/android/net/NetworkCapabilities.java b/framework/src/android/net/NetworkCapabilities.java
index 3843b9a..26d14cb 100644
--- a/framework/src/android/net/NetworkCapabilities.java
+++ b/framework/src/android/net/NetworkCapabilities.java
@@ -34,9 +34,9 @@
import android.util.proto.ProtoOutputStream;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.ArrayUtils;
import com.android.internal.util.BitUtils;
import com.android.internal.util.Preconditions;
+import com.android.net.module.util.CollectionUtils;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -401,11 +401,18 @@
public static final int NET_CAPABILITY_VEHICLE_INTERNAL = 27;
/**
- * Indicates that this network is not managed by a Virtual Carrier Network (VCN).
- *
- * TODO(b/177299683): Add additional clarifying javadoc.
+ * Indicates that this network is not subsumed by a Virtual Carrier Network (VCN).
+ * <p>
+ * To provide an experience on a VCN similar to a single traditional carrier network, in
+ * some cases the system sets this bit is set by default in application's network requests,
+ * and may choose to remove it at its own discretion when matching the request to a network.
+ * <p>
+ * Applications that want to know about a Virtual Carrier Network's underlying networks,
+ * for example to use them for multipath purposes, should remove this bit from their network
+ * requests ; the system will not add it back once removed.
* @hide
*/
+ @SystemApi
public static final int NET_CAPABILITY_NOT_VCN_MANAGED = 28;
private static final int MIN_NET_CAPABILITY = NET_CAPABILITY_MMS;
@@ -755,19 +762,21 @@
final int originalSignalStrength = mSignalStrength;
final int originalOwnerUid = getOwnerUid();
final int[] originalAdministratorUids = getAdministratorUids();
+ final TransportInfo originalTransportInfo = getTransportInfo();
clearAll();
mTransportTypes = (originalTransportTypes & TEST_NETWORKS_ALLOWED_TRANSPORTS)
| (1 << TRANSPORT_TEST);
mNetworkCapabilities = originalCapabilities & TEST_NETWORKS_ALLOWED_CAPABILITIES;
mNetworkSpecifier = originalSpecifier;
mSignalStrength = originalSignalStrength;
+ mTransportInfo = originalTransportInfo;
// Only retain the owner and administrator UIDs if they match the app registering the remote
// caller that registered the network.
if (originalOwnerUid == creatorUid) {
setOwnerUid(creatorUid);
}
- if (ArrayUtils.contains(originalAdministratorUids, creatorUid)) {
+ if (CollectionUtils.contains(originalAdministratorUids, creatorUid)) {
setAdministratorUids(new int[] {creatorUid});
}
// There is no need to clear the UIDs, they have already been cleared by clearAll() above.
@@ -1779,6 +1788,15 @@
return 0;
}
+ private <T extends Parcelable> void writeParcelableArraySet(Parcel in,
+ @Nullable ArraySet<T> val, int flags) {
+ final int size = (val != null) ? val.size() : -1;
+ in.writeInt(size);
+ for (int i = 0; i < size; i++) {
+ in.writeParcelable(val.valueAt(i), flags);
+ }
+ }
+
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(mNetworkCapabilities);
@@ -1789,7 +1807,7 @@
dest.writeParcelable((Parcelable) mNetworkSpecifier, flags);
dest.writeParcelable((Parcelable) mTransportInfo, flags);
dest.writeInt(mSignalStrength);
- dest.writeArraySet(mUids);
+ writeParcelableArraySet(dest, mUids, flags);
dest.writeString(mSSID);
dest.writeBoolean(mPrivateDnsBroken);
dest.writeIntArray(getAdministratorUids());
@@ -1812,8 +1830,7 @@
netCap.mNetworkSpecifier = in.readParcelable(null);
netCap.mTransportInfo = in.readParcelable(null);
netCap.mSignalStrength = in.readInt();
- netCap.mUids = (ArraySet<UidRange>) in.readArraySet(
- null /* ClassLoader, null for default */);
+ netCap.mUids = readParcelableArraySet(in, null /* ClassLoader, null for default */);
netCap.mSSID = in.readString();
netCap.mPrivateDnsBroken = in.readBoolean();
netCap.setAdministratorUids(in.createIntArray());
@@ -1826,6 +1843,20 @@
public NetworkCapabilities[] newArray(int size) {
return new NetworkCapabilities[size];
}
+
+ private @Nullable <T extends Parcelable> ArraySet<T> readParcelableArraySet(Parcel in,
+ @Nullable ClassLoader loader) {
+ final int size = in.readInt();
+ if (size < 0) {
+ return null;
+ }
+ final ArraySet<T> result = new ArraySet<>(size);
+ for (int i = 0; i < size; i++) {
+ final T value = in.readParcelable(loader);
+ result.append(value);
+ }
+ return result;
+ }
};
@Override
@@ -1873,7 +1904,7 @@
sb.append(" OwnerUid: ").append(mOwnerUid);
}
- if (!ArrayUtils.isEmpty(mAdministratorUids)) {
+ if (mAdministratorUids != null && mAdministratorUids.length != 0) {
sb.append(" AdminUids: ").append(Arrays.toString(mAdministratorUids));
}
@@ -2054,9 +2085,10 @@
/**
* Check if private dns is broken.
*
- * @return {@code true} if {@code mPrivateDnsBroken} is set when private DNS is broken.
+ * @return {@code true} if private DNS is broken on this network.
* @hide
*/
+ @SystemApi
public boolean isPrivateDnsBroken() {
return mPrivateDnsBroken;
}
@@ -2299,6 +2331,17 @@
}
/**
+ * Completely clears the contents of this object, removing even the capabilities that are
+ * set by default when the object is constructed.
+ * @return this builder
+ */
+ @NonNull
+ public Builder clearAll() {
+ mCaps.clearAll();
+ return this;
+ }
+
+ /**
* Sets the owner UID.
*
* The default value is {@link Process#INVALID_UID}. Pass this value to reset.
@@ -2506,7 +2549,7 @@
@NonNull
public NetworkCapabilities build() {
if (mCaps.getOwnerUid() != Process.INVALID_UID) {
- if (!ArrayUtils.contains(mCaps.getAdministratorUids(), mCaps.getOwnerUid())) {
+ if (!CollectionUtils.contains(mCaps.getAdministratorUids(), mCaps.getOwnerUid())) {
throw new IllegalStateException("The owner UID must be included in "
+ " administrator UIDs.");
}
diff --git a/framework/src/android/net/NetworkRequest.java b/framework/src/android/net/NetworkRequest.java
index 04011fc..4e3085f 100644
--- a/framework/src/android/net/NetworkRequest.java
+++ b/framework/src/android/net/NetworkRequest.java
@@ -86,17 +86,14 @@
* callbacks about the single, highest scoring current network
* (if any) that matches the specified NetworkCapabilities, or
*
- * - TRACK_DEFAULT, a hybrid of the two designed such that the
- * framework will issue callbacks for the single, highest scoring
- * current network (if any) that matches the capabilities of the
- * default Internet request (mDefaultRequest), but which cannot cause
- * the framework to either create or retain the existence of any
- * specific network. Note that from the point of view of the request
- * matching code, TRACK_DEFAULT is identical to REQUEST: its special
- * behaviour is not due to different semantics, but to the fact that
- * the system will only ever create a TRACK_DEFAULT with capabilities
- * that are identical to the default request's capabilities, thus
- * causing it to share fate in every way with the default request.
+ * - TRACK_DEFAULT, which causes the framework to issue callbacks for
+ * the single, highest scoring current network (if any) that will
+ * be chosen for an app, but which cannot cause the framework to
+ * either create or retain the existence of any specific network.
+ *
+ * - TRACK_SYSTEM_DEFAULT, which causes the framework to send callbacks
+ * for the network (if any) that satisfies the default Internet
+ * request.
*
* - BACKGROUND_REQUEST, like REQUEST but does not cause any networks
* to retain the NET_CAPABILITY_FOREGROUND capability. A network with
@@ -119,6 +116,7 @@
TRACK_DEFAULT,
REQUEST,
BACKGROUND_REQUEST,
+ TRACK_SYSTEM_DEFAULT,
};
/**
@@ -435,25 +433,7 @@
* @hide
*/
public boolean isRequest() {
- return isForegroundRequest() || isBackgroundRequest();
- }
-
- /**
- * Returns true iff. the contained NetworkRequest is one that:
- *
- * - should be associated with at most one satisfying network
- * at a time;
- *
- * - should cause a network to be kept up and in the foreground if
- * it is the best network which can satisfy the NetworkRequest.
- *
- * For full detail of how isRequest() is used for pairing Networks with
- * NetworkRequests read rematchNetworkAndRequests().
- *
- * @hide
- */
- public boolean isForegroundRequest() {
- return type == Type.TRACK_DEFAULT || type == Type.REQUEST;
+ return type == Type.REQUEST || type == Type.BACKGROUND_REQUEST;
}
/**
@@ -550,6 +530,8 @@
return NetworkRequestProto.TYPE_REQUEST;
case BACKGROUND_REQUEST:
return NetworkRequestProto.TYPE_BACKGROUND_REQUEST;
+ case TRACK_SYSTEM_DEFAULT:
+ return NetworkRequestProto.TYPE_TRACK_SYSTEM_DEFAULT;
default:
return NetworkRequestProto.TYPE_UNKNOWN;
}
@@ -567,7 +549,7 @@
proto.end(token);
}
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (obj instanceof NetworkRequest == false) return false;
NetworkRequest that = (NetworkRequest)obj;
return (that.legacyType == this.legacyType &&
diff --git a/framework/src/android/net/Proxy.java b/framework/src/android/net/Proxy.java
index 03b07e0..77c8a4f 100644
--- a/framework/src/android/net/Proxy.java
+++ b/framework/src/android/net/Proxy.java
@@ -16,8 +16,10 @@
package android.net;
+import android.annotation.Nullable;
import android.annotation.SdkConstant;
import android.annotation.SdkConstant.SdkConstantType;
+import android.annotation.SystemApi;
import android.compat.annotation.UnsupportedAppUsage;
import android.content.Context;
import android.os.Build;
@@ -30,8 +32,6 @@
import java.net.ProxySelector;
import java.net.URI;
import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
/**
* A convenience class for accessing the user and default proxy
@@ -64,40 +64,9 @@
@Deprecated
public static final String EXTRA_PROXY_INFO = "android.intent.extra.PROXY_INFO";
- /** @hide */
- public static final int PROXY_VALID = 0;
- /** @hide */
- public static final int PROXY_HOSTNAME_EMPTY = 1;
- /** @hide */
- public static final int PROXY_HOSTNAME_INVALID = 2;
- /** @hide */
- public static final int PROXY_PORT_EMPTY = 3;
- /** @hide */
- public static final int PROXY_PORT_INVALID = 4;
- /** @hide */
- public static final int PROXY_EXCLLIST_INVALID = 5;
-
private static ConnectivityManager sConnectivityManager = null;
- // Hostname / IP REGEX validation
- // Matches blank input, ips, and domain names
- private static final String NAME_IP_REGEX =
- "[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*(\\.[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*)*";
-
- private static final String HOSTNAME_REGEXP = "^$|^" + NAME_IP_REGEX + "$";
-
- private static final Pattern HOSTNAME_PATTERN;
-
- private static final String EXCL_REGEX =
- "[a-zA-Z0-9*]+(\\-[a-zA-Z0-9*]+)*(\\.[a-zA-Z0-9*]+(\\-[a-zA-Z0-9*]+)*)*";
-
- private static final String EXCLLIST_REGEXP = "^$|^" + EXCL_REGEX + "(," + EXCL_REGEX + ")*$";
-
- private static final Pattern EXCLLIST_PATTERN;
-
static {
- HOSTNAME_PATTERN = Pattern.compile(HOSTNAME_REGEXP);
- EXCLLIST_PATTERN = Pattern.compile(EXCLLIST_REGEXP);
sDefaultProxySelector = ProxySelector.getDefault();
}
@@ -216,36 +185,21 @@
return false;
}
- /**
- * Validate syntax of hostname, port and exclusion list entries
- * {@hide}
- */
- public static int validate(String hostname, String port, String exclList) {
- Matcher match = HOSTNAME_PATTERN.matcher(hostname);
- Matcher listMatch = EXCLLIST_PATTERN.matcher(exclList);
-
- if (!match.matches()) return PROXY_HOSTNAME_INVALID;
-
- if (!listMatch.matches()) return PROXY_EXCLLIST_INVALID;
-
- if (hostname.length() > 0 && port.length() == 0) return PROXY_PORT_EMPTY;
-
- if (port.length() > 0) {
- if (hostname.length() == 0) return PROXY_HOSTNAME_EMPTY;
- int portVal = -1;
- try {
- portVal = Integer.parseInt(port);
- } catch (NumberFormatException ex) {
- return PROXY_PORT_INVALID;
- }
- if (portVal <= 0 || portVal > 0xFFFF) return PROXY_PORT_INVALID;
- }
- return PROXY_VALID;
- }
-
/** @hide */
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
- public static final void setHttpProxySystemProperty(ProxyInfo p) {
+ @Deprecated
+ public static void setHttpProxySystemProperty(ProxyInfo p) {
+ setHttpProxyConfiguration(p);
+ }
+
+ /**
+ * Set HTTP proxy configuration for the process to match the provided ProxyInfo.
+ *
+ * If the provided ProxyInfo is null, the proxy configuration will be cleared.
+ * @hide
+ */
+ @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
+ public static void setHttpProxyConfiguration(@Nullable ProxyInfo p) {
String host = null;
String port = null;
String exclList = null;
@@ -256,11 +210,11 @@
exclList = ProxyUtils.exclusionListAsString(p.getExclusionList());
pacFileUrl = p.getPacFileUrl();
}
- setHttpProxySystemProperty(host, port, exclList, pacFileUrl);
+ setHttpProxyConfiguration(host, port, exclList, pacFileUrl);
}
/** @hide */
- public static final void setHttpProxySystemProperty(String host, String port, String exclList,
+ public static void setHttpProxyConfiguration(String host, String port, String exclList,
Uri pacFileUrl) {
if (exclList != null) exclList = exclList.replace(",", "|");
if (false) Log.d(TAG, "setHttpProxySystemProperty :"+host+":"+port+" - "+exclList);
diff --git a/framework/src/android/net/ProxyInfo.java b/framework/src/android/net/ProxyInfo.java
index c9bca28..229db0d 100644
--- a/framework/src/android/net/ProxyInfo.java
+++ b/framework/src/android/net/ProxyInfo.java
@@ -23,6 +23,8 @@
import android.os.Parcelable;
import android.text.TextUtils;
+import com.android.net.module.util.ProxyUtils;
+
import java.net.InetSocketAddress;
import java.net.URLConnection;
import java.util.List;
@@ -233,7 +235,7 @@
*/
public boolean isValid() {
if (!Uri.EMPTY.equals(mPacFileUrl)) return true;
- return Proxy.PROXY_VALID == Proxy.validate(mHost == null ? "" : mHost,
+ return ProxyUtils.PROXY_VALID == ProxyUtils.validate(mHost == null ? "" : mHost,
mPort == 0 ? "" : Integer.toString(mPort),
mExclusionList == null ? "" : mExclusionList);
}
@@ -275,7 +277,7 @@
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (!(o instanceof ProxyInfo)) return false;
ProxyInfo p = (ProxyInfo)o;
// If PAC URL is present in either then they must be equal.
diff --git a/framework/src/android/net/RouteInfo.java b/framework/src/android/net/RouteInfo.java
index 94f849f..5b6684a 100644
--- a/framework/src/android/net/RouteInfo.java
+++ b/framework/src/android/net/RouteInfo.java
@@ -534,7 +534,7 @@
* Compares this RouteInfo object against the specified object and indicates if they are equal.
* @return {@code true} if the objects are equal, {@code false} otherwise.
*/
- public boolean equals(Object obj) {
+ public boolean equals(@Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof RouteInfo)) return false;
@@ -570,7 +570,7 @@
}
@Override
- public boolean equals(Object o) {
+ public boolean equals(@Nullable Object o) {
if (!(o instanceof RouteKey)) {
return false;
}
diff --git a/framework/src/android/net/TestNetworkManager.java b/framework/src/android/net/TestNetworkManager.java
index 4e89414..a174a7b 100644
--- a/framework/src/android/net/TestNetworkManager.java
+++ b/framework/src/android/net/TestNetworkManager.java
@@ -41,7 +41,6 @@
/**
* Prefix for tap interfaces created by this class.
- * @hide
*/
public static final String TEST_TAP_PREFIX = "testtap";
diff --git a/framework/src/android/net/UidRange.aidl b/framework/src/android/net/UidRange.aidl
deleted file mode 100644
index f70fc8e..0000000
--- a/framework/src/android/net/UidRange.aidl
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2018 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;
-
-/**
- * An inclusive range of UIDs.
- *
- * {@hide}
- */
-parcelable UidRange;
\ No newline at end of file
diff --git a/framework/src/android/net/VpnManager.java b/framework/src/android/net/VpnManager.java
deleted file mode 100644
index c87b827..0000000
--- a/framework/src/android/net/VpnManager.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * 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;
-
-import static com.android.internal.util.Preconditions.checkNotNull;
-
-import android.annotation.IntDef;
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.app.Activity;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.res.Resources;
-import android.os.RemoteException;
-
-import com.android.internal.net.VpnProfile;
-
-import java.io.IOException;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.security.GeneralSecurityException;
-
-/**
- * This class provides an interface for apps to manage platform VPN profiles
- *
- * <p>Apps can use this API to provide profiles with which the platform can set up a VPN without
- * further app intermediation. When a VPN profile is present and the app is selected as an always-on
- * VPN, the platform will directly trigger the negotiation of the VPN without starting or waking the
- * app (unlike VpnService).
- *
- * <p>VPN apps using supported protocols should preferentially use this API over the {@link
- * VpnService} API for ease-of-development and reduced maintainance burden. This also give the user
- * the guarantee that VPN network traffic is not subjected to on-device packet interception.
- *
- * @see Ikev2VpnProfile
- */
-public class VpnManager {
- /** Type representing a lack of VPN @hide */
- public static final int TYPE_VPN_NONE = -1;
- /** VPN service type code @hide */
- public static final int TYPE_VPN_SERVICE = 1;
- /** Platform VPN type code @hide */
- public static final int TYPE_VPN_PLATFORM = 2;
-
- /** @hide */
- @IntDef(value = {TYPE_VPN_NONE, TYPE_VPN_SERVICE, TYPE_VPN_PLATFORM})
- @Retention(RetentionPolicy.SOURCE)
- public @interface VpnType {}
-
- @NonNull private final Context mContext;
- @NonNull private final IConnectivityManager mService;
-
- private static Intent getIntentForConfirmation() {
- final Intent intent = new Intent();
- final ComponentName componentName = ComponentName.unflattenFromString(
- Resources.getSystem().getString(
- com.android.internal.R.string.config_platformVpnConfirmDialogComponent));
- intent.setComponent(componentName);
- return intent;
- }
-
- /**
- * Create an instance of the VpnManager with the given context.
- *
- * <p>Internal only. Applications are expected to obtain an instance of the VpnManager via the
- * {@link Context.getSystemService()} method call.
- *
- * @hide
- */
- public VpnManager(@NonNull Context ctx, @NonNull IConnectivityManager service) {
- mContext = checkNotNull(ctx, "missing Context");
- mService = checkNotNull(service, "missing IConnectivityManager");
- }
-
- /**
- * Install a VpnProfile configuration keyed on the calling app's package name.
- *
- * <p>This method returns {@code null} if user consent has already been granted, or an {@link
- * Intent} to a system activity. If an intent is returned, the application should launch the
- * activity using {@link Activity#startActivityForResult} to request user consent. The activity
- * may pop up a dialog to require user action, and the result will come back via its {@link
- * Activity#onActivityResult}. If the result is {@link Activity#RESULT_OK}, the user has
- * consented, and the VPN profile can be started.
- *
- * @param profile the VpnProfile provided by this package. Will override any previous VpnProfile
- * stored for this package.
- * @return an Intent requesting user consent to start the VPN, or null if consent is not
- * required based on privileges or previous user consent.
- */
- @Nullable
- public Intent provisionVpnProfile(@NonNull PlatformVpnProfile profile) {
- final VpnProfile internalProfile;
-
- try {
- internalProfile = profile.toVpnProfile();
- } catch (GeneralSecurityException | IOException e) {
- // Conversion to VpnProfile failed; this is an invalid profile. Both of these exceptions
- // indicate a failure to convert a PrivateKey or X509Certificate to a Base64 encoded
- // string as required by the VpnProfile.
- throw new IllegalArgumentException("Failed to serialize PlatformVpnProfile", e);
- }
-
- try {
- // Profile can never be null; it either gets set, or an exception is thrown.
- if (mService.provisionVpnProfile(internalProfile, mContext.getOpPackageName())) {
- return null;
- }
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- return getIntentForConfirmation();
- }
-
- /**
- * Delete the VPN profile configuration that was provisioned by the calling app
- *
- * @throws SecurityException if this would violate user settings
- */
- public void deleteProvisionedVpnProfile() {
- try {
- mService.deleteVpnProfile(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Request the startup of a previously provisioned VPN.
- *
- * @throws SecurityException exception if user or device settings prevent this VPN from being
- * setup, or if user consent has not been granted
- */
- public void startProvisionedVpnProfile() {
- try {
- mService.startVpnProfile(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /** Tear down the VPN provided by the calling app (if any) */
- public void stopProvisionedVpnProfile() {
- try {
- mService.stopVpnProfile(mContext.getOpPackageName());
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-}
diff --git a/framework/src/android/net/VpnService.java b/framework/src/android/net/VpnService.java
deleted file mode 100644
index 8e90a11..0000000
--- a/framework/src/android/net/VpnService.java
+++ /dev/null
@@ -1,903 +0,0 @@
-/*
- * Copyright (C) 2011 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;
-
-import static android.system.OsConstants.AF_INET;
-import static android.system.OsConstants.AF_INET6;
-
-import android.annotation.NonNull;
-import android.annotation.Nullable;
-import android.annotation.RequiresPermission;
-import android.annotation.SystemApi;
-import android.app.Activity;
-import android.app.PendingIntent;
-import android.app.Service;
-import android.app.admin.DevicePolicyManager;
-import android.compat.annotation.UnsupportedAppUsage;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.pm.IPackageManager;
-import android.content.pm.PackageManager;
-import android.os.Binder;
-import android.os.IBinder;
-import android.os.Parcel;
-import android.os.ParcelFileDescriptor;
-import android.os.RemoteException;
-import android.os.ServiceManager;
-import android.os.UserHandle;
-
-import com.android.internal.net.VpnConfig;
-
-import java.net.DatagramSocket;
-import java.net.Inet4Address;
-import java.net.Inet6Address;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-/**
- * VpnService is a base class for applications to extend and build their
- * own VPN solutions. In general, it creates a virtual network interface,
- * configures addresses and routing rules, and returns a file descriptor
- * to the application. Each read from the descriptor retrieves an outgoing
- * packet which was routed to the interface. Each write to the descriptor
- * injects an incoming packet just like it was received from the interface.
- * The interface is running on Internet Protocol (IP), so packets are
- * always started with IP headers. The application then completes a VPN
- * connection by processing and exchanging packets with the remote server
- * over a tunnel.
- *
- * <p>Letting applications intercept packets raises huge security concerns.
- * A VPN application can easily break the network. Besides, two of them may
- * conflict with each other. The system takes several actions to address
- * these issues. Here are some key points:
- * <ul>
- * <li>User action is required the first time an application creates a VPN
- * connection.</li>
- * <li>There can be only one VPN connection running at the same time. The
- * existing interface is deactivated when a new one is created.</li>
- * <li>A system-managed notification is shown during the lifetime of a
- * VPN connection.</li>
- * <li>A system-managed dialog gives the information of the current VPN
- * connection. It also provides a button to disconnect.</li>
- * <li>The network is restored automatically when the file descriptor is
- * closed. It also covers the cases when a VPN application is crashed
- * or killed by the system.</li>
- * </ul>
- *
- * <p>There are two primary methods in this class: {@link #prepare} and
- * {@link Builder#establish}. The former deals with user action and stops
- * the VPN connection created by another application. The latter creates
- * a VPN interface using the parameters supplied to the {@link Builder}.
- * An application must call {@link #prepare} to grant the right to use
- * other methods in this class, and the right can be revoked at any time.
- * Here are the general steps to create a VPN connection:
- * <ol>
- * <li>When the user presses the button to connect, call {@link #prepare}
- * and launch the returned intent, if non-null.</li>
- * <li>When the application becomes prepared, start the service.</li>
- * <li>Create a tunnel to the remote server and negotiate the network
- * parameters for the VPN connection.</li>
- * <li>Supply those parameters to a {@link Builder} and create a VPN
- * interface by calling {@link Builder#establish}.</li>
- * <li>Process and exchange packets between the tunnel and the returned
- * file descriptor.</li>
- * <li>When {@link #onRevoke} is invoked, close the file descriptor and
- * shut down the tunnel gracefully.</li>
- * </ol>
- *
- * <p>Services extending this class need to be declared with an appropriate
- * permission and intent filter. Their access must be secured by
- * {@link android.Manifest.permission#BIND_VPN_SERVICE} permission, and
- * their intent filter must match {@link #SERVICE_INTERFACE} action. Here
- * is an example of declaring a VPN service in {@code AndroidManifest.xml}:
- * <pre>
- * <service android:name=".ExampleVpnService"
- * android:permission="android.permission.BIND_VPN_SERVICE">
- * <intent-filter>
- * <action android:name="android.net.VpnService"/>
- * </intent-filter>
- * </service></pre>
- *
- * <p> The Android system starts a VPN in the background by calling
- * {@link android.content.Context#startService startService()}. In Android 8.0
- * (API level 26) and higher, the system places VPN apps on the temporary
- * allowlist for a short period so the app can start in the background. The VPN
- * app must promote itself to the foreground after it's launched or the system
- * will shut down the app.
- *
- * <h3>Developer's guide</h3>
- *
- * <p>To learn more about developing VPN apps, read the
- * <a href="{@docRoot}guide/topics/connectivity/vpn">VPN developer's guide</a>.
- *
- * @see Builder
- */
-public class VpnService extends Service {
-
- /**
- * The action must be matched by the intent filter of this service. It also
- * needs to require {@link android.Manifest.permission#BIND_VPN_SERVICE}
- * permission so that other applications cannot abuse it.
- */
- public static final String SERVICE_INTERFACE = VpnConfig.SERVICE_INTERFACE;
-
- /**
- * Key for boolean meta-data field indicating whether this VpnService supports always-on mode.
- *
- * <p>For a VPN app targeting {@link android.os.Build.VERSION_CODES#N API 24} or above, Android
- * provides users with the ability to set it as always-on, so that VPN connection is
- * persisted after device reboot and app upgrade. Always-on VPN can also be enabled by device
- * owner and profile owner apps through
- * {@link DevicePolicyManager#setAlwaysOnVpnPackage}.
- *
- * <p>VPN apps not supporting this feature should opt out by adding this meta-data field to the
- * {@code VpnService} component of {@code AndroidManifest.xml}. In case there is more than one
- * {@code VpnService} component defined in {@code AndroidManifest.xml}, opting out any one of
- * them will opt out the entire app. For example,
- * <pre> {@code
- * <service android:name=".ExampleVpnService"
- * android:permission="android.permission.BIND_VPN_SERVICE">
- * <intent-filter>
- * <action android:name="android.net.VpnService"/>
- * </intent-filter>
- * <meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON"
- * android:value=false/>
- * </service>
- * } </pre>
- *
- * <p>This meta-data field defaults to {@code true} if absent. It will only have effect on
- * {@link android.os.Build.VERSION_CODES#O_MR1} or higher.
- */
- public static final String SERVICE_META_DATA_SUPPORTS_ALWAYS_ON =
- "android.net.VpnService.SUPPORTS_ALWAYS_ON";
-
- /**
- * Use IConnectivityManager since those methods are hidden and not
- * available in ConnectivityManager.
- */
- private static IConnectivityManager getService() {
- return IConnectivityManager.Stub.asInterface(
- ServiceManager.getService(Context.CONNECTIVITY_SERVICE));
- }
-
- /**
- * Prepare to establish a VPN connection. This method returns {@code null}
- * if the VPN application is already prepared or if the user has previously
- * consented to the VPN application. Otherwise, it returns an
- * {@link Intent} to a system activity. The application should launch the
- * activity using {@link Activity#startActivityForResult} to get itself
- * prepared. The activity may pop up a dialog to require user action, and
- * the result will come back via its {@link Activity#onActivityResult}.
- * If the result is {@link Activity#RESULT_OK}, the application becomes
- * prepared and is granted to use other methods in this class.
- *
- * <p>Only one application can be granted at the same time. The right
- * is revoked when another application is granted. The application
- * losing the right will be notified via its {@link #onRevoke}. Unless
- * it becomes prepared again, subsequent calls to other methods in this
- * class will fail.
- *
- * <p>The user may disable the VPN at any time while it is activated, in
- * which case this method will return an intent the next time it is
- * executed to obtain the user's consent again.
- *
- * @see #onRevoke
- */
- public static Intent prepare(Context context) {
- try {
- if (getService().prepareVpn(context.getPackageName(), null, context.getUserId())) {
- return null;
- }
- } catch (RemoteException e) {
- // ignore
- }
- return VpnConfig.getIntentForConfirmation();
- }
-
- /**
- * Version of {@link #prepare(Context)} which does not require user consent.
- *
- * <p>Requires {@link android.Manifest.permission#CONTROL_VPN} and should generally not be
- * used. Only acceptable in situations where user consent has been obtained through other means.
- *
- * <p>Once this is run, future preparations may be done with the standard prepare method as this
- * will authorize the package to prepare the VPN without consent in the future.
- *
- * @hide
- */
- @SystemApi
- @RequiresPermission(android.Manifest.permission.CONTROL_VPN)
- public static void prepareAndAuthorize(Context context) {
- IConnectivityManager cm = getService();
- String packageName = context.getPackageName();
- try {
- // Only prepare if we're not already prepared.
- int userId = context.getUserId();
- if (!cm.prepareVpn(packageName, null, userId)) {
- cm.prepareVpn(null, packageName, userId);
- }
- cm.setVpnPackageAuthorization(packageName, userId, VpnManager.TYPE_VPN_SERVICE);
- } catch (RemoteException e) {
- // ignore
- }
- }
-
- /**
- * Protect a socket from VPN connections. After protecting, data sent
- * through this socket will go directly to the underlying network,
- * so its traffic will not be forwarded through the VPN.
- * This method is useful if some connections need to be kept
- * outside of VPN. For example, a VPN tunnel should protect itself if its
- * destination is covered by VPN routes. Otherwise its outgoing packets
- * will be sent back to the VPN interface and cause an infinite loop. This
- * method will fail if the application is not prepared or is revoked.
- *
- * <p class="note">The socket is NOT closed by this method.
- *
- * @return {@code true} on success.
- */
- public boolean protect(int socket) {
- return NetworkUtils.protectFromVpn(socket);
- }
-
- /**
- * Convenience method to protect a {@link Socket} from VPN connections.
- *
- * @return {@code true} on success.
- * @see #protect(int)
- */
- public boolean protect(Socket socket) {
- return protect(socket.getFileDescriptor$().getInt$());
- }
-
- /**
- * Convenience method to protect a {@link DatagramSocket} from VPN
- * connections.
- *
- * @return {@code true} on success.
- * @see #protect(int)
- */
- public boolean protect(DatagramSocket socket) {
- return protect(socket.getFileDescriptor$().getInt$());
- }
-
- /**
- * Adds a network address to the VPN interface.
- *
- * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
- * address is already in use or cannot be assigned to the interface for any other reason.
- *
- * Adding an address implicitly allows traffic from that address family (i.e., IPv4 or IPv6) to
- * be routed over the VPN. @see Builder#allowFamily
- *
- * @throws IllegalArgumentException if the address is invalid.
- *
- * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
- * @param prefixLength The prefix length of the address.
- *
- * @return {@code true} on success.
- * @see Builder#addAddress
- *
- * @hide
- */
- public boolean addAddress(InetAddress address, int prefixLength) {
- check(address, prefixLength);
- try {
- return getService().addVpnAddress(address.getHostAddress(), prefixLength);
- } catch (RemoteException e) {
- throw new IllegalStateException(e);
- }
- }
-
- /**
- * Removes a network address from the VPN interface.
- *
- * Both IPv4 and IPv6 addresses are supported. The VPN must already be established. Fails if the
- * address is not assigned to the VPN interface, or if it is the only address assigned (thus
- * cannot be removed), or if the address cannot be removed for any other reason.
- *
- * After removing an address, if there are no addresses, routes or DNS servers of a particular
- * address family (i.e., IPv4 or IPv6) configured on the VPN, that <b>DOES NOT</b> block that
- * family from being routed. In other words, once an address family has been allowed, it stays
- * allowed for the rest of the VPN's session. @see Builder#allowFamily
- *
- * @throws IllegalArgumentException if the address is invalid.
- *
- * @param address The IP address (IPv4 or IPv6) to assign to the VPN interface.
- * @param prefixLength The prefix length of the address.
- *
- * @return {@code true} on success.
- *
- * @hide
- */
- public boolean removeAddress(InetAddress address, int prefixLength) {
- check(address, prefixLength);
- try {
- return getService().removeVpnAddress(address.getHostAddress(), prefixLength);
- } catch (RemoteException e) {
- throw new IllegalStateException(e);
- }
- }
-
- /**
- * Sets the underlying networks used by the VPN for its upstream connections.
- *
- * <p>Used by the system to know the actual networks that carry traffic for apps affected by
- * this VPN in order to present this information to the user (e.g., via status bar icons).
- *
- * <p>This method only needs to be called if the VPN has explicitly bound its underlying
- * communications channels — such as the socket(s) passed to {@link #protect(int)} —
- * to a {@code Network} using APIs such as {@link Network#bindSocket(Socket)} or
- * {@link Network#bindSocket(DatagramSocket)}. The VPN should call this method every time
- * the set of {@code Network}s it is using changes.
- *
- * <p>{@code networks} is one of the following:
- * <ul>
- * <li><strong>a non-empty array</strong>: an array of one or more {@link Network}s, in
- * decreasing preference order. For example, if this VPN uses both wifi and mobile (cellular)
- * networks to carry app traffic, but prefers or uses wifi more than mobile, wifi should appear
- * first in the array.</li>
- * <li><strong>an empty array</strong>: a zero-element array, meaning that the VPN has no
- * underlying network connection, and thus, app traffic will not be sent or received.</li>
- * <li><strong>null</strong>: (default) signifies that the VPN uses whatever is the system's
- * default network. I.e., it doesn't use the {@code bindSocket} or {@code bindDatagramSocket}
- * APIs mentioned above to send traffic over specific channels.</li>
- * </ul>
- *
- * <p>This call will succeed only if the VPN is currently established. For setting this value
- * when the VPN has not yet been established, see {@link Builder#setUnderlyingNetworks}.
- *
- * @param networks An array of networks the VPN uses to tunnel traffic to/from its servers.
- *
- * @return {@code true} on success.
- */
- public boolean setUnderlyingNetworks(Network[] networks) {
- try {
- return getService().setUnderlyingNetworksForVpn(networks);
- } catch (RemoteException e) {
- throw new IllegalStateException(e);
- }
- }
-
- /**
- * Returns whether the service is running in always-on VPN mode. In this mode the system ensures
- * that the service is always running by restarting it when necessary, e.g. after reboot.
- *
- * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
- */
- public final boolean isAlwaysOn() {
- try {
- return getService().isCallerCurrentAlwaysOnVpnApp();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Returns whether the service is running in always-on VPN lockdown mode. In this mode the
- * system ensures that the service is always running and that the apps aren't allowed to bypass
- * the VPN.
- *
- * @see DevicePolicyManager#setAlwaysOnVpnPackage(ComponentName, String, boolean, Set)
- */
- public final boolean isLockdownEnabled() {
- try {
- return getService().isCallerCurrentAlwaysOnVpnLockdownApp();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
- * Return the communication interface to the service. This method returns
- * {@code null} on {@link Intent}s other than {@link #SERVICE_INTERFACE}
- * action. Applications overriding this method must identify the intent
- * and return the corresponding interface accordingly.
- *
- * @see Service#onBind
- */
- @Override
- public IBinder onBind(Intent intent) {
- if (intent != null && SERVICE_INTERFACE.equals(intent.getAction())) {
- return new Callback();
- }
- return null;
- }
-
- /**
- * Invoked when the application is revoked. At this moment, the VPN
- * interface is already deactivated by the system. The application should
- * close the file descriptor and shut down gracefully. The default
- * implementation of this method is calling {@link Service#stopSelf()}.
- *
- * <p class="note">Calls to this method may not happen on the main thread
- * of the process.
- *
- * @see #prepare
- */
- public void onRevoke() {
- stopSelf();
- }
-
- /**
- * Use raw Binder instead of AIDL since now there is only one usage.
- */
- private class Callback extends Binder {
- @Override
- protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
- if (code == IBinder.LAST_CALL_TRANSACTION) {
- onRevoke();
- return true;
- }
- return false;
- }
- }
-
- /**
- * Private method to validate address and prefixLength.
- */
- private static void check(InetAddress address, int prefixLength) {
- if (address.isLoopbackAddress()) {
- throw new IllegalArgumentException("Bad address");
- }
- if (address instanceof Inet4Address) {
- if (prefixLength < 0 || prefixLength > 32) {
- throw new IllegalArgumentException("Bad prefixLength");
- }
- } else if (address instanceof Inet6Address) {
- if (prefixLength < 0 || prefixLength > 128) {
- throw new IllegalArgumentException("Bad prefixLength");
- }
- } else {
- throw new IllegalArgumentException("Unsupported family");
- }
- }
-
- /**
- * Helper class to create a VPN interface. This class should be always
- * used within the scope of the outer {@link VpnService}.
- *
- * @see VpnService
- */
- public class Builder {
-
- private final VpnConfig mConfig = new VpnConfig();
- @UnsupportedAppUsage
- private final List<LinkAddress> mAddresses = new ArrayList<LinkAddress>();
- @UnsupportedAppUsage
- private final List<RouteInfo> mRoutes = new ArrayList<RouteInfo>();
-
- public Builder() {
- mConfig.user = VpnService.this.getClass().getName();
- }
-
- /**
- * Set the name of this session. It will be displayed in
- * system-managed dialogs and notifications. This is recommended
- * not required.
- */
- @NonNull
- public Builder setSession(@NonNull String session) {
- mConfig.session = session;
- return this;
- }
-
- /**
- * Set the {@link PendingIntent} to an activity for users to
- * configure the VPN connection. If it is not set, the button
- * to configure will not be shown in system-managed dialogs.
- */
- @NonNull
- public Builder setConfigureIntent(@NonNull PendingIntent intent) {
- mConfig.configureIntent = intent;
- return this;
- }
-
- /**
- * Set the maximum transmission unit (MTU) of the VPN interface. If
- * it is not set, the default value in the operating system will be
- * used.
- *
- * @throws IllegalArgumentException if the value is not positive.
- */
- @NonNull
- public Builder setMtu(int mtu) {
- if (mtu <= 0) {
- throw new IllegalArgumentException("Bad mtu");
- }
- mConfig.mtu = mtu;
- return this;
- }
-
- /**
- * Sets an HTTP proxy for the VPN network. This proxy is only a recommendation
- * and it is possible that some apps will ignore it.
- */
- @NonNull
- public Builder setHttpProxy(@NonNull ProxyInfo proxyInfo) {
- mConfig.proxyInfo = proxyInfo;
- return this;
- }
-
- /**
- * Add a network address to the VPN interface. Both IPv4 and IPv6
- * addresses are supported. At least one address must be set before
- * calling {@link #establish}.
- *
- * Adding an address implicitly allows traffic from that address family
- * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
- *
- * @throws IllegalArgumentException if the address is invalid.
- */
- @NonNull
- public Builder addAddress(@NonNull InetAddress address, int prefixLength) {
- check(address, prefixLength);
-
- if (address.isAnyLocalAddress()) {
- throw new IllegalArgumentException("Bad address");
- }
- mAddresses.add(new LinkAddress(address, prefixLength));
- mConfig.updateAllowedFamilies(address);
- return this;
- }
-
- /**
- * Convenience method to add a network address to the VPN interface
- * using a numeric address string. See {@link InetAddress} for the
- * definitions of numeric address formats.
- *
- * Adding an address implicitly allows traffic from that address family
- * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
- *
- * @throws IllegalArgumentException if the address is invalid.
- * @see #addAddress(InetAddress, int)
- */
- @NonNull
- public Builder addAddress(@NonNull String address, int prefixLength) {
- return addAddress(InetAddress.parseNumericAddress(address), prefixLength);
- }
-
- /**
- * Add a network route to the VPN interface. Both IPv4 and IPv6
- * routes are supported.
- *
- * Adding a route implicitly allows traffic from that address family
- * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
- *
- * @throws IllegalArgumentException if the route is invalid.
- */
- @NonNull
- public Builder addRoute(@NonNull InetAddress address, int prefixLength) {
- check(address, prefixLength);
-
- int offset = prefixLength / 8;
- byte[] bytes = address.getAddress();
- if (offset < bytes.length) {
- for (bytes[offset] <<= prefixLength % 8; offset < bytes.length; ++offset) {
- if (bytes[offset] != 0) {
- throw new IllegalArgumentException("Bad address");
- }
- }
- }
- mRoutes.add(new RouteInfo(new IpPrefix(address, prefixLength), null));
- mConfig.updateAllowedFamilies(address);
- return this;
- }
-
- /**
- * Convenience method to add a network route to the VPN interface
- * using a numeric address string. See {@link InetAddress} for the
- * definitions of numeric address formats.
- *
- * Adding a route implicitly allows traffic from that address family
- * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
- *
- * @throws IllegalArgumentException if the route is invalid.
- * @see #addRoute(InetAddress, int)
- */
- @NonNull
- public Builder addRoute(@NonNull String address, int prefixLength) {
- return addRoute(InetAddress.parseNumericAddress(address), prefixLength);
- }
-
- /**
- * Add a DNS server to the VPN connection. Both IPv4 and IPv6
- * addresses are supported. If none is set, the DNS servers of
- * the default network will be used.
- *
- * Adding a server implicitly allows traffic from that address family
- * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
- *
- * @throws IllegalArgumentException if the address is invalid.
- */
- @NonNull
- public Builder addDnsServer(@NonNull InetAddress address) {
- if (address.isLoopbackAddress() || address.isAnyLocalAddress()) {
- throw new IllegalArgumentException("Bad address");
- }
- if (mConfig.dnsServers == null) {
- mConfig.dnsServers = new ArrayList<String>();
- }
- mConfig.dnsServers.add(address.getHostAddress());
- return this;
- }
-
- /**
- * Convenience method to add a DNS server to the VPN connection
- * using a numeric address string. See {@link InetAddress} for the
- * definitions of numeric address formats.
- *
- * Adding a server implicitly allows traffic from that address family
- * (i.e., IPv4 or IPv6) to be routed over the VPN. @see #allowFamily
- *
- * @throws IllegalArgumentException if the address is invalid.
- * @see #addDnsServer(InetAddress)
- */
- @NonNull
- public Builder addDnsServer(@NonNull String address) {
- return addDnsServer(InetAddress.parseNumericAddress(address));
- }
-
- /**
- * Add a search domain to the DNS resolver.
- */
- @NonNull
- public Builder addSearchDomain(@NonNull String domain) {
- if (mConfig.searchDomains == null) {
- mConfig.searchDomains = new ArrayList<String>();
- }
- mConfig.searchDomains.add(domain);
- return this;
- }
-
- /**
- * Allows traffic from the specified address family.
- *
- * By default, if no address, route or DNS server of a specific family (IPv4 or IPv6) is
- * added to this VPN, then all outgoing traffic of that family is blocked. If any address,
- * route or DNS server is added, that family is allowed.
- *
- * This method allows an address family to be unblocked even without adding an address,
- * route or DNS server of that family. Traffic of that family will then typically
- * fall-through to the underlying network if it's supported.
- *
- * {@code family} must be either {@code AF_INET} (for IPv4) or {@code AF_INET6} (for IPv6).
- * {@link IllegalArgumentException} is thrown if it's neither.
- *
- * @param family The address family ({@code AF_INET} or {@code AF_INET6}) to allow.
- *
- * @return this {@link Builder} object to facilitate chaining of method calls.
- */
- @NonNull
- public Builder allowFamily(int family) {
- if (family == AF_INET) {
- mConfig.allowIPv4 = true;
- } else if (family == AF_INET6) {
- mConfig.allowIPv6 = true;
- } else {
- throw new IllegalArgumentException(family + " is neither " + AF_INET + " nor " +
- AF_INET6);
- }
- return this;
- }
-
- private void verifyApp(String packageName) throws PackageManager.NameNotFoundException {
- IPackageManager pm = IPackageManager.Stub.asInterface(
- ServiceManager.getService("package"));
- try {
- pm.getApplicationInfo(packageName, 0, UserHandle.getCallingUserId());
- } catch (RemoteException e) {
- throw new IllegalStateException(e);
- }
- }
-
- /**
- * Adds an application that's allowed to access the VPN connection.
- *
- * If this method is called at least once, only applications added through this method (and
- * no others) are allowed access. Else (if this method is never called), all applications
- * are allowed by default. If some applications are added, other, un-added applications
- * will use networking as if the VPN wasn't running.
- *
- * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
- * ones, but not both. Calling this method after {@link #addDisallowedApplication} has
- * already been called, or vice versa, will throw an {@link UnsupportedOperationException}.
- *
- * {@code packageName} must be the canonical name of a currently installed application.
- * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
- *
- * @throws PackageManager.NameNotFoundException If the application isn't installed.
- *
- * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
- *
- * @return this {@link Builder} object to facilitate chaining method calls.
- */
- @NonNull
- public Builder addAllowedApplication(@NonNull String packageName)
- throws PackageManager.NameNotFoundException {
- if (mConfig.disallowedApplications != null) {
- throw new UnsupportedOperationException("addDisallowedApplication already called");
- }
- verifyApp(packageName);
- if (mConfig.allowedApplications == null) {
- mConfig.allowedApplications = new ArrayList<String>();
- }
- mConfig.allowedApplications.add(packageName);
- return this;
- }
-
- /**
- * Adds an application that's denied access to the VPN connection.
- *
- * By default, all applications are allowed access, except for those denied through this
- * method. Denied applications will use networking as if the VPN wasn't running.
- *
- * A {@link Builder} may have only a set of allowed applications OR a set of disallowed
- * ones, but not both. Calling this method after {@link #addAllowedApplication} has already
- * been called, or vice versa, will throw an {@link UnsupportedOperationException}.
- *
- * {@code packageName} must be the canonical name of a currently installed application.
- * {@link PackageManager.NameNotFoundException} is thrown if there's no such application.
- *
- * @throws PackageManager.NameNotFoundException If the application isn't installed.
- *
- * @param packageName The full name (e.g.: "com.google.apps.contacts") of an application.
- *
- * @return this {@link Builder} object to facilitate chaining method calls.
- */
- @NonNull
- public Builder addDisallowedApplication(@NonNull String packageName)
- throws PackageManager.NameNotFoundException {
- if (mConfig.allowedApplications != null) {
- throw new UnsupportedOperationException("addAllowedApplication already called");
- }
- verifyApp(packageName);
- if (mConfig.disallowedApplications == null) {
- mConfig.disallowedApplications = new ArrayList<String>();
- }
- mConfig.disallowedApplications.add(packageName);
- return this;
- }
-
- /**
- * Allows all apps to bypass this VPN connection.
- *
- * By default, all traffic from apps is forwarded through the VPN interface and it is not
- * possible for apps to side-step the VPN. If this method is called, apps may use methods
- * such as {@link ConnectivityManager#bindProcessToNetwork} to instead send/receive
- * directly over the underlying network or any other network they have permissions for.
- *
- * @return this {@link Builder} object to facilitate chaining of method calls.
- */
- @NonNull
- public Builder allowBypass() {
- mConfig.allowBypass = true;
- return this;
- }
-
- /**
- * Sets the VPN interface's file descriptor to be in blocking/non-blocking mode.
- *
- * By default, the file descriptor returned by {@link #establish} is non-blocking.
- *
- * @param blocking True to put the descriptor into blocking mode; false for non-blocking.
- *
- * @return this {@link Builder} object to facilitate chaining method calls.
- */
- @NonNull
- public Builder setBlocking(boolean blocking) {
- mConfig.blocking = blocking;
- return this;
- }
-
- /**
- * Sets the underlying networks used by the VPN for its upstream connections.
- *
- * @see VpnService#setUnderlyingNetworks
- *
- * @param networks An array of networks the VPN uses to tunnel traffic to/from its servers.
- *
- * @return this {@link Builder} object to facilitate chaining method calls.
- */
- @NonNull
- public Builder setUnderlyingNetworks(@Nullable Network[] networks) {
- mConfig.underlyingNetworks = networks != null ? networks.clone() : null;
- return this;
- }
-
- /**
- * Marks the VPN network as metered. A VPN network is classified as metered when the user is
- * sensitive to heavy data usage due to monetary costs and/or data limitations. In such
- * cases, you should set this to {@code true} so that apps on the system can avoid doing
- * large data transfers. Otherwise, set this to {@code false}. Doing so would cause VPN
- * network to inherit its meteredness from its underlying networks.
- *
- * <p>VPN apps targeting {@link android.os.Build.VERSION_CODES#Q} or above will be
- * considered metered by default.
- *
- * @param isMetered {@code true} if VPN network should be treated as metered regardless of
- * underlying network meteredness
- * @return this {@link Builder} object to facilitate chaining method calls
- * @see #setUnderlyingNetworks(Network[])
- * @see ConnectivityManager#isActiveNetworkMetered()
- */
- @NonNull
- public Builder setMetered(boolean isMetered) {
- mConfig.isMetered = isMetered;
- return this;
- }
-
- /**
- * Create a VPN interface using the parameters supplied to this
- * builder. The interface works on IP packets, and a file descriptor
- * is returned for the application to access them. Each read
- * retrieves an outgoing packet which was routed to the interface.
- * Each write injects an incoming packet just like it was received
- * from the interface. The file descriptor is put into non-blocking
- * mode by default to avoid blocking Java threads. To use the file
- * descriptor completely in native space, see
- * {@link ParcelFileDescriptor#detachFd()}. The application MUST
- * close the file descriptor when the VPN connection is terminated.
- * The VPN interface will be removed and the network will be
- * restored by the system automatically.
- *
- * <p>To avoid conflicts, there can be only one active VPN interface
- * at the same time. Usually network parameters are never changed
- * during the lifetime of a VPN connection. It is also common for an
- * application to create a new file descriptor after closing the
- * previous one. However, it is rare but not impossible to have two
- * interfaces while performing a seamless handover. In this case, the
- * old interface will be deactivated when the new one is created
- * successfully. Both file descriptors are valid but now outgoing
- * packets will be routed to the new interface. Therefore, after
- * draining the old file descriptor, the application MUST close it
- * and start using the new file descriptor. If the new interface
- * cannot be created, the existing interface and its file descriptor
- * remain untouched.
- *
- * <p>An exception will be thrown if the interface cannot be created
- * for any reason. However, this method returns {@code null} if the
- * application is not prepared or is revoked. This helps solve
- * possible race conditions between other VPN applications.
- *
- * @return {@link ParcelFileDescriptor} of the VPN interface, or
- * {@code null} if the application is not prepared.
- * @throws IllegalArgumentException if a parameter is not accepted
- * by the operating system.
- * @throws IllegalStateException if a parameter cannot be applied
- * by the operating system.
- * @throws SecurityException if the service is not properly declared
- * in {@code AndroidManifest.xml}.
- * @see VpnService
- */
- @Nullable
- public ParcelFileDescriptor establish() {
- mConfig.addresses = mAddresses;
- mConfig.routes = mRoutes;
-
- try {
- return getService().establishVpn(mConfig);
- } catch (RemoteException e) {
- throw new IllegalStateException(e);
- }
- }
- }
-}
diff --git a/framework/src/android/net/VpnTransportInfo.java b/framework/src/android/net/VpnTransportInfo.java
new file mode 100644
index 0000000..0242ba0
--- /dev/null
+++ b/framework/src/android/net/VpnTransportInfo.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2017 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;
+
+import static android.annotation.SystemApi.Client.MODULE_LIBRARIES;
+
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.SparseArray;
+
+import com.android.internal.util.MessageUtils;
+
+import java.util.Objects;
+
+/**
+ * Container for VPN-specific transport information.
+ *
+ * @see android.net.TransportInfo
+ * @see NetworkCapabilities#getTransportInfo()
+ *
+ * @hide
+ */
+@SystemApi(client = MODULE_LIBRARIES)
+public final class VpnTransportInfo implements TransportInfo, Parcelable {
+ private static final SparseArray<String> sTypeToString =
+ MessageUtils.findMessageNames(new Class[]{VpnManager.class}, new String[]{"TYPE_VPN_"});
+
+ /** Type of this VPN. */
+ @VpnManager.VpnType public final int type;
+
+ public VpnTransportInfo(@VpnManager.VpnType int type) {
+ this.type = type;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof VpnTransportInfo)) return false;
+
+ VpnTransportInfo that = (VpnTransportInfo) o;
+ return this.type == that.type;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(type);
+ }
+
+ @Override
+ public String toString() {
+ final String typeString = sTypeToString.get(type, "VPN_TYPE_???");
+ return String.format("VpnTransportInfo{%s}", typeString);
+ }
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(@NonNull Parcel dest, int flags) {
+ dest.writeInt(type);
+ }
+
+ public static final @NonNull Creator<VpnTransportInfo> CREATOR =
+ new Creator<VpnTransportInfo>() {
+ public VpnTransportInfo createFromParcel(Parcel in) {
+ return new VpnTransportInfo(in.readInt());
+ }
+ public VpnTransportInfo[] newArray(int size) {
+ return new VpnTransportInfo[size];
+ }
+ };
+}
diff --git a/service/Android.bp b/service/Android.bp
index c8f3bd3..f20b89f 100644
--- a/service/Android.bp
+++ b/service/Android.bp
@@ -14,6 +14,15 @@
// limitations under the License.
//
+package {
+ // See: http://go/android-license-faq
+ // A large-scale-change added 'default_applicable_licenses' to import
+ // all of the 'license_kinds' from "frameworks_base_license"
+ // to get the below license kinds:
+ // SPDX-license-identifier-Apache-2.0
+ default_applicable_licenses: ["frameworks_base_license"],
+}
+
cc_library_shared {
name: "libservice-connectivity",
// TODO: build against the NDK (sdk_version: "30" for example)
@@ -25,7 +34,6 @@
],
srcs: [
"jni/com_android_server_TestNetworkService.cpp",
- "jni/com_android_server_connectivity_Vpn.cpp",
"jni/onload.cpp",
],
shared_libs: [
@@ -57,6 +65,7 @@
static_libs: [
"net-utils-device-common",
"net-utils-framework-common",
+ "netd-client",
],
apex_available: [
"//apex_available:platform",
diff --git a/service/jni/com_android_server_connectivity_Vpn.cpp b/service/jni/com_android_server_connectivity_Vpn.cpp
deleted file mode 100644
index ea5e718..0000000
--- a/service/jni/com_android_server_connectivity_Vpn.cpp
+++ /dev/null
@@ -1,377 +0,0 @@
-/*
- * Copyright (C) 2011 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.
- */
-
-#define LOG_NDEBUG 0
-
-#define LOG_TAG "VpnJni"
-
-#include <arpa/inet.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <linux/if.h>
-#include <linux/if_tun.h>
-#include <linux/route.h>
-#include <linux/ipv6_route.h>
-#include <netinet/in.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/ioctl.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-
-#include <log/log.h>
-#include <android/log.h>
-
-#include "netutils/ifc.h"
-
-#include "jni.h"
-#include <nativehelper/JNIHelp.h>
-
-namespace android
-{
-
-static int inet4 = -1;
-static int inet6 = -1;
-
-static inline in_addr_t *as_in_addr(sockaddr *sa) {
- return &((sockaddr_in *)sa)->sin_addr.s_addr;
-}
-
-//------------------------------------------------------------------------------
-
-#define SYSTEM_ERROR (-1)
-#define BAD_ARGUMENT (-2)
-
-static int create_interface(int mtu)
-{
- int tun = open("/dev/tun", O_RDWR | O_NONBLOCK | O_CLOEXEC);
-
- ifreq ifr4;
- memset(&ifr4, 0, sizeof(ifr4));
-
- // Allocate interface.
- ifr4.ifr_flags = IFF_TUN | IFF_NO_PI;
- if (ioctl(tun, TUNSETIFF, &ifr4)) {
- ALOGE("Cannot allocate TUN: %s", strerror(errno));
- goto error;
- }
-
- // Activate interface.
- ifr4.ifr_flags = IFF_UP;
- if (ioctl(inet4, SIOCSIFFLAGS, &ifr4)) {
- ALOGE("Cannot activate %s: %s", ifr4.ifr_name, strerror(errno));
- goto error;
- }
-
- // Set MTU if it is specified.
- ifr4.ifr_mtu = mtu;
- if (mtu > 0 && ioctl(inet4, SIOCSIFMTU, &ifr4)) {
- ALOGE("Cannot set MTU on %s: %s", ifr4.ifr_name, strerror(errno));
- goto error;
- }
-
- return tun;
-
-error:
- close(tun);
- return SYSTEM_ERROR;
-}
-
-static int get_interface_name(char *name, int tun)
-{
- ifreq ifr4;
- if (ioctl(tun, TUNGETIFF, &ifr4)) {
- ALOGE("Cannot get interface name: %s", strerror(errno));
- return SYSTEM_ERROR;
- }
- strncpy(name, ifr4.ifr_name, IFNAMSIZ);
- return 0;
-}
-
-static int get_interface_index(const char *name)
-{
- ifreq ifr4;
- strncpy(ifr4.ifr_name, name, IFNAMSIZ);
- if (ioctl(inet4, SIOGIFINDEX, &ifr4)) {
- ALOGE("Cannot get index of %s: %s", name, strerror(errno));
- return SYSTEM_ERROR;
- }
- return ifr4.ifr_ifindex;
-}
-
-static int set_addresses(const char *name, const char *addresses)
-{
- int index = get_interface_index(name);
- if (index < 0) {
- return index;
- }
-
- ifreq ifr4;
- memset(&ifr4, 0, sizeof(ifr4));
- strncpy(ifr4.ifr_name, name, IFNAMSIZ);
- ifr4.ifr_addr.sa_family = AF_INET;
- ifr4.ifr_netmask.sa_family = AF_INET;
-
- in6_ifreq ifr6;
- memset(&ifr6, 0, sizeof(ifr6));
- ifr6.ifr6_ifindex = index;
-
- char address[65];
- int prefix;
- int chars;
- int count = 0;
-
- while (sscanf(addresses, " %64[^/]/%d %n", address, &prefix, &chars) == 2) {
- addresses += chars;
-
- if (strchr(address, ':')) {
- // Add an IPv6 address.
- if (inet_pton(AF_INET6, address, &ifr6.ifr6_addr) != 1 ||
- prefix < 0 || prefix > 128) {
- count = BAD_ARGUMENT;
- break;
- }
-
- ifr6.ifr6_prefixlen = prefix;
- if (ioctl(inet6, SIOCSIFADDR, &ifr6)) {
- count = (errno == EINVAL) ? BAD_ARGUMENT : SYSTEM_ERROR;
- break;
- }
- } else {
- // Add an IPv4 address.
- if (inet_pton(AF_INET, address, as_in_addr(&ifr4.ifr_addr)) != 1 ||
- prefix < 0 || prefix > 32) {
- count = BAD_ARGUMENT;
- break;
- }
-
- if (count) {
- snprintf(ifr4.ifr_name, sizeof(ifr4.ifr_name), "%s:%d", name, count);
- }
- if (ioctl(inet4, SIOCSIFADDR, &ifr4)) {
- count = (errno == EINVAL) ? BAD_ARGUMENT : SYSTEM_ERROR;
- break;
- }
-
- in_addr_t mask = prefix ? (~0 << (32 - prefix)) : 0;
- *as_in_addr(&ifr4.ifr_netmask) = htonl(mask);
- if (ioctl(inet4, SIOCSIFNETMASK, &ifr4)) {
- count = (errno == EINVAL) ? BAD_ARGUMENT : SYSTEM_ERROR;
- break;
- }
- }
- ALOGD("Address added on %s: %s/%d", name, address, prefix);
- ++count;
- }
-
- if (count == BAD_ARGUMENT) {
- ALOGE("Invalid address: %s/%d", address, prefix);
- } else if (count == SYSTEM_ERROR) {
- ALOGE("Cannot add address: %s/%d: %s", address, prefix, strerror(errno));
- } else if (*addresses) {
- ALOGE("Invalid address: %s", addresses);
- count = BAD_ARGUMENT;
- }
-
- return count;
-}
-
-static int reset_interface(const char *name)
-{
- ifreq ifr4;
- strncpy(ifr4.ifr_name, name, IFNAMSIZ);
- ifr4.ifr_flags = 0;
-
- if (ioctl(inet4, SIOCSIFFLAGS, &ifr4) && errno != ENODEV) {
- ALOGE("Cannot reset %s: %s", name, strerror(errno));
- return SYSTEM_ERROR;
- }
- return 0;
-}
-
-static int check_interface(const char *name)
-{
- ifreq ifr4;
- strncpy(ifr4.ifr_name, name, IFNAMSIZ);
- ifr4.ifr_flags = 0;
-
- if (ioctl(inet4, SIOCGIFFLAGS, &ifr4) && errno != ENODEV) {
- ALOGE("Cannot check %s: %s", name, strerror(errno));
- }
- return ifr4.ifr_flags;
-}
-
-static bool modifyAddress(JNIEnv *env, jobject thiz, jstring jName, jstring jAddress,
- jint jPrefixLength, bool add)
-{
- int error = SYSTEM_ERROR;
- const char *name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
- const char *address = jAddress ? env->GetStringUTFChars(jAddress, NULL) : NULL;
-
- if (!name) {
- jniThrowNullPointerException(env, "name");
- } else if (!address) {
- jniThrowNullPointerException(env, "address");
- } else {
- if (add) {
- if ((error = ifc_add_address(name, address, jPrefixLength)) != 0) {
- ALOGE("Cannot add address %s/%d on interface %s (%s)", address, jPrefixLength, name,
- strerror(-error));
- }
- } else {
- if ((error = ifc_del_address(name, address, jPrefixLength)) != 0) {
- ALOGE("Cannot del address %s/%d on interface %s (%s)", address, jPrefixLength, name,
- strerror(-error));
- }
- }
- }
-
- if (name) {
- env->ReleaseStringUTFChars(jName, name);
- }
- if (address) {
- env->ReleaseStringUTFChars(jAddress, address);
- }
- return !error;
-}
-
-//------------------------------------------------------------------------------
-
-static void throwException(JNIEnv *env, int error, const char *message)
-{
- if (error == SYSTEM_ERROR) {
- jniThrowException(env, "java/lang/IllegalStateException", message);
- } else {
- jniThrowException(env, "java/lang/IllegalArgumentException", message);
- }
-}
-
-static jint create(JNIEnv *env, jobject /* thiz */, jint mtu)
-{
- int tun = create_interface(mtu);
- if (tun < 0) {
- throwException(env, tun, "Cannot create interface");
- return -1;
- }
- return tun;
-}
-
-static jstring getName(JNIEnv *env, jobject /* thiz */, jint tun)
-{
- char name[IFNAMSIZ];
- if (get_interface_name(name, tun) < 0) {
- throwException(env, SYSTEM_ERROR, "Cannot get interface name");
- return NULL;
- }
- return env->NewStringUTF(name);
-}
-
-static jint setAddresses(JNIEnv *env, jobject /* thiz */, jstring jName,
- jstring jAddresses)
-{
- const char *name = NULL;
- const char *addresses = NULL;
- int count = -1;
-
- name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
- if (!name) {
- jniThrowNullPointerException(env, "name");
- goto error;
- }
- addresses = jAddresses ? env->GetStringUTFChars(jAddresses, NULL) : NULL;
- if (!addresses) {
- jniThrowNullPointerException(env, "addresses");
- goto error;
- }
- count = set_addresses(name, addresses);
- if (count < 0) {
- throwException(env, count, "Cannot set address");
- count = -1;
- }
-
-error:
- if (name) {
- env->ReleaseStringUTFChars(jName, name);
- }
- if (addresses) {
- env->ReleaseStringUTFChars(jAddresses, addresses);
- }
- return count;
-}
-
-static void reset(JNIEnv *env, jobject /* thiz */, jstring jName)
-{
- const char *name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
- if (!name) {
- jniThrowNullPointerException(env, "name");
- return;
- }
- if (reset_interface(name) < 0) {
- throwException(env, SYSTEM_ERROR, "Cannot reset interface");
- }
- env->ReleaseStringUTFChars(jName, name);
-}
-
-static jint check(JNIEnv *env, jobject /* thiz */, jstring jName)
-{
- const char *name = jName ? env->GetStringUTFChars(jName, NULL) : NULL;
- if (!name) {
- jniThrowNullPointerException(env, "name");
- return 0;
- }
- int flags = check_interface(name);
- env->ReleaseStringUTFChars(jName, name);
- return flags;
-}
-
-static bool addAddress(JNIEnv *env, jobject thiz, jstring jName, jstring jAddress,
- jint jPrefixLength)
-{
- return modifyAddress(env, thiz, jName, jAddress, jPrefixLength, true);
-}
-
-static bool delAddress(JNIEnv *env, jobject thiz, jstring jName, jstring jAddress,
- jint jPrefixLength)
-{
- return modifyAddress(env, thiz, jName, jAddress, jPrefixLength, false);
-}
-
-//------------------------------------------------------------------------------
-
-static const JNINativeMethod gMethods[] = {
- {"jniCreate", "(I)I", (void *)create},
- {"jniGetName", "(I)Ljava/lang/String;", (void *)getName},
- {"jniSetAddresses", "(Ljava/lang/String;Ljava/lang/String;)I", (void *)setAddresses},
- {"jniReset", "(Ljava/lang/String;)V", (void *)reset},
- {"jniCheck", "(Ljava/lang/String;)I", (void *)check},
- {"jniAddAddress", "(Ljava/lang/String;Ljava/lang/String;I)Z", (void *)addAddress},
- {"jniDelAddress", "(Ljava/lang/String;Ljava/lang/String;I)Z", (void *)delAddress},
-};
-
-int register_android_server_connectivity_Vpn(JNIEnv *env)
-{
- if (inet4 == -1) {
- inet4 = socket(AF_INET, SOCK_DGRAM, 0);
- }
- if (inet6 == -1) {
- inet6 = socket(AF_INET6, SOCK_DGRAM, 0);
- }
- return jniRegisterNativeMethods(env, "com/android/server/connectivity/Vpn",
- gMethods, NELEM(gMethods));
-}
-
-};
diff --git a/service/jni/onload.cpp b/service/jni/onload.cpp
index 3afcb0e..0012879 100644
--- a/service/jni/onload.cpp
+++ b/service/jni/onload.cpp
@@ -19,7 +19,6 @@
namespace android {
-int register_android_server_connectivity_Vpn(JNIEnv* env);
int register_android_server_TestNetworkService(JNIEnv* env);
extern "C" jint JNI_OnLoad(JavaVM* vm, void*) {
@@ -29,12 +28,11 @@
return JNI_ERR;
}
- if (register_android_server_connectivity_Vpn(env) < 0
- || register_android_server_TestNetworkService(env) < 0) {
+ if (register_android_server_TestNetworkService(env) < 0) {
return JNI_ERR;
}
return JNI_VERSION_1_6;
}
-};
\ No newline at end of file
+};