Merge "Support for Venue URL and friendly name from Network agent"
diff --git a/core/java/android/net/ConnectivityDiagnosticsManager.java b/core/java/android/net/ConnectivityDiagnosticsManager.java
index 704f31d..5234494 100644
--- a/core/java/android/net/ConnectivityDiagnosticsManager.java
+++ b/core/java/android/net/ConnectivityDiagnosticsManager.java
@@ -623,32 +623,41 @@
/** @hide */
@VisibleForTesting
public void onConnectivityReportAvailable(@NonNull ConnectivityReport report) {
- Binder.withCleanCallingIdentity(() -> {
+ final long token = Binder.clearCallingIdentity();
+ try {
mExecutor.execute(() -> {
mCb.onConnectivityReportAvailable(report);
});
- });
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
}
/** @hide */
@VisibleForTesting
public void onDataStallSuspected(@NonNull DataStallReport report) {
- Binder.withCleanCallingIdentity(() -> {
+ final long token = Binder.clearCallingIdentity();
+ try {
mExecutor.execute(() -> {
mCb.onDataStallSuspected(report);
});
- });
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
}
/** @hide */
@VisibleForTesting
public void onNetworkConnectivityReported(
@NonNull Network network, boolean hasConnectivity) {
- Binder.withCleanCallingIdentity(() -> {
+ final long token = Binder.clearCallingIdentity();
+ try {
mExecutor.execute(() -> {
mCb.onNetworkConnectivityReported(network, hasConnectivity);
});
- });
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
}
}
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index 540ea5c..06c1598 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -59,8 +59,10 @@
import android.telephony.TelephonyManager;
import android.util.ArrayMap;
import android.util.Log;
+import android.util.Range;
import android.util.SparseIntArray;
+import com.android.connectivity.aidl.INetworkAgent;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.util.Preconditions;
import com.android.internal.util.Protocol;
@@ -72,10 +74,12 @@
import java.io.UncheckedIOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
+import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -1162,6 +1166,55 @@
}
/**
+ * 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
+ * have any connectivity except if a VPN is connected and applies to the UIDs, or if the UIDs
+ * otherwise have permission to bypass the VPN (e.g., because they have the
+ * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission, or when
+ * using a socket protected by a method such as {@link VpnService#protect(DatagramSocket)}. If
+ * set to {@code false}, a previously-added restriction is removed.
+ * <p>
+ * Each of the UID ranges specified by this method is added and removed as is, and no processing
+ * is performed on the ranges to de-duplicate, merge, split, or intersect them. In order to
+ * remove a previously-added range, the exact range must be removed as is.
+ * <p>
+ * The changes are applied asynchronously and may not have been applied by the time the method
+ * returns. Apps will be notified about any changes that apply to them via
+ * {@link NetworkCallback#onBlockedStatusChanged} callbacks called after the changes take
+ * effect.
+ * <p>
+ * This method should be called only by the VPN code.
+ *
+ * @param ranges the UID ranges to restrict
+ * @param requireVpn whether the specified UID ranges must use a VPN
+ *
+ * TODO: expose as @SystemApi.
+ * @hide
+ */
+ @RequiresPermission(anyOf = {
+ NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
+ android.Manifest.permission.NETWORK_STACK})
+ public void setRequireVpnForUids(boolean requireVpn,
+ @NonNull Collection<Range<Integer>> ranges) {
+ Objects.requireNonNull(ranges);
+ // The Range class is not parcelable. Convert to UidRange, which is what is used internally.
+ // This method is not necessarily expected to be used outside the system server, so
+ // parceling may not be necessary, but it could be used out-of-process, e.g., by the network
+ // stack process, or by tests.
+ UidRange[] rangesArray = new UidRange[ranges.size()];
+ int index = 0;
+ for (Range<Integer> range : ranges) {
+ rangesArray[index++] = new UidRange(range.getLower(), range.getUpper());
+ }
+ try {
+ mService.setRequireVpnForUids(requireVpn, rangesArray);
+ } 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.
@@ -1832,30 +1885,42 @@
mCallback = new ISocketKeepaliveCallback.Stub() {
@Override
public void onStarted(int slot) {
- Binder.withCleanCallingIdentity(() ->
- mExecutor.execute(() -> {
- mSlot = slot;
- callback.onStarted();
- }));
+ final long token = Binder.clearCallingIdentity();
+ try {
+ mExecutor.execute(() -> {
+ mSlot = slot;
+ callback.onStarted();
+ });
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
}
@Override
public void onStopped() {
- Binder.withCleanCallingIdentity(() ->
- mExecutor.execute(() -> {
- mSlot = null;
- callback.onStopped();
- }));
+ final long token = Binder.clearCallingIdentity();
+ try {
+ mExecutor.execute(() -> {
+ mSlot = null;
+ callback.onStopped();
+ });
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
mExecutor.shutdown();
}
@Override
public void onError(int error) {
- Binder.withCleanCallingIdentity(() ->
- mExecutor.execute(() -> {
- mSlot = null;
- callback.onError(error);
- }));
+ final long token = Binder.clearCallingIdentity();
+ try {
+ mExecutor.execute(() -> {
+ mSlot = null;
+ callback.onError(error);
+ });
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
mExecutor.shutdown();
}
@@ -3119,39 +3184,6 @@
}
/**
- * Check mobile provisioning.
- *
- * @param suggestedTimeOutMs, timeout in milliseconds
- *
- * @return time out that will be used, maybe less that suggestedTimeOutMs
- * -1 if an error.
- *
- * {@hide}
- */
- public int checkMobileProvisioning(int suggestedTimeOutMs) {
- int timeOutMs = -1;
- try {
- timeOutMs = mService.checkMobileProvisioning(suggestedTimeOutMs);
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- return timeOutMs;
- }
-
- /**
- * Get the mobile provisioning url.
- * {@hide}
- */
- @RequiresPermission(android.Manifest.permission.NETWORK_SETTINGS)
- public String getMobileProvisioningUrl() {
- try {
- return mService.getMobileProvisioningUrl();
- } catch (RemoteException e) {
- throw e.rethrowFromSystemServer();
- }
- }
-
- /**
* Set sign in error notification to visible or invisible
*
* @hide
@@ -3287,9 +3319,9 @@
@RequiresPermission(anyOf = {
NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
android.Manifest.permission.NETWORK_FACTORY})
- public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
+ public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
NetworkCapabilities nc, int score, NetworkAgentConfig config) {
- return registerNetworkAgent(messenger, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
+ return registerNetworkAgent(na, ni, lp, nc, score, config, NetworkProvider.ID_NONE);
}
/**
@@ -3300,10 +3332,10 @@
@RequiresPermission(anyOf = {
NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK,
android.Manifest.permission.NETWORK_FACTORY})
- public Network registerNetworkAgent(Messenger messenger, NetworkInfo ni, LinkProperties lp,
+ public Network registerNetworkAgent(INetworkAgent na, NetworkInfo ni, LinkProperties lp,
NetworkCapabilities nc, int score, NetworkAgentConfig config, int providerId) {
try {
- return mService.registerNetworkAgent(messenger, ni, lp, nc, score, config, providerId);
+ return mService.registerNetworkAgent(na, ni, lp, nc, score, config, providerId);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
diff --git a/core/java/android/net/IConnectivityManager.aidl b/core/java/android/net/IConnectivityManager.aidl
index 95a2f2e..b32c98b 100644
--- a/core/java/android/net/IConnectivityManager.aidl
+++ b/core/java/android/net/IConnectivityManager.aidl
@@ -29,6 +29,7 @@
import android.net.NetworkState;
import android.net.ISocketKeepaliveCallback;
import android.net.ProxyInfo;
+import android.net.UidRange;
import android.os.Bundle;
import android.os.IBinder;
import android.os.INetworkActivityListener;
@@ -37,6 +38,7 @@
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.VpnInfo;
@@ -145,10 +147,7 @@
String getAlwaysOnVpnPackage(int userId);
boolean isVpnLockdownEnabled(int userId);
List<String> getVpnLockdownWhitelist(int userId);
-
- int checkMobileProvisioning(int suggestedTimeOutMs);
-
- String getMobileProvisioningUrl();
+ void setRequireVpnForUids(boolean requireVpn, in UidRange[] ranges);
void setProvisioningNotificationVisible(boolean visible, int networkType, in String action);
@@ -164,7 +163,7 @@
void declareNetworkRequestUnfulfillable(in NetworkRequest request);
- Network registerNetworkAgent(in Messenger messenger, in NetworkInfo ni, in LinkProperties lp,
+ Network registerNetworkAgent(in INetworkAgent na, in NetworkInfo ni, in LinkProperties lp,
in NetworkCapabilities nc, int score, in NetworkAgentConfig config,
in int factorySerialNumber);
diff --git a/core/java/android/net/NetworkAgent.java b/core/java/android/net/NetworkAgent.java
index 6780167..4166c2c 100644
--- a/core/java/android/net/NetworkAgent.java
+++ b/core/java/android/net/NetworkAgent.java
@@ -29,11 +29,12 @@
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
-import android.os.Messenger;
+import android.os.RemoteException;
import android.util.Log;
+import com.android.connectivity.aidl.INetworkAgent;
+import com.android.connectivity.aidl.INetworkAgentRegistry;
import com.android.internal.annotations.VisibleForTesting;
-import com.android.internal.util.AsyncChannel;
import com.android.internal.util.Protocol;
import java.lang.annotation.Retention;
@@ -94,12 +95,18 @@
@Nullable
private volatile Network mNetwork;
+ @Nullable
+ private volatile INetworkAgentRegistry mRegistry;
+
+ private interface RegistryAction {
+ void execute(@NonNull INetworkAgentRegistry registry) throws RemoteException;
+ }
+
private final Handler mHandler;
- private volatile AsyncChannel mAsyncChannel;
private final String LOG_TAG;
private static final boolean DBG = true;
private static final boolean VDBG = false;
- private final ArrayList<Message> mPreConnectedQueue = new ArrayList<Message>();
+ private final ArrayList<RegistryAction> mPreConnectedQueue = new ArrayList<>();
private volatile long mLastBwRefreshTime = 0;
private static final long BW_REFRESH_MIN_WIN_MS = 500;
private boolean mBandwidthUpdateScheduled = false;
@@ -329,6 +336,17 @@
*/
public static final int CMD_REMOVE_KEEPALIVE_PACKET_FILTER = BASE + 17;
+ /**
+ * Sent by ConnectivityService to the NetworkAgent to complete the bidirectional connection.
+ * obj = INetworkAgentRegistry
+ */
+ private static final int EVENT_AGENT_CONNECTED = BASE + 18;
+
+ /**
+ * Sent by ConnectivityService to the NetworkAgent to inform the agent that it was disconnected.
+ */
+ private static final int EVENT_AGENT_DISCONNECTED = BASE + 19;
+
private static NetworkInfo getLegacyNetworkInfo(final NetworkAgentConfig config) {
// The subtype can be changed with (TODO) setLegacySubtype, but it starts
// with 0 (TelephonyManager.NETWORK_TYPE_UNKNOWN) and an empty description.
@@ -402,36 +420,33 @@
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
- case AsyncChannel.CMD_CHANNEL_FULL_CONNECTION: {
- if (mAsyncChannel != null) {
+ case EVENT_AGENT_CONNECTED: {
+ if (mRegistry != null) {
log("Received new connection while already connected!");
} else {
if (VDBG) log("NetworkAgent fully connected");
- AsyncChannel ac = new AsyncChannel();
- ac.connected(null, this, msg.replyTo);
- ac.replyToMessage(msg, AsyncChannel.CMD_CHANNEL_FULLY_CONNECTED,
- AsyncChannel.STATUS_SUCCESSFUL);
synchronized (mPreConnectedQueue) {
- mAsyncChannel = ac;
- for (Message m : mPreConnectedQueue) {
- ac.sendMessage(m);
+ final INetworkAgentRegistry registry = (INetworkAgentRegistry) msg.obj;
+ mRegistry = registry;
+ for (RegistryAction a : mPreConnectedQueue) {
+ try {
+ a.execute(registry);
+ } catch (RemoteException e) {
+ Log.wtf(LOG_TAG, "Communication error with registry", e);
+ // Fall through
+ }
}
mPreConnectedQueue.clear();
}
}
break;
}
- case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
- if (VDBG) log("CMD_CHANNEL_DISCONNECT");
- if (mAsyncChannel != null) mAsyncChannel.disconnect();
- break;
- }
- case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
+ case EVENT_AGENT_DISCONNECTED: {
if (DBG) log("NetworkAgent channel lost");
// let the client know CS is done with us.
onNetworkUnwanted();
synchronized (mPreConnectedQueue) {
- mAsyncChannel = null;
+ mRegistry = null;
}
break;
}
@@ -494,15 +509,7 @@
}
case CMD_SET_SIGNAL_STRENGTH_THRESHOLDS: {
- ArrayList<Integer> thresholds =
- ((Bundle) msg.obj).getIntegerArrayList("thresholds");
- // TODO: Change signal strength thresholds API to use an ArrayList<Integer>
- // rather than convert to int[].
- int[] intThresholds = new int[(thresholds != null) ? thresholds.size() : 0];
- for (int i = 0; i < intThresholds.length; i++) {
- intThresholds[i] = thresholds.get(i);
- }
- onSignalStrengthThresholdsUpdated(intThresholds);
+ onSignalStrengthThresholdsUpdated((int[]) msg.obj);
break;
}
case CMD_PREVENT_AUTOMATIC_RECONNECT: {
@@ -541,7 +548,7 @@
}
final ConnectivityManager cm = (ConnectivityManager) mInitialConfiguration.context
.getSystemService(Context.CONNECTIVITY_SERVICE);
- mNetwork = cm.registerNetworkAgent(new Messenger(mHandler),
+ mNetwork = cm.registerNetworkAgent(new NetworkAgentBinder(mHandler),
new NetworkInfo(mInitialConfiguration.info),
mInitialConfiguration.properties, mInitialConfiguration.capabilities,
mInitialConfiguration.score, mInitialConfiguration.config, providerId);
@@ -550,6 +557,95 @@
return mNetwork;
}
+ private static class NetworkAgentBinder extends INetworkAgent.Stub {
+ private final Handler mHandler;
+
+ private NetworkAgentBinder(Handler handler) {
+ mHandler = handler;
+ }
+
+ @Override
+ public void onRegistered(@NonNull INetworkAgentRegistry registry) {
+ mHandler.sendMessage(mHandler.obtainMessage(EVENT_AGENT_CONNECTED, registry));
+ }
+
+ @Override
+ public void onDisconnected() {
+ mHandler.sendMessage(mHandler.obtainMessage(EVENT_AGENT_DISCONNECTED));
+ }
+
+ @Override
+ public void onBandwidthUpdateRequested() {
+ mHandler.sendMessage(mHandler.obtainMessage(CMD_REQUEST_BANDWIDTH_UPDATE));
+ }
+
+ @Override
+ public void onValidationStatusChanged(
+ int validationStatus, @Nullable String captivePortalUrl) {
+ // TODO: consider using a parcelable as argument when the interface is structured
+ Bundle redirectUrlBundle = new Bundle();
+ redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, captivePortalUrl);
+ mHandler.sendMessage(mHandler.obtainMessage(CMD_REPORT_NETWORK_STATUS,
+ validationStatus, 0, redirectUrlBundle));
+ }
+
+ @Override
+ public void onSaveAcceptUnvalidated(boolean acceptUnvalidated) {
+ mHandler.sendMessage(mHandler.obtainMessage(CMD_SAVE_ACCEPT_UNVALIDATED,
+ acceptUnvalidated ? 1 : 0, 0));
+ }
+
+ @Override
+ public void onStartNattSocketKeepalive(int slot, int intervalDurationMs,
+ @NonNull NattKeepalivePacketData packetData) {
+ mHandler.sendMessage(mHandler.obtainMessage(CMD_START_SOCKET_KEEPALIVE,
+ slot, intervalDurationMs, packetData));
+ }
+
+ @Override
+ public void onStartTcpSocketKeepalive(int slot, int intervalDurationMs,
+ @NonNull TcpKeepalivePacketData packetData) {
+ mHandler.sendMessage(mHandler.obtainMessage(CMD_START_SOCKET_KEEPALIVE,
+ slot, intervalDurationMs, packetData));
+ }
+
+ @Override
+ public void onStopSocketKeepalive(int slot) {
+ mHandler.sendMessage(mHandler.obtainMessage(CMD_STOP_SOCKET_KEEPALIVE, slot, 0));
+ }
+
+ @Override
+ public void onSignalStrengthThresholdsUpdated(@NonNull int[] thresholds) {
+ mHandler.sendMessage(mHandler.obtainMessage(
+ CMD_SET_SIGNAL_STRENGTH_THRESHOLDS, thresholds));
+ }
+
+ @Override
+ public void onPreventAutomaticReconnect() {
+ mHandler.sendMessage(mHandler.obtainMessage(CMD_PREVENT_AUTOMATIC_RECONNECT));
+ }
+
+ @Override
+ public void onAddNattKeepalivePacketFilter(int slot,
+ @NonNull NattKeepalivePacketData packetData) {
+ mHandler.sendMessage(mHandler.obtainMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER,
+ slot, 0, packetData));
+ }
+
+ @Override
+ public void onAddTcpKeepalivePacketFilter(int slot,
+ @NonNull TcpKeepalivePacketData packetData) {
+ mHandler.sendMessage(mHandler.obtainMessage(CMD_ADD_KEEPALIVE_PACKET_FILTER,
+ slot, 0, packetData));
+ }
+
+ @Override
+ public void onRemoveKeepalivePacketFilter(int slot) {
+ mHandler.sendMessage(mHandler.obtainMessage(CMD_REMOVE_KEEPALIVE_PACKET_FILTER,
+ slot, 0));
+ }
+ }
+
/**
* Register this network agent with a testing harness.
*
@@ -559,13 +655,13 @@
*
* @hide
*/
- public Messenger registerForTest(final Network network) {
+ public INetworkAgent registerForTest(final Network network) {
log("Registering NetworkAgent for test");
synchronized (mRegisterLock) {
mNetwork = network;
mInitialConfiguration = null;
}
- return new Messenger(mHandler);
+ return new NetworkAgentBinder(mHandler);
}
/**
@@ -589,29 +685,17 @@
return mNetwork;
}
- private void queueOrSendMessage(int what, Object obj) {
- queueOrSendMessage(what, 0, 0, obj);
- }
-
- private void queueOrSendMessage(int what, int arg1, int arg2) {
- queueOrSendMessage(what, arg1, arg2, null);
- }
-
- private void queueOrSendMessage(int what, int arg1, int arg2, Object obj) {
- Message msg = Message.obtain();
- msg.what = what;
- msg.arg1 = arg1;
- msg.arg2 = arg2;
- msg.obj = obj;
- queueOrSendMessage(msg);
- }
-
- private void queueOrSendMessage(Message msg) {
+ private void queueOrSendMessage(@NonNull RegistryAction action) {
synchronized (mPreConnectedQueue) {
- if (mAsyncChannel != null) {
- mAsyncChannel.sendMessage(msg);
+ if (mRegistry != null) {
+ try {
+ action.execute(mRegistry);
+ } catch (RemoteException e) {
+ Log.wtf(LOG_TAG, "Error executing registry action", e);
+ // Fall through: the channel is asynchronous and does not report errors back
+ }
} else {
- mPreConnectedQueue.add(msg);
+ mPreConnectedQueue.add(action);
}
}
}
@@ -622,7 +706,8 @@
*/
public final void sendLinkProperties(@NonNull LinkProperties linkProperties) {
Objects.requireNonNull(linkProperties);
- queueOrSendMessage(EVENT_NETWORK_PROPERTIES_CHANGED, new LinkProperties(linkProperties));
+ final LinkProperties lp = new LinkProperties(linkProperties);
+ queueOrSendMessage(reg -> reg.sendLinkProperties(lp));
}
/**
@@ -647,9 +732,7 @@
public final void setUnderlyingNetworks(@Nullable List<Network> underlyingNetworks) {
final ArrayList<Network> underlyingArray = (underlyingNetworks != null)
? new ArrayList<>(underlyingNetworks) : null;
- final Bundle bundle = new Bundle();
- bundle.putParcelableArrayList(UNDERLYING_NETWORKS_KEY, underlyingArray);
- queueOrSendMessage(EVENT_UNDERLYING_NETWORKS_CHANGED, bundle);
+ queueOrSendMessage(reg -> reg.sendUnderlyingNetworks(underlyingArray));
}
/**
@@ -659,7 +742,7 @@
public void markConnected() {
mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.CONNECTED, null /* reason */,
mNetworkInfo.getExtraInfo());
- queueOrSendMessage(EVENT_NETWORK_INFO_CHANGED, mNetworkInfo);
+ queueOrSendNetworkInfo(mNetworkInfo);
}
/**
@@ -672,7 +755,7 @@
// When unregistering an agent nobody should use the extrainfo (or reason) any more.
mNetworkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null /* reason */,
null /* extraInfo */);
- queueOrSendMessage(EVENT_NETWORK_INFO_CHANGED, mNetworkInfo);
+ queueOrSendNetworkInfo(mNetworkInfo);
}
/**
@@ -689,7 +772,7 @@
@Deprecated
public void setLegacySubtype(final int legacySubtype, @NonNull final String legacySubtypeName) {
mNetworkInfo.setSubtype(legacySubtype, legacySubtypeName);
- queueOrSendMessage(EVENT_NETWORK_INFO_CHANGED, mNetworkInfo);
+ queueOrSendNetworkInfo(mNetworkInfo);
}
/**
@@ -711,7 +794,7 @@
@Deprecated
public void setLegacyExtraInfo(@Nullable final String extraInfo) {
mNetworkInfo.setExtraInfo(extraInfo);
- queueOrSendMessage(EVENT_NETWORK_INFO_CHANGED, mNetworkInfo);
+ queueOrSendNetworkInfo(mNetworkInfo);
}
/**
@@ -720,7 +803,11 @@
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
public final void sendNetworkInfo(NetworkInfo networkInfo) {
- queueOrSendMessage(EVENT_NETWORK_INFO_CHANGED, new NetworkInfo(networkInfo));
+ queueOrSendNetworkInfo(new NetworkInfo(networkInfo));
+ }
+
+ private void queueOrSendNetworkInfo(NetworkInfo networkInfo) {
+ queueOrSendMessage(reg -> reg.sendNetworkInfo(networkInfo));
}
/**
@@ -731,8 +818,8 @@
Objects.requireNonNull(networkCapabilities);
mBandwidthUpdatePending.set(false);
mLastBwRefreshTime = System.currentTimeMillis();
- queueOrSendMessage(EVENT_NETWORK_CAPABILITIES_CHANGED,
- new NetworkCapabilities(networkCapabilities));
+ final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
+ queueOrSendMessage(reg -> reg.sendNetworkCapabilities(nc));
}
/**
@@ -744,7 +831,7 @@
if (score < 0) {
throw new IllegalArgumentException("Score must be >= 0");
}
- queueOrSendMessage(EVENT_NETWORK_SCORE_CHANGED, score, 0);
+ queueOrSendMessage(reg -> reg.sendScore(score));
}
/**
@@ -784,9 +871,8 @@
* @hide should move to NetworkAgentConfig.
*/
public void explicitlySelected(boolean explicitlySelected, boolean acceptUnvalidated) {
- queueOrSendMessage(EVENT_SET_EXPLICITLY_SELECTED,
- explicitlySelected ? 1 : 0,
- acceptUnvalidated ? 1 : 0);
+ queueOrSendMessage(reg -> reg.sendExplicitlySelected(
+ explicitlySelected, acceptUnvalidated));
}
/**
@@ -909,7 +995,7 @@
*/
public final void sendSocketKeepaliveEvent(int slot,
@SocketKeepalive.KeepaliveEvent int event) {
- queueOrSendMessage(EVENT_SOCKET_KEEPALIVE, slot, event);
+ queueOrSendMessage(reg -> reg.sendSocketKeepaliveEvent(slot, event));
}
/** @hide TODO delete once callers have moved to sendSocketKeepaliveEvent */
public void onSocketKeepaliveEvent(int slot, int reason) {
diff --git a/core/java/android/net/NetworkCapabilities.java b/core/java/android/net/NetworkCapabilities.java
index 1a37fb9..286cdf9 100644
--- a/core/java/android/net/NetworkCapabilities.java
+++ b/core/java/android/net/NetworkCapabilities.java
@@ -171,6 +171,7 @@
NET_CAPABILITY_PARTIAL_CONNECTIVITY,
NET_CAPABILITY_TEMPORARILY_NOT_METERED,
NET_CAPABILITY_OEM_PRIVATE,
+ NET_CAPABILITY_VEHICLE_INTERNAL,
})
public @interface NetCapability { }
@@ -357,8 +358,17 @@
@SystemApi
public static final int NET_CAPABILITY_OEM_PRIVATE = 26;
+ /**
+ * Indicates this is an internal vehicle network, meant to communicate with other
+ * automotive systems.
+ *
+ * @hide
+ */
+ @SystemApi
+ public static final int NET_CAPABILITY_VEHICLE_INTERNAL = 27;
+
private static final int MIN_NET_CAPABILITY = NET_CAPABILITY_MMS;
- private static final int MAX_NET_CAPABILITY = NET_CAPABILITY_OEM_PRIVATE;
+ private static final int MAX_NET_CAPABILITY = NET_CAPABILITY_VEHICLE_INTERNAL;
/**
* Network capabilities that are expected to be mutable, i.e., can change while a particular
@@ -401,15 +411,16 @@
*/
@VisibleForTesting
/* package */ static final long RESTRICTED_CAPABILITIES =
- (1 << NET_CAPABILITY_CBS) |
- (1 << NET_CAPABILITY_DUN) |
- (1 << NET_CAPABILITY_EIMS) |
- (1 << NET_CAPABILITY_FOTA) |
- (1 << NET_CAPABILITY_IA) |
- (1 << NET_CAPABILITY_IMS) |
- (1 << NET_CAPABILITY_RCS) |
- (1 << NET_CAPABILITY_XCAP) |
- (1 << NET_CAPABILITY_MCX);
+ (1 << NET_CAPABILITY_CBS)
+ | (1 << NET_CAPABILITY_DUN)
+ | (1 << NET_CAPABILITY_EIMS)
+ | (1 << NET_CAPABILITY_FOTA)
+ | (1 << NET_CAPABILITY_IA)
+ | (1 << NET_CAPABILITY_IMS)
+ | (1 << NET_CAPABILITY_MCX)
+ | (1 << NET_CAPABILITY_RCS)
+ | (1 << NET_CAPABILITY_VEHICLE_INTERNAL)
+ | (1 << NET_CAPABILITY_XCAP);
/**
* Capabilities that force network to be restricted.
@@ -1939,6 +1950,7 @@
case NET_CAPABILITY_PARTIAL_CONNECTIVITY: return "PARTIAL_CONNECTIVITY";
case NET_CAPABILITY_TEMPORARILY_NOT_METERED: return "TEMPORARILY_NOT_METERED";
case NET_CAPABILITY_OEM_PRIVATE: return "OEM_PRIVATE";
+ case NET_CAPABILITY_VEHICLE_INTERNAL: return "NET_CAPABILITY_VEHICLE_INTERNAL";
default: return Integer.toString(capability);
}
}
diff --git a/core/java/android/net/NetworkRequest.java b/core/java/android/net/NetworkRequest.java
index dc16d74..f0c637c 100644
--- a/core/java/android/net/NetworkRequest.java
+++ b/core/java/android/net/NetworkRequest.java
@@ -40,6 +40,18 @@
*/
public class NetworkRequest implements Parcelable {
/**
+ * The first requestId value that will be allocated.
+ * @hide only used by ConnectivityService.
+ */
+ public static final int FIRST_REQUEST_ID = 1;
+
+ /**
+ * The requestId value that represents the absence of a request.
+ * @hide only used by ConnectivityService.
+ */
+ public static final int REQUEST_ID_NONE = -1;
+
+ /**
* The {@link NetworkCapabilities} that define this request.
* @hide
*/
diff --git a/core/java/android/net/NetworkUtils.java b/core/java/android/net/NetworkUtils.java
index d84ee2a..b5962c5 100644
--- a/core/java/android/net/NetworkUtils.java
+++ b/core/java/android/net/NetworkUtils.java
@@ -16,14 +16,9 @@
package android.net;
-import static android.system.OsConstants.AF_INET;
-import static android.system.OsConstants.AF_INET6;
-
-import android.annotation.NonNull;
import android.compat.annotation.UnsupportedAppUsage;
import android.os.Build;
import android.system.ErrnoException;
-import android.system.Os;
import android.util.Log;
import android.util.Pair;
@@ -155,14 +150,6 @@
public static native Network getDnsNetwork() throws ErrnoException;
/**
- * Allow/Disallow creating AF_INET/AF_INET6 sockets and DNS lookups for current process.
- *
- * @param allowNetworking whether to allow or disallow creating AF_INET/AF_INET6 sockets
- * and DNS lookups.
- */
- public static native void setAllowNetworkingForProcess(boolean allowNetworking);
-
- /**
* Get the tcp repair window associated with the {@code fd}.
*
* @param fd the tcp socket's {@link FileDescriptor}.
@@ -437,60 +424,4 @@
return routedIPCount;
}
- private static final int[] ADDRESS_FAMILIES = new int[] {AF_INET, AF_INET6};
-
- /**
- * Returns true if the hostname is weakly validated.
- * @param hostname Name of host to validate.
- * @return True if it's a valid-ish hostname.
- *
- * @hide
- */
- public static boolean isWeaklyValidatedHostname(@NonNull String hostname) {
- // TODO(b/34953048): Use a validation method that permits more accurate,
- // but still inexpensive, checking of likely valid DNS hostnames.
- final String weakHostnameRegex = "^[a-zA-Z0-9_.-]+$";
- if (!hostname.matches(weakHostnameRegex)) {
- return false;
- }
-
- for (int address_family : ADDRESS_FAMILIES) {
- if (Os.inet_pton(address_family, hostname) != null) {
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * Safely multiple a value by a rational.
- * <p>
- * Internally it uses integer-based math whenever possible, but switches
- * over to double-based math if values would overflow.
- * @hide
- */
- public static long multiplySafeByRational(long value, long num, long den) {
- if (den == 0) {
- throw new ArithmeticException("Invalid Denominator");
- }
- long x = value;
- long y = num;
-
- // Logic shamelessly borrowed from Math.multiplyExact()
- long r = x * y;
- long ax = Math.abs(x);
- long ay = Math.abs(y);
- if (((ax | ay) >>> 31 != 0)) {
- // Some bits greater than 2^31 that might cause overflow
- // Check the result using the divide operator
- // and check for the special case of Long.MIN_VALUE * -1
- if (((y != 0) && (r / y != x)) ||
- (x == Long.MIN_VALUE && y == -1)) {
- // Use double math to avoid overflowing
- return (long) (((double) num / den) * value);
- }
- }
- return r / den;
- }
}
diff --git a/core/java/android/net/SocketKeepalive.java b/core/java/android/net/SocketKeepalive.java
index a7dce18..d007a95 100644
--- a/core/java/android/net/SocketKeepalive.java
+++ b/core/java/android/net/SocketKeepalive.java
@@ -187,38 +187,54 @@
mCallback = new ISocketKeepaliveCallback.Stub() {
@Override
public void onStarted(int slot) {
- Binder.withCleanCallingIdentity(() ->
- mExecutor.execute(() -> {
- mSlot = slot;
- callback.onStarted();
- }));
+ final long token = Binder.clearCallingIdentity();
+ try {
+ mExecutor.execute(() -> {
+ mSlot = slot;
+ callback.onStarted();
+ });
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
}
@Override
public void onStopped() {
- Binder.withCleanCallingIdentity(() ->
- executor.execute(() -> {
- mSlot = null;
- callback.onStopped();
- }));
+ final long token = Binder.clearCallingIdentity();
+ try {
+ executor.execute(() -> {
+ mSlot = null;
+ callback.onStopped();
+ });
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
}
@Override
public void onError(int error) {
- Binder.withCleanCallingIdentity(() ->
- executor.execute(() -> {
- mSlot = null;
- callback.onError(error);
- }));
+ final long token = Binder.clearCallingIdentity();
+ try {
+ executor.execute(() -> {
+ mSlot = null;
+ callback.onError(error);
+ });
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
}
@Override
public void onDataReceived() {
- Binder.withCleanCallingIdentity(() ->
- executor.execute(() -> {
- mSlot = null;
- callback.onDataReceived();
- }));
+ final long token = Binder.clearCallingIdentity();
+ try {
+ executor.execute(() -> {
+ mSlot = null;
+ callback.onDataReceived();
+ });
+ } finally {
+ Binder.restoreCallingIdentity(token);
+ }
}
};
}
diff --git a/core/jni/android_net_NetUtils.cpp b/core/jni/android_net_NetUtils.cpp
index 8d4c4e5..2155246 100644
--- a/core/jni/android_net_NetUtils.cpp
+++ b/core/jni/android_net_NetUtils.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright 2008, The Android Open Source Project
+ * Copyright 2020, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,7 +28,6 @@
#include <netinet/udp.h>
#include <DnsProxydProtocol.h> // NETID_USE_LOCAL_NAMESERVERS
-#include <android_runtime/AndroidRuntime.h>
#include <cutils/properties.h>
#include <nativehelper/JNIPlatformHelp.h>
#include <nativehelper/ScopedLocalRef.h>
@@ -226,11 +225,6 @@
class_Network, ctor, dnsNetId & ~NETID_USE_LOCAL_NAMESERVERS, privateDnsBypass);
}
-static void android_net_utils_setAllowNetworkingForProcess(JNIEnv *env, jobject thiz,
- jboolean hasConnectivity) {
- setAllowNetworkingForProcess(hasConnectivity == JNI_TRUE);
-}
-
static jobject android_net_utils_getTcpRepairWindow(JNIEnv *env, jobject thiz, jobject javaFd) {
if (javaFd == NULL) {
jniThrowNullPointerException(env, NULL);
@@ -288,7 +282,6 @@
{ "resNetworkResult", "(Ljava/io/FileDescriptor;)Landroid/net/DnsResolver$DnsResponse;", (void*) android_net_utils_resNetworkResult },
{ "resNetworkCancel", "(Ljava/io/FileDescriptor;)V", (void*) android_net_utils_resNetworkCancel },
{ "getDnsNetwork", "()Landroid/net/Network;", (void*) android_net_utils_getDnsNetwork },
- { "setAllowNetworkingForProcess", "(Z)V", (void *)android_net_utils_setAllowNetworkingForProcess },
};
// clang-format on
diff --git a/service/Android.bp b/service/Android.bp
new file mode 100644
index 0000000..c8f3bd3
--- /dev/null
+++ b/service/Android.bp
@@ -0,0 +1,65 @@
+//
+// Copyright (C) 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+cc_library_shared {
+ name: "libservice-connectivity",
+ // TODO: build against the NDK (sdk_version: "30" for example)
+ cflags: [
+ "-Wall",
+ "-Werror",
+ "-Wno-unused-parameter",
+ "-Wthread-safety",
+ ],
+ srcs: [
+ "jni/com_android_server_TestNetworkService.cpp",
+ "jni/com_android_server_connectivity_Vpn.cpp",
+ "jni/onload.cpp",
+ ],
+ shared_libs: [
+ "libbase",
+ "liblog",
+ "libnativehelper",
+ // TODO: remove dependency on ifc_[add/del]_address by having Java code to add/delete
+ // addresses, and remove dependency on libnetutils.
+ "libnetutils",
+ ],
+ apex_available: [
+ "com.android.tethering",
+ ],
+}
+
+java_library {
+ name: "service-connectivity",
+ srcs: [
+ ":connectivity-service-srcs",
+ ],
+ installable: true,
+ jarjar_rules: "jarjar-rules.txt",
+ libs: [
+ "android.net.ipsec.ike",
+ "services.core",
+ "services.net",
+ "unsupportedappusage",
+ ],
+ static_libs: [
+ "net-utils-device-common",
+ "net-utils-framework-common",
+ ],
+ apex_available: [
+ "//apex_available:platform",
+ "com.android.tethering",
+ ],
+}
diff --git a/service/jarjar-rules.txt b/service/jarjar-rules.txt
new file mode 100644
index 0000000..ef53ebb
--- /dev/null
+++ b/service/jarjar-rules.txt
@@ -0,0 +1 @@
+rule com.android.net.module.util.** com.android.connectivity.util.@1
\ No newline at end of file
diff --git a/services/core/jni/com_android_server_TestNetworkService.cpp b/service/jni/com_android_server_TestNetworkService.cpp
similarity index 100%
rename from services/core/jni/com_android_server_TestNetworkService.cpp
rename to service/jni/com_android_server_TestNetworkService.cpp
diff --git a/service/jni/com_android_server_connectivity_Vpn.cpp b/service/jni/com_android_server_connectivity_Vpn.cpp
new file mode 100644
index 0000000..ea5e718
--- /dev/null
+++ b/service/jni/com_android_server_connectivity_Vpn.cpp
@@ -0,0 +1,377 @@
+/*
+ * 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
new file mode 100644
index 0000000..3afcb0e
--- /dev/null
+++ b/service/jni/onload.cpp
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2020 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <nativehelper/JNIHelp.h>
+#include <log/log.h>
+
+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*) {
+ JNIEnv *env;
+ if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
+ ALOGE("GetEnv failed");
+ return JNI_ERR;
+ }
+
+ if (register_android_server_connectivity_Vpn(env) < 0
+ || register_android_server_TestNetworkService(env) < 0) {
+ return JNI_ERR;
+ }
+
+ return JNI_VERSION_1_6;
+}
+
+};
\ No newline at end of file
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index f9a261f..86f0fb9 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -56,12 +56,14 @@
import static android.net.NetworkPolicyManager.uidRulesToString;
import static android.net.shared.NetworkMonitorUtils.isPrivateDnsValidationRequired;
import static android.os.Process.INVALID_UID;
+import static android.os.Process.VPN_UID;
import static android.system.OsConstants.IPPROTO_TCP;
import static android.system.OsConstants.IPPROTO_UDP;
import static java.util.Map.Entry;
import android.Manifest;
+import android.annotation.BoolRes;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.app.AppOpsManager;
@@ -74,7 +76,6 @@
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
-import android.content.res.Configuration;
import android.database.ContentObserver;
import android.net.CaptivePortal;
import android.net.CaptivePortalData;
@@ -83,18 +84,16 @@
import android.net.ConnectivityDiagnosticsManager.DataStallReport;
import android.net.ConnectivityManager;
import android.net.DataStallReportParcelable;
+import android.net.DnsResolverServiceManager;
import android.net.ICaptivePortal;
import android.net.IConnectivityDiagnosticsCallback;
import android.net.IConnectivityManager;
import android.net.IDnsResolver;
-import android.net.IIpConnectivityMetrics;
import android.net.INetd;
-import android.net.INetdEventCallback;
import android.net.INetworkManagementEventObserver;
import android.net.INetworkMonitor;
import android.net.INetworkMonitorCallbacks;
import android.net.INetworkPolicyListener;
-import android.net.INetworkPolicyManager;
import android.net.INetworkStatsService;
import android.net.ISocketKeepaliveCallback;
import android.net.InetAddresses;
@@ -132,6 +131,7 @@
import android.net.Uri;
import android.net.VpnManager;
import android.net.VpnService;
+import android.net.metrics.INetdEventListener;
import android.net.metrics.IpConnectivityLog;
import android.net.metrics.NetworkEvent;
import android.net.netlink.InetDiagMessage;
@@ -155,7 +155,6 @@
import android.os.PowerManager;
import android.os.Process;
import android.os.RemoteException;
-import android.os.ServiceManager;
import android.os.ServiceSpecificException;
import android.os.SystemClock;
import android.os.SystemProperties;
@@ -172,8 +171,8 @@
import android.util.Pair;
import android.util.SparseArray;
import android.util.SparseIntArray;
-import android.util.Xml;
+import com.android.connectivity.aidl.INetworkAgent;
import com.android.internal.R;
import com.android.internal.annotations.GuardedBy;
import com.android.internal.annotations.VisibleForTesting;
@@ -188,7 +187,6 @@
import com.android.internal.util.IndentingPrintWriter;
import com.android.internal.util.LocationPermissionChecker;
import com.android.internal.util.MessageUtils;
-import com.android.internal.util.XmlUtils;
import com.android.modules.utils.BasicShellCommandHandler;
import com.android.net.module.util.LinkPropertiesUtils.CompareOrUpdateResult;
import com.android.net.module.util.LinkPropertiesUtils.CompareResult;
@@ -201,7 +199,6 @@
import com.android.server.connectivity.KeepaliveTracker;
import com.android.server.connectivity.LingerMonitor;
import com.android.server.connectivity.MockableSystemProperties;
-import com.android.server.connectivity.MultipathPolicyTracker;
import com.android.server.connectivity.NetworkAgentInfo;
import com.android.server.connectivity.NetworkDiagnostics;
import com.android.server.connectivity.NetworkNotificationManager;
@@ -210,7 +207,6 @@
import com.android.server.connectivity.PermissionMonitor;
import com.android.server.connectivity.ProxyTracker;
import com.android.server.connectivity.Vpn;
-import com.android.server.net.BaseNetdEventCallback;
import com.android.server.net.BaseNetworkObserver;
import com.android.server.net.LockdownVpnTracker;
import com.android.server.net.NetworkPolicyManagerInternal;
@@ -220,14 +216,7 @@
import libcore.io.IoUtils;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import java.io.File;
import java.io.FileDescriptor;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
@@ -336,7 +325,7 @@
@VisibleForTesting
protected INetd mNetd;
private INetworkStatsService mStatsService;
- private INetworkPolicyManager mPolicyManager;
+ private NetworkPolicyManager mPolicyManager;
private NetworkPolicyManagerInternal mPolicyManagerInternal;
/**
@@ -442,11 +431,6 @@
private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
/**
- * Used internally to indicate the system is ready.
- */
- private static final int EVENT_SYSTEM_READY = 25;
-
- /**
* used to add a network request with a pending intent
* obj = NetworkRequestInfo
*/
@@ -562,6 +546,13 @@
private static final int EVENT_CAPPORT_DATA_CHANGED = 46;
/**
+ * Used by setRequireVpnForUids.
+ * arg1 = whether the specified UID ranges are required to use a VPN.
+ * obj = Array of UidRange objects.
+ */
+ private static final int EVENT_SET_REQUIRE_VPN_FOR_UIDS = 47;
+
+ /**
* Argument for {@link #EVENT_PROVISIONING_NOTIFICATION} to indicate that the notification
* should be shown.
*/
@@ -577,9 +568,8 @@
return sMagicDecoderRing.get(what, Integer.toString(what));
}
- private static IDnsResolver getDnsResolver() {
- return IDnsResolver.Stub
- .asInterface(ServiceManager.getService("dnsresolver"));
+ private static IDnsResolver getDnsResolver(Context context) {
+ return IDnsResolver.Stub.asInterface(DnsResolverServiceManager.getService(context));
}
/** Handler thread used for all of the handlers below. */
@@ -630,7 +620,7 @@
private LingerMonitor mLingerMonitor;
// sequence number of NetworkRequests
- private int mNextNetworkRequestId = 1;
+ private int mNextNetworkRequestId = NetworkRequest.FIRST_REQUEST_ID;
// Sequence number for NetworkProvider IDs.
private final AtomicInteger mNextNetworkProviderId = new AtomicInteger(
@@ -661,9 +651,6 @@
final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
@VisibleForTesting
- final MultipathPolicyTracker mMultipathPolicyTracker;
-
- @VisibleForTesting
final Map<IBinder, ConnectivityDiagnosticsCallbackInfo> mConnectivityDiagnosticsCallbacks =
new HashMap<>();
@@ -940,29 +927,21 @@
"no IpConnectivityMetrics service");
}
- /**
- * @see IpConnectivityMetrics
- */
- public IIpConnectivityMetrics getIpConnectivityMetrics() {
- return IIpConnectivityMetrics.Stub.asInterface(
- ServiceManager.getService(IpConnectivityLog.SERVICE_NAME));
- }
-
public IBatteryStats getBatteryStatsService() {
return BatteryStatsService.getService();
}
}
public ConnectivityService(Context context, INetworkManagementService netManager,
- INetworkStatsService statsService, INetworkPolicyManager policyManager) {
- this(context, netManager, statsService, policyManager, getDnsResolver(),
- new IpConnectivityLog(), NetdService.getInstance(), new Dependencies());
+ INetworkStatsService statsService) {
+ this(context, netManager, statsService, getDnsResolver(context), new IpConnectivityLog(),
+ NetdService.getInstance(), new Dependencies());
}
@VisibleForTesting
protected ConnectivityService(Context context, INetworkManagementService netManager,
- INetworkStatsService statsService, INetworkPolicyManager policyManager,
- IDnsResolver dnsresolver, IpConnectivityLog logger, INetd netd, Dependencies deps) {
+ INetworkStatsService statsService, IDnsResolver dnsresolver, IpConnectivityLog logger,
+ INetd netd, Dependencies deps) {
if (DBG) log("ConnectivityService starting up");
mDeps = Objects.requireNonNull(deps, "missing Dependencies");
@@ -986,6 +965,10 @@
mDefaultWifiRequest = createDefaultInternetRequestForTransport(
NetworkCapabilities.TRANSPORT_WIFI, NetworkRequest.Type.BACKGROUND_REQUEST);
+ mDefaultVehicleRequest = createAlwaysOnRequestForCapability(
+ NetworkCapabilities.NET_CAPABILITY_VEHICLE_INTERNAL,
+ NetworkRequest.Type.BACKGROUND_REQUEST);
+
mHandlerThread = mDeps.makeHandlerThread();
mHandlerThread.start();
mHandler = new InternalHandler(mHandlerThread.getLooper());
@@ -1000,7 +983,7 @@
mNMS = Objects.requireNonNull(netManager, "missing INetworkManagementService");
mStatsService = Objects.requireNonNull(statsService, "missing INetworkStatsService");
- mPolicyManager = Objects.requireNonNull(policyManager, "missing INetworkPolicyManager");
+ mPolicyManager = mContext.getSystemService(NetworkPolicyManager.class);
mPolicyManagerInternal = Objects.requireNonNull(
LocalServices.getService(NetworkPolicyManagerInternal.class),
"missing NetworkPolicyManagerInternal");
@@ -1016,12 +999,7 @@
// To ensure uid rules are synchronized with Network Policy, register for
// NetworkPolicyManagerService events must happen prior to NetworkPolicyManagerService
// reading existing policy from disk.
- try {
- mPolicyManager.registerListener(mPolicyListener);
- } catch (RemoteException e) {
- // ouch, no rules updates means some processes may never get network
- loge("unable to register INetworkPolicyListener" + e);
- }
+ mPolicyManager.registerListener(mPolicyListener);
final PowerManager powerManager = (PowerManager) context.getSystemService(
Context.POWER_SERVICE);
@@ -1167,8 +1145,6 @@
mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
mMultinetworkPolicyTracker.start();
- mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
-
mDnsManager = new DnsManager(mContext, mDnsResolver);
registerPrivateDnsSettingsCallbacks();
}
@@ -1192,6 +1168,15 @@
return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
}
+ private NetworkRequest createAlwaysOnRequestForCapability(int capability,
+ NetworkRequest.Type type) {
+ final NetworkCapabilities netCap = new NetworkCapabilities();
+ netCap.clearAll();
+ netCap.addCapability(capability);
+ netCap.setRequestorUidAndPackageName(Process.myUid(), mContext.getPackageName());
+ return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
+ }
+
// Used only for testing.
// TODO: Delete this and either:
// 1. Give FakeSettingsProvider the ability to send settings change notifications (requires
@@ -1209,10 +1194,19 @@
mHandler.sendEmptyMessage(EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
}
+ private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, @BoolRes int id) {
+ final boolean enable = mContext.getResources().getBoolean(id);
+ handleAlwaysOnNetworkRequest(networkRequest, enable);
+ }
+
private void handleAlwaysOnNetworkRequest(
NetworkRequest networkRequest, String settingName, boolean defaultValue) {
final boolean enable = toBool(Settings.Global.getInt(
mContext.getContentResolver(), settingName, encodeBool(defaultValue)));
+ handleAlwaysOnNetworkRequest(networkRequest, enable);
+ }
+
+ private void handleAlwaysOnNetworkRequest(NetworkRequest networkRequest, boolean enable) {
final boolean isEnabled = (mNetworkRequests.get(networkRequest) != null);
if (enable == isEnabled) {
return; // Nothing to do.
@@ -1229,9 +1223,11 @@
private void handleConfigureAlwaysOnNetworks() {
handleAlwaysOnNetworkRequest(
- mDefaultMobileDataRequest,Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
+ mDefaultMobileDataRequest, Settings.Global.MOBILE_DATA_ALWAYS_ON, true);
handleAlwaysOnNetworkRequest(mDefaultWifiRequest, Settings.Global.WIFI_ALWAYS_REQUESTED,
false);
+ handleAlwaysOnNetworkRequest(mDefaultVehicleRequest,
+ com.android.internal.R.bool.config_vehicleInternalNetworkAlwaysRequested);
}
private void registerSettingsCallbacks() {
@@ -1258,6 +1254,8 @@
}
private synchronized int nextNetworkRequestId() {
+ // TODO: Consider handle wrapping and exclude {@link NetworkRequest#REQUEST_ID_NONE} if
+ // doing that.
return mNextNetworkRequestId++;
}
@@ -1300,19 +1298,28 @@
}
}
- private Network[] getVpnUnderlyingNetworks(int uid) {
- synchronized (mVpns) {
- if (!mLockdownEnabled) {
- int user = UserHandle.getUserId(uid);
- Vpn vpn = mVpns.get(user);
- if (vpn != null && vpn.appliesToUid(uid)) {
- return vpn.getUnderlyingNetworks();
+ // TODO: determine what to do when more than one VPN applies to |uid|.
+ private NetworkAgentInfo getVpnForUid(int uid) {
+ synchronized (mNetworkForNetId) {
+ for (int i = 0; i < mNetworkForNetId.size(); i++) {
+ final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
+ if (nai.isVPN() && nai.everConnected && nai.networkCapabilities.appliesToUid(uid)) {
+ return nai;
}
}
}
return null;
}
+ private Network[] getVpnUnderlyingNetworks(int uid) {
+ synchronized (mVpns) {
+ if (mLockdownEnabled) return null;
+ }
+ final NetworkAgentInfo nai = getVpnForUid(uid);
+ if (nai != null) return nai.declaredUnderlyingNetworks;
+ return null;
+ }
+
private NetworkState getUnfilteredActiveNetworkState(int uid) {
NetworkAgentInfo nai = getDefaultNetwork();
@@ -1338,22 +1345,22 @@
}
/**
- * Check if UID should be blocked from using the network with the given LinkProperties.
+ * Check if UID should be blocked from using the specified network.
*/
- private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
- boolean ignoreBlocked) {
+ private boolean isNetworkWithCapabilitiesBlocked(@Nullable final NetworkCapabilities nc,
+ final int uid, final boolean ignoreBlocked) {
// Networks aren't blocked when ignoring blocked status
if (ignoreBlocked) {
return false;
}
- synchronized (mVpns) {
- final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
- if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
- return true;
- }
+ if (isUidBlockedByVpn(uid, mVpnBlockedUidRanges)) return true;
+ final long ident = Binder.clearCallingIdentity();
+ try {
+ final boolean metered = nc == null ? true : nc.isMetered();
+ return mPolicyManager.isUidNetworkingBlocked(uid, metered);
+ } finally {
+ Binder.restoreCallingIdentity(ident);
}
- final String iface = (lp == null ? "" : lp.getInterfaceName());
- return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
}
private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
@@ -1391,12 +1398,13 @@
/**
* Apply any relevant filters to {@link NetworkState} for the given UID. For
* example, this may mark the network as {@link DetailedState#BLOCKED} based
- * on {@link #isNetworkWithLinkPropertiesBlocked}.
+ * on {@link #isNetworkWithCapabilitiesBlocked}.
*/
private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
if (state == null || state.networkInfo == null || state.linkProperties == null) return;
- if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
+ if (isNetworkWithCapabilitiesBlocked(state.networkCapabilities, uid,
+ ignoreBlocked)) {
state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
}
synchronized (mVpns) {
@@ -1456,8 +1464,8 @@
}
}
nai = getDefaultNetwork();
- if (nai != null
- && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
+ if (nai != null && isNetworkWithCapabilitiesBlocked(
+ nai.networkCapabilities, uid, ignoreBlocked)) {
nai = null;
}
return nai != null ? nai.network : null;
@@ -1529,7 +1537,7 @@
enforceAccessPermission();
final int uid = mDeps.getCallingUid();
NetworkState state = getFilteredNetworkState(networkType, uid);
- if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
+ if (!isNetworkWithCapabilitiesBlocked(state.networkCapabilities, uid, false)) {
return state.network;
}
return null;
@@ -1577,22 +1585,14 @@
nc, mDeps.getCallingUid(), callingPackageName));
}
- synchronized (mVpns) {
- if (!mLockdownEnabled) {
- Vpn vpn = mVpns.get(userId);
- if (vpn != null) {
- Network[] networks = vpn.getUnderlyingNetworks();
- if (networks != null) {
- for (Network network : networks) {
- nc = getNetworkCapabilitiesInternal(network);
- if (nc != null) {
- result.put(
- network,
- maybeSanitizeLocationInfoForCaller(
- nc, mDeps.getCallingUid(), callingPackageName));
- }
- }
- }
+ // No need to check mLockdownEnabled. If it's true, getVpnUnderlyingNetworks returns null.
+ final Network[] networks = getVpnUnderlyingNetworks(Binder.getCallingUid());
+ if (networks != null) {
+ for (Network network : networks) {
+ nc = getNetworkCapabilitiesInternal(network);
+ if (nc != null) {
+ result.put(network, maybeSanitizeLocationInfoForCaller(
+ nc, mDeps.getCallingUid(), callingPackageName));
}
}
}
@@ -1803,9 +1803,9 @@
private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
@Override
- public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
- int deviceType = Integer.parseInt(label);
- sendDataActivityBroadcast(deviceType, active, tsNanos);
+ public void interfaceClassDataActivityChanged(int networkType, boolean active, long tsNanos,
+ int uid) {
+ sendDataActivityBroadcast(networkType, active, tsNanos);
}
};
@@ -1930,8 +1930,7 @@
return true;
}
- @VisibleForTesting
- protected final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
+ private class NetdEventCallback extends INetdEventListener.Stub {
@Override
public void onPrivateDnsValidationEvent(int netId, String ipAddress,
String hostname, boolean validated) {
@@ -1947,8 +1946,8 @@
}
@Override
- public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
- String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
+ public void onDnsEvent(int netId, int eventType, int returnCode, int latencyMs,
+ String hostname, String[] ipAddresses, int ipAddressesCount, int uid) {
NetworkAgentInfo nai = getNetworkAgentInfoForNetId(netId);
// Netd event only allow registrants from system. Each NetworkMonitor thread is under
// the caller thread of registerNetworkAgent. Thus, it's not allowed to register netd
@@ -1967,21 +1966,42 @@
String prefixString, int prefixLength) {
mHandler.post(() -> handleNat64PrefixEvent(netId, added, prefixString, prefixLength));
}
- };
- private void registerNetdEventCallback() {
- final IIpConnectivityMetrics ipConnectivityMetrics = mDeps.getIpConnectivityMetrics();
- if (ipConnectivityMetrics == null) {
- Log.wtf(TAG, "Missing IIpConnectivityMetrics");
- return;
+ @Override
+ public void onConnectEvent(int netId, int error, int latencyMs, String ipAddr, int port,
+ int uid) {
}
+ @Override
+ public void onWakeupEvent(String prefix, int uid, int ethertype, int ipNextHeader,
+ byte[] dstHw, String srcIp, String dstIp, int srcPort, int dstPort,
+ long timestampNs) {
+ }
+
+ @Override
+ public void onTcpSocketStatsEvent(int[] networkIds, int[] sentPackets, int[] lostPackets,
+ int[] rttsUs, int[] sentAckDiffsMs) {
+ }
+
+ @Override
+ public int getInterfaceVersion() throws RemoteException {
+ return this.VERSION;
+ }
+
+ @Override
+ public String getInterfaceHash() {
+ return this.HASH;
+ }
+ };
+
+ @VisibleForTesting
+ protected final INetdEventListener mNetdEventCallback = new NetdEventCallback();
+
+ private void registerNetdEventCallback() {
try {
- ipConnectivityMetrics.addNetdEventCallback(
- INetdEventCallback.CALLBACK_CALLER_CONNECTIVITY_SERVICE,
- mNetdEventCallback);
+ mDnsResolver.registerEventListener(mNetdEventCallback);
} catch (Exception e) {
- loge("Error registering netd callback: " + e);
+ loge("Error registering DnsResolver callback: " + e);
}
}
@@ -2018,29 +2038,18 @@
void handleRestrictBackgroundChanged(boolean restrictBackground) {
if (mRestrictBackground == restrictBackground) return;
- for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+ final List<UidRange> blockedRanges = mVpnBlockedUidRanges;
+ for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
final boolean curMetered = nai.networkCapabilities.isMetered();
maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
- restrictBackground);
+ restrictBackground, blockedRanges, blockedRanges);
}
mRestrictBackground = restrictBackground;
}
- private boolean isUidNetworkingWithVpnBlocked(int uid, int uidRules, boolean isNetworkMetered,
+ private boolean isUidBlockedByRules(int uid, int uidRules, boolean isNetworkMetered,
boolean isBackgroundRestricted) {
- synchronized (mVpns) {
- final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
- // Because the return value of this function depends on the list of UIDs the
- // always-on VPN blocks when in lockdown mode, when the always-on VPN changes that
- // list all state depending on the return value of this function has to be recomputed.
- // TODO: add a trigger when the always-on VPN sets its blocked UIDs to reevaluate and
- // send the necessary onBlockedStatusChanged callbacks.
- if (vpn != null && vpn.getLockdown() && vpn.isBlockingUid(uid)) {
- return true;
- }
- }
-
return NetworkPolicyManagerInternal.isUidNetworkingBlocked(uid, uidRules,
isNetworkMetered, isBackgroundRestricted);
}
@@ -2314,10 +2323,13 @@
*/
@VisibleForTesting
public void systemReadyInternal() {
- // Let PermissionMonitor#startMonitoring() running in the beginning of the systemReady
- // before MultipathPolicyTracker.start(). Since mApps in PermissionMonitor needs to be
- // populated first to ensure that listening network request which is sent by
- // MultipathPolicyTracker won't be added NET_CAPABILITY_FOREGROUND capability.
+ // Since mApps in PermissionMonitor needs to be populated first to ensure that
+ // listening network request which is sent by MultipathPolicyTracker won't be added
+ // NET_CAPABILITY_FOREGROUND capability. Thus, MultipathPolicyTracker.start() must
+ // be called after PermissionMonitor#startMonitoring().
+ // Calling PermissionMonitor#startMonitoring() in systemReadyInternal() and the
+ // MultipathPolicyTracker.start() is called in NetworkPolicyManagerService#systemReady()
+ // to ensure the tracking will be initialized correctly.
mPermissionMonitor.startMonitoring();
mProxyTracker.loadGlobalProxy();
registerNetdEventCallback();
@@ -2336,8 +2348,6 @@
// Create network requests for always-on networks.
mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_ALWAYS_ON_NETWORKS));
-
- mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
}
/**
@@ -2637,7 +2647,6 @@
dumpAvoidBadWifiSettings(pw);
pw.println();
- mMultipathPolicyTracker.dump(pw);
if (ArrayUtils.contains(args, SHORT_ARG) == false) {
pw.println();
@@ -2726,7 +2735,7 @@
*/
private NetworkAgentInfo[] networksSortedById() {
NetworkAgentInfo[] networks = new NetworkAgentInfo[0];
- networks = mNetworkAgentInfos.values().toArray(networks);
+ networks = mNetworkAgentInfos.toArray(networks);
Arrays.sort(networks, Comparator.comparingInt(nai -> nai.network.getNetId()));
return networks;
}
@@ -2772,11 +2781,6 @@
handleAsyncChannelHalfConnect(msg);
break;
}
- case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
- NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
- if (nai != null) nai.asyncChannel.disconnect();
- break;
- }
case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
handleAsyncChannelDisconnected(msg);
break;
@@ -2786,8 +2790,9 @@
}
private void maybeHandleNetworkAgentMessage(Message msg) {
- NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
- if (nai == null) {
+ final Pair<NetworkAgentInfo, Object> arg = (Pair<NetworkAgentInfo, Object>) msg.obj;
+ final NetworkAgentInfo nai = arg.first;
+ if (!mNetworkAgentInfos.contains(nai)) {
if (VDBG) {
log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
}
@@ -2796,7 +2801,7 @@
switch (msg.what) {
case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
- NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
+ NetworkCapabilities networkCapabilities = (NetworkCapabilities) arg.second;
if (networkCapabilities.hasConnectivityManagedCapability()) {
Log.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
}
@@ -2813,13 +2818,13 @@
break;
}
case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
- LinkProperties newLp = (LinkProperties) msg.obj;
+ LinkProperties newLp = (LinkProperties) arg.second;
processLinkPropertiesFromAgent(nai, newLp);
handleUpdateLinkProperties(nai, newLp);
break;
}
case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
- NetworkInfo info = (NetworkInfo) msg.obj;
+ NetworkInfo info = (NetworkInfo) arg.second;
updateNetworkInfo(nai, info);
break;
}
@@ -2844,7 +2849,7 @@
break;
}
case NetworkAgent.EVENT_SOCKET_KEEPALIVE: {
- mKeepaliveTracker.handleEventSocketKeepalive(nai, msg);
+ mKeepaliveTracker.handleEventSocketKeepalive(nai, msg.arg1, msg.arg2);
break;
}
case NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED: {
@@ -2855,7 +2860,7 @@
}
final ArrayList<Network> underlying;
try {
- underlying = ((Bundle) msg.obj).getParcelableArrayList(
+ underlying = ((Bundle) arg.second).getParcelableArrayList(
NetworkAgent.UNDERLYING_NETWORKS_KEY);
} catch (NullPointerException | ClassCastException e) {
break;
@@ -2934,8 +2939,7 @@
if (nai.lastCaptivePortalDetected &&
Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
if (DBG) log("Avoiding captive portal network: " + nai.toShortString());
- nai.asyncChannel.sendMessage(
- NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
+ nai.onPreventAutomaticReconnect();
teardownUnneededNetwork(nai);
break;
}
@@ -2995,9 +2999,7 @@
}
if (valid != nai.lastValidated) {
if (wasDefault) {
- mDeps.getMetricsLogger()
- .defaultNetworkMetrics().logDefaultNetworkValidity(
- SystemClock.elapsedRealtime(), valid);
+ mMetricsLog.logDefaultNetworkValidity(valid);
}
final int oldScore = nai.getCurrentScore();
nai.lastValidated = valid;
@@ -3027,13 +3029,10 @@
}
updateInetCondition(nai);
// Let the NetworkAgent know the state of its network
- Bundle redirectUrlBundle = new Bundle();
- redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
// TODO: Evaluate to update partial connectivity to status to NetworkAgent.
- nai.asyncChannel.sendMessage(
- NetworkAgent.CMD_REPORT_NETWORK_STATUS,
- (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
- 0, redirectUrlBundle);
+ nai.onValidationStatusChanged(
+ valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK,
+ redirectUrl);
// If NetworkMonitor detects partial connectivity before
// EVENT_PROMPT_UNVALIDATED arrives, show the partial connectivity notification
@@ -3067,6 +3066,14 @@
}
break;
}
+ case NetworkAgentInfo.EVENT_AGENT_REGISTERED: {
+ handleNetworkAgentRegistered(msg);
+ break;
+ }
+ case NetworkAgentInfo.EVENT_AGENT_DISCONNECTED: {
+ handleNetworkAgentDisconnected(msg);
+ break;
+ }
}
return true;
}
@@ -3243,7 +3250,7 @@
private void handlePrivateDnsSettingsChanged() {
final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
- for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+ for (NetworkAgentInfo nai : mNetworkAgentInfos) {
handlePerNetworkPrivateDnsConfig(nai, cfg);
if (networkRequiresPrivateDnsValidation(nai)) {
handleUpdateLinkProperties(nai, new LinkProperties(nai.linkProperties));
@@ -3341,7 +3348,6 @@
private void handleAsyncChannelHalfConnect(Message msg) {
ensureRunningOnConnectivityServiceThread();
- final AsyncChannel ac = (AsyncChannel) msg.obj;
if (mNetworkProviderInfos.containsKey(msg.replyTo)) {
if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
if (VDBG) log("NetworkFactory connected");
@@ -3353,39 +3359,45 @@
loge("Error connecting NetworkFactory");
mNetworkProviderInfos.remove(msg.obj);
}
- } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
- if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
- if (VDBG) log("NetworkAgent connected");
- // A network agent has requested a connection. Establish the connection.
- mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
- sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
- } else {
- loge("Error connecting NetworkAgent");
- NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
- if (nai != null) {
- final boolean wasDefault = isDefaultNetwork(nai);
- synchronized (mNetworkForNetId) {
- mNetworkForNetId.remove(nai.network.getNetId());
- }
- mNetIdManager.releaseNetId(nai.network.getNetId());
- // Just in case.
- mLegacyTypeTracker.remove(nai, wasDefault);
+ }
+ }
+
+ private void handleNetworkAgentRegistered(Message msg) {
+ final NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
+ if (!mNetworkAgentInfos.contains(nai)) {
+ return;
+ }
+
+ if (msg.arg1 == NetworkAgentInfo.ARG_AGENT_SUCCESS) {
+ if (VDBG) log("NetworkAgent registered");
+ } else {
+ loge("Error connecting NetworkAgent");
+ mNetworkAgentInfos.remove(nai);
+ if (nai != null) {
+ final boolean wasDefault = isDefaultNetwork(nai);
+ synchronized (mNetworkForNetId) {
+ mNetworkForNetId.remove(nai.network.getNetId());
}
+ mNetIdManager.releaseNetId(nai.network.getNetId());
+ // Just in case.
+ mLegacyTypeTracker.remove(nai, wasDefault);
}
}
}
- // This is a no-op if it's called with a message designating a network that has
+ private void handleNetworkAgentDisconnected(Message msg) {
+ NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
+ if (mNetworkAgentInfos.contains(nai)) {
+ disconnectAndDestroyNetwork(nai);
+ }
+ }
+
+ // This is a no-op if it's called with a message designating a provider that has
// already been destroyed, because its reference will not be found in the relevant
// maps.
private void handleAsyncChannelDisconnected(Message msg) {
- NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
- if (nai != null) {
- disconnectAndDestroyNetwork(nai);
- } else {
- NetworkProviderInfo npi = mNetworkProviderInfos.remove(msg.replyTo);
- if (DBG && npi != null) log("unregisterNetworkFactory for " + npi.name);
- }
+ NetworkProviderInfo npi = mNetworkProviderInfos.remove(msg.replyTo);
+ if (DBG && npi != null) log("unregisterNetworkFactory for " + npi.name);
}
// Destroys a network, remove references to it from the internal state managed by
@@ -3415,7 +3427,9 @@
// if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
// whose timestamps tell how long it takes to recover a default network.
long now = SystemClock.elapsedRealtime();
- mDeps.getMetricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
+ mMetricsLog.logDefaultNetworkEvent(null, 0, false,
+ null /* lp */, null /* nc */, nai.network, nai.getCurrentScore(),
+ nai.linkProperties, nai.networkCapabilities);
}
notifyIfacesChangedForNetworkStats();
// TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
@@ -3429,7 +3443,7 @@
wakeupModifyInterface(iface, nai.networkCapabilities, false);
}
nai.networkMonitor().notifyNetworkDisconnected();
- mNetworkAgentInfos.remove(nai.messenger);
+ mNetworkAgentInfos.remove(nai);
nai.clatd.update();
synchronized (mNetworkForNetId) {
// Remove the NetworkAgent, but don't mark the netId as
@@ -3537,7 +3551,7 @@
mNetworkRequests.put(nri.request, nri);
mNetworkRequestInfoLogs.log("REGISTER " + nri);
if (nri.request.isListen()) {
- for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
+ for (NetworkAgentInfo network : mNetworkAgentInfos) {
if (nri.request.networkCapabilities.hasSignalStrength() &&
network.satisfiesImmutableCapabilitiesOf(nri.request)) {
updateSignalStrengthThresholds(network, "REGISTER", nri.request);
@@ -3602,8 +3616,8 @@
private boolean isNetworkPotentialSatisfier(
@NonNull final NetworkAgentInfo candidate, @NonNull final NetworkRequestInfo nri) {
// listen requests won't keep up a network satisfying it. If this is not a multilayer
- // request, we can return immediately. For multilayer requests, we have to check to see if
- // any of the multilayer requests may have a potential satisfier.
+ // request, return immediately. For multilayer requests, check to see if any of the
+ // multilayer requests may have a potential satisfier.
if (!nri.isMultilayerRequest() && nri.mRequests.get(0).isListen()) {
return false;
}
@@ -3753,7 +3767,7 @@
} else {
// listens don't have a singular affectedNetwork. Check all networks to see
// if this listen request applies and remove it.
- for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+ for (NetworkAgentInfo nai : mNetworkAgentInfos) {
nai.removeRequest(nri.request.requestId);
if (nri.request.networkCapabilities.hasSignalStrength() &&
nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
@@ -3826,13 +3840,12 @@
}
if (always) {
- nai.asyncChannel.sendMessage(
- NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
+ nai.onSaveAcceptUnvalidated(accept);
}
if (!accept) {
// Tell the NetworkAgent to not automatically reconnect to the network.
- nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
+ nai.onPreventAutomaticReconnect();
// Teardown the network.
teardownUnneededNetwork(nai);
}
@@ -3863,13 +3876,12 @@
// TODO: Use the current design or save the user choice into IpMemoryStore.
if (always) {
- nai.asyncChannel.sendMessage(
- NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
+ nai.onSaveAcceptUnvalidated(accept);
}
if (!accept) {
// Tell the NetworkAgent to not automatically reconnect to the network.
- nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
+ nai.onPreventAutomaticReconnect();
// Tear down the network.
teardownUnneededNetwork(nai);
} else {
@@ -4007,7 +4019,7 @@
private void rematchForAvoidBadWifiUpdate() {
rematchAllNetworksAndRequests();
- for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
+ for (NetworkAgentInfo nai: mNetworkAgentInfos) {
if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
sendUpdatedScoreToFactories(nai);
}
@@ -4150,7 +4162,7 @@
// to a network that provides no or limited connectivity is not useful, because the user
// cannot use that network except through the notification shown by this method, and the
// notification is only shown if the network is explicitly selected by the user.
- nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
+ nai.onPreventAutomaticReconnect();
// TODO: Evaluate if it's needed to wait 8 seconds for triggering notification when
// NetworkMonitor detects the network is partial connectivity. Need to change the design to
@@ -4185,11 +4197,13 @@
return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
}
- Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
- if (networkPreference != null) {
+ final NetworkPolicyManager netPolicyManager =
+ mContext.getSystemService(NetworkPolicyManager.class);
+
+ final int networkPreference = netPolicyManager.getMultipathPreference(network);
+ if (networkPreference != 0) {
return networkPreference;
}
-
return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
}
@@ -4293,10 +4307,6 @@
mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
break;
}
- case EVENT_SYSTEM_READY: {
- mMultipathPolicyTracker.start();
- break;
- }
case EVENT_REVALIDATE_NETWORK: {
handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
break;
@@ -4314,6 +4324,9 @@
case EVENT_DATA_SAVER_CHANGED:
handleRestrictBackgroundChanged(toBool(msg.arg1));
break;
+ case EVENT_SET_REQUIRE_VPN_FOR_UIDS:
+ handleSetRequireVpnForUids(toBool(msg.arg1), (UidRange[]) msg.obj);
+ break;
}
}
}
@@ -4482,8 +4495,8 @@
if (!nai.everConnected) {
return;
}
- LinkProperties lp = getLinkProperties(nai);
- if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
+ final NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
+ if (isNetworkWithCapabilitiesBlocked(nc, uid, false)) {
return;
}
nai.networkMonitor().forceReevaluation(uid);
@@ -4802,7 +4815,7 @@
return new VpnInfo[0];
}
List<VpnInfo> infoList = new ArrayList<>();
- for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+ for (NetworkAgentInfo nai : mNetworkAgentInfos) {
VpnInfo info = createVpnInfo(nai);
if (info != null) {
infoList.add(info);
@@ -4903,13 +4916,63 @@
*/
private void propagateUnderlyingNetworkCapabilities(Network updatedNetwork) {
ensureRunningOnConnectivityServiceThread();
- for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+ for (NetworkAgentInfo nai : mNetworkAgentInfos) {
if (updatedNetwork == null || hasUnderlyingNetwork(nai, updatedNetwork)) {
updateCapabilitiesForNetwork(nai);
}
}
}
+ private boolean isUidBlockedByVpn(int uid, List<UidRange> blockedUidRanges) {
+ // Determine whether this UID is blocked because of always-on VPN lockdown. If a VPN applies
+ // to the UID, then the UID is not blocked because always-on VPN lockdown applies only when
+ // a VPN is not up.
+ final NetworkAgentInfo vpnNai = getVpnForUid(uid);
+ if (vpnNai != null && !vpnNai.networkAgentConfig.allowBypass) return false;
+ for (UidRange range : blockedUidRanges) {
+ if (range.contains(uid)) return true;
+ }
+ return false;
+ }
+
+ @Override
+ public void setRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
+ NetworkStack.checkNetworkStackPermission(mContext);
+ mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_REQUIRE_VPN_FOR_UIDS,
+ encodeBool(requireVpn), 0 /* arg2 */, ranges));
+ }
+
+ private void handleSetRequireVpnForUids(boolean requireVpn, UidRange[] ranges) {
+ if (DBG) {
+ Log.d(TAG, "Setting VPN " + (requireVpn ? "" : "not ") + "required for UIDs: "
+ + Arrays.toString(ranges));
+ }
+ // Cannot use a Set since the list of UID ranges might contain duplicates.
+ final List<UidRange> newVpnBlockedUidRanges = new ArrayList(mVpnBlockedUidRanges);
+ for (int i = 0; i < ranges.length; i++) {
+ if (requireVpn) {
+ newVpnBlockedUidRanges.add(ranges[i]);
+ } else {
+ newVpnBlockedUidRanges.remove(ranges[i]);
+ }
+ }
+
+ try {
+ mNetd.networkRejectNonSecureVpn(requireVpn, toUidRangeStableParcels(ranges));
+ } catch (RemoteException | ServiceSpecificException e) {
+ Log.e(TAG, "setRequireVpnForUids(" + requireVpn + ", "
+ + Arrays.toString(ranges) + "): netd command failed: " + e);
+ }
+
+ for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
+ final boolean curMetered = nai.networkCapabilities.isMetered();
+ maybeNotifyNetworkBlocked(nai, curMetered, curMetered, mRestrictBackground,
+ mRestrictBackground, mVpnBlockedUidRanges, newVpnBlockedUidRanges);
+ }
+
+ mVpnBlockedUidRanges = newVpnBlockedUidRanges;
+ }
+
@Override
public boolean updateLockdownVpn() {
if (mDeps.getCallingUid() != Process.SYSTEM_UID) {
@@ -5094,101 +5157,6 @@
}
@Override
- public int checkMobileProvisioning(int suggestedTimeOutMs) {
- // TODO: Remove? Any reason to trigger a provisioning check?
- return -1;
- }
-
- /** Location to an updatable file listing carrier provisioning urls.
- * An example:
- *
- * <?xml version="1.0" encoding="utf-8"?>
- * <provisioningUrls>
- * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
- * </provisioningUrls>
- */
- private static final String PROVISIONING_URL_PATH =
- "/data/misc/radio/provisioning_urls.xml";
- private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
-
- /** XML tag for root element. */
- private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
- /** XML tag for individual url */
- private static final String TAG_PROVISIONING_URL = "provisioningUrl";
- /** XML attribute for mcc */
- private static final String ATTR_MCC = "mcc";
- /** XML attribute for mnc */
- private static final String ATTR_MNC = "mnc";
-
- private String getProvisioningUrlBaseFromFile() {
- XmlPullParser parser;
- Configuration config = mContext.getResources().getConfiguration();
-
- try (FileReader fileReader = new FileReader(mProvisioningUrlFile)) {
- parser = Xml.newPullParser();
- parser.setInput(fileReader);
- XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
-
- while (true) {
- XmlUtils.nextElement(parser);
-
- String element = parser.getName();
- if (element == null) break;
-
- if (element.equals(TAG_PROVISIONING_URL)) {
- String mcc = parser.getAttributeValue(null, ATTR_MCC);
- try {
- if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
- String mnc = parser.getAttributeValue(null, ATTR_MNC);
- if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
- parser.next();
- if (parser.getEventType() == XmlPullParser.TEXT) {
- return parser.getText();
- }
- }
- }
- } catch (NumberFormatException e) {
- loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
- }
- }
- }
- return null;
- } catch (FileNotFoundException e) {
- loge("Carrier Provisioning Urls file not found");
- } catch (XmlPullParserException e) {
- loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
- } catch (IOException e) {
- loge("I/O exception reading Carrier Provisioning Urls file: " + e);
- }
- return null;
- }
-
- @Override
- public String getMobileProvisioningUrl() {
- enforceSettingsPermission();
- String url = getProvisioningUrlBaseFromFile();
- if (TextUtils.isEmpty(url)) {
- url = mContext.getResources().getString(R.string.mobile_provisioning_url);
- log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
- } else {
- log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
- }
- // populate the iccid, imei and phone number in the provisioning url.
- if (!TextUtils.isEmpty(url)) {
- String phoneNumber = mTelephonyManager.getLine1Number();
- if (TextUtils.isEmpty(phoneNumber)) {
- phoneNumber = "0000000000";
- }
- url = String.format(url,
- mTelephonyManager.getSimSerialNumber() /* ICCID */,
- mTelephonyManager.getDeviceId() /* IMEI */,
- phoneNumber /* Phone number */);
- }
-
- return url;
- }
-
- @Override
public void setProvisioningNotificationVisible(boolean visible, int networkType,
String action) {
enforceSettingsPermission();
@@ -5604,7 +5572,7 @@
mAppOpsManager.checkPackage(callerUid, callerPackageName);
}
- private ArrayList<Integer> getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
+ private int[] getSignalStrengthThresholds(@NonNull final NetworkAgentInfo nai) {
final SortedSet<Integer> thresholds = new TreeSet<>();
synchronized (nai) {
for (final NetworkRequestInfo nri : mNetworkRequests.values()) {
@@ -5616,14 +5584,13 @@
}
}
}
- return new ArrayList<>(thresholds);
+ // TODO: use NetworkStackUtils.convertToIntArray after moving it
+ return ArrayUtils.convertToIntArray(new ArrayList<>(thresholds));
}
private void updateSignalStrengthThresholds(
NetworkAgentInfo nai, String reason, NetworkRequest request) {
- ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
- Bundle thresholds = new Bundle();
- thresholds.putIntegerArrayList("thresholds", thresholdsArray);
+ final int[] thresholdsArray = getSignalStrengthThresholds(nai);
if (VDBG || (DBG && !"CONNECT".equals(reason))) {
String detail;
@@ -5633,12 +5600,10 @@
detail = reason;
}
log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
- detail, Arrays.toString(thresholdsArray.toArray()), nai.toShortString()));
+ detail, Arrays.toString(thresholdsArray), nai.toShortString()));
}
- nai.asyncChannel.sendMessage(
- android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
- 0, 0, thresholds);
+ nai.onSignalStrengthThresholdsUpdated(thresholdsArray);
}
private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
@@ -5748,7 +5713,7 @@
nai = mNetworkForNetId.get(network.getNetId());
}
if (nai != null) {
- nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
+ nai.onBandwidthUpdateRequested();
synchronized (mBandwidthRequests) {
final int uid = mDeps.getCallingUid();
Integer uidReqs = mBandwidthRequests.get(uid);
@@ -5991,7 +5956,13 @@
// NetworkAgentInfo keyed off its connecting messenger
// TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
// NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
- private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos = new HashMap<>();
+ private final ArraySet<NetworkAgentInfo> mNetworkAgentInfos = new ArraySet<>();
+
+ // UID ranges for users that are currently blocked by VPNs.
+ // This array is accessed and iterated on multiple threads without holding locks, so its
+ // contents must never be mutated. When the ranges change, the array is replaced with a new one
+ // (on the handler thread).
+ private volatile List<UidRange> mVpnBlockedUidRanges = new ArrayList<>();
@GuardedBy("mBlockedAppUids")
private final HashSet<Integer> mBlockedAppUids = new HashSet<>();
@@ -6010,6 +5981,9 @@
// priority networks like ethernet are active.
private final NetworkRequest mDefaultWifiRequest;
+ // Request used to optionally keep vehicle internal network always active
+ private final NetworkRequest mDefaultVehicleRequest;
+
private NetworkAgentInfo getDefaultNetwork() {
return mDefaultNetworkNai;
}
@@ -6039,17 +6013,17 @@
/**
* Register a new agent. {@see #registerNetworkAgent} below.
*/
- public Network registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
+ public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
int currentScore, NetworkAgentConfig networkAgentConfig) {
- return registerNetworkAgent(messenger, networkInfo, linkProperties, networkCapabilities,
+ return registerNetworkAgent(na, networkInfo, linkProperties, networkCapabilities,
currentScore, networkAgentConfig, NetworkProvider.ID_NONE);
}
/**
* Register a new agent with ConnectivityService to handle a network.
*
- * @param messenger a messenger for ConnectivityService to contact the agent asynchronously.
+ * @param na a reference for ConnectivityService to contact the agent asynchronously.
* @param networkInfo the initial info associated with this network. It can be updated later :
* see {@link #updateNetworkInfo}.
* @param linkProperties the initial link properties of this network. They can be updated
@@ -6062,7 +6036,7 @@
* @param providerId the ID of the provider owning this NetworkAgent.
* @return the network created for this agent.
*/
- public Network registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
+ public Network registerNetworkAgent(INetworkAgent na, NetworkInfo networkInfo,
LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
int currentScore, NetworkAgentConfig networkAgentConfig, int providerId) {
if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
@@ -6074,14 +6048,14 @@
final int uid = mDeps.getCallingUid();
final long token = Binder.clearCallingIdentity();
try {
- return registerNetworkAgentInternal(messenger, networkInfo, linkProperties,
+ return registerNetworkAgentInternal(na, networkInfo, linkProperties,
networkCapabilities, currentScore, networkAgentConfig, providerId, uid);
} finally {
Binder.restoreCallingIdentity(token);
}
}
- private Network registerNetworkAgentInternal(Messenger messenger, NetworkInfo networkInfo,
+ private Network registerNetworkAgentInternal(INetworkAgent na, NetworkInfo networkInfo,
LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
int currentScore, NetworkAgentConfig networkAgentConfig, int providerId, int uid) {
if (networkCapabilities.hasTransport(TRANSPORT_TEST)) {
@@ -6097,7 +6071,7 @@
// TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
// satisfies mDefaultRequest.
final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
- final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
+ final NetworkAgentInfo nai = new NetworkAgentInfo(na,
new Network(mNetIdManager.reserveNetId()), new NetworkInfo(networkInfo), lp, nc,
currentScore, mContext, mTrackerHandler, new NetworkAgentConfig(networkAgentConfig),
this, mNetd, mDnsResolver, mNMS, providerId, uid);
@@ -6115,7 +6089,7 @@
nai.network, name, new NetworkMonitorCallbacks(nai));
// NetworkAgentInfo registration will finish when the NetworkMonitor is created.
// If the network disconnects or sends any other event before that, messages are deferred by
- // NetworkAgent until nai.asyncChannel.connect(), which will be called when finalizing the
+ // NetworkAgent until nai.connect(), which will be called when finalizing the
// registration.
return nai.network;
}
@@ -6123,7 +6097,7 @@
private void handleRegisterNetworkAgent(NetworkAgentInfo nai, INetworkMonitor networkMonitor) {
nai.onNetworkMonitorCreated(networkMonitor);
if (VDBG) log("Got NetworkAgent Messenger");
- mNetworkAgentInfos.put(nai.messenger, nai);
+ mNetworkAgentInfos.add(nai);
synchronized (mNetworkForNetId) {
mNetworkForNetId.put(nai.network.getNetId(), nai);
}
@@ -6133,7 +6107,7 @@
} catch (RemoteException e) {
e.rethrowAsRuntimeException();
}
- nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
+ nai.notifyRegistered();
NetworkInfo networkInfo = nai.networkInfo;
updateNetworkInfo(nai, networkInfo);
updateUids(nai, null, nai.networkCapabilities);
@@ -6701,7 +6675,7 @@
if (meteredChanged) {
maybeNotifyNetworkBlocked(nai, oldMetered, newMetered, mRestrictBackground,
- mRestrictBackground);
+ mRestrictBackground, mVpnBlockedUidRanges, mVpnBlockedUidRanges);
}
final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
@@ -6766,6 +6740,48 @@
return stableRanges;
}
+ private static UidRangeParcel[] toUidRangeStableParcels(UidRange[] ranges) {
+ final UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
+ for (int i = 0; i < ranges.length; i++) {
+ stableRanges[i] = new UidRangeParcel(ranges[i].start, ranges[i].stop);
+ }
+ return stableRanges;
+ }
+
+ private void maybeCloseSockets(NetworkAgentInfo nai, UidRangeParcel[] ranges,
+ int[] exemptUids) {
+ if (nai.isVPN() && !nai.networkAgentConfig.allowBypass) {
+ try {
+ mNetd.socketDestroy(ranges, exemptUids);
+ } catch (Exception e) {
+ loge("Exception in socket destroy: ", e);
+ }
+ }
+ }
+
+ private void updateUidRanges(boolean add, NetworkAgentInfo nai, Set<UidRange> uidRanges) {
+ int[] exemptUids = new int[2];
+ // TODO: Excluding VPN_UID is necessary in order to not to kill the TCP connection used
+ // by PPTP. Fix this by making Vpn set the owner UID to VPN_UID instead of system when
+ // starting a legacy VPN, and remove VPN_UID here. (b/176542831)
+ exemptUids[0] = VPN_UID;
+ exemptUids[1] = nai.networkCapabilities.getOwnerUid();
+ UidRangeParcel[] ranges = toUidRangeStableParcels(uidRanges);
+
+ maybeCloseSockets(nai, ranges, exemptUids);
+ try {
+ if (add) {
+ mNetd.networkAddUidRanges(nai.network.netId, ranges);
+ } else {
+ mNetd.networkRemoveUidRanges(nai.network.netId, ranges);
+ }
+ } catch (Exception e) {
+ loge("Exception while " + (add ? "adding" : "removing") + " uid ranges " + uidRanges +
+ " on netId " + nai.network.netId + ". " + e);
+ }
+ maybeCloseSockets(nai, ranges, exemptUids);
+ }
+
private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
NetworkCapabilities newNc) {
Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
@@ -6784,12 +6800,21 @@
// in both ranges are not subject to any VPN routing rules. Adding new range before
// removing old range works because, unlike the filtering rules below, it's possible to
// add duplicate UID routing rules.
+ // TODO: calculate the intersection of add & remove. Imagining that we are trying to
+ // remove uid 3 from a set containing 1-5. Intersection of the prev and new sets is:
+ // [1-5] & [1-2],[4-5] == [3]
+ // Then we can do:
+ // maybeCloseSockets([3])
+ // mNetd.networkAddUidRanges([1-2],[4-5])
+ // mNetd.networkRemoveUidRanges([1-5])
+ // maybeCloseSockets([3])
+ // This can prevent the sockets of uid 1-2, 4-5 from being closed. It also reduce the
+ // number of binder calls from 6 to 4.
if (!newRanges.isEmpty()) {
- mNetd.networkAddUidRanges(nai.network.netId, toUidRangeStableParcels(newRanges));
+ updateUidRanges(true, nai, newRanges);
}
if (!prevRanges.isEmpty()) {
- mNetd.networkRemoveUidRanges(
- nai.network.netId, toUidRangeStableParcels(prevRanges));
+ updateUidRanges(false, nai, prevRanges);
}
final boolean wasFiltering = requiresVpnIsolation(nai, prevNc, nai.linkProperties);
final boolean shouldFilter = requiresVpnIsolation(nai, newNc, nai.linkProperties);
@@ -7000,7 +7025,7 @@
break;
}
}
- nai.asyncChannel.disconnect();
+ nai.disconnect();
}
private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
@@ -7164,11 +7189,11 @@
log(" accepting network in place of " + previousSatisfier.toShortString());
}
previousSatisfier.removeRequest(nri.request.requestId);
- previousSatisfier.lingerRequest(nri.request, now, mLingerDelayMs);
+ previousSatisfier.lingerRequest(nri.request.requestId, now, mLingerDelayMs);
} else {
if (VDBG || DDBG) log(" accepting network in place of null");
}
- newSatisfier.unlingerRequest(nri.request);
+ newSatisfier.unlingerRequest(nri.request.requestId);
if (!newSatisfier.addRequest(nri.request)) {
Log.wtf(TAG, "BUG: " + newSatisfier.toShortString() + " already has "
+ nri.request);
@@ -7190,7 +7215,7 @@
// Gather the list of all relevant agents and sort them by score.
final ArrayList<NetworkAgentInfo> nais = new ArrayList<>();
- for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+ for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
if (!nai.everConnected) continue;
nais.add(nai);
}
@@ -7225,7 +7250,7 @@
private void applyNetworkReassignment(@NonNull final NetworkReassignment changes,
final long now) {
- final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos.values();
+ final Collection<NetworkAgentInfo> nais = mNetworkAgentInfos;
// Since most of the time there are only 0 or 1 background networks, it would probably
// be more efficient to just use an ArrayList here. TODO : measure performance
@@ -7257,9 +7282,28 @@
updateDataActivityTracking(newDefaultNetwork, oldDefaultNetwork);
// Notify system services of the new default.
makeDefault(newDefaultNetwork);
+
// Log 0 -> X and Y -> X default network transitions, where X is the new default.
- mDeps.getMetricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
- now, newDefaultNetwork, oldDefaultNetwork);
+ final Network network = (newDefaultNetwork != null) ? newDefaultNetwork.network : null;
+ final int score = (newDefaultNetwork != null) ? newDefaultNetwork.getCurrentScore() : 0;
+ final boolean validated = newDefaultNetwork != null && newDefaultNetwork.lastValidated;
+ final LinkProperties lp = (newDefaultNetwork != null)
+ ? newDefaultNetwork.linkProperties : null;
+ final NetworkCapabilities nc = (newDefaultNetwork != null)
+ ? newDefaultNetwork.networkCapabilities : null;
+
+ final Network prevNetwork = (oldDefaultNetwork != null)
+ ? oldDefaultNetwork.network : null;
+ final int prevScore = (oldDefaultNetwork != null)
+ ? oldDefaultNetwork.getCurrentScore() : 0;
+ final LinkProperties prevLp = (oldDefaultNetwork != null)
+ ? oldDefaultNetwork.linkProperties : null;
+ final NetworkCapabilities prevNc = (oldDefaultNetwork != null)
+ ? oldDefaultNetwork.networkCapabilities : null;
+
+ mMetricsLog.logDefaultNetworkEvent(network, score, validated, lp, nc,
+ prevNetwork, prevScore, prevLp, prevNc);
+
// Have a new default network, release the transition wakelock in
scheduleReleaseNetworkTransitionWakelock();
}
@@ -7318,7 +7362,7 @@
updateLegacyTypeTrackerAndVpnLockdownForRematch(oldDefaultNetwork, newDefaultNetwork, nais);
// Tear down all unneeded networks.
- for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+ for (NetworkAgentInfo nai : mNetworkAgentInfos) {
if (unneeded(nai, UnneededFor.TEARDOWN)) {
if (nai.getLingerExpiry() > 0) {
// This network has active linger timers and no requests, but is not
@@ -7555,7 +7599,7 @@
// This has to happen after matching the requests, because callbacks are just requests.
notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
} else if (state == NetworkInfo.State.DISCONNECTED) {
- networkAgent.asyncChannel.disconnect();
+ networkAgent.disconnect();
if (networkAgent.isVPN()) {
updateUids(networkAgent, networkAgent.networkCapabilities, null);
}
@@ -7593,7 +7637,9 @@
}
final boolean metered = nai.networkCapabilities.isMetered();
- final boolean blocked = isUidNetworkingWithVpnBlocked(nri.mUid, mUidRules.get(nri.mUid),
+ boolean blocked;
+ blocked = isUidBlockedByVpn(nri.mUid, mVpnBlockedUidRanges);
+ blocked |= isUidBlockedByRules(nri.mUid, mUidRules.get(nri.mUid),
metered, mRestrictBackground);
callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, blocked ? 1 : 0);
}
@@ -7615,21 +7661,25 @@
* @param newRestrictBackground True if data saver is enabled.
*/
private void maybeNotifyNetworkBlocked(NetworkAgentInfo nai, boolean oldMetered,
- boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground) {
+ boolean newMetered, boolean oldRestrictBackground, boolean newRestrictBackground,
+ List<UidRange> oldBlockedUidRanges, List<UidRange> newBlockedUidRanges) {
for (int i = 0; i < nai.numNetworkRequests(); i++) {
NetworkRequest nr = nai.requestAt(i);
NetworkRequestInfo nri = mNetworkRequests.get(nr);
final int uidRules = mUidRules.get(nri.mUid);
- final boolean oldBlocked, newBlocked;
- // mVpns lock needs to be hold here to ensure that the active VPN cannot be changed
- // between these two calls.
- synchronized (mVpns) {
- oldBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, oldMetered,
- oldRestrictBackground);
- newBlocked = isUidNetworkingWithVpnBlocked(nri.mUid, uidRules, newMetered,
- newRestrictBackground);
- }
+ final boolean oldBlocked, newBlocked, oldVpnBlocked, newVpnBlocked;
+
+ oldVpnBlocked = isUidBlockedByVpn(nri.mUid, oldBlockedUidRanges);
+ newVpnBlocked = (oldBlockedUidRanges != newBlockedUidRanges)
+ ? isUidBlockedByVpn(nri.mUid, newBlockedUidRanges)
+ : oldVpnBlocked;
+
+ oldBlocked = oldVpnBlocked || isUidBlockedByRules(nri.mUid, uidRules, oldMetered,
+ oldRestrictBackground);
+ newBlocked = newVpnBlocked || isUidBlockedByRules(nri.mUid, uidRules, newMetered,
+ newRestrictBackground);
+
if (oldBlocked != newBlocked) {
callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_BLK_CHANGED,
encodeBool(newBlocked));
@@ -7643,19 +7693,14 @@
* @param newRules The new rules to apply.
*/
private void maybeNotifyNetworkBlockedForNewUidRules(int uid, int newRules) {
- for (final NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+ for (final NetworkAgentInfo nai : mNetworkAgentInfos) {
final boolean metered = nai.networkCapabilities.isMetered();
+ final boolean vpnBlocked = isUidBlockedByVpn(uid, mVpnBlockedUidRanges);
final boolean oldBlocked, newBlocked;
- // TODO: Consider that doze mode or turn on/off battery saver would deliver lots of uid
- // rules changed event. And this function actually loop through all connected nai and
- // its requests. It seems that mVpns lock will be grabbed frequently in this case.
- // Reduce the number of locking or optimize the use of lock are likely needed in future.
- synchronized (mVpns) {
- oldBlocked = isUidNetworkingWithVpnBlocked(
- uid, mUidRules.get(uid), metered, mRestrictBackground);
- newBlocked = isUidNetworkingWithVpnBlocked(
- uid, newRules, metered, mRestrictBackground);
- }
+ oldBlocked = vpnBlocked || isUidBlockedByRules(
+ uid, mUidRules.get(uid), metered, mRestrictBackground);
+ newBlocked = vpnBlocked || isUidBlockedByRules(
+ uid, newRules, metered, mRestrictBackground);
if (oldBlocked == newBlocked) {
continue;
}
@@ -7749,7 +7794,7 @@
ensureRunningOnConnectivityServiceThread();
ArrayList<Network> defaultNetworks = new ArrayList<>();
NetworkAgentInfo defaultNetwork = getDefaultNetwork();
- for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
+ for (NetworkAgentInfo nai : mNetworkAgentInfos) {
if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
defaultNetworks.add(nai.network);
}
@@ -8300,6 +8345,13 @@
final IBinder iCb = cb.asBinder();
final NetworkRequestInfo nri = cbInfo.mRequestInfo;
+ // Connectivity Diagnostics are meant to be used with a single network request. It would be
+ // confusing for these networks to change when an NRI is satisfied in another layer.
+ if (nri.isMultilayerRequest()) {
+ throw new IllegalArgumentException("Connectivity Diagnostics do not support multilayer "
+ + "network requests.");
+ }
+
// This means that the client registered the same callback multiple times. Do
// not override the previous entry, and exit silently.
if (mConnectivityDiagnosticsCallbacks.containsKey(iCb)) {
@@ -8326,7 +8378,8 @@
synchronized (mNetworkForNetId) {
for (int i = 0; i < mNetworkForNetId.size(); i++) {
final NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
- if (nai.satisfies(nri.request)) {
+ // Connectivity Diagnostics rejects multilayer requests at registration hence get(0)
+ if (nai.satisfies(nri.mRequests.get(0))) {
matchingNetworks.add(nai);
}
}
@@ -8454,7 +8507,8 @@
mConnectivityDiagnosticsCallbacks.entrySet()) {
final ConnectivityDiagnosticsCallbackInfo cbInfo = entry.getValue();
final NetworkRequestInfo nri = cbInfo.mRequestInfo;
- if (nai.satisfies(nri.request)) {
+ // Connectivity Diagnostics rejects multilayer requests at registration hence get(0).
+ if (nai.satisfies(nri.mRequests.get(0))) {
if (checkConnectivityDiagnosticsPermissions(
nri.mPid, nri.mUid, nai, cbInfo.mCallingPackageName)) {
results.add(entry.getValue().mCb);
@@ -8483,7 +8537,7 @@
return false;
}
- for (NetworkAgentInfo virtual : mNetworkAgentInfos.values()) {
+ for (NetworkAgentInfo virtual : mNetworkAgentInfos) {
if (virtual.supportsUnderlyingNetworks()
&& virtual.networkCapabilities.getOwnerUid() == callbackUid
&& ArrayUtils.contains(virtual.declaredUnderlyingNetworks, nai.network)) {
diff --git a/services/core/java/com/android/server/ConnectivityServiceInitializer.java b/services/core/java/com/android/server/ConnectivityServiceInitializer.java
index 2bc8925..0779f71 100644
--- a/services/core/java/com/android/server/ConnectivityServiceInitializer.java
+++ b/services/core/java/com/android/server/ConnectivityServiceInitializer.java
@@ -20,7 +20,6 @@
import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_NORMAL;
import android.content.Context;
-import android.net.INetworkPolicyManager;
import android.net.INetworkStatsService;
import android.os.INetworkManagementService;
import android.os.ServiceManager;
@@ -36,9 +35,11 @@
public ConnectivityServiceInitializer(Context context) {
super(context);
+ // Load JNI libraries used by ConnectivityService and its dependencies
+ System.loadLibrary("service-connectivity");
// TODO: Define formal APIs to get the needed services.
mConnectivity = new ConnectivityService(context, getNetworkManagementService(),
- getNetworkStatsService(), getNetworkPolicyManager());
+ getNetworkStatsService());
}
@Override
@@ -57,10 +58,4 @@
return INetworkStatsService.Stub.asInterface(
ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
}
-
- private INetworkPolicyManager getNetworkPolicyManager() {
- return INetworkPolicyManager.Stub.asInterface(
- ServiceManager.getService(Context.NETWORK_POLICY_SERVICE));
- }
-
}
diff --git a/services/core/java/com/android/server/connectivity/KeepaliveTracker.java b/services/core/java/com/android/server/connectivity/KeepaliveTracker.java
index 96cbfde..34d9ccc 100644
--- a/services/core/java/com/android/server/connectivity/KeepaliveTracker.java
+++ b/services/core/java/com/android/server/connectivity/KeepaliveTracker.java
@@ -18,10 +18,7 @@
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
import static android.net.NattSocketKeepalive.NATT_PORT;
-import static android.net.NetworkAgent.CMD_ADD_KEEPALIVE_PACKET_FILTER;
-import static android.net.NetworkAgent.CMD_REMOVE_KEEPALIVE_PACKET_FILTER;
import static android.net.NetworkAgent.CMD_START_SOCKET_KEEPALIVE;
-import static android.net.NetworkAgent.CMD_STOP_SOCKET_KEEPALIVE;
import static android.net.SocketKeepalive.BINDER_DIED;
import static android.net.SocketKeepalive.DATA_RECEIVED;
import static android.net.SocketKeepalive.ERROR_INSUFFICIENT_RESOURCES;
@@ -330,10 +327,9 @@
Log.d(TAG, "Starting keepalive " + mSlot + " on " + mNai.toShortString());
switch (mType) {
case TYPE_NATT:
- mNai.asyncChannel.sendMessage(
- CMD_ADD_KEEPALIVE_PACKET_FILTER, slot, 0 /* Unused */, mPacket);
- mNai.asyncChannel
- .sendMessage(CMD_START_SOCKET_KEEPALIVE, slot, mInterval, mPacket);
+ final NattKeepalivePacketData nattData = (NattKeepalivePacketData) mPacket;
+ mNai.onAddNattKeepalivePacketFilter(slot, nattData);
+ mNai.onStartNattSocketKeepalive(slot, mInterval, nattData);
break;
case TYPE_TCP:
try {
@@ -342,11 +338,10 @@
handleStopKeepalive(mNai, mSlot, ERROR_INVALID_SOCKET);
return;
}
- mNai.asyncChannel.sendMessage(
- CMD_ADD_KEEPALIVE_PACKET_FILTER, slot, 0 /* Unused */, mPacket);
+ final TcpKeepalivePacketData tcpData = (TcpKeepalivePacketData) mPacket;
+ mNai.onAddTcpKeepalivePacketFilter(slot, tcpData);
// TODO: check result from apf and notify of failure as needed.
- mNai.asyncChannel
- .sendMessage(CMD_START_SOCKET_KEEPALIVE, slot, mInterval, mPacket);
+ mNai.onStartTcpSocketKeepalive(slot, mInterval, tcpData);
break;
default:
Log.wtf(TAG, "Starting keepalive with unknown type: " + mType);
@@ -394,9 +389,8 @@
mTcpController.stopSocketMonitor(mSlot);
// fall through
case TYPE_NATT:
- mNai.asyncChannel.sendMessage(CMD_STOP_SOCKET_KEEPALIVE, mSlot);
- mNai.asyncChannel.sendMessage(CMD_REMOVE_KEEPALIVE_PACKET_FILTER,
- mSlot);
+ mNai.onStopSocketKeepalive(mSlot);
+ mNai.onRemoveKeepalivePacketFilter(mSlot);
break;
default:
Log.wtf(TAG, "Stopping keepalive with unknown type: " + mType);
@@ -548,17 +542,13 @@
}
/** Handle keepalive events from lower layer. */
- public void handleEventSocketKeepalive(@NonNull NetworkAgentInfo nai,
- @NonNull Message message) {
- int slot = message.arg1;
- int reason = message.arg2;
-
+ public void handleEventSocketKeepalive(@NonNull NetworkAgentInfo nai, int slot, int reason) {
KeepaliveInfo ki = null;
try {
ki = mKeepalives.get(nai).get(slot);
} catch(NullPointerException e) {}
if (ki == null) {
- Log.e(TAG, "Event " + message.what + "," + slot + "," + reason
+ Log.e(TAG, "Event " + NetworkAgent.EVENT_SOCKET_KEEPALIVE + "," + slot + "," + reason
+ " for unknown keepalive " + slot + " on " + nai.toShortString());
return;
}
@@ -601,7 +591,7 @@
ki.mStartedState = KeepaliveInfo.NOT_STARTED;
cleanupStoppedKeepalive(nai, slot);
} else {
- Log.wtf(TAG, "Event " + message.what + "," + slot + "," + reason
+ Log.wtf(TAG, "Event " + NetworkAgent.EVENT_SOCKET_KEEPALIVE + "," + slot + "," + reason
+ " for keepalive in wrong state: " + ki.toString());
}
}
diff --git a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
index 823901d..b0a73f1 100644
--- a/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
+++ b/services/core/java/com/android/server/connectivity/NetworkAgentInfo.java
@@ -27,25 +27,35 @@
import android.net.INetd;
import android.net.INetworkMonitor;
import android.net.LinkProperties;
+import android.net.NattKeepalivePacketData;
import android.net.Network;
+import android.net.NetworkAgent;
import android.net.NetworkAgentConfig;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkMonitorManager;
import android.net.NetworkRequest;
import android.net.NetworkState;
+import android.net.TcpKeepalivePacketData;
+import android.os.Bundle;
import android.os.Handler;
+import android.os.IBinder;
import android.os.INetworkManagementService;
-import android.os.Messenger;
+import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;
+import android.util.Pair;
import android.util.SparseArray;
-import com.android.internal.util.AsyncChannel;
+import com.android.connectivity.aidl.INetworkAgent;
+import com.android.connectivity.aidl.INetworkAgentRegistry;
import com.android.internal.util.WakeupMessage;
import com.android.server.ConnectivityService;
import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;
@@ -136,7 +146,11 @@
// Underlying networks declared by the agent. Only set if supportsUnderlyingNetworks is true.
// The networks in this list might be declared by a VPN app using setUnderlyingNetworks and are
// not guaranteed to be current or correct, or even to exist.
- public @Nullable Network[] declaredUnderlyingNetworks;
+ //
+ // This array is read and iterated on multiple threads with no locking so its contents must
+ // never be modified. When the list of networks changes, replace with a new array, on the
+ // handler thread.
+ public @Nullable volatile Network[] declaredUnderlyingNetworks;
// The capabilities originally announced by the NetworkAgent, regardless of any capabilities
// that were added or removed due to this network's underlying networks.
@@ -193,28 +207,28 @@
// either the linger timeout expiring and the network being taken down, or the network
// satisfying a request again.
public static class LingerTimer implements Comparable<LingerTimer> {
- public final NetworkRequest request;
+ public final int requestId;
public final long expiryMs;
- public LingerTimer(NetworkRequest request, long expiryMs) {
- this.request = request;
+ public LingerTimer(int requestId, long expiryMs) {
+ this.requestId = requestId;
this.expiryMs = expiryMs;
}
public boolean equals(Object o) {
if (!(o instanceof LingerTimer)) return false;
LingerTimer other = (LingerTimer) o;
- return (request.requestId == other.request.requestId) && (expiryMs == other.expiryMs);
+ return (requestId == other.requestId) && (expiryMs == other.expiryMs);
}
public int hashCode() {
- return Objects.hash(request.requestId, expiryMs);
+ return Objects.hash(requestId, expiryMs);
}
public int compareTo(LingerTimer other) {
return (expiryMs != other.expiryMs) ?
Long.compare(expiryMs, other.expiryMs) :
- Integer.compare(request.requestId, other.request.requestId);
+ Integer.compare(requestId, other.requestId);
}
public String toString() {
- return String.format("%s, expires %dms", request.toString(),
+ return String.format("%s, expires %dms", requestId,
expiryMs - SystemClock.elapsedRealtime());
}
}
@@ -226,6 +240,31 @@
*/
public static final int EVENT_NETWORK_LINGER_COMPLETE = 1001;
+ /**
+ * Inform ConnectivityService that the agent is half-connected.
+ * arg1 = ARG_AGENT_SUCCESS or ARG_AGENT_FAILURE
+ * obj = NetworkAgentInfo
+ * @hide
+ */
+ public static final int EVENT_AGENT_REGISTERED = 1002;
+
+ /**
+ * Inform ConnectivityService that the agent was disconnected.
+ * obj = NetworkAgentInfo
+ * @hide
+ */
+ public static final int EVENT_AGENT_DISCONNECTED = 1003;
+
+ /**
+ * Argument for EVENT_AGENT_HALF_CONNECTED indicating failure.
+ */
+ public static final int ARG_AGENT_FAILURE = 0;
+
+ /**
+ * Argument for EVENT_AGENT_HALF_CONNECTED indicating success.
+ */
+ public static final int ARG_AGENT_SUCCESS = 1;
+
// All linger timers for this network, sorted by expiry time. A linger timer is added whenever
// a request is moved to a network with a better score, regardless of whether the network is or
// was lingering or not.
@@ -267,8 +306,9 @@
// report is generated. Once non-null, it will never be null again.
@Nullable private ConnectivityReport mConnectivityReport;
- public final Messenger messenger;
- public final AsyncChannel asyncChannel;
+ public final INetworkAgent networkAgent;
+ // Only accessed from ConnectivityService handler thread
+ private final AgentDeathMonitor mDeathMonitor = new AgentDeathMonitor();
public final int factorySerialNumber;
@@ -284,13 +324,12 @@
private final Context mContext;
private final Handler mHandler;
- public NetworkAgentInfo(Messenger messenger, AsyncChannel ac, Network net, NetworkInfo info,
+ public NetworkAgentInfo(INetworkAgent na, Network net, NetworkInfo info,
LinkProperties lp, NetworkCapabilities nc, int score, Context context,
Handler handler, NetworkAgentConfig config, ConnectivityService connService, INetd netd,
IDnsResolver dnsResolver, INetworkManagementService nms, int factorySerialNumber,
int creatorUid) {
- this.messenger = messenger;
- asyncChannel = ac;
+ networkAgent = na;
network = net;
networkInfo = info;
linkProperties = lp;
@@ -305,6 +344,249 @@
this.creatorUid = creatorUid;
}
+ private class AgentDeathMonitor implements IBinder.DeathRecipient {
+ @Override
+ public void binderDied() {
+ notifyDisconnected();
+ }
+ }
+
+ /**
+ * Notify the NetworkAgent that it was registered, and should be unregistered if it dies.
+ *
+ * Must be called from the ConnectivityService handler thread. A NetworkAgent can only be
+ * registered once.
+ */
+ public void notifyRegistered() {
+ try {
+ networkAgent.asBinder().linkToDeath(mDeathMonitor, 0);
+ networkAgent.onRegistered(new NetworkAgentMessageHandler(mHandler));
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error registering NetworkAgent", e);
+ maybeUnlinkDeathMonitor();
+ mHandler.obtainMessage(EVENT_AGENT_REGISTERED, ARG_AGENT_FAILURE, 0, this)
+ .sendToTarget();
+ return;
+ }
+
+ mHandler.obtainMessage(EVENT_AGENT_REGISTERED, ARG_AGENT_SUCCESS, 0, this).sendToTarget();
+ }
+
+ /**
+ * Disconnect the NetworkAgent. Must be called from the ConnectivityService handler thread.
+ */
+ public void disconnect() {
+ try {
+ networkAgent.onDisconnected();
+ } catch (RemoteException e) {
+ Log.i(TAG, "Error disconnecting NetworkAgent", e);
+ // Fall through: it's fine if the remote has died
+ }
+
+ notifyDisconnected();
+ maybeUnlinkDeathMonitor();
+ }
+
+ private void maybeUnlinkDeathMonitor() {
+ try {
+ networkAgent.asBinder().unlinkToDeath(mDeathMonitor, 0);
+ } catch (NoSuchElementException e) {
+ // Was not linked: ignore
+ }
+ }
+
+ private void notifyDisconnected() {
+ // Note this may be called multiple times if ConnectivityService disconnects while the
+ // NetworkAgent also dies. ConnectivityService ignores disconnects of already disconnected
+ // agents.
+ mHandler.obtainMessage(EVENT_AGENT_DISCONNECTED, this).sendToTarget();
+ }
+
+ /**
+ * Notify the NetworkAgent that bandwidth update was requested.
+ */
+ public void onBandwidthUpdateRequested() {
+ try {
+ networkAgent.onBandwidthUpdateRequested();
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error sending bandwidth update request event", e);
+ }
+ }
+
+ /**
+ * Notify the NetworkAgent that validation status has changed.
+ */
+ public void onValidationStatusChanged(int validationStatus, @Nullable String captivePortalUrl) {
+ try {
+ networkAgent.onValidationStatusChanged(validationStatus, captivePortalUrl);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error sending validation status change event", e);
+ }
+ }
+
+ /**
+ * Notify the NetworkAgent that the acceptUnvalidated setting should be saved.
+ */
+ public void onSaveAcceptUnvalidated(boolean acceptUnvalidated) {
+ try {
+ networkAgent.onSaveAcceptUnvalidated(acceptUnvalidated);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error sending accept unvalidated event", e);
+ }
+ }
+
+ /**
+ * Notify the NetworkAgent that NATT socket keepalive should be started.
+ */
+ public void onStartNattSocketKeepalive(int slot, int intervalDurationMs,
+ @NonNull NattKeepalivePacketData packetData) {
+ try {
+ networkAgent.onStartNattSocketKeepalive(slot, intervalDurationMs, packetData);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error sending NATT socket keepalive start event", e);
+ }
+ }
+
+ /**
+ * Notify the NetworkAgent that TCP socket keepalive should be started.
+ */
+ public void onStartTcpSocketKeepalive(int slot, int intervalDurationMs,
+ @NonNull TcpKeepalivePacketData packetData) {
+ try {
+ networkAgent.onStartTcpSocketKeepalive(slot, intervalDurationMs, packetData);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error sending TCP socket keepalive start event", e);
+ }
+ }
+
+ /**
+ * Notify the NetworkAgent that socket keepalive should be stopped.
+ */
+ public void onStopSocketKeepalive(int slot) {
+ try {
+ networkAgent.onStopSocketKeepalive(slot);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error sending TCP socket keepalive stop event", e);
+ }
+ }
+
+ /**
+ * Notify the NetworkAgent that signal strength thresholds should be updated.
+ */
+ public void onSignalStrengthThresholdsUpdated(@NonNull int[] thresholds) {
+ try {
+ networkAgent.onSignalStrengthThresholdsUpdated(thresholds);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error sending signal strength thresholds event", e);
+ }
+ }
+
+ /**
+ * Notify the NetworkAgent that automatic reconnect should be prevented.
+ */
+ public void onPreventAutomaticReconnect() {
+ try {
+ networkAgent.onPreventAutomaticReconnect();
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error sending prevent automatic reconnect event", e);
+ }
+ }
+
+ /**
+ * Notify the NetworkAgent that a NATT keepalive packet filter should be added.
+ */
+ public void onAddNattKeepalivePacketFilter(int slot,
+ @NonNull NattKeepalivePacketData packetData) {
+ try {
+ networkAgent.onAddNattKeepalivePacketFilter(slot, packetData);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error sending add NATT keepalive packet filter event", e);
+ }
+ }
+
+ /**
+ * Notify the NetworkAgent that a TCP keepalive packet filter should be added.
+ */
+ public void onAddTcpKeepalivePacketFilter(int slot,
+ @NonNull TcpKeepalivePacketData packetData) {
+ try {
+ networkAgent.onAddTcpKeepalivePacketFilter(slot, packetData);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error sending add TCP keepalive packet filter event", e);
+ }
+ }
+
+ /**
+ * Notify the NetworkAgent that a keepalive packet filter should be removed.
+ */
+ public void onRemoveKeepalivePacketFilter(int slot) {
+ try {
+ networkAgent.onRemoveKeepalivePacketFilter(slot);
+ } catch (RemoteException e) {
+ Log.e(TAG, "Error sending remove keepalive packet filter event", e);
+ }
+ }
+
+ // TODO: consider moving out of NetworkAgentInfo into its own class
+ private class NetworkAgentMessageHandler extends INetworkAgentRegistry.Stub {
+ private final Handler mHandler;
+
+ private NetworkAgentMessageHandler(Handler handler) {
+ mHandler = handler;
+ }
+
+ @Override
+ public void sendNetworkCapabilities(NetworkCapabilities nc) {
+ mHandler.obtainMessage(NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED,
+ new Pair<>(NetworkAgentInfo.this, nc)).sendToTarget();
+ }
+
+ @Override
+ public void sendLinkProperties(LinkProperties lp) {
+ mHandler.obtainMessage(NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED,
+ new Pair<>(NetworkAgentInfo.this, lp)).sendToTarget();
+ }
+
+ @Override
+ public void sendNetworkInfo(NetworkInfo info) {
+ mHandler.obtainMessage(NetworkAgent.EVENT_NETWORK_INFO_CHANGED,
+ new Pair<>(NetworkAgentInfo.this, info)).sendToTarget();
+ }
+
+ @Override
+ public void sendScore(int score) {
+ mHandler.obtainMessage(NetworkAgent.EVENT_NETWORK_SCORE_CHANGED, score, 0,
+ new Pair<>(NetworkAgentInfo.this, null)).sendToTarget();
+ }
+
+ @Override
+ public void sendExplicitlySelected(boolean explicitlySelected, boolean acceptPartial) {
+ mHandler.obtainMessage(NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED,
+ explicitlySelected ? 1 : 0, acceptPartial ? 1 : 0,
+ new Pair<>(NetworkAgentInfo.this, null)).sendToTarget();
+ }
+
+ @Override
+ public void sendSocketKeepaliveEvent(int slot, int reason) {
+ mHandler.obtainMessage(NetworkAgent.EVENT_SOCKET_KEEPALIVE,
+ slot, reason, new Pair<>(NetworkAgentInfo.this, null)).sendToTarget();
+ }
+
+ @Override
+ public void sendUnderlyingNetworks(@Nullable List<Network> networks) {
+ final Bundle args = new Bundle();
+ if (networks instanceof ArrayList<?>) {
+ args.putParcelableArrayList(NetworkAgent.UNDERLYING_NETWORKS_KEY,
+ (ArrayList<Network>) networks);
+ } else {
+ args.putParcelableArrayList(NetworkAgent.UNDERLYING_NETWORKS_KEY,
+ networks == null ? null : new ArrayList<>(networks));
+ }
+ mHandler.obtainMessage(NetworkAgent.EVENT_UNDERLYING_NETWORKS_CHANGED,
+ new Pair<>(NetworkAgentInfo.this, args)).sendToTarget();
+ }
+ }
+
/**
* Inform NetworkAgentInfo that a new NetworkMonitor was created.
*/
@@ -416,7 +698,7 @@
updateRequestCounts(REMOVE, existing);
mNetworkRequests.remove(requestId);
if (existing.isRequest()) {
- unlingerRequest(existing);
+ unlingerRequest(existing.requestId);
}
}
@@ -562,33 +844,33 @@
}
/**
- * Sets the specified request to linger on this network for the specified time. Called by
+ * Sets the specified requestId to linger on this network for the specified time. Called by
* ConnectivityService when the request is moved to another network with a higher score.
*/
- public void lingerRequest(NetworkRequest request, long now, long duration) {
- if (mLingerTimerForRequest.get(request.requestId) != null) {
+ public void lingerRequest(int requestId, long now, long duration) {
+ if (mLingerTimerForRequest.get(requestId) != null) {
// Cannot happen. Once a request is lingering on a particular network, we cannot
// re-linger it unless that network becomes the best for that request again, in which
// case we should have unlingered it.
- Log.wtf(TAG, toShortString() + ": request " + request.requestId + " already lingered");
+ Log.wtf(TAG, toShortString() + ": request " + requestId + " already lingered");
}
final long expiryMs = now + duration;
- LingerTimer timer = new LingerTimer(request, expiryMs);
+ LingerTimer timer = new LingerTimer(requestId, expiryMs);
if (VDBG) Log.d(TAG, "Adding LingerTimer " + timer + " to " + toShortString());
mLingerTimers.add(timer);
- mLingerTimerForRequest.put(request.requestId, timer);
+ mLingerTimerForRequest.put(requestId, timer);
}
/**
* Cancel lingering. Called by ConnectivityService when a request is added to this network.
- * Returns true if the given request was lingering on this network, false otherwise.
+ * Returns true if the given requestId was lingering on this network, false otherwise.
*/
- public boolean unlingerRequest(NetworkRequest request) {
- LingerTimer timer = mLingerTimerForRequest.get(request.requestId);
+ public boolean unlingerRequest(int requestId) {
+ LingerTimer timer = mLingerTimerForRequest.get(requestId);
if (timer != null) {
if (VDBG) Log.d(TAG, "Removing LingerTimer " + timer + " from " + toShortString());
mLingerTimers.remove(timer);
- mLingerTimerForRequest.remove(request.requestId);
+ mLingerTimerForRequest.remove(requestId);
return true;
}
return false;
diff --git a/services/core/java/com/android/server/connectivity/ProxyTracker.java b/services/core/java/com/android/server/connectivity/ProxyTracker.java
index 5cb3d94..f6ca152 100644
--- a/services/core/java/com/android/server/connectivity/ProxyTracker.java
+++ b/services/core/java/com/android/server/connectivity/ProxyTracker.java
@@ -38,7 +38,9 @@
import android.util.Log;
import com.android.internal.annotations.GuardedBy;
+import com.android.net.module.util.ProxyUtils;
+import java.util.Collections;
import java.util.Objects;
/**
@@ -163,9 +165,10 @@
if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
ProxyInfo proxyProperties;
if (!TextUtils.isEmpty(pacFileUrl)) {
- proxyProperties = new ProxyInfo(Uri.parse(pacFileUrl));
+ proxyProperties = ProxyInfo.buildPacProxy(Uri.parse(pacFileUrl));
} else {
- proxyProperties = new ProxyInfo(host, port, exclList);
+ proxyProperties = ProxyInfo.buildDirectProxy(host, port,
+ ProxyUtils.exclusionStringAsList(exclList));
}
if (!proxyProperties.isValid()) {
if (DBG) Log.d(TAG, "Invalid proxy properties, ignoring: " + proxyProperties);
@@ -204,7 +207,8 @@
return false;
}
}
- final ProxyInfo p = new ProxyInfo(proxyHost, proxyPort, "");
+ final ProxyInfo p = ProxyInfo.buildDirectProxy(proxyHost, proxyPort,
+ Collections.emptyList());
setGlobalProxy(p);
return true;
}
@@ -219,7 +223,8 @@
*/
public void sendProxyBroadcast() {
final ProxyInfo defaultProxy = getDefaultProxy();
- final ProxyInfo proxyInfo = null != defaultProxy ? defaultProxy : new ProxyInfo("", 0, "");
+ final ProxyInfo proxyInfo = null != defaultProxy ?
+ defaultProxy : ProxyInfo.buildDirectProxy("", 0, Collections.emptyList());
if (mPacManager.setCurrentProxyScriptUrl(proxyInfo) == PacManager.DONT_SEND_BROADCAST) {
return;
}
@@ -261,7 +266,7 @@
mGlobalProxy = new ProxyInfo(proxyInfo);
host = mGlobalProxy.getHost();
port = mGlobalProxy.getPort();
- exclList = mGlobalProxy.getExclusionListAsString();
+ exclList = ProxyUtils.exclusionListAsString(mGlobalProxy.getExclusionList());
pacFileUrl = Uri.EMPTY.equals(proxyInfo.getPacFileUrl())
? "" : proxyInfo.getPacFileUrl().toString();
} else {
diff --git a/tests/net/Android.bp b/tests/net/Android.bp
index a762219..f6a2846 100644
--- a/tests/net/Android.bp
+++ b/tests/net/Android.bp
@@ -70,4 +70,7 @@
"android.test.base",
"android.test.mock",
],
+ jni_libs: [
+ "libservice-connectivity",
+ ],
}
diff --git a/tests/net/common/java/android/net/NetworkProviderTest.kt b/tests/net/common/java/android/net/NetworkProviderTest.kt
index 77e9f12..bcc9072 100644
--- a/tests/net/common/java/android/net/NetworkProviderTest.kt
+++ b/tests/net/common/java/android/net/NetworkProviderTest.kt
@@ -29,6 +29,7 @@
import com.android.net.module.util.ArrayTrackRecord
import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo
import com.android.testutils.DevSdkIgnoreRunner
+import com.android.testutils.isDevSdkInRange
import org.junit.After
import org.junit.Before
import org.junit.Test
@@ -173,10 +174,12 @@
@Test
fun testDeclareNetworkRequestUnfulfillable() {
val mockContext = mock(Context::class.java)
- val provider = createNetworkProvider(mockContext)
- // ConnectivityManager not required at creation time
- verifyNoMoreInteractions(mockContext)
doReturn(mCm).`when`(mockContext).getSystemService(Context.CONNECTIVITY_SERVICE)
+ val provider = createNetworkProvider(mockContext)
+ // ConnectivityManager not required at creation time after R
+ if (!isDevSdkInRange(0, Build.VERSION_CODES.R)) {
+ verifyNoMoreInteractions(mockContext)
+ }
mCm.registerNetworkProvider(provider)
diff --git a/tests/net/integration/src/com/android/server/net/integrationtests/ConnectivityServiceIntegrationTest.kt b/tests/net/integration/src/com/android/server/net/integrationtests/ConnectivityServiceIntegrationTest.kt
index 70f6386..8e18751 100644
--- a/tests/net/integration/src/com/android/server/net/integrationtests/ConnectivityServiceIntegrationTest.kt
+++ b/tests/net/integration/src/com/android/server/net/integrationtests/ConnectivityServiceIntegrationTest.kt
@@ -25,7 +25,6 @@
import android.net.ConnectivityManager
import android.net.IDnsResolver
import android.net.INetd
-import android.net.INetworkPolicyManager
import android.net.INetworkStatsService
import android.net.LinkProperties
import android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL
@@ -88,8 +87,6 @@
@Mock
private lateinit var statsService: INetworkStatsService
@Mock
- private lateinit var policyManager: INetworkPolicyManager
- @Mock
private lateinit var log: IpConnectivityLog
@Mock
private lateinit var netd: INetd
@@ -171,7 +168,7 @@
}
private inner class TestConnectivityService(deps: Dependencies) : ConnectivityService(
- context, netManager, statsService, policyManager, dnsResolver, log, netd, deps)
+ context, netManager, statsService, dnsResolver, log, netd, deps)
private fun makeDependencies(): ConnectivityService.Dependencies {
val deps = spy(ConnectivityService.Dependencies())
diff --git a/tests/net/java/android/net/Ikev2VpnProfileTest.java b/tests/net/java/android/net/Ikev2VpnProfileTest.java
index ada5494..076e41d 100644
--- a/tests/net/java/android/net/Ikev2VpnProfileTest.java
+++ b/tests/net/java/android/net/Ikev2VpnProfileTest.java
@@ -29,6 +29,7 @@
import androidx.test.runner.AndroidJUnit4;
import com.android.internal.net.VpnProfile;
+import com.android.net.module.util.ProxyUtils;
import com.android.org.bouncycastle.x509.X509V1CertificateGenerator;
import org.junit.Before;
@@ -67,7 +68,8 @@
return "fooPackage";
}
};
- private final ProxyInfo mProxy = new ProxyInfo(SERVER_ADDR_STRING, -1, EXCL_LIST);
+ private final ProxyInfo mProxy = ProxyInfo.buildDirectProxy(
+ SERVER_ADDR_STRING, -1, ProxyUtils.exclusionStringAsList(EXCL_LIST));
private X509Certificate mUserCert;
private X509Certificate mServerRootCa;
diff --git a/tests/net/java/android/net/NetworkUtilsTest.java b/tests/net/java/android/net/NetworkUtilsTest.java
index 3158cc8..7748288 100644
--- a/tests/net/java/android/net/NetworkUtilsTest.java
+++ b/tests/net/java/android/net/NetworkUtilsTest.java
@@ -16,24 +16,10 @@
package android.net;
-import static android.system.OsConstants.AF_INET;
-import static android.system.OsConstants.AF_INET6;
-import static android.system.OsConstants.AF_UNIX;
-import static android.system.OsConstants.EPERM;
-import static android.system.OsConstants.SOCK_DGRAM;
-import static android.system.OsConstants.SOCK_STREAM;
-
import static junit.framework.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import android.system.ErrnoException;
-import android.system.Os;
-
import androidx.test.runner.AndroidJUnit4;
-import libcore.io.IoUtils;
-
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -139,50 +125,4 @@
assertEquals(BigInteger.valueOf(7l - 4 + 4 + 16 + 65536),
NetworkUtils.routedIPv6AddressCount(set));
}
-
- private static void expectSocketSuccess(String msg, int domain, int type) {
- try {
- IoUtils.closeQuietly(Os.socket(domain, type, 0));
- } catch (ErrnoException e) {
- fail(msg + e.getMessage());
- }
- }
-
- private static void expectSocketPemissionError(String msg, int domain, int type) {
- try {
- IoUtils.closeQuietly(Os.socket(domain, type, 0));
- fail(msg);
- } catch (ErrnoException e) {
- assertEquals(msg, e.errno, EPERM);
- }
- }
-
- private static void expectHasNetworking() {
- expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException",
- AF_UNIX, SOCK_STREAM);
- expectSocketSuccess("Creating a AF_INET socket shouldn't have thrown ErrnoException",
- AF_INET, SOCK_DGRAM);
- expectSocketSuccess("Creating a AF_INET6 socket shouldn't have thrown ErrnoException",
- AF_INET6, SOCK_DGRAM);
- }
-
- private static void expectNoNetworking() {
- expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException",
- AF_UNIX, SOCK_STREAM);
- expectSocketPemissionError(
- "Creating a AF_INET socket should have thrown ErrnoException(EPERM)",
- AF_INET, SOCK_DGRAM);
- expectSocketPemissionError(
- "Creating a AF_INET6 socket should have thrown ErrnoException(EPERM)",
- AF_INET6, SOCK_DGRAM);
- }
-
- @Test
- public void testSetAllowNetworkingForProcess() {
- expectHasNetworking();
- NetworkUtils.setAllowNetworkingForProcess(false);
- expectNoNetworking();
- NetworkUtils.setAllowNetworkingForProcess(true);
- expectHasNetworking();
- }
}
diff --git a/tests/net/java/com/android/internal/net/NetworkUtilsInternalTest.java b/tests/net/java/com/android/internal/net/NetworkUtilsInternalTest.java
new file mode 100644
index 0000000..3cfecd5
--- /dev/null
+++ b/tests/net/java/com/android/internal/net/NetworkUtilsInternalTest.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.internal.net;
+
+import static android.system.OsConstants.AF_INET;
+import static android.system.OsConstants.AF_INET6;
+import static android.system.OsConstants.AF_UNIX;
+import static android.system.OsConstants.EPERM;
+import static android.system.OsConstants.SOCK_DGRAM;
+import static android.system.OsConstants.SOCK_STREAM;
+
+import static junit.framework.Assert.assertEquals;
+
+import static org.junit.Assert.fail;
+
+import android.system.ErrnoException;
+import android.system.Os;
+
+import androidx.test.runner.AndroidJUnit4;
+
+import libcore.io.IoUtils;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+@RunWith(AndroidJUnit4.class)
+@androidx.test.filters.SmallTest
+public class NetworkUtilsInternalTest {
+
+ private static void expectSocketSuccess(String msg, int domain, int type) {
+ try {
+ IoUtils.closeQuietly(Os.socket(domain, type, 0));
+ } catch (ErrnoException e) {
+ fail(msg + e.getMessage());
+ }
+ }
+
+ private static void expectSocketPemissionError(String msg, int domain, int type) {
+ try {
+ IoUtils.closeQuietly(Os.socket(domain, type, 0));
+ fail(msg);
+ } catch (ErrnoException e) {
+ assertEquals(msg, e.errno, EPERM);
+ }
+ }
+
+ private static void expectHasNetworking() {
+ expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException",
+ AF_UNIX, SOCK_STREAM);
+ expectSocketSuccess("Creating a AF_INET socket shouldn't have thrown ErrnoException",
+ AF_INET, SOCK_DGRAM);
+ expectSocketSuccess("Creating a AF_INET6 socket shouldn't have thrown ErrnoException",
+ AF_INET6, SOCK_DGRAM);
+ }
+
+ private static void expectNoNetworking() {
+ expectSocketSuccess("Creating a UNIX socket should not have thrown ErrnoException",
+ AF_UNIX, SOCK_STREAM);
+ expectSocketPemissionError(
+ "Creating a AF_INET socket should have thrown ErrnoException(EPERM)",
+ AF_INET, SOCK_DGRAM);
+ expectSocketPemissionError(
+ "Creating a AF_INET6 socket should have thrown ErrnoException(EPERM)",
+ AF_INET6, SOCK_DGRAM);
+ }
+
+ @Test
+ public void testSetAllowNetworkingForProcess() {
+ expectHasNetworking();
+ NetworkUtilsInternal.setAllowNetworkingForProcess(false);
+ expectNoNetworking();
+ NetworkUtilsInternal.setAllowNetworkingForProcess(true);
+ expectHasNetworking();
+ }
+}
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index 3a4b1c9..42abad9 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -161,12 +161,10 @@
import android.net.EthernetManager;
import android.net.IConnectivityDiagnosticsCallback;
import android.net.IDnsResolver;
-import android.net.IIpConnectivityMetrics;
import android.net.INetd;
import android.net.INetworkMonitor;
import android.net.INetworkMonitorCallbacks;
import android.net.INetworkPolicyListener;
-import android.net.INetworkPolicyManager;
import android.net.INetworkStatsService;
import android.net.InetAddresses;
import android.net.InterfaceConfigurationParcel;
@@ -183,6 +181,7 @@
import android.net.NetworkFactory;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
+import android.net.NetworkPolicyManager;
import android.net.NetworkRequest;
import android.net.NetworkSpecifier;
import android.net.NetworkStack;
@@ -299,6 +298,7 @@
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
import java.util.function.Supplier;
+import java.util.stream.Collectors;
import kotlin.reflect.KClass;
@@ -363,14 +363,12 @@
private HandlerThread mAlarmManagerThread;
private TestNetIdManager mNetIdManager;
- @Mock IIpConnectivityMetrics mIpConnectivityMetrics;
@Mock IpConnectivityMetrics.Logger mMetricsService;
@Mock DefaultNetworkMetrics mDefaultNetworkMetrics;
@Mock DeviceIdleInternal mDeviceIdleInternal;
@Mock INetworkManagementService mNetworkManagementService;
@Mock INetworkStatsService mStatsService;
@Mock IBatteryStats mBatteryStatsService;
- @Mock INetworkPolicyManager mNpm;
@Mock IDnsResolver mMockDnsResolver;
@Mock INetd mMockNetd;
@Mock NetworkStackClient mNetworkStack;
@@ -385,6 +383,7 @@
@Mock TelephonyManager mTelephonyManager;
@Mock MockableSystemProperties mSystemProperties;
@Mock EthernetManager mEthernetManager;
+ @Mock NetworkPolicyManager mNetworkPolicyManager;
private ArgumentCaptor<ResolverParamsParcel> mResolverParamsParcelCaptor =
ArgumentCaptor.forClass(ResolverParamsParcel.class);
@@ -417,6 +416,7 @@
@Spy private Resources mResources;
private final LinkedBlockingQueue<Intent> mStartedActivities = new LinkedBlockingQueue<>();
+
// Map of permission name -> PermissionManager.Permission_{GRANTED|DENIED} constant
private final HashMap<String, Integer> mMockedPermissions = new HashMap<>();
@@ -482,6 +482,7 @@
if (Context.APP_OPS_SERVICE.equals(name)) return mAppOpsManager;
if (Context.TELEPHONY_SERVICE.equals(name)) return mTelephonyManager;
if (Context.ETHERNET_SERVICE.equals(name)) return mEthernetManager;
+ if (Context.NETWORK_POLICY_SERVICE.equals(name)) return mNetworkPolicyManager;
return super.getSystemService(name);
}
@@ -1201,6 +1202,8 @@
updateState(NetworkInfo.DetailedState.DISCONNECTED, "disconnect");
}
mAgentRegistered = false;
+ setUids(null);
+ mInterface = null;
}
@Override
@@ -1331,7 +1334,6 @@
mService = new ConnectivityService(mServiceContext,
mNetworkManagementService,
mStatsService,
- mNpm,
mMockDnsResolver,
mock(IpConnectivityLog.class),
mMockNetd,
@@ -1341,7 +1343,7 @@
final ArgumentCaptor<INetworkPolicyListener> policyListenerCaptor =
ArgumentCaptor.forClass(INetworkPolicyListener.class);
- verify(mNpm).registerListener(policyListenerCaptor.capture());
+ verify(mNetworkPolicyManager).registerListener(policyListenerCaptor.capture());
mPolicyListener = policyListenerCaptor.getValue();
// Create local CM before sending system ready so that we can answer
@@ -1374,7 +1376,6 @@
doReturn(mock(ProxyTracker.class)).when(deps).makeProxyTracker(any(), any());
doReturn(mMetricsService).when(deps).getMetricsLogger();
doReturn(true).when(deps).queryUserAccess(anyInt(), anyInt());
- doReturn(mIpConnectivityMetrics).when(deps).getIpConnectivityMetrics();
doReturn(mBatteryStatsService).when(deps).getBatteryStatsService();
doAnswer(inv -> {
mPolicyTracker = new WrappedMultinetworkPolicyTracker(
@@ -3494,6 +3495,7 @@
assertEquals(null, mCm.getActiveNetwork());
mMockVpn.establishForMyUid();
+ assertUidRangesUpdatedForMyUid(true);
defaultNetworkCallback.expectAvailableThenValidatedCallbacks(mMockVpn);
assertEquals(defaultNetworkCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
@@ -3757,51 +3759,55 @@
// Register the factory and expect it to start looking for a network.
testFactory.expectAddRequestsWithScores(0); // Score 0 as the request is not served yet.
testFactory.register();
- testFactory.waitForNetworkRequests(1);
- assertTrue(testFactory.getMyStartRequested());
- // Bring up wifi. The factory stops looking for a network.
- mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
- // Score 60 - 40 penalty for not validated yet, then 60 when it validates
- testFactory.expectAddRequestsWithScores(20, 60);
- mWiFiNetworkAgent.connect(true);
- testFactory.waitForRequests();
- assertFalse(testFactory.getMyStartRequested());
+ try {
+ testFactory.waitForNetworkRequests(1);
+ assertTrue(testFactory.getMyStartRequested());
- ContentResolver cr = mServiceContext.getContentResolver();
+ // Bring up wifi. The factory stops looking for a network.
+ mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
+ // Score 60 - 40 penalty for not validated yet, then 60 when it validates
+ testFactory.expectAddRequestsWithScores(20, 60);
+ mWiFiNetworkAgent.connect(true);
+ testFactory.waitForRequests();
+ assertFalse(testFactory.getMyStartRequested());
- // Turn on mobile data always on. The factory starts looking again.
- testFactory.expectAddRequestsWithScores(0); // Always on requests comes up with score 0
- setAlwaysOnNetworks(true);
- testFactory.waitForNetworkRequests(2);
- assertTrue(testFactory.getMyStartRequested());
+ ContentResolver cr = mServiceContext.getContentResolver();
- // Bring up cell data and check that the factory stops looking.
- assertLength(1, mCm.getAllNetworks());
- mCellNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_CELLULAR);
- testFactory.expectAddRequestsWithScores(10, 50); // Unvalidated, then validated
- mCellNetworkAgent.connect(true);
- cellNetworkCallback.expectAvailableThenValidatedCallbacks(mCellNetworkAgent);
- testFactory.waitForNetworkRequests(2);
- assertFalse(testFactory.getMyStartRequested()); // Because the cell network outscores us.
+ // Turn on mobile data always on. The factory starts looking again.
+ testFactory.expectAddRequestsWithScores(0); // Always on requests comes up with score 0
+ setAlwaysOnNetworks(true);
+ testFactory.waitForNetworkRequests(2);
+ assertTrue(testFactory.getMyStartRequested());
- // Check that cell data stays up.
- waitForIdle();
- verifyActiveNetwork(TRANSPORT_WIFI);
- assertLength(2, mCm.getAllNetworks());
+ // Bring up cell data and check that the factory stops looking.
+ assertLength(1, mCm.getAllNetworks());
+ mCellNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_CELLULAR);
+ testFactory.expectAddRequestsWithScores(10, 50); // Unvalidated, then validated
+ mCellNetworkAgent.connect(true);
+ cellNetworkCallback.expectAvailableThenValidatedCallbacks(mCellNetworkAgent);
+ testFactory.waitForNetworkRequests(2);
+ assertFalse(
+ testFactory.getMyStartRequested()); // Because the cell network outscores us.
- // Turn off mobile data always on and expect the request to disappear...
- testFactory.expectRemoveRequests(1);
- setAlwaysOnNetworks(false);
- testFactory.waitForNetworkRequests(1);
+ // Check that cell data stays up.
+ waitForIdle();
+ verifyActiveNetwork(TRANSPORT_WIFI);
+ assertLength(2, mCm.getAllNetworks());
- // ... and cell data to be torn down.
- cellNetworkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
- assertLength(1, mCm.getAllNetworks());
+ // Turn off mobile data always on and expect the request to disappear...
+ testFactory.expectRemoveRequests(1);
+ setAlwaysOnNetworks(false);
+ testFactory.waitForNetworkRequests(1);
- testFactory.terminate();
- mCm.unregisterNetworkCallback(cellNetworkCallback);
- handlerThread.quit();
+ // ... and cell data to be torn down.
+ cellNetworkCallback.expectCallback(CallbackEntry.LOST, mCellNetworkAgent);
+ assertLength(1, mCm.getAllNetworks());
+ } finally {
+ testFactory.terminate();
+ mCm.unregisterNetworkCallback(cellNetworkCallback);
+ handlerThread.quit();
+ }
}
@Test
@@ -4877,11 +4883,9 @@
@Test
public void testNetworkCallbackMaximum() {
- // We can only have 99 callbacks, because MultipathPolicyTracker is
- // already one of them.
- final int MAX_REQUESTS = 99;
+ final int MAX_REQUESTS = 100;
final int CALLBACKS = 89;
- final int INTENTS = 10;
+ final int INTENTS = 11;
assertEquals(MAX_REQUESTS, CALLBACKS + INTENTS);
NetworkRequest networkRequest = new NetworkRequest.Builder().build();
@@ -5182,6 +5186,7 @@
lp.setInterfaceName(VPN_IFNAME);
mMockVpn.establishForMyUid(lp);
+ assertUidRangesUpdatedForMyUid(true);
final Network[] cellAndVpn = new Network[] {
mCellNetworkAgent.getNetwork(), mMockVpn.getNetwork()};
@@ -5767,6 +5772,7 @@
// (and doing so is difficult without using reflection) but it's good to test that the code
// behaves approximately correctly.
mMockVpn.establishForMyUid(false, true, false);
+ assertUidRangesUpdatedForMyUid(true);
final Network wifiNetwork = new Network(mNetIdManager.peekNextNetId());
mService.setUnderlyingNetworksForVpn(new Network[]{wifiNetwork});
callback.expectAvailableCallbacksUnvalidated(mMockVpn);
@@ -5924,6 +5930,7 @@
mMockVpn.establishForMyUid(true /* validated */, false /* hasInternet */,
false /* isStrictMode */);
+ assertUidRangesUpdatedForMyUid(true);
defaultCallback.assertNoCallback();
assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
@@ -5949,6 +5956,7 @@
mMockVpn.establishForMyUid(true /* validated */, true /* hasInternet */,
false /* isStrictMode */);
+ assertUidRangesUpdatedForMyUid(true);
defaultCallback.expectAvailableThenValidatedCallbacks(mMockVpn);
assertEquals(defaultCallback.getLastAvailableNetwork(), mCm.getActiveNetwork());
@@ -5974,6 +5982,7 @@
// Bring up a VPN that has the INTERNET capability, initially unvalidated.
mMockVpn.establishForMyUid(false /* validated */, true /* hasInternet */,
false /* isStrictMode */);
+ assertUidRangesUpdatedForMyUid(true);
// Even though the VPN is unvalidated, it becomes the default network for our app.
callback.expectAvailableCallbacksUnvalidated(mMockVpn);
@@ -6025,6 +6034,7 @@
mMockVpn.establishForMyUid(true /* validated */, false /* hasInternet */,
false /* isStrictMode */);
+ assertUidRangesUpdatedForMyUid(true);
vpnNetworkCallback.expectAvailableCallbacks(mMockVpn.getNetwork(),
false /* suspended */, false /* validated */, false /* blocked */, TIMEOUT_MS);
@@ -6066,6 +6076,7 @@
mMockVpn.establishForMyUid(true /* validated */, false /* hasInternet */,
false /* isStrictMode */);
+ assertUidRangesUpdatedForMyUid(true);
vpnNetworkCallback.expectAvailableThenValidatedCallbacks(mMockVpn);
nc = mCm.getNetworkCapabilities(mMockVpn.getNetwork());
@@ -6233,6 +6244,7 @@
mMockVpn.establishForMyUid(true /* validated */, false /* hasInternet */,
false /* isStrictMode */);
+ assertUidRangesUpdatedForMyUid(true);
vpnNetworkCallback.expectAvailableThenValidatedCallbacks(mMockVpn);
nc = mCm.getNetworkCapabilities(mMockVpn.getNetwork());
@@ -6291,6 +6303,7 @@
// Bring up a VPN
mMockVpn.establishForMyUid();
+ assertUidRangesUpdatedForMyUid(true);
callback.expectAvailableThenValidatedCallbacks(mMockVpn);
callback.assertNoCallback();
@@ -6311,11 +6324,15 @@
// Create a fake restricted profile whose parent is our user ID.
final int userId = UserHandle.getUserId(uid);
+ when(mUserManager.canHaveRestrictedProfile(userId)).thenReturn(true);
final int restrictedUserId = userId + 1;
final UserInfo info = new UserInfo(restrictedUserId, "user", UserInfo.FLAG_RESTRICTED);
info.restrictedProfileParentId = userId;
assertTrue(info.isRestricted());
when(mUserManager.getUserInfo(restrictedUserId)).thenReturn(info);
+ when(mPackageManager.getPackageUidAsUser(ALWAYS_ON_PACKAGE, restrictedUserId))
+ .thenReturn(UserHandle.getUid(restrictedUserId, VPN_UID));
+
final Intent addedIntent = new Intent(ACTION_USER_ADDED);
addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, restrictedUserId);
@@ -6355,6 +6372,54 @@
&& caps.getUids().contains(new UidRange(uid, uid))
&& caps.hasTransport(TRANSPORT_VPN)
&& !caps.hasTransport(TRANSPORT_WIFI));
+
+ // Test lockdown with restricted profiles.
+ mServiceContext.setPermission(
+ Manifest.permission.CONTROL_ALWAYS_ON_VPN, PERMISSION_GRANTED);
+ mServiceContext.setPermission(
+ Manifest.permission.CONTROL_VPN, PERMISSION_GRANTED);
+ mServiceContext.setPermission(
+ Manifest.permission.NETWORK_SETTINGS, PERMISSION_GRANTED);
+
+ // Connect wifi and check that UIDs in the main and restricted profiles have network access.
+ mMockVpn.disconnect();
+ mWiFiNetworkAgent = new TestNetworkAgentWrapper(TRANSPORT_WIFI);
+ mWiFiNetworkAgent.connect(true /* validated */);
+ final int restrictedUid = UserHandle.getUid(restrictedUserId, 42 /* appId */);
+ assertNotNull(mCm.getActiveNetworkForUid(uid));
+ assertNotNull(mCm.getActiveNetworkForUid(restrictedUid));
+
+ // Enable always-on VPN lockdown. The main user loses network access because no VPN is up.
+ final ArrayList<String> allowList = new ArrayList<>();
+ mService.setAlwaysOnVpnPackage(userId, ALWAYS_ON_PACKAGE, true /* lockdown */, allowList);
+ waitForIdle();
+ assertNull(mCm.getActiveNetworkForUid(uid));
+ assertNotNull(mCm.getActiveNetworkForUid(restrictedUid));
+
+ // Start the restricted profile, and check that the UID within it loses network access.
+ when(mUserManager.getAliveUsers()).thenReturn(
+ Arrays.asList(new UserInfo[] {
+ new UserInfo(userId, "", 0),
+ info
+ }));
+ // TODO: check that VPN app within restricted profile still has access, etc.
+ handler.post(() -> mServiceContext.sendBroadcast(addedIntent));
+ waitForIdle();
+ assertNull(mCm.getActiveNetworkForUid(uid));
+ assertNull(mCm.getActiveNetworkForUid(restrictedUid));
+
+ // Stop the restricted profile, and check that the UID within it has network access again.
+ when(mUserManager.getAliveUsers()).thenReturn(
+ Arrays.asList(new UserInfo[] {
+ new UserInfo(userId, "", 0),
+ }));
+ handler.post(() -> mServiceContext.sendBroadcast(removedIntent));
+ waitForIdle();
+ assertNull(mCm.getActiveNetworkForUid(uid));
+ assertNotNull(mCm.getActiveNetworkForUid(restrictedUid));
+
+ mService.setAlwaysOnVpnPackage(userId, null, false /* lockdown */, allowList);
+ waitForIdle();
}
@Test
@@ -6393,6 +6458,7 @@
// Connect VPN network. By default it is using current default network (Cell).
mMockVpn.establishForMyUid();
+ assertUidRangesUpdatedForMyUid(true);
// Ensure VPN is now the active network.
assertEquals(mMockVpn.getNetwork(), mCm.getActiveNetwork());
@@ -6445,6 +6511,7 @@
// Connect VPN network.
mMockVpn.establishForMyUid();
+ assertUidRangesUpdatedForMyUid(true);
// Ensure VPN is now the active network.
assertEquals(mMockVpn.getNetwork(), mCm.getActiveNetwork());
@@ -6646,6 +6713,26 @@
checkNetworkInfo(mCm.getNetworkInfo(type), type, state);
}
+ // Checks that each of the |agents| receive a blocked status change callback with the specified
+ // |blocked| value, in any order. This is needed because when an event affects multiple
+ // networks, ConnectivityService does not guarantee the order in which callbacks are fired.
+ private void assertBlockedCallbackInAnyOrder(TestNetworkCallback callback, boolean blocked,
+ TestNetworkAgentWrapper... agents) {
+ final List<Network> expectedNetworks = Arrays.asList(agents).stream()
+ .map((agent) -> agent.getNetwork())
+ .collect(Collectors.toList());
+
+ // Expect exactly one blocked callback for each agent.
+ for (int i = 0; i < agents.length; i++) {
+ CallbackEntry e = callback.expectCallbackThat(TIMEOUT_MS, (c) ->
+ c instanceof CallbackEntry.BlockedStatus
+ && ((CallbackEntry.BlockedStatus) c).getBlocked() == blocked);
+ Network network = e.getNetwork();
+ assertTrue("Received unexpected blocked callback for network " + network,
+ expectedNetworks.remove(network));
+ }
+ }
+
@Test
public void testNetworkBlockedStatusAlwaysOnVpn() throws Exception {
mServiceContext.setPermission(
@@ -6692,9 +6779,10 @@
assertNetworkInfo(TYPE_WIFI, DetailedState.BLOCKED);
// Disable lockdown, expect to see the network unblocked.
- // There are no callbacks because they are not implemented yet.
mService.setAlwaysOnVpnPackage(userId, null, false /* lockdown */, allowList);
expectNetworkRejectNonSecureVpn(inOrder, false, firstHalf, secondHalf);
+ callback.expectBlockedStatusCallback(false, mWiFiNetworkAgent);
+ defaultCallback.expectBlockedStatusCallback(false, mWiFiNetworkAgent);
vpnUidCallback.assertNoCallback();
assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetworkForUid(VPN_UID));
assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
@@ -6742,6 +6830,8 @@
allowList.clear();
mService.setAlwaysOnVpnPackage(userId, ALWAYS_ON_PACKAGE, true /* lockdown */, allowList);
expectNetworkRejectNonSecureVpn(inOrder, true, firstHalf, secondHalf);
+ defaultCallback.expectBlockedStatusCallback(true, mWiFiNetworkAgent);
+ assertBlockedCallbackInAnyOrder(callback, true, mWiFiNetworkAgent, mCellNetworkAgent);
vpnUidCallback.assertNoCallback();
assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetworkForUid(VPN_UID));
assertNull(mCm.getActiveNetwork());
@@ -6751,6 +6841,8 @@
// Disable lockdown. Everything is unblocked.
mService.setAlwaysOnVpnPackage(userId, null, false /* lockdown */, allowList);
+ defaultCallback.expectBlockedStatusCallback(false, mWiFiNetworkAgent);
+ assertBlockedCallbackInAnyOrder(callback, false, mWiFiNetworkAgent, mCellNetworkAgent);
vpnUidCallback.assertNoCallback();
assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetworkForUid(VPN_UID));
assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetwork());
@@ -6784,6 +6876,8 @@
// Enable lockdown and connect a VPN. The VPN is not blocked.
mService.setAlwaysOnVpnPackage(userId, ALWAYS_ON_PACKAGE, true /* lockdown */, allowList);
+ defaultCallback.expectBlockedStatusCallback(true, mWiFiNetworkAgent);
+ assertBlockedCallbackInAnyOrder(callback, true, mWiFiNetworkAgent, mCellNetworkAgent);
vpnUidCallback.assertNoCallback();
assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetworkForUid(VPN_UID));
assertNull(mCm.getActiveNetwork());
@@ -6792,10 +6886,11 @@
assertNetworkInfo(TYPE_WIFI, DetailedState.BLOCKED);
mMockVpn.establishForMyUid();
+ assertUidRangesUpdatedForMyUid(true);
defaultCallback.expectAvailableThenValidatedCallbacks(mMockVpn);
vpnUidCallback.assertNoCallback(); // vpnUidCallback has NOT_VPN capability.
assertEquals(mMockVpn.getNetwork(), mCm.getActiveNetwork());
- assertEquals(null, mCm.getActiveNetworkForUid(VPN_UID)); // BUG?
+ assertEquals(mWiFiNetworkAgent.getNetwork(), mCm.getActiveNetworkForUid(VPN_UID));
assertActiveNetworkInfo(TYPE_WIFI, DetailedState.CONNECTED);
assertNetworkInfo(TYPE_MOBILE, DetailedState.DISCONNECTED);
assertNetworkInfo(TYPE_VPN, DetailedState.CONNECTED);
@@ -7449,6 +7544,7 @@
LinkProperties testLinkProperties = new LinkProperties();
testLinkProperties.setHttpProxy(testProxyInfo);
mMockVpn.establishForMyUid(testLinkProperties);
+ assertUidRangesUpdatedForMyUid(true);
// Test that the VPN network returns a proxy, and the WiFi does not.
assertEquals(testProxyInfo, mService.getProxyForNetwork(mMockVpn.getNetwork()));
@@ -7486,6 +7582,7 @@
// The uid range needs to cover the test app so the network is visible to it.
final Set<UidRange> vpnRange = Collections.singleton(UidRange.createForUser(VPN_USER));
mMockVpn.establish(lp, VPN_UID, vpnRange);
+ assertVpnUidRangesUpdated(true, vpnRange, VPN_UID);
// A connected VPN should have interface rules set up. There are two expected invocations,
// one during the VPN initial connection, one during the VPN LinkProperties update.
@@ -7513,6 +7610,7 @@
// The uid range needs to cover the test app so the network is visible to it.
final Set<UidRange> vpnRange = Collections.singleton(UidRange.createForUser(VPN_USER));
mMockVpn.establish(lp, Process.SYSTEM_UID, vpnRange);
+ assertVpnUidRangesUpdated(true, vpnRange, Process.SYSTEM_UID);
// Legacy VPN should not have interface rules set up
verify(mMockNetd, never()).firewallAddUidInterfaceRules(any(), any());
@@ -7528,6 +7626,7 @@
// The uid range needs to cover the test app so the network is visible to it.
final Set<UidRange> vpnRange = Collections.singleton(UidRange.createForUser(VPN_USER));
mMockVpn.establish(lp, Process.SYSTEM_UID, vpnRange);
+ assertVpnUidRangesUpdated(true, vpnRange, Process.SYSTEM_UID);
// IPv6 unreachable route should not be misinterpreted as a default route
verify(mMockNetd, never()).firewallAddUidInterfaceRules(any(), any());
@@ -7542,6 +7641,7 @@
// The uid range needs to cover the test app so the network is visible to it.
final Set<UidRange> vpnRange = Collections.singleton(UidRange.createForUser(VPN_USER));
mMockVpn.establish(lp, VPN_UID, vpnRange);
+ assertVpnUidRangesUpdated(true, vpnRange, VPN_UID);
// Connected VPN should have interface rules set up. There are two expected invocations,
// one during VPN uid update, one during VPN LinkProperties update
@@ -7592,7 +7692,9 @@
lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), null));
// The uid range needs to cover the test app so the network is visible to it.
final UidRange vpnRange = UidRange.createForUser(VPN_USER);
- mMockVpn.establish(lp, VPN_UID, Collections.singleton(vpnRange));
+ final Set<UidRange> vpnRanges = Collections.singleton(vpnRange);
+ mMockVpn.establish(lp, VPN_UID, vpnRanges);
+ assertVpnUidRangesUpdated(true, vpnRanges, VPN_UID);
reset(mMockNetd);
InOrder inOrder = inOrder(mMockNetd);
@@ -7743,6 +7845,7 @@
throws Exception {
final Set<UidRange> vpnRange = Collections.singleton(UidRange.createForUser(VPN_USER));
mMockVpn.establish(new LinkProperties(), vpnOwnerUid, vpnRange);
+ assertVpnUidRangesUpdated(true, vpnRange, vpnOwnerUid);
mMockVpn.setVpnType(vpnType);
final VpnInfo vpnInfo = new VpnInfo();
@@ -7947,8 +8050,7 @@
@Test
public void testCheckConnectivityDiagnosticsPermissionsNetworkStack() throws Exception {
final NetworkAgentInfo naiWithoutUid =
- new NetworkAgentInfo(
- null, null, null, null, null, new NetworkCapabilities(), 0,
+ new NetworkAgentInfo(null, null, null, null, new NetworkCapabilities(), 0,
mServiceContext, null, null, mService, null, null, null, 0, INVALID_UID);
mServiceContext.setPermission(
@@ -7963,8 +8065,7 @@
@Test
public void testCheckConnectivityDiagnosticsPermissionsWrongUidPackageName() throws Exception {
final NetworkAgentInfo naiWithoutUid =
- new NetworkAgentInfo(
- null, null, null, null, null, new NetworkCapabilities(), 0,
+ new NetworkAgentInfo(null, null, null, null, new NetworkCapabilities(), 0,
mServiceContext, null, null, mService, null, null, null, 0, INVALID_UID);
mServiceContext.setPermission(android.Manifest.permission.NETWORK_STACK, PERMISSION_DENIED);
@@ -7979,8 +8080,7 @@
@Test
public void testCheckConnectivityDiagnosticsPermissionsNoLocationPermission() throws Exception {
final NetworkAgentInfo naiWithoutUid =
- new NetworkAgentInfo(
- null, null, null, null, null, new NetworkCapabilities(), 0,
+ new NetworkAgentInfo(null, null, null, null, new NetworkCapabilities(), 0,
mServiceContext, null, null, mService, null, null, null, 0, INVALID_UID);
mServiceContext.setPermission(android.Manifest.permission.NETWORK_STACK, PERMISSION_DENIED);
@@ -7996,14 +8096,14 @@
public void testCheckConnectivityDiagnosticsPermissionsActiveVpn() throws Exception {
final Network network = new Network(NET_ID);
final NetworkAgentInfo naiWithoutUid =
- new NetworkAgentInfo(
- null, null, network, null, null, new NetworkCapabilities(), 0,
+ new NetworkAgentInfo(null, network, null, null, new NetworkCapabilities(), 0,
mServiceContext, null, null, mService, null, null, null, 0, INVALID_UID);
setupLocationPermissions(Build.VERSION_CODES.Q, true, AppOpsManager.OPSTR_FINE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION);
mMockVpn.establishForMyUid();
+ assertUidRangesUpdatedForMyUid(true);
// Wait for networks to connect and broadcasts to be sent before removing permissions.
waitForIdle();
@@ -8031,8 +8131,7 @@
final NetworkCapabilities nc = new NetworkCapabilities();
nc.setAdministratorUids(new int[] {Process.myUid()});
final NetworkAgentInfo naiWithUid =
- new NetworkAgentInfo(
- null, null, null, null, null, nc, 0, mServiceContext, null, null,
+ new NetworkAgentInfo(null, null, null, null, nc, 0, mServiceContext, null, null,
mService, null, null, null, 0, INVALID_UID);
setupLocationPermissions(Build.VERSION_CODES.Q, true, AppOpsManager.OPSTR_FINE_LOCATION,
@@ -8051,8 +8150,7 @@
nc.setOwnerUid(Process.myUid());
nc.setAdministratorUids(new int[] {Process.myUid()});
final NetworkAgentInfo naiWithUid =
- new NetworkAgentInfo(
- null, null, null, null, null, nc, 0, mServiceContext, null, null,
+ new NetworkAgentInfo(null, null, null, null, nc, 0, mServiceContext, null, null,
mService, null, null, null, 0, INVALID_UID);
setupLocationPermissions(Build.VERSION_CODES.Q, true, AppOpsManager.OPSTR_FINE_LOCATION,
@@ -8285,4 +8383,54 @@
assertTrue(isRequestIdInOrder);
}
}
+
+ private void assertUidRangesUpdatedForMyUid(boolean add) throws Exception {
+ final int uid = Process.myUid();
+ assertVpnUidRangesUpdated(add, uidRangesForUid(uid), uid);
+ }
+
+ private void assertVpnUidRangesUpdated(boolean add, Set<UidRange> vpnRanges, int exemptUid)
+ throws Exception {
+ InOrder inOrder = inOrder(mMockNetd);
+ ArgumentCaptor<int[]> exemptUidCaptor = ArgumentCaptor.forClass(int[].class);
+
+ inOrder.verify(mMockNetd, times(1)).socketDestroy(eq(toUidRangeStableParcels(vpnRanges)),
+ exemptUidCaptor.capture());
+ assertContainsExactly(exemptUidCaptor.getValue(), Process.VPN_UID, exemptUid);
+
+ if (add) {
+ inOrder.verify(mMockNetd, times(1)).networkAddUidRanges(eq(mMockVpn.getNetId()),
+ eq(toUidRangeStableParcels(vpnRanges)));
+ } else {
+ inOrder.verify(mMockNetd, times(1)).networkRemoveUidRanges(eq(mMockVpn.getNetId()),
+ eq(toUidRangeStableParcels(vpnRanges)));
+ }
+
+ inOrder.verify(mMockNetd, times(1)).socketDestroy(eq(toUidRangeStableParcels(vpnRanges)),
+ exemptUidCaptor.capture());
+ assertContainsExactly(exemptUidCaptor.getValue(), Process.VPN_UID, exemptUid);
+ }
+
+ @Test
+ public void testVpnUidRangesUpdate() throws Exception {
+ LinkProperties lp = new LinkProperties();
+ lp.setInterfaceName("tun0");
+ lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.ANY, 0), null));
+ lp.addRoute(new RouteInfo(new IpPrefix(Inet6Address.ANY, 0), null));
+ final UidRange vpnRange = UidRange.createForUser(VPN_USER);
+ Set<UidRange> vpnRanges = Collections.singleton(vpnRange);
+ mMockVpn.establish(lp, VPN_UID, vpnRanges);
+ assertVpnUidRangesUpdated(true, vpnRanges, VPN_UID);
+
+ reset(mMockNetd);
+ // Update to new range which is old range minus APP1, i.e. only APP2
+ final Set<UidRange> newRanges = new HashSet<>(Arrays.asList(
+ new UidRange(vpnRange.start, APP1_UID - 1),
+ new UidRange(APP1_UID + 1, vpnRange.stop)));
+ mMockVpn.setUids(newRanges);
+ waitForIdle();
+
+ assertVpnUidRangesUpdated(true, newRanges, VPN_UID);
+ assertVpnUidRangesUpdated(false, vpnRanges, VPN_UID);
+ }
}
diff --git a/tests/net/java/com/android/server/NetworkManagementServiceTest.java b/tests/net/java/com/android/server/NetworkManagementServiceTest.java
index ea763d2..13516d7 100644
--- a/tests/net/java/com/android/server/NetworkManagementServiceTest.java
+++ b/tests/net/java/com/android/server/NetworkManagementServiceTest.java
@@ -68,11 +68,12 @@
@SmallTest
public class NetworkManagementServiceTest {
private NetworkManagementService mNMService;
-
@Mock private Context mContext;
@Mock private IBatteryStats.Stub mBatteryStatsService;
@Mock private INetd.Stub mNetdService;
+ private static final int TEST_UID = 111;
+
@NonNull
@Captor
private ArgumentCaptor<INetdUnsolicitedEventListener> mUnsolListenerCaptor;
@@ -165,14 +166,14 @@
/**
* Interface class activity.
*/
- unsolListener.onInterfaceClassActivityChanged(true, 1, 1234, 0);
- expectSoon(observer).interfaceClassDataActivityChanged("1", true, 1234);
+ unsolListener.onInterfaceClassActivityChanged(true, 1, 1234, TEST_UID);
+ expectSoon(observer).interfaceClassDataActivityChanged(1, true, 1234, TEST_UID);
- unsolListener.onInterfaceClassActivityChanged(false, 9, 5678, 0);
- expectSoon(observer).interfaceClassDataActivityChanged("9", false, 5678);
+ unsolListener.onInterfaceClassActivityChanged(false, 9, 5678, TEST_UID);
+ expectSoon(observer).interfaceClassDataActivityChanged(9, false, 5678, TEST_UID);
- unsolListener.onInterfaceClassActivityChanged(false, 9, 4321, 0);
- expectSoon(observer).interfaceClassDataActivityChanged("9", false, 4321);
+ unsolListener.onInterfaceClassActivityChanged(false, 9, 4321, TEST_UID);
+ expectSoon(observer).interfaceClassDataActivityChanged(9, false, 4321, TEST_UID);
/**
* IP address changes.
@@ -222,8 +223,6 @@
assertFalse(mNMService.isFirewallEnabled());
}
- private static final int TEST_UID = 111;
-
@Test
public void testNetworkRestrictedDefault() {
assertFalse(mNMService.isNetworkRestricted(TEST_UID));
@@ -235,23 +234,23 @@
doReturn(true).when(mNetdService).bandwidthEnableDataSaver(anyBoolean());
// Restrict usage of mobile data in background
- mNMService.setUidMeteredNetworkDenylist(TEST_UID, true);
+ mNMService.setUidOnMeteredNetworkDenylist(TEST_UID, true);
assertTrue("Should be true since mobile data usage is restricted",
mNMService.isNetworkRestricted(TEST_UID));
mNMService.setDataSaverModeEnabled(true);
verify(mNetdService).bandwidthEnableDataSaver(true);
- mNMService.setUidMeteredNetworkDenylist(TEST_UID, false);
+ mNMService.setUidOnMeteredNetworkDenylist(TEST_UID, false);
assertTrue("Should be true since data saver is on and the uid is not allowlisted",
mNMService.isNetworkRestricted(TEST_UID));
- mNMService.setUidMeteredNetworkAllowlist(TEST_UID, true);
+ mNMService.setUidOnMeteredNetworkAllowlist(TEST_UID, true);
assertFalse("Should be false since data saver is on and the uid is allowlisted",
mNMService.isNetworkRestricted(TEST_UID));
// remove uid from allowlist and turn datasaver off again
- mNMService.setUidMeteredNetworkAllowlist(TEST_UID, false);
+ mNMService.setUidOnMeteredNetworkAllowlist(TEST_UID, false);
mNMService.setDataSaverModeEnabled(false);
verify(mNetdService).bandwidthEnableDataSaver(false);
assertFalse("Network should not be restricted when data saver is off",
diff --git a/tests/net/java/com/android/server/connectivity/IpConnectivityMetricsTest.java b/tests/net/java/com/android/server/connectivity/IpConnectivityMetricsTest.java
index 3a07166..8c5d1d6 100644
--- a/tests/net/java/com/android/server/connectivity/IpConnectivityMetricsTest.java
+++ b/tests/net/java/com/android/server/connectivity/IpConnectivityMetricsTest.java
@@ -124,6 +124,22 @@
assertEquals("", output2);
}
+ private void logDefaultNetworkEvent(long timeMs, NetworkAgentInfo nai,
+ NetworkAgentInfo oldNai) {
+ final Network network = (nai != null) ? nai.network() : null;
+ final int score = (nai != null) ? nai.getCurrentScore() : 0;
+ final boolean validated = (nai != null) ? nai.lastValidated : false;
+ final LinkProperties lp = (nai != null) ? nai.linkProperties : null;
+ final NetworkCapabilities nc = (nai != null) ? nai.networkCapabilities : null;
+
+ final Network prevNetwork = (oldNai != null) ? oldNai.network() : null;
+ final int prevScore = (oldNai != null) ? oldNai.getCurrentScore() : 0;
+ final LinkProperties prevLp = (oldNai != null) ? oldNai.linkProperties : null;
+ final NetworkCapabilities prevNc = (oldNai != null) ? oldNai.networkCapabilities : null;
+
+ mService.mDefaultNetworkMetrics.logDefaultNetworkEvent(timeMs, network, score, validated,
+ lp, nc, prevNetwork, prevScore, prevLp, prevNc);
+ }
@Test
public void testDefaultNetworkEvents() throws Exception {
final long cell = BitUtils.packBits(new int[]{NetworkCapabilities.TRANSPORT_CELLULAR});
@@ -147,7 +163,7 @@
for (NetworkAgentInfo[] pair : defaultNetworks) {
timeMs += durationMs;
durationMs += durationMs;
- mService.mDefaultNetworkMetrics.logDefaultNetworkEvent(timeMs, pair[1], pair[0]);
+ logDefaultNetworkEvent(timeMs, pair[1], pair[0]);
}
String want = String.join("\n",
@@ -331,8 +347,8 @@
final long wifi = BitUtils.packBits(new int[]{NetworkCapabilities.TRANSPORT_WIFI});
NetworkAgentInfo cellNai = makeNai(100, 50, false, true, cell);
NetworkAgentInfo wifiNai = makeNai(101, 60, true, false, wifi);
- mService.mDefaultNetworkMetrics.logDefaultNetworkEvent(timeMs + 200, cellNai, null);
- mService.mDefaultNetworkMetrics.logDefaultNetworkEvent(timeMs + 300, wifiNai, cellNai);
+ logDefaultNetworkEvent(timeMs + 200L, cellNai, null);
+ logDefaultNetworkEvent(timeMs + 300L, wifiNai, cellNai);
String want = String.join("\n",
"dropped_events: 0",
diff --git a/tests/net/java/com/android/server/connectivity/LingerMonitorTest.java b/tests/net/java/com/android/server/connectivity/LingerMonitorTest.java
index aafa18a..96c56e3 100644
--- a/tests/net/java/com/android/server/connectivity/LingerMonitorTest.java
+++ b/tests/net/java/com/android/server/connectivity/LingerMonitorTest.java
@@ -353,7 +353,7 @@
NetworkCapabilities caps = new NetworkCapabilities();
caps.addCapability(0);
caps.addTransportType(transport);
- NetworkAgentInfo nai = new NetworkAgentInfo(null, null, new Network(netId), info, null,
+ NetworkAgentInfo nai = new NetworkAgentInfo(null, new Network(netId), info, null,
caps, 50, mCtx, null, null /* config */, mConnService, mNetd, mDnsResolver, mNMS,
NetworkProvider.ID_NONE, Binder.getCallingUid());
nai.everValidated = true;
diff --git a/tests/net/java/com/android/server/connectivity/VpnTest.java b/tests/net/java/com/android/server/connectivity/VpnTest.java
index cc47317..02a2aad 100644
--- a/tests/net/java/com/android/server/connectivity/VpnTest.java
+++ b/tests/net/java/com/android/server/connectivity/VpnTest.java
@@ -27,7 +27,6 @@
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
-import static org.mockito.AdditionalMatchers.aryEq;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
@@ -89,6 +88,7 @@
import android.security.KeyStore;
import android.util.ArrayMap;
import android.util.ArraySet;
+import android.util.Range;
import androidx.test.filters.SmallTest;
import androidx.test.runner.AndroidJUnit4;
@@ -339,40 +339,26 @@
final Vpn vpn = createVpn(primaryUser.id);
final UidRange user = PRI_USER_RANGE;
- // Default state.
- assertUnblocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[1],
- user.start + PKG_UIDS[2], user.start + PKG_UIDS[3]);
-
// Set always-on without lockdown.
assertTrue(vpn.setAlwaysOnPackage(PKGS[1], false, null, mKeyStore));
- assertUnblocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[1],
- user.start + PKG_UIDS[2], user.start + PKG_UIDS[3]);
// Set always-on with lockdown.
assertTrue(vpn.setAlwaysOnPackage(PKGS[1], true, null, mKeyStore));
- verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(true, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start, user.start + PKG_UIDS[1] - 1),
new UidRangeParcel(user.start + PKG_UIDS[1] + 1, user.stop)
}));
- assertBlocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[2],
- user.start + PKG_UIDS[3]);
- assertUnblocked(vpn, user.start + PKG_UIDS[1]);
-
// Switch to another app.
assertTrue(vpn.setAlwaysOnPackage(PKGS[3], true, null, mKeyStore));
- verify(mNetd).networkRejectNonSecureVpn(eq(false), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(false, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start, user.start + PKG_UIDS[1] - 1),
new UidRangeParcel(user.start + PKG_UIDS[1] + 1, user.stop)
}));
-
- verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(true, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start, user.start + PKG_UIDS[3] - 1),
new UidRangeParcel(user.start + PKG_UIDS[3] + 1, user.stop)
}));
- assertBlocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[1],
- user.start + PKG_UIDS[2]);
- assertUnblocked(vpn, user.start + PKG_UIDS[3]);
}
@Test
@@ -383,64 +369,53 @@
// Set always-on with lockdown and allow app PKGS[2] from lockdown.
assertTrue(vpn.setAlwaysOnPackage(
PKGS[1], true, Collections.singletonList(PKGS[2]), mKeyStore));
- verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(true, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start, user.start + PKG_UIDS[1] - 1),
new UidRangeParcel(user.start + PKG_UIDS[2] + 1, user.stop)
}));
- assertBlocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[3]);
- assertUnblocked(vpn, user.start + PKG_UIDS[1], user.start + PKG_UIDS[2]);
// Change allowed app list to PKGS[3].
assertTrue(vpn.setAlwaysOnPackage(
PKGS[1], true, Collections.singletonList(PKGS[3]), mKeyStore));
- verify(mNetd).networkRejectNonSecureVpn(eq(false), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(false, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start + PKG_UIDS[2] + 1, user.stop)
}));
- verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(true, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start + PKG_UIDS[1] + 1, user.start + PKG_UIDS[3] - 1),
new UidRangeParcel(user.start + PKG_UIDS[3] + 1, user.stop)
}));
- assertBlocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[2]);
- assertUnblocked(vpn, user.start + PKG_UIDS[1], user.start + PKG_UIDS[3]);
// Change the VPN app.
assertTrue(vpn.setAlwaysOnPackage(
PKGS[0], true, Collections.singletonList(PKGS[3]), mKeyStore));
- verify(mNetd).networkRejectNonSecureVpn(eq(false), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(false, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start, user.start + PKG_UIDS[1] - 1),
new UidRangeParcel(user.start + PKG_UIDS[1] + 1, user.start + PKG_UIDS[3] - 1)
}));
- verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(true, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start, user.start + PKG_UIDS[0] - 1),
new UidRangeParcel(user.start + PKG_UIDS[0] + 1, user.start + PKG_UIDS[3] - 1)
}));
- assertBlocked(vpn, user.start + PKG_UIDS[1], user.start + PKG_UIDS[2]);
- assertUnblocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[3]);
// Remove the list of allowed packages.
assertTrue(vpn.setAlwaysOnPackage(PKGS[0], true, null, mKeyStore));
- verify(mNetd).networkRejectNonSecureVpn(eq(false), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(false, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start + PKG_UIDS[0] + 1, user.start + PKG_UIDS[3] - 1),
new UidRangeParcel(user.start + PKG_UIDS[3] + 1, user.stop)
}));
- verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(true, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start + PKG_UIDS[0] + 1, user.stop),
}));
- assertBlocked(vpn, user.start + PKG_UIDS[1], user.start + PKG_UIDS[2],
- user.start + PKG_UIDS[3]);
- assertUnblocked(vpn, user.start + PKG_UIDS[0]);
// Add the list of allowed packages.
assertTrue(vpn.setAlwaysOnPackage(
PKGS[0], true, Collections.singletonList(PKGS[1]), mKeyStore));
- verify(mNetd).networkRejectNonSecureVpn(eq(false), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(false, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start + PKG_UIDS[0] + 1, user.stop)
}));
- verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(new UidRangeParcel[] {
+ verify(mConnectivityManager).setRequireVpnForUids(true, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start + PKG_UIDS[0] + 1, user.start + PKG_UIDS[1] - 1),
new UidRangeParcel(user.start + PKG_UIDS[1] + 1, user.stop)
}));
- assertBlocked(vpn, user.start + PKG_UIDS[2], user.start + PKG_UIDS[3]);
- assertUnblocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[1]);
// Try allowing a package with a comma, should be rejected.
assertFalse(vpn.setAlwaysOnPackage(
@@ -450,78 +425,46 @@
// allowed package should change from PGKS[1] to PKGS[2].
assertTrue(vpn.setAlwaysOnPackage(
PKGS[0], true, Arrays.asList("com.foo.app", PKGS[2], "com.bar.app"), mKeyStore));
- verify(mNetd).networkRejectNonSecureVpn(eq(false), aryEq(new UidRangeParcel[]{
+ verify(mConnectivityManager).setRequireVpnForUids(false, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start + PKG_UIDS[0] + 1, user.start + PKG_UIDS[1] - 1),
new UidRangeParcel(user.start + PKG_UIDS[1] + 1, user.stop)
}));
- verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(new UidRangeParcel[]{
+ verify(mConnectivityManager).setRequireVpnForUids(true, toRanges(new UidRangeParcel[] {
new UidRangeParcel(user.start + PKG_UIDS[0] + 1, user.start + PKG_UIDS[2] - 1),
new UidRangeParcel(user.start + PKG_UIDS[2] + 1, user.stop)
}));
}
@Test
- public void testLockdownAddingAProfile() throws Exception {
- final Vpn vpn = createVpn(primaryUser.id);
- setMockedUsers(primaryUser);
-
- // Make a copy of the restricted profile, as we're going to mark it deleted halfway through.
- final UserInfo tempProfile = new UserInfo(restrictedProfileA.id, restrictedProfileA.name,
- restrictedProfileA.flags);
- tempProfile.restrictedProfileParentId = primaryUser.id;
-
- final UidRange user = PRI_USER_RANGE;
- final UidRange profile = UidRange.createForUser(tempProfile.id);
-
- // Set lockdown.
- assertTrue(vpn.setAlwaysOnPackage(PKGS[3], true, null, mKeyStore));
- verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(new UidRangeParcel[] {
- new UidRangeParcel(user.start, user.start + PKG_UIDS[3] - 1),
- new UidRangeParcel(user.start + PKG_UIDS[3] + 1, user.stop)
- }));
- // Verify restricted user isn't affected at first.
- assertUnblocked(vpn, profile.start + PKG_UIDS[0]);
-
- // Add the restricted user.
- setMockedUsers(primaryUser, tempProfile);
- vpn.onUserAdded(tempProfile.id);
- verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(new UidRangeParcel[] {
- new UidRangeParcel(profile.start, profile.start + PKG_UIDS[3] - 1),
- new UidRangeParcel(profile.start + PKG_UIDS[3] + 1, profile.stop)
- }));
-
- // Remove the restricted user.
- tempProfile.partial = true;
- vpn.onUserRemoved(tempProfile.id);
- verify(mNetd).networkRejectNonSecureVpn(eq(false), aryEq(new UidRangeParcel[] {
- new UidRangeParcel(profile.start, profile.start + PKG_UIDS[3] - 1),
- new UidRangeParcel(profile.start + PKG_UIDS[3] + 1, profile.stop)
- }));
- }
-
- @Test
public void testLockdownRuleRepeatability() throws Exception {
final Vpn vpn = createVpn(primaryUser.id);
final UidRangeParcel[] primaryUserRangeParcel = new UidRangeParcel[] {
new UidRangeParcel(PRI_USER_RANGE.start, PRI_USER_RANGE.stop)};
// Given legacy lockdown is already enabled,
vpn.setLockdown(true);
-
- verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(primaryUserRangeParcel));
+ verify(mConnectivityManager, times(1)).setRequireVpnForUids(true,
+ toRanges(primaryUserRangeParcel));
// Enabling legacy lockdown twice should do nothing.
vpn.setLockdown(true);
- verify(mNetd, times(1))
- .networkRejectNonSecureVpn(anyBoolean(), any(UidRangeParcel[].class));
+ verify(mConnectivityManager, times(1)).setRequireVpnForUids(anyBoolean(), any());
// And disabling should remove the rules exactly once.
vpn.setLockdown(false);
- verify(mNetd).networkRejectNonSecureVpn(eq(false), aryEq(primaryUserRangeParcel));
+ verify(mConnectivityManager, times(1)).setRequireVpnForUids(false,
+ toRanges(primaryUserRangeParcel));
// Removing the lockdown again should have no effect.
vpn.setLockdown(false);
- verify(mNetd, times(2)).networkRejectNonSecureVpn(
- anyBoolean(), any(UidRangeParcel[].class));
+ verify(mConnectivityManager, times(2)).setRequireVpnForUids(anyBoolean(), any());
+ }
+
+ private ArrayList<Range<Integer>> toRanges(UidRangeParcel[] ranges) {
+ ArrayList<Range<Integer>> rangesArray = new ArrayList<>(ranges.length);
+ for (int i = 0; i < ranges.length; i++) {
+ rangesArray.add(new Range<>(ranges[i].start, ranges[i].stop));
+ }
+ return rangesArray;
}
@Test
@@ -535,21 +478,21 @@
new UidRangeParcel(entireUser[0].start + PKG_UIDS[0] + 1, entireUser[0].stop)
};
- final InOrder order = inOrder(mNetd);
+ final InOrder order = inOrder(mConnectivityManager);
// Given lockdown is enabled with no package (legacy VPN),
vpn.setLockdown(true);
- order.verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(entireUser));
+ order.verify(mConnectivityManager).setRequireVpnForUids(true, toRanges(entireUser));
// When a new VPN package is set the rules should change to cover that package.
vpn.prepare(null, PKGS[0], VpnManager.TYPE_VPN_SERVICE);
- order.verify(mNetd).networkRejectNonSecureVpn(eq(false), aryEq(entireUser));
- order.verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(exceptPkg0));
+ order.verify(mConnectivityManager).setRequireVpnForUids(false, toRanges(entireUser));
+ order.verify(mConnectivityManager).setRequireVpnForUids(true, toRanges(exceptPkg0));
// When that VPN package is unset, everything should be undone again in reverse.
vpn.prepare(null, VpnConfig.LEGACY_VPN, VpnManager.TYPE_VPN_SERVICE);
- order.verify(mNetd).networkRejectNonSecureVpn(eq(false), aryEq(exceptPkg0));
- order.verify(mNetd).networkRejectNonSecureVpn(eq(true), aryEq(entireUser));
+ order.verify(mConnectivityManager).setRequireVpnForUids(false, toRanges(exceptPkg0));
+ order.verify(mConnectivityManager).setRequireVpnForUids(true, toRanges(entireUser));
}
@Test
@@ -1201,20 +1144,6 @@
return vpn;
}
- private static void assertBlocked(Vpn vpn, int... uids) {
- for (int uid : uids) {
- final boolean blocked = vpn.getLockdown() && vpn.isBlockingUid(uid);
- assertTrue("Uid " + uid + " should be blocked", blocked);
- }
- }
-
- private static void assertUnblocked(Vpn vpn, int... uids) {
- for (int uid : uids) {
- final boolean blocked = vpn.getLockdown() && vpn.isBlockingUid(uid);
- assertFalse("Uid " + uid + " should not be blocked", blocked);
- }
- }
-
/**
* Populate {@link #mUserManager} with a list of fake users.
*/
diff --git a/tests/net/java/com/android/server/net/NetworkStatsCollectionTest.java b/tests/net/java/com/android/server/net/NetworkStatsCollectionTest.java
index fb0cfc0..435c3c0 100644
--- a/tests/net/java/com/android/server/net/NetworkStatsCollectionTest.java
+++ b/tests/net/java/com/android/server/net/NetworkStatsCollectionTest.java
@@ -23,11 +23,11 @@
import static android.net.NetworkStats.UID_ALL;
import static android.net.NetworkStatsHistory.FIELD_ALL;
import static android.net.NetworkTemplate.buildTemplateMobileAll;
-import static android.net.NetworkUtils.multiplySafeByRational;
import static android.os.Process.myUid;
import static android.text.format.DateUtils.HOUR_IN_MILLIS;
import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
+import static com.android.internal.net.NetworkUtilsInternal.multiplySafeByRational;
import static com.android.testutils.MiscAsserts.assertThrows;
import static org.junit.Assert.assertArrayEquals;
@@ -64,7 +64,6 @@
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
@@ -124,7 +123,7 @@
// now export into a unified format
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- collection.write(new DataOutputStream(bos));
+ collection.write(bos);
// clear structure completely
collection.reset();
@@ -152,7 +151,7 @@
// now export into a unified format
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- collection.write(new DataOutputStream(bos));
+ collection.write(bos);
// clear structure completely
collection.reset();
@@ -180,7 +179,7 @@
// now export into a unified format
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- collection.write(new DataOutputStream(bos));
+ collection.write(bos);
// clear structure completely
collection.reset();
diff --git a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
index cd9406c..c783629 100644
--- a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
+++ b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
@@ -23,6 +23,7 @@
import static android.net.ConnectivityManager.TYPE_WIFI;
import static android.net.ConnectivityManager.TYPE_WIMAX;
import static android.net.NetworkStats.DEFAULT_NETWORK_ALL;
+import static android.net.NetworkStats.DEFAULT_NETWORK_NO;
import static android.net.NetworkStats.DEFAULT_NETWORK_YES;
import static android.net.NetworkStats.IFACE_ALL;
import static android.net.NetworkStats.INTERFACES_ALL;
@@ -917,7 +918,8 @@
public void testMetered() throws Exception {
// pretend that network comes online
expectDefaultSettings();
- NetworkState[] states = new NetworkState[] {buildWifiState(true /* isMetered */)};
+ NetworkState[] states =
+ new NetworkState[] {buildWifiState(true /* isMetered */, TEST_IFACE)};
expectNetworkStatsSummary(buildEmptyStats());
expectNetworkStatsUidDetail(buildEmptyStats());
@@ -1146,7 +1148,8 @@
public void testStatsProviderUpdateStats() throws Exception {
// Pretend that network comes online.
expectDefaultSettings();
- final NetworkState[] states = new NetworkState[]{buildWifiState(true /* isMetered */)};
+ final NetworkState[] states =
+ new NetworkState[]{buildWifiState(true /* isMetered */, TEST_IFACE)};
expectNetworkStatsSummary(buildEmptyStats());
expectNetworkStatsUidDetail(buildEmptyStats());
@@ -1206,7 +1209,8 @@
public void testStatsProviderSetAlert() throws Exception {
// Pretend that network comes online.
expectDefaultSettings();
- NetworkState[] states = new NetworkState[]{buildWifiState(true /* isMetered */)};
+ NetworkState[] states =
+ new NetworkState[]{buildWifiState(true /* isMetered */, TEST_IFACE)};
mService.forceUpdateIfaces(NETWORKS_WIFI, states, getActiveIface(states), new VpnInfo[0]);
// Register custom provider and retrieve callback.
@@ -1319,6 +1323,47 @@
assertUidTotal(templateAll, UID_RED, 22L + 35L, 26L + 29L, 19L + 7L, 5L + 11L, 1);
}
+ @Test
+ public void testOperationCount_nonDefault_traffic() throws Exception {
+ // Pretend mobile network comes online, but wifi is the default network.
+ expectDefaultSettings();
+ NetworkState[] states = new NetworkState[]{
+ buildWifiState(true /*isMetered*/, TEST_IFACE2), buildMobile3gState(IMSI_1)};
+ expectNetworkStatsUidDetail(buildEmptyStats());
+ mService.forceUpdateIfaces(NETWORKS_WIFI, states, getActiveIface(states), new VpnInfo[0]);
+
+ // Create some traffic on mobile network.
+ incrementCurrentTime(HOUR_IN_MILLIS);
+ expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 4)
+ .insertEntry(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 2L, 1L, 3L, 4L, 0L)
+ .insertEntry(TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_YES, 1L, 3L, 2L, 1L, 0L)
+ .insertEntry(TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 5L, 4L, 1L, 4L, 0L));
+ // Increment operation count, which must have a specific tag.
+ mService.incrementOperationCount(UID_RED, 0xF00D, 2);
+ forcePollAndWaitForIdle();
+
+ // Verify mobile summary is not changed by the operation count.
+ final NetworkTemplate templateMobile =
+ buildTemplateMobileWithRatType(null, NETWORK_TYPE_ALL);
+ final NetworkStats statsMobile = mSession.getSummaryForAllUid(
+ templateMobile, Long.MIN_VALUE, Long.MAX_VALUE, true);
+ assertValues(statsMobile, IFACE_ALL, UID_RED, SET_ALL, TAG_NONE, METERED_ALL, ROAMING_ALL,
+ DEFAULT_NETWORK_ALL, 3L, 4L, 5L, 5L, 0);
+ assertValues(statsMobile, IFACE_ALL, UID_RED, SET_ALL, 0xF00D, METERED_ALL, ROAMING_ALL,
+ DEFAULT_NETWORK_ALL, 5L, 4L, 1L, 4L, 0);
+
+ // Verify the operation count is blamed onto the default network.
+ // TODO: Blame onto the default network is not very reasonable. Consider blame onto the
+ // network that generates the traffic.
+ final NetworkTemplate templateWifi = buildTemplateWifiWildcard();
+ final NetworkStats statsWifi = mSession.getSummaryForAllUid(
+ templateWifi, Long.MIN_VALUE, Long.MAX_VALUE, true);
+ assertValues(statsWifi, IFACE_ALL, UID_RED, SET_ALL, 0xF00D, METERED_ALL, ROAMING_ALL,
+ DEFAULT_NETWORK_ALL, 0L, 0L, 0L, 0L, 2);
+ }
+
private static File getBaseDir(File statsDir) {
File baseDir = new File(statsDir, "netstats");
baseDir.mkdirs();
@@ -1446,14 +1491,14 @@
}
private static NetworkState buildWifiState() {
- return buildWifiState(false);
+ return buildWifiState(false, TEST_IFACE);
}
- private static NetworkState buildWifiState(boolean isMetered) {
+ private static NetworkState buildWifiState(boolean isMetered, @NonNull String iface) {
final NetworkInfo info = new NetworkInfo(TYPE_WIFI, 0, null, null);
info.setDetailedState(DetailedState.CONNECTED, null, null);
final LinkProperties prop = new LinkProperties();
- prop.setInterfaceName(TEST_IFACE);
+ prop.setInterfaceName(iface);
final NetworkCapabilities capabilities = new NetworkCapabilities();
capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED, !isMetered);
capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING, true);