Merge "Mark networks with OEM_PAID always restricted"
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index 3a8a254..40f47b0 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -453,133 +453,177 @@
public static final int TYPE_NONE = -1;
/**
- * The Mobile data connection. When active, all data traffic
- * will use this network type's interface by default
- * (it has a default route)
+ * A Mobile data connection. Devices may support more than one.
+ *
+ * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
+ * appropriate network. {@see NetworkCapabilities} for supported transports.
*/
+ @Deprecated
public static final int TYPE_MOBILE = 0;
+
/**
- * The WIFI data connection. When active, all data traffic
- * will use this network type's interface by default
- * (it has a default route).
+ * A WIFI data connection. Devices may support more than one.
+ *
+ * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
+ * appropriate network. {@see NetworkCapabilities} for supported transports.
*/
+ @Deprecated
public static final int TYPE_WIFI = 1;
+
/**
* An MMS-specific Mobile data connection. This network type may use the
* same network interface as {@link #TYPE_MOBILE} or it may use a different
* one. This is used by applications needing to talk to the carrier's
* Multimedia Messaging Service servers.
*
- * @deprecated Applications should instead use
+ * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
* {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
* provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
*/
@Deprecated
public static final int TYPE_MOBILE_MMS = 2;
+
/**
* A SUPL-specific Mobile data connection. This network type may use the
* same network interface as {@link #TYPE_MOBILE} or it may use a different
* one. This is used by applications needing to talk to the carrier's
* Secure User Plane Location servers for help locating the device.
*
- * @deprecated Applications should instead use
+ * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
* {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
* provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
*/
@Deprecated
public static final int TYPE_MOBILE_SUPL = 3;
+
/**
* A DUN-specific Mobile data connection. This network type may use the
* same network interface as {@link #TYPE_MOBILE} or it may use a different
* one. This is sometimes by the system when setting up an upstream connection
* for tethering so that the carrier is aware of DUN traffic.
+ *
+ * @deprecated Applications should instead use {@link NetworkCapabilities#hasCapability} or
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
+ * provides the {@link NetworkCapabilities#NET_CAPABILITY_DUN} capability.
*/
+ @Deprecated
public static final int TYPE_MOBILE_DUN = 4;
+
/**
* A High Priority Mobile data connection. This network type uses the
* same network interface as {@link #TYPE_MOBILE} but the routing setup
* is different.
*
- * @deprecated Applications should instead use
- * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
- * uses the {@link NetworkCapabilities#TRANSPORT_CELLULAR} transport.
+ * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
+ * appropriate network. {@see NetworkCapabilities} for supported transports.
*/
@Deprecated
public static final int TYPE_MOBILE_HIPRI = 5;
+
/**
- * The WiMAX data connection. When active, all data traffic
- * will use this network type's interface by default
- * (it has a default route).
+ * A WiMAX data connection.
+ *
+ * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
+ * appropriate network. {@see NetworkCapabilities} for supported transports.
*/
+ @Deprecated
public static final int TYPE_WIMAX = 6;
/**
- * The Bluetooth data connection. When active, all data traffic
- * will use this network type's interface by default
- * (it has a default route).
+ * A Bluetooth data connection.
+ *
+ * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
+ * appropriate network. {@see NetworkCapabilities} for supported transports.
*/
+ @Deprecated
public static final int TYPE_BLUETOOTH = 7;
/**
* Dummy data connection. This should not be used on shipping devices.
+ * @deprecated This is not used any more.
*/
+ @Deprecated
public static final int TYPE_DUMMY = 8;
/**
- * The Ethernet data connection. When active, all data traffic
- * will use this network type's interface by default
- * (it has a default route).
+ * An Ethernet data connection.
+ *
+ * @deprecated Applications should instead use {@link NetworkCapabilities#hasTransport} or
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request an
+ * appropriate network. {@see NetworkCapabilities} for supported transports.
*/
+ @Deprecated
public static final int TYPE_ETHERNET = 9;
/**
* Over the air Administration.
+ * @deprecated Use {@link NetworkCapabilities} instead.
* {@hide}
*/
+ @Deprecated
public static final int TYPE_MOBILE_FOTA = 10;
/**
* IP Multimedia Subsystem.
+ * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IMS} instead.
* {@hide}
*/
+ @Deprecated
public static final int TYPE_MOBILE_IMS = 11;
/**
* Carrier Branded Services.
+ * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_CBS} instead.
* {@hide}
*/
+ @Deprecated
public static final int TYPE_MOBILE_CBS = 12;
/**
* A Wi-Fi p2p connection. Only requesting processes will have access to
* the peers connected.
+ * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_WIFI_P2P} instead.
* {@hide}
*/
+ @Deprecated
public static final int TYPE_WIFI_P2P = 13;
/**
* The network to use for initially attaching to the network
+ * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_IA} instead.
* {@hide}
*/
+ @Deprecated
public static final int TYPE_MOBILE_IA = 14;
/**
* Emergency PDN connection for emergency services. This
* may include IMS and MMS in emergency situations.
+ * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_EIMS} instead.
* {@hide}
*/
+ @Deprecated
public static final int TYPE_MOBILE_EMERGENCY = 15;
/**
* The network that uses proxy to achieve connectivity.
+ * @deprecated Use {@link NetworkCapabilities} instead.
* {@hide}
*/
+ @Deprecated
public static final int TYPE_PROXY = 16;
/**
* A virtual network using one or more native bearers.
* It may or may not be providing security services.
+ * @deprecated Applications should use {@link NetworkCapabilities#TRANSPORT_VPN} instead.
*/
+ @Deprecated
public static final int TYPE_VPN = 17;
/** {@hide} */
@@ -686,8 +730,10 @@
* @param type the type needing naming
* @return a String for the given type, or a string version of the type ("87")
* if no name is known.
+ * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
* {@hide}
*/
+ @Deprecated
public static String getNetworkTypeName(int type) {
switch (type) {
case TYPE_NONE:
@@ -738,8 +784,10 @@
* This should be replaced in the future by a network property.
* @param networkType the type to check
* @return a boolean - {@code true} if uses cellular network, else {@code false}
+ * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
* {@hide}
*/
+ @Deprecated
public static boolean isNetworkTypeMobile(int networkType) {
switch (networkType) {
case TYPE_MOBILE:
@@ -761,8 +809,10 @@
/**
* Checks if the given network type is backed by a Wi-Fi radio.
*
+ * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
* @hide
*/
+ @Deprecated
public static boolean isNetworkTypeWifi(int networkType) {
switch (networkType) {
case TYPE_WIFI:
@@ -811,6 +861,10 @@
* You should always check {@link NetworkInfo#isConnected()} before initiating
* network traffic. This may return {@code null} when there is no default
* network.
+ * Note that if the default network is a VPN, this method will return the
+ * NetworkInfo for one of its underlying networks instead, or null if the
+ * VPN agent did not specify any. Apps interested in learning about VPNs
+ * should use {@link #getNetworkInfo(android.net.Network)} instead.
*
* @return a {@link NetworkInfo} object for the current default network
* or {@code null} if no default network is currently active
@@ -968,7 +1022,11 @@
* which you're interested.
* @return a {@link NetworkInfo} object for the requested
* network type or {@code null} if the type is not
- * supported by the device.
+ * supported by the device. If {@code networkType} is
+ * TYPE_VPN and a VPN is active for the calling app,
+ * then this method will try to return one of the
+ * underlying networks for the VPN or null if the
+ * VPN agent didn't specify any.
*
* @deprecated This method does not support multiple connected networks
* of the same type. Use {@link #getAllNetworks} and
@@ -1529,6 +1587,8 @@
* IllegalArgumentException if no mapping from the legacy type to
* NetworkCapabilities is known.
*
+ * @deprecated Types are deprecated. Use {@link NetworkCallback} or {@link NetworkRequest}
+ * to find the network instead.
* @hide
*/
public static NetworkCapabilities networkCapabilitiesForType(int type) {
@@ -1925,13 +1985,6 @@
* services.jar, possibly in com.android.server.net. */
/** {@hide} */
- public static final boolean checkChangePermission(Context context) {
- int uid = Binder.getCallingUid();
- return Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
- .getPackageNameForUid(context, uid), false /* throwException */);
- }
-
- /** {@hide} */
public static final void enforceChangePermission(Context context) {
int uid = Binder.getCallingUid();
Settings.checkAndNoteChangeNetworkStateOperation(context, uid, Settings
@@ -2380,6 +2433,7 @@
*
* @param networkType The type of network you want to report on
* @param percentage The quality of the connection 0 is bad, 100 is good
+ * @deprecated Types are deprecated. Use {@link #reportNetworkConnectivity} instead.
* {@hide}
*/
public void reportInetCondition(int networkType, int percentage) {
@@ -2511,9 +2565,10 @@
*
* @param networkType The network type we'd like to check
* @return {@code true} if supported, else {@code false}
- *
+ * @deprecated Types are deprecated. Use {@link NetworkCapabilities} instead.
* @hide
*/
+ @Deprecated
@RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE)
public boolean isNetworkSupported(int networkType) {
try {
diff --git a/core/java/android/net/NetworkCapabilities.java b/core/java/android/net/NetworkCapabilities.java
index cadd445..19f0c90 100644
--- a/core/java/android/net/NetworkCapabilities.java
+++ b/core/java/android/net/NetworkCapabilities.java
@@ -387,7 +387,7 @@
/**
* Removes (if found) the given capability from this {@code NetworkCapability} instance.
* <p>
- * Note that this method removes capabilities that was added via {@link #addCapability(int)},
+ * Note that this method removes capabilities that were added via {@link #addCapability(int)},
* {@link #addUnwantedCapability(int)} or {@link #setCapabilities(int[], int[])} .
*
* @param capability the capability to be removed.
@@ -476,6 +476,7 @@
&& ((mUnwantedNetworkCapabilities & (1 << capability)) != 0);
}
+ /** Note this method may result in having the same capability in wanted and unwanted lists. */
private void combineNetCapabilities(NetworkCapabilities nc) {
this.mNetworkCapabilities |= nc.mNetworkCapabilities;
this.mUnwantedNetworkCapabilities |= nc.mUnwantedNetworkCapabilities;
@@ -1142,7 +1143,11 @@
}
/**
- * Combine a set of Capabilities to this one. Useful for coming up with the complete set
+ * Combine a set of Capabilities to this one. Useful for coming up with the complete set.
+ * <p>
+ * Note that this method may break an invariant of having a particular capability in either
+ * wanted or unwanted lists but never in both. Requests that have the same capability in
+ * both lists will never be satisfied.
* @hide
*/
public void combineCapabilities(NetworkCapabilities nc) {
diff --git a/core/java/android/net/NetworkInfo.java b/core/java/android/net/NetworkInfo.java
index e6ad89a..999771a 100644
--- a/core/java/android/net/NetworkInfo.java
+++ b/core/java/android/net/NetworkInfo.java
@@ -38,14 +38,18 @@
* <table>
* <tr><td><b>Detailed state</b></td><td><b>Coarse-grained state</b></td></tr>
* <tr><td><code>IDLE</code></td><td><code>DISCONNECTED</code></td></tr>
- * <tr><td><code>SCANNING</code></td><td><code>CONNECTING</code></td></tr>
+ * <tr><td><code>SCANNING</code></td><td><code>DISCONNECTED</code></td></tr>
* <tr><td><code>CONNECTING</code></td><td><code>CONNECTING</code></td></tr>
* <tr><td><code>AUTHENTICATING</code></td><td><code>CONNECTING</code></td></tr>
+ * <tr><td><code>OBTAINING_IPADDR</code></td><td><code>CONNECTING</code></td></tr>
+ * <tr><td><code>VERIFYING_POOR_LINK</code></td><td><code>CONNECTING</code></td></tr>
+ * <tr><td><code>CAPTIVE_PORTAL_CHECK</code></td><td><code>CONNECTING</code></td></tr>
* <tr><td><code>CONNECTED</code></td><td><code>CONNECTED</code></td></tr>
+ * <tr><td><code>SUSPENDED</code></td><td><code>SUSPENDED</code></td></tr>
* <tr><td><code>DISCONNECTING</code></td><td><code>DISCONNECTING</code></td></tr>
* <tr><td><code>DISCONNECTED</code></td><td><code>DISCONNECTED</code></td></tr>
- * <tr><td><code>UNAVAILABLE</code></td><td><code>DISCONNECTED</code></td></tr>
* <tr><td><code>FAILED</code></td><td><code>DISCONNECTED</code></td></tr>
+ * <tr><td><code>BLOCKED</code></td><td><code>DISCONNECTED</code></td></tr>
* </table>
*/
public enum State {
@@ -163,8 +167,17 @@
* @return one of {@link ConnectivityManager#TYPE_MOBILE}, {@link
* ConnectivityManager#TYPE_WIFI}, {@link ConnectivityManager#TYPE_WIMAX}, {@link
* ConnectivityManager#TYPE_ETHERNET}, {@link ConnectivityManager#TYPE_BLUETOOTH}, or other
- * types defined by {@link ConnectivityManager}
+ * types defined by {@link ConnectivityManager}.
+ * @deprecated Callers should switch to checking {@link NetworkCapabilities#hasTransport}
+ * instead with one of the NetworkCapabilities#TRANSPORT_* constants :
+ * {@link #getType} and {@link #getTypeName} cannot account for networks using
+ * multiple transports. Note that generally apps should not care about transport;
+ * {@link NetworkCapabilities#NET_CAPABILITY_NOT_METERED} and
+ * {@link NetworkCapabilities#getLinkDownstreamBandwidthKbps} are calls that
+ * apps concerned with meteredness or bandwidth should be looking at, as they
+ * offer this information with much better accuracy.
*/
+ @Deprecated
public int getType() {
synchronized (this) {
return mNetworkType;
@@ -172,8 +185,10 @@
}
/**
+ * @deprecated Use {@link NetworkCapabilities} instead
* @hide
*/
+ @Deprecated
public void setType(int type) {
synchronized (this) {
mNetworkType = type;
@@ -205,7 +220,16 @@
* Return a human-readable name describe the type of the network,
* for example "WIFI" or "MOBILE".
* @return the name of the network type
+ * @deprecated Callers should switch to checking {@link NetworkCapabilities#hasTransport}
+ * instead with one of the NetworkCapabilities#TRANSPORT_* constants :
+ * {@link #getType} and {@link #getTypeName} cannot account for networks using
+ * multiple transports. Note that generally apps should not care about transport;
+ * {@link NetworkCapabilities#NET_CAPABILITY_NOT_METERED} and
+ * {@link NetworkCapabilities#getLinkDownstreamBandwidthKbps} are calls that
+ * apps concerned with meteredness or bandwidth should be looking at, as they
+ * offer this information with much better accuracy.
*/
+ @Deprecated
public String getTypeName() {
synchronized (this) {
return mTypeName;
@@ -230,7 +254,15 @@
* that the network is fully usable.
* @return {@code true} if network connectivity exists or is in the process
* of being established, {@code false} otherwise.
+ * @deprecated Apps should instead use the
+ * {@link android.net.ConnectivityManager.NetworkCallback} API to
+ * learn about connectivity changes.
+ * {@link ConnectivityManager#registerDefaultNetworkCallback} and
+ * {@link ConnectivityManager#registerNetworkCallback}. These will
+ * give a more accurate picture of the connectivity state of
+ * the device and let apps react more easily and quickly to changes.
*/
+ @Deprecated
public boolean isConnectedOrConnecting() {
synchronized (this) {
return mState == State.CONNECTED || mState == State.CONNECTING;
@@ -259,8 +291,18 @@
* data roaming has been disabled.</li>
* <li>The device's radio is turned off, e.g., because airplane mode is enabled.</li>
* </ul>
+ * Since Android L, this always returns {@code true}, because the system only
+ * returns info for available networks.
* @return {@code true} if the network is available, {@code false} otherwise
+ * @deprecated Apps should instead use the
+ * {@link android.net.ConnectivityManager.NetworkCallback} API to
+ * learn about connectivity changes.
+ * {@link ConnectivityManager#registerDefaultNetworkCallback} and
+ * {@link ConnectivityManager#registerNetworkCallback}. These will
+ * give a more accurate picture of the connectivity state of
+ * the device and let apps react more easily and quickly to changes.
*/
+ @Deprecated
public boolean isAvailable() {
synchronized (this) {
return mIsAvailable;
@@ -270,9 +312,11 @@
/**
* Sets if the network is available, ie, if the connectivity is possible.
* @param isAvailable the new availability value.
+ * @deprecated Use {@link NetworkCapabilities} instead
*
* @hide
*/
+ @Deprecated
public void setIsAvailable(boolean isAvailable) {
synchronized (this) {
mIsAvailable = isAvailable;
@@ -285,7 +329,10 @@
* network following a disconnect from another network.
* @return {@code true} if this is a failover attempt, {@code false}
* otherwise.
+ * @deprecated This field is not populated in recent Android releases,
+ * and does not make a lot of sense in a multi-network world.
*/
+ @Deprecated
public boolean isFailover() {
synchronized (this) {
return mIsFailover;
@@ -296,8 +343,10 @@
* Set the failover boolean.
* @param isFailover {@code true} to mark the current connection attempt
* as a failover.
+ * @deprecated This hasn't been set in any recent Android release.
* @hide
*/
+ @Deprecated
public void setFailover(boolean isFailover) {
synchronized (this) {
mIsFailover = isFailover;
@@ -322,7 +371,10 @@
}
}
- /** {@hide} */
+ /**
+ * @deprecated Use {@link NetworkCapabilities#NET_CAPABILITY_NOT_ROAMING} instead.
+ * {@hide}
+ */
@VisibleForTesting
@Deprecated
public void setRoaming(boolean isRoaming) {
@@ -334,7 +386,15 @@
/**
* Reports the current coarse-grained state of the network.
* @return the coarse-grained state
+ * @deprecated Apps should instead use the
+ * {@link android.net.ConnectivityManager.NetworkCallback} API to
+ * learn about connectivity changes.
+ * {@link ConnectivityManager#registerDefaultNetworkCallback} and
+ * {@link ConnectivityManager#registerNetworkCallback}. These will
+ * give a more accurate picture of the connectivity state of
+ * the device and let apps react more easily and quickly to changes.
*/
+ @Deprecated
public State getState() {
synchronized (this) {
return mState;
@@ -358,8 +418,10 @@
* if one was supplied. May be {@code null}.
* @param extraInfo an optional {@code String} providing addditional network state
* information passed up from the lower networking layers.
+ * @deprecated Use {@link NetworkCapabilities} instead.
* @hide
*/
+ @Deprecated
public void setDetailedState(DetailedState detailedState, String reason, String extraInfo) {
synchronized (this) {
this.mDetailedState = detailedState;
@@ -385,6 +447,8 @@
* Report the reason an attempt to establish connectivity failed,
* if one is available.
* @return the reason for failure, or null if not available
+ * @deprecated This method does not have a consistent contract that could make it useful
+ * to callers.
*/
public String getReason() {
synchronized (this) {
diff --git a/core/java/android/net/NetworkRequest.java b/core/java/android/net/NetworkRequest.java
index 96826f8..1ee0ed7 100644
--- a/core/java/android/net/NetworkRequest.java
+++ b/core/java/android/net/NetworkRequest.java
@@ -23,6 +23,7 @@
import android.text.TextUtils;
import java.util.Objects;
+import java.util.Set;
/**
* Defines a request for a network, made through {@link NetworkRequest.Builder} and used
@@ -204,6 +205,19 @@
}
/**
+ * Set the watched UIDs for this request. This will be reset and wiped out unless
+ * the calling app holds the CHANGE_NETWORK_STATE permission.
+ *
+ * @param uids The watched UIDs as a set of UidRanges, or null for everything.
+ * @return The builder to facilitate chaining.
+ * @hide
+ */
+ public Builder setUids(Set<UidRange> uids) {
+ mNetworkCapabilities.setUids(uids);
+ return this;
+ }
+
+ /**
* Add a capability that must not exist in the requested network.
* <p>
* If the capability was previously added to the list of required capabilities (for
diff --git a/services/core/java/com/android/server/ConnectivityService.java b/services/core/java/com/android/server/ConnectivityService.java
index 6c24e94..ae7ac8f 100644
--- a/services/core/java/com/android/server/ConnectivityService.java
+++ b/services/core/java/com/android/server/ConnectivityService.java
@@ -1356,6 +1356,12 @@
}
}
+ private void restrictBackgroundRequestForCaller(NetworkCapabilities nc) {
+ if (!mPermissionMonitor.hasUseBackgroundNetworksPermission(Binder.getCallingUid())) {
+ nc.addCapability(NET_CAPABILITY_FOREGROUND);
+ }
+ }
+
@Override
public NetworkState[] getAllNetworkState() {
// Require internal since we're handing out IMSI details
@@ -4365,15 +4371,13 @@
NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
restrictRequestUidsForCaller(nc);
- if (!ConnectivityManager.checkChangePermission(mContext)) {
- // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
- // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
- // onLost and onAvailable callbacks when networks move in and out of the background.
- // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
- // can't request networks.
- nc.addCapability(NET_CAPABILITY_FOREGROUND);
- }
- ensureValidNetworkSpecifier(networkCapabilities);
+ // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
+ // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
+ // onLost and onAvailable callbacks when networks move in and out of the background.
+ // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
+ // can't request networks.
+ restrictBackgroundRequestForCaller(nc);
+ ensureValidNetworkSpecifier(nc);
NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
NetworkRequest.Type.LISTEN);
@@ -4531,17 +4535,17 @@
return nai.network.netId;
}
- private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
+ private void handleRegisterNetworkAgent(NetworkAgentInfo nai) {
if (VDBG) log("Got NetworkAgent Messenger");
- mNetworkAgentInfos.put(na.messenger, na);
+ mNetworkAgentInfos.put(nai.messenger, nai);
synchronized (mNetworkForNetId) {
- mNetworkForNetId.put(na.network.netId, na);
+ mNetworkForNetId.put(nai.network.netId, nai);
}
- na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
- NetworkInfo networkInfo = na.networkInfo;
- na.networkInfo = null;
- updateNetworkInfo(na, networkInfo);
- updateUids(na, null, na.networkCapabilities);
+ nai.asyncChannel.connect(mContext, mTrackerHandler, nai.messenger);
+ NetworkInfo networkInfo = nai.networkInfo;
+ nai.networkInfo = null;
+ updateNetworkInfo(nai, networkInfo);
+ updateUids(nai, null, nai.networkCapabilities);
}
private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
@@ -5268,7 +5272,6 @@
for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
final String stackedIface = stacked.getInterfaceName();
bs.noteNetworkInterfaceType(stackedIface, type);
- NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
}
} catch (RemoteException ignored) {
}
diff --git a/services/core/java/com/android/server/connectivity/DnsManager.java b/services/core/java/com/android/server/connectivity/DnsManager.java
index 557828a..36f5a6c 100644
--- a/services/core/java/com/android/server/connectivity/DnsManager.java
+++ b/services/core/java/com/android/server/connectivity/DnsManager.java
@@ -192,6 +192,12 @@
public void setDnsConfigurationForNetwork(
int netId, LinkProperties lp, boolean isDefaultNetwork) {
+ final String[] assignedServers = NetworkUtils.makeStrings(lp.getDnsServers());
+ final String[] domainStrs = getDomainStrings(lp.getDomains());
+
+ updateParametersSettings();
+ final int[] params = { mSampleValidity, mSuccessThreshold, mMinSamples, mMaxSamples };
+
// We only use the PrivateDnsConfig data pushed to this class instance
// from ConnectivityService because it works in coordination with
// NetworkMonitor to decide which networks need validation and runs the
@@ -204,23 +210,20 @@
final boolean useTls = (privateDnsCfg != null) && privateDnsCfg.useTls;
final boolean strictMode = (privateDnsCfg != null) && privateDnsCfg.inStrictMode();
final String tlsHostname = strictMode ? privateDnsCfg.hostname : "";
-
- final String[] serverStrs = NetworkUtils.makeStrings(
- strictMode ? Arrays.stream(privateDnsCfg.ips)
- .filter((ip) -> lp.isReachable(ip))
- .collect(Collectors.toList())
- : lp.getDnsServers());
- final String[] domainStrs = getDomainStrings(lp.getDomains());
-
- updateParametersSettings();
- final int[] params = { mSampleValidity, mSuccessThreshold, mMinSamples, mMaxSamples };
+ final String[] tlsServers =
+ strictMode ? NetworkUtils.makeStrings(
+ Arrays.stream(privateDnsCfg.ips)
+ .filter((ip) -> lp.isReachable(ip))
+ .collect(Collectors.toList()))
+ : useTls ? assignedServers // Opportunistic
+ : new String[0]; // Off
Slog.d(TAG, String.format("setDnsConfigurationForNetwork(%d, %s, %s, %s, %s, %s)",
- netId, Arrays.toString(serverStrs), Arrays.toString(domainStrs),
- Arrays.toString(params), useTls, tlsHostname));
+ netId, Arrays.toString(assignedServers), Arrays.toString(domainStrs),
+ Arrays.toString(params), tlsHostname, Arrays.toString(tlsServers)));
try {
mNMS.setDnsConfigurationForNetwork(
- netId, serverStrs, domainStrs, params, useTls, tlsHostname);
+ netId, assignedServers, domainStrs, params, tlsHostname, tlsServers);
} catch (Exception e) {
Slog.e(TAG, "Error setting DNS configuration: " + e);
return;
diff --git a/services/core/java/com/android/server/connectivity/PermissionMonitor.java b/services/core/java/com/android/server/connectivity/PermissionMonitor.java
index e084ff8..d578e95 100644
--- a/services/core/java/com/android/server/connectivity/PermissionMonitor.java
+++ b/services/core/java/com/android/server/connectivity/PermissionMonitor.java
@@ -19,6 +19,7 @@
import static android.Manifest.permission.CHANGE_NETWORK_STATE;
import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
import static android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS;
+import static android.Manifest.permission.NETWORK_STACK;
import static android.content.pm.ApplicationInfo.FLAG_SYSTEM;
import static android.content.pm.ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
import static android.content.pm.PackageManager.GET_PERMISSIONS;
@@ -27,6 +28,7 @@
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
+import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
@@ -39,6 +41,8 @@
import android.text.TextUtils;
import android.util.Log;
+import com.android.internal.annotations.VisibleForTesting;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
@@ -150,7 +154,14 @@
update(mUsers, mApps, true);
}
- private boolean hasPermission(PackageInfo app, String permission) {
+ @VisibleForTesting
+ boolean isPreinstalledSystemApp(PackageInfo app) {
+ int flags = app.applicationInfo != null ? app.applicationInfo.flags : 0;
+ return (flags & (FLAG_SYSTEM | FLAG_UPDATED_SYSTEM_APP)) != 0;
+ }
+
+ @VisibleForTesting
+ boolean hasPermission(PackageInfo app, String permission) {
if (app.requestedPermissions != null) {
for (String p : app.requestedPermissions) {
if (permission.equals(p)) {
@@ -166,14 +177,40 @@
}
private boolean hasRestrictedNetworkPermission(PackageInfo app) {
- int flags = app.applicationInfo != null ? app.applicationInfo.flags : 0;
- if ((flags & FLAG_SYSTEM) != 0 || (flags & FLAG_UPDATED_SYSTEM_APP) != 0) {
- return true;
- }
+ if (isPreinstalledSystemApp(app)) return true;
return hasPermission(app, CONNECTIVITY_INTERNAL)
|| hasPermission(app, CONNECTIVITY_USE_RESTRICTED_NETWORKS);
}
+ private boolean hasUseBackgroundNetworksPermission(PackageInfo app) {
+ // This function defines what it means to hold the permission to use
+ // background networks.
+ return hasPermission(app, CHANGE_NETWORK_STATE)
+ || hasPermission(app, CONNECTIVITY_USE_RESTRICTED_NETWORKS)
+ || hasPermission(app, CONNECTIVITY_INTERNAL)
+ || hasPermission(app, NETWORK_STACK)
+ // TODO : remove this check (b/31479477). Not all preinstalled apps should
+ // have access to background networks, they should just request the appropriate
+ // permission for their use case from the list above.
+ || isPreinstalledSystemApp(app);
+ }
+
+ public boolean hasUseBackgroundNetworksPermission(int uid) {
+ final String[] names = mPackageManager.getPackagesForUid(uid);
+ if (null == names || names.length == 0) return false;
+ try {
+ // Only using the first package name. There may be multiple names if multiple
+ // apps share the same UID, but in that case they also share permissions so
+ // querying with any of the names will return the same results.
+ final PackageInfo app = mPackageManager.getPackageInfo(names[0], GET_PERMISSIONS);
+ return hasUseBackgroundNetworksPermission(app);
+ } catch (NameNotFoundException e) {
+ // App not found.
+ loge("NameNotFoundException " + names[0], e);
+ return false;
+ }
+ }
+
private int[] toIntArray(List<Integer> list) {
int[] array = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
@@ -308,4 +345,8 @@
private static void loge(String s) {
Log.e(TAG, s);
}
+
+ private static void loge(String s, Throwable e) {
+ Log.e(TAG, s, e);
+ }
}
diff --git a/tests/net/java/android/net/IpSecAlgorithmTest.java b/tests/net/java/android/net/IpSecAlgorithmTest.java
index 6bdfdc6..85e8361 100644
--- a/tests/net/java/android/net/IpSecAlgorithmTest.java
+++ b/tests/net/java/android/net/IpSecAlgorithmTest.java
@@ -22,8 +22,12 @@
import android.os.Parcel;
import android.support.test.filters.SmallTest;
import android.support.test.runner.AndroidJUnit4;
+
+import java.util.AbstractMap.SimpleEntry;
import java.util.Arrays;
+import java.util.Map.Entry;
import java.util.Random;
+
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -40,19 +44,29 @@
};
@Test
- public void testDefaultTruncLen() throws Exception {
- IpSecAlgorithm explicit =
+ public void testNoTruncLen() throws Exception {
+ Entry<String, Integer>[] authAndAeadList =
+ new Entry[] {
+ new SimpleEntry<>(IpSecAlgorithm.AUTH_HMAC_MD5, 128),
+ new SimpleEntry<>(IpSecAlgorithm.AUTH_HMAC_SHA1, 160),
+ new SimpleEntry<>(IpSecAlgorithm.AUTH_HMAC_SHA256, 256),
+ new SimpleEntry<>(IpSecAlgorithm.AUTH_HMAC_SHA384, 384),
+ new SimpleEntry<>(IpSecAlgorithm.AUTH_HMAC_SHA512, 512),
+ new SimpleEntry<>(IpSecAlgorithm.AUTH_CRYPT_AES_GCM, 224)
+ };
+
+ // Expect auth and aead algorithms to throw errors if trunclen is omitted.
+ for (Entry<String, Integer> algData : authAndAeadList) {
+ try {
new IpSecAlgorithm(
- IpSecAlgorithm.AUTH_HMAC_SHA256, Arrays.copyOf(KEY_MATERIAL, 256 / 8), 256);
- IpSecAlgorithm implicit =
- new IpSecAlgorithm(
- IpSecAlgorithm.AUTH_HMAC_SHA256, Arrays.copyOf(KEY_MATERIAL, 256 / 8));
- assertTrue(
- "Default Truncation Length Incorrect, Explicit: "
- + explicit
- + "implicit: "
- + implicit,
- IpSecAlgorithm.equals(explicit, implicit));
+ algData.getKey(), Arrays.copyOf(KEY_MATERIAL, algData.getValue() / 8));
+ fail("Expected exception on unprovided auth trunclen");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ // Ensure crypt works with no truncation length supplied.
+ new IpSecAlgorithm(IpSecAlgorithm.CRYPT_AES_CBC, Arrays.copyOf(KEY_MATERIAL, 256 / 8));
}
@Test
diff --git a/tests/net/java/android/net/IpSecConfigTest.java b/tests/net/java/android/net/IpSecConfigTest.java
index f186ee5..771faaf 100644
--- a/tests/net/java/android/net/IpSecConfigTest.java
+++ b/tests/net/java/android/net/IpSecConfigTest.java
@@ -62,7 +62,8 @@
c.setAuthentication(
new IpSecAlgorithm(
IpSecAlgorithm.AUTH_HMAC_MD5,
- new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0}));
+ new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0},
+ 128));
c.setAuthenticatedEncryption(
new IpSecAlgorithm(
IpSecAlgorithm.AUTH_CRYPT_AES_GCM,
diff --git a/tests/net/java/android/net/IpSecManagerTest.java b/tests/net/java/android/net/IpSecManagerTest.java
index cc3366f..970596d 100644
--- a/tests/net/java/android/net/IpSecManagerTest.java
+++ b/tests/net/java/android/net/IpSecManagerTest.java
@@ -50,13 +50,18 @@
private static final int TEST_UDP_ENCAP_PORT = 34567;
private static final int DROID_SPI = 0xD1201D;
+ private static final int DUMMY_RESOURCE_ID = 0x1234;
private static final InetAddress GOOGLE_DNS_4;
+ private static final String VTI_INTF_NAME = "ipsec_test";
+ private static final InetAddress VTI_LOCAL_ADDRESS;
+ private static final LinkAddress VTI_INNER_ADDRESS = new LinkAddress("10.0.1.1/24");
static {
try {
// Google Public DNS Addresses;
GOOGLE_DNS_4 = InetAddress.getByName("8.8.8.8");
+ VTI_LOCAL_ADDRESS = InetAddress.getByName("8.8.4.4");
} catch (UnknownHostException e) {
throw new RuntimeException("Could not resolve DNS Addresses", e);
}
@@ -77,9 +82,8 @@
*/
@Test
public void testAllocSpi() throws Exception {
- int resourceId = 1;
IpSecSpiResponse spiResp =
- new IpSecSpiResponse(IpSecManager.Status.OK, resourceId, DROID_SPI);
+ new IpSecSpiResponse(IpSecManager.Status.OK, DUMMY_RESOURCE_ID, DROID_SPI);
when(mMockIpSecService.allocateSecurityParameterIndex(
eq(GOOGLE_DNS_4.getHostAddress()),
eq(DROID_SPI),
@@ -92,14 +96,13 @@
droidSpi.close();
- verify(mMockIpSecService).releaseSecurityParameterIndex(resourceId);
+ verify(mMockIpSecService).releaseSecurityParameterIndex(DUMMY_RESOURCE_ID);
}
@Test
public void testAllocRandomSpi() throws Exception {
- int resourceId = 1;
IpSecSpiResponse spiResp =
- new IpSecSpiResponse(IpSecManager.Status.OK, resourceId, DROID_SPI);
+ new IpSecSpiResponse(IpSecManager.Status.OK, DUMMY_RESOURCE_ID, DROID_SPI);
when(mMockIpSecService.allocateSecurityParameterIndex(
eq(GOOGLE_DNS_4.getHostAddress()),
eq(IpSecManager.INVALID_SECURITY_PARAMETER_INDEX),
@@ -113,7 +116,7 @@
randomSpi.close();
- verify(mMockIpSecService).releaseSecurityParameterIndex(resourceId);
+ verify(mMockIpSecService).releaseSecurityParameterIndex(DUMMY_RESOURCE_ID);
}
/*
@@ -165,11 +168,10 @@
@Test
public void testOpenEncapsulationSocket() throws Exception {
- int resourceId = 1;
IpSecUdpEncapResponse udpEncapResp =
new IpSecUdpEncapResponse(
IpSecManager.Status.OK,
- resourceId,
+ DUMMY_RESOURCE_ID,
TEST_UDP_ENCAP_PORT,
Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP));
when(mMockIpSecService.openUdpEncapsulationSocket(eq(TEST_UDP_ENCAP_PORT), anyObject()))
@@ -177,21 +179,20 @@
IpSecManager.UdpEncapsulationSocket encapSocket =
mIpSecManager.openUdpEncapsulationSocket(TEST_UDP_ENCAP_PORT);
- assertNotNull(encapSocket.getSocket());
+ assertNotNull(encapSocket.getFileDescriptor());
assertEquals(TEST_UDP_ENCAP_PORT, encapSocket.getPort());
encapSocket.close();
- verify(mMockIpSecService).closeUdpEncapsulationSocket(resourceId);
+ verify(mMockIpSecService).closeUdpEncapsulationSocket(DUMMY_RESOURCE_ID);
}
@Test
public void testOpenEncapsulationSocketOnRandomPort() throws Exception {
- int resourceId = 1;
IpSecUdpEncapResponse udpEncapResp =
new IpSecUdpEncapResponse(
IpSecManager.Status.OK,
- resourceId,
+ DUMMY_RESOURCE_ID,
TEST_UDP_ENCAP_PORT,
Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP));
@@ -201,12 +202,12 @@
IpSecManager.UdpEncapsulationSocket encapSocket =
mIpSecManager.openUdpEncapsulationSocket();
- assertNotNull(encapSocket.getSocket());
+ assertNotNull(encapSocket.getFileDescriptor());
assertEquals(TEST_UDP_ENCAP_PORT, encapSocket.getPort());
encapSocket.close();
- verify(mMockIpSecService).closeUdpEncapsulationSocket(resourceId);
+ verify(mMockIpSecService).closeUdpEncapsulationSocket(DUMMY_RESOURCE_ID);
}
@Test
@@ -219,4 +220,45 @@
}
// TODO: add test when applicable transform builder interface is available
-}
+
+ private IpSecManager.IpSecTunnelInterface createAndValidateVti(int resourceId, String intfName)
+ throws Exception {
+ IpSecTunnelInterfaceResponse dummyResponse =
+ new IpSecTunnelInterfaceResponse(IpSecManager.Status.OK, resourceId, intfName);
+ when(mMockIpSecService.createTunnelInterface(
+ eq(VTI_LOCAL_ADDRESS.getHostAddress()), eq(GOOGLE_DNS_4.getHostAddress()),
+ anyObject(), anyObject()))
+ .thenReturn(dummyResponse);
+
+ IpSecManager.IpSecTunnelInterface tunnelIntf = mIpSecManager.createIpSecTunnelInterface(
+ VTI_LOCAL_ADDRESS, GOOGLE_DNS_4, mock(Network.class));
+
+ assertNotNull(tunnelIntf);
+ return tunnelIntf;
+ }
+
+ @Test
+ public void testCreateVti() throws Exception {
+ IpSecManager.IpSecTunnelInterface tunnelIntf =
+ createAndValidateVti(DUMMY_RESOURCE_ID, VTI_INTF_NAME);
+
+ assertEquals(VTI_INTF_NAME, tunnelIntf.getInterfaceName());
+
+ tunnelIntf.close();
+ verify(mMockIpSecService).deleteTunnelInterface(eq(DUMMY_RESOURCE_ID));
+ }
+
+ @Test
+ public void testAddRemoveAddressesFromVti() throws Exception {
+ IpSecManager.IpSecTunnelInterface tunnelIntf =
+ createAndValidateVti(DUMMY_RESOURCE_ID, VTI_INTF_NAME);
+
+ tunnelIntf.addAddress(VTI_INNER_ADDRESS);
+ verify(mMockIpSecService)
+ .addAddressToTunnelInterface(eq(DUMMY_RESOURCE_ID), eq(VTI_INNER_ADDRESS));
+
+ tunnelIntf.removeAddress(VTI_INNER_ADDRESS);
+ verify(mMockIpSecService)
+ .addAddressToTunnelInterface(eq(DUMMY_RESOURCE_ID), eq(VTI_INNER_ADDRESS));
+ }
+}
\ No newline at end of file
diff --git a/tests/net/java/android/net/NetworkCapabilitiesTest.java b/tests/net/java/android/net/NetworkCapabilitiesTest.java
index cc51b8e..0696592 100644
--- a/tests/net/java/android/net/NetworkCapabilitiesTest.java
+++ b/tests/net/java/android/net/NetworkCapabilitiesTest.java
@@ -305,7 +305,7 @@
assertTrue("Request: " + request + ", Network:" + network,
request.satisfiedByNetworkCapabilities(network));
- // Adding capabilities that doesn't exist in the network anyway
+ // Requesting absence of capabilities that network doesn't have. Request should satisfy.
request.addUnwantedCapability(NET_CAPABILITY_WIFI_P2P);
request.addUnwantedCapability(NET_CAPABILITY_NOT_METERED);
assertTrue(request.satisfiedByNetworkCapabilities(network));
@@ -321,7 +321,6 @@
assertTrue(request.hasUnwantedCapability(NET_CAPABILITY_NOT_RESTRICTED));
assertFalse(request.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
-
// Now this request won't be satisfied because network contains NOT_RESTRICTED.
assertFalse(request.satisfiedByNetworkCapabilities(network));
network.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
diff --git a/tests/net/java/android/net/NetworkStatsTest.java b/tests/net/java/android/net/NetworkStatsTest.java
index 035a4cd..8f18d07 100644
--- a/tests/net/java/android/net/NetworkStatsTest.java
+++ b/tests/net/java/android/net/NetworkStatsTest.java
@@ -19,6 +19,7 @@
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.INTERFACES_ALL;
import static android.net.NetworkStats.METERED_ALL;
import static android.net.NetworkStats.METERED_NO;
import static android.net.NetworkStats.METERED_YES;
@@ -31,14 +32,17 @@
import static android.net.NetworkStats.SET_DBG_VPN_OUT;
import static android.net.NetworkStats.SET_ALL;
import static android.net.NetworkStats.IFACE_ALL;
+import static android.net.NetworkStats.TAG_ALL;
import static android.net.NetworkStats.TAG_NONE;
import static android.net.NetworkStats.UID_ALL;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
+import android.os.Process;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.filters.SmallTest;
+import android.util.ArrayMap;
import com.google.android.collect.Sets;
@@ -641,6 +645,218 @@
ROAMING_ALL, DEFAULT_NETWORK_ALL, 50500L, 27L, 100200L, 55, 0);
}
+ @Test
+ public void testFilter_NoFilter() {
+ NetworkStats.Entry entry1 = new NetworkStats.Entry(
+ "test1", 10100, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats.Entry entry2 = new NetworkStats.Entry(
+ "test2", 10101, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats.Entry entry3 = new NetworkStats.Entry(
+ "test2", 10101, SET_DEFAULT, 123, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats stats = new NetworkStats(TEST_START, 3)
+ .addValues(entry1)
+ .addValues(entry2)
+ .addValues(entry3);
+
+ stats.filter(UID_ALL, INTERFACES_ALL, TAG_ALL);
+ assertEquals(3, stats.size());
+ assertEquals(entry1, stats.getValues(0, null));
+ assertEquals(entry2, stats.getValues(1, null));
+ assertEquals(entry3, stats.getValues(2, null));
+ }
+
+ @Test
+ public void testFilter_UidFilter() {
+ final int testUid = 10101;
+ NetworkStats.Entry entry1 = new NetworkStats.Entry(
+ "test1", 10100, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats.Entry entry2 = new NetworkStats.Entry(
+ "test2", testUid, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats.Entry entry3 = new NetworkStats.Entry(
+ "test2", testUid, SET_DEFAULT, 123, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats stats = new NetworkStats(TEST_START, 3)
+ .addValues(entry1)
+ .addValues(entry2)
+ .addValues(entry3);
+
+ stats.filter(testUid, INTERFACES_ALL, TAG_ALL);
+ assertEquals(2, stats.size());
+ assertEquals(entry2, stats.getValues(0, null));
+ assertEquals(entry3, stats.getValues(1, null));
+ }
+
+ @Test
+ public void testFilter_InterfaceFilter() {
+ final String testIf1 = "testif1";
+ final String testIf2 = "testif2";
+ NetworkStats.Entry entry1 = new NetworkStats.Entry(
+ testIf1, 10100, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats.Entry entry2 = new NetworkStats.Entry(
+ "otherif", 10101, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats.Entry entry3 = new NetworkStats.Entry(
+ testIf1, 10101, SET_DEFAULT, 123, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats.Entry entry4 = new NetworkStats.Entry(
+ testIf2, 10101, SET_DEFAULT, 123, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats stats = new NetworkStats(TEST_START, 4)
+ .addValues(entry1)
+ .addValues(entry2)
+ .addValues(entry3)
+ .addValues(entry4);
+
+ stats.filter(UID_ALL, new String[] { testIf1, testIf2 }, TAG_ALL);
+ assertEquals(3, stats.size());
+ assertEquals(entry1, stats.getValues(0, null));
+ assertEquals(entry3, stats.getValues(1, null));
+ assertEquals(entry4, stats.getValues(2, null));
+ }
+
+ @Test
+ public void testFilter_EmptyInterfaceFilter() {
+ NetworkStats.Entry entry1 = new NetworkStats.Entry(
+ "if1", 10100, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats.Entry entry2 = new NetworkStats.Entry(
+ "if2", 10101, SET_DEFAULT, TAG_NONE, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats stats = new NetworkStats(TEST_START, 3)
+ .addValues(entry1)
+ .addValues(entry2);
+
+ stats.filter(UID_ALL, new String[] { }, TAG_ALL);
+ assertEquals(0, stats.size());
+ }
+
+ @Test
+ public void testFilter_TagFilter() {
+ final int testTag = 123;
+ final int otherTag = 456;
+ NetworkStats.Entry entry1 = new NetworkStats.Entry(
+ "test1", 10100, SET_DEFAULT, testTag, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats.Entry entry2 = new NetworkStats.Entry(
+ "test2", 10101, SET_DEFAULT, testTag, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats.Entry entry3 = new NetworkStats.Entry(
+ "test2", 10101, SET_DEFAULT, otherTag, METERED_NO, ROAMING_NO,
+ DEFAULT_NETWORK_NO, 50000L, 25L, 100000L, 50L, 0L);
+
+ NetworkStats stats = new NetworkStats(TEST_START, 3)
+ .addValues(entry1)
+ .addValues(entry2)
+ .addValues(entry3);
+
+ stats.filter(UID_ALL, INTERFACES_ALL, testTag);
+ assertEquals(2, stats.size());
+ assertEquals(entry1, stats.getValues(0, null));
+ assertEquals(entry2, stats.getValues(1, null));
+ }
+
+ @Test
+ public void testApply464xlatAdjustments() {
+ final String v4Iface = "v4-wlan0";
+ final String baseIface = "wlan0";
+ final String otherIface = "other";
+ final int appUid = 10001;
+ final int rootUid = Process.ROOT_UID;
+ ArrayMap<String, String> stackedIface = new ArrayMap<>();
+ stackedIface.put(v4Iface, baseIface);
+
+ NetworkStats.Entry otherEntry = new NetworkStats.Entry(
+ otherIface, appUid, SET_DEFAULT, TAG_NONE,
+ 2600 /* rxBytes */,
+ 2 /* rxPackets */,
+ 3800 /* txBytes */,
+ 3 /* txPackets */,
+ 0 /* operations */);
+
+ NetworkStats stats = new NetworkStats(TEST_START, 3)
+ .addValues(v4Iface, appUid, SET_DEFAULT, TAG_NONE,
+ 30501490 /* rxBytes */,
+ 22401 /* rxPackets */,
+ 876235 /* txBytes */,
+ 13805 /* txPackets */,
+ 0 /* operations */)
+ .addValues(baseIface, rootUid, SET_DEFAULT, TAG_NONE,
+ 31113087,
+ 22588,
+ 1169942,
+ 13902,
+ 0)
+ .addValues(otherEntry);
+
+ stats.apply464xlatAdjustments(stackedIface);
+
+ assertEquals(3, stats.size());
+ assertValues(stats, 0, v4Iface, appUid, SET_DEFAULT, TAG_NONE,
+ METERED_NO, ROAMING_NO, DEFAULT_NETWORK_NO,
+ 30949510,
+ 22401,
+ 1152335,
+ 13805,
+ 0);
+ assertValues(stats, 1, baseIface, 0, SET_DEFAULT, TAG_NONE,
+ METERED_NO, ROAMING_NO, DEFAULT_NETWORK_NO,
+ 163577,
+ 187,
+ 17607,
+ 97,
+ 0);
+ assertEquals(otherEntry, stats.getValues(2, null));
+ }
+
+ @Test
+ public void testApply464xlatAdjustments_noStackedIface() {
+ NetworkStats.Entry firstEntry = new NetworkStats.Entry(
+ "if1", 10002, SET_DEFAULT, TAG_NONE,
+ 2600 /* rxBytes */,
+ 2 /* rxPackets */,
+ 3800 /* txBytes */,
+ 3 /* txPackets */,
+ 0 /* operations */);
+ NetworkStats.Entry secondEntry = new NetworkStats.Entry(
+ "if2", 10002, SET_DEFAULT, TAG_NONE,
+ 5000 /* rxBytes */,
+ 3 /* rxPackets */,
+ 6000 /* txBytes */,
+ 4 /* txPackets */,
+ 0 /* operations */);
+
+ NetworkStats stats = new NetworkStats(TEST_START, 2)
+ .addValues(firstEntry)
+ .addValues(secondEntry);
+
+ // Empty map: no adjustment
+ stats.apply464xlatAdjustments(new ArrayMap<>());
+
+ assertEquals(2, stats.size());
+ assertEquals(firstEntry, stats.getValues(0, null));
+ assertEquals(secondEntry, stats.getValues(1, null));
+ }
+
private static void assertContains(NetworkStats stats, String iface, int uid, int set,
int tag, int metered, int roaming, int defaultNetwork, long rxBytes, long rxPackets,
long txBytes, long txPackets, long operations) {
diff --git a/tests/net/java/com/android/internal/net/NetworkStatsFactoryTest.java b/tests/net/java/com/android/internal/net/NetworkStatsFactoryTest.java
index b14f550..fc46b9c 100644
--- a/tests/net/java/com/android/internal/net/NetworkStatsFactoryTest.java
+++ b/tests/net/java/com/android/internal/net/NetworkStatsFactoryTest.java
@@ -184,7 +184,7 @@
assertStatsEntry(stats, "dummy0", 0, SET_DEFAULT, 0x0, 0L, 168L);
assertStatsEntry(stats, "lo", 0, SET_DEFAULT, 0x0, 1288L, 1288L);
- NetworkStatsFactory.noteStackedIface("v4-wlan0", null);
+ NetworkStatsFactory.clearStackedIfaces();
}
@Test
@@ -212,7 +212,7 @@
assertStatsEntry(stats, "v4-wlan0", 10106, SET_FOREGROUND, 0x0, appRxBytesAfter, 7867488L);
assertStatsEntry(stats, "wlan0", 0, SET_DEFAULT, 0x0, rootRxBytesAfter, 647587L);
- NetworkStatsFactory.noteStackedIface("v4-wlan0", null);
+ NetworkStatsFactory.clearStackedIfaces();
}
/**
diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java
index 5ea21ea..82b7bec 100644
--- a/tests/net/java/com/android/server/ConnectivityServiceTest.java
+++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java
@@ -63,6 +63,7 @@
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
@@ -133,6 +134,7 @@
import com.android.internal.util.test.FakeSettingsProvider;
import com.android.server.connectivity.ConnectivityConstants;
import com.android.server.connectivity.DefaultNetworkMetrics;
+import com.android.server.connectivity.DnsManager;
import com.android.server.connectivity.IpConnectivityMetrics;
import com.android.server.connectivity.MockableSystemProperties;
import com.android.server.connectivity.NetworkAgentInfo;
@@ -749,6 +751,7 @@
// NetworkMonitor implementation allowing overriding of Internet connectivity probe result.
private class WrappedNetworkMonitor extends NetworkMonitor {
+ public Handler connectivityHandler;
// HTTP response code fed back to NetworkMonitor for Internet connectivity probe.
public int gen204ProbeResult = 500;
public String gen204ProbeRedirectUrl = null;
@@ -758,6 +761,7 @@
IpConnectivityLog log) {
super(context, handler, networkAgentInfo, defaultRequest, log,
NetworkMonitor.NetworkMonitorSettings.DEFAULT);
+ connectivityHandler = handler;
}
@Override
@@ -3664,18 +3668,29 @@
@Test
public void testBasicDnsConfigurationPushed() throws Exception {
+ final String IFNAME = "test_rmnet_data0";
+ final String[] EMPTY_TLS_SERVERS = new String[0];
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
waitForIdle();
verify(mNetworkManagementService, never()).setDnsConfigurationForNetwork(
- anyInt(), any(), any(), any(), anyBoolean(), anyString());
+ anyInt(), any(), any(), any(), anyString(), eq(EMPTY_TLS_SERVERS));
final LinkProperties cellLp = new LinkProperties();
- cellLp.setInterfaceName("test_rmnet_data0");
+ cellLp.setInterfaceName(IFNAME);
+ // Add IPv4 and IPv6 default routes, because DNS-over-TLS code does
+ // "is-reachable" testing in order to not program netd with unreachable
+ // nameservers that it might try repeated to validate.
+ cellLp.addLinkAddress(new LinkAddress("192.0.2.4/24"));
+ cellLp.addRoute(new RouteInfo((IpPrefix) null, InetAddress.getByName("192.0.2.4"), IFNAME));
+ cellLp.addLinkAddress(new LinkAddress("2001:db8:1::1/64"));
+ cellLp.addRoute(
+ new RouteInfo((IpPrefix) null, InetAddress.getByName("2001:db8:1::1"), IFNAME));
mCellNetworkAgent.sendLinkProperties(cellLp);
mCellNetworkAgent.connect(false);
waitForIdle();
verify(mNetworkManagementService, times(1)).setDnsConfigurationForNetwork(
- anyInt(), mStringArrayCaptor.capture(), any(), any(), anyBoolean(), anyString());
+ anyInt(), mStringArrayCaptor.capture(), any(), any(),
+ anyString(), eq(EMPTY_TLS_SERVERS));
// CS tells netd about the empty DNS config for this network.
assertEmpty(mStringArrayCaptor.getValue());
reset(mNetworkManagementService);
@@ -3684,7 +3699,8 @@
mCellNetworkAgent.sendLinkProperties(cellLp);
waitForIdle();
verify(mNetworkManagementService, times(1)).setDnsConfigurationForNetwork(
- anyInt(), mStringArrayCaptor.capture(), any(), any(), anyBoolean(), anyString());
+ anyInt(), mStringArrayCaptor.capture(), any(), any(),
+ anyString(), eq(EMPTY_TLS_SERVERS));
assertEquals(1, mStringArrayCaptor.getValue().length);
assertTrue(ArrayUtils.contains(mStringArrayCaptor.getValue(), "2001:db8::1"));
reset(mNetworkManagementService);
@@ -3693,7 +3709,26 @@
mCellNetworkAgent.sendLinkProperties(cellLp);
waitForIdle();
verify(mNetworkManagementService, times(1)).setDnsConfigurationForNetwork(
- anyInt(), mStringArrayCaptor.capture(), any(), any(), anyBoolean(), anyString());
+ anyInt(), mStringArrayCaptor.capture(), any(), any(),
+ anyString(), eq(EMPTY_TLS_SERVERS));
+ assertEquals(2, mStringArrayCaptor.getValue().length);
+ assertTrue(ArrayUtils.containsAll(mStringArrayCaptor.getValue(),
+ new String[]{"2001:db8::1", "192.0.2.1"}));
+ reset(mNetworkManagementService);
+
+ final String TLS_SPECIFIER = "tls.example.com";
+ final String TLS_SERVER6 = "2001:db8:53::53";
+ final InetAddress[] TLS_IPS = new InetAddress[]{ InetAddress.getByName(TLS_SERVER6) };
+ final String[] TLS_SERVERS = new String[]{ TLS_SERVER6 };
+ final Handler h = mCellNetworkAgent.getWrappedNetworkMonitor().connectivityHandler;
+ h.sendMessage(h.obtainMessage(
+ NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED, 0,
+ mCellNetworkAgent.getNetwork().netId,
+ new DnsManager.PrivateDnsConfig(TLS_SPECIFIER, TLS_IPS)));
+ waitForIdle();
+ verify(mNetworkManagementService, times(1)).setDnsConfigurationForNetwork(
+ anyInt(), mStringArrayCaptor.capture(), any(), any(),
+ eq(TLS_SPECIFIER), eq(TLS_SERVERS));
assertEquals(2, mStringArrayCaptor.getValue().length);
assertTrue(ArrayUtils.containsAll(mStringArrayCaptor.getValue(),
new String[]{"2001:db8::1", "192.0.2.1"}));
diff --git a/tests/net/java/com/android/server/IpSecServiceParameterizedTest.java b/tests/net/java/com/android/server/IpSecServiceParameterizedTest.java
index 3e1ff6d..410f754 100644
--- a/tests/net/java/com/android/server/IpSecServiceParameterizedTest.java
+++ b/tests/net/java/com/android/server/IpSecServiceParameterizedTest.java
@@ -17,11 +17,13 @@
package com.android.server;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -32,6 +34,9 @@
import android.net.IpSecManager;
import android.net.IpSecSpiResponse;
import android.net.IpSecTransformResponse;
+import android.net.IpSecTunnelInterfaceResponse;
+import android.net.LinkAddress;
+import android.net.Network;
import android.net.NetworkUtils;
import android.os.Binder;
import android.os.ParcelFileDescriptor;
@@ -56,10 +61,15 @@
private final String mDestinationAddr;
private final String mSourceAddr;
+ private final LinkAddress mLocalInnerAddress;
@Parameterized.Parameters
public static Collection ipSecConfigs() {
- return Arrays.asList(new Object[][] {{"1.2.3.4", "8.8.4.4"}, {"2601::2", "2601::10"}});
+ return Arrays.asList(
+ new Object[][] {
+ {"1.2.3.4", "8.8.4.4", "10.0.1.1/24"},
+ {"2601::2", "2601::10", "2001:db8::1/64"}
+ });
}
private static final byte[] AEAD_KEY = {
@@ -86,6 +96,7 @@
INetd mMockNetd;
IpSecService.IpSecServiceConfiguration mMockIpSecSrvConfig;
IpSecService mIpSecService;
+ Network fakeNetwork = new Network(0xAB);
private static final IpSecAlgorithm AUTH_ALGO =
new IpSecAlgorithm(IpSecAlgorithm.AUTH_HMAC_SHA256, AUTH_KEY, AUTH_KEY.length * 4);
@@ -94,9 +105,11 @@
private static final IpSecAlgorithm AEAD_ALGO =
new IpSecAlgorithm(IpSecAlgorithm.AUTH_CRYPT_AES_GCM, AEAD_KEY, 128);
- public IpSecServiceParameterizedTest(String sourceAddr, String destAddr) {
+ public IpSecServiceParameterizedTest(
+ String sourceAddr, String destAddr, String localInnerAddr) {
mSourceAddr = sourceAddr;
mDestinationAddr = destAddr;
+ mLocalInnerAddress = new LinkAddress(localInnerAddr);
}
@Before
@@ -308,6 +321,30 @@
}
@Test
+ public void testReleaseOwnedSpi() throws Exception {
+ IpSecConfig ipSecConfig = new IpSecConfig();
+ addDefaultSpisAndRemoteAddrToIpSecConfig(ipSecConfig);
+ addAuthAndCryptToIpSecConfig(ipSecConfig);
+
+ IpSecTransformResponse createTransformResp =
+ mIpSecService.createTransform(ipSecConfig, new Binder());
+ IpSecService.UserRecord userRecord =
+ mIpSecService.mUserResourceTracker.getUserRecord(Os.getuid());
+ assertEquals(1, userRecord.mSpiQuotaTracker.mCurrent);
+ mIpSecService.releaseSecurityParameterIndex(ipSecConfig.getSpiResourceId());
+ verify(mMockNetd, times(0))
+ .ipSecDeleteSecurityAssociation(
+ eq(createTransformResp.resourceId),
+ anyString(),
+ anyString(),
+ eq(TEST_SPI),
+ anyInt(),
+ anyInt());
+ // quota is not released until the SPI is released by the Transform
+ assertEquals(1, userRecord.mSpiQuotaTracker.mCurrent);
+ }
+
+ @Test
public void testDeleteTransform() throws Exception {
IpSecConfig ipSecConfig = new IpSecConfig();
addDefaultSpisAndRemoteAddrToIpSecConfig(ipSecConfig);
@@ -317,7 +354,7 @@
mIpSecService.createTransform(ipSecConfig, new Binder());
mIpSecService.deleteTransform(createTransformResp.resourceId);
- verify(mMockNetd)
+ verify(mMockNetd, times(1))
.ipSecDeleteSecurityAssociation(
eq(createTransformResp.resourceId),
anyString(),
@@ -330,6 +367,21 @@
IpSecService.UserRecord userRecord =
mIpSecService.mUserResourceTracker.getUserRecord(Os.getuid());
assertEquals(0, userRecord.mTransformQuotaTracker.mCurrent);
+ assertEquals(1, userRecord.mSpiQuotaTracker.mCurrent);
+
+ mIpSecService.releaseSecurityParameterIndex(ipSecConfig.getSpiResourceId());
+ // Verify that ipSecDeleteSa was not called when the SPI was released because the
+ // ownedByTransform property should prevent it; (note, the called count is cumulative).
+ verify(mMockNetd, times(1))
+ .ipSecDeleteSecurityAssociation(
+ anyInt(),
+ anyString(),
+ anyString(),
+ anyInt(),
+ anyInt(),
+ anyInt());
+ assertEquals(0, userRecord.mSpiQuotaTracker.mCurrent);
+
try {
userRecord.mTransformRecords.getRefcountedResourceOrThrow(
createTransformResp.resourceId);
@@ -406,4 +458,103 @@
verify(mMockNetd).ipSecRemoveTransportModeTransform(pfd.getFileDescriptor());
}
+
+ private IpSecTunnelInterfaceResponse createAndValidateTunnel(
+ String localAddr, String remoteAddr) {
+ IpSecTunnelInterfaceResponse createTunnelResp =
+ mIpSecService.createTunnelInterface(
+ mSourceAddr, mDestinationAddr, fakeNetwork, new Binder());
+
+ assertNotNull(createTunnelResp);
+ assertEquals(IpSecManager.Status.OK, createTunnelResp.status);
+ return createTunnelResp;
+ }
+
+ @Test
+ public void testCreateTunnelInterface() throws Exception {
+ IpSecTunnelInterfaceResponse createTunnelResp =
+ createAndValidateTunnel(mSourceAddr, mDestinationAddr);
+
+ // Check that we have stored the tracking object, and retrieve it
+ IpSecService.UserRecord userRecord =
+ mIpSecService.mUserResourceTracker.getUserRecord(Os.getuid());
+ IpSecService.RefcountedResource refcountedRecord =
+ userRecord.mTunnelInterfaceRecords.getRefcountedResourceOrThrow(
+ createTunnelResp.resourceId);
+
+ assertEquals(1, userRecord.mTunnelQuotaTracker.mCurrent);
+ verify(mMockNetd)
+ .addVirtualTunnelInterface(
+ eq(createTunnelResp.interfaceName),
+ eq(mSourceAddr),
+ eq(mDestinationAddr),
+ anyInt(),
+ anyInt());
+ }
+
+ @Test
+ public void testDeleteTunnelInterface() throws Exception {
+ IpSecTunnelInterfaceResponse createTunnelResp =
+ createAndValidateTunnel(mSourceAddr, mDestinationAddr);
+
+ IpSecService.UserRecord userRecord =
+ mIpSecService.mUserResourceTracker.getUserRecord(Os.getuid());
+
+ mIpSecService.deleteTunnelInterface(createTunnelResp.resourceId);
+
+ // Verify quota and RefcountedResource objects cleaned up
+ assertEquals(0, userRecord.mTunnelQuotaTracker.mCurrent);
+ verify(mMockNetd).removeVirtualTunnelInterface(eq(createTunnelResp.interfaceName));
+ try {
+ userRecord.mTunnelInterfaceRecords.getRefcountedResourceOrThrow(
+ createTunnelResp.resourceId);
+ fail("Expected IllegalArgumentException on attempt to access deleted resource");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ @Test
+ public void testTunnelInterfaceBinderDeath() throws Exception {
+ IpSecTunnelInterfaceResponse createTunnelResp =
+ createAndValidateTunnel(mSourceAddr, mDestinationAddr);
+
+ IpSecService.UserRecord userRecord =
+ mIpSecService.mUserResourceTracker.getUserRecord(Os.getuid());
+ IpSecService.RefcountedResource refcountedRecord =
+ userRecord.mTunnelInterfaceRecords.getRefcountedResourceOrThrow(
+ createTunnelResp.resourceId);
+
+ refcountedRecord.binderDied();
+
+ // Verify quota and RefcountedResource objects cleaned up
+ assertEquals(0, userRecord.mTunnelQuotaTracker.mCurrent);
+ verify(mMockNetd).removeVirtualTunnelInterface(eq(createTunnelResp.interfaceName));
+ try {
+ userRecord.mTunnelInterfaceRecords.getRefcountedResourceOrThrow(
+ createTunnelResp.resourceId);
+ fail("Expected IllegalArgumentException on attempt to access deleted resource");
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ @Test
+ public void testAddRemoveAddressFromTunnelInterface() throws Exception {
+ IpSecTunnelInterfaceResponse createTunnelResp =
+ createAndValidateTunnel(mSourceAddr, mDestinationAddr);
+
+ mIpSecService.addAddressToTunnelInterface(createTunnelResp.resourceId, mLocalInnerAddress);
+ verify(mMockNetd)
+ .interfaceAddAddress(
+ eq(createTunnelResp.interfaceName),
+ eq(mLocalInnerAddress.getAddress().getHostAddress()),
+ eq(mLocalInnerAddress.getPrefixLength()));
+
+ mIpSecService.removeAddressFromTunnelInterface(
+ createTunnelResp.resourceId, mLocalInnerAddress);
+ verify(mMockNetd)
+ .interfaceDelAddress(
+ eq(createTunnelResp.interfaceName),
+ eq(mLocalInnerAddress.getAddress().getHostAddress()),
+ eq(mLocalInnerAddress.getPrefixLength()));
+ }
}
diff --git a/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java b/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java
new file mode 100644
index 0000000..4a83d1b
--- /dev/null
+++ b/tests/net/java/com/android/server/connectivity/PermissionMonitorTest.java
@@ -0,0 +1,134 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.server.connectivity;
+
+import static android.Manifest.permission.CHANGE_NETWORK_STATE;
+import static android.Manifest.permission.CHANGE_WIFI_STATE;
+import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
+import static android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS;
+import static android.Manifest.permission.NETWORK_STACK;
+import static android.content.pm.ApplicationInfo.FLAG_SYSTEM;
+import static android.content.pm.PackageManager.GET_PERMISSIONS;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.support.test.filters.SmallTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+@RunWith(AndroidJUnit4.class)
+@SmallTest
+public class PermissionMonitorTest {
+ private static final int MOCK_UID = 10001;
+ private static final String[] MOCK_PACKAGE_NAMES = new String[] { "com.foo.bar" };
+
+ @Mock private Context mContext;
+ @Mock private PackageManager mPackageManager;
+
+ private PermissionMonitor mPermissionMonitor;
+
+ @Before
+ public void setUp() throws Exception {
+ MockitoAnnotations.initMocks(this);
+ when(mContext.getPackageManager()).thenReturn(mPackageManager);
+ when(mPackageManager.getPackagesForUid(MOCK_UID)).thenReturn(MOCK_PACKAGE_NAMES);
+ mPermissionMonitor = new PermissionMonitor(mContext, null);
+ }
+
+ private void expectPermission(String[] permissions, boolean preinstalled) throws Exception {
+ final PackageInfo packageInfo = packageInfoWithPermissions(permissions, preinstalled);
+ when(mPackageManager.getPackageInfo(MOCK_PACKAGE_NAMES[0], GET_PERMISSIONS))
+ .thenReturn(packageInfo);
+ }
+
+ private PackageInfo packageInfoWithPermissions(String[] permissions, boolean preinstalled) {
+ final PackageInfo packageInfo = new PackageInfo();
+ packageInfo.requestedPermissions = permissions;
+ packageInfo.applicationInfo = new ApplicationInfo();
+ packageInfo.applicationInfo.flags = preinstalled ? FLAG_SYSTEM : 0;
+ return packageInfo;
+ }
+
+ @Test
+ public void testHasPermission() {
+ PackageInfo app = packageInfoWithPermissions(new String[] {}, false);
+ assertFalse(mPermissionMonitor.hasPermission(app, CHANGE_NETWORK_STATE));
+ assertFalse(mPermissionMonitor.hasPermission(app, NETWORK_STACK));
+ assertFalse(mPermissionMonitor.hasPermission(app, CONNECTIVITY_USE_RESTRICTED_NETWORKS));
+ assertFalse(mPermissionMonitor.hasPermission(app, CONNECTIVITY_INTERNAL));
+
+ app = packageInfoWithPermissions(new String[] {
+ CHANGE_NETWORK_STATE, NETWORK_STACK
+ }, false);
+ assertTrue(mPermissionMonitor.hasPermission(app, CHANGE_NETWORK_STATE));
+ assertTrue(mPermissionMonitor.hasPermission(app, NETWORK_STACK));
+ assertFalse(mPermissionMonitor.hasPermission(app, CONNECTIVITY_USE_RESTRICTED_NETWORKS));
+ assertFalse(mPermissionMonitor.hasPermission(app, CONNECTIVITY_INTERNAL));
+
+ app = packageInfoWithPermissions(new String[] {
+ CONNECTIVITY_USE_RESTRICTED_NETWORKS, CONNECTIVITY_INTERNAL
+ }, false);
+ assertFalse(mPermissionMonitor.hasPermission(app, CHANGE_NETWORK_STATE));
+ assertFalse(mPermissionMonitor.hasPermission(app, NETWORK_STACK));
+ assertTrue(mPermissionMonitor.hasPermission(app, CONNECTIVITY_USE_RESTRICTED_NETWORKS));
+ assertTrue(mPermissionMonitor.hasPermission(app, CONNECTIVITY_INTERNAL));
+ }
+
+ @Test
+ public void testIsPreinstalledSystemApp() {
+ PackageInfo app = packageInfoWithPermissions(new String[] {}, false);
+ assertFalse(mPermissionMonitor.isPreinstalledSystemApp(app));
+
+ app = packageInfoWithPermissions(new String[] {}, true);
+ assertTrue(mPermissionMonitor.isPreinstalledSystemApp(app));
+ }
+
+ @Test
+ public void testHasUseBackgroundNetworksPermission() throws Exception {
+ expectPermission(new String[] { CHANGE_NETWORK_STATE }, false);
+ assertTrue(mPermissionMonitor.hasUseBackgroundNetworksPermission(MOCK_UID));
+
+ expectPermission(new String[] { NETWORK_STACK, CONNECTIVITY_INTERNAL }, false);
+ assertTrue(mPermissionMonitor.hasUseBackgroundNetworksPermission(MOCK_UID));
+
+ // TODO : make this false when b/31479477 is fixed
+ expectPermission(new String[] {}, true);
+ assertTrue(mPermissionMonitor.hasUseBackgroundNetworksPermission(MOCK_UID));
+ expectPermission(new String[] { CHANGE_WIFI_STATE }, true);
+ assertTrue(mPermissionMonitor.hasUseBackgroundNetworksPermission(MOCK_UID));
+
+ expectPermission(new String[] { NETWORK_STACK, CONNECTIVITY_INTERNAL }, true);
+ assertTrue(mPermissionMonitor.hasUseBackgroundNetworksPermission(MOCK_UID));
+
+ expectPermission(new String[] {}, false);
+ assertFalse(mPermissionMonitor.hasUseBackgroundNetworksPermission(MOCK_UID));
+
+ expectPermission(new String[] { CHANGE_WIFI_STATE }, false);
+ assertFalse(mPermissionMonitor.hasUseBackgroundNetworksPermission(MOCK_UID));
+ }
+}
diff --git a/tests/net/java/com/android/server/connectivity/VpnTest.java b/tests/net/java/com/android/server/connectivity/VpnTest.java
index f59850d..e377a47 100644
--- a/tests/net/java/com/android/server/connectivity/VpnTest.java
+++ b/tests/net/java/com/android/server/connectivity/VpnTest.java
@@ -70,6 +70,7 @@
import android.os.Bundle;
import android.os.INetworkManagementService;
import android.os.Looper;
+import android.os.SystemClock;
import android.os.UserHandle;
import android.os.UserManager;
import android.support.test.filters.SmallTest;
@@ -88,6 +89,8 @@
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
+import java.net.Inet4Address;
+import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -639,4 +642,32 @@
lp.addRoute(new RouteInfo(new IpPrefix("::/1")));
assertTrue(Vpn.providesRoutesToMostDestinations(lp));
}
+
+ @Test
+ public void testDoesNotLockUpWithTooManyRoutes() {
+ final LinkProperties lp = new LinkProperties();
+ final byte[] ad = new byte[4];
+ // Actually evaluating this many routes under 1500ms is impossible on
+ // current hardware and for some time, as the algorithm is O(n²).
+ // Make sure the system has a safeguard against this and does not
+ // lock up.
+ final int MAX_ROUTES = 4000;
+ final long MAX_ALLOWED_TIME_MS = 1500;
+ for (int i = 0; i < MAX_ROUTES; ++i) {
+ ad[0] = (byte)((i >> 24) & 0xFF);
+ ad[1] = (byte)((i >> 16) & 0xFF);
+ ad[2] = (byte)((i >> 8) & 0xFF);
+ ad[3] = (byte)(i & 0xFF);
+ try {
+ lp.addRoute(new RouteInfo(new IpPrefix(Inet4Address.getByAddress(ad), 32)));
+ } catch (UnknownHostException e) {
+ // UnknownHostException is only thrown for an address of illegal length,
+ // which can't happen in the case above.
+ }
+ }
+ final long start = SystemClock.currentThreadTimeMillis();
+ assertTrue(Vpn.providesRoutesToMostDestinations(lp));
+ final long end = SystemClock.currentThreadTimeMillis();
+ assertTrue(end - start < MAX_ALLOWED_TIME_MS);
+ }
}
diff --git a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
index 47c3455..17ca651 100644
--- a/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
+++ b/tests/net/java/com/android/server/net/NetworkStatsServiceTest.java
@@ -25,6 +25,7 @@
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;
import static android.net.NetworkStats.METERED_ALL;
import static android.net.NetworkStats.METERED_NO;
import static android.net.NetworkStats.METERED_YES;
@@ -58,6 +59,9 @@
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.argThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -95,6 +99,7 @@
import android.util.TrustedTime;
import com.android.internal.net.VpnInfo;
+import com.android.internal.util.ArrayUtils;
import com.android.internal.util.test.BroadcastInterceptingContext;
import com.android.server.net.NetworkStatsService.NetworkStatsSettings;
import com.android.server.net.NetworkStatsService.NetworkStatsSettings.Config;
@@ -668,6 +673,94 @@
}
@Test
+ public void testDetailedUidStats() throws Exception {
+ // pretend that network comes online
+ expectDefaultSettings();
+ expectNetworkState(buildWifiState());
+ expectNetworkStatsSummary(buildEmptyStats());
+ expectNetworkStatsUidDetail(buildEmptyStats());
+ expectBandwidthControlCheck();
+
+ mService.forceUpdateIfaces(NETWORKS_WIFI);
+
+ NetworkStats.Entry entry1 = new NetworkStats.Entry(
+ TEST_IFACE, UID_RED, SET_DEFAULT, TAG_NONE, 50L, 5L, 50L, 5L, 0L);
+ NetworkStats.Entry entry2 = new NetworkStats.Entry(
+ TEST_IFACE, UID_RED, SET_DEFAULT, 0xF00D, 50L, 5L, 50L, 5L, 0L);
+ NetworkStats.Entry entry3 = new NetworkStats.Entry(
+ TEST_IFACE, UID_BLUE, SET_DEFAULT, 0xBEEF, 1024L, 8L, 512L, 4L, 0L);
+
+ incrementCurrentTime(HOUR_IN_MILLIS);
+ expectDefaultSettings();
+ expectNetworkStatsSummary(buildEmptyStats());
+ expectNetworkStatsUidDetail(new NetworkStats(getElapsedRealtime(), 3)
+ .addValues(entry1)
+ .addValues(entry2)
+ .addValues(entry3));
+ mService.incrementOperationCount(UID_RED, 0xF00D, 1);
+
+ NetworkStats stats = mService.getDetailedUidStats(INTERFACES_ALL);
+
+ assertEquals(3, stats.size());
+ entry1.operations = 1;
+ assertEquals(entry1, stats.getValues(0, null));
+ entry2.operations = 1;
+ assertEquals(entry2, stats.getValues(1, null));
+ assertEquals(entry3, stats.getValues(2, null));
+ }
+
+ @Test
+ public void testDetailedUidStats_Filtered() throws Exception {
+ // pretend that network comes online
+ expectDefaultSettings();
+
+ final String stackedIface = "stacked-test0";
+ final LinkProperties stackedProp = new LinkProperties();
+ stackedProp.setInterfaceName(stackedIface);
+ final NetworkState wifiState = buildWifiState();
+ wifiState.linkProperties.addStackedLink(stackedProp);
+ expectNetworkState(wifiState);
+
+ expectNetworkStatsSummary(buildEmptyStats());
+ expectNetworkStatsUidDetail(buildEmptyStats());
+ expectBandwidthControlCheck();
+
+ mService.forceUpdateIfaces(NETWORKS_WIFI);
+
+ NetworkStats.Entry uidStats = new NetworkStats.Entry(
+ TEST_IFACE, UID_BLUE, SET_DEFAULT, 0xF00D, 1024L, 8L, 512L, 4L, 0L);
+ // Stacked on matching interface
+ NetworkStats.Entry tetheredStats1 = new NetworkStats.Entry(
+ stackedIface, UID_BLUE, SET_DEFAULT, 0xF00D, 1024L, 8L, 512L, 4L, 0L);
+ // Different interface
+ NetworkStats.Entry tetheredStats2 = new NetworkStats.Entry(
+ "otherif", UID_BLUE, SET_DEFAULT, 0xF00D, 1024L, 8L, 512L, 4L, 0L);
+
+ final String[] ifaceFilter = new String[] { TEST_IFACE };
+ incrementCurrentTime(HOUR_IN_MILLIS);
+ expectDefaultSettings();
+ expectNetworkStatsSummary(buildEmptyStats());
+ when(mNetManager.getNetworkStatsUidDetail(eq(UID_ALL), any()))
+ .thenReturn(new NetworkStats(getElapsedRealtime(), 1)
+ .addValues(uidStats));
+ when(mNetManager.getNetworkStatsTethering(STATS_PER_UID))
+ .thenReturn(new NetworkStats(getElapsedRealtime(), 2)
+ .addValues(tetheredStats1)
+ .addValues(tetheredStats2));
+
+ NetworkStats stats = mService.getDetailedUidStats(ifaceFilter);
+
+ verify(mNetManager, times(1)).getNetworkStatsUidDetail(eq(UID_ALL), argThat(ifaces ->
+ ifaces != null && ifaces.length == 2
+ && ArrayUtils.contains(ifaces, TEST_IFACE)
+ && ArrayUtils.contains(ifaces, stackedIface)));
+
+ assertEquals(2, stats.size());
+ assertEquals(uidStats, stats.getValues(0, null));
+ assertEquals(tetheredStats1, stats.getValues(1, null));
+ }
+
+ @Test
public void testForegroundBackground() throws Exception {
// pretend that network comes online
expectCurrentTime();
@@ -1056,7 +1149,7 @@
private void expectNetworkStatsUidDetail(NetworkStats detail, NetworkStats tetherStats)
throws Exception {
- when(mNetManager.getNetworkStatsUidDetail(UID_ALL)).thenReturn(detail);
+ when(mNetManager.getNetworkStatsUidDetail(UID_ALL, INTERFACES_ALL)).thenReturn(detail);
// also include tethering details, since they are folded into UID
when(mNetManager.getNetworkStatsTethering(STATS_PER_UID)).thenReturn(tetherStats);