/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.net; import static com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE; import android.annotation.IntDef; import android.annotation.LongDef; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.RequiresPermission; import android.annotation.SuppressLint; import android.annotation.SystemApi; import android.compat.annotation.UnsupportedAppUsage; import android.net.ConnectivityManager.NetworkCallback; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; import android.os.Process; import android.text.TextUtils; import android.util.ArraySet; import android.util.Range; import com.android.internal.annotations.VisibleForTesting; import com.android.net.module.util.CollectionUtils; import com.android.net.module.util.NetworkCapabilitiesUtils; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.StringJoiner; /** * Representation of the capabilities of an active network. Instances are * typically obtained through * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} * or {@link ConnectivityManager#getNetworkCapabilities(Network)}. *
* This replaces the old {@link ConnectivityManager#TYPE_MOBILE} method of
* network selection. Rather than indicate a need for Wi-Fi because an
* application needs high bandwidth and risk obsolescence when a new, fast
* network appears (like LTE), the application should specify it needs high
* bandwidth. Similarly if an application needs an unmetered network for a bulk
* transfer it can specify that rather than assuming all cellular based
* connections are metered and all Wi-Fi based connections are not.
*/
public final class NetworkCapabilities implements Parcelable {
private static final String TAG = "NetworkCapabilities";
/**
* Mechanism to support redaction of fields in NetworkCapabilities that are guarded by specific
* app permissions.
**/
/**
* Don't redact any fields since the receiving app holds all the necessary permissions.
*
* @hide
*/
@SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
public static final long REDACT_NONE = 0;
/**
* Redact any fields that need {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
* permission since the receiving app does not hold this permission or the location toggle
* is off.
*
* @see android.Manifest.permission#ACCESS_FINE_LOCATION
* @hide
*/
@SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
public static final long REDACT_FOR_ACCESS_FINE_LOCATION = 1 << 0;
/**
* Redact any fields that need {@link android.Manifest.permission#LOCAL_MAC_ADDRESS}
* permission since the receiving app does not hold this permission.
*
* @see android.Manifest.permission#LOCAL_MAC_ADDRESS
* @hide
*/
@SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
public static final long REDACT_FOR_LOCAL_MAC_ADDRESS = 1 << 1;
/**
*
* Redact any fields that need {@link android.Manifest.permission#NETWORK_SETTINGS}
* permission since the receiving app does not hold this permission.
*
* @see android.Manifest.permission#NETWORK_SETTINGS
* @hide
*/
@SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
public static final long REDACT_FOR_NETWORK_SETTINGS = 1 << 2;
/**
* Redact all fields in this object that require any relevant permission.
* @hide
*/
@SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
public static final long REDACT_ALL = -1L;
/** @hide */
@LongDef(flag = true, prefix = { "REDACT_" }, value = {
REDACT_NONE,
REDACT_FOR_ACCESS_FINE_LOCATION,
REDACT_FOR_LOCAL_MAC_ADDRESS,
REDACT_FOR_NETWORK_SETTINGS,
REDACT_ALL
})
@Retention(RetentionPolicy.SOURCE)
public @interface RedactionType {}
// Set to true when private DNS is broken.
private boolean mPrivateDnsBroken;
// Underlying networks, if any. VPNs and VCNs typically have underlying networks.
// This is an unmodifiable list and it will be returned as is in the getter.
@Nullable
private List
* When a network is congested, applications should defer network traffic
* that can be done at a later time, such as uploading analytics.
*/
public static final int NET_CAPABILITY_NOT_CONGESTED = 20;
/**
* Indicates that this network is not currently suspended.
*
* When a network is suspended, the network's IP addresses and any connections
* established on the network remain valid, but the network is temporarily unable
* to transfer data. This can happen, for example, if a cellular network experiences
* a temporary loss of signal, such as when driving through a tunnel, etc.
* A network with this capability is not suspended, so is expected to be able to
* transfer data.
*/
public static final int NET_CAPABILITY_NOT_SUSPENDED = 21;
/**
* Indicates that traffic that goes through this network is paid by oem. For example,
* this network can be used by system apps to upload telemetry data.
* @hide
*/
@SystemApi
public static final int NET_CAPABILITY_OEM_PAID = 22;
/**
* Indicates this is a network that has the ability to reach a carrier's Mission Critical
* servers.
*/
public static final int NET_CAPABILITY_MCX = 23;
/**
* Indicates that this network was tested to only provide partial connectivity.
* @hide
*/
@SystemApi
public static final int NET_CAPABILITY_PARTIAL_CONNECTIVITY = 24;
/**
* Indicates that this network is temporarily unmetered.
*
* This capability will be set for networks that are generally metered, but are currently
* unmetered, e.g., because the user is in a particular area. This capability can be changed at
* any time. When it is removed, applications are responsible for stopping any data transfer
* that should not occur on a metered network.
* Note that most apps should use {@link #NET_CAPABILITY_NOT_METERED} instead. For more
* information, see https://developer.android.com/about/versions/11/features/5g#meteredness.
*/
public static final int NET_CAPABILITY_TEMPORARILY_NOT_METERED = 25;
/**
* Indicates that this network is private to the OEM and meant only for OEM use.
* @hide
*/
@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;
/**
* Indicates that this network is not subsumed by a Virtual Carrier Network (VCN).
*
* To provide an experience on a VCN similar to a single traditional carrier network, in
* some cases the system sets this bit is set by default in application's network requests,
* and may choose to remove it at its own discretion when matching the request to a network.
*
* Applications that want to know about a Virtual Carrier Network's underlying networks,
* for example to use them for multipath purposes, should remove this bit from their network
* requests ; the system will not add it back once removed.
* @hide
*/
@SystemApi
public static final int NET_CAPABILITY_NOT_VCN_MANAGED = 28;
/**
* Indicates that this network is intended for enterprise use.
*
* 5G URSP rules may indicate that all data should use a connection dedicated for enterprise
* use. If the enterprise capability is requested, all enterprise traffic will be routed over
* the connection with this capability.
*/
public static final int NET_CAPABILITY_ENTERPRISE = 29;
/**
* Indicates that this network has ability to access the carrier's Virtual Sim service.
* @hide
*/
@SystemApi
public static final int NET_CAPABILITY_VSIM = 30;
/**
* Indicates that this network has ability to support Bearer Independent Protol.
* @hide
*/
@SystemApi
public static final int NET_CAPABILITY_BIP = 31;
/**
* Indicates that this network is connected to an automotive head unit.
*/
public static final int NET_CAPABILITY_HEAD_UNIT = 32;
/**
* Indicates that this network has ability to support MMTEL (Multimedia Telephony service).
*/
public static final int NET_CAPABILITY_MMTEL = 33;
/**
* Indicates that this network should be able to prioritize latency for the internet.
*/
public static final int NET_CAPABILITY_PRIORITIZE_LATENCY = 34;
/**
* Indicates that this network should be able to prioritize bandwidth for the internet.
*/
public static final int NET_CAPABILITY_PRIORITIZE_BANDWIDTH = 35;
private static final int MIN_NET_CAPABILITY = NET_CAPABILITY_MMS;
private static final int MAX_NET_CAPABILITY = NET_CAPABILITY_PRIORITIZE_BANDWIDTH;
/**
* Network capabilities that are expected to be mutable, i.e., can change while a particular
* network is connected.
*/
private static final long MUTABLE_CAPABILITIES = NetworkCapabilitiesUtils.packBitList(
// TRUSTED can change when user explicitly connects to an untrusted network in Settings.
// http://b/18206275
NET_CAPABILITY_TRUSTED,
NET_CAPABILITY_VALIDATED,
NET_CAPABILITY_CAPTIVE_PORTAL,
NET_CAPABILITY_NOT_ROAMING,
NET_CAPABILITY_FOREGROUND,
NET_CAPABILITY_NOT_CONGESTED,
NET_CAPABILITY_NOT_SUSPENDED,
NET_CAPABILITY_PARTIAL_CONNECTIVITY,
NET_CAPABILITY_TEMPORARILY_NOT_METERED,
NET_CAPABILITY_NOT_VCN_MANAGED,
// The value of NET_CAPABILITY_HEAD_UNIT is 32, which cannot use int to do bit shift,
// otherwise there will be an overflow. Use long to do bit shift instead.
NET_CAPABILITY_HEAD_UNIT);
/**
* Network capabilities that are not allowed in NetworkRequests. This exists because the
* NetworkFactory / NetworkAgent model does not deal well with the situation where a
* capability's presence cannot be known in advance. If such a capability is requested, then we
* can get into a cycle where the NetworkFactory endlessly churns out NetworkAgents that then
* get immediately torn down because they do not have the requested capability.
*/
// Note that as a historical exception, the TRUSTED and NOT_VCN_MANAGED capabilities
// are mutable but requestable. Factories are responsible for not getting
// in an infinite loop about these.
private static final long NON_REQUESTABLE_CAPABILITIES =
MUTABLE_CAPABILITIES
& ~(1L << NET_CAPABILITY_TRUSTED)
& ~(1L << NET_CAPABILITY_NOT_VCN_MANAGED);
/**
* Capabilities that are set by default when the object is constructed.
*/
private static final long DEFAULT_CAPABILITIES = NetworkCapabilitiesUtils.packBitList(
NET_CAPABILITY_NOT_RESTRICTED,
NET_CAPABILITY_TRUSTED,
NET_CAPABILITY_NOT_VPN);
/**
* Capabilities that are managed by ConnectivityService.
*/
private static final long CONNECTIVITY_MANAGED_CAPABILITIES =
NetworkCapabilitiesUtils.packBitList(
NET_CAPABILITY_VALIDATED,
NET_CAPABILITY_CAPTIVE_PORTAL,
NET_CAPABILITY_FOREGROUND,
NET_CAPABILITY_PARTIAL_CONNECTIVITY);
/**
* Capabilities that are allowed for test networks. This list must be set so that it is safe
* for an unprivileged user to create a network with these capabilities via shell. As such,
* it must never contain capabilities that are generally useful to the system, such as
* INTERNET, IMS, SUPL, etc.
*/
private static final long TEST_NETWORKS_ALLOWED_CAPABILITIES =
NetworkCapabilitiesUtils.packBitList(
NET_CAPABILITY_NOT_METERED,
NET_CAPABILITY_TEMPORARILY_NOT_METERED,
NET_CAPABILITY_NOT_RESTRICTED,
NET_CAPABILITY_NOT_VPN,
NET_CAPABILITY_NOT_ROAMING,
NET_CAPABILITY_NOT_CONGESTED,
NET_CAPABILITY_NOT_SUSPENDED,
NET_CAPABILITY_NOT_VCN_MANAGED);
/**
* Adds the given capability to this {@code NetworkCapability} instance.
* Note that when searching for a network to satisfy a request, all capabilities
* requested must be satisfied.
*
* @param capability the capability to be added.
* @return This NetworkCapabilities instance, to facilitate chaining.
* @hide
*/
public @NonNull NetworkCapabilities addCapability(@NetCapability int capability) {
// If the given capability was previously added to the list of forbidden capabilities
// then the capability will also be removed from the list of forbidden capabilities.
// TODO: Consider adding forbidden capabilities to the public API and mention this
// in the documentation.
checkValidCapability(capability);
mNetworkCapabilities |= 1L << capability;
// remove from forbidden capability list
mForbiddenNetworkCapabilities &= ~(1L << capability);
return this;
}
/**
* Adds the given capability to the list of forbidden capabilities of this
* {@code NetworkCapability} instance. Note that when searching for a network to
* satisfy a request, the network must not contain any capability from forbidden capability
* list.
*
* If the capability was previously added to the list of required capabilities (for
* example, it was there by default or added using {@link #addCapability(int)} method), then
* it will be removed from the list of required capabilities as well.
*
* @see #addCapability(int)
* @hide
*/
public void addForbiddenCapability(@NetCapability int capability) {
checkValidCapability(capability);
mForbiddenNetworkCapabilities |= 1L << capability;
mNetworkCapabilities &= ~(1L << capability); // remove from requested capabilities
}
/**
* Removes (if found) the given capability from this {@code NetworkCapability}
* instance that were added via addCapability(int) or setCapabilities(int[], int[]).
*
* @param capability the capability to be removed.
* @return This NetworkCapabilities instance, to facilitate chaining.
* @hide
*/
public @NonNull NetworkCapabilities removeCapability(@NetCapability int capability) {
checkValidCapability(capability);
final long mask = ~(1L << capability);
mNetworkCapabilities &= mask;
return this;
}
/**
* Removes (if found) the given forbidden capability from this {@code NetworkCapability}
* instance that were added via addForbiddenCapability(int) or setCapabilities(int[], int[]).
*
* @param capability the capability to be removed.
* @return This NetworkCapabilities instance, to facilitate chaining.
* @hide
*/
public @NonNull NetworkCapabilities removeForbiddenCapability(@NetCapability int capability) {
checkValidCapability(capability);
mForbiddenNetworkCapabilities &= ~(1L << capability);
return this;
}
/**
* Sets (or clears) the given capability on this {@link NetworkCapabilities}
* instance.
* @hide
*/
public @NonNull NetworkCapabilities setCapability(@NetCapability int capability,
boolean value) {
if (value) {
addCapability(capability);
} else {
removeCapability(capability);
}
return this;
}
/**
* Gets all the capabilities set on this {@code NetworkCapability} instance.
*
* @return an array of capability values for this instance.
*/
public @NonNull @NetCapability int[] getCapabilities() {
return NetworkCapabilitiesUtils.unpackBits(mNetworkCapabilities);
}
/**
* Gets all the forbidden capabilities set on this {@code NetworkCapability} instance.
*
* @return an array of forbidden capability values for this instance.
* @hide
*/
public @NetCapability int[] getForbiddenCapabilities() {
return NetworkCapabilitiesUtils.unpackBits(mForbiddenNetworkCapabilities);
}
/**
* Sets all the capabilities set on this {@code NetworkCapability} instance.
* This overwrites any existing capabilities.
*
* @hide
*/
public void setCapabilities(@NetCapability int[] capabilities,
@NetCapability int[] forbiddenCapabilities) {
mNetworkCapabilities = NetworkCapabilitiesUtils.packBits(capabilities);
mForbiddenNetworkCapabilities = NetworkCapabilitiesUtils.packBits(forbiddenCapabilities);
}
/**
* @deprecated use {@link #setCapabilities(int[], int[])}
* @hide
*/
@Deprecated
public void setCapabilities(@NetCapability int[] capabilities) {
setCapabilities(capabilities, new int[] {});
}
/**
* Adds the given enterprise capability identifier to this {@code NetworkCapability} instance.
* Note that when searching for a network to satisfy a request, all capabilities identifier
* requested must be satisfied.
*
* @param enterpriseId the enterprise capability identifier to be added.
* @return This NetworkCapabilities instance, to facilitate chaining.
* @hide
*/
public @NonNull NetworkCapabilities addEnterpriseId(
@EnterpriseId int enterpriseId) {
checkValidEnterpriseId(enterpriseId);
mEnterpriseId |= 1 << enterpriseId;
return this;
}
/**
* Removes (if found) the given enterprise capability identifier from this
* {@code NetworkCapability} instance that were added via addEnterpriseId(int)
*
* @param enterpriseId the enterprise capability identifier to be removed.
* @return This NetworkCapabilities instance, to facilitate chaining.
* @hide
*/
private @NonNull NetworkCapabilities removeEnterpriseId(
@EnterpriseId int enterpriseId) {
checkValidEnterpriseId(enterpriseId);
final int mask = ~(1 << enterpriseId);
mEnterpriseId &= mask;
return this;
}
/**
* Set the underlying networks of this network.
*
* @param networks The underlying networks of this network.
*
* @hide
*/
public void setUnderlyingNetworks(@Nullable List This field keeps track of the UID of the app that created this network and is in charge of
* its lifecycle. This could be the UID of apps such as the Wifi network suggestor, the running
* VPN, or Carrier Service app managing a cellular data connection.
*
* For NetworkCapability instances being sent from ConnectivityService, this value MUST be
* reset to Process.INVALID_UID unless all the following conditions are met:
*
* The caller is the network owner, AND one of the following sets of requirements is met:
*
* OR:
*
* This is populated by the network agents and for the NetworkCapabilities instance sent by
* an app to the System Server, the value MUST be reset to Process.INVALID_UID by the system
* server.
*/
private int mOwnerUid = Process.INVALID_UID;
/**
* Set the UID of the owner app.
* @hide
*/
public @NonNull NetworkCapabilities setOwnerUid(final int uid) {
mOwnerUid = uid;
return this;
}
/**
* Retrieves the UID of the app that owns this network.
*
* For user privacy reasons, this field will only be populated if the following conditions
* are met:
*
* The caller is the network owner, AND one of the following sets of requirements is met:
*
* OR:
*
*
* This field will only be populated for VPN and wifi network suggestor apps (i.e using
* {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}), and only for the
* network they own. In the case of wifi network suggestors apps, this field is also location
* sensitive, so the app needs to hold {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
* permission. If the app targets SDK version greater than or equal to
* {@link Build.VERSION_CODES#S}, then they also need to use
* {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} to get the info in their callback. If the
* apps targets SDK version equal to {{@link Build.VERSION_CODES#R}, this field will always be
* included. The app will be blamed for location access if this field is included.
* This field tracks the UIDs of packages that have permission to manage this network.
*
* Network owners will also be listed as administrators.
*
* For NetworkCapability instances being sent from the System Server, this value MUST be
* empty unless the destination is 1) the System Server, or 2) Telephony. In either case, the
* receiving entity must have the ACCESS_FINE_LOCATION permission and target R+.
*
* When received from an app in a NetworkRequest this is always cleared out by the system
* server. This field is never used for matching NetworkRequests to NetworkAgents.
*/
@NonNull private int[] mAdministratorUids = new int[0];
/**
* Sets the int[] of UIDs that are administrators of this network.
*
* UIDs included in administratorUids gain administrator privileges over this Network.
* Examples of UIDs that should be included in administratorUids are:
*
* In general, user-supplied networks (such as WiFi networks) do not have an administrator.
*
* An app is granted owner privileges over Networks that it supplies. The owner UID MUST
* always be included in administratorUids.
*
* The administrator UIDs are set by network agents.
*
* @param administratorUids the UIDs to be set as administrators of this Network.
* @throws IllegalArgumentException if duplicate UIDs are contained in administratorUids
* @see #mAdministratorUids
* @hide
*/
@NonNull
public NetworkCapabilities setAdministratorUids(@NonNull final int[] administratorUids) {
mAdministratorUids = Arrays.copyOf(administratorUids, administratorUids.length);
Arrays.sort(mAdministratorUids);
for (int i = 0; i < mAdministratorUids.length - 1; i++) {
if (mAdministratorUids[i] >= mAdministratorUids[i + 1]) {
throw new IllegalArgumentException("All administrator UIDs must be unique");
}
}
return this;
}
/**
* Retrieves the UIDs that are administrators of this Network.
*
* This is only populated in NetworkCapabilities objects that come from network agents for
* networks that are managed by specific apps on the system, such as carrier privileged apps or
* wifi suggestion apps. This will include the network owner.
*
* @return the int[] of UIDs that are administrators of this Network
* @see #mAdministratorUids
* @hide
*/
@NonNull
@SystemApi
public int[] getAdministratorUids() {
return Arrays.copyOf(mAdministratorUids, mAdministratorUids.length);
}
/**
* Tests if the set of administrator UIDs of this network is the same as that of the passed one.
*
* The administrator UIDs must be in sorted order.
*
* nc is assumed non-null. Else, NPE.
*
* @hide
*/
@VisibleForTesting(visibility = PRIVATE)
public boolean equalsAdministratorUids(@NonNull final NetworkCapabilities nc) {
return Arrays.equals(mAdministratorUids, nc.mAdministratorUids);
}
/**
* Value indicating that link bandwidth is unspecified.
* @hide
*/
public static final int LINK_BANDWIDTH_UNSPECIFIED = 0;
/**
* Passive link bandwidth. This is a rough guide of the expected peak bandwidth
* for the first hop on the given transport. It is not measured, but may take into account
* link parameters (Radio technology, allocated channels, etc).
*/
private int mLinkUpBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED;
private int mLinkDownBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED;
/**
* Sets the upstream bandwidth for this network in Kbps. This always only refers to
* the estimated first hop transport bandwidth.
*
* {@see Builder#setLinkUpstreamBandwidthKbps}
*
* @param upKbps the estimated first hop upstream (device to network) bandwidth.
* @hide
*/
public @NonNull NetworkCapabilities setLinkUpstreamBandwidthKbps(int upKbps) {
mLinkUpBandwidthKbps = upKbps;
return this;
}
/**
* Retrieves the upstream bandwidth for this network in Kbps. This always only refers to
* the estimated first hop transport bandwidth.
*
* @return The estimated first hop upstream (device to network) bandwidth.
*/
public int getLinkUpstreamBandwidthKbps() {
return mLinkUpBandwidthKbps;
}
/**
* Sets the downstream bandwidth for this network in Kbps. This always only refers to
* the estimated first hop transport bandwidth.
*
* {@see Builder#setLinkUpstreamBandwidthKbps}
*
* @param downKbps the estimated first hop downstream (network to device) bandwidth.
* @hide
*/
public @NonNull NetworkCapabilities setLinkDownstreamBandwidthKbps(int downKbps) {
mLinkDownBandwidthKbps = downKbps;
return this;
}
/**
* Retrieves the downstream bandwidth for this network in Kbps. This always only refers to
* the estimated first hop transport bandwidth.
*
* @return The estimated first hop downstream (network to device) bandwidth.
*/
public int getLinkDownstreamBandwidthKbps() {
return mLinkDownBandwidthKbps;
}
private boolean satisfiedByLinkBandwidths(NetworkCapabilities nc) {
return !(this.mLinkUpBandwidthKbps > nc.mLinkUpBandwidthKbps
|| this.mLinkDownBandwidthKbps > nc.mLinkDownBandwidthKbps);
}
private boolean equalsLinkBandwidths(NetworkCapabilities nc) {
return (this.mLinkUpBandwidthKbps == nc.mLinkUpBandwidthKbps
&& this.mLinkDownBandwidthKbps == nc.mLinkDownBandwidthKbps);
}
/** @hide */
public static int minBandwidth(int a, int b) {
if (a == LINK_BANDWIDTH_UNSPECIFIED) {
return b;
} else if (b == LINK_BANDWIDTH_UNSPECIFIED) {
return a;
} else {
return Math.min(a, b);
}
}
/** @hide */
public static int maxBandwidth(int a, int b) {
return Math.max(a, b);
}
private NetworkSpecifier mNetworkSpecifier = null;
private TransportInfo mTransportInfo = null;
/**
* Sets the optional bearer specific network specifier.
* This has no meaning if a single transport is also not specified, so calling
* this without a single transport set will generate an exception, as will
* subsequently adding or removing transports after this is set.
*
* Note that when used to register a network callback, this specifies the minimum acceptable
* signal strength. When received as the state of an existing network it specifies the current
* value. A value of {@link #SIGNAL_STRENGTH_UNSPECIFIED} means no value when received and has
* no effect when requesting a callback.
*
* @param signalStrength the bearer-specific signal strength.
* @hide
*/
public @NonNull NetworkCapabilities setSignalStrength(int signalStrength) {
mSignalStrength = signalStrength;
return this;
}
/**
* Returns {@code true} if this object specifies a signal strength.
*
* @hide
*/
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
public boolean hasSignalStrength() {
return mSignalStrength > SIGNAL_STRENGTH_UNSPECIFIED;
}
/**
* Retrieves the signal strength.
*
* @return The bearer-specific signal strength.
*/
public int getSignalStrength() {
return mSignalStrength;
}
private boolean satisfiedBySignalStrength(NetworkCapabilities nc) {
return this.mSignalStrength <= nc.mSignalStrength;
}
private boolean equalsSignalStrength(NetworkCapabilities nc) {
return this.mSignalStrength == nc.mSignalStrength;
}
/**
* List of UIDs this network applies to. No restriction if null.
*
* For networks, mUids represent the list of network this applies to, and null means this
* network applies to all UIDs.
* For requests, mUids is the list of UIDs this network MUST apply to to match ; ALL UIDs
* must be included in a network so that they match. As an exception to the general rule,
* a null mUids field for requests mean "no requirements" rather than what the general rule
* would suggest ("must apply to all UIDs") : this is because this has shown to be what users
* of this API expect in practice. A network that must match all UIDs can still be
* expressed with a set ranging the entire set of possible UIDs.
*
* mUids is typically (and at this time, only) used by VPN. This network is only available to
* the UIDs in this list, and it is their default network. Apps in this list that wish to
* bypass the VPN can do so iff the VPN app allows them to or if they are privileged. If this
* member is null, then the network is not restricted by app UID. If it's an empty list, then
* it means nobody can use it.
* As a special exception, the app managing this network (as identified by its UID stored in
* mOwnerUid) can always see this network. This is embodied by a special check in
* satisfiedByUids. That still does not mean the network necessarily applies
* to the app that manages it as determined by #appliesToUid.
*
* Please note that in principle a single app can be associated with multiple UIDs because
* each app will have a different UID when it's run as a different (macro-)user. A single
* macro user can only have a single active VPN app at any given time however.
*
* Also please be aware this class does not try to enforce any normalization on this. Callers
* can only alter the UIDs by setting them wholesale : this class does not provide any utility
* to add or remove individual UIDs or ranges. If callers have any normalization needs on
* their own (like requiring sortedness or no overlap) they need to enforce it
* themselves. Some of the internal methods also assume this is normalized as in no adjacent
* or overlapping ranges are present.
*
* @hide
*/
private ArraySet
* This test only checks whether equal range objects are in both sets. It will
* return false if the ranges are not exactly the same, even if the covered UIDs
* are for an equivalent result.
*
* Note that this method is not very optimized, which is fine as long as it's not used very
* often.
*
* nc is assumed nonnull, else NPE.
*
* @hide
*/
@VisibleForTesting
public boolean equalsUids(@NonNull NetworkCapabilities nc) {
return UidRange.hasSameUids(nc.mUids, mUids);
}
/**
* Test whether the passed NetworkCapabilities satisfies the UIDs this capabilities require.
*
* This method is called on the NetworkCapabilities embedded in a request with the
* capabilities of an available network. It checks whether all the UIDs from this listen
* (representing the UIDs that must have access to the network) are satisfied by the UIDs
* in the passed nc (representing the UIDs that this network is available to).
*
* As a special exception, the UID that created the passed network (as represented by its
* mOwnerUid field) always satisfies a NetworkRequest requiring it (of LISTEN
* or REQUEST types alike), even if the network does not apply to it. That is so a VPN app
* can see its own network when it listens for it.
*
* nc is assumed nonnull. Else, NPE.
* @see #appliesToUid
* @hide
*/
public boolean satisfiedByUids(@NonNull NetworkCapabilities nc) {
if (null == nc.mUids || null == mUids) return true; // The network satisfies everything.
for (UidRange requiredRange : mUids) {
if (requiredRange.contains(nc.mOwnerUid)) return true;
if (!nc.appliesToUidRange(requiredRange)) {
return false;
}
}
return true;
}
/**
* Returns whether this network applies to the passed ranges.
* This assumes that to apply, the passed range has to be entirely contained
* within one of the ranges this network applies to. If the ranges are not normalized,
* this method may return false even though all required UIDs are covered because no
* single range contained them all.
* @hide
*/
@VisibleForTesting
public boolean appliesToUidRange(@NonNull UidRange requiredRange) {
if (null == mUids) return true;
for (UidRange uidRange : mUids) {
if (uidRange.containsRange(requiredRange)) {
return true;
}
}
return false;
}
/**
* List of UIDs that can always access this network.
*
* UIDs in this list have access to this network, even if the network doesn't have the
* {@link #NET_CAPABILITY_NOT_RESTRICTED} capability and the UID does not hold the
* {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission.
* This is only useful for restricted networks. For non-restricted networks it has no effect.
*
* This is disallowed in {@link NetworkRequest}, and can only be set by network agents. Network
* agents also have restrictions on how they can set theseĀ ; they can only back a public
* Android API. As such, Ethernet agents can set this when backing the per-UID access API, and
* Telephony can set exactly one UID which has to match the manager app for the associated
* subscription. Failure to comply with these rules will see this member cleared.
*
* This member is never null, but can be empty.
* @hide
*/
@NonNull
private final ArraySet
* This is filled in by wifi code.
* @hide
*/
private String mSSID;
/**
* Sets the SSID of this network.
* @hide
*/
public @NonNull NetworkCapabilities setSSID(@Nullable String ssid) {
mSSID = ssid;
return this;
}
/**
* Gets the SSID of this network, or null if none or unknown.
* @hide
*/
@SystemApi
public @Nullable String getSsid() {
return mSSID;
}
/**
* Tests if the SSID of this network is the same as the SSID of the passed network.
* @hide
*/
public boolean equalsSSID(@NonNull NetworkCapabilities nc) {
return Objects.equals(mSSID, nc.mSSID);
}
/**
* Check if the SSID requirements of this object are matched by the passed object.
* @hide
*/
public boolean satisfiedBySSID(@NonNull NetworkCapabilities nc) {
return mSSID == null || mSSID.equals(nc.mSSID);
}
/**
* Check if our requirements are satisfied by the given {@code NetworkCapabilities}.
*
* @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements.
* @param onlyImmutable if {@code true}, do not consider mutable requirements such as link
* bandwidth, signal strength, or validation / captive portal status.
*
* @hide
*/
private boolean satisfiedByNetworkCapabilities(NetworkCapabilities nc, boolean onlyImmutable) {
return (nc != null
&& satisfiedByNetCapabilities(nc, onlyImmutable)
&& satisfiedByTransportTypes(nc)
&& (onlyImmutable || satisfiedByLinkBandwidths(nc))
&& satisfiedBySpecifier(nc)
&& satisfiedByEnterpriseCapabilitiesId(nc)
&& (onlyImmutable || satisfiedBySignalStrength(nc))
&& (onlyImmutable || satisfiedByUids(nc))
&& (onlyImmutable || satisfiedBySSID(nc))
&& (onlyImmutable || satisfiedByRequestor(nc))
&& (onlyImmutable || satisfiedBySubscriptionIds(nc)));
}
/**
* Check if our requirements are satisfied by the given {@code NetworkCapabilities}.
*
* @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements.
*
* @hide
*/
@SystemApi
public boolean satisfiedByNetworkCapabilities(@Nullable NetworkCapabilities nc) {
return satisfiedByNetworkCapabilities(nc, false);
}
/**
* Check if our immutable requirements are satisfied by the given {@code NetworkCapabilities}.
*
* @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements.
*
* @hide
*/
public boolean satisfiedByImmutableNetworkCapabilities(@Nullable NetworkCapabilities nc) {
return satisfiedByNetworkCapabilities(nc, true);
}
/**
* Checks that our immutable capabilities are the same as those of the given
* {@code NetworkCapabilities} and return a String describing any difference.
* The returned String is empty if there is no difference.
*
* @hide
*/
public String describeImmutableDifferences(@Nullable NetworkCapabilities that) {
if (that == null) {
return "other NetworkCapabilities was null";
}
StringJoiner joiner = new StringJoiner(", ");
// Ignore NOT_METERED being added or removed as it is effectively dynamic. http://b/63326103
// TODO: properly support NOT_METERED as a mutable and requestable capability.
final long mask = ~MUTABLE_CAPABILITIES & ~(1 << NET_CAPABILITY_NOT_METERED);
long oldImmutableCapabilities = this.mNetworkCapabilities & mask;
long newImmutableCapabilities = that.mNetworkCapabilities & mask;
if (oldImmutableCapabilities != newImmutableCapabilities) {
String before = capabilityNamesOf(NetworkCapabilitiesUtils.unpackBits(
oldImmutableCapabilities));
String after = capabilityNamesOf(NetworkCapabilitiesUtils.unpackBits(
newImmutableCapabilities));
joiner.add(String.format("immutable capabilities changed: %s -> %s", before, after));
}
if (!equalsSpecifier(that)) {
NetworkSpecifier before = this.getNetworkSpecifier();
NetworkSpecifier after = that.getNetworkSpecifier();
joiner.add(String.format("specifier changed: %s -> %s", before, after));
}
if (!equalsTransportTypes(that)) {
String before = transportNamesOf(this.getTransportTypes());
String after = transportNamesOf(that.getTransportTypes());
joiner.add(String.format("transports changed: %s -> %s", before, after));
}
return joiner.toString();
}
/**
* Checks that our requestable capabilities are the same as those of the given
* {@code NetworkCapabilities}.
*
* @hide
*/
public boolean equalRequestableCapabilities(@Nullable NetworkCapabilities nc) {
if (nc == null) return false;
return (equalsNetCapabilitiesRequestable(nc)
&& equalsTransportTypes(nc)
&& equalsSpecifier(nc));
}
@Override
public boolean equals(@Nullable Object obj) {
if (obj == null || (obj instanceof NetworkCapabilities == false)) return false;
NetworkCapabilities that = (NetworkCapabilities) obj;
return equalsNetCapabilities(that)
&& equalsTransportTypes(that)
&& equalsLinkBandwidths(that)
&& equalsSignalStrength(that)
&& equalsSpecifier(that)
&& equalsTransportInfo(that)
&& equalsUids(that)
&& equalsAllowedUids(that)
&& equalsSSID(that)
&& equalsOwnerUid(that)
&& equalsPrivateDnsBroken(that)
&& equalsRequestor(that)
&& equalsAdministratorUids(that)
&& equalsSubscriptionIds(that)
&& equalsUnderlyingNetworks(that)
&& equalsEnterpriseCapabilitiesId(that);
}
@Override
public int hashCode() {
return (int) (mNetworkCapabilities & 0xFFFFFFFF)
+ ((int) (mNetworkCapabilities >> 32) * 3)
+ ((int) (mForbiddenNetworkCapabilities & 0xFFFFFFFF) * 5)
+ ((int) (mForbiddenNetworkCapabilities >> 32) * 7)
+ ((int) (mTransportTypes & 0xFFFFFFFF) * 11)
+ ((int) (mTransportTypes >> 32) * 13)
+ mLinkUpBandwidthKbps * 17
+ mLinkDownBandwidthKbps * 19
+ Objects.hashCode(mNetworkSpecifier) * 23
+ mSignalStrength * 29
+ mOwnerUid * 31
+ Objects.hashCode(mUids) * 37
+ Objects.hashCode(mAllowedUids) * 41
+ Objects.hashCode(mSSID) * 43
+ Objects.hashCode(mTransportInfo) * 47
+ Objects.hashCode(mPrivateDnsBroken) * 53
+ Objects.hashCode(mRequestorUid) * 59
+ Objects.hashCode(mRequestorPackageName) * 61
+ Arrays.hashCode(mAdministratorUids) * 67
+ Objects.hashCode(mSubIds) * 71
+ Objects.hashCode(mUnderlyingNetworks) * 73
+ mEnterpriseId * 79;
}
@Override
public int describeContents() {
return 0;
}
private
* nc is assumed nonnull. Else, NPE.
*/
private boolean satisfiedByRequestor(NetworkCapabilities nc) {
// No uid set, matches everything.
if (mRequestorUid == Process.INVALID_UID || nc.mRequestorUid == Process.INVALID_UID) {
return true;
}
// uids don't match.
if (mRequestorUid != nc.mRequestorUid) return false;
// No package names set, matches everything
if (null == nc.mRequestorPackageName || null == mRequestorPackageName) return true;
// check for package name match.
return TextUtils.equals(mRequestorPackageName, nc.mRequestorPackageName);
}
private boolean equalsRequestor(NetworkCapabilities nc) {
return mRequestorUid == nc.mRequestorUid
&& TextUtils.equals(mRequestorPackageName, nc.mRequestorPackageName);
}
/**
* Set of the subscription IDs that identifies the network or request, empty if none.
*/
@NonNull
private ArraySet Instances of NetworkCapabilities will only have this field populated by the system if the
* receiver holds the NETWORK_FACTORY permission. In all other cases, it will be the empty set.
*
* @return
* @hide
*/
@NonNull
@SystemApi
public Set UIDs included in administratorUids gain administrator privileges over this
* Network. Examples of UIDs that should be included in administratorUids are:
* In general, user-supplied networks (such as WiFi networks) do not have
* administrators.
*
* An app is granted owner privileges over Networks that it supplies. The owner
* UID MUST always be included in administratorUids.
*
* The default value is the empty array. Pass an empty array to reset.
*
* Note: for security the system will clear out this field when received from a
* non-privileged source, such as an app using reflection to call this or
* mutate the member in the built object.
*
* @param administratorUids the UIDs to be set as administrators of this Network.
* @return this builder
*/
@NonNull
@RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
public Builder setAdministratorUids(@NonNull final int[] administratorUids) {
Objects.requireNonNull(administratorUids);
mCaps.setAdministratorUids(administratorUids);
return this;
}
/**
* Sets the upstream bandwidth of the link.
*
* Sets the upstream bandwidth for this network in Kbps. This always only refers to
* the estimated first hop transport bandwidth.
*
* Note that when used to request a network, this specifies the minimum acceptable.
* When received as the state of an existing network this specifies the typical
* first hop bandwidth expected. This is never measured, but rather is inferred
* from technology type and other link parameters. It could be used to differentiate
* between very slow 1xRTT cellular links and other faster networks or even between
* 802.11b vs 802.11AC wifi technologies. It should not be used to differentiate between
* fast backhauls and slow backhauls.
*
* @param upKbps the estimated first hop upstream (device to network) bandwidth.
* @return this builder
*/
@NonNull
public Builder setLinkUpstreamBandwidthKbps(final int upKbps) {
mCaps.setLinkUpstreamBandwidthKbps(upKbps);
return this;
}
/**
* Sets the downstream bandwidth for this network in Kbps. This always only refers to
* the estimated first hop transport bandwidth.
*
* Note that when used to request a network, this specifies the minimum acceptable.
* When received as the state of an existing network this specifies the typical
* first hop bandwidth expected. This is never measured, but rather is inferred
* from technology type and other link parameters. It could be used to differentiate
* between very slow 1xRTT cellular links and other faster networks or even between
* 802.11b vs 802.11AC wifi technologies. It should not be used to differentiate between
* fast backhauls and slow backhauls.
*
* @param downKbps the estimated first hop downstream (network to device) bandwidth.
* @return this builder
*/
@NonNull
public Builder setLinkDownstreamBandwidthKbps(final int downKbps) {
mCaps.setLinkDownstreamBandwidthKbps(downKbps);
return this;
}
/**
* Sets the optional bearer specific network specifier.
* This has no meaning if a single transport is also not specified, so calling
* this without a single transport set will generate an exception, as will
* subsequently adding or removing transports after this is set.
*
* Note that when used to register a network callback, this specifies the minimum
* acceptable signal strength. When received as the state of an existing network it
* specifies the current value. A value of code SIGNAL_STRENGTH_UNSPECIFIED} means
* no value when received and has no effect when requesting a callback.
*
* Note: for security the system will throw if it receives a NetworkRequest where
* the underlying NetworkCapabilities has this member set from a source that does
* not hold the {@link android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP}
* permission. Apps with this permission can use this indirectly through
* {@link android.net.NetworkRequest}.
*
* @param signalStrength the bearer-specific signal strength.
* @return this builder
*/
@NonNull
@RequiresPermission(android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP)
public Builder setSignalStrength(final int signalStrength) {
mCaps.setSignalStrength(signalStrength);
return this;
}
/**
* Sets the SSID of this network.
*
* Note: for security the system will clear out this field when received from a
* non-privileged source, like an app using reflection to set this.
*
* @param ssid the SSID, or null to clear it.
* @return this builder
*/
@NonNull
@RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
public Builder setSsid(@Nullable final String ssid) {
mCaps.setSSID(ssid);
return this;
}
/**
* Set the uid of the app causing this network to exist.
*
* Note: for security the system will clear out this field when received from a
* non-privileged source.
*
* @param uid UID of the app.
* @return this builder
*/
@NonNull
@RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
public Builder setRequestorUid(final int uid) {
mCaps.setRequestorUid(uid);
return this;
}
/**
* Set the package name of the app causing this network to exist.
*
* Note: for security the system will clear out this field when received from a
* non-privileged source.
*
* @param packageName package name of the app, or null to clear it.
* @return this builder
*/
@NonNull
@RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
public Builder setRequestorPackageName(@Nullable final String packageName) {
mCaps.setRequestorPackageName(packageName);
return this;
}
/**
* Set the subscription ID set.
*
* SubIds are populated in NetworkCapability instances from the system only for callers
* that hold the NETWORK_FACTORY permission. Similarly, the system will reject any
* NetworkRequests filed with a non-empty set of subIds unless the caller holds the
* NETWORK_FACTORY permission.
*
* @param subIds a set that represent the subscription IDs. Empty if clean up.
* @return this builder.
* @hide
*/
@NonNull
@SystemApi
public Builder setSubscriptionIds(@NonNull final Set
* Provide a list of UIDs that can access this network even if the network doesn't have the
* {@link #NET_CAPABILITY_NOT_RESTRICTED} capability and the UID does not hold the
* {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission.
*
* This is disallowed in {@link NetworkRequest}, and can only be set by
* {@link NetworkAgent}s, who hold the
* {@link android.Manifest.permission.NETWORK_FACTORY} permission.
* Network agents also have restrictions on how they can set theseĀ ; they can only back
* a public Android API. As such, Ethernet agents can set this when backing the per-UID
* access API, and Telephony can set exactly one UID which has to match the manager app for
* the associated subscription. Failure to comply with these rules will see this member
* cleared.
*
* These UIDs are only visible to network factories and the system server, since the system
* server makes sure to redact them before sending a {@link NetworkCapabilities} instance
* to a process that doesn't hold the {@link android.Manifest.permission.NETWORK_FACTORY}
* permission.
*
* This list cannot be null, but it can be empty to mean that no UID without the
* {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission
* gets to access this network.
*
* @param uids the list of UIDs that can always access this network
* @return this builder
* @hide
*/
@NonNull
@SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
@RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
public Builder setAllowedUids(@NonNull Set This API is mainly for {@link NetworkAgent}s who hold
* {@link android.Manifest.permission.NETWORK_FACTORY} to set its underlying networks.
*
* The underlying networks are only visible for the receiver who has one of
* {@link android.Manifest.permission.NETWORK_FACTORY},
* {@link android.Manifest.permission.NETWORK_SETTINGS} and
* {@link NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}.
* If the receiver doesn't have required permissions, the field will be cleared before
* sending to the caller.
*
*
*
*
*
* This is because the owner UID is location-sensitive. The apps that request a network could
* know where the device is if they can tell for sure the system has connected to the network
* they requested.
*
*
*
*
*
*
*
* Instances of NetworkCapabilities sent to apps without the appropriate permissions will have
* this field cleared out.
*
*
*
*
*
*
*
*