1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.net;
18 
19 import static com.android.internal.annotations.VisibleForTesting.Visibility.PRIVATE;
20 import static com.android.net.module.util.BitUtils.appendStringRepresentationOfBitMaskToStringBuilder;
21 import static com.android.net.module.util.BitUtils.describeDifferences;
22 
23 import android.annotation.FlaggedApi;
24 import android.annotation.IntDef;
25 import android.annotation.LongDef;
26 import android.annotation.NonNull;
27 import android.annotation.Nullable;
28 import android.annotation.RequiresPermission;
29 import android.annotation.SuppressLint;
30 import android.annotation.SystemApi;
31 import android.compat.annotation.UnsupportedAppUsage;
32 import android.net.ConnectivityManager.NetworkCallback;
33 import android.os.Build;
34 import android.os.Parcel;
35 import android.os.Parcelable;
36 import android.os.Process;
37 import android.text.TextUtils;
38 import android.util.ArraySet;
39 import android.util.Log;
40 import android.util.Range;
41 
42 import com.android.internal.annotations.VisibleForTesting;
43 import com.android.modules.utils.build.SdkLevel;
44 import com.android.net.module.util.BitUtils;
45 import com.android.net.module.util.CollectionUtils;
46 import com.android.net.module.util.NetworkCapabilitiesUtils;
47 
48 import java.lang.annotation.Retention;
49 import java.lang.annotation.RetentionPolicy;
50 import java.util.ArrayList;
51 import java.util.Arrays;
52 import java.util.Collections;
53 import java.util.List;
54 import java.util.Objects;
55 import java.util.Set;
56 import java.util.StringJoiner;
57 
58 /**
59  * Representation of the capabilities of an active network.
60  *
61  * <p>@see <a href="https://developer.android.com/training/basics/network-ops/reading-network-state>
62  * this general guide</a> on how to use NetworkCapabilities and related classes.
63  *
64  * <p>NetworkCapabilities represent what a network can do and what its
65  * characteristics are like. The principal attribute of NetworkCapabilities
66  * is in the capabilities bits, which are checked with
67  * {@link #hasCapability(int)}. See the list of capabilities and each
68  * capability for a description of what it means.
69  *
70  * <p>Some prime examples include {@code NET_CAPABILITY_MMS}, which means that the
71  * network is capable of sending MMS. A network without this capability
72  * is not capable of sending MMS.
73  * <p>The {@code NET_CAPABILITY_INTERNET} capability means that the network is
74  * configured to reach the general Internet. It may or may not actually
75  * provide connectivity ; the {@code NET_CAPABILITY_VALIDATED} bit indicates that
76  * the system found actual connectivity to the general Internet the last
77  * time it checked. Apps interested in actual connectivity should usually
78  * look at both these capabilities.
79  * <p>The {@code NET_CAPABILITY_NOT_METERED} capability is set for networks that
80  * do not bill the user for consumption of bytes. Applications are
81  * encouraged to consult this to determine appropriate usage, and to
82  * limit usage of metered network where possible, including deferring
83  * big downloads until such a time that an unmetered network is connected.
84  * Also see {@link android.app.job.JobScheduler} to help with scheduling such
85  * downloads, in particular
86  * {@link android.app.job.JobInfo.Builder#setRequiredNetwork(NetworkRequest)}.
87  * <p>NetworkCapabilities contain a number of other capabilities that
88  * represent what modern networks can and can't do. Look up the individual
89  * capabilities in this class to learn about each of them.
90  *
91  * <p>NetworkCapabilities typically represent attributes that can apply to
92  * any network. The attributes that apply only to specific transports like
93  * cellular or Wi-Fi can be found in the specifier (for requestable attributes)
94  * or in the transport info (for non-requestable ones). See
95  * {@link #getNetworkSpecifier} and {@link #getTransportInfo}. An app would
96  * downcast these to the specific class for the transport they need if they
97  * are interested in transport-specific attributes. Also see
98  * {@link android.net.wifi.WifiNetworkSpecifier} or
99  * {@link android.net.wifi.WifiInfo} for some examples of each of these.
100  *
101  * <p>NetworkCapabilities also contains other attributes like the estimated
102  * upstream and downstream bandwidth and the specific transport of that
103  * network (e.g. {@link #TRANSPORT_CELLULAR}). Generally, apps should normally
104  * have little reason to check for the type of transport ; for example, to
105  * query whether a network costs money to the user, do not look at the
106  * transport, but instead look at the absence or presence of
107  * {@link #NET_CAPABILITY_NOT_METERED} which will correctly account for
108  * metered Wi-Fis and free of charge cell connections.
109  *
110  * <p>The system communicates with apps about connected networks and uses
111  * NetworkCapabilities to express these capabilities about these networks.
112  * Apps should register callbacks with the {@link ConnectivityManager#requestNetwork}
113  * or {@link ConnectivityManager#registerNetworkCallback} family of methods
114  * to learn about the capabilities of a network on a continuous basis
115  * and be able to react to changes to capabilities. For quick debugging Android also
116  * provides {@link ConnectivityManager#getNetworkCapabilities(Network)},
117  * but the dynamic nature of networking makes this ill-suited to production
118  * code since capabilities obtained in this way can go stale immediately.
119  *
120  * <p>Also see {@link NetworkRequest} which uses the same capabilities
121  * together with {@link ConnectivityManager#requestNetwork} for how to
122  * request the system brings up the kind of network your application needs.
123  */
124 public final class NetworkCapabilities implements Parcelable {
125     private static final String TAG = "NetworkCapabilities";
126 
127     // TODO : remove this class when udc-mainline-prod is abandoned and android.net.flags.Flags is
128     // available here
129     /** @hide */
130     public static class Flags {
131         static final String FLAG_FORBIDDEN_CAPABILITY =
132                 "com.android.net.flags.forbidden_capability";
133         static final String FLAG_NET_CAPABILITY_LOCAL_NETWORK =
134                 "com.android.net.flags.net_capability_local_network";
135         static final String REQUEST_RESTRICTED_WIFI =
136                 "com.android.net.flags.request_restricted_wifi";
137         static final String SUPPORT_TRANSPORT_SATELLITE =
138                 "com.android.net.flags.support_transport_satellite";
139         static final String NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED =
140                 "com.android.net.flags.net_capability_not_bandwidth_constrained";
141     }
142 
143     /**
144      * Mechanism to support redaction of fields in NetworkCapabilities that are guarded by specific
145      * app permissions.
146      **/
147     /**
148      * Don't redact any fields since the receiving app holds all the necessary permissions.
149      *
150      * @hide
151      */
152     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
153     public static final long REDACT_NONE = 0;
154 
155     /**
156      * Redact any fields that need {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
157      * permission since the receiving app does not hold this permission or the location toggle
158      * is off.
159      *
160      * @see android.Manifest.permission#ACCESS_FINE_LOCATION
161      * @hide
162      */
163     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
164     public static final long REDACT_FOR_ACCESS_FINE_LOCATION = 1 << 0;
165 
166     /**
167      * Redact any fields that need {@link android.Manifest.permission#LOCAL_MAC_ADDRESS}
168      * permission since the receiving app does not hold this permission.
169      *
170      * @see android.Manifest.permission#LOCAL_MAC_ADDRESS
171      * @hide
172      */
173     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
174     public static final long REDACT_FOR_LOCAL_MAC_ADDRESS = 1 << 1;
175 
176     /**
177      *
178      * Redact any fields that need {@link android.Manifest.permission#NETWORK_SETTINGS}
179      * permission since the receiving app does not hold this permission.
180      *
181      * @see android.Manifest.permission#NETWORK_SETTINGS
182      * @hide
183      */
184     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
185     public static final long REDACT_FOR_NETWORK_SETTINGS = 1 << 2;
186 
187     /**
188      * Redact all fields in this object that require any relevant permission.
189      * @hide
190      */
191     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
192     public static final long REDACT_ALL = -1L;
193 
194     /** @hide */
195     @LongDef(flag = true, prefix = { "REDACT_" }, value = {
196             REDACT_NONE,
197             REDACT_FOR_ACCESS_FINE_LOCATION,
198             REDACT_FOR_LOCAL_MAC_ADDRESS,
199             REDACT_FOR_NETWORK_SETTINGS,
200             REDACT_ALL
201     })
202     @Retention(RetentionPolicy.SOURCE)
203     public @interface RedactionType {}
204 
205     // Set to true when private DNS is broken.
206     private boolean mPrivateDnsBroken;
207 
208     // Underlying networks, if any. VPNs and VCNs typically have underlying networks.
209     // This is an unmodifiable list and it will be returned as is in the getter.
210     @Nullable
211     private List<Network> mUnderlyingNetworks;
212 
213     /**
214      * Uid of the app making the request.
215      */
216     private int mRequestorUid;
217 
218     /**
219      * Package name of the app making the request.
220      */
221     private String mRequestorPackageName;
222 
223     /**
224      * Enterprise capability identifier 1. It will be used to uniquely identify specific
225      * enterprise network.
226      */
227     public static final int NET_ENTERPRISE_ID_1 = 1;
228 
229     /**
230      * Enterprise capability identifier 2. It will be used to uniquely identify specific
231      * enterprise network.
232      */
233     public static final int NET_ENTERPRISE_ID_2 = 2;
234 
235     /**
236      * Enterprise capability identifier 3. It will be used to uniquely identify specific
237      * enterprise network.
238      */
239     public static final int NET_ENTERPRISE_ID_3 = 3;
240 
241     /**
242      * Enterprise capability identifier 4. It will be used to uniquely identify specific
243      * enterprise network.
244      */
245     public static final int NET_ENTERPRISE_ID_4 = 4;
246 
247     /**
248      * Enterprise capability identifier 5. It will be used to uniquely identify specific
249      * enterprise network.
250      */
251     public static final int NET_ENTERPRISE_ID_5 = 5;
252 
253     /** @hide */
254     @Retention(RetentionPolicy.SOURCE)
255     @IntDef(prefix = { "NET_CAPABILITY_ENTERPRISE_SUB_LEVEL" }, value = {
256             NET_ENTERPRISE_ID_1,
257             NET_ENTERPRISE_ID_2,
258             NET_ENTERPRISE_ID_3,
259             NET_ENTERPRISE_ID_4,
260             NET_ENTERPRISE_ID_5,
261     })
262     public @interface EnterpriseId {
263     }
264 
265     private static final int ALL_VALID_ENTERPRISE_IDS;
266     static {
267         int enterpriseIds = 0;
268         for (int i = NET_ENTERPRISE_ID_1; i <= NET_ENTERPRISE_ID_5; ++i) {
269             enterpriseIds |= 1 << i;
270         }
271         ALL_VALID_ENTERPRISE_IDS = enterpriseIds;
272     }
273 
274     /**
275      * Bitfield representing the network's enterprise capability identifier.  If any are specified
276      * they will be satisfied by any Network that matches all of them.
277      * See {@link #addEnterpriseId(int)} for details on how masks are added
278      */
279     private int mEnterpriseId;
280 
281     /**
282      * Gets the enterprise IDs as an int. Internal callers only.
283      *
284      * DO NOT USE THIS if not immediately collapsing back into a scalar. Instead,
285      * prefer getEnterpriseIds/hasEnterpriseId.
286      *
287      * @return the internal, version-dependent int representing enterprise ids
288      * @hide
289      */
getEnterpriseIdsInternal()290     public int getEnterpriseIdsInternal() {
291         return mEnterpriseId;
292     }
293 
294     /**
295      * Get enteprise identifiers set.
296      *
297      * Get all the enterprise capabilities identifier set on this {@code NetworkCapability}
298      * If NET_CAPABILITY_ENTERPRISE is set and no enterprise ID is set, it is
299      * considered to have NET_CAPABILITY_ENTERPRISE by default.
300      * @return all the enterprise capabilities identifier set.
301      *
302      */
getEnterpriseIds()303     public @NonNull @EnterpriseId int[] getEnterpriseIds() {
304         if (hasCapability(NET_CAPABILITY_ENTERPRISE) && mEnterpriseId == 0) {
305             return new int[]{NET_ENTERPRISE_ID_1};
306         }
307         return BitUtils.unpackBits(mEnterpriseId);
308     }
309 
310     /**
311      * Tests for the presence of an enterprise capability identifier on this instance.
312      *
313      * If NET_CAPABILITY_ENTERPRISE is set and no enterprise ID is set, it is
314      * considered to have NET_CAPABILITY_ENTERPRISE by default.
315      * @param enterpriseId the enterprise capability identifier to be tested for.
316      * @return {@code true} if set on this instance.
317      */
hasEnterpriseId( @nterpriseId int enterpriseId)318     public boolean hasEnterpriseId(
319             @EnterpriseId int enterpriseId) {
320         if (enterpriseId == NET_ENTERPRISE_ID_1) {
321             if (hasCapability(NET_CAPABILITY_ENTERPRISE) && mEnterpriseId == 0) {
322                 return true;
323             }
324         }
325         return isValidEnterpriseId(enterpriseId)
326                 && ((mEnterpriseId & (1L << enterpriseId)) != 0);
327     }
328 
NetworkCapabilities()329     public NetworkCapabilities() {
330         clearAll();
331         mNetworkCapabilities = DEFAULT_CAPABILITIES;
332     }
333 
NetworkCapabilities(NetworkCapabilities nc)334     public NetworkCapabilities(NetworkCapabilities nc) {
335         this(nc, REDACT_NONE);
336     }
337 
338     /**
339      * Make a copy of NetworkCapabilities.
340      *
341      * @param nc Original NetworkCapabilities
342      * @param redactions bitmask of redactions that needs to be performed on this new instance of
343      *                   {@link NetworkCapabilities}.
344      * @hide
345      */
NetworkCapabilities(@ullable NetworkCapabilities nc, @RedactionType long redactions)346     public NetworkCapabilities(@Nullable NetworkCapabilities nc, @RedactionType long redactions) {
347         if (nc != null) {
348             set(nc);
349         }
350         if (mTransportInfo != null) {
351             mTransportInfo = nc.mTransportInfo.makeCopy(redactions);
352         }
353     }
354 
355     /**
356      * Completely clears the contents of this object, removing even the capabilities that are set
357      * by default when the object is constructed.
358      * @hide
359      */
clearAll()360     public void clearAll() {
361         mNetworkCapabilities = mTransportTypes = mForbiddenNetworkCapabilities = 0;
362         mLinkUpBandwidthKbps = mLinkDownBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED;
363         mNetworkSpecifier = null;
364         mTransportInfo = null;
365         mSignalStrength = SIGNAL_STRENGTH_UNSPECIFIED;
366         mUids = null;
367         mAllowedUids.clear();
368         mAdministratorUids = new int[0];
369         mOwnerUid = Process.INVALID_UID;
370         mSSID = null;
371         mPrivateDnsBroken = false;
372         mRequestorUid = Process.INVALID_UID;
373         mRequestorPackageName = null;
374         mSubIds = new ArraySet<>();
375         mUnderlyingNetworks = null;
376         mEnterpriseId = 0;
377     }
378 
379     /**
380      * Set all contents of this object to the contents of a NetworkCapabilities.
381      *
382      * @param nc Original NetworkCapabilities
383      * @hide
384      */
set(@onNull NetworkCapabilities nc)385     public void set(@NonNull NetworkCapabilities nc) {
386         mNetworkCapabilities = nc.mNetworkCapabilities;
387         mTransportTypes = nc.mTransportTypes;
388         mLinkUpBandwidthKbps = nc.mLinkUpBandwidthKbps;
389         mLinkDownBandwidthKbps = nc.mLinkDownBandwidthKbps;
390         mNetworkSpecifier = nc.mNetworkSpecifier;
391         if (nc.getTransportInfo() != null) {
392             setTransportInfo(nc.getTransportInfo());
393         } else {
394             setTransportInfo(null);
395         }
396         mSignalStrength = nc.mSignalStrength;
397         mUids = (nc.mUids == null) ? null : new ArraySet<>(nc.mUids);
398         setAllowedUids(nc.mAllowedUids);
399         setAdministratorUids(nc.getAdministratorUids());
400         mOwnerUid = nc.mOwnerUid;
401         mForbiddenNetworkCapabilities = nc.mForbiddenNetworkCapabilities;
402         mSSID = nc.mSSID;
403         mPrivateDnsBroken = nc.mPrivateDnsBroken;
404         mRequestorUid = nc.mRequestorUid;
405         mRequestorPackageName = nc.mRequestorPackageName;
406         mSubIds = new ArraySet<>(nc.mSubIds);
407         // mUnderlyingNetworks is an unmodifiable list if non-null, so a defensive copy is not
408         // necessary.
409         mUnderlyingNetworks = nc.mUnderlyingNetworks;
410         mEnterpriseId = nc.mEnterpriseId;
411     }
412 
413     /**
414      * Represents the network's capabilities.  If any are specified they will be satisfied
415      * by any Network that matches all of them.
416      */
417     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
418     private long mNetworkCapabilities;
419 
420     /**
421      * If any capabilities specified here they must not exist in the matching Network.
422      */
423     private long mForbiddenNetworkCapabilities;
424 
425     /** @hide */
426     @Retention(RetentionPolicy.SOURCE)
427     @IntDef(prefix = { "NET_CAPABILITY_" }, value = {
428             NET_CAPABILITY_MMS,
429             NET_CAPABILITY_SUPL,
430             NET_CAPABILITY_DUN,
431             NET_CAPABILITY_FOTA,
432             NET_CAPABILITY_IMS,
433             NET_CAPABILITY_CBS,
434             NET_CAPABILITY_WIFI_P2P,
435             NET_CAPABILITY_IA,
436             NET_CAPABILITY_RCS,
437             NET_CAPABILITY_XCAP,
438             NET_CAPABILITY_EIMS,
439             NET_CAPABILITY_NOT_METERED,
440             NET_CAPABILITY_INTERNET,
441             NET_CAPABILITY_NOT_RESTRICTED,
442             NET_CAPABILITY_TRUSTED,
443             NET_CAPABILITY_NOT_VPN,
444             NET_CAPABILITY_VALIDATED,
445             NET_CAPABILITY_CAPTIVE_PORTAL,
446             NET_CAPABILITY_NOT_ROAMING,
447             NET_CAPABILITY_FOREGROUND,
448             NET_CAPABILITY_NOT_CONGESTED,
449             NET_CAPABILITY_NOT_SUSPENDED,
450             NET_CAPABILITY_OEM_PAID,
451             NET_CAPABILITY_MCX,
452             NET_CAPABILITY_PARTIAL_CONNECTIVITY,
453             NET_CAPABILITY_TEMPORARILY_NOT_METERED,
454             NET_CAPABILITY_OEM_PRIVATE,
455             NET_CAPABILITY_VEHICLE_INTERNAL,
456             NET_CAPABILITY_NOT_VCN_MANAGED,
457             NET_CAPABILITY_ENTERPRISE,
458             NET_CAPABILITY_VSIM,
459             NET_CAPABILITY_BIP,
460             NET_CAPABILITY_HEAD_UNIT,
461             NET_CAPABILITY_MMTEL,
462             NET_CAPABILITY_PRIORITIZE_LATENCY,
463             NET_CAPABILITY_PRIORITIZE_BANDWIDTH,
464             NET_CAPABILITY_LOCAL_NETWORK,
465             NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED,
466     })
467     public @interface NetCapability { }
468 
469     /**
470      * Indicates this is a network that has the ability to reach the
471      * carrier's MMSC for sending and receiving MMS messages.
472      */
473     public static final int NET_CAPABILITY_MMS            = 0;
474 
475     /**
476      * Indicates this is a network that has the ability to reach the carrier's
477      * SUPL server, used to retrieve GPS information.
478      */
479     public static final int NET_CAPABILITY_SUPL           = 1;
480 
481     /**
482      * Indicates this is a network that has the ability to reach the carrier's
483      * DUN or tethering gateway.
484      */
485     public static final int NET_CAPABILITY_DUN            = 2;
486 
487     /**
488      * Indicates this is a network that has the ability to reach the carrier's
489      * FOTA portal, used for over the air updates.
490      */
491     public static final int NET_CAPABILITY_FOTA           = 3;
492 
493     /**
494      * Indicates this is a network that has the ability to reach the carrier's
495      * IMS servers, used for network registration and signaling.
496      */
497     public static final int NET_CAPABILITY_IMS            = 4;
498 
499     /**
500      * Indicates this is a network that has the ability to reach the carrier's
501      * CBS servers, used for carrier specific services.
502      */
503     public static final int NET_CAPABILITY_CBS            = 5;
504 
505     /**
506      * Indicates this is a network that has the ability to reach a Wi-Fi direct
507      * peer.
508      */
509     public static final int NET_CAPABILITY_WIFI_P2P       = 6;
510 
511     /**
512      * Indicates this is a network that has the ability to reach a carrier's
513      * Initial Attach servers.
514      */
515     public static final int NET_CAPABILITY_IA             = 7;
516 
517     /**
518      * Indicates this is a network that has the ability to reach a carrier's
519      * RCS servers, used for Rich Communication Services.
520      */
521     public static final int NET_CAPABILITY_RCS            = 8;
522 
523     /**
524      * Indicates this is a network that has the ability to reach a carrier's
525      * XCAP servers, used for configuration and control.
526      */
527     public static final int NET_CAPABILITY_XCAP           = 9;
528 
529     /**
530      * Indicates this is a network that has the ability to reach a carrier's
531      * Emergency IMS servers or other services, used for network signaling
532      * during emergency calls.
533      */
534     public static final int NET_CAPABILITY_EIMS           = 10;
535 
536     /**
537      * Indicates that this network is unmetered.
538      */
539     public static final int NET_CAPABILITY_NOT_METERED    = 11;
540 
541     /**
542      * Indicates that this network should be able to reach the internet.
543      */
544     public static final int NET_CAPABILITY_INTERNET       = 12;
545 
546     /**
547      * Indicates that this network is available for general use.  If this is not set
548      * applications should not attempt to communicate on this network.  Note that this
549      * is simply informative and not enforcement - enforcement is handled via other means.
550      * Set by default.
551      */
552     public static final int NET_CAPABILITY_NOT_RESTRICTED = 13;
553 
554     /**
555      * Indicates that the user has indicated implicit trust of this network.  This
556      * generally means it's a sim-selected carrier, a plugged in ethernet, a paired
557      * BT device or a wifi the user asked to connect to.  Untrusted networks
558      * are probably limited to unknown wifi AP.  Set by default.
559      */
560     public static final int NET_CAPABILITY_TRUSTED        = 14;
561 
562     /**
563      * Indicates that this network is not a VPN.  This capability is set by default and should be
564      * explicitly cleared for VPN networks.
565      */
566     public static final int NET_CAPABILITY_NOT_VPN        = 15;
567 
568     /**
569      * Indicates that connectivity on this network was successfully validated. For example, for a
570      * network with NET_CAPABILITY_INTERNET, it means that Internet connectivity was successfully
571      * detected.
572      */
573     public static final int NET_CAPABILITY_VALIDATED      = 16;
574 
575     /**
576      * Indicates that this network was found to have a captive portal in place last time it was
577      * probed.
578      */
579     public static final int NET_CAPABILITY_CAPTIVE_PORTAL = 17;
580 
581     /**
582      * Indicates that this network is not roaming.
583      */
584     public static final int NET_CAPABILITY_NOT_ROAMING = 18;
585 
586     /**
587      * Indicates that this network is available for use by apps, and not a network that is being
588      * kept up in the background to facilitate fast network switching.
589      */
590     public static final int NET_CAPABILITY_FOREGROUND = 19;
591 
592     /**
593      * Indicates that this network is not congested.
594      * <p>
595      * When a network is congested, applications should defer network traffic
596      * that can be done at a later time, such as uploading analytics.
597      */
598     public static final int NET_CAPABILITY_NOT_CONGESTED = 20;
599 
600     /**
601      * Indicates that this network is not currently suspended.
602      * <p>
603      * When a network is suspended, the network's IP addresses and any connections
604      * established on the network remain valid, but the network is temporarily unable
605      * to transfer data. This can happen, for example, if a cellular network experiences
606      * a temporary loss of signal, such as when driving through a tunnel, etc.
607      * A network with this capability is not suspended, so is expected to be able to
608      * transfer data.
609      */
610     public static final int NET_CAPABILITY_NOT_SUSPENDED = 21;
611 
612     /**
613      * Indicates that traffic that goes through this network is paid by oem. For example,
614      * this network can be used by system apps to upload telemetry data.
615      * @hide
616      */
617     @SystemApi
618     public static final int NET_CAPABILITY_OEM_PAID = 22;
619 
620     /**
621      * Indicates this is a network that has the ability to reach a carrier's Mission Critical
622      * servers.
623      */
624     public static final int NET_CAPABILITY_MCX = 23;
625 
626     /**
627      * Indicates that this network was tested to only provide partial connectivity.
628      * @hide
629      */
630     @SystemApi
631     public static final int NET_CAPABILITY_PARTIAL_CONNECTIVITY = 24;
632 
633     /**
634      * Indicates that this network is temporarily unmetered.
635      * <p>
636      * This capability will be set for networks that are generally metered, but are currently
637      * unmetered, e.g., because the user is in a particular area. This capability can be changed at
638      * any time. When it is removed, applications are responsible for stopping any data transfer
639      * that should not occur on a metered network.
640      * Note that most apps should use {@link #NET_CAPABILITY_NOT_METERED} instead. For more
641      * information, see https://developer.android.com/about/versions/11/features/5g#meteredness.
642      */
643     public static final int NET_CAPABILITY_TEMPORARILY_NOT_METERED = 25;
644 
645     /**
646      * Indicates that this network is private to the OEM and meant only for OEM use.
647      * @hide
648      */
649     @SystemApi
650     public static final int NET_CAPABILITY_OEM_PRIVATE = 26;
651 
652     /**
653      * Indicates this is an internal vehicle network, meant to communicate with other
654      * automotive systems.
655      *
656      * @hide
657      */
658     @SystemApi
659     public static final int NET_CAPABILITY_VEHICLE_INTERNAL = 27;
660 
661     /**
662      * Indicates that this network is not subsumed by a Virtual Carrier Network (VCN).
663      * <p>
664      * To provide an experience on a VCN similar to a single traditional carrier network, in
665      * some cases the system sets this bit is set by default in application's network requests,
666      * and may choose to remove it at its own discretion when matching the request to a network.
667      * <p>
668      * Applications that want to know about a Virtual Carrier Network's underlying networks,
669      * for example to use them for multipath purposes, should remove this bit from their network
670      * requests ; the system will not add it back once removed.
671      * @hide
672      */
673     @SystemApi
674     public static final int NET_CAPABILITY_NOT_VCN_MANAGED = 28;
675 
676     /**
677      * Indicates that this network is intended for enterprise use.
678      * <p>
679      * 5G URSP rules may indicate that all data should use a connection dedicated for enterprise
680      * use. If the enterprise capability is requested, all enterprise traffic will be routed over
681      * the connection with this capability.
682      */
683     public static final int NET_CAPABILITY_ENTERPRISE = 29;
684 
685     /**
686      * Indicates that this network has ability to access the carrier's Virtual Sim service.
687      * @hide
688      */
689     @SystemApi
690     public static final int NET_CAPABILITY_VSIM = 30;
691 
692     /**
693      * Indicates that this network has ability to support Bearer Independent Protol.
694      * @hide
695      */
696     @SystemApi
697     public static final int NET_CAPABILITY_BIP = 31;
698 
699     /**
700      * Indicates that this network is connected to an automotive head unit.
701      */
702     public static final int NET_CAPABILITY_HEAD_UNIT = 32;
703 
704     /**
705      * Indicates that this network has ability to support MMTEL (Multimedia Telephony service).
706      */
707     public static final int NET_CAPABILITY_MMTEL = 33;
708 
709     /**
710      * Indicates that this network should be able to prioritize latency for the internet.
711      *
712      * Starting with {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, requesting this capability with
713      * {@link ConnectivityManager#requestNetwork} requires declaration in the self-certified
714      * network capabilities. See {@link NetworkRequest} for the self-certification documentation.
715      */
716     public static final int NET_CAPABILITY_PRIORITIZE_LATENCY = 34;
717 
718     /**
719      * Indicates that this network should be able to prioritize bandwidth for the internet.
720      *
721      * Starting with {@link Build.VERSION_CODES#UPSIDE_DOWN_CAKE}, requesting this capability with
722      * {@link ConnectivityManager#requestNetwork} requires declaration in the self-certified
723      * network capabilities. See {@link NetworkRequest} for the self-certification documentation.
724      */
725     public static final int NET_CAPABILITY_PRIORITIZE_BANDWIDTH = 35;
726 
727     /**
728      * Indicates that this network is a local network.
729      *
730      * Local networks are networks where the device is not obtaining IP addresses from the
731      * network, but advertising IP addresses itself. Examples of local networks are:
732      * <ul>
733      * <li>USB tethering or Wi-Fi hotspot networks to which the device is sharing its Internet
734      * connectivity.
735      * <li>Thread networks where the current device is the Thread Border Router.
736      * <li>Wi-Fi P2P networks where the current device is the Group Owner.
737      * </ul>
738      *
739      * Networks used to obtain Internet access are never local networks.
740      *
741      * Apps that target an SDK before {@link Build.VERSION_CODES.VANILLA_ICE_CREAM} will not see
742      * networks with this capability unless they explicitly set the NET_CAPABILITY_LOCAL_NETWORK
743      * in their NetworkRequests.
744      */
745     @FlaggedApi(Flags.FLAG_NET_CAPABILITY_LOCAL_NETWORK)
746     public static final int NET_CAPABILITY_LOCAL_NETWORK = 36;
747 
748     /**
749      * Indicates that this is not a bandwidth-constrained network.
750      *
751      * Starting from {@link Build.VERSION_CODES.VANILLA_ICE_CREAM}, this capability is by default
752      * set in {@link NetworkRequest}s and true for most networks.
753      *
754      * If a network lacks this capability, it is bandwidth-constrained. Bandwidth constrained
755      * networks cannot support high-bandwidth data transfers and applications that request and use
756      * them must ensure that they limit bandwidth usage to below the values returned by
757      * {@link #getLinkDownstreamBandwidthKbps()} and {@link #getLinkUpstreamBandwidthKbps()} and
758      * limit the frequency of their network usage. If applications perform high-bandwidth data
759      * transfers on constrained networks or perform network access too frequently, the system may
760      * block the app's access to the network. The system may take other measures to reduce network
761      * usage on constrained networks, such as disabling network access to apps that are not in the
762      * foreground.
763      */
764     @FlaggedApi(Flags.NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED)
765     public static final int NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED = 37;
766 
767     private static final int MAX_NET_CAPABILITY = NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED;
768 
769     // Set all bits up to the MAX_NET_CAPABILITY-th bit
770     private static final long ALL_VALID_CAPABILITIES = (2L << MAX_NET_CAPABILITY) - 1;
771 
772     /**
773      * Network capabilities that are expected to be mutable, i.e., can change while a particular
774      * network is connected.
775      */
776     private static final long MUTABLE_CAPABILITIES =
777             // TRUSTED can change when user explicitly connects to an untrusted network in Settings.
778             // http://b/18206275
779             (1L << NET_CAPABILITY_TRUSTED) |
780             (1L << NET_CAPABILITY_VALIDATED) |
781             (1L << NET_CAPABILITY_CAPTIVE_PORTAL) |
782             (1L << NET_CAPABILITY_NOT_ROAMING) |
783             (1L << NET_CAPABILITY_FOREGROUND) |
784             (1L << NET_CAPABILITY_NOT_CONGESTED) |
785             (1L << NET_CAPABILITY_NOT_SUSPENDED) |
786             (1L << NET_CAPABILITY_PARTIAL_CONNECTIVITY) |
787             (1L << NET_CAPABILITY_TEMPORARILY_NOT_METERED) |
788             (1L << NET_CAPABILITY_NOT_VCN_MANAGED) |
789             // The value of NET_CAPABILITY_HEAD_UNIT is 32, which cannot use int to do bit shift,
790             // otherwise there will be an overflow. Use long to do bit shift instead.
791             (1L << NET_CAPABILITY_HEAD_UNIT);
792 
793     /**
794      * Network capabilities that are not allowed in NetworkRequests. This exists because the
795      * NetworkFactory / NetworkAgent model does not deal well with the situation where a
796      * capability's presence cannot be known in advance. If such a capability is requested, then we
797      * can get into a cycle where the NetworkFactory endlessly churns out NetworkAgents that then
798      * get immediately torn down because they do not have the requested capability.
799      */
800     // Note that as a historical exception, the TRUSTED and NOT_VCN_MANAGED capabilities
801     // are mutable but requestable. Factories are responsible for not getting
802     // in an infinite loop about these.
803     private static final long NON_REQUESTABLE_CAPABILITIES =
804             MUTABLE_CAPABILITIES
805             & ~(1L << NET_CAPABILITY_TRUSTED)
806             & ~(1L << NET_CAPABILITY_NOT_VCN_MANAGED);
807 
808     /**
809      * Capabilities that are set by default when the object is constructed.
810      */
811     private static final long DEFAULT_CAPABILITIES;
812     static {
813         long defaultCapabilities =
814                 (1L << NET_CAPABILITY_NOT_RESTRICTED)
815                 | (1L << NET_CAPABILITY_TRUSTED)
816                 | (1L << NET_CAPABILITY_NOT_VPN);
817         if (SdkLevel.isAtLeastV()) {
818             defaultCapabilities |= (1L << NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED);
819         }
820         DEFAULT_CAPABILITIES = defaultCapabilities;
821     }
822 
823     /**
824      * Capabilities that are managed by ConnectivityService.
825      * @hide
826      */
827     @VisibleForTesting
828     public static final long CONNECTIVITY_MANAGED_CAPABILITIES =
829             (1L << NET_CAPABILITY_VALIDATED) |
830             (1L << NET_CAPABILITY_CAPTIVE_PORTAL) |
831             (1L << NET_CAPABILITY_FOREGROUND) |
832             (1L << NET_CAPABILITY_PARTIAL_CONNECTIVITY);
833 
834     /**
835      * Capabilities that are allowed for all test networks. This list must be set so that it is safe
836      * for an unprivileged user to create a network with these capabilities via shell. As such, it
837      * must never contain capabilities that are generally useful to the system, such as INTERNET,
838      * IMS, SUPL, etc.
839      */
840     private static final long TEST_NETWORKS_ALLOWED_CAPABILITIES =
841             (1L << NET_CAPABILITY_NOT_METERED) |
842             (1L << NET_CAPABILITY_TEMPORARILY_NOT_METERED) |
843             (1L << NET_CAPABILITY_NOT_RESTRICTED) |
844             (1L << NET_CAPABILITY_NOT_VPN) |
845             (1L << NET_CAPABILITY_NOT_ROAMING) |
846             (1L << NET_CAPABILITY_NOT_CONGESTED) |
847             (1L << NET_CAPABILITY_NOT_SUSPENDED) |
848             (1L << NET_CAPABILITY_NOT_VCN_MANAGED) |
849             (1L << NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED);
850 
851 
852     /**
853      * Extra allowed capabilities for test networks that do not have TRANSPORT_CELLULAR. Test
854      * networks with TRANSPORT_CELLULAR must not have those capabilities in order to mitigate
855      * the risk of being used by running apps.
856      */
857     private static final long TEST_NETWORKS_EXTRA_ALLOWED_CAPABILITIES_ON_NON_CELL =
858             (1L << NET_CAPABILITY_CBS) |
859             (1L << NET_CAPABILITY_DUN) |
860             (1L << NET_CAPABILITY_RCS);
861 
862     /**
863      * Adds the given capability to this {@code NetworkCapability} instance.
864      * Note that when searching for a network to satisfy a request, all capabilities
865      * requested must be satisfied.
866      * <p>
867      * If the capability was previously added to the list of forbidden capabilities (either
868      * by default or added using {@link #addForbiddenCapability(int)}), then it will be removed
869      * from the list of forbidden capabilities as well.
870      *
871      * @param capability the capability to be added.
872      * @return This NetworkCapabilities instance, to facilitate chaining.
873      * @hide
874      */
addCapability(@etCapability int capability)875     public @NonNull NetworkCapabilities addCapability(@NetCapability int capability) {
876         // If the given capability was previously added to the list of forbidden capabilities
877         // then the capability will also be removed from the list of forbidden capabilities.
878         // TODO: Add forbidden capabilities to the public API
879         if (!isValidCapability(capability)) {
880             Log.e(TAG, "addCapability is called with invalid capability: " + capability);
881             return this;
882         }
883         mNetworkCapabilities |= 1L << capability;
884         // remove from forbidden capability list
885         mForbiddenNetworkCapabilities &= ~(1L << capability);
886         return this;
887     }
888 
889     /**
890      * Adds the given capability to the list of forbidden capabilities of this
891      * {@code NetworkCapability} instance. Note that when searching for a network to
892      * satisfy a request, the network must not contain any capability from forbidden capability
893      * list.
894      * <p>
895      * If the capability was previously added to the list of required capabilities (for
896      * example, it was there by default or added using {@link #addCapability(int)} method), then
897      * it will be removed from the list of required capabilities as well.
898      *
899      * @see #addCapability(int)
900      * @hide
901      */
addForbiddenCapability(@etCapability int capability)902     public void addForbiddenCapability(@NetCapability int capability) {
903         if (!isValidCapability(capability)) {
904             Log.e(TAG, "addForbiddenCapability is called with invalid capability: " + capability);
905             return;
906         }
907         mForbiddenNetworkCapabilities |= 1L << capability;
908         mNetworkCapabilities &= ~(1L << capability);  // remove from requested capabilities
909     }
910 
911     /**
912      * Removes (if found) the given capability from this {@code NetworkCapability}
913      * instance that were added via addCapability(int) or setCapabilities(int[], int[]).
914      *
915      * @param capability the capability to be removed.
916      * @return This NetworkCapabilities instance, to facilitate chaining.
917      * @hide
918      */
removeCapability(@etCapability int capability)919     public @NonNull NetworkCapabilities removeCapability(@NetCapability int capability) {
920         if (!isValidCapability(capability)) {
921             Log.e(TAG, "removeCapability is called with invalid capability: " + capability);
922             return this;
923         }
924         final long mask = ~(1L << capability);
925         mNetworkCapabilities &= mask;
926         return this;
927     }
928 
929     /**
930      * Removes (if found) the given forbidden capability from this {@link NetworkCapabilities}
931      * instance that were added via addForbiddenCapability(int) or setCapabilities(int[], int[]).
932      *
933      * @param capability the capability to be removed.
934      * @return This NetworkCapabilities instance, to facilitate chaining.
935      * @hide
936      */
removeForbiddenCapability(@etCapability int capability)937     public @NonNull NetworkCapabilities removeForbiddenCapability(@NetCapability int capability) {
938         if (!isValidCapability(capability)) {
939             Log.e(TAG,
940                     "removeForbiddenCapability is called with invalid capability: " + capability);
941             return this;
942         }
943         mForbiddenNetworkCapabilities &= ~(1L << capability);
944         return this;
945     }
946 
947     /**
948      * Removes all forbidden capabilities from this {@link NetworkCapabilities} instance.
949      * @return This NetworkCapabilities instance, to facilitate chaining.
950      * @hide
951      */
removeAllForbiddenCapabilities()952     public @NonNull NetworkCapabilities removeAllForbiddenCapabilities() {
953         mForbiddenNetworkCapabilities = 0;
954         return this;
955     }
956 
957     /**
958      * Sets (or clears) the given capability on this {@link NetworkCapabilities}
959      * instance.
960      * @hide
961      */
setCapability(@etCapability int capability, boolean value)962     public @NonNull NetworkCapabilities setCapability(@NetCapability int capability,
963             boolean value) {
964         if (value) {
965             addCapability(capability);
966         } else {
967             removeCapability(capability);
968         }
969         return this;
970     }
971 
972     /**
973      * Gets the capabilities as an int. Internal callers only.
974      *
975      * DO NOT USE THIS if not immediately collapsing back into a scalar. Instead,
976      * prefer getCapabilities/hasCapability.
977      *
978      * @return an internal, version-dependent int representing the capabilities
979      * @hide
980      */
getCapabilitiesInternal()981     public long getCapabilitiesInternal() {
982         return mNetworkCapabilities;
983     }
984 
985     /**
986      * Gets all the capabilities set on this {@code NetworkCapability} instance.
987      *
988      * @return an array of capability values for this instance.
989      */
getCapabilities()990     public @NonNull @NetCapability int[] getCapabilities() {
991         return BitUtils.unpackBits(mNetworkCapabilities);
992     }
993 
994     /**
995      * Gets all the forbidden capabilities set on this {@code NetworkCapability} instance.
996      *
997      * @return an array of forbidden capability values for this instance.
998      * @hide
999      */
1000     @NonNull
1001     // TODO : @FlaggedApi(Flags.FLAG_FORBIDDEN_CAPABILITY) and public
getForbiddenCapabilities()1002     public @NetCapability int[] getForbiddenCapabilities() {
1003         return BitUtils.unpackBits(mForbiddenNetworkCapabilities);
1004     }
1005 
1006 
1007     /**
1008      * Sets all the capabilities set on this {@code NetworkCapability} instance.
1009      * This overwrites any existing capabilities.
1010      *
1011      * @hide
1012      */
setCapabilities(@etCapability int[] capabilities, @NetCapability int[] forbiddenCapabilities)1013     public void setCapabilities(@NetCapability int[] capabilities,
1014             @NetCapability int[] forbiddenCapabilities) {
1015         mNetworkCapabilities = BitUtils.packBits(capabilities);
1016         mForbiddenNetworkCapabilities = BitUtils.packBits(forbiddenCapabilities);
1017     }
1018 
1019     /**
1020      * @deprecated use {@link #setCapabilities(int[], int[])}
1021      * @hide
1022      */
1023     @Deprecated
setCapabilities(@etCapability int[] capabilities)1024     public void setCapabilities(@NetCapability int[] capabilities) {
1025         setCapabilities(capabilities, new int[] {});
1026     }
1027 
1028     /**
1029      * Adds the given enterprise capability identifier to this {@code NetworkCapability} instance.
1030      * Note that when searching for a network to satisfy a request, all capabilities identifier
1031      * requested must be satisfied.
1032      *
1033      * @param enterpriseId the enterprise capability identifier to be added.
1034      * @return This NetworkCapabilities instance, to facilitate chaining.
1035      * @hide
1036      */
addEnterpriseId( @nterpriseId int enterpriseId)1037     public @NonNull NetworkCapabilities addEnterpriseId(
1038             @EnterpriseId int enterpriseId) {
1039         checkValidEnterpriseId(enterpriseId);
1040         mEnterpriseId |= 1 << enterpriseId;
1041         return this;
1042     }
1043 
1044     /**
1045      * Removes (if found) the given enterprise capability identifier from this
1046      * {@code NetworkCapability} instance that were added via addEnterpriseId(int)
1047      *
1048      * @param enterpriseId the enterprise capability identifier to be removed.
1049      * @return This NetworkCapabilities instance, to facilitate chaining.
1050      * @hide
1051      */
removeEnterpriseId( @nterpriseId int enterpriseId)1052     private @NonNull NetworkCapabilities removeEnterpriseId(
1053             @EnterpriseId  int enterpriseId) {
1054         checkValidEnterpriseId(enterpriseId);
1055         final int mask = ~(1 << enterpriseId);
1056         mEnterpriseId &= mask;
1057         return this;
1058     }
1059 
1060     /**
1061      * Set the underlying networks of this network.
1062      *
1063      * @param networks The underlying networks of this network.
1064      *
1065      * @hide
1066      */
setUnderlyingNetworks(@ullable List<Network> networks)1067     public void setUnderlyingNetworks(@Nullable List<Network> networks) {
1068         mUnderlyingNetworks =
1069                 (networks == null) ? null : Collections.unmodifiableList(new ArrayList<>(networks));
1070     }
1071 
1072     /**
1073      * Get the underlying networks of this network. If the caller doesn't have one of
1074      * {@link android.Manifest.permission.NETWORK_FACTORY},
1075      * {@link android.Manifest.permission.NETWORK_SETTINGS} and
1076      * {@link NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}, this is always redacted to null and
1077      * it will be never useful to the caller.
1078      *
1079      * @return <li>If the list is null, this network hasn't declared underlying networks.</li>
1080      *         <li>If the list is empty, this network has declared that it has no underlying
1081      *         networks or it doesn't run on any of the available networks.</li>
1082      *         <li>The list can contain multiple underlying networks, e.g. a VPN running over
1083      *         multiple networks at the same time.</li>
1084      *
1085      * @hide
1086      */
1087     @SuppressLint("NullableCollection")
1088     @Nullable
1089     @SystemApi
getUnderlyingNetworks()1090     public List<Network> getUnderlyingNetworks() {
1091         return mUnderlyingNetworks;
1092     }
1093 
equalsUnderlyingNetworks(@onNull NetworkCapabilities nc)1094     private boolean equalsUnderlyingNetworks(@NonNull NetworkCapabilities nc) {
1095         return Objects.equals(getUnderlyingNetworks(), nc.getUnderlyingNetworks());
1096     }
1097 
1098     /**
1099      * Tests for the presence of a capability on this instance.
1100      *
1101      * @param capability the capability to be tested for.
1102      * @return {@code true} if set on this instance.
1103      */
hasCapability(@etCapability int capability)1104     public boolean hasCapability(@NetCapability int capability) {
1105         return isValidCapability(capability)
1106                 && ((mNetworkCapabilities & (1L << capability)) != 0);
1107     }
1108 
1109     /**
1110      * Tests for the presence of a forbidden capability on this instance.
1111      *
1112      * @param capability the capability to be tested for.
1113      * @return {@code true} if this capability is set forbidden on this instance.
1114      * @hide
1115      */
1116     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
1117     // TODO : @FlaggedApi(Flags.FLAG_FORBIDDEN_CAPABILITY) and public
hasForbiddenCapability(@etCapability int capability)1118     public boolean hasForbiddenCapability(@NetCapability int capability) {
1119         return isValidCapability(capability)
1120                 && ((mForbiddenNetworkCapabilities & (1L << capability)) != 0);
1121     }
1122 
1123     /**
1124      * Check if this NetworkCapabilities has connectivity-managed capabilities or not.
1125      * @hide
1126      */
hasConnectivityManagedCapability()1127     public boolean hasConnectivityManagedCapability() {
1128         return (mNetworkCapabilities & CONNECTIVITY_MANAGED_CAPABILITIES) != 0
1129                 || mForbiddenNetworkCapabilities != 0;
1130     }
1131 
1132     /**
1133      * Get the name of the given capability that carriers use.
1134      * If the capability does not have a carrier-name, returns null.
1135      *
1136      * @param capability The capability to get the carrier-name of.
1137      * @return The carrier-name of the capability, or null if it doesn't exist.
1138      * @hide
1139      */
1140     @SystemApi
getCapabilityCarrierName(@etCapability int capability)1141     public static @Nullable String getCapabilityCarrierName(@NetCapability int capability) {
1142         if (capability == NET_CAPABILITY_ENTERPRISE) {
1143             return capabilityNameOf(capability);
1144         } else {
1145             return null;
1146         }
1147     }
1148 
1149     /**
1150      * Convenience function that returns a human-readable description of the first mutable
1151      * capability we find. Used to present an error message to apps that request mutable
1152      * capabilities.
1153      *
1154      * @hide
1155      */
describeFirstNonRequestableCapability()1156     public @Nullable String describeFirstNonRequestableCapability() {
1157         final long nonRequestable = (mNetworkCapabilities | mForbiddenNetworkCapabilities)
1158                 & NON_REQUESTABLE_CAPABILITIES;
1159 
1160         if (nonRequestable != 0) {
1161             return capabilityNameOf(BitUtils.unpackBits(nonRequestable)[0]);
1162         }
1163         if (mLinkUpBandwidthKbps != 0 || mLinkDownBandwidthKbps != 0) return "link bandwidth";
1164         if (hasSignalStrength()) return "signalStrength";
1165         if (isPrivateDnsBroken()) {
1166             return "privateDnsBroken";
1167         }
1168         return null;
1169     }
1170 
equalsEnterpriseCapabilitiesId(@onNull NetworkCapabilities nc)1171     private boolean equalsEnterpriseCapabilitiesId(@NonNull NetworkCapabilities nc) {
1172         return nc.mEnterpriseId == this.mEnterpriseId;
1173     }
1174 
satisfiedByEnterpriseCapabilitiesId(@onNull NetworkCapabilities nc)1175     private boolean satisfiedByEnterpriseCapabilitiesId(@NonNull NetworkCapabilities nc) {
1176         final int requestedEnterpriseCapabilitiesId = mEnterpriseId;
1177         final int providedEnterpriseCapabailitiesId = nc.mEnterpriseId;
1178 
1179         if ((providedEnterpriseCapabailitiesId & requestedEnterpriseCapabilitiesId)
1180                 == requestedEnterpriseCapabilitiesId) {
1181             return true;
1182         } else if (providedEnterpriseCapabailitiesId == 0
1183                 && (requestedEnterpriseCapabilitiesId == (1L << NET_ENTERPRISE_ID_1))) {
1184             return true;
1185         } else {
1186             return false;
1187         }
1188     }
1189 
satisfiedByNetCapabilities(@onNull NetworkCapabilities nc, boolean onlyImmutable)1190     private boolean satisfiedByNetCapabilities(@NonNull NetworkCapabilities nc,
1191             boolean onlyImmutable) {
1192         long requestedCapabilities = mNetworkCapabilities;
1193         long requestedForbiddenCapabilities = mForbiddenNetworkCapabilities;
1194         long providedCapabilities = nc.mNetworkCapabilities;
1195 
1196         if (onlyImmutable) {
1197             requestedCapabilities &= ~MUTABLE_CAPABILITIES;
1198             requestedForbiddenCapabilities &= ~MUTABLE_CAPABILITIES;
1199         }
1200         return ((providedCapabilities & requestedCapabilities) == requestedCapabilities)
1201                 && ((requestedForbiddenCapabilities & providedCapabilities) == 0);
1202     }
1203 
1204     /** @hide */
equalsNetCapabilities(@onNull NetworkCapabilities nc)1205     public boolean equalsNetCapabilities(@NonNull NetworkCapabilities nc) {
1206         return (nc.mNetworkCapabilities == this.mNetworkCapabilities)
1207                 && (nc.mForbiddenNetworkCapabilities == this.mForbiddenNetworkCapabilities);
1208     }
1209 
equalsNetCapabilitiesRequestable(@onNull NetworkCapabilities that)1210     private boolean equalsNetCapabilitiesRequestable(@NonNull NetworkCapabilities that) {
1211         return ((this.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES)
1212                 == (that.mNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES))
1213                 && ((this.mForbiddenNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES)
1214                 == (that.mForbiddenNetworkCapabilities & ~NON_REQUESTABLE_CAPABILITIES));
1215     }
1216 
1217     /**
1218      * Removes the NET_CAPABILITY_NOT_RESTRICTED capability if inferring the network is restricted.
1219      *
1220      * @hide
1221      */
maybeMarkCapabilitiesRestricted()1222     public void maybeMarkCapabilitiesRestricted() {
1223         if (NetworkCapabilitiesUtils.inferRestrictedCapability(mNetworkCapabilities)) {
1224             removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
1225         }
1226     }
1227 
1228     /**
1229      * @see #restrictCapabilitiesForTestNetwork(int)
1230      * @deprecated Use {@link #restrictCapabilitiesForTestNetwork(int)} (without the typo) instead.
1231      * @hide
1232      */
1233     @Deprecated
restrictCapabilitesForTestNetwork(int creatorUid)1234     public void restrictCapabilitesForTestNetwork(int creatorUid) {
1235         // Do not remove without careful consideration: this method has a typo in its name but is
1236         // called by the first S CTS releases, therefore it cannot be removed from the connectivity
1237         // module as long as such CTS releases are valid for testing S devices.
1238         restrictCapabilitiesForTestNetwork(creatorUid);
1239     }
1240 
1241     /**
1242      * Test networks have strong restrictions on what capabilities they can have. Enforce these
1243      * restrictions.
1244      * @hide
1245      */
restrictCapabilitiesForTestNetwork(int creatorUid)1246     public void restrictCapabilitiesForTestNetwork(int creatorUid) {
1247         final long originalCapabilities = mNetworkCapabilities;
1248         final long originalTransportTypes = mTransportTypes;
1249         final NetworkSpecifier originalSpecifier = mNetworkSpecifier;
1250         final int originalSignalStrength = mSignalStrength;
1251         final int originalOwnerUid = getOwnerUid();
1252         final int[] originalAdministratorUids = getAdministratorUids();
1253         final TransportInfo originalTransportInfo = getTransportInfo();
1254         final Set<Integer> originalSubIds = getSubscriptionIds();
1255         final Set<Integer> originalAllowedUids = new ArraySet<>(mAllowedUids);
1256         clearAll();
1257         if (0 != (originalCapabilities & (1 << NET_CAPABILITY_NOT_RESTRICTED))) {
1258             // If the test network is not restricted, then it is only allowed to declare some
1259             // specific transports. This is to minimize impact on running apps in case an app
1260             // run from the shell creates a test a network.
1261             mTransportTypes =
1262                     (originalTransportTypes & UNRESTRICTED_TEST_NETWORKS_ALLOWED_TRANSPORTS)
1263                             | (1 << TRANSPORT_TEST);
1264         } else {
1265             // If the test network is restricted, then it may declare any transport.
1266             mTransportTypes = (originalTransportTypes | (1 << TRANSPORT_TEST));
1267         }
1268 
1269         if (hasSingleTransport(TRANSPORT_TEST)) {
1270             // SubIds are only allowed for Test Networks that only declare TRANSPORT_TEST.
1271             setSubscriptionIds(originalSubIds);
1272         }
1273 
1274         mNetworkCapabilities = originalCapabilities & TEST_NETWORKS_ALLOWED_CAPABILITIES;
1275         if (!hasTransport(TRANSPORT_CELLULAR)) {
1276             mNetworkCapabilities |=
1277                     (originalCapabilities & TEST_NETWORKS_EXTRA_ALLOWED_CAPABILITIES_ON_NON_CELL);
1278         }
1279 
1280         mNetworkSpecifier = originalSpecifier;
1281         mSignalStrength = originalSignalStrength;
1282         mTransportInfo = originalTransportInfo;
1283         mAllowedUids.addAll(originalAllowedUids);
1284 
1285         // Only retain the owner and administrator UIDs if they match the app registering the remote
1286         // caller that registered the network.
1287         if (originalOwnerUid == creatorUid) {
1288             setOwnerUid(creatorUid);
1289         }
1290         if (CollectionUtils.contains(originalAdministratorUids, creatorUid)) {
1291             setAdministratorUids(new int[] {creatorUid});
1292         }
1293         // There is no need to clear the UIDs, they have already been cleared by clearAll() above.
1294     }
1295 
1296     /**
1297      * Representing the transport type.  Apps should generally not care about transport.  A
1298      * request for a fast internet connection could be satisfied by a number of different
1299      * transports.  If any are specified here it will be satisfied a Network that matches
1300      * any of them.  If a caller doesn't care about the transport it should not specify any.
1301      */
1302     private long mTransportTypes;
1303 
1304     /** @hide */
1305     @Retention(RetentionPolicy.SOURCE)
1306     @IntDef(prefix = { "TRANSPORT_" }, value = {
1307             TRANSPORT_CELLULAR,
1308             TRANSPORT_WIFI,
1309             TRANSPORT_BLUETOOTH,
1310             TRANSPORT_ETHERNET,
1311             TRANSPORT_VPN,
1312             TRANSPORT_WIFI_AWARE,
1313             TRANSPORT_LOWPAN,
1314             TRANSPORT_TEST,
1315             TRANSPORT_USB,
1316             TRANSPORT_THREAD,
1317             TRANSPORT_SATELLITE,
1318     })
1319     public @interface Transport { }
1320 
1321     /**
1322      * Indicates this network uses a Cellular transport.
1323      */
1324     public static final int TRANSPORT_CELLULAR = 0;
1325 
1326     /**
1327      * Indicates this network uses a Wi-Fi transport.
1328      */
1329     public static final int TRANSPORT_WIFI = 1;
1330 
1331     /**
1332      * Indicates this network uses a Bluetooth transport.
1333      */
1334     public static final int TRANSPORT_BLUETOOTH = 2;
1335 
1336     /**
1337      * Indicates this network uses an Ethernet transport.
1338      */
1339     public static final int TRANSPORT_ETHERNET = 3;
1340 
1341     /**
1342      * Indicates this network uses a VPN transport.
1343      */
1344     public static final int TRANSPORT_VPN = 4;
1345 
1346     /**
1347      * Indicates this network uses a Wi-Fi Aware transport.
1348      */
1349     public static final int TRANSPORT_WIFI_AWARE = 5;
1350 
1351     /**
1352      * Indicates this network uses a LoWPAN transport.
1353      */
1354     public static final int TRANSPORT_LOWPAN = 6;
1355 
1356     /**
1357      * Indicates this network uses a Test-only virtual interface as a transport.
1358      *
1359      * @hide
1360      */
1361     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
1362     public static final int TRANSPORT_TEST = 7;
1363 
1364     /**
1365      * Indicates this network uses a USB transport.
1366      */
1367     public static final int TRANSPORT_USB = 8;
1368 
1369     /**
1370      * Indicates this network uses a Thread transport.
1371      */
1372     public static final int TRANSPORT_THREAD = 9;
1373 
1374     /**
1375      * Indicates this network uses a Satellite transport.
1376      */
1377     @FlaggedApi(Flags.SUPPORT_TRANSPORT_SATELLITE)
1378     public static final int TRANSPORT_SATELLITE = 10;
1379 
1380     /** @hide */
1381     public static final int MIN_TRANSPORT = TRANSPORT_CELLULAR;
1382     /** @hide */
1383     public static final int MAX_TRANSPORT = TRANSPORT_SATELLITE;
1384 
1385     private static final int ALL_VALID_TRANSPORTS;
1386     static {
1387         int transports = 0;
1388         for (int i = MIN_TRANSPORT; i <= MAX_TRANSPORT; ++i) {
1389             transports |= 1 << i;
1390         }
1391         ALL_VALID_TRANSPORTS = transports;
1392     }
1393 
1394     /** @hide */
isValidTransport(@ransport int transportType)1395     public static boolean isValidTransport(@Transport int transportType) {
1396         return (MIN_TRANSPORT <= transportType) && (transportType <= MAX_TRANSPORT);
1397     }
1398 
1399     private static final String[] TRANSPORT_NAMES = {
1400         "CELLULAR",
1401         "WIFI",
1402         "BLUETOOTH",
1403         "ETHERNET",
1404         "VPN",
1405         "WIFI_AWARE",
1406         "LOWPAN",
1407         "TEST",
1408         "USB",
1409         "THREAD",
1410         "SATELLITE",
1411     };
1412 
1413     /**
1414      * Allowed transports on an unrestricted test network (in addition to TRANSPORT_TEST).
1415      */
1416     private static final long UNRESTRICTED_TEST_NETWORKS_ALLOWED_TRANSPORTS =
1417             (1L << TRANSPORT_TEST) |
1418             // Test eth networks are created with EthernetManager#setIncludeTestInterfaces
1419             (1L << TRANSPORT_ETHERNET) |
1420             // Test VPN networks can be created but their UID ranges must be empty.
1421             (1L << TRANSPORT_VPN);
1422 
1423     /**
1424      * Adds the given transport type to this {@code NetworkCapability} instance.
1425      * Multiple transports may be applied.  Note that when searching
1426      * for a network to satisfy a request, any listed in the request will satisfy the request.
1427      * For example {@code TRANSPORT_WIFI} and {@code TRANSPORT_ETHERNET} added to a
1428      * {@code NetworkCapabilities} would cause either a Wi-Fi network or an Ethernet network
1429      * to be selected.  This is logically different than
1430      * {@code NetworkCapabilities.NET_CAPABILITY_*} listed above.
1431      *
1432      * @param transportType the transport type to be added.
1433      * @return This NetworkCapabilities instance, to facilitate chaining.
1434      * @hide
1435      */
addTransportType(@ransport int transportType)1436     public @NonNull NetworkCapabilities addTransportType(@Transport int transportType) {
1437         checkValidTransportType(transportType);
1438         mTransportTypes |= 1 << transportType;
1439         setNetworkSpecifier(mNetworkSpecifier); // used for exception checking
1440         return this;
1441     }
1442 
1443     /**
1444      * Removes (if found) the given transport from this {@code NetworkCapability} instance.
1445      *
1446      * @param transportType the transport type to be removed.
1447      * @return This NetworkCapabilities instance, to facilitate chaining.
1448      * @hide
1449      */
removeTransportType(@ransport int transportType)1450     public @NonNull NetworkCapabilities removeTransportType(@Transport int transportType) {
1451         checkValidTransportType(transportType);
1452         mTransportTypes &= ~(1 << transportType);
1453         setNetworkSpecifier(mNetworkSpecifier); // used for exception checking
1454         return this;
1455     }
1456 
1457     /**
1458      * Sets (or clears) the given transport on this {@link NetworkCapabilities}
1459      * instance.
1460      *
1461      * @hide
1462      */
setTransportType(@ransport int transportType, boolean value)1463     public @NonNull NetworkCapabilities setTransportType(@Transport int transportType,
1464             boolean value) {
1465         if (value) {
1466             addTransportType(transportType);
1467         } else {
1468             removeTransportType(transportType);
1469         }
1470         return this;
1471     }
1472 
1473     /**
1474      * Gets all the transports set on this {@code NetworkCapability} instance.
1475      *
1476      * @return an array of transport type values for this instance.
1477      * @hide
1478      */
1479     @SystemApi
getTransportTypes()1480     @NonNull public @Transport int[] getTransportTypes() {
1481         return BitUtils.unpackBits(mTransportTypes);
1482     }
1483 
1484     /**
1485      * Gets the transports as an int. Internal callers only.
1486      *
1487      * Prefer getTransportTypes/hasTransportType if not immediately collapsing back into a scalar.
1488      *
1489      * @return a long integer representing the transport types.
1490      * @hide
1491      */
getTransportTypesInternal()1492     public long getTransportTypesInternal() {
1493         return mTransportTypes;
1494     }
1495 
1496     /**
1497      * Sets all the transports set on this {@code NetworkCapability} instance.
1498      * This overwrites any existing transports.
1499      *
1500      * @hide
1501      */
setTransportTypes(@ransport int[] transportTypes)1502     public void setTransportTypes(@Transport int[] transportTypes) {
1503         mTransportTypes = BitUtils.packBits(transportTypes);
1504     }
1505 
1506     /**
1507      * Tests for the presence of a transport on this instance.
1508      *
1509      * @param transportType the transport type to be tested for.
1510      * @return {@code true} if set on this instance.
1511      */
hasTransport(@ransport int transportType)1512     public boolean hasTransport(@Transport int transportType) {
1513         return isValidTransport(transportType) && ((mTransportTypes & (1 << transportType)) != 0);
1514     }
1515 
1516     /**
1517      * Returns true iff this NetworkCapabilities has the specified transport and no other.
1518      * @hide
1519      */
hasSingleTransport(@ransport int transportType)1520     public boolean hasSingleTransport(@Transport int transportType) {
1521         return mTransportTypes == (1 << transportType);
1522     }
1523 
1524     /**
1525      * Returns true iff this NC has the specified transport and no other, ignoring TRANSPORT_TEST.
1526      *
1527      * If this NC has the passed transport and no other, this method returns true.
1528      * If this NC has the passed transport, TRANSPORT_TEST and no other, this method returns true.
1529      * Otherwise, this method returns false.
1530      * @hide
1531      */
hasSingleTransportBesidesTest(@ransport int transportType)1532     public boolean hasSingleTransportBesidesTest(@Transport int transportType) {
1533         return (mTransportTypes & ~(1 << TRANSPORT_TEST)) == (1 << transportType);
1534     }
1535 
satisfiedByTransportTypes(NetworkCapabilities nc)1536     private boolean satisfiedByTransportTypes(NetworkCapabilities nc) {
1537         return ((this.mTransportTypes == 0)
1538                 || ((this.mTransportTypes & nc.mTransportTypes) != 0));
1539     }
1540 
1541     /** @hide */
equalsTransportTypes(NetworkCapabilities nc)1542     public boolean equalsTransportTypes(NetworkCapabilities nc) {
1543         return (nc.mTransportTypes == this.mTransportTypes);
1544     }
1545 
1546     /**
1547      * UID of the app that owns this network, or Process#INVALID_UID if none/unknown.
1548      *
1549      * <p>This field keeps track of the UID of the app that created this network and is in charge of
1550      * its lifecycle. This could be the UID of apps such as the Wifi network suggestor, the running
1551      * VPN, or Carrier Service app managing a cellular data connection.
1552      *
1553      * <p>For NetworkCapability instances being sent from ConnectivityService, this value MUST be
1554      * reset to Process.INVALID_UID unless all the following conditions are met:
1555      *
1556      * <p>The caller is the network owner, AND one of the following sets of requirements is met:
1557      *
1558      * <ol>
1559      *   <li>The described Network is a VPN
1560      * </ol>
1561      *
1562      * <p>OR:
1563      *
1564      * <ol>
1565      *   <li>The calling app is the network owner
1566      *   <li>The calling app has the ACCESS_FINE_LOCATION permission granted
1567      *   <li>The user's location toggle is on
1568      * </ol>
1569      *
1570      * This is because the owner UID is location-sensitive. The apps that request a network could
1571      * know where the device is if they can tell for sure the system has connected to the network
1572      * they requested.
1573      *
1574      * <p>This is populated by the network agents and for the NetworkCapabilities instance sent by
1575      * an app to the System Server, the value MUST be reset to Process.INVALID_UID by the system
1576      * server.
1577      */
1578     private int mOwnerUid = Process.INVALID_UID;
1579 
1580     /**
1581      * Set the UID of the owner app.
1582      * @hide
1583      */
setOwnerUid(final int uid)1584     public @NonNull NetworkCapabilities setOwnerUid(final int uid) {
1585         mOwnerUid = uid;
1586         return this;
1587     }
1588 
1589     /**
1590      * Retrieves the UID of the app that owns this network.
1591      *
1592      * <p>For user privacy reasons, this field will only be populated if the following conditions
1593      * are met:
1594      *
1595      * <p>The caller is the network owner, AND one of the following sets of requirements is met:
1596      *
1597      * <ol>
1598      *   <li>The described Network is a VPN
1599      * </ol>
1600      *
1601      * <p>OR:
1602      *
1603      * <ol>
1604      *   <li>The calling app is the network owner
1605      *   <li>The calling app has the ACCESS_FINE_LOCATION permission granted
1606      *   <li>The user's location toggle is on
1607      * </ol>
1608      *
1609      * Instances of NetworkCapabilities sent to apps without the appropriate permissions will have
1610      * this field cleared out.
1611      *
1612      * <p>
1613      * This field will only be populated for VPN and wifi network suggestor apps (i.e using
1614      * {@link android.net.wifi.WifiNetworkSuggestion WifiNetworkSuggestion}), and only for the
1615      * network they own. In the case of wifi network suggestors apps, this field is also location
1616      * sensitive, so the app needs to hold {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
1617      * permission. If the app targets SDK version greater than or equal to
1618      * {@link Build.VERSION_CODES#S}, then they also need to use
1619      * {@link NetworkCallback#FLAG_INCLUDE_LOCATION_INFO} to get the info in their callback. If the
1620      * apps targets SDK version equal to {{@link Build.VERSION_CODES#R}, this field will always be
1621      * included. The app will be blamed for location access if this field is included.
1622      * </p>
1623      */
getOwnerUid()1624     public int getOwnerUid() {
1625         return mOwnerUid;
1626     }
1627 
equalsOwnerUid(@onNull final NetworkCapabilities nc)1628     private boolean equalsOwnerUid(@NonNull final NetworkCapabilities nc) {
1629         return mOwnerUid == nc.mOwnerUid;
1630     }
1631 
1632     /**
1633      * UIDs of packages that are administrators of this network, or empty if none.
1634      *
1635      * <p>This field tracks the UIDs of packages that have permission to manage this network.
1636      *
1637      * <p>Network owners will also be listed as administrators.
1638      *
1639      * <p>For NetworkCapability instances being sent from the System Server, this value MUST be
1640      * empty unless the destination is 1) the System Server, or 2) Telephony. In either case, the
1641      * receiving entity must have the ACCESS_FINE_LOCATION permission and target R+.
1642      *
1643      * <p>When received from an app in a NetworkRequest this is always cleared out by the system
1644      * server. This field is never used for matching NetworkRequests to NetworkAgents.
1645      */
1646     @NonNull private int[] mAdministratorUids = new int[0];
1647 
1648     /**
1649      * Sets the int[] of UIDs that are administrators of this network.
1650      *
1651      * <p>UIDs included in administratorUids gain administrator privileges over this Network.
1652      * Examples of UIDs that should be included in administratorUids are:
1653      *
1654      * <ul>
1655      *   <li>Carrier apps with privileges for the relevant subscription
1656      *   <li>Active VPN apps
1657      *   <li>Other application groups with a particular Network-related role
1658      * </ul>
1659      *
1660      * <p>In general, user-supplied networks (such as WiFi networks) do not have an administrator.
1661      *
1662      * <p>An app is granted owner privileges over Networks that it supplies. The owner UID MUST
1663      * always be included in administratorUids.
1664      *
1665      * <p>The administrator UIDs are set by network agents.
1666      *
1667      * @param administratorUids the UIDs to be set as administrators of this Network.
1668      * @throws IllegalArgumentException if duplicate UIDs are contained in administratorUids
1669      * @see #mAdministratorUids
1670      * @hide
1671      */
1672     @NonNull
setAdministratorUids(@onNull final int[] administratorUids)1673     public NetworkCapabilities setAdministratorUids(@NonNull final int[] administratorUids) {
1674         mAdministratorUids = Arrays.copyOf(administratorUids, administratorUids.length);
1675         Arrays.sort(mAdministratorUids);
1676         for (int i = 0; i < mAdministratorUids.length - 1; i++) {
1677             if (mAdministratorUids[i] >= mAdministratorUids[i + 1]) {
1678                 throw new IllegalArgumentException("All administrator UIDs must be unique");
1679             }
1680         }
1681         return this;
1682     }
1683 
1684     /**
1685      * Retrieves the UIDs that are administrators of this Network.
1686      *
1687      * <p>This is only populated in NetworkCapabilities objects that come from network agents for
1688      * networks that are managed by specific apps on the system, such as carrier privileged apps or
1689      * wifi suggestion apps. This will include the network owner.
1690      *
1691      * @return the int[] of UIDs that are administrators of this Network
1692      * @see #mAdministratorUids
1693      * @hide
1694      */
1695     @NonNull
1696     @SystemApi
getAdministratorUids()1697     public int[] getAdministratorUids() {
1698         return Arrays.copyOf(mAdministratorUids, mAdministratorUids.length);
1699     }
1700 
1701     /**
1702      * Tests if the set of administrator UIDs of this network is the same as that of the passed one.
1703      *
1704      * <p>The administrator UIDs must be in sorted order.
1705      *
1706      * <p>nc is assumed non-null. Else, NPE.
1707      *
1708      * @hide
1709      */
1710     @VisibleForTesting(visibility = PRIVATE)
equalsAdministratorUids(@onNull final NetworkCapabilities nc)1711     public boolean equalsAdministratorUids(@NonNull final NetworkCapabilities nc) {
1712         return Arrays.equals(mAdministratorUids, nc.mAdministratorUids);
1713     }
1714 
1715     /**
1716      * Value indicating that link bandwidth is unspecified.
1717      * @hide
1718      */
1719     public static final int LINK_BANDWIDTH_UNSPECIFIED = 0;
1720 
1721     /**
1722      * Passive link bandwidth.  This is a rough guide of the expected peak bandwidth
1723      * for the first hop on the given transport.  It is not measured, but may take into account
1724      * link parameters (Radio technology, allocated channels, etc).
1725      */
1726     private int mLinkUpBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED;
1727     private int mLinkDownBandwidthKbps = LINK_BANDWIDTH_UNSPECIFIED;
1728 
1729     /**
1730      * Sets the upstream bandwidth for this network in Kbps.  This always only refers to
1731      * the estimated first hop transport bandwidth.
1732      * <p>
1733      * @see Builder#setLinkUpstreamBandwidthKbps
1734      *
1735      * @param upKbps the estimated first hop upstream (device to network) bandwidth.
1736      * @hide
1737      */
setLinkUpstreamBandwidthKbps(int upKbps)1738     public @NonNull NetworkCapabilities setLinkUpstreamBandwidthKbps(int upKbps) {
1739         mLinkUpBandwidthKbps = upKbps;
1740         return this;
1741     }
1742 
1743     /**
1744      * Retrieves the upstream bandwidth for this network in Kbps.  This always only refers to
1745      * the estimated first hop transport bandwidth.
1746      *
1747      * @return The estimated first hop upstream (device to network) bandwidth.
1748      */
getLinkUpstreamBandwidthKbps()1749     public int getLinkUpstreamBandwidthKbps() {
1750         return mLinkUpBandwidthKbps;
1751     }
1752 
1753     /**
1754      * Sets the downstream bandwidth for this network in Kbps.  This always only refers to
1755      * the estimated first hop transport bandwidth.
1756      * <p>
1757      * @see Builder#setLinkUpstreamBandwidthKbps
1758      *
1759      * @param downKbps the estimated first hop downstream (network to device) bandwidth.
1760      * @hide
1761      */
setLinkDownstreamBandwidthKbps(int downKbps)1762     public @NonNull NetworkCapabilities setLinkDownstreamBandwidthKbps(int downKbps) {
1763         mLinkDownBandwidthKbps = downKbps;
1764         return this;
1765     }
1766 
1767     /**
1768      * Retrieves the downstream bandwidth for this network in Kbps.  This always only refers to
1769      * the estimated first hop transport bandwidth.
1770      *
1771      * @return The estimated first hop downstream (network to device) bandwidth.
1772      */
getLinkDownstreamBandwidthKbps()1773     public int getLinkDownstreamBandwidthKbps() {
1774         return mLinkDownBandwidthKbps;
1775     }
1776 
satisfiedByLinkBandwidths(NetworkCapabilities nc)1777     private boolean satisfiedByLinkBandwidths(NetworkCapabilities nc) {
1778         return !(this.mLinkUpBandwidthKbps > nc.mLinkUpBandwidthKbps
1779                 || this.mLinkDownBandwidthKbps > nc.mLinkDownBandwidthKbps);
1780     }
equalsLinkBandwidths(NetworkCapabilities nc)1781     private boolean equalsLinkBandwidths(NetworkCapabilities nc) {
1782         return (this.mLinkUpBandwidthKbps == nc.mLinkUpBandwidthKbps
1783                 && this.mLinkDownBandwidthKbps == nc.mLinkDownBandwidthKbps);
1784     }
1785     /** @hide */
minBandwidth(int a, int b)1786     public static int minBandwidth(int a, int b) {
1787         if (a == LINK_BANDWIDTH_UNSPECIFIED)  {
1788             return b;
1789         } else if (b == LINK_BANDWIDTH_UNSPECIFIED) {
1790             return a;
1791         } else {
1792             return Math.min(a, b);
1793         }
1794     }
1795     /** @hide */
maxBandwidth(int a, int b)1796     public static int maxBandwidth(int a, int b) {
1797         return Math.max(a, b);
1798     }
1799 
1800     private NetworkSpecifier mNetworkSpecifier = null;
1801     private TransportInfo mTransportInfo = null;
1802 
1803     /**
1804      * Sets the optional bearer specific network specifier.
1805      * This has no meaning if a single transport is also not specified, so calling
1806      * this without a single transport set will generate an exception, as will
1807      * subsequently adding or removing transports after this is set.
1808      * </p>
1809      *
1810      * @param networkSpecifier A concrete, parcelable framework class that extends
1811      *                         NetworkSpecifier.
1812      * @return This NetworkCapabilities instance, to facilitate chaining.
1813      * @hide
1814      */
setNetworkSpecifier( @onNull NetworkSpecifier networkSpecifier)1815     public @NonNull NetworkCapabilities setNetworkSpecifier(
1816             @NonNull NetworkSpecifier networkSpecifier) {
1817         if (networkSpecifier != null
1818                 // Transport can be test, or test + a single other transport or cellular + satellite
1819                 // transport. Note: cellular + satellite combination is allowed since both transport
1820                 // use the same specifier, TelephonyNetworkSpecifier.
1821                 && mTransportTypes != (1L << TRANSPORT_TEST)
1822                 && Long.bitCount(mTransportTypes & ~(1L << TRANSPORT_TEST)) != 1
1823                 && !specifierAcceptableForMultipleTransports(mTransportTypes)) {
1824             throw new IllegalStateException("Must have a single non-test transport specified to "
1825                     + "use setNetworkSpecifier");
1826         }
1827 
1828         mNetworkSpecifier = networkSpecifier;
1829 
1830         return this;
1831     }
1832 
specifierAcceptableForMultipleTransports(long transportTypes)1833     private boolean specifierAcceptableForMultipleTransports(long transportTypes) {
1834         return (transportTypes & ~(1L << TRANSPORT_TEST))
1835                 // Cellular and satellite use the same NetworkSpecifier.
1836                 == (1 << TRANSPORT_CELLULAR | 1 << TRANSPORT_SATELLITE);
1837     }
1838 
1839     /**
1840      * Sets the optional transport specific information.
1841      *
1842      * @param transportInfo A concrete, parcelable framework class that extends
1843      * {@link TransportInfo}.
1844      * @return This NetworkCapabilities instance, to facilitate chaining.
1845      * @hide
1846      */
setTransportInfo(@onNull TransportInfo transportInfo)1847     public @NonNull NetworkCapabilities setTransportInfo(@NonNull TransportInfo transportInfo) {
1848         mTransportInfo = transportInfo;
1849         return this;
1850     }
1851 
1852     /**
1853      * Gets the optional bearer specific network specifier. May be {@code null} if not set.
1854      *
1855      * @return The optional {@link NetworkSpecifier} specifying the bearer specific network
1856      *         specifier or {@code null}.
1857      */
getNetworkSpecifier()1858     public @Nullable NetworkSpecifier getNetworkSpecifier() {
1859         return mNetworkSpecifier;
1860     }
1861 
1862     /**
1863      * Returns a transport-specific information container. The application may cast this
1864      * container to a concrete sub-class based on its knowledge of the network request. The
1865      * application should be able to deal with a {@code null} return value or an invalid case,
1866      * e.g. use {@code instanceof} operator to verify expected type.
1867      *
1868      * @return A concrete implementation of the {@link TransportInfo} class or null if not
1869      * available for the network.
1870      */
getTransportInfo()1871     @Nullable public TransportInfo getTransportInfo() {
1872         return mTransportInfo;
1873     }
1874 
satisfiedBySpecifier(NetworkCapabilities nc)1875     private boolean satisfiedBySpecifier(NetworkCapabilities nc) {
1876         return mNetworkSpecifier == null || mNetworkSpecifier.canBeSatisfiedBy(nc.mNetworkSpecifier)
1877                 || nc.mNetworkSpecifier instanceof MatchAllNetworkSpecifier;
1878     }
1879 
equalsSpecifier(NetworkCapabilities nc)1880     private boolean equalsSpecifier(NetworkCapabilities nc) {
1881         return Objects.equals(mNetworkSpecifier, nc.mNetworkSpecifier);
1882     }
1883 
equalsTransportInfo(NetworkCapabilities nc)1884     private boolean equalsTransportInfo(NetworkCapabilities nc) {
1885         return Objects.equals(mTransportInfo, nc.mTransportInfo);
1886     }
1887 
1888     /**
1889      * Magic value that indicates no signal strength provided. A request specifying this value is
1890      * always satisfied.
1891      */
1892     public static final int SIGNAL_STRENGTH_UNSPECIFIED = Integer.MIN_VALUE;
1893 
1894     /**
1895      * Signal strength. This is a signed integer, and higher values indicate better signal.
1896      * The exact units are bearer-dependent. For example, Wi-Fi uses RSSI.
1897      */
1898     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
1899     private int mSignalStrength = SIGNAL_STRENGTH_UNSPECIFIED;
1900 
1901     /**
1902      * Sets the signal strength. This is a signed integer, with higher values indicating a stronger
1903      * signal. The exact units are bearer-dependent. For example, Wi-Fi uses the same RSSI units
1904      * reported by wifi code.
1905      * <p>
1906      * Note that when used to register a network callback, this specifies the minimum acceptable
1907      * signal strength. When received as the state of an existing network it specifies the current
1908      * value. A value of {@link #SIGNAL_STRENGTH_UNSPECIFIED} means no value when received and has
1909      * no effect when requesting a callback.
1910      *
1911      * @param signalStrength the bearer-specific signal strength.
1912      * @hide
1913      */
setSignalStrength(int signalStrength)1914     public @NonNull NetworkCapabilities setSignalStrength(int signalStrength) {
1915         mSignalStrength = signalStrength;
1916         return this;
1917     }
1918 
1919     /**
1920      * Returns {@code true} if this object specifies a signal strength.
1921      *
1922      * @hide
1923      */
1924     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
hasSignalStrength()1925     public boolean hasSignalStrength() {
1926         return mSignalStrength > SIGNAL_STRENGTH_UNSPECIFIED;
1927     }
1928 
1929     /**
1930      * Retrieves the signal strength.
1931      *
1932      * @return The bearer-specific signal strength.
1933      */
getSignalStrength()1934     public int getSignalStrength() {
1935         return mSignalStrength;
1936     }
1937 
satisfiedBySignalStrength(NetworkCapabilities nc)1938     private boolean satisfiedBySignalStrength(NetworkCapabilities nc) {
1939         return this.mSignalStrength <= nc.mSignalStrength;
1940     }
1941 
equalsSignalStrength(NetworkCapabilities nc)1942     private boolean equalsSignalStrength(NetworkCapabilities nc) {
1943         return this.mSignalStrength == nc.mSignalStrength;
1944     }
1945 
1946     /**
1947      * List of UIDs this network applies to. No restriction if null.
1948      * <p>
1949      * For networks, mUids represent the list of network this applies to, and null means this
1950      * network applies to all UIDs.
1951      * For requests, mUids is the list of UIDs this network MUST apply to to match ; ALL UIDs
1952      * must be included in a network so that they match. As an exception to the general rule,
1953      * a null mUids field for requests mean "no requirements" rather than what the general rule
1954      * would suggest ("must apply to all UIDs") : this is because this has shown to be what users
1955      * of this API expect in practice. A network that must match all UIDs can still be
1956      * expressed with a set ranging the entire set of possible UIDs.
1957      * <p>
1958      * mUids is typically (and at this time, only) used by VPN. This network is only available to
1959      * the UIDs in this list, and it is their default network. Apps in this list that wish to
1960      * bypass the VPN can do so iff the VPN app allows them to or if they are privileged. If this
1961      * member is null, then the network is not restricted by app UID. If it's an empty list, then
1962      * it means nobody can use it.
1963      * As a special exception, the app managing this network (as identified by its UID stored in
1964      * mOwnerUid) can always see this network. This is embodied by a special check in
1965      * satisfiedByUids. That still does not mean the network necessarily <strong>applies</strong>
1966      * to the app that manages it as determined by #appliesToUid.
1967      * <p>
1968      * Please note that in principle a single app can be associated with multiple UIDs because
1969      * each app will have a different UID when it's run as a different (macro-)user. A single
1970      * macro user can only have a single active VPN app at any given time however.
1971      * <p>
1972      * Also please be aware this class does not try to enforce any normalization on this. Callers
1973      * can only alter the UIDs by setting them wholesale : this class does not provide any utility
1974      * to add or remove individual UIDs or ranges. If callers have any normalization needs on
1975      * their own (like requiring sortedness or no overlap) they need to enforce it
1976      * themselves. Some of the internal methods also assume this is normalized as in no adjacent
1977      * or overlapping ranges are present.
1978      *
1979      * @hide
1980      */
1981     private ArraySet<UidRange> mUids = null;
1982 
1983     /**
1984      * Convenience method to set the UIDs this network applies to to a single UID.
1985      * @hide
1986      */
setSingleUid(int uid)1987     public @NonNull NetworkCapabilities setSingleUid(int uid) {
1988         mUids = new ArraySet<>(1);
1989         mUids.add(new UidRange(uid, uid));
1990         return this;
1991     }
1992 
1993     /**
1994      * Set the list of UIDs this network applies to.
1995      * This makes a copy of the set so that callers can't modify it after the call.
1996      * @hide
1997      */
setUids(@ullable Set<Range<Integer>> uids)1998     public @NonNull NetworkCapabilities setUids(@Nullable Set<Range<Integer>> uids) {
1999         mUids = UidRange.fromIntRanges(uids);
2000         return this;
2001     }
2002 
2003     /**
2004      * Get the list of UIDs this network applies to.
2005      * This returns a copy of the set so that callers can't modify the original object.
2006      *
2007      * @return the list of UIDs this network applies to. If {@code null}, then the network applies
2008      *         to all UIDs.
2009      * @hide
2010      */
2011     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
2012     @SuppressLint("NullableCollection")
getUids()2013     public @Nullable Set<Range<Integer>> getUids() {
2014         return UidRange.toIntRanges(mUids);
2015     }
2016 
2017     /**
2018      * Get the list of UIDs this network applies to.
2019      * This returns a copy of the set so that callers can't modify the original object.
2020      * @hide
2021      */
getUidRanges()2022     public @Nullable Set<UidRange> getUidRanges() {
2023         if (mUids == null) return null;
2024 
2025         return new ArraySet<>(mUids);
2026     }
2027 
2028     /**
2029      * Test whether this network applies to this UID.
2030      * @hide
2031      */
appliesToUid(int uid)2032     public boolean appliesToUid(int uid) {
2033         if (null == mUids) return true;
2034         for (UidRange range : mUids) {
2035             if (range.contains(uid)) {
2036                 return true;
2037             }
2038         }
2039         return false;
2040     }
2041 
2042     /**
2043      * Tests if the set of UIDs that this network applies to is the same as the passed network.
2044      * <p>
2045      * This test only checks whether equal range objects are in both sets. It will
2046      * return false if the ranges are not exactly the same, even if the covered UIDs
2047      * are for an equivalent result.
2048      * <p>
2049      * Note that this method is not very optimized, which is fine as long as it's not used very
2050      * often.
2051      * <p>
2052      * nc is assumed nonnull, else NPE.
2053      *
2054      * @hide
2055      */
2056     @VisibleForTesting
equalsUids(@onNull NetworkCapabilities nc)2057     public boolean equalsUids(@NonNull NetworkCapabilities nc) {
2058         return UidRange.hasSameUids(nc.mUids, mUids);
2059     }
2060 
2061     /**
2062      * Test whether the passed NetworkCapabilities satisfies the UIDs this capabilities require.
2063      *
2064      * This method is called on the NetworkCapabilities embedded in a request with the
2065      * capabilities of an available network. It checks whether all the UIDs from this listen
2066      * (representing the UIDs that must have access to the network) are satisfied by the UIDs
2067      * in the passed nc (representing the UIDs that this network is available to).
2068      * <p>
2069      * As a special exception, the UID that created the passed network (as represented by its
2070      * mOwnerUid field) always satisfies a NetworkRequest requiring it (of LISTEN
2071      * or REQUEST types alike), even if the network does not apply to it. That is so a VPN app
2072      * can see its own network when it listens for it.
2073      * <p>
2074      * nc is assumed nonnull. Else, NPE.
2075      * @see #appliesToUid
2076      * @hide
2077      */
satisfiedByUids(@onNull NetworkCapabilities nc)2078     public boolean satisfiedByUids(@NonNull NetworkCapabilities nc) {
2079         if (null == nc.mUids || null == mUids) return true; // The network satisfies everything.
2080         for (UidRange requiredRange : mUids) {
2081             if (requiredRange.contains(nc.mOwnerUid)) return true;
2082             if (!nc.appliesToUidRange(requiredRange)) {
2083                 return false;
2084             }
2085         }
2086         return true;
2087     }
2088 
2089     /**
2090      * Returns whether this network applies to the passed ranges.
2091      * This assumes that to apply, the passed range has to be entirely contained
2092      * within one of the ranges this network applies to. If the ranges are not normalized,
2093      * this method may return false even though all required UIDs are covered because no
2094      * single range contained them all.
2095      * @hide
2096      */
2097     @VisibleForTesting
appliesToUidRange(@onNull UidRange requiredRange)2098     public boolean appliesToUidRange(@NonNull UidRange requiredRange) {
2099         if (null == mUids) return true;
2100         for (UidRange uidRange : mUids) {
2101             if (uidRange.containsRange(requiredRange)) {
2102                 return true;
2103             }
2104         }
2105         return false;
2106     }
2107 
2108     /**
2109      * List of UIDs that can always access this network.
2110      * <p>
2111      * UIDs in this list have access to this network, even if the network doesn't have the
2112      * {@link #NET_CAPABILITY_NOT_RESTRICTED} capability and the UID does not hold the
2113      * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission.
2114      * This is only useful for restricted networks. For non-restricted networks it has no effect.
2115      * <p>
2116      * This is disallowed in {@link NetworkRequest}, and can only be set by network agents. Network
2117      * agents also have restrictions on how they can set these ; they can only back a public
2118      * Android API. As such, Ethernet agents can set this when backing the per-UID access API, and
2119      * Telephony can set exactly one UID which has to match the manager app for the associated
2120      * subscription. Failure to comply with these rules will see this member cleared.
2121      * <p>
2122      * This member is never null, but can be empty.
2123      * @hide
2124      */
2125     @NonNull
2126     private final ArraySet<Integer> mAllowedUids = new ArraySet<>();
2127 
2128     /**
2129      * Set the list of UIDs that can always access this network.
2130      * @param uids
2131      * @hide
2132      */
setAllowedUids(@onNull final Set<Integer> uids)2133     public void setAllowedUids(@NonNull final Set<Integer> uids) {
2134         // could happen with nc.set(nc), cheaper than always making a defensive copy
2135         if (uids == mAllowedUids) return;
2136 
2137         Objects.requireNonNull(uids);
2138         mAllowedUids.clear();
2139         mAllowedUids.addAll(uids);
2140     }
2141 
2142     /**
2143      * The list of UIDs that can always access this network.
2144      *
2145      * The UIDs in this list can always access this network, even if it is restricted and
2146      * the UID doesn't hold the USE_RESTRICTED_NETWORKS permission. This is defined by the
2147      * network agent in charge of creating the network.
2148      *
2149      * The UIDs are only visible to network factories and the system server, since the system
2150      * server makes sure to redact them before sending a NetworkCapabilities to a process
2151      * that doesn't hold the permission.
2152      *
2153      * @hide
2154      */
2155     @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
2156     @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
getAllowedUids()2157     public @NonNull Set<Integer> getAllowedUids() {
2158         return new ArraySet<>(mAllowedUids);
2159     }
2160 
2161     /** @hide */
2162     // For internal clients that know what they are doing and need to avoid the performance hit
2163     // of the defensive copy.
getAllowedUidsNoCopy()2164     public @NonNull ArraySet<Integer> getAllowedUidsNoCopy() {
2165         return mAllowedUids;
2166     }
2167 
2168     /**
2169      * Test whether this UID has special permission to access this network, as per mAllowedUids.
2170      * @hide
2171      */
2172     // TODO : should this be "doesUidHaveAccess" and check the USE_RESTRICTED_NETWORKS permission ?
isUidWithAccess(int uid)2173     public boolean isUidWithAccess(int uid) {
2174         return mAllowedUids.contains(uid);
2175     }
2176 
2177     /**
2178      * @return whether any UID is in the list of access UIDs
2179      * @hide
2180      */
hasAllowedUids()2181     public boolean hasAllowedUids() {
2182         return !mAllowedUids.isEmpty();
2183     }
2184 
equalsAllowedUids(@onNull NetworkCapabilities other)2185     private boolean equalsAllowedUids(@NonNull NetworkCapabilities other) {
2186         return mAllowedUids.equals(other.mAllowedUids);
2187     }
2188 
2189     /**
2190      * The SSID of the network, or null if not applicable or unknown.
2191      * <p>
2192      * This is filled in by wifi code.
2193      * @hide
2194      */
2195     private String mSSID;
2196 
2197     /**
2198      * Sets the SSID of this network.
2199      * @hide
2200      */
setSSID(@ullable String ssid)2201     public @NonNull NetworkCapabilities setSSID(@Nullable String ssid) {
2202         mSSID = ssid;
2203         return this;
2204     }
2205 
2206     /**
2207      * Gets the SSID of this network, or null if none or unknown.
2208      * @hide
2209      */
2210     @SystemApi
getSsid()2211     public @Nullable String getSsid() {
2212         return mSSID;
2213     }
2214 
2215     /**
2216      * Tests if the SSID of this network is the same as the SSID of the passed network.
2217      * @hide
2218      */
equalsSSID(@onNull NetworkCapabilities nc)2219     public boolean equalsSSID(@NonNull NetworkCapabilities nc) {
2220         return Objects.equals(mSSID, nc.mSSID);
2221     }
2222 
2223     /**
2224      * Check if the SSID requirements of this object are matched by the passed object.
2225      * @hide
2226      */
satisfiedBySSID(@onNull NetworkCapabilities nc)2227     public boolean satisfiedBySSID(@NonNull NetworkCapabilities nc) {
2228         return mSSID == null || mSSID.equals(nc.mSSID);
2229     }
2230 
2231     /**
2232      * Check if our requirements are satisfied by the given {@code NetworkCapabilities}.
2233      *
2234      * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements.
2235      * @param onlyImmutable if {@code true}, do not consider mutable requirements such as link
2236      *         bandwidth, signal strength, or validation / captive portal status.
2237      *
2238      * @hide
2239      */
satisfiedByNetworkCapabilities(NetworkCapabilities nc, boolean onlyImmutable)2240     private boolean satisfiedByNetworkCapabilities(NetworkCapabilities nc, boolean onlyImmutable) {
2241         return (nc != null
2242                 && satisfiedByNetCapabilities(nc, onlyImmutable)
2243                 && satisfiedByTransportTypes(nc)
2244                 && (onlyImmutable || satisfiedByLinkBandwidths(nc))
2245                 && satisfiedBySpecifier(nc)
2246                 && satisfiedByEnterpriseCapabilitiesId(nc)
2247                 && (onlyImmutable || satisfiedBySignalStrength(nc))
2248                 && (onlyImmutable || satisfiedByUids(nc))
2249                 && (onlyImmutable || satisfiedBySSID(nc))
2250                 && (onlyImmutable || satisfiedByRequestor(nc))
2251                 && (onlyImmutable || satisfiedBySubscriptionIds(nc)));
2252     }
2253 
2254     /**
2255      * Check if our requirements are satisfied by the given {@code NetworkCapabilities}.
2256      *
2257      * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements.
2258      *
2259      * @hide
2260      */
2261     @SystemApi
satisfiedByNetworkCapabilities(@ullable NetworkCapabilities nc)2262     public boolean satisfiedByNetworkCapabilities(@Nullable NetworkCapabilities nc) {
2263         return satisfiedByNetworkCapabilities(nc, false);
2264     }
2265 
2266     /**
2267      * Check if our immutable requirements are satisfied by the given {@code NetworkCapabilities}.
2268      *
2269      * @param nc the {@code NetworkCapabilities} that may or may not satisfy our requirements.
2270      *
2271      * @hide
2272      */
satisfiedByImmutableNetworkCapabilities(@ullable NetworkCapabilities nc)2273     public boolean satisfiedByImmutableNetworkCapabilities(@Nullable NetworkCapabilities nc) {
2274         return satisfiedByNetworkCapabilities(nc, true);
2275     }
2276 
2277     /**
2278      * Checks that our immutable capabilities are the same as those of the given
2279      * {@code NetworkCapabilities} and return a String describing any difference.
2280      * The returned String is empty if there is no difference.
2281      *
2282      * @hide
2283      */
describeImmutableDifferences(@ullable NetworkCapabilities that)2284     public String describeImmutableDifferences(@Nullable NetworkCapabilities that) {
2285         if (that == null) {
2286             return "other NetworkCapabilities was null";
2287         }
2288 
2289         StringJoiner joiner = new StringJoiner(", ");
2290 
2291         // Ignore NOT_METERED being added or removed as it is effectively dynamic. http://b/63326103
2292         // TODO: properly support NOT_METERED as a mutable and requestable capability.
2293         final long mask = ~MUTABLE_CAPABILITIES & ~(1 << NET_CAPABILITY_NOT_METERED);
2294         long oldImmutableCapabilities = this.mNetworkCapabilities & mask;
2295         long newImmutableCapabilities = that.mNetworkCapabilities & mask;
2296         if (oldImmutableCapabilities != newImmutableCapabilities) {
2297             String before = capabilityNamesOf(BitUtils.unpackBits(
2298                     oldImmutableCapabilities));
2299             String after = capabilityNamesOf(BitUtils.unpackBits(
2300                     newImmutableCapabilities));
2301             joiner.add(String.format("immutable capabilities changed: %s -> %s", before, after));
2302         }
2303 
2304         if (!equalsSpecifier(that)) {
2305             NetworkSpecifier before = this.getNetworkSpecifier();
2306             NetworkSpecifier after = that.getNetworkSpecifier();
2307             joiner.add(String.format("specifier changed: %s -> %s", before, after));
2308         }
2309 
2310         if (!equalsTransportTypes(that)) {
2311             String before = transportNamesOf(this.getTransportTypes());
2312             String after = transportNamesOf(that.getTransportTypes());
2313             joiner.add(String.format("transports changed: %s -> %s", before, after));
2314         }
2315 
2316         return joiner.toString();
2317     }
2318 
2319     /**
2320      * Returns a short but human-readable string of updates from an older set of capabilities.
2321      * @param old the old capabilities to diff from
2322      * @return a string fit for logging differences, or null if no differences.
2323      *         this never returns the empty string. See BitUtils#describeDifferences.
2324      * @hide
2325      */
2326     @Nullable
describeCapsDifferencesFrom(@ullable final NetworkCapabilities old)2327     public String describeCapsDifferencesFrom(@Nullable final NetworkCapabilities old) {
2328         final long oldCaps = null == old ? 0 : old.mNetworkCapabilities;
2329         return describeDifferences(oldCaps, mNetworkCapabilities,
2330                 NetworkCapabilities::capabilityNameOf);
2331     }
2332 
2333     /**
2334      * Checks that our requestable capabilities are the same as those of the given
2335      * {@code NetworkCapabilities}.
2336      *
2337      * @hide
2338      */
equalRequestableCapabilities(@ullable NetworkCapabilities nc)2339     public boolean equalRequestableCapabilities(@Nullable NetworkCapabilities nc) {
2340         if (nc == null) return false;
2341         return (equalsNetCapabilitiesRequestable(nc)
2342                 && equalsTransportTypes(nc)
2343                 && equalsSpecifier(nc));
2344     }
2345 
2346     @Override
equals(@ullable Object obj)2347     public boolean equals(@Nullable Object obj) {
2348         if (obj == null || (obj instanceof NetworkCapabilities == false)) return false;
2349         NetworkCapabilities that = (NetworkCapabilities) obj;
2350         return equalsNetCapabilities(that)
2351                 && equalsTransportTypes(that)
2352                 && equalsLinkBandwidths(that)
2353                 && equalsSignalStrength(that)
2354                 && equalsSpecifier(that)
2355                 && equalsTransportInfo(that)
2356                 && equalsUids(that)
2357                 && equalsAllowedUids(that)
2358                 && equalsSSID(that)
2359                 && equalsOwnerUid(that)
2360                 && equalsPrivateDnsBroken(that)
2361                 && equalsRequestor(that)
2362                 && equalsAdministratorUids(that)
2363                 && equalsSubscriptionIds(that)
2364                 && equalsUnderlyingNetworks(that)
2365                 && equalsEnterpriseCapabilitiesId(that);
2366     }
2367 
2368     @Override
hashCode()2369     public int hashCode() {
2370         return (int) (mNetworkCapabilities & 0xFFFFFFFF)
2371                 + ((int) (mNetworkCapabilities >> 32) * 3)
2372                 + ((int) (mForbiddenNetworkCapabilities & 0xFFFFFFFF) * 5)
2373                 + ((int) (mForbiddenNetworkCapabilities >> 32) * 7)
2374                 + ((int) (mTransportTypes & 0xFFFFFFFF) * 11)
2375                 + ((int) (mTransportTypes >> 32) * 13)
2376                 + mLinkUpBandwidthKbps * 17
2377                 + mLinkDownBandwidthKbps * 19
2378                 + Objects.hashCode(mNetworkSpecifier) * 23
2379                 + mSignalStrength * 29
2380                 + mOwnerUid * 31
2381                 + Objects.hashCode(mUids) * 37
2382                 + Objects.hashCode(mAllowedUids) * 41
2383                 + Objects.hashCode(mSSID) * 43
2384                 + Objects.hashCode(mTransportInfo) * 47
2385                 + Objects.hashCode(mPrivateDnsBroken) * 53
2386                 + Objects.hashCode(mRequestorUid) * 59
2387                 + Objects.hashCode(mRequestorPackageName) * 61
2388                 + Arrays.hashCode(mAdministratorUids) * 67
2389                 + Objects.hashCode(mSubIds) * 71
2390                 + Objects.hashCode(mUnderlyingNetworks) * 73
2391                 + mEnterpriseId * 79;
2392     }
2393 
2394     @Override
describeContents()2395     public int describeContents() {
2396         return 0;
2397     }
2398 
writeParcelableArraySet(Parcel in, @Nullable ArraySet<T> val, int flags)2399     private <T extends Parcelable> void writeParcelableArraySet(Parcel in,
2400             @Nullable ArraySet<T> val, int flags) {
2401         final int size = (val != null) ? val.size() : -1;
2402         in.writeInt(size);
2403         for (int i = 0; i < size; i++) {
2404             in.writeParcelable(val.valueAt(i), flags);
2405         }
2406     }
2407 
2408     @Override
writeToParcel(Parcel dest, int flags)2409     public void writeToParcel(Parcel dest, int flags) {
2410         dest.writeLong(mNetworkCapabilities & ALL_VALID_CAPABILITIES);
2411         dest.writeLong(mForbiddenNetworkCapabilities & ALL_VALID_CAPABILITIES);
2412         dest.writeLong(mTransportTypes & ALL_VALID_TRANSPORTS);
2413         dest.writeInt(mLinkUpBandwidthKbps);
2414         dest.writeInt(mLinkDownBandwidthKbps);
2415         dest.writeParcelable((Parcelable) mNetworkSpecifier, flags);
2416         dest.writeParcelable((Parcelable) mTransportInfo, flags);
2417         dest.writeInt(mSignalStrength);
2418         writeParcelableArraySet(dest, mUids, flags);
2419         dest.writeIntArray(CollectionUtils.toIntArray(mAllowedUids));
2420         dest.writeString(mSSID);
2421         dest.writeBoolean(mPrivateDnsBroken);
2422         dest.writeIntArray(getAdministratorUids());
2423         dest.writeInt(mOwnerUid);
2424         dest.writeInt(mRequestorUid);
2425         dest.writeString(mRequestorPackageName);
2426         dest.writeIntArray(CollectionUtils.toIntArray(mSubIds));
2427         dest.writeTypedList(mUnderlyingNetworks);
2428         dest.writeInt(mEnterpriseId & ALL_VALID_ENTERPRISE_IDS);
2429     }
2430 
2431     public static final @android.annotation.NonNull Creator<NetworkCapabilities> CREATOR =
2432             new Creator<>() {
2433             @Override
2434             public NetworkCapabilities createFromParcel(Parcel in) {
2435                 NetworkCapabilities netCap = new NetworkCapabilities();
2436                 // Validate the unparceled data, in case the parceling party was malicious.
2437                 netCap.mNetworkCapabilities = in.readLong() & ALL_VALID_CAPABILITIES;
2438                 netCap.mForbiddenNetworkCapabilities = in.readLong() & ALL_VALID_CAPABILITIES;
2439                 netCap.mTransportTypes = in.readLong() & ALL_VALID_TRANSPORTS;
2440                 netCap.mLinkUpBandwidthKbps = in.readInt();
2441                 netCap.mLinkDownBandwidthKbps = in.readInt();
2442                 netCap.mNetworkSpecifier = in.readParcelable(null);
2443                 netCap.mTransportInfo = in.readParcelable(null);
2444                 netCap.mSignalStrength = in.readInt();
2445                 netCap.mUids = readParcelableArraySet(in, null /* ClassLoader, null for default */);
2446                 final int[] allowedUids = in.createIntArray();
2447                 netCap.mAllowedUids.ensureCapacity(allowedUids.length);
2448                 for (int uid : allowedUids) {
2449                     netCap.mAllowedUids.add(uid);
2450                 }
2451                 netCap.mSSID = in.readString();
2452                 netCap.mPrivateDnsBroken = in.readBoolean();
2453                 netCap.setAdministratorUids(in.createIntArray());
2454                 netCap.mOwnerUid = in.readInt();
2455                 netCap.mRequestorUid = in.readInt();
2456                 netCap.mRequestorPackageName = in.readString();
2457                 netCap.mSubIds = new ArraySet<>();
2458                 final int[] subIdInts = Objects.requireNonNull(in.createIntArray());
2459                 for (int i = 0; i < subIdInts.length; i++) {
2460                     netCap.mSubIds.add(subIdInts[i]);
2461                 }
2462                 netCap.setUnderlyingNetworks(in.createTypedArrayList(Network.CREATOR));
2463                 netCap.mEnterpriseId = in.readInt() & ALL_VALID_ENTERPRISE_IDS;
2464                 return netCap;
2465             }
2466             @Override
2467             public NetworkCapabilities[] newArray(int size) {
2468                 return new NetworkCapabilities[size];
2469             }
2470 
2471             private @Nullable <T extends Parcelable> ArraySet<T> readParcelableArraySet(Parcel in,
2472                     @Nullable ClassLoader loader) {
2473                 final int size = in.readInt();
2474                 if (size < 0) {
2475                     return null;
2476                 }
2477                 final ArraySet<T> result = new ArraySet<>(size);
2478                 for (int i = 0; i < size; i++) {
2479                     final T value = in.readParcelable(loader);
2480                     result.add(value);
2481                 }
2482                 return result;
2483             }
2484         };
2485 
2486     @Override
toString()2487     public @NonNull String toString() {
2488         final StringBuilder sb = new StringBuilder("[");
2489         if (0 != mTransportTypes) {
2490             sb.append(" Transports: ");
2491             appendStringRepresentationOfBitMaskToStringBuilder(sb, mTransportTypes,
2492                     NetworkCapabilities::transportNameOf, "|");
2493         }
2494         if (0 != mNetworkCapabilities) {
2495             sb.append(" Capabilities: ");
2496             appendStringRepresentationOfBitMaskToStringBuilder(sb, mNetworkCapabilities,
2497                     NetworkCapabilities::capabilityNameOf, "&");
2498         }
2499         if (0 != mForbiddenNetworkCapabilities) {
2500             sb.append(" Forbidden: ");
2501             appendStringRepresentationOfBitMaskToStringBuilder(sb, mForbiddenNetworkCapabilities,
2502                     NetworkCapabilities::capabilityNameOf, "&");
2503         }
2504         if (mLinkUpBandwidthKbps > 0) {
2505             sb.append(" LinkUpBandwidth>=").append(mLinkUpBandwidthKbps).append("Kbps");
2506         }
2507         if (mLinkDownBandwidthKbps > 0) {
2508             sb.append(" LinkDnBandwidth>=").append(mLinkDownBandwidthKbps).append("Kbps");
2509         }
2510         if (mNetworkSpecifier != null) {
2511             sb.append(" Specifier: <").append(mNetworkSpecifier).append(">");
2512         }
2513         if (mTransportInfo != null) {
2514             sb.append(" TransportInfo: <").append(mTransportInfo).append(">");
2515         }
2516         if (hasSignalStrength()) {
2517             sb.append(" SignalStrength: ").append(mSignalStrength);
2518         }
2519 
2520         if (null != mUids) {
2521             if ((1 == mUids.size()) && (mUids.valueAt(0).count() == 1)) {
2522                 sb.append(" Uid: ").append(mUids.valueAt(0).start);
2523             } else {
2524                 sb.append(" Uids: <").append(mUids).append(">");
2525             }
2526         }
2527 
2528         if (hasAllowedUids()) {
2529             sb.append(" AllowedUids: <").append(mAllowedUids).append(">");
2530         }
2531 
2532         if (mOwnerUid != Process.INVALID_UID) {
2533             sb.append(" OwnerUid: ").append(mOwnerUid);
2534         }
2535 
2536         if (mAdministratorUids != null && mAdministratorUids.length != 0) {
2537             sb.append(" AdminUids: ").append(Arrays.toString(mAdministratorUids));
2538         }
2539 
2540         if (mRequestorUid != Process.INVALID_UID) {
2541             sb.append(" RequestorUid: ").append(mRequestorUid);
2542         }
2543 
2544         if (mRequestorPackageName != null) {
2545             sb.append(" RequestorPkg: ").append(mRequestorPackageName);
2546         }
2547 
2548         if (null != mSSID) {
2549             sb.append(" SSID: ").append(mSSID);
2550         }
2551 
2552         if (mPrivateDnsBroken) {
2553             sb.append(" PrivateDnsBroken");
2554         }
2555 
2556         if (!mSubIds.isEmpty()) {
2557             sb.append(" SubscriptionIds: ").append(mSubIds);
2558         }
2559 
2560         if (0 != mEnterpriseId) {
2561             sb.append(" EnterpriseId: ");
2562             appendStringRepresentationOfBitMaskToStringBuilder(sb, mEnterpriseId,
2563                     NetworkCapabilities::enterpriseIdNameOf, "&");
2564         }
2565 
2566         sb.append(" UnderlyingNetworks: ");
2567         if (mUnderlyingNetworks != null) {
2568             sb.append("[");
2569             final StringJoiner joiner = new StringJoiner(",");
2570             for (int i = 0; i < mUnderlyingNetworks.size(); i++) {
2571                 joiner.add(mUnderlyingNetworks.get(i).toString());
2572             }
2573             sb.append(joiner.toString());
2574             sb.append("]");
2575         } else {
2576             sb.append("Null");
2577         }
2578 
2579         sb.append("]");
2580         return sb.toString();
2581     }
2582 
2583     /**
2584      * @hide
2585      */
capabilityNamesOf(@ullable @etCapability int[] capabilities)2586     public static @NonNull String capabilityNamesOf(@Nullable @NetCapability int[] capabilities) {
2587         StringJoiner joiner = new StringJoiner("|");
2588         if (capabilities != null) {
2589             for (int c : capabilities) {
2590                 joiner.add(capabilityNameOf(c));
2591             }
2592         }
2593         return joiner.toString();
2594     }
2595 
2596     /**
2597      * @hide
2598      */
capabilityNameOf(@etCapability int capability)2599     public static @NonNull String capabilityNameOf(@NetCapability int capability) {
2600         switch (capability) {
2601             case NET_CAPABILITY_MMS:                  return "MMS";
2602             case NET_CAPABILITY_SUPL:                 return "SUPL";
2603             case NET_CAPABILITY_DUN:                  return "DUN";
2604             case NET_CAPABILITY_FOTA:                 return "FOTA";
2605             case NET_CAPABILITY_IMS:                  return "IMS";
2606             case NET_CAPABILITY_CBS:                  return "CBS";
2607             case NET_CAPABILITY_WIFI_P2P:             return "WIFI_P2P";
2608             case NET_CAPABILITY_IA:                   return "IA";
2609             case NET_CAPABILITY_RCS:                  return "RCS";
2610             case NET_CAPABILITY_XCAP:                 return "XCAP";
2611             case NET_CAPABILITY_EIMS:                 return "EIMS";
2612             case NET_CAPABILITY_NOT_METERED:          return "NOT_METERED";
2613             case NET_CAPABILITY_INTERNET:             return "INTERNET";
2614             case NET_CAPABILITY_NOT_RESTRICTED:       return "NOT_RESTRICTED";
2615             case NET_CAPABILITY_TRUSTED:              return "TRUSTED";
2616             case NET_CAPABILITY_NOT_VPN:              return "NOT_VPN";
2617             case NET_CAPABILITY_VALIDATED:            return "VALIDATED";
2618             case NET_CAPABILITY_CAPTIVE_PORTAL:       return "CAPTIVE_PORTAL";
2619             case NET_CAPABILITY_NOT_ROAMING:          return "NOT_ROAMING";
2620             case NET_CAPABILITY_FOREGROUND:           return "FOREGROUND";
2621             case NET_CAPABILITY_NOT_CONGESTED:        return "NOT_CONGESTED";
2622             case NET_CAPABILITY_NOT_SUSPENDED:        return "NOT_SUSPENDED";
2623             case NET_CAPABILITY_OEM_PAID:             return "OEM_PAID";
2624             case NET_CAPABILITY_MCX:                  return "MCX";
2625             case NET_CAPABILITY_PARTIAL_CONNECTIVITY: return "PARTIAL_CONNECTIVITY";
2626             case NET_CAPABILITY_TEMPORARILY_NOT_METERED:    return "TEMPORARILY_NOT_METERED";
2627             case NET_CAPABILITY_OEM_PRIVATE:          return "OEM_PRIVATE";
2628             case NET_CAPABILITY_VEHICLE_INTERNAL:     return "VEHICLE_INTERNAL";
2629             case NET_CAPABILITY_NOT_VCN_MANAGED:      return "NOT_VCN_MANAGED";
2630             case NET_CAPABILITY_ENTERPRISE:           return "ENTERPRISE";
2631             case NET_CAPABILITY_VSIM:                 return "VSIM";
2632             case NET_CAPABILITY_BIP:                  return "BIP";
2633             case NET_CAPABILITY_HEAD_UNIT:            return "HEAD_UNIT";
2634             case NET_CAPABILITY_MMTEL:                return "MMTEL";
2635             case NET_CAPABILITY_PRIORITIZE_LATENCY:          return "PRIORITIZE_LATENCY";
2636             case NET_CAPABILITY_PRIORITIZE_BANDWIDTH:        return "PRIORITIZE_BANDWIDTH";
2637             case NET_CAPABILITY_LOCAL_NETWORK:        return "LOCAL_NETWORK";
2638             case NET_CAPABILITY_NOT_BANDWIDTH_CONSTRAINED:    return "NOT_BANDWIDTH_CONSTRAINED";
2639             default:                                  return Integer.toString(capability);
2640         }
2641     }
2642 
enterpriseIdNameOf( @etCapability int capability)2643     private static @NonNull String enterpriseIdNameOf(
2644             @NetCapability int capability) {
2645         return Integer.toString(capability);
2646     }
2647 
2648     /**
2649      * @hide
2650      */
2651     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
transportNamesOf(@ullable @ransport int[] types)2652     public static @NonNull String transportNamesOf(@Nullable @Transport int[] types) {
2653         StringJoiner joiner = new StringJoiner("|");
2654         if (types != null) {
2655             for (int t : types) {
2656                 joiner.add(transportNameOf(t));
2657             }
2658         }
2659         return joiner.toString();
2660     }
2661 
2662     /**
2663      * @hide
2664      */
transportNameOf(@ransport int transport)2665     public static @NonNull String transportNameOf(@Transport int transport) {
2666         if (!isValidTransport(transport)) {
2667             return "UNKNOWN";
2668         }
2669         return TRANSPORT_NAMES[transport];
2670     }
2671 
checkValidTransportType(@ransport int transport)2672     private static void checkValidTransportType(@Transport int transport) {
2673         if (!isValidTransport(transport)) {
2674             throw new IllegalArgumentException("Invalid TransportType " + transport);
2675         }
2676     }
2677 
isValidCapability(@etworkCapabilities.NetCapability int capability)2678     private static boolean isValidCapability(@NetworkCapabilities.NetCapability int capability) {
2679         return capability >= 0 && capability <= MAX_NET_CAPABILITY;
2680     }
2681 
isValidEnterpriseId( @etworkCapabilities.EnterpriseId int enterpriseId)2682     private static boolean isValidEnterpriseId(
2683             @NetworkCapabilities.EnterpriseId int enterpriseId) {
2684         return enterpriseId >= NET_ENTERPRISE_ID_1
2685                 && enterpriseId <= NET_ENTERPRISE_ID_5;
2686     }
2687 
checkValidEnterpriseId( @etworkCapabilities.EnterpriseId int enterpriseId)2688     private static void checkValidEnterpriseId(
2689             @NetworkCapabilities.EnterpriseId int enterpriseId) {
2690         if (!isValidEnterpriseId(enterpriseId)) {
2691             throw new IllegalArgumentException("enterprise capability identifier "
2692                     + enterpriseId + " is out of range");
2693         }
2694     }
2695 
2696     /**
2697      * Check if this {@code NetworkCapability} instance is metered.
2698      *
2699      * @return {@code true} if {@code NET_CAPABILITY_NOT_METERED} is not set on this instance.
2700      * @hide
2701      */
isMetered()2702     public boolean isMetered() {
2703         return !hasCapability(NET_CAPABILITY_NOT_METERED);
2704     }
2705 
2706     /**
2707      * Check if private dns is broken.
2708      *
2709      * @return {@code true} if private DNS is broken on this network.
2710      * @hide
2711      */
2712     @SystemApi
isPrivateDnsBroken()2713     public boolean isPrivateDnsBroken() {
2714         return mPrivateDnsBroken;
2715     }
2716 
2717     /**
2718      * Set mPrivateDnsBroken to true when private dns is broken.
2719      *
2720      * @param broken the status of private DNS to be set.
2721      * @hide
2722      */
setPrivateDnsBroken(boolean broken)2723     public void setPrivateDnsBroken(boolean broken) {
2724         mPrivateDnsBroken = broken;
2725     }
2726 
equalsPrivateDnsBroken(NetworkCapabilities nc)2727     private boolean equalsPrivateDnsBroken(NetworkCapabilities nc) {
2728         return mPrivateDnsBroken == nc.mPrivateDnsBroken;
2729     }
2730 
2731     /**
2732      * Set the UID of the app making the request.
2733      *
2734      * For instances of NetworkCapabilities representing a request, sets the
2735      * UID of the app making the request. For a network created by the system,
2736      * sets the UID of the only app whose requests can match this network.
2737      * This can be set to {@link Process#INVALID_UID} if there is no such app,
2738      * or if this instance of NetworkCapabilities is about to be sent to a
2739      * party that should not learn about this.
2740      *
2741      * @param uid UID of the app.
2742      * @hide
2743      */
setRequestorUid(int uid)2744     public @NonNull NetworkCapabilities setRequestorUid(int uid) {
2745         mRequestorUid = uid;
2746         return this;
2747     }
2748 
2749     /**
2750      * Returns the UID of the app making the request.
2751      *
2752      * For a NetworkRequest being made by an app, contains the app's UID. For a network
2753      * created by the system, contains the UID of the only app whose requests can match
2754      * this network, or {@link Process#INVALID_UID} if none or if the
2755      * caller does not have permission to learn about this.
2756      *
2757      * @return the uid of the app making the request.
2758      * @hide
2759      */
getRequestorUid()2760     public int getRequestorUid() {
2761         return mRequestorUid;
2762     }
2763 
2764     /**
2765      * Set the package name of the app making the request.
2766      *
2767      * For instances of NetworkCapabilities representing a request, sets the
2768      * package name of the app making the request. For a network created by the system,
2769      * sets the package name of the only app whose requests can match this network.
2770      * This can be set to null if there is no such app, or if this instance of
2771      * NetworkCapabilities is about to be sent to a party that should not learn about this.
2772      *
2773      * @param packageName package name of the app.
2774      * @hide
2775      */
setRequestorPackageName(@onNull String packageName)2776     public @NonNull NetworkCapabilities setRequestorPackageName(@NonNull String packageName) {
2777         mRequestorPackageName = packageName;
2778         return this;
2779     }
2780 
2781     /**
2782      * Returns the package name of the app making the request.
2783      *
2784      * For a NetworkRequest being made by an app, contains the app's package name. For a
2785      * network created by the system, contains the package name of the only app whose
2786      * requests can match this network, or null if none or if the caller does not have
2787      * permission to learn about this.
2788      *
2789      * @return the package name of the app making the request.
2790      * @hide
2791      */
2792     @Nullable
getRequestorPackageName()2793     public String getRequestorPackageName() {
2794         return mRequestorPackageName;
2795     }
2796 
2797     /**
2798      * Set the uid and package name of the app causing this network to exist.
2799      *
2800      * See {@link #setRequestorUid} and {@link #setRequestorPackageName}
2801      *
2802      * @param uid UID of the app.
2803      * @param packageName package name of the app.
2804      * @hide
2805      */
setRequestorUidAndPackageName( int uid, @NonNull String packageName)2806     public @NonNull NetworkCapabilities setRequestorUidAndPackageName(
2807             int uid, @NonNull String packageName) {
2808         return setRequestorUid(uid).setRequestorPackageName(packageName);
2809     }
2810 
2811     /**
2812      * Test whether the passed NetworkCapabilities satisfies the requestor restrictions of this
2813      * capabilities.
2814      *
2815      * This method is called on the NetworkCapabilities embedded in a request with the
2816      * capabilities of an available network. If the available network, sets a specific
2817      * requestor (by uid and optionally package name), then this will only match a request from the
2818      * same app. If either of the capabilities have an unset uid or package name, then it matches
2819      * everything.
2820      * <p>
2821      * nc is assumed nonnull. Else, NPE.
2822      */
satisfiedByRequestor(NetworkCapabilities nc)2823     private boolean satisfiedByRequestor(NetworkCapabilities nc) {
2824         // No uid set, matches everything.
2825         if (mRequestorUid == Process.INVALID_UID || nc.mRequestorUid == Process.INVALID_UID) {
2826             return true;
2827         }
2828         // uids don't match.
2829         if (mRequestorUid != nc.mRequestorUid) return false;
2830         // No package names set, matches everything
2831         if (null == nc.mRequestorPackageName || null == mRequestorPackageName) return true;
2832         // check for package name match.
2833         return TextUtils.equals(mRequestorPackageName, nc.mRequestorPackageName);
2834     }
2835 
equalsRequestor(NetworkCapabilities nc)2836     private boolean equalsRequestor(NetworkCapabilities nc) {
2837         return mRequestorUid == nc.mRequestorUid
2838                 && TextUtils.equals(mRequestorPackageName, nc.mRequestorPackageName);
2839     }
2840 
2841     /**
2842      * Set of the subscription IDs that identifies the network or request, empty if none.
2843      */
2844     @NonNull
2845     private ArraySet<Integer> mSubIds = new ArraySet<>();
2846 
2847     /**
2848      * Sets the subscription ID set that associated to this network or request.
2849      *
2850      * @hide
2851      */
2852     @NonNull
setSubscriptionIds(@onNull Set<Integer> subIds)2853     public NetworkCapabilities setSubscriptionIds(@NonNull Set<Integer> subIds) {
2854         mSubIds = new ArraySet(Objects.requireNonNull(subIds));
2855         return this;
2856     }
2857 
2858     /**
2859      * Gets the subscription ID set that associated to this network or request.
2860      *
2861      * <p>Instances of NetworkCapabilities will only have this field populated by the system if the
2862      * receiver holds the NETWORK_FACTORY permission. In all other cases, it will be the empty set.
2863      *
2864      * @return
2865      */
2866     @NonNull
2867     @FlaggedApi(Flags.REQUEST_RESTRICTED_WIFI)
getSubscriptionIds()2868     public Set<Integer> getSubscriptionIds() {
2869         return new ArraySet<>(mSubIds);
2870     }
2871 
2872     /**
2873      * Tests if the subscription ID set of this network is the same as that of the passed one.
2874      */
equalsSubscriptionIds(@onNull NetworkCapabilities nc)2875     private boolean equalsSubscriptionIds(@NonNull NetworkCapabilities nc) {
2876         return Objects.equals(mSubIds, nc.mSubIds);
2877     }
2878 
2879     /**
2880      * Check if the subscription ID set requirements of this object are matched by the passed one.
2881      * If specified in the request, the passed one need to have at least one subId and at least
2882      * one of them needs to be in the request set.
2883      */
satisfiedBySubscriptionIds(@onNull NetworkCapabilities nc)2884     private boolean satisfiedBySubscriptionIds(@NonNull NetworkCapabilities nc) {
2885         if (mSubIds.isEmpty()) return true;
2886         if (nc.mSubIds.isEmpty()) return false;
2887         for (final Integer subId : nc.mSubIds) {
2888             if (mSubIds.contains(subId)) return true;
2889         }
2890         return false;
2891     }
2892 
2893     /**
2894      * Returns a bitmask of all the applicable redactions (based on the permissions held by the
2895      * receiving app) to be performed on this object.
2896      *
2897      * @return bitmask of redactions applicable on this instance.
2898      * @hide
2899      */
getApplicableRedactions()2900     public @RedactionType long getApplicableRedactions() {
2901         // Currently, there are no fields redacted in NetworkCapabilities itself, so we just
2902         // passthrough the redactions required by the embedded TransportInfo. If this changes
2903         // in the future, modify this method.
2904         if (mTransportInfo == null) {
2905             return NetworkCapabilities.REDACT_NONE;
2906         }
2907         return mTransportInfo.getApplicableRedactions();
2908     }
2909 
removeDefaultCapabilites()2910     private NetworkCapabilities removeDefaultCapabilites() {
2911         mNetworkCapabilities &= ~DEFAULT_CAPABILITIES;
2912         return this;
2913     }
2914 
2915     /**
2916      * Builder class for NetworkCapabilities.
2917      *
2918      * This class is mainly for {@link NetworkAgent} instances to use. Many fields in
2919      * the built class require holding a signature permission to use - mostly
2920      * {@link android.Manifest.permission.NETWORK_FACTORY}, but refer to the specific
2921      * description of each setter. As this class lives entirely in app space it does not
2922      * enforce these restrictions itself but the system server clears out the relevant
2923      * fields when receiving a NetworkCapabilities object from a caller without the
2924      * appropriate permission.
2925      *
2926      * Apps don't use this builder directly. Instead, they use {@link NetworkRequest} via
2927      * its builder object.
2928      *
2929      * @hide
2930      */
2931     @SystemApi
2932     public static final class Builder {
2933         private final NetworkCapabilities mCaps;
2934 
2935         /**
2936          * Creates a new Builder to construct NetworkCapabilities objects.
2937          */
Builder()2938         public Builder() {
2939             mCaps = new NetworkCapabilities();
2940         }
2941 
2942         /**
2943          * Creates a new Builder of NetworkCapabilities from an existing instance.
2944          */
Builder(@onNull final NetworkCapabilities nc)2945         public Builder(@NonNull final NetworkCapabilities nc) {
2946             Objects.requireNonNull(nc);
2947             mCaps = new NetworkCapabilities(nc);
2948         }
2949 
2950         /**
2951          * Creates a new Builder without the default capabilities.
2952          */
2953         @NonNull
withoutDefaultCapabilities()2954         public static Builder withoutDefaultCapabilities() {
2955             final NetworkCapabilities nc = new NetworkCapabilities();
2956             nc.removeDefaultCapabilites();
2957             return new Builder(nc);
2958         }
2959 
2960         /**
2961          * Adds the given transport type.
2962          *
2963          * Multiple transports may be added. Note that when searching for a network to satisfy a
2964          * request, satisfying any of the transports listed in the request will satisfy the request.
2965          * For example {@code TRANSPORT_WIFI} and {@code TRANSPORT_ETHERNET} added to a
2966          * {@code NetworkCapabilities} would cause either a Wi-Fi network or an Ethernet network
2967          * to be selected. This is logically different than
2968          * {@code NetworkCapabilities.NET_CAPABILITY_*}. Also note that multiple networks with the
2969          * same transport type may be active concurrently.
2970          *
2971          * @param transportType the transport type to be added or removed.
2972          * @return this builder
2973          */
2974         @NonNull
addTransportType(@ransport int transportType)2975         public Builder addTransportType(@Transport int transportType) {
2976             checkValidTransportType(transportType);
2977             mCaps.addTransportType(transportType);
2978             return this;
2979         }
2980 
2981         /**
2982          * Removes the given transport type.
2983          *
2984          * @see #addTransportType
2985          *
2986          * @param transportType the transport type to be added or removed.
2987          * @return this builder
2988          */
2989         @NonNull
removeTransportType(@ransport int transportType)2990         public Builder removeTransportType(@Transport int transportType) {
2991             checkValidTransportType(transportType);
2992             mCaps.removeTransportType(transportType);
2993             return this;
2994         }
2995 
2996         /**
2997          * Adds the given capability.
2998          *
2999          * @param capability the capability
3000          * @return this builder
3001          */
3002         @NonNull
addCapability(@etCapability final int capability)3003         public Builder addCapability(@NetCapability final int capability) {
3004             mCaps.setCapability(capability, true);
3005             return this;
3006         }
3007 
3008         /**
3009          * Removes the given capability.
3010          *
3011          * @param capability the capability
3012          * @return this builder
3013          */
3014         @NonNull
removeCapability(@etCapability final int capability)3015         public Builder removeCapability(@NetCapability final int capability) {
3016             mCaps.setCapability(capability, false);
3017             return this;
3018         }
3019 
3020         /**
3021          * Adds the given capability to the list of forbidden capabilities.
3022          *
3023          * A network with a capability will not match a {@link NetworkCapabilities} or
3024          * {@link NetworkRequest} which has said capability set as forbidden. For example, if
3025          * a request has NET_CAPABILITY_INTERNET in the list of forbidden capabilities, networks
3026          * with NET_CAPABILITY_INTERNET will not match the request.
3027          *
3028          * If the capability was previously added to the list of required capabilities (for
3029          * example, it was there by default or added using {@link #addCapability(int)} method), then
3030          * it will be removed from the list of required capabilities as well.
3031          *
3032          * @param capability the capability
3033          * @return this builder
3034          * @hide
3035          */
3036         @NonNull
3037         // TODO : @FlaggedApi(Flags.FLAG_FORBIDDEN_CAPABILITY) and public
addForbiddenCapability(@etCapability final int capability)3038         public Builder addForbiddenCapability(@NetCapability final int capability) {
3039             mCaps.addForbiddenCapability(capability);
3040             return this;
3041         }
3042 
3043         /**
3044          * Removes the given capability from the list of forbidden capabilities.
3045          *
3046          * @see #addForbiddenCapability(int)
3047          * @param capability the capability
3048          * @return this builder
3049          * @hide
3050          */
3051         @NonNull
3052         // TODO : @FlaggedApi(Flags.FLAG_FORBIDDEN_CAPABILITY) and public
removeForbiddenCapability(@etCapability final int capability)3053         public Builder removeForbiddenCapability(@NetCapability final int capability) {
3054             mCaps.removeForbiddenCapability(capability);
3055             return this;
3056         }
3057 
3058         /**
3059          * Adds the given enterprise capability identifier.
3060          * Note that when searching for a network to satisfy a request, all capabilities identifier
3061          * requested must be satisfied. Enterprise capability identifier is applicable only
3062          * for NET_CAPABILITY_ENTERPRISE capability
3063          *
3064          * @param enterpriseId enterprise capability identifier.
3065          *
3066          * @return this builder
3067          */
3068         @NonNull
addEnterpriseId( @nterpriseId int enterpriseId)3069         public Builder addEnterpriseId(
3070                 @EnterpriseId  int enterpriseId) {
3071             mCaps.addEnterpriseId(enterpriseId);
3072             return this;
3073         }
3074 
3075         /**
3076          * Removes the given enterprise capability identifier. Enterprise capability identifier is
3077          * applicable only for NET_CAPABILITY_ENTERPRISE capability
3078          *
3079          * @param enterpriseId the enterprise capability identifier
3080          * @return this builder
3081          */
3082         @NonNull
removeEnterpriseId( @nterpriseId int enterpriseId)3083         public Builder removeEnterpriseId(
3084                 @EnterpriseId  int enterpriseId) {
3085             mCaps.removeEnterpriseId(enterpriseId);
3086             return this;
3087         }
3088 
3089         /**
3090          * Sets the owner UID.
3091          *
3092          * The default value is {@link Process#INVALID_UID}. Pass this value to reset.
3093          *
3094          * Note: for security the system will clear out this field when received from a
3095          * non-privileged source.
3096          *
3097          * @param ownerUid the owner UID
3098          * @return this builder
3099          */
3100         @NonNull
3101         @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
setOwnerUid(final int ownerUid)3102         public Builder setOwnerUid(final int ownerUid) {
3103             mCaps.setOwnerUid(ownerUid);
3104             return this;
3105         }
3106 
3107         /**
3108          * Sets the list of UIDs that are administrators of this network.
3109          *
3110          * <p>UIDs included in administratorUids gain administrator privileges over this
3111          * Network. Examples of UIDs that should be included in administratorUids are:
3112          * <ul>
3113          *     <li>Carrier apps with privileges for the relevant subscription
3114          *     <li>Active VPN apps
3115          *     <li>Other application groups with a particular Network-related role
3116          * </ul>
3117          *
3118          * <p>In general, user-supplied networks (such as WiFi networks) do not have
3119          * administrators.
3120          *
3121          * <p>An app is granted owner privileges over Networks that it supplies. The owner
3122          * UID MUST always be included in administratorUids.
3123          *
3124          * The default value is the empty array. Pass an empty array to reset.
3125          *
3126          * Note: for security the system will clear out this field when received from a
3127          * non-privileged source, such as an app using reflection to call this or
3128          * mutate the member in the built object.
3129          *
3130          * @param administratorUids the UIDs to be set as administrators of this Network.
3131          * @return this builder
3132          */
3133         @NonNull
3134         @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
setAdministratorUids(@onNull final int[] administratorUids)3135         public Builder setAdministratorUids(@NonNull final int[] administratorUids) {
3136             Objects.requireNonNull(administratorUids);
3137             mCaps.setAdministratorUids(administratorUids);
3138             return this;
3139         }
3140 
3141         /**
3142          * Sets the upstream bandwidth of the link.
3143          *
3144          * Sets the upstream bandwidth for this network in Kbps. This always only refers to
3145          * the estimated first hop transport bandwidth.
3146          * <p>
3147          * Note that when used to request a network, this specifies the minimum acceptable.
3148          * When received as the state of an existing network this specifies the typical
3149          * first hop bandwidth expected. This is never measured, but rather is inferred
3150          * from technology type and other link parameters. It could be used to differentiate
3151          * between very slow 1xRTT cellular links and other faster networks or even between
3152          * 802.11b vs 802.11AC wifi technologies. It should not be used to differentiate between
3153          * fast backhauls and slow backhauls.
3154          *
3155          * @param upKbps the estimated first hop upstream (device to network) bandwidth.
3156          * @return this builder
3157          */
3158         @NonNull
setLinkUpstreamBandwidthKbps(final int upKbps)3159         public Builder setLinkUpstreamBandwidthKbps(final int upKbps) {
3160             mCaps.setLinkUpstreamBandwidthKbps(upKbps);
3161             return this;
3162         }
3163 
3164         /**
3165          * Sets the downstream bandwidth for this network in Kbps. This always only refers to
3166          * the estimated first hop transport bandwidth.
3167          * <p>
3168          * Note that when used to request a network, this specifies the minimum acceptable.
3169          * When received as the state of an existing network this specifies the typical
3170          * first hop bandwidth expected. This is never measured, but rather is inferred
3171          * from technology type and other link parameters. It could be used to differentiate
3172          * between very slow 1xRTT cellular links and other faster networks or even between
3173          * 802.11b vs 802.11AC wifi technologies. It should not be used to differentiate between
3174          * fast backhauls and slow backhauls.
3175          *
3176          * @param downKbps the estimated first hop downstream (network to device) bandwidth.
3177          * @return this builder
3178          */
3179         @NonNull
setLinkDownstreamBandwidthKbps(final int downKbps)3180         public Builder setLinkDownstreamBandwidthKbps(final int downKbps) {
3181             mCaps.setLinkDownstreamBandwidthKbps(downKbps);
3182             return this;
3183         }
3184 
3185         /**
3186          * Sets the optional bearer specific network specifier.
3187          * This has no meaning if a single transport is also not specified, so calling
3188          * this without a single transport set will generate an exception, as will
3189          * subsequently adding or removing transports after this is set.
3190          * </p>
3191          *
3192          * @param specifier a concrete, parcelable framework class that extends NetworkSpecifier,
3193          *        or null to clear it.
3194          * @return this builder
3195          */
3196         @NonNull
setNetworkSpecifier(@ullable final NetworkSpecifier specifier)3197         public Builder setNetworkSpecifier(@Nullable final NetworkSpecifier specifier) {
3198             mCaps.setNetworkSpecifier(specifier);
3199             return this;
3200         }
3201 
3202         /**
3203          * Sets the optional transport specific information.
3204          *
3205          * @param info A concrete, parcelable framework class that extends {@link TransportInfo},
3206          *             or null to clear it.
3207          * @return this builder
3208          */
3209         @NonNull
setTransportInfo(@ullable final TransportInfo info)3210         public Builder setTransportInfo(@Nullable final TransportInfo info) {
3211             mCaps.setTransportInfo(info);
3212             return this;
3213         }
3214 
3215         /**
3216          * Sets the signal strength. This is a signed integer, with higher values indicating a
3217          * stronger signal. The exact units are bearer-dependent. For example, Wi-Fi uses the
3218          * same RSSI units reported by wifi code.
3219          * <p>
3220          * Note that when used to register a network callback, this specifies the minimum
3221          * acceptable signal strength. When received as the state of an existing network it
3222          * specifies the current value. A value of code SIGNAL_STRENGTH_UNSPECIFIED} means
3223          * no value when received and has no effect when requesting a callback.
3224          *
3225          * Note: for security the system will throw if it receives a NetworkRequest where
3226          * the underlying NetworkCapabilities has this member set from a source that does
3227          * not hold the {@link android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP}
3228          * permission. Apps with this permission can use this indirectly through
3229          * {@link android.net.NetworkRequest}.
3230          *
3231          * @param signalStrength the bearer-specific signal strength.
3232          * @return this builder
3233          */
3234         @NonNull
3235         @RequiresPermission(android.Manifest.permission.NETWORK_SIGNAL_STRENGTH_WAKEUP)
setSignalStrength(final int signalStrength)3236         public Builder setSignalStrength(final int signalStrength) {
3237             mCaps.setSignalStrength(signalStrength);
3238             return this;
3239         }
3240 
3241         /**
3242          * Sets the SSID of this network.
3243          *
3244          * Note: for security the system will clear out this field when received from a
3245          * non-privileged source, like an app using reflection to set this.
3246          *
3247          * @param ssid the SSID, or null to clear it.
3248          * @return this builder
3249          */
3250         @NonNull
3251         @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
setSsid(@ullable final String ssid)3252         public Builder setSsid(@Nullable final String ssid) {
3253             mCaps.setSSID(ssid);
3254             return this;
3255         }
3256 
3257         /**
3258          * Set the uid of the app causing this network to exist.
3259          *
3260          * Note: for security the system will clear out this field when received from a
3261          * non-privileged source.
3262          *
3263          * @param uid UID of the app.
3264          * @return this builder
3265          */
3266         @NonNull
3267         @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
setRequestorUid(final int uid)3268         public Builder setRequestorUid(final int uid) {
3269             mCaps.setRequestorUid(uid);
3270             return this;
3271         }
3272 
3273         /**
3274          * Set the package name of the app causing this network to exist.
3275          *
3276          * Note: for security the system will clear out this field when received from a
3277          * non-privileged source.
3278          *
3279          * @param packageName package name of the app, or null to clear it.
3280          * @return this builder
3281          */
3282         @NonNull
3283         @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
setRequestorPackageName(@ullable final String packageName)3284         public Builder setRequestorPackageName(@Nullable final String packageName) {
3285             mCaps.setRequestorPackageName(packageName);
3286             return this;
3287         }
3288 
3289         /**
3290          * Set the subscription ID set.
3291          *
3292          * <p>SubIds are populated in NetworkCapability instances from the system only for callers
3293          * that hold the NETWORK_FACTORY permission. Similarly, the system will reject any
3294          * NetworkRequests filed with a non-empty set of subIds unless the caller holds the
3295          * NETWORK_FACTORY permission.
3296          *
3297          * @param subIds a set that represent the subscription IDs. Empty if clean up.
3298          * @return this builder.
3299          * @hide
3300          */
3301         @NonNull
3302         @SystemApi
setSubscriptionIds(@onNull final Set<Integer> subIds)3303         public Builder setSubscriptionIds(@NonNull final Set<Integer> subIds) {
3304             mCaps.setSubscriptionIds(subIds);
3305             return this;
3306         }
3307 
3308         /**
3309          * Set the list of UIDs this network applies to.
3310          *
3311          * @param uids the list of UIDs this network applies to, or {@code null} if this network
3312          *             applies to all UIDs.
3313          * @return this builder
3314          * @hide
3315          */
3316         @NonNull
3317         @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
setUids(@ullable Set<Range<Integer>> uids)3318         public Builder setUids(@Nullable Set<Range<Integer>> uids) {
3319             mCaps.setUids(uids);
3320             return this;
3321         }
3322 
3323         /**
3324          * Set a list of UIDs that can always access this network
3325          * <p>
3326          * Provide a list of UIDs that can access this network even if the network doesn't have the
3327          * {@link #NET_CAPABILITY_NOT_RESTRICTED} capability and the UID does not hold the
3328          * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission.
3329          * <p>
3330          * This is disallowed in {@link NetworkRequest}, and can only be set by
3331          * {@link NetworkAgent}s, who hold the
3332          * {@link android.Manifest.permission.NETWORK_FACTORY} permission.
3333          * Network agents also have restrictions on how they can set these ; they can only back
3334          * a public Android API. As such, Ethernet agents can set this when backing the per-UID
3335          * access API, and Telephony can set exactly one UID which has to match the manager app for
3336          * the associated subscription. Failure to comply with these rules will see this member
3337          * cleared.
3338          * <p>
3339          * These UIDs are only visible to network factories and the system server, since the system
3340          * server makes sure to redact them before sending a {@link NetworkCapabilities} instance
3341          * to a process that doesn't hold the {@link android.Manifest.permission.NETWORK_FACTORY}
3342          * permission.
3343          * <p>
3344          * This list cannot be null, but it can be empty to mean that no UID without the
3345          * {@link android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS} permission
3346          * can access this network.
3347          *
3348          * @param uids the list of UIDs that can always access this network
3349          * @return this builder
3350          * @hide
3351          */
3352         @NonNull
3353         @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES)
3354         @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
setAllowedUids(@onNull Set<Integer> uids)3355         public Builder setAllowedUids(@NonNull Set<Integer> uids) {
3356             Objects.requireNonNull(uids);
3357             mCaps.setAllowedUids(uids);
3358             return this;
3359         }
3360 
3361         /**
3362          * Set the underlying networks of this network.
3363          *
3364          * <p>This API is mainly for {@link NetworkAgent}s who hold
3365          * {@link android.Manifest.permission.NETWORK_FACTORY} to set its underlying networks.
3366          *
3367          * <p>The underlying networks are only visible for the receiver who has one of
3368          * {@link android.Manifest.permission.NETWORK_FACTORY},
3369          * {@link android.Manifest.permission.NETWORK_SETTINGS} and
3370          * {@link NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}.
3371          * If the receiver doesn't have required permissions, the field will be cleared before
3372          * sending to the caller.</p>
3373          *
3374          * @param networks The underlying networks of this network.
3375          */
3376         @NonNull
3377         @RequiresPermission(android.Manifest.permission.NETWORK_FACTORY)
setUnderlyingNetworks(@ullable List<Network> networks)3378         public Builder setUnderlyingNetworks(@Nullable List<Network> networks) {
3379             mCaps.setUnderlyingNetworks(networks);
3380             return this;
3381         }
3382 
3383         /**
3384          * Builds the instance of the capabilities.
3385          *
3386          * @return the built instance of NetworkCapabilities.
3387          */
3388         @NonNull
build()3389         public NetworkCapabilities build() {
3390             if (mCaps.getOwnerUid() != Process.INVALID_UID) {
3391                 if (!CollectionUtils.contains(mCaps.getAdministratorUids(), mCaps.getOwnerUid())) {
3392                     throw new IllegalStateException("The owner UID must be included in "
3393                             + " administrator UIDs.");
3394                 }
3395             }
3396 
3397             if ((mCaps.getEnterpriseIds().length != 0)
3398                     && !mCaps.hasCapability(NET_CAPABILITY_ENTERPRISE)) {
3399                 throw new IllegalStateException("Enterprise capability identifier is applicable"
3400                         + " only with ENTERPRISE capability.");
3401             }
3402             return new NetworkCapabilities(mCaps);
3403         }
3404     }
3405 }
3406